diff --git a/.github/bump_version.sh b/.github/bump_version.sh index 24f712742..9333238a4 100644 --- a/.github/bump_version.sh +++ b/.github/bump_version.sh @@ -25,10 +25,19 @@ fi # Default bump type is patch BUMP_TYPE="patch" -# Define arrays for directories that trigger a major or minor bump +# Define arrays for directories that trigger a major or minor bump. +# Matched as path prefixes against `git diff --name-only`, so a directory entry +# covers everything beneath it and a file entry matches that file exactly. major_paths=( - "code/framework/src/networking/messages" + # Replaces the long-gone code/framework/src/networking/messages: replication + # is where the sync flow lives now. + "code/framework/src/networking/replication" "code/framework/src/networking/rpc" + # MafiaNet is fetched, not vendored, so its headers are not in this tree and a + # wire break cannot be detected by path. The pin is the proxy: message ids are + # positional, so moving MafiaNet can shift every id and break every peer built + # against the old header. + "cmake/MafiaNetPin.cmake" ) minor_paths=( "code/framework/src/scripting/builtins" @@ -38,7 +47,10 @@ minor_paths=( # Check for major bump directories for file in "${changed_files[@]}"; do for major in "${major_paths[@]}"; do - if [[ "$file" == "$major"* ]]; then + # Exact file match, or anything genuinely beneath a directory entry. A bare + # "$major"* prefix would also fire on a sibling that merely starts with the + # same characters -- cmake/MafiaNetPin.cmake.bak, or .../replication2/foo. + if [[ "$file" == "$major" || "$file" == "$major/"* ]]; then BUMP_TYPE="major" break 2 fi @@ -49,7 +61,7 @@ done if [[ "$BUMP_TYPE" != "major" ]]; then for file in "${changed_files[@]}"; do for minor in "${minor_paths[@]}"; do - if [[ "$file" == "$minor"* ]]; then + if [[ "$file" == "$minor" || "$file" == "$minor/"* ]]; then BUMP_TYPE="minor" break 2 fi diff --git a/CLAUDE.md b/CLAUDE.md index bb7eac72d..5d09c015c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -56,6 +56,7 @@ Or use Visual Studio 2022 with CMake tools installed and open the repository fol 4. **Scripting** (`scripting/`) - JavaScript/TypeScript scripting for game logic (Server: libnode, Client: V8) 5. **GUI Manager** (`gui/manager.h`) - UI using CEF and Dear ImGui 6. **Job System** (`jobs/job_system.h`) - Opt-in fiber-based task scheduling using FTL +7. **Voice** (`voice/`) - Proximity voice chat; the server relays opaque Opus frames (RakVoice) without decoding, routed by `VoiceRouter` ### Integration Layer diff --git a/cmake/MafiaNetPin.cmake b/cmake/MafiaNetPin.cmake new file mode 100644 index 000000000..fb2017c93 --- /dev/null +++ b/cmake/MafiaNetPin.cmake @@ -0,0 +1,27 @@ +# MafiaNet dependency pin. +# +# Deliberately its own file rather than a line inside vendors/CMakeLists.txt. +# MafiaNet's message-id enum is positional: inserting an id shifts every id after +# it and breaks every peer built against the old header. Framework's release +# tooling classifies a version bump by which paths a change touches +# (.github/bump_version.sh), so the pin needs a path of its own that means +# exactly one thing -- "the wire format may have moved" -- instead of being +# buried among unrelated vendor edits. +# +# Raising this pin across a MAJOR or MINOR MafiaNet version is a breaking change +# for the Framework too, and bump_version.sh treats a change to this file as a +# major bump on that basis. A PATCH-only bump is wire-compatible by MafiaNet's own +# versioning, but still lands here so the pin has a single home. +# +# Note it must NOT live under vendors/: .gitignore carries `vendors/**/*.cmake`, +# which would silently exclude it from the repository. + +# Pinned by commit, not by tag. A tag is a mutable ref -- repointing it would +# change what every future build fetches while this file still reads the same -- +# whereas a commit is what it is. Keep the human-readable release beside it. +# +# Plain set(), not a CACHE entry: a cached value survives in an existing build +# tree, so bumping the pin here and rebuilding incrementally would silently keep +# fetching the old revision. This file is the single source of truth, and there is +# no reason to let -D override the wire format of the protocol. +set(MAFIANET_PIN "a515c827e01868ecc6be26ee82e4da7a04955f77") # v0.13.0 diff --git a/code/framework/CMakeLists.txt b/code/framework/CMakeLists.txt index b7d261357..4664da791 100644 --- a/code/framework/CMakeLists.txt +++ b/code/framework/CMakeLists.txt @@ -66,6 +66,9 @@ set(FRAMEWORK_SERVER_SRC # JavaScript scripting (server module) src/integrations/server/scripting/module.cpp + + src/voice/server/voice_router.cpp + src/voice/server/voice_server.cpp ) set(FRAMEWORK_CLIENT_SRC @@ -93,6 +96,8 @@ set(FRAMEWORK_CLIENT_SRC src/integrations/client/scripting/builtins/keybinds.cpp src/integrations/client/scripting/builtins/chat.cpp src/integrations/client/scripting/builtins/discord.cpp + + src/voice/client/mixer.cpp ) # GUI (CEF-based) @@ -195,7 +200,6 @@ macro(link_shared_deps target_name) ${CMAKE_SOURCE_DIR}/vendors/spdlog/include ${CMAKE_SOURCE_DIR}/vendors/fmt/include ${CMAKE_SOURCE_DIR}/vendors/fu2 # function2 (used in network_peer.h) - ${CMAKE_SOURCE_DIR}/vendors/mafianet/Source/include # Networking / MafiaNet (used in connection.h) ${CMAKE_SOURCE_DIR}/vendors/cxxopts # Command-line parsing (used in integrations) ${CMAKE_SOURCE_DIR}/vendors # sentry, etc. ) @@ -221,7 +225,7 @@ macro(link_shared_deps target_name) endif() # Global libraries (v8/v8pp excluded - linked explicitly to scripting targets only) - target_link_libraries(${target_name} MafiaNet glm spdlog cppfs nlohmann_json Sentry httplib OpenSSL::SSL OpenSSL::Crypto Curl semver Hash ftl Tracy::TracyClient) + target_link_libraries(${target_name} MafiaNet::MafiaNetStatic glm spdlog cppfs nlohmann_json Sentry httplib OpenSSL::SSL OpenSSL::Crypto Curl semver Hash ftl Tracy::TracyClient) # Required libraries for windows if(WIN32) diff --git a/code/framework/src/core_modules.h b/code/framework/src/core_modules.h index 1090fc0ef..3bc7bf6d9 100644 --- a/code/framework/src/core_modules.h +++ b/code/framework/src/core_modules.h @@ -21,6 +21,10 @@ namespace Framework::Networking::Replication { } // namespace Framework::Networking::Replication +namespace Framework::Voice { + class VoiceServer; +} // namespace Framework::Voice + namespace Framework::GUI { class Manager; } // namespace Framework::GUI @@ -48,6 +52,7 @@ namespace Framework { static void Reset() noexcept { _networkPeer = nullptr; _replication = nullptr; + _voiceServer = nullptr; _scriptingModule = nullptr; _webManager = nullptr; _input = nullptr; @@ -66,6 +71,11 @@ namespace Framework { _replication = replication; } + static void SetVoiceServer(Voice::VoiceServer *voice) { + FW_ASSERT_MODULE_REGISTRATION(_voiceServer, voice, "VoiceServer"); + _voiceServer = voice; + } + static void SetScriptingModule(Scripting::ScriptingModule *module) { FW_ASSERT_MODULE_REGISTRATION(_scriptingModule, module, "ScriptingModule"); _scriptingModule = module; @@ -99,6 +109,10 @@ namespace Framework { return _replication; } + static Voice::VoiceServer *GetVoiceServer() noexcept { + return _voiceServer; + } + static Scripting::ScriptingModule *GetScriptingModule() noexcept { return _scriptingModule; } @@ -122,6 +136,7 @@ namespace Framework { private: static inline Networking::NetworkPeer *_networkPeer {}; static inline Networking::Replication::ReplicationManager *_replication {}; + static inline Voice::VoiceServer *_voiceServer {}; static inline Scripting::ScriptingModule *_scriptingModule {}; static inline GUI::Manager *_webManager {}; static inline Input::IInput *_input {}; diff --git a/code/framework/src/integrations/server/instance.cpp b/code/framework/src/integrations/server/instance.cpp index e73c4888f..26178f91a 100644 --- a/code/framework/src/integrations/server/instance.cpp +++ b/code/framework/src/integrations/server/instance.cpp @@ -176,6 +176,15 @@ namespace Framework::Integrations::Server { }); } + // Voice relay: attaches RakVoice to the live peer, so it must come up after the networking + // engine. Failure is not fatal — the server simply runs without voice. + if (_voiceServer.Init(_networkingEngine->GetNetworkServer())) { + CoreModules::SetVoiceServer(&_voiceServer); + } + else { + Logging::GetLogger(FRAMEWORK_INNER_SERVER)->warn("Voice relay unavailable; voice chat disabled"); + } + if (!_opts.bindPublicServer || !_masterlist->Init(_opts.services.masterlistUrl, _opts.bindSecretKey)) { Logging::GetLogger(FRAMEWORK_INNER_SERVER)->warn("Server will not be announced to masterlist"); } @@ -349,6 +358,9 @@ namespace Framework::Integrations::Server { Logging::GetLogger(FRAMEWORK_INNER_SERVER)->debug("Disconnecting peer {}, reason: {}", guid.g, static_cast(reason)); _armedSpawnBarrierGuids.erase(guid.g); _readyPlayerGuids.erase(guid.g); + // Drop voice state unconditionally: a peer that never reached the ready barrier can + // still have been registered in the router by a position push. + _voiceServer.OnPlayerDisconnect(guid.g); // Player notification and avatar teardown run in ReplicationManager::OnClosedConnection, // which RakNet fires before this packet is delivered; here we just finalise the connection. @@ -453,6 +465,20 @@ namespace Framework::Integrations::Server { OnClientEvent(sender->GetNetworkID(), name, payload.GetPayload()); }); + // Voice frames are not RPCs: RakVoice writes a raw message id, so they surface on the + // unknown-packet path (the relay host deliberately declines to consume them itself). + net->SetUnknownPacketHandler([this, net](MafiaNet::Packet *packet) { + // GetPacketDataOffset() is the offset the peer resolved for this very packet, so an + // ID_TIMESTAMP prefix is already skipped. + const int offset = net->GetPacketDataOffset(); + if (offset < 0 || static_cast(offset) >= packet->length) { + return; + } + if (packet->data[offset] == ID_RAKVOICE_RELAY_DATA) { + _voiceServer.OnVoiceFrame(packet); + } + }); + Logging::GetLogger(FRAMEWORK_INNER_SERVER)->debug("Networking messages registered"); } @@ -865,6 +891,9 @@ namespace Framework::Integrations::Server { _scriptingModule->PreShutdown(); } + // Detach from the peer before the networking engine tears it down. + _voiceServer.Shutdown(); + if (_networkingEngine) { _networkingEngine->Shutdown(); } @@ -891,6 +920,7 @@ namespace Framework::Integrations::Server { CoreModules::SetNetworkPeer(nullptr); CoreModules::SetReplication(nullptr); + CoreModules::SetVoiceServer(nullptr); CoreModules::SetScriptingModule(nullptr); CoreModules::Reset(); @@ -907,6 +937,21 @@ namespace Framework::Integrations::Server { _networkingEngine->Update(); } + // Refresh the voice router's world view from the replicated entities. Every entity + // carrying an owner GUID is a player-controlled one, which is exactly the set the + // proximity rule keys on; ForEachEntity avoids the per-entity dynamic_cast that + // ForEach would cost for no added selectivity. + if (auto *replication = _networkingEngine ? _networkingEngine->GetNetworkServer()->GetReplicationManager() : nullptr) { + FW_PROFILE_SCOPE_N("Server::VoicePositions"); + auto &router = _voiceServer.GetRouter(); + replication->ForEachEntity([&router](Framework::Networking::Replication::NetworkEntity *entity) { + if (entity->ownerGUID != MafiaNet::UNASSIGNED_PEER_GUID) { + router.SetPlayerPosition(static_cast(entity->ownerGUID), entity->position); + } + }); + _voiceServer.Update(); + } + if (_scriptingModule) { FW_PROFILE_SCOPE_N("Server::Scripting"); _scriptingModule->Update(); diff --git a/code/framework/src/integrations/server/instance.h b/code/framework/src/integrations/server/instance.h index 7633aea8e..07264d6de 100644 --- a/code/framework/src/integrations/server/instance.h +++ b/code/framework/src/integrations/server/instance.h @@ -17,6 +17,7 @@ #include "logging/logger.h" #include "networking/engine.h" #include "scripting/module.h" +#include "voice/server/voice_server.h" #include @@ -144,6 +145,9 @@ namespace Framework::Integrations::Server { std::unique_ptr _commandListener; std::unique_ptr _commandProcessor; std::unique_ptr _crashReporter; + // Proximity voice relay. Value member: it holds no resources until Init attaches it to + // the peer, so a mod that never enables voice pays nothing beyond the empty maps. + Voice::VoiceServer _voiceServer; std::unordered_set _armedSpawnBarrierGuids; std::unordered_set _readyPlayerGuids; diff --git a/code/framework/src/voice/client/mixer.cpp b/code/framework/src/voice/client/mixer.cpp new file mode 100644 index 000000000..38406ca6a --- /dev/null +++ b/code/framework/src/voice/client/mixer.cpp @@ -0,0 +1,76 @@ +/* + * MafiaHub OSS license + * Copyright (c) 2026, MafiaHub. All rights reserved. + * + * This file comes from MafiaHub, hosted at https://github.com/MafiaHub/Framework. + * See LICENSE file in the source repository for information regarding licensing. + */ + +#include "mixer.h" + +#include +#include + +namespace Framework::Voice { + namespace { + constexpr float kInt16Scale = 1.0f / 32768.0f; + + // Below this distance a speaker is at full volume; attenuation starts beyond it. + // Without it, a speaker standing on top of the listener produces a division blow-up + // and an unpleasant volume spike as they cross the origin. + constexpr float kMinDistance = 1.0f; + + // How far the pan is allowed to swing. A full hard pan sounds wrong on headphones + // for a speaker only slightly off-axis, so the effect is deliberately partial. + constexpr float kMaxPan = 0.6f; + } // namespace + + SpeakerGain ComputeGain(const ListenerTransform &listener, const glm::vec3 &speakerPos, float range) { + SpeakerGain gain; + + const glm::vec3 delta = speakerPos - listener.position; + const float distance = glm::length(delta); + + if (range <= 0.0f || distance > range) { + return gain; // silent + } + + // Inverse-distance rolloff, normalised so it reaches zero exactly at `range` rather + // than trailing off asymptotically and leaving a faint always-audible tail. + const float clamped = std::max(distance, kMinDistance); + const float rolloff = kMinDistance / clamped; + const float edgeFade = 1.0f - (distance / range); + const float attenuation = std::clamp(rolloff * edgeFade, 0.0f, 1.0f); + + // Pan on the listener's right axis. cross(up, forward) — not cross(forward, up), + // which yields the left axis in a right-handed system and inverts the whole pan. + // Degenerate transforms fall back to centred. + float pan = 0.0f; + if (distance > 0.0001f) { + const glm::vec3 right = glm::cross(listener.up, listener.forward); + const float rightLen = glm::length(right); + if (rightLen > 0.0001f) { + pan = glm::dot(delta / distance, right / rightLen) * kMaxPan; + } + } + + // Constant-power pan: gains follow a quarter-circle so total energy stays flat as a + // speaker sweeps across, instead of dipping in the middle as linear panning does. + // A centred speaker therefore sits at cos(45 degrees) = ~0.707 per ear, not 1.0 — + // that is the property that keeps perceived loudness constant, so it is not + // normalised away. + const float angle = (pan + 1.0f) * 0.25f * 3.14159265358979323846f; + + gain.left = std::clamp(attenuation * std::cos(angle), 0.0f, 1.0f); + gain.right = std::clamp(attenuation * std::sin(angle), 0.0f, 1.0f); + return gain; + } + + void MixFrameInto(float *stereoOut, const int16_t *monoIn, uint32_t samples, SpeakerGain gain) { + for (uint32_t i = 0; i < samples; i++) { + const float sample = static_cast(monoIn[i]) * kInt16Scale; + stereoOut[i * 2] += sample * gain.left; + stereoOut[i * 2 + 1] += sample * gain.right; + } + } +} // namespace Framework::Voice diff --git a/code/framework/src/voice/client/mixer.h b/code/framework/src/voice/client/mixer.h new file mode 100644 index 000000000..ff53a25ae --- /dev/null +++ b/code/framework/src/voice/client/mixer.h @@ -0,0 +1,38 @@ +/* + * MafiaHub OSS license + * Copyright (c) 2026, MafiaHub. All rights reserved. + * + * This file comes from MafiaHub, hosted at https://github.com/MafiaHub/Framework. + * See LICENSE file in the source repository for information regarding licensing. + */ + +#pragma once + +#include + +#include + +namespace Framework::Voice { + // Where the local player is listening from. Published by the game each frame; consumed + // by the audio thread through an atomically swapped snapshot. + struct ListenerTransform { + glm::vec3 position {0.0f}; + glm::vec3 forward {0.0f, 0.0f, 1.0f}; + glm::vec3 up {0.0f, 1.0f, 0.0f}; + }; + + // Per-ear linear gain for one speaker, in [0, 1]. + struct SpeakerGain { + float left = 0.0f; + float right = 0.0f; + }; + + // Distance attenuation and constant-power stereo pan for one speaker relative to the + // listener. Returns silence beyond `range`. Pure: no state, safe on the audio thread. + SpeakerGain ComputeGain(const ListenerTransform &listener, const glm::vec3 &speakerPos, float range); + + // Accumulates `samples` mono int16 samples into an interleaved stereo float buffer, + // applying `gain`. Adds rather than assigns so several speakers can be layered. + // `stereoOut` must hold at least samples * 2 floats. + void MixFrameInto(float *stereoOut, const int16_t *monoIn, uint32_t samples, SpeakerGain gain); +} // namespace Framework::Voice diff --git a/code/framework/src/voice/client/spsc_ring.h b/code/framework/src/voice/client/spsc_ring.h new file mode 100644 index 000000000..810fb1b0d --- /dev/null +++ b/code/framework/src/voice/client/spsc_ring.h @@ -0,0 +1,85 @@ +/* + * MafiaHub OSS license + * Copyright (c) 2026, MafiaHub. All rights reserved. + * + * This file comes from MafiaHub, hosted at https://github.com/MafiaHub/Framework. + * See LICENSE file in the source repository for information regarding licensing. + */ + +#pragma once + +#include +#include +#include +#include + +namespace Framework::Voice { + // Wait-free ring for exactly one producer thread and one consumer thread. Used to carry + // PCM across the audio-callback boundary, where allocating or locking would risk an + // underrun. One slot is always left empty so a full buffer is distinguishable from an + // empty one without a separate count. + // + // Capacity must be a power of two so the wrap is a mask rather than a modulo. + template + class SpscRing final { + // Capacity 0 would satisfy the power-of-two test on its own, leaving kMask as + // SIZE_MAX and Push writing into zero-length storage. + static_assert(Capacity >= 2 && (Capacity & (Capacity - 1)) == 0, "Capacity must be a power of two and at least 2"); + + public: + // Producer side. Returns false and writes nothing if the data would not fit. + bool Push(const T *src, size_t count) { + const size_t write = _write.load(std::memory_order_relaxed); + const size_t read = _read.load(std::memory_order_acquire); + const size_t free = Capacity - 1 - ((write - read) & kMask); + + if (count > free) { + return false; + } + + for (size_t i = 0; i < count; i++) { + _buffer[(write + i) & kMask] = src[i]; + } + + _write.store(write + count, std::memory_order_release); + return true; + } + + // Consumer side. Returns false and writes nothing if fewer than `count` are buffered. + bool Pop(T *dst, size_t count) { + const size_t read = _read.load(std::memory_order_relaxed); + const size_t write = _write.load(std::memory_order_acquire); + + if (((write - read) & kMask) < count) { + return false; + } + + for (size_t i = 0; i < count; i++) { + dst[i] = _buffer[(read + i) & kMask]; + } + + _read.store(read + count, std::memory_order_release); + return true; + } + + // Consumer side. Elements currently readable. + size_t Available() const { + const size_t write = _write.load(std::memory_order_acquire); + const size_t read = _read.load(std::memory_order_relaxed); + return (write - read) & kMask; + } + + // Not safe against a concurrent producer or consumer; call only when both are stopped. + void Clear() { + _read.store(0, std::memory_order_relaxed); + _write.store(0, std::memory_order_relaxed); + } + + private: + static constexpr size_t kMask = Capacity - 1; + + std::array _buffer {}; + std::atomic _read {0}; + std::atomic _write {0}; + }; +} // namespace Framework::Voice diff --git a/code/framework/src/voice/server/voice_router.cpp b/code/framework/src/voice/server/voice_router.cpp new file mode 100644 index 000000000..c9b15bed1 --- /dev/null +++ b/code/framework/src/voice/server/voice_router.cpp @@ -0,0 +1,81 @@ +/* + * MafiaHub OSS license + * Copyright (c) 2026, MafiaHub. All rights reserved. + * + * This file comes from MafiaHub, hosted at https://github.com/MafiaHub/Framework. + * See LICENSE file in the source repository for information regarding licensing. + */ + +#include "voice_router.h" + +namespace Framework::Voice { + void VoiceRouter::SetPlayerPosition(uint64_t guid, const glm::vec3 &pos) { + _players[guid].position = pos; + } + + void VoiceRouter::RemovePlayer(uint64_t guid) { + _players.erase(guid); + + // A local mute naming the departed player must go too, or a recycled GUID would + // silently inherit it. + for (auto &entry : _players) { + entry.second.locallyMuted.erase(guid); + } + } + + void VoiceRouter::SetPlayerRange(uint64_t guid, float meters) { + _players[guid].range = meters; + } + + void VoiceRouter::SetPlayerMuted(uint64_t guid, bool muted) { + _players[guid].serverMuted = muted; + } + + void VoiceRouter::SetLocalMute(uint64_t listener, uint64_t target, bool muted) { + auto &state = _players[listener]; + if (muted) { + state.locallyMuted.insert(target); + } + else { + state.locallyMuted.erase(target); + } + } + + void VoiceRouter::SetPlayerDeaf(uint64_t guid, bool deaf) { + _players[guid].deaf = deaf; + } + + void VoiceRouter::ComputeRecipients(uint64_t talker, std::vector &out) const { + out.clear(); + + const auto talkerIt = _players.find(talker); + if (talkerIt == _players.end() || talkerIt->second.serverMuted) { + return; + } + + const auto &talkerState = talkerIt->second; + const float range = talkerState.range > 0.0f ? talkerState.range : kDefaultProximityRange; + const float rangeSq = range * range; + + // Every eligible listener in range receives the frame; proximity is the only + // fan-out bound. Order is unspecified -- callers must not read anything into it. + out.reserve(_players.size()); + + for (const auto &[guid, state] : _players) { + if (guid == talker || state.deaf) { + continue; + } + if (state.locallyMuted.count(talker) != 0) { + continue; + } + + const glm::vec3 delta = state.position - talkerState.position; + const float distSq = glm::dot(delta, delta); + if (distSq > rangeSq) { + continue; + } + + out.push_back(guid); + } + } +} // namespace Framework::Voice diff --git a/code/framework/src/voice/server/voice_router.h b/code/framework/src/voice/server/voice_router.h new file mode 100644 index 000000000..b79c6b2ca --- /dev/null +++ b/code/framework/src/voice/server/voice_router.h @@ -0,0 +1,66 @@ +/* + * MafiaHub OSS license + * Copyright (c) 2026, MafiaHub. All rights reserved. + * + * This file comes from MafiaHub, hosted at https://github.com/MafiaHub/Framework. + * See LICENSE file in the source repository for information regarding licensing. + */ + +#pragma once + +#include "voice/voice_config.h" + +#include + +#include +#include +#include +#include + +namespace Framework::Voice { + // Decides who hears a given talker. Deliberately free of networking and audio: it is a + // pure function of positions, ranges and mute state, so the routing rule can be tested + // without standing up a server. VoiceServer owns one of these and feeds it positions. + // + // Proximity is evaluated with a linear scan rather than through the replication interest + // grid: InterestGrid::QueryRadius is private and keyed on NetworkEntity rather than + // player GUIDs, and at realistic player counts the scan is cheaper than that coupling. + class VoiceRouter final { + public: + // Upserts a player's world position. Also registers a previously unknown player. + void SetPlayerPosition(uint64_t guid, const glm::vec3 &pos); + + // Drops all state for a player: position, range, mute flags, and every local-mute + // entry naming them, so a reused GUID cannot inherit a stale mute. + void RemovePlayer(uint64_t guid); + + // Overrides the audibility radius for one talker (whisper / normal / shout). + // Pass a value <= 0 to fall back to kDefaultProximityRange. + void SetPlayerRange(uint64_t guid, float meters); + + // Server-wide mute: a muted talker reaches nobody. + void SetPlayerMuted(uint64_t guid, bool muted); + + // Listener-side mute: `listener` stops receiving `target`. + void SetLocalMute(uint64_t listener, uint64_t target, bool muted); + + // A deaf listener receives nobody. + void SetPlayerDeaf(uint64_t guid, bool deaf); + + // Fills `out` with the GUIDs that should receive `talker`'s frames. Clears `out` + // first. Every eligible listener in range is returned -- there is no server-side + // cap on fan-out, and the order is unspecified. + void ComputeRecipients(uint64_t talker, std::vector &out) const; + + private: + struct PlayerState { + glm::vec3 position {0.0f}; + float range = 0.0f; // <= 0 means kDefaultProximityRange + bool serverMuted = false; + bool deaf = false; + std::unordered_set locallyMuted; // talkers this player does not hear + }; + + std::unordered_map _players; + }; +} // namespace Framework::Voice diff --git a/code/framework/src/voice/server/voice_server.cpp b/code/framework/src/voice/server/voice_server.cpp new file mode 100644 index 000000000..60a219741 --- /dev/null +++ b/code/framework/src/voice/server/voice_server.cpp @@ -0,0 +1,143 @@ +/* + * MafiaHub OSS license + * Copyright (c) 2026, MafiaHub. All rights reserved. + * + * This file comes from MafiaHub, hosted at https://github.com/MafiaHub/Framework. + * See LICENSE file in the source repository for information regarding licensing. + */ + +#include "voice_server.h" + +#include "voice/voice_config.h" + +#include +#include +#include +#include + +namespace Framework::Voice { + bool VoiceServer::Init(Networking::NetworkServer *server) { + if (server == nullptr || server->GetPeer() == nullptr) { + return false; + } + + _server = server; + + // Relay host only. SetRelayHost is mandatory: without it RakVoice consumes + // ID_RAKVOICE_RELAY_DATA inside RakPeer::Receive and the packet never reaches the + // application loop, so OnVoiceFrame would never fire and voice would fail silently. + // + // SetRelayMode is deliberately NOT set. It is the flag a talking/listening client + // enables: it opens a self-keyed encoder channel and makes Update() walk the relay + // reap branch. A host neither encodes nor decodes -- RelayFrame ignores relayMode + // entirely -- so setting it would only put the plugin in a contradictory state. + // No Init() call either, so no codec is ever allocated here. + _voice.SetRelayHost(true); + server->GetPeer()->AttachPlugin(&_voice); + _attached = true; + + // Debug, not info: no client on any platform can produce or consume a frame until the + // client half lands, so announcing this on every server would only mislead operators. + Logging::GetLogger(FRAMEWORK_INNER_NETWORKING)->debug("Voice relay attached"); + return true; + } + + VoiceServer::~VoiceServer() { + // RakPeer holds a raw PluginInterface2* and PluginInterface2's destructor does not + // self-detach, so a VoiceServer destroyed while still attached would leave the peer + // with a dangling pointer. This object is owned outside NetworkPeer, so its lifetime + // is not tied to the peer's; detach here rather than depending on member declaration + // order in whatever owns it. + Shutdown(); + } + + void VoiceServer::Shutdown() { + // Idempotent: the explicit shutdown path and the destructor both land here. + if (_attached && _server != nullptr && _server->GetPeer() != nullptr) { + _server->GetPeer()->DetachPlugin(&_voice); + } + _attached = false; + _server = nullptr; + _cache.clear(); + } + + void VoiceServer::Update() { + // Nothing periodic is required: cache entries expire lazily in RecipientsFor(). + // Kept as an explicit hook so M2's channel bookkeeping has somewhere to live. + } + + void VoiceServer::OnPlayerDisconnect(uint64_t guid) { + _router.RemovePlayer(guid); + _cache.erase(guid); + } + + const std::vector &VoiceServer::RecipientsFor(uint64_t talker) { + auto &entry = _cache[talker]; + const int64_t nowMs = Utils::Time::GetTime(); + + if (entry.computedAtMs != 0 && (nowMs - entry.computedAtMs) < static_cast(kRecipientRefreshMs)) { + return entry.guids; + } + + _router.ComputeRecipients(talker, _scratch); + + entry.guids.clear(); + entry.guids.reserve(_scratch.size()); + for (const uint64_t guid : _scratch) { + entry.guids.push_back(MafiaNet::ToGuid(static_cast(guid))); + } + entry.computedAtMs = nowMs; + + return entry.guids; + } + + void VoiceServer::OnVoiceFrame(MafiaNet::Packet *packet) { + if (packet == nullptr || packet->length == 0) { + return; + } + + // The relay format is defined from byte 0: MafiaNet writes the id there and both of + // its readers use fixed offsets from it, so a timestamp-prefixed relay frame cannot + // be parsed at all. The dispatcher upstream identifies packets through + // GetPacketDataOffset(), which skips an ID_TIMESTAMP prefix, so the two would + // disagree if such a frame ever arrived. Assert the invariant here rather than + // threading an offset through a format that has nowhere to put it -- MafiaNet's + // RelayFrame rejects the same mismatch, so today this is belt and braces. + if (packet->data[0] != ID_RAKVOICE_RELAY_DATA) { + return; + } + + // A frame carrying nothing past the relay header is useless to every receiver, which + // drops it on the same test. Rejecting it here denies an amplification primitive: the + // fan-out below multiplies one inbound packet into one send per in-range listener, so + // a client spamming header-only frames would cost the server that multiple in egress. + if (packet->length <= MafiaNet::RAKVOICE_RELAY_HEADER_SIZE) { + return; + } + + // Upper bound for the same reason: RelayFrame forwards the payload verbatim once per + // recipient, so an oversized "frame" from a modified client would be amplified across + // the whole proximity set. No legitimate frame exceeds one maximum Opus packet. + if (packet->length > MafiaNet::RAKVOICE_RELAY_HEADER_SIZE + MafiaNet::RAKVOICE_MAX_OPUS_PACKET_SIZE) { + return; + } + + const MafiaNet::RakNetGUID origin = MafiaNet::RakVoice::ReadRelayOrigin(packet); + if (origin == MafiaNet::UNASSIGNED_RAKNET_GUID) { + return; + } + + // A client may only speak as itself. Without this check a modified client could + // stamp someone else's GUID and impersonate them. + if (origin != packet->guid) { + return; + } + + const auto &recipients = RecipientsFor(static_cast(MafiaNet::ToPeerGuid(origin))); + if (recipients.empty()) { + return; + } + + _voice.RelayFrame(packet, recipients.data(), static_cast(recipients.size())); + } +} // namespace Framework::Voice diff --git a/code/framework/src/voice/server/voice_server.h b/code/framework/src/voice/server/voice_server.h new file mode 100644 index 000000000..e91a4a6f8 --- /dev/null +++ b/code/framework/src/voice/server/voice_server.h @@ -0,0 +1,72 @@ +/* + * MafiaHub OSS license + * Copyright (c) 2026, MafiaHub. All rights reserved. + * + * This file comes from MafiaHub, hosted at https://github.com/MafiaHub/Framework. + * See LICENSE file in the source repository for information regarding licensing. + */ + +#pragma once + +#include "voice_router.h" + +#include + +#include +#include +#include + +namespace Framework::Networking { + class NetworkServer; +} // namespace Framework::Networking + +namespace Framework::Voice { + // Server half of voice: owns the routing rule and forwards frames. Deliberately never + // initialises a codec — RakVoice is attached purely so its relay path can forward + // payloads, which is what keeps voice off the server's CPU budget. + class VoiceServer final { + public: + VoiceServer() = default; + // Detaches the plugin if Shutdown() was not called explicitly; see the definition. + ~VoiceServer(); + + // Non-copyable, non-movable: the attached RakVoice member's address is registered with + // RakPeer, so relocating or duplicating this object would invalidate that pointer. + VoiceServer(const VoiceServer &) = delete; + VoiceServer &operator=(const VoiceServer &) = delete; + + bool Init(Networking::NetworkServer *server); + // Safe to call more than once. + void Shutdown(); + + // Call once per server tick. Frame forwarding itself happens on packet arrival, not + // here; kept as an explicit hook for periodic bookkeeping. + void Update(); + + VoiceRouter &GetRouter() { + return _router; + } + + // Called by the network layer for every ID_RAKVOICE_RELAY_DATA packet. + void OnVoiceFrame(MafiaNet::Packet *packet); + + void OnPlayerDisconnect(uint64_t guid); + + private: + // Recipient sets are cached per talker and refreshed on an interval rather than per + // frame; see kRecipientRefreshMs. + struct CachedRecipients { + std::vector guids; + int64_t computedAtMs = 0; + }; + + const std::vector &RecipientsFor(uint64_t talker); + + Networking::NetworkServer *_server = nullptr; + bool _attached = false; + MafiaNet::RakVoice _voice; + VoiceRouter _router; + std::unordered_map _cache; + std::vector _scratch; + }; +} // namespace Framework::Voice diff --git a/code/framework/src/voice/voice_config.h b/code/framework/src/voice/voice_config.h new file mode 100644 index 000000000..1e7901afe --- /dev/null +++ b/code/framework/src/voice/voice_config.h @@ -0,0 +1,44 @@ +/* + * MafiaHub OSS license + * Copyright (c) 2026, MafiaHub. All rights reserved. + * + * This file comes from MafiaHub, hosted at https://github.com/MafiaHub/Framework. + * See LICENSE file in the source repository for information regarding licensing. + */ + +#pragma once + +#include + +namespace Framework::Voice { + // Opus operates natively at 48kHz; 20ms frames are the standard trade-off between + // latency and per-packet header overhead. Mono, because voice is positioned by the + // client mixer rather than carried as stereo. + constexpr uint32_t kSampleRate = 48000; + constexpr uint32_t kChannels = 1; + constexpr uint32_t kFrameSamples = 960; // 20ms at 48kHz + constexpr uint32_t kFrameBytes = kFrameSamples * sizeof(int16_t); + + // Target Opus bitrate. 24kbps is transparent for speech and keeps a full lobby of + // talkers within a few hundred kbps of server egress. Opus picks its own rate unless + // told otherwise, so the client half must pass this to RakVoice::SetEncoderBitrate + // before opening its encode channel; the server never encodes. + constexpr uint32_t kBitrate = 24000; + + // How many concurrent speakers one client decodes and mixes: the number of speaker + // slots the client-side mixer allocates. This is NOT a server-side guard -- the router + // returns every listener in range, and proximity is the only fan-out bound. A true + // per-listener bound on inbound streams is an M2 item. + constexpr uint32_t kMaxAudibleTalkers = 6; + + // Recipient sets are recomputed on this interval rather than per frame; at 50 frames + // per second per talker, per-frame recomputation would be 50x the work for a set that + // changes slowly. + constexpr uint32_t kRecipientRefreshMs = 250; + + // Default proximity audibility radius, in world units. + constexpr float kDefaultProximityRange = 25.0f; + + // A speaker's decoder is released after this long without a frame. + constexpr uint32_t kSpeakerSilenceTimeoutMs = 2000; +} // namespace Framework::Voice diff --git a/code/tests/CMakeLists.txt b/code/tests/CMakeLists.txt index b2baca9a1..1f4eef65a 100644 --- a/code/tests/CMakeLists.txt +++ b/code/tests/CMakeLists.txt @@ -1,4 +1,4 @@ -add_executable(FrameworkTests framework_ut.cpp) +add_executable(FrameworkTests framework_ut.cpp ../framework/src/voice/client/mixer.cpp) target_include_directories(FrameworkTests PRIVATE . ../framework/src) target_link_libraries(FrameworkTests Framework FrameworkServer libnode) diff --git a/code/tests/framework_ut.cpp b/code/tests/framework_ut.cpp index d88e1017e..cf1314c1e 100644 --- a/code/tests/framework_ut.cpp +++ b/code/tests/framework_ut.cpp @@ -18,6 +18,9 @@ #include "modules/state_machine_ut.h" #include "modules/persistent_config_ut.h" #include "modules/snapshot_buffer_ut.h" +#include "modules/voice_router_ut.h" +#include "modules/spsc_ring_ut.h" +#include "modules/voice_mixer_ut.h" // Scripting tests #include "modules/engine_ut.h" @@ -38,6 +41,9 @@ int main() { UNIT_MODULE(state_machine); UNIT_MODULE(persistent_config); UNIT_MODULE(snapshot_buffer); + UNIT_MODULE(voice_router); + UNIT_MODULE(spsc_ring); + UNIT_MODULE(voice_mixer); // Scripting tests UNIT_MODULE(engine); diff --git a/code/tests/modules/spsc_ring_ut.h b/code/tests/modules/spsc_ring_ut.h new file mode 100644 index 000000000..dd51dc894 --- /dev/null +++ b/code/tests/modules/spsc_ring_ut.h @@ -0,0 +1,72 @@ +/* + * MafiaHub OSS license + * Copyright (c) 2026, MafiaHub. All rights reserved. + * + * This file comes from MafiaHub, hosted at https://github.com/MafiaHub/Framework. + * See LICENSE file in the source repository for information regarding licensing. + */ + +#pragma once + +#include "voice/client/spsc_ring.h" + +MODULE(spsc_ring, { + using namespace Framework::Voice; + + IT("returns what was pushed, in order", { + SpscRing ring; + const int16_t in[4] = {1, 2, 3, 4}; + EQUALS(ring.Push(in, 4), true); + + int16_t out[4] = {0, 0, 0, 0}; + EQUALS(ring.Pop(out, 4), true); + EQUALS(out[0], static_cast(1)); + EQUALS(out[3], static_cast(4)); + }); + + IT("reports how much is readable", { + SpscRing ring; + const int16_t in[3] = {7, 8, 9}; + ring.Push(in, 3); + EQUALS(ring.Available(), static_cast(3)); + }); + + IT("refuses a pop larger than what is buffered", { + SpscRing ring; + const int16_t in[2] = {1, 2}; + ring.Push(in, 2); + + int16_t out[4] = {0, 0, 0, 0}; + EQUALS(ring.Pop(out, 4), false); + EQUALS(ring.Available(), static_cast(2)); + }); + + IT("refuses a push that would overflow", { + SpscRing ring; + const int16_t in[8] = {1, 2, 3, 4, 5, 6, 7, 8}; + EQUALS(ring.Push(in, 8), false); + }); + + IT("wraps around the end of the buffer", { + SpscRing ring; + const int16_t first[5] = {1, 2, 3, 4, 5}; + int16_t scratch[5] = {0, 0, 0, 0, 0}; + + ring.Push(first, 5); + ring.Pop(scratch, 5); + + const int16_t second[5] = {6, 7, 8, 9, 10}; + EQUALS(ring.Push(second, 5), true); + EQUALS(ring.Pop(scratch, 5), true); + EQUALS(scratch[0], static_cast(6)); + EQUALS(scratch[4], static_cast(10)); + }); + + IT("is empty after being cleared", { + SpscRing ring; + const int16_t in[3] = {1, 2, 3}; + ring.Push(in, 3); + ring.Clear(); + EQUALS(ring.Available(), static_cast(0)); + }); +}); diff --git a/code/tests/modules/voice_mixer_ut.h b/code/tests/modules/voice_mixer_ut.h new file mode 100644 index 000000000..f201dbbe7 --- /dev/null +++ b/code/tests/modules/voice_mixer_ut.h @@ -0,0 +1,92 @@ +/* + * MafiaHub OSS license + * Copyright (c) 2026, MafiaHub. All rights reserved. + * + * This file comes from MafiaHub, hosted at https://github.com/MafiaHub/Framework. + * See LICENSE file in the source repository for information regarding licensing. + */ + +#pragma once + +#include "voice/client/mixer.h" + +#include + +namespace { + Framework::Voice::ListenerTransform OriginListener() { + Framework::Voice::ListenerTransform t; + t.position = glm::vec3(0.0f, 0.0f, 0.0f); + t.forward = glm::vec3(0.0f, 0.0f, 1.0f); + t.up = glm::vec3(0.0f, 1.0f, 0.0f); + return t; + } + + bool NearlyEqual(float a, float b) { + return std::fabs(a - b) < 0.02f; + } +} // namespace + +MODULE(voice_mixer, { + using namespace Framework::Voice; + + IT("plays a co-located speaker at equal, unattenuated volume in both ears", { + // Constant-power panning puts a centred speaker at cos(45 degrees) per ear, which is + // ~0.707 and not 1.0 — that is what keeps loudness flat as a speaker pans across. + const auto gain = ComputeGain(OriginListener(), glm::vec3(0.0f, 0.0f, 0.0f), 25.0f); + EQUALS(NearlyEqual(gain.left, 0.707f), true); + EQUALS(NearlyEqual(gain.right, 0.707f), true); + }); + + IT("silences a speaker beyond the range", { + const auto gain = ComputeGain(OriginListener(), glm::vec3(0.0f, 0.0f, 100.0f), 25.0f); + EQUALS(gain.left, 0.0f); + EQUALS(gain.right, 0.0f); + }); + + IT("attenuates with distance", { + // Not `near`/`far`: both are legacy macros from windows.h, so those names + // expand to nothing under MSVC and the declarations stop parsing. + const auto nearGain = ComputeGain(OriginListener(), glm::vec3(0.0f, 0.0f, 5.0f), 25.0f); + const auto farGain = ComputeGain(OriginListener(), glm::vec3(0.0f, 0.0f, 20.0f), 25.0f); + EQUALS(nearGain.left > farGain.left, true); + }); + + IT("pans a speaker on the right louder in the right ear", { + const auto gain = ComputeGain(OriginListener(), glm::vec3(5.0f, 0.0f, 0.0f), 25.0f); + EQUALS(gain.right > gain.left, true); + }); + + IT("pans a speaker on the left louder in the left ear", { + const auto gain = ComputeGain(OriginListener(), glm::vec3(-5.0f, 0.0f, 0.0f), 25.0f); + EQUALS(gain.left > gain.right, true); + }); + + IT("keeps a speaker dead ahead centred", { + const auto gain = ComputeGain(OriginListener(), glm::vec3(0.0f, 0.0f, 5.0f), 25.0f); + EQUALS(NearlyEqual(gain.left, gain.right), true); + }); + + IT("accumulates a frame into the stereo output", { + float out[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + const int16_t in[2] = {16384, -16384}; + const SpeakerGain g = {1.0f, 0.5f}; + + MixFrameInto(out, in, 2, g); + + EQUALS(NearlyEqual(out[0], 0.5f), true); // sample 0, left + EQUALS(NearlyEqual(out[1], 0.25f), true); // sample 0, right + EQUALS(NearlyEqual(out[2], -0.5f), true); // sample 1, left + EQUALS(NearlyEqual(out[3], -0.25f), true); // sample 1, right + }); + + IT("sums two speakers rather than replacing", { + float out[2] = {0.0f, 0.0f}; + const int16_t in[1] = {16384}; + const SpeakerGain g = {1.0f, 1.0f}; + + MixFrameInto(out, in, 1, g); + MixFrameInto(out, in, 1, g); + + EQUALS(NearlyEqual(out[0], 1.0f), true); + }); +}); diff --git a/code/tests/modules/voice_router_ut.h b/code/tests/modules/voice_router_ut.h new file mode 100644 index 000000000..3582382bc --- /dev/null +++ b/code/tests/modules/voice_router_ut.h @@ -0,0 +1,150 @@ +/* + * MafiaHub OSS license + * Copyright (c) 2026, MafiaHub. All rights reserved. + * + * This file comes from MafiaHub, hosted at https://github.com/MafiaHub/Framework. + * See LICENSE file in the source repository for information regarding licensing. + */ + +#pragma once + +#include "voice/server/voice_router.h" + +#include + +namespace { + bool RouterContains(const std::vector &v, uint64_t id) { + return std::find(v.begin(), v.end(), id) != v.end(); + } +} // namespace + +MODULE(voice_router, { + using namespace Framework::Voice; + + IT("delivers to a player inside the proximity range", { + VoiceRouter router; + router.SetPlayerPosition(1, glm::vec3(0, 0, 0)); + router.SetPlayerPosition(2, glm::vec3(10, 0, 0)); + + std::vector out; + router.ComputeRecipients(1, out); + + EQUALS(out.size(), static_cast(1)); + EQUALS(out[0], static_cast(2)); + }); + + IT("excludes a player outside the proximity range", { + VoiceRouter router; + router.SetPlayerPosition(1, glm::vec3(0, 0, 0)); + router.SetPlayerPosition(2, glm::vec3(500, 0, 0)); + + std::vector out; + router.ComputeRecipients(1, out); + + EQUALS(out.size(), static_cast(0)); + }); + + IT("never delivers a talker's own voice back to them", { + VoiceRouter router; + router.SetPlayerPosition(1, glm::vec3(0, 0, 0)); + // A second player in range is what makes this test able to fail: with only the + // talker registered, an empty result would also be produced by "nobody is here". + router.SetPlayerPosition(2, glm::vec3(1, 0, 0)); + + std::vector out; + router.ComputeRecipients(1, out); + + EQUALS(out.size(), static_cast(1)); + EQUALS(RouterContains(out, 2), true); + EQUALS(RouterContains(out, 1), false); + }); + + IT("returns every listener in range with no server-side cap", { + VoiceRouter router; + router.SetPlayerPosition(1, glm::vec3(0, 0, 0)); + + // Comfortably more than kMaxAudibleTalkers, which is a client mixer slot count and + // must not bound what the router returns. + constexpr uint64_t kListeners = 20; + for (uint64_t i = 2; i < 2 + kListeners; i++) { + router.SetPlayerPosition(i, glm::vec3(static_cast(i % 5), 0, 0)); + } + + std::vector out; + router.ComputeRecipients(1, out); + + EQUALS(out.size(), static_cast(kListeners)); + }); + + IT("honours a per-talker range override", { + VoiceRouter router; + router.SetPlayerPosition(1, glm::vec3(0, 0, 0)); + router.SetPlayerPosition(2, glm::vec3(60, 0, 0)); + router.SetPlayerRange(1, 100.0f); + + std::vector out; + router.ComputeRecipients(1, out); + + EQUALS(out.size(), static_cast(1)); + }); + + IT("drops every recipient when the talker is server-muted", { + VoiceRouter router; + router.SetPlayerPosition(1, glm::vec3(0, 0, 0)); + router.SetPlayerPosition(2, glm::vec3(5, 0, 0)); + router.SetPlayerMuted(1, true); + + std::vector out; + router.ComputeRecipients(1, out); + + EQUALS(out.size(), static_cast(0)); + }); + + IT("skips a listener who locally muted the talker", { + VoiceRouter router; + router.SetPlayerPosition(1, glm::vec3(0, 0, 0)); + router.SetPlayerPosition(2, glm::vec3(5, 0, 0)); + router.SetPlayerPosition(3, glm::vec3(5, 0, 0)); + router.SetLocalMute(2, 1, true); + + std::vector out; + router.ComputeRecipients(1, out); + + EQUALS(out.size(), static_cast(1)); + EQUALS(RouterContains(out, 3), true); + }); + + IT("skips a deaf listener", { + VoiceRouter router; + router.SetPlayerPosition(1, glm::vec3(0, 0, 0)); + router.SetPlayerPosition(2, glm::vec3(5, 0, 0)); + router.SetPlayerDeaf(2, true); + + std::vector out; + router.ComputeRecipients(1, out); + + EQUALS(out.size(), static_cast(0)); + }); + + IT("forgets a removed player", { + VoiceRouter router; + router.SetPlayerPosition(1, glm::vec3(0, 0, 0)); + router.SetPlayerPosition(2, glm::vec3(5, 0, 0)); + router.RemovePlayer(2); + + std::vector out; + router.ComputeRecipients(1, out); + + EQUALS(out.size(), static_cast(0)); + }); + + IT("returns nothing for an unknown talker", { + VoiceRouter router; + router.SetPlayerPosition(2, glm::vec3(5, 0, 0)); + + std::vector out; + router.ComputeRecipients(99, out); + + EQUALS(out.size(), static_cast(0)); + }); +}); diff --git a/vendors/CMakeLists.txt b/vendors/CMakeLists.txt index 0c97ab274..610c8fde3 100644 --- a/vendors/CMakeLists.txt +++ b/vendors/CMakeLists.txt @@ -51,8 +51,76 @@ set(HTTPLIB_REQUIRE_OPENSSL ON) set(HTTPLIB_COMPILE ON) add_subdirectory(httplib) -# Build MafiaNet (networking, vendored fork of RakNet/SLikeNet) -add_subdirectory(mafianet) +# MafiaNet (networking) - fetched, not vendored. +# +# MafiaNet owns RakVoice, and therefore owns RakVoice's Opus and RNNoise +# dependencies, which its own build fetches. Vendoring MafiaNet here would mean +# hoisting those two a level up into this repository: ~85 MB of third-party +# source, a collision with this repo's `vendors/**/*.cmake` ignore rule, and a +# re-vendor split across three trees that have to stay in lockstep. Fetching the +# release instead keeps the dependency boundary where it belongs. +# +# This is the only FetchContent in the Framework build; everything else under +# vendors/ is genuinely vendored in-tree. Building therefore needs network access +# on a cold configure (the fetch is cached in the build tree afterwards). +include(FetchContent) + +# Framework links the static library only; samples and MafiaNet's own test suite +# are not our concern. +set(MAFIANET_BUILD_SHARED OFF CACHE BOOL "" FORCE) +set(MAFIANET_BUILD_STATIC ON CACHE BOOL "" FORCE) +set(MAFIANET_BUILD_SAMPLES OFF CACHE BOOL "" FORCE) +set(MAFIANET_BUILD_TESTS OFF CACHE BOOL "" FORCE) + +# Pinned to a release tag, never a branch: the message-id enum is positional, so +# an unpinned bump would silently change the wire format. The pin lives in +# cmake/MafiaNetPin.cmake so the release tooling can watch that one path. +include(MafiaNetPin) + +FetchContent_Declare( + MafiaNet + GIT_REPOSITORY https://github.com/MafiaHub/MafiaNet.git + GIT_TAG ${MAFIANET_PIN} + GIT_SHALLOW TRUE +) +FetchContent_MakeAvailable(MafiaNet) + +# Reconcile the fetched dependencies with this build's CRT convention. +# +# Framework uses the RELEASE CRT even in Debug builds: FrameworkSetup forces +# CMAKE_MSVC_RUNTIME_LIBRARY to MultiThreadedDLL and replaces +# CMAKE_CXX_FLAGS_DEBUG outright, so no /MDd and no _DEBUG reach its objects. +# +# MafiaNet follows the ordinary convention instead -- Source/CMakeLists.txt does +# target_compile_definitions(... $<$:_DEBUG>). Defining _DEBUG makes +# MSVC select the debug CRT semantics in the object itself: _ITERATOR_DEBUG_LEVEL +# becomes 2 and the object records MDd_DynamicDebug. Linking that against +# Framework's MD_DynamicRelease objects fails with LNK2038, and no flag or +# MSVC_RUNTIME_LIBRARY property can override it, because the definition is what +# drives it. CI confirmed exactly that: the property was applied correctly and the +# objects still came out MDd. +# +# So drop the definition on the fetched targets rather than fighting the symptom. +# This is Framework adapting to its own unusual choice, not a defect upstream -- +# MafiaNet is right to define _DEBUG when it is built normally. +# +# Nothing analogous was needed while MafiaNet was vendored: that copy was a bare +# add_library() with no target_compile_definitions of its own. +if(MSVC) + foreach(_mafianet_target MafiaNetStatic MafiaNet opus rnnoise) + if(TARGET ${_mafianet_target}) + set_property(TARGET ${_mafianet_target} PROPERTY + MSVC_RUNTIME_LIBRARY "MultiThreadedDLL") + + get_target_property(_fw_defs ${_mafianet_target} COMPILE_DEFINITIONS) + if(_fw_defs) + list(REMOVE_ITEM _fw_defs "$<$:_DEBUG>" "_DEBUG") + set_property(TARGET ${_mafianet_target} PROPERTY + COMPILE_DEFINITIONS ${_fw_defs}) + endif() + endif() + endforeach() +endif() # Build sentry set(CURL_STATICLIB ON) diff --git a/vendors/mafianet/CMakeLists.txt b/vendors/mafianet/CMakeLists.txt deleted file mode 100644 index b99b7c92a..000000000 --- a/vendors/mafianet/CMakeLists.txt +++ /dev/null @@ -1,38 +0,0 @@ -# MafiaNet - MafiaHub's networking engine (fork of RakNet/SLikeNet). -# Vendored, pinned to tag v0.10.0 (see VERSION.txt). Built as a static library. -# -# Public headers live under Source/include and are consumed with the -# "mafianet/" prefix, e.g. #include . - -file(GLOB MAFIANET_SRC - "Source/src/*.cpp" - "Source/src/crypto/*.cpp" -) -# Guard against stray hidden/temp files (e.g. ".!!foo.cpp") being picked up. -list(FILTER MAFIANET_SRC EXCLUDE REGEX "/\\.") - -add_library(MafiaNet STATIC ${MAFIANET_SRC}) - -target_include_directories(MafiaNet PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/Source/include") - -# OpenSSL is required by MafiaNet's crypto module and secure handshake. Reuse the -# targets already provided by the surrounding build (httplib pulls OpenSSL in -# before this directory is configured); fall back to find_package otherwise. -if(NOT TARGET OpenSSL::SSL) - find_package(OpenSSL REQUIRED) -endif() -find_package(Threads REQUIRED) - -target_link_libraries(MafiaNet PUBLIC OpenSSL::SSL OpenSSL::Crypto Threads::Threads) - -if(WIN32) - target_link_libraries(MafiaNet PUBLIC ws2_32) - target_compile_definitions(MafiaNet PUBLIC _MAFIANET_LIB) -endif() - -# Suppress third-party warnings (this is vendored code). -if(MSVC) - target_compile_options(MafiaNet PRIVATE /w) -else() - target_compile_options(MafiaNet PRIVATE -w) -endif() diff --git a/vendors/mafianet/LICENSE.md b/vendors/mafianet/LICENSE.md deleted file mode 100644 index 616d1331f..000000000 --- a/vendors/mafianet/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -Copyright © 2024 MafiaHub - - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - ------------------------------------------------------ -END OF LICENSE \ No newline at end of file diff --git a/vendors/mafianet/README.md b/vendors/mafianet/README.md deleted file mode 100644 index 761b4c87a..000000000 --- a/vendors/mafianet/README.md +++ /dev/null @@ -1,357 +0,0 @@ -
- - MafiaHub - - -

MafiaNet

- -

A modern, cross-platform networking engine for multiplayer games

- -

- Build & Test - Discord - License - C++17 - CMake -

- -

- Quick Start • - Features • - Documentation • - Community -

-
- ---- - -## About - -MafiaNet is an actively maintained networking library built for game developers who need reliable, high-performance multiplayer networking. Built on the foundation of RakNet and SLikeNet, MafiaNet delivers battle-tested networking capabilities with modern C++ standards and security practices. - -**Supported Platforms:** Windows, Linux, macOS (primary) | iOS, Android (limited) - -## Quick Start - -### Requirements - -- CMake 3.21+ -- C++17 compatible compiler -- OpenSSL 1.0.0+ -- Internet connection (first build fetches dependencies automatically) - -### Building - -**Linux / macOS:** -```bash -git clone https://github.com/MafiaHub/MafiaNet.git -cd MafiaNet -mkdir build && cd build -cmake .. -cmake --build . -j$(nproc) # Linux -cmake --build . -j$(sysctl -n hw.ncpu) # macOS -``` - -**Windows (Visual Studio):** -```powershell -git clone https://github.com/MafiaHub/MafiaNet.git -cd MafiaNet - -# Generate Visual Studio 2022 solution -cmake -G "Visual Studio 17 2022" -A x64 -B build - -# Build from command line, or open build/MafiaNet.sln in Visual Studio -cmake --build build --config Release -``` - -### Build Options - -| Option | Default | Description | -|--------|---------|-------------| -| `MAFIANET_BUILD_SHARED` | ON | Build shared library (.dll/.so/.dylib) | -| `MAFIANET_BUILD_STATIC` | ON | Build static library (.lib/.a) | -| `MAFIANET_BUILD_SAMPLES` | OFF | Build 80 sample applications and extensions | -| `MAFIANET_BUILD_TESTS` | OFF | Build test suite | - -To build with samples: -```bash -cmake -DMAFIANET_BUILD_SAMPLES=ON .. -``` - -### Basic Usage - -```cpp -#include "mafianet/peerinterface.h" -#include "mafianet/MessageIdentifiers.h" - -// Create a peer -MafiaNet::RakPeerInterface* peer = MafiaNet::RakPeerInterface::GetInstance(); - -// Start as server -MafiaNet::SocketDescriptor sd(60000, 0); -peer->Startup(32, &sd, 1); -peer->SetMaximumIncomingConnections(32); - -// Or connect as client -peer->Connect("127.0.0.1", 60000, nullptr, 0); - -// Process incoming packets -MafiaNet::Packet* packet; -while ((packet = peer->Receive()) != nullptr) { - switch (packet->data[0]) { - case ID_NEW_INCOMING_CONNECTION: - printf("Client connected\n"); - break; - case ID_CONNECTION_REQUEST_ACCEPTED: - printf("Connected to server\n"); - break; - } - peer->DeallocatePacket(packet); -} - -// Cleanup -MafiaNet::RakPeerInterface::DestroyInstance(peer); -``` - -## Features - - - - - - - - - - -
- -### Core Networking -- Reliable UDP with automatic retransmission -- Packet ordering and sequencing -- Automatic packet splitting for large messages -- IPv4 and IPv6 dual-stack support -- SSL/TLS encryption via OpenSSL -- Connection statistics and monitoring - - - -### Multiplayer Systems -- Peer-to-peer and client-server architectures -- NAT punchthrough and traversal -- Host migration -- Room and lobby management -- Object replication (ReplicaManager3) -- Remote procedure calls (RPC4) - -
- -### Development Tools -- Packet logger with multiple outputs -- Network simulator (latency, packet loss) -- Bandwidth monitoring and limiting -- Message filtering -- Comprehensive debug statistics - - - -### Extensions -- **RakVoice** - Voice chat with Opus codec and RNNoise -- **Autopatcher** - Delta patching for game updates -- **FileListTransfer** - Reliable file transfer -- **Database** - MySQL, PostgreSQL, SQLite integration -- **UPnP** - Automatic port forwarding - -
- -## Plugins - -MafiaNet provides a modular plugin system for extending functionality: - -| Plugin | Description | -|--------|-------------| -| **ReplicaManager3** | Automatic object replication and state synchronization | -| **RPC4** | Remote procedure calls with parameter serialization | -| **FullyConnectedMesh2** | P2P mesh networking with host migration | -| **NatPunchthrough** | NAT traversal for peer-to-peer connections | -| **FileListTransfer** | Reliable file transfer with progress callbacks | -| **DirectoryDeltaTransfer** | Incremental directory synchronization | -| **Autopatcher** | Delta patching system for game updates | -| **RakVoice** | Voice chat with Opus codec and noise suppression | -| **ReadyEvent** | Player ready state synchronization | -| **TeamManager** | Team assignment and balancing | -| **Router2** | Message routing through intermediate peers | -| **MessageFilter** | Security filtering for incoming messages | -| **PacketLogger** | Network traffic logging and debugging | -| **TwoWayAuthentication** | Mutual authentication between peers | -| **CloudComputing** | Distributed data storage and retrieval | -| **Lobby2** | Matchmaking and lobby system | - -See the [Plugin Documentation](https://mafianet.mafiahub.dev/plugins/overview.html) for detailed usage. - -## Documentation - -Full documentation is available at **[mafianet.mafiahub.dev](https://mafianet.mafiahub.dev)** - -Documentation includes: -- [Installation Guide](https://mafianet.mafiahub.dev/getting-started/installation.html) -- [Quick Start Tutorial](https://mafianet.mafiahub.dev/getting-started/quickstart.html) -- [Architecture Guide](https://mafianet.mafiahub.dev/guide/concepts.html) -- [Plugin Reference](https://mafianet.mafiahub.dev/plugins/overview.html) -- [API Reference](https://mafianet.mafiahub.dev/api/core.html) -- [FAQ](https://mafianet.mafiahub.dev/support/faq.html) - -### Building Documentation Locally - -```bash -# Install dependencies -brew install doxygen # macOS -sudo apt install doxygen # Ubuntu/Debian -pip install -r docs/requirements.txt - -# Build and serve -cd docs -./build.sh serve # http://localhost:8000 -``` - -## Project Structure - -``` -MafiaNet/ -├── Source/ -│ ├── include/mafianet/ # Public API headers (include as "mafianet/...") -│ └── src/ # Implementation files -├── Samples/ # 80 example applications -│ ├── ChatExample/ # Simple chat application -│ ├── Ping/ # Basic UDP communication -│ ├── ReplicaManager3/ # Object replication demo -│ ├── NATCompleteClient/ # NAT traversal client -│ ├── NATCompleteServer/ # NAT traversal server -│ ├── RakVoice/ # Voice chat examples -│ ├── FileListTransfer/ # File transfer demo -│ └── Tests/ # Comprehensive test suite -├── DependentExtensions/ # Optional integrations -│ ├── Autopatcher/ # Delta patching system -│ ├── Lobby2/ # Matchmaking and lobbies -│ ├── RakVoice.cpp/h # Voice communication -│ ├── MySQLInterface/ # MySQL connectivity -│ ├── PostgreSQLInterface/# PostgreSQL connectivity -│ ├── SQLite3Plugin/ # SQLite integration -│ └── RPC3/ # Legacy RPC system -├── docs/ # Sphinx documentation source -└── cmake/ # CMake modules and helpers -``` - -## Dependencies - -MafiaNet automatically fetches required dependencies via CMake FetchContent: - -| Dependency | Version | Used For | -|------------|---------|----------| -| OpenSSL | 1.0.0+ | Encryption (required, system-installed) | -| bzip2 | - | Compression (Autopatcher) | -| miniupnpc | - | UPnP port forwarding | -| Opus | 1.5.2 | Voice codec (RakVoice) | -| RNNoise | - | Noise suppression (RakVoice) | - -## Running Tests - -Build with samples enabled, then run the test suite: - -```bash -cmake -DMAFIANET_BUILD_SAMPLES=ON .. -cmake --build . -./Samples/Tests/Tests - -# Run a specific test -./Samples/Tests/Tests EightPeerTest -``` - -Available tests include: `EightPeerTest`, `MaximumConnectTest`, `PeerConnectDisconnectTest`, `ManyClientsOneServerBlockingTest`, `ReliableOrderedConvertedTest`, `SecurityFunctionsTest`, `SystemAddressAndGuidTest`, and more. - -## Changelog - -### Version 0.10.0 (Latest) -- **Umbrella header `mafianet/mafianet.h`**: aggregates the core public headers (`RakPeerInterface`, types, message IDs, `PacketPriority`, `BitStream`, `GetTime`, `Statistics`) so the common path only needs `#include "mafianet/mafianet.h"`. Additive — granular headers remain; encryption headers are intentionally omitted (security stays opt-in via `InitializeSecurity()`) -- **Canonical type aliases** (`mafianet/aliases.h`): `PeerInterface` (`RakPeerInterface`), `Guid` (`RakNetGUID`), `Statistics` (`RakNetStatistics`), `UnassignedGuid`. `using` aliases denoting the same types, so old and new names interoperate; legacy names left untouched -- **RAII handles `Peer` & `PacketPtr`** (`mafianet/PeerHandle.h`): own a `RakPeerInterface` / received `Packet` and clean up on scope exit, removing manual `DestroyInstance` / `DeallocatePacket` bookkeeping. ChatExample client rewritten to use them -- **Thread-safe GUID value accessors** (`mafianet/guid_util.h`): `MafiaNet::to_string(const RakNetGUID&)` owns its buffer; `connected_address(...)` returns `std::optional` (sentinel → `nullopt`) -- **`PointGridSectorizer`**: uniform point grid with O(1) `RemoveEntry`/`MoveEntry` via per-entry hash + swap-remove (early-out on same-cell moves), upsert add/move semantics, duplicate-free `GetEntries`, and edge-cell clamping. `GridSectorizer` left untouched -- **Breaking — scoped enum classes**: the global `PacketPriority` / `PacketReliability` C enums are removed in favour of scoped `MafiaNet::Priority` / `MafiaNet::Reliability`. Enumerator order (and the wire field) is preserved, but call sites must update (`HIGH_PRIORITY` → `MafiaNet::Priority::High`, `RELIABLE_ORDERED` → `MafiaNet::Reliability::ReliableOrdered`); `NUMBER_OF_*` sentinels are now `constexpr` counts in `MafiaNet` -- **Breaking — removed non-thread-safe `RakNetGUID::ToString(void)`** (shared static buffer); use `MafiaNet::to_string(g).c_str()` -- **Bug fix**: `PeerHandle` no longer dereferences a moved-from `Peer` in `receive()` - -### Version 0.9.0 -- **Strong-typed `PeerGuid`**: a new `enum class PeerGuid : uint64_t` names a peer's `RakNetGUID` value distinctly from `NetworkID` (an object id), so the two can no longer be passed interchangeably in a `uint64_t`-typed signature — removing a class of silent "passed the wrong id" bugs in ReplicaManager3 glue and `void(uint64_t)` callbacks. Convert with `ToPeerGuid()` / `ToGuid()` and compare against `UNASSIGNED_PEER_GUID`. As a trivially-copyable 8-byte scoped enum it serializes byte-identically through `BitStream` (and therefore `VariableDeltaSerializer`) to the raw `uint64_t` it replaces — fully wire-compatible, no netcode bump. Purely additive, no behavioural change - -### Version 0.8.0 -- **Optional disconnect reason**: `CloseConnection` gains a final optional `const BitStream *reasonData` argument whose bytes are appended right after the `ID_DISCONNECTION_NOTIFICATION` message ID, so the remote peer can learn *why* it was dropped (e.g. a kick/ban enum plus a custom string). The receiver reads it like any other body — `packet->data + 1` for `packet->length - 1` bytes. Only graceful disconnects carry a reason; locally-synthesized notifications (`ID_CONNECTION_LOST`, timeout/dead-connection) stay payload-less, so always tolerate a zero-length body. Wire-backward-compatible: peers that only inspect `data[0]` are unaffected -- **Bug fix**: `RakPeer::CloseConnection` no longer coerces an unresolved target index (`-1`) to `0` and reads `remoteSystemList[0]` — which targeted an unrelated peer's slot or crashed on an unallocated list; the close socket is now resolved without assuming a valid slot index - -### Version 0.7.0 -- **Virtual worlds (dimensions)**: new per-entity / per-observer `VirtualWorldId` scoping on top of ReplicaManager3 — the SA-MP `SetPlayerVirtualWorld` / routing-bucket model for instanced interiors (e.g. apartments). Players only see entities sharing their virtual world (or `VIRTUAL_WORLD_GLOBAL`), switchable at runtime with no reconnect. Derive entities from `VirtualWorldReplica3`; `Connection_RM3` gets `Get/SetVirtualWorld`; `ReplicaManager3` gets `GetConnectionsInVirtualWorld`/`GetGuidsInVirtualWorld` and `SetPlayerVirtualWorld`. The filter is authority-only, so a downloaded copy never despawns the entity at its owner. See `Samples/VirtualWorld` - -### Version 0.6.1 -- **ReplicaManager3**: `GetReplicaAtIndex` is now `const`, matching the other read accessors (`GetReplicaCount`, `GetConnectionCount`, `GetConnectionAtIndex`) — const methods iterating replicas no longer need a `const_cast`. The returned `Replica3*` stays non-const. Source-compatible (no break for existing non-const call sites) - -### Version 0.6.0 -- **RPC4 user context**: `RegisterFunction`, `RegisterSlot`, `RegisterBlockingFunction` and the `RPC4GlobalRegistration` handler constructors now take an opaque `void *context` passed back to the handler on every call — no more file-static global pointers to route an RPC to an object instance (each registration carries its own context) -- **Bug fix**: `RakPeer::CloseConnection` no longer dereferences a null `rakNetSocket` during teardown (a pre-existing crash in release builds); falls back to the primary socket -- **Testing**: added `RPC4ContextTest` (slot/nonblocking/blocking context); quarantined the flaky `ManyClientsOneServerDeallocateBlockingTest` in CI pending a teardown-race fix -- _Breaking_: RPC4 handler signatures gained a trailing `void *context` and the registration calls take a context argument; there are no compatibility overloads (pass `nullptr` when unused) - -### Version 0.5.1 -- **Plugins**: Added `DirectoryDeltaTransfer::AddFile(filePath, fileName)` to queue a single file for upload (complements the recursive `AddUploadsFromSubdirectory`) - -### Version 0.5.0 -- **Namespace cleanup**: Standardized on the `MafiaNet` namespace; removed the legacy `SLNet` macro in favor of an `MNet` shorthand alias, and dropped stale `RakNet` alias references -- **Single header set**: Collapsed the legacy redirect-stub header layers into the canonical `mafianet/...` includes -- **BitStream safety**: Catch-all serialization now `static_assert`s on trivially-copyable types (preventing `std::string` double-frees), with added length-prefixed `std::string` specializations -- _Breaking_: legacy include spellings and the `SLNet` namespace macro are removed; serializing non-trivially-copyable types via the generic `BitStream::Write`/`Read` is now a compile error - -### Version 0.4.0 -- **Cross-platform**: Full macOS and Linux support, merged `Socket2` definitions, removed deprecated platform back-ends -- Fixed IPv6 connectivity and initialization issues -- Upgraded dependencies: OpenSSL 3.6.0, miniupnpc 2.3.3, Opus 1.6.1; dependencies now fetched on demand via CMake -- Fixed undefined behaviour in congestion control and a null-socket crash in connection teardown -- CI now runs the full test suite on Linux, macOS and Windows, with numerous test-stability fixes - -### Version 0.3.0 -- **RakVoice**: Migrated from Speex to Opus codec with RNNoise noise suppression -- Added support for 8000, 16000, 24000, 48000 Hz sample rates -- Voice activity detection using Opus DTX - -### Version 0.2.0 -- Rebranded from SLikeNet to MafiaNet -- Updated to C++17 standard -- Modernized CMake build system -- Added Sphinx documentation with Breathe integration -- Removed pre-generated Visual Studio solution files - -See [CHANGELOG](https://mafianet.mafiahub.dev/changelog.html) for full history. - -## Background - -MafiaNet continues the legacy of two foundational networking libraries: - -- **RakNet** (2001-2014) - Industry-standard game networking library by Jenkins Software, used in countless multiplayer games. Acquired and open-sourced by Oculus VR. -- **SLikeNet** (2016-2019) - Community continuation by SLikeSoft that modernized RakNet with bug fixes, security patches, and C++11 support. - -With SLikeNet no longer maintained, MafiaNet carries the torch forward—providing an actively developed, modern networking solution for the game development community. - -## Community - -- **Discord**: [Join our server](https://discord.gg/eBQ4QHX) for support and discussion -- **Documentation**: [mafianet.mafiahub.dev](https://mafianet.mafiahub.dev) -- **Issues**: [Report bugs](https://github.com/MafiaHub/MafiaNet/issues) or request features -- **Contributions**: Pull requests are welcome! - -## License - -MafiaNet is released under the [MIT License](LICENSE.md). - ---- - -
- Built with passion by the MafiaHub community -
diff --git a/vendors/mafianet/Source/CMakeLists.txt b/vendors/mafianet/Source/CMakeLists.txt deleted file mode 100644 index 4d714cdba..000000000 --- a/vendors/mafianet/Source/CMakeLists.txt +++ /dev/null @@ -1,437 +0,0 @@ -# MafiaNet Library -# -# Copyright (c) 2024, MafiaHub -# Licensed under MIT-style license - -# Source files (explicit list, no GLOB) -set(MAFIANET_SOURCES - src/_FindFirst.cpp - src/Base64Encoder.cpp - src/BitStream.cpp - src/CCRakNetSlidingWindow.cpp - src/CCRakNetUDT.cpp - src/CheckSum.cpp - src/CloudClient.cpp - src/CloudCommon.cpp - src/CloudServer.cpp - src/CommandParserInterface.cpp - src/ConnectionGraph2.cpp - src/ConsoleServer.cpp - src/DataCompressor.cpp - src/DirectoryDeltaTransfer.cpp - src/DR_SHA1.cpp - src/DS_BytePool.cpp - src/DS_ByteQueue.cpp - src/DS_HuffmanEncodingTree.cpp - src/DS_Table.cpp - src/DynDNS.cpp - src/EmailSender.cpp - src/EpochTimeToString.cpp - src/FileList.cpp - src/FileListTransfer.cpp - src/FileOperations.cpp - src/FormatString.cpp - src/FullyConnectedMesh2.cpp - src/Getche.cpp - src/Gets.cpp - src/GetTime.cpp - src/gettimeofday.cpp - src/GridSectorizer.cpp - src/guid_util.cpp - src/HTTPConnection.cpp - src/HTTPConnection2.cpp - src/IncrementalReadInterface.cpp - src/Itoa.cpp - src/linux_adapter.cpp - src/LinuxStrings.cpp - src/LocklessTypes.cpp - src/LogCommandParser.cpp - src/MessageFilter.cpp - src/NatPunchthroughClient.cpp - src/NatPunchthroughServer.cpp - src/NatTypeDetectionClient.cpp - src/NatTypeDetectionCommon.cpp - src/NatTypeDetectionServer.cpp - src/NetworkIDManager.cpp - src/NetworkIDObject.cpp - src/osx_adapter.cpp - src/PacketConsoleLogger.cpp - src/PacketFileLogger.cpp - src/PacketizedTCP.cpp - src/PacketLogger.cpp - src/PacketOutputWindowLogger.cpp - src/PeerHandle.cpp - src/PluginInterface2.cpp - src/PointGridSectorizer.cpp - src/PS4Includes.cpp - src/Rackspace.cpp - src/RakMemoryOverride.cpp - src/RakNetCommandParser.cpp - src/RakNetSocket.cpp - src/RakNetSocket2.cpp - src/RakNetSocket2_Berkley.cpp - src/RakNetSocket2_Windows_Linux.cpp - src/RakNetSocket2_Windows_Linux_360.cpp - src/RakNetStatistics.cpp - src/RakNetTransport2.cpp - src/RakNetTypes.cpp - src/RakPeer.cpp - src/RakSleep.cpp - src/RakString.cpp - src/RakThread.cpp - src/RakWString.cpp - src/Rand.cpp - src/RandSync.cpp - src/ReadyEvent.cpp - src/RelayPlugin.cpp - src/ReliabilityLayer.cpp - src/ReplicaManager3.cpp - src/Router2.cpp - src/RPC4Plugin.cpp - src/SecureHandshake.cpp - src/SendToThread.cpp - src/SignaledEvent.cpp - src/SimpleMutex.cpp - src/SocketLayer.cpp - src/StatisticsHistory.cpp - src/StringCompressor.cpp - src/StringTable.cpp - src/SuperFastHash.cpp - src/TableSerializer.cpp - src/TCPInterface.cpp - src/TeamBalancer.cpp - src/TeamManager.cpp - src/TelnetTransport.cpp - src/ThreadsafePacketLogger.cpp - src/TwoWayAuthentication.cpp - src/UDPForwarder.cpp - src/UDPProxyClient.cpp - src/UDPProxyCoordinator.cpp - src/UDPProxyServer.cpp - src/VariableDeltaSerializer.cpp - src/VariableListDeltaTracker.cpp - src/VariadicSQLParser.cpp - src/VitaIncludes.cpp - src/WSAStartupSingleton.cpp -) - -set(MAFIANET_CRYPTO_SOURCES - src/crypto/cryptomanager.cpp - src/crypto/factory.cpp - src/crypto/fileencrypter.cpp - src/crypto/securestring.cpp -) - -set(MAFIANET_HEADERS - include/mafianet/_FindFirst.h - include/mafianet/alloca.h - include/mafianet/assert.h - include/mafianet/AutopatcherPatchContext.h - include/mafianet/AutopatcherRepositoryInterface.h - include/mafianet/Base64Encoder.h - include/mafianet/BitStream.h - include/mafianet/CCRakNetSlidingWindow.h - include/mafianet/CCRakNetUDT.h - include/mafianet/CheckSum.h - include/mafianet/CloudClient.h - include/mafianet/CloudCommon.h - include/mafianet/CloudServer.h - include/mafianet/commandparser.h - include/mafianet/CommandParserInterface.h - include/mafianet/ConnectionGraph2.h - include/mafianet/ConsoleServer.h - include/mafianet/DataCompressor.h - include/mafianet/defineoverrides.h - include/mafianet/defines.h - include/mafianet/DirectoryDeltaTransfer.h - include/mafianet/DR_SHA1.h - include/mafianet/DS_BinarySearchTree.h - include/mafianet/DS_BPlusTree.h - include/mafianet/DS_BytePool.h - include/mafianet/DS_ByteQueue.h - include/mafianet/DS_Hash.h - include/mafianet/DS_Heap.h - include/mafianet/DS_HuffmanEncodingTree.h - include/mafianet/DS_HuffmanEncodingTreeFactory.h - include/mafianet/DS_HuffmanEncodingTreeNode.h - include/mafianet/DS_LinkedList.h - include/mafianet/DS_List.h - include/mafianet/DS_Map.h - include/mafianet/DS_MemoryPool.h - include/mafianet/DS_Multilist.h - include/mafianet/DS_OrderedChannelHeap.h - include/mafianet/DS_OrderedList.h - include/mafianet/DS_Queue.h - include/mafianet/DS_QueueLinkedList.h - include/mafianet/DS_RangeList.h - include/mafianet/DS_Table.h - include/mafianet/DS_ThreadsafeAllocatingQueue.h - include/mafianet/DS_Tree.h - include/mafianet/DS_WeightedGraph.h - include/mafianet/DynDNS.h - include/mafianet/EmailSender.h - include/mafianet/EmptyHeader.h - include/mafianet/EpochTimeToString.h - include/mafianet/Export.h - include/mafianet/FileList.h - include/mafianet/FileListNodeContext.h - include/mafianet/FileListTransfer.h - include/mafianet/FileListTransferCBInterface.h - include/mafianet/FileOperations.h - include/mafianet/FormatString.h - include/mafianet/FullyConnectedMesh2.h - include/mafianet/Getche.h - include/mafianet/Gets.h - include/mafianet/GetTime.h - include/mafianet/gettimeofday.h - include/mafianet/GridSectorizer.h - include/mafianet/guid_util.h - include/mafianet/HTTPConnection.h - include/mafianet/HTTPConnection2.h - include/mafianet/IncrementalReadInterface.h - include/mafianet/InternalPacket.h - include/mafianet/Itoa.h - include/mafianet/Kbhit.h - include/mafianet/linux_adapter.h - include/mafianet/LinuxStrings.h - include/mafianet/LocklessTypes.h - include/mafianet/LogCommandParser.h - include/mafianet/memoryoverride.h - include/mafianet/MessageFilter.h - include/mafianet/MessageIdentifiers.h - include/mafianet/MTUSize.h - include/mafianet/NativeFeatureIncludes.h - include/mafianet/NativeFeatureIncludesOverrides.h - include/mafianet/NativeTypes.h - include/mafianet/NatPunchthroughClient.h - include/mafianet/NatPunchthroughServer.h - include/mafianet/NatTypeDetectionClient.h - include/mafianet/NatTypeDetectionCommon.h - include/mafianet/NatTypeDetectionServer.h - include/mafianet/NetworkIDManager.h - include/mafianet/NetworkIDObject.h - include/mafianet/osx_adapter.h - include/mafianet/PacketConsoleLogger.h - include/mafianet/PacketFileLogger.h - include/mafianet/PacketizedTCP.h - include/mafianet/PacketLogger.h - include/mafianet/PacketOutputWindowLogger.h - include/mafianet/PacketPool.h - include/mafianet/PacketPriority.h - include/mafianet/PeerHandle.h - include/mafianet/peer.h - include/mafianet/peerinterface.h - include/mafianet/PluginInterface2.h - include/mafianet/PointGridSectorizer.h - include/mafianet/PS3Includes.h - include/mafianet/PS4Includes.h - include/mafianet/Rackspace.h - include/mafianet/Rand.h - include/mafianet/RandSync.h - include/mafianet/ReadyEvent.h - include/mafianet/RefCountedObj.h - include/mafianet/RelayPlugin.h - include/mafianet/ReliabilityLayer.h - include/mafianet/ReplicaEnums.h - include/mafianet/ReplicaManager3.h - include/mafianet/Router2.h - include/mafianet/RPC4Plugin.h - include/mafianet/SecureHandshake.h - include/mafianet/SendToThread.h - include/mafianet/SignaledEvent.h - include/mafianet/SimpleMutex.h - include/mafianet/SimpleTCPServer.h - include/mafianet/SingleProducerConsumer.h - include/mafianet/sleep.h - include/mafianet/mafianet.h - include/mafianet/smartptr.h - include/mafianet/socket.h - include/mafianet/socket2.h - include/mafianet/SocketDefines.h - include/mafianet/SocketIncludes.h - include/mafianet/SocketLayer.h - include/mafianet/statistics.h - include/mafianet/StatisticsHistory.h - include/mafianet/string.h - include/mafianet/StringCompressor.h - include/mafianet/StringTable.h - include/mafianet/SuperFastHash.h - include/mafianet/TableSerializer.h - include/mafianet/TCPInterface.h - include/mafianet/TeamBalancer.h - include/mafianet/TeamManager.h - include/mafianet/TelnetTransport.h - include/mafianet/thread.h - include/mafianet/ThreadPool.h - include/mafianet/ThreadsafePacketLogger.h - include/mafianet/time.h - include/mafianet/transport2.h - include/mafianet/TransportInterface.h - include/mafianet/TwoWayAuthentication.h - include/mafianet/types.h - include/mafianet/UDPForwarder.h - include/mafianet/UDPProxyClient.h - include/mafianet/UDPProxyCommon.h - include/mafianet/UDPProxyCoordinator.h - include/mafianet/UDPProxyServer.h - include/mafianet/VariableDeltaSerializer.h - include/mafianet/VariableListDeltaTracker.h - include/mafianet/VariadicSQLParser.h - include/mafianet/version.h - include/mafianet/VirtualWorld.h - include/mafianet/VirtualWorldReplica3.h - include/mafianet/VitaIncludes.h - include/mafianet/WindowsIncludes.h - include/mafianet/WSAStartupSingleton.h - include/mafianet/wstring.h - include/mafianet/XBox360Includes.h -) - -set(MAFIANET_CRYPTO_HEADERS - include/mafianet/crypto/cryptomanager.h - include/mafianet/crypto/factory.h - include/mafianet/crypto/fileencrypter.h - include/mafianet/crypto/ifileencrypter.h - include/mafianet/crypto/securestring.h -) - -# Combine all sources -set(MAFIANET_ALL_SOURCES - ${MAFIANET_SOURCES} - ${MAFIANET_CRYPTO_SOURCES} -) - -set(MAFIANET_ALL_HEADERS - ${MAFIANET_HEADERS} - ${MAFIANET_CRYPTO_HEADERS} -) - -# Common target setup function -function(mafianet_configure_target target_name) - target_include_directories(${target_name} - PUBLIC - $ - $ - PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/src - ) - - target_link_libraries(${target_name} - PUBLIC - OpenSSL::SSL - OpenSSL::Crypto - PRIVATE - Threads::Threads - $<$:ws2_32> - ) - - target_compile_definitions(${target_name} - PRIVATE - $<$:_DEBUG> - $<$:NDEBUG> - ) - - set_target_properties(${target_name} PROPERTIES - VERSION ${PROJECT_VERSION} - SOVERSION ${PROJECT_VERSION_MAJOR} - FOLDER "Libraries" - ) - - # Source groups for IDE organization - source_group("Source Files" FILES ${MAFIANET_SOURCES}) - source_group("Source Files\\crypto" FILES ${MAFIANET_CRYPTO_SOURCES}) - source_group("Header Files" FILES ${MAFIANET_HEADERS}) - source_group("Header Files\\crypto" FILES ${MAFIANET_CRYPTO_HEADERS}) -endfunction() - -# Static library -if(MAFIANET_BUILD_STATIC) - add_library(MafiaNetStatic STATIC - ${MAFIANET_ALL_SOURCES} - ${MAFIANET_ALL_HEADERS} - ) - add_library(MafiaNet::MafiaNetStatic ALIAS MafiaNetStatic) - - mafianet_configure_target(MafiaNetStatic) - - target_compile_definitions(MafiaNetStatic - PUBLIC - $<$:_MAFIANET_LIB> - ) -endif() - -# Shared library -if(MAFIANET_BUILD_SHARED) - add_library(MafiaNet SHARED - ${MAFIANET_ALL_SOURCES} - ${MAFIANET_ALL_HEADERS} - ) - add_library(MafiaNet::MafiaNet ALIAS MafiaNet) - - mafianet_configure_target(MafiaNet) - - target_compile_definitions(MafiaNet - PRIVATE - MAFIANET_DLL_EXPORT - PUBLIC - $<$:_MAFIANET_DLL> - ) - - if(NOT WIN32) - set_target_properties(MafiaNet PROPERTIES - OUTPUT_NAME "mafianet" - ) - endif() -endif() - -# Installation -include(GNUInstallDirs) -include(CMakePackageConfigHelpers) - -# Determine which targets to install -set(MAFIANET_INSTALL_TARGETS) -if(MAFIANET_BUILD_STATIC) - list(APPEND MAFIANET_INSTALL_TARGETS MafiaNetStatic) -endif() -if(MAFIANET_BUILD_SHARED) - list(APPEND MAFIANET_INSTALL_TARGETS MafiaNet) -endif() - -# Install targets -install(TARGETS ${MAFIANET_INSTALL_TARGETS} - EXPORT MafiaNetTargets - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} - INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} -) - -# Install headers -install(DIRECTORY include/ - DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} -) - -# Generate and install config -configure_package_config_file( - ${PROJECT_SOURCE_DIR}/cmake/MafiaNetConfig.cmake.in - ${CMAKE_CURRENT_BINARY_DIR}/MafiaNetConfig.cmake - INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/MafiaNet -) - -write_basic_package_version_file( - ${CMAKE_CURRENT_BINARY_DIR}/MafiaNetConfigVersion.cmake - VERSION ${PROJECT_VERSION} - COMPATIBILITY SameMajorVersion -) - -install(FILES - ${CMAKE_CURRENT_BINARY_DIR}/MafiaNetConfig.cmake - ${CMAKE_CURRENT_BINARY_DIR}/MafiaNetConfigVersion.cmake - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/MafiaNet -) - -install(EXPORT MafiaNetTargets - FILE MafiaNetTargets.cmake - NAMESPACE MafiaNet:: - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/MafiaNet -) diff --git a/vendors/mafianet/Source/include/mafianet/AutopatcherPatchContext.h b/vendors/mafianet/Source/include/mafianet/AutopatcherPatchContext.h deleted file mode 100644 index 7eb85b00e..000000000 --- a/vendors/mafianet/Source/include/mafianet/AutopatcherPatchContext.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -#ifndef __AUTOPATCHER_PATCH_CONTEXT_H -#define __AUTOPATCHER_PATCH_CONTEXT_H - -enum PatchContext -{ - PC_HASH_1_WITH_PATCH, - PC_HASH_2_WITH_PATCH, - PC_WRITE_FILE, - PC_ERROR_FILE_WRITE_FAILURE, - PC_ERROR_PATCH_TARGET_MISSING, - PC_ERROR_PATCH_APPLICATION_FAILURE, - PC_ERROR_PATCH_RESULT_CHECKSUM_FAILURE, - PC_NOTICE_WILL_COPY_ON_RESTART, - PC_NOTICE_FILE_DOWNLOADED, - PC_NOTICE_FILE_DOWNLOADED_PATCH, -}; - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/AutopatcherRepositoryInterface.h b/vendors/mafianet/Source/include/mafianet/AutopatcherRepositoryInterface.h deleted file mode 100644 index 4b99cfd99..000000000 --- a/vendors/mafianet/Source/include/mafianet/AutopatcherRepositoryInterface.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// -/// \file AutopatcherRepositoryInterface.h -/// \brief An interface used by AutopatcherServer to get the data necessary to run an autopatcher. -/// - - -#ifndef __AUTOPATCHER_REPOSITORY_INTERFACE_H -#define __AUTOPATCHER_REPOSITORY_INTERFACE_H - -#include "IncrementalReadInterface.h" -#include "SimpleMutex.h" - -namespace MafiaNet -{ -/// Forward declarations -class FileList; -class BitStream; - -/// An interface used by AutopatcherServer to get the data necessary to run an autopatcher. This is up to you to implement for custom repository solutions. -class AutopatcherRepositoryInterface : public IncrementalReadInterface -{ -public: - /// Get list of files added and deleted since a certain date. This is used by AutopatcherServer and not usually explicitly called. - /// \param[in] applicationName A null terminated string identifying the application - /// \param[out] addedFiles A list of the current versions of filenames with hashes as their data that were created after \a sinceData - /// \param[out] deletedFiles A list of the current versions of filenames that were deleted after \a sinceData - /// \param[in] An input date, in whatever format your repository uses - /// \param[out] currentDate The current server date, in whatever format your repository uses - /// \return True on success, false on failure. - virtual bool GetChangelistSinceDate(const char *applicationName, FileList *addedOrModifiedFilesWithHashData, FileList *deletedFiles, double sinceDate)=0; - - /// Get patches (or files) for every file in input, assuming that input has a hash for each of those files. - /// \param[in] applicationName A null terminated string identifying the application - /// \param[in] input A list of files with SHA1_LENGTH byte hashes to get from the database. - /// \param[out] patchList You should return list of files with either the filedata or the patch. This is a subset of \a input. The context data for each file will be either PC_WRITE_FILE (to just write the file) or PC_HASH_WITH_PATCH (to patch). If PC_HASH_WITH_PATCH, then the file contains a SHA1_LENGTH byte patch followed by the hash. The datalength is patchlength + SHA1_LENGTH - /// \param[out] currentDate The current server date, in whatever format your repository uses - /// \return 1 on success, 0 on database failure, -1 on tried to download original unmodified file - virtual int GetPatches(const char *applicationName, FileList *input, bool allowDownloadOfOriginalUnmodifiedFiles, FileList *patchList)=0; - - /// For the most recent update, return files that were patched, added, or deleted. For files that were patched, return both the patch in \a patchedFiles and the current version in \a updatedFiles - /// \param[in,out] applicationName Name of the application to get patches for. If empty, uses the most recently updated application, and the string will be updated to reflect this name. - /// \param[out] patchedFiles A list of patched files with op PC_HASH_2_WITH_PATCH. It has 2 hashes, the priorHash and the currentHash. The currentHash is checked on the client after patching for patch success. The priorHash is checked in AutopatcherServer::OnGetPatch() to see if the client is able to hash with the version they currently have - /// \param[out] patchedFiles A list of new files. It contains the actual data in addition to the filename - /// \param[out] addedOrModifiedFileHashes A list of file hashes that were either modified or new. This is returned to the client when replying to ID_AUTOPATCHER_CREATION_LIST, which tells the client what files have changed on the server since a certain date - /// \param[out] deletedFiles A list of the current versions of filenames that were deleted in the most recent patch - /// \param[out] whenPatched time in seconds since epoch when patched. Use time() function to get this in C - /// \return true on success, false on failure - virtual bool GetMostRecentChangelistWithPatches( - MafiaNet::RakString &applicationName, - FileList *patchedFiles, - FileList *updatedFiles, - FileList *addedOrModifiedFileHashes, - FileList *deletedFiles, - double *priorRowPatchTime, - double *mostRecentRowPatchTime)=0; - - /// \return Whatever this function returns is sent from the AutopatcherServer to the AutopatcherClient when one of the above functions returns false. - virtual const char *GetLastError(void) const=0; - - /// \return Passed to FileListTransfer::Send() as the _chunkSize parameter. - virtual const int GetIncrementalReadChunkSize(void) const=0; -}; - -} // namespace MafiaNet - -#endif - diff --git a/vendors/mafianet/Source/include/mafianet/Base64Encoder.h b/vendors/mafianet/Source/include/mafianet/Base64Encoder.h deleted file mode 100644 index 33d7f4a95..000000000 --- a/vendors/mafianet/Source/include/mafianet/Base64Encoder.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -#ifndef __BASE_64_ENCODER_H -#define __BASE_64_ENCODER_H - -#include "Export.h" - -extern "C" { -/// \brief Returns how many bytes were written. -// outputData should be at least the size of inputData * 2 + 6 -int Base64Encoding(const unsigned char *inputData, int dataLength, char *outputData); -} - -extern "C" { -const char *Base64Map(void); -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/BitStream.h b/vendors/mafianet/Source/include/mafianet/BitStream.h deleted file mode 100644 index 3b82db6b8..000000000 --- a/vendors/mafianet/Source/include/mafianet/BitStream.h +++ /dev/null @@ -1,1936 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2019, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file BitStream.h -/// \brief This class allows you to write and read native types as a string of bits. -/// \details BitStream is used extensively throughout RakNet and is designed to be used by users as well. -/// - -#ifndef __BITSTREAM_H -#define __BITSTREAM_H - -#include "memoryoverride.h" -#include "defines.h" -#include "Export.h" -#include "types.h" -#include "string.h" -#include "wstring.h" -#include "assert.h" -#include -#include -#include -#include - -#ifdef _MSC_VER -#pragma warning( push ) -#endif - -// MSWin uses _copysign, others use copysign... -#ifndef _WIN32 -#define _copysign copysign -#endif - -namespace MafiaNet -{ - /// This class allows you to write and read native types as a string of bits. BitStream is used extensively throughout RakNet and is designed to be used by users as well. - /// \sa BitStreamSample.txt - class RAK_DLL_EXPORT BitStream - { - - public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(BitStream) - - /// Default Constructor - BitStream(); - - /// \brief Create the bitstream, with some number of bytes to immediately allocate. - /// \details There is no benefit to calling this, unless you know exactly how many bytes you need and it is greater than BITSTREAM_STACK_ALLOCATION_SIZE. - /// In that case all it does is save you one or more realloc calls. - /// \param[in] initialBytesToAllocate the number of bytes to pre-allocate. - BitStream( const unsigned int initialBytesToAllocate ); - - /// \brief Initialize the BitStream, immediately setting the data it contains to a predefined pointer. - /// \details Set \a _copyData to true if you want to make an internal copy of the data you are passing. Set it to false to just save a pointer to the data. - /// You shouldn't call Write functions with \a _copyData as false, as this will write to unallocated memory - /// 99% of the time you will use this function to cast Packet::data to a bitstream for reading, in which case you should write something as follows: - /// \code - /// MafiaNet::BitStream bs(packet->data, packet->length, false); - /// \endcode - /// \param[in] _data An array of bytes. - /// \param[in] lengthInBytes Size of the \a _data. - /// \param[in] _copyData true or false to make a copy of \a _data or not. - BitStream( unsigned char* _data, const unsigned int lengthInBytes, bool _copyData ); - - // Destructor - ~BitStream(); - - /// Resets the bitstream for reuse. - void Reset( void ); - - /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. - /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. - /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data - /// \param[in] inOutTemplateVar The value to write - /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. - template - bool Serialize(bool writeToBitstream, templateType &inOutTemplateVar); - - /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. - /// \details If the current value is different from the last value - /// the current value will be written. Otherwise, a single bit will be written - /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data - /// \param[in] inOutCurrentValue The current value to write - /// \param[in] lastValue The last value to compare against. Only used if \a writeToBitstream is true. - /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. - template - bool SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue); - - /// \brief Bidirectional version of SerializeDelta when you don't know what the last value is, or there is no last value. - /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data - /// \param[in] inOutCurrentValue The current value to write - /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. - template - bool SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue); - - /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. - /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. - /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte - /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. - /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type - /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data - /// \param[in] inOutTemplateVar The value to write - /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. - template - bool SerializeCompressed(bool writeToBitstream, templateType &inOutTemplateVar); - - /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. - /// \details If the current value is different from the last value - /// the current value will be written. Otherwise, a single bit will be written - /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. - /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type - /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte - /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data - /// \param[in] inOutCurrentValue The current value to write - /// \param[in] lastValue The last value to compare against. Only used if \a writeToBitstream is true. - /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. - template - bool SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue); - - /// \brief Save as SerializeCompressedDelta(templateType ¤tValue, const templateType &lastValue) when we have an unknown second parameter - /// \return true on data read. False on insufficient data in bitstream - template - bool SerializeCompressedDelta(bool writeToBitstream, templateType &inOutTemplateVar); - - /// \brief Bidirectional serialize/deserialize an array or casted stream or raw data. This does NOT do endian swapping. - /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data - /// \param[in] inOutByteArray a byte buffer - /// \param[in] numberOfBytes the size of \a input in bytes - /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. - bool Serialize(bool writeToBitstream, char* inOutByteArray, const unsigned int numberOfBytes ); - - /// \brief Serialize a float into 2 bytes, spanning the range between \a floatMin and \a floatMax - /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data - /// \param[in] inOutFloat The float to write - /// \param[in] floatMin Predetermined minimum value of f - /// \param[in] floatMax Predetermined maximum value of f - bool SerializeFloat16(bool writeToBitstream, float &inOutFloat, float floatMin, float floatMax); - - /// Serialize one type casted to another (smaller) type, to save bandwidth - /// serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t - /// Example: int num=53; SerializeCasted(true, num); would use 1 byte to write what would otherwise be an integer (4 or 8 bytes) - /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data - /// \param[in] value The value to serialize - template - bool SerializeCasted( bool writeToBitstream, sourceType &value ); - - /// Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range - /// Then serialize only those bits - /// \note A static is used so that the required number of bits for (maximum-minimum) is only calculated once. This does require that \a minimum and \maximum are fixed values for a given line of code for the life of the program - /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data - /// \param[in] value Integer value to write, which should be between \a minimum and \a maximum - /// \param[in] minimum Minimum value of \a value - /// \param[in] maximum Maximum value of \a value - /// \param[in] allowOutsideRange If true, all sends will take an extra bit, however value can deviate from outside \a minimum and \a maximum. If false, will assert if the value deviates - template - bool SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange=false ); - /// \param[in] requiredBits Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum - template - bool SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange=false ); - - /// \brief Bidirectional serialize/deserialize a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. - /// \details Will further compress y or z axis aligned vectors. - /// Accurate to 1/32767.5. - /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data - /// \param[in] x x - /// \param[in] y y - /// \param[in] z z - /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. - template // templateType for this function must be a float or double - bool SerializeNormVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ); - - /// \brief Bidirectional serialize/deserialize a vector, using 10 bytes instead of 12. - /// \details Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important. - /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data - /// \param[in] x x - /// \param[in] y y - /// \param[in] z z - /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. - template // templateType for this function must be a float or double - bool SerializeVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ); - - /// \brief Bidirectional serialize/deserialize a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy. - /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data - /// \param[in] w w - /// \param[in] x x - /// \param[in] y y - /// \param[in] z z - /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. - template // templateType for this function must be a float or double - bool SerializeNormQuat(bool writeToBitstream, templateType &w, templateType &x, templateType &y, templateType &z); - - /// \brief Bidirectional serialize/deserialize an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each. - /// \details Use 6 bytes instead of 36 - /// Lossy, although the result is renormalized - /// \return true on success, false on failure. - template // templateType for this function must be a float or double - bool SerializeOrthMatrix( - bool writeToBitstream, - templateType &m00, templateType &m01, templateType &m02, - templateType &m10, templateType &m11, templateType &m12, - templateType &m20, templateType &m21, templateType &m22 ); - - /// \brief Bidirectional serialize/deserialize numberToSerialize bits to/from the input. - /// \details Right aligned data means in the case of a partial byte, the bits are aligned - /// from the right (bit 0) rather than the left (as in the normal - /// internal representation) You would set this to true when - /// writing user data, and false when copying bitstream data, such - /// as writing one bitstream to another - /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data - /// \param[in] inOutByteArray The data - /// \param[in] numberOfBitsToSerialize The number of bits to write - /// \param[in] rightAlignedBits if true data will be right aligned - /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. - bool SerializeBits(bool writeToBitstream, unsigned char* inOutByteArray, const BitSize_t numberOfBitsToSerialize, const bool rightAlignedBits = true ); - - /// \brief Write any integral type to a bitstream. - /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. - /// \param[in] inTemplateVar The value to write - template - void Write(const templateType &inTemplateVar); - - /// \brief Write the dereferenced pointer to any integral type to a bitstream. - /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. - /// \param[in] inTemplateVar The value to write - template - void WritePtr(templateType *inTemplateVar); - - /// \brief Write any integral type to a bitstream. - /// \details If the current value is different from the last value - /// the current value will be written. Otherwise, a single bit will be written - /// \param[in] currentValue The current value to write - /// \param[in] lastValue The last value to compare against - template - void WriteDelta(const templateType ¤tValue, const templateType &lastValue); - - /// \brief WriteDelta when you don't know what the last value is, or there is no last value. - /// \param[in] currentValue The current value to write - template - void WriteDelta(const templateType ¤tValue); - - /// \brief Write any integral type to a bitstream. - /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. - /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte - /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. - /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type - /// \param[in] inTemplateVar The value to write - template - void WriteCompressed(const templateType &inTemplateVar); - - /// \brief Write any integral type to a bitstream. - /// \details If the current value is different from the last value - /// the current value will be written. Otherwise, a single bit will be written - /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. - /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type - /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte - /// \param[in] currentValue The current value to write - /// \param[in] lastValue The last value to compare against - template - void WriteCompressedDelta(const templateType ¤tValue, const templateType &lastValue); - - /// \brief Save as WriteCompressedDelta(const templateType ¤tValue, const templateType &lastValue) when we have an unknown second parameter - template - void WriteCompressedDelta(const templateType ¤tValue); - - /// \brief Read any integral type from a bitstream. - /// \details Define __BITSTREAM_NATIVE_END if you need endian swapping. - /// \param[in] outTemplateVar The value to read - /// \return true on success, false on failure. - template - bool Read(templateType &outTemplateVar); - - /// \brief Read a wchar from a bitstream. - /// \details Define __BITSTREAM_NATIVE_END if you need endian swapping. - /// \param[in] varString The value to read - /// \param[in] varStringLength The length of the given varString array (in wchar_t) - /// \return true on success, false on failure. - bool Read(wchar_t *&varString); - bool Read(wchar_t *&varString, size_t varStringLength); - - /// \brief Read any integral type from a bitstream. - /// \details If the written value differed from the value compared against in the write function, - /// var will be updated. Otherwise it will retain the current value. - /// ReadDelta is only valid from a previous call to WriteDelta - /// \param[in] outTemplateVar The value to read - /// \return true on success, false on failure. - template - bool ReadDelta(templateType &outTemplateVar); - - /// \brief Read any integral type from a bitstream. - /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. - /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. - /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type - /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte - /// \param[in] outTemplateVar The value to read - /// \return true on success, false on failure. - template - bool ReadCompressed(templateType &outTemplateVar); - - /// \brief Read a wchar from a bitstream. - /// \details Define __BITSTREAM_NATIVE_END if you need endian swapping. - /// This is lossless, but only has benefit if you use less than half the bits of the type - /// If you are not using __BITSTREAM_NATIVE_END the opposite is true - /// \param[in] varString The value to read - /// \param[in] varStringLength The length of the given varString array (in wchar_t) - /// \return true on success, false on failure. - bool ReadCompressed(wchar_t *&varString); - bool ReadCompressed(wchar_t *&varString, size_t varStringLength); - - /// \brief Read any integral type from a bitstream. - /// \details If the written value differed from the value compared against in the write function, - /// var will be updated. Otherwise it will retain the current value. - /// the current value will be updated. - /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. - /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type - /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte - /// ReadCompressedDelta is only valid from a previous call to WriteDelta - /// \param[in] outTemplateVar The value to read - /// \return true on success, false on failure. - template - bool ReadCompressedDelta(templateType &outTemplateVar); - - /// \brief Read one bitstream to another. - /// \param[in] numberOfBits bits to read - /// \param bitStream the bitstream to read into from - /// \return true on success, false on failure. - bool Read( BitStream *bitStream, BitSize_t numberOfBits ); - bool Read( BitStream *bitStream ); - bool Read( BitStream &bitStream, BitSize_t numberOfBits ); - bool Read( BitStream &bitStream ); - - /// \brief Write an array or casted stream or raw data. This does NOT do endian swapping. - /// \param[in] inputByteArray a byte buffer - /// \param[in] numberOfBytes the size of \a input in bytes - void Write( const char* inputByteArray, const unsigned int numberOfBytes ); - - /// \brief Write one bitstream to another. - /// \param[in] numberOfBits bits to write - /// \param bitStream the bitstream to copy from - void Write( BitStream *bitStream, BitSize_t numberOfBits ); - void Write( BitStream *bitStream ); - void Write( BitStream &bitStream, BitSize_t numberOfBits ); - void Write( BitStream &bitStream );\ - - /// \brief Write a float into 2 bytes, spanning the range between \a floatMin and \a floatMax - /// \param[in] x The float to write - /// \param[in] floatMin Predetermined minimum value of f - /// \param[in] floatMax Predetermined maximum value of f - void WriteFloat16( float x, float floatMin, float floatMax ); - - /// Write one type serialized as another (smaller) type, to save bandwidth - /// serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t - /// Example: int num=53; WriteCasted(num); would use 1 byte to write what would otherwise be an integer (4 or 8 bytes) - /// \param[in] value The value to write - template - void WriteCasted( const sourceType &value ); - - /// Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range - /// Then write only those bits - /// \note A static is used so that the required number of bits for (maximum-minimum) is only calculated once. This does require that \a minimum and \maximum are fixed values for a given line of code for the life of the program - /// \param[in] value Integer value to write, which should be between \a minimum and \a maximum - /// \param[in] minimum Minimum value of \a value - /// \param[in] maximum Maximum value of \a value - /// \param[in] allowOutsideRange If true, all sends will take an extra bit, however value can deviate from outside \a minimum and \a maximum. If false, will assert if the value deviates. This should match the corresponding value passed to Read(). - template - void WriteBitsFromIntegerRange( const templateType value, const templateType minimum, const templateType maximum, bool allowOutsideRange=false ); - /// \param[in] requiredBits Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum - template - void WriteBitsFromIntegerRange( const templateType value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange=false ); - - /// \brief Write a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. - /// \details Will further compress y or z axis aligned vectors. - /// Accurate to 1/32767.5. - /// \param[in] x x - /// \param[in] y y - /// \param[in] z z - template // templateType for this function must be a float or double - void WriteNormVector( templateType x, templateType y, templateType z ); - - /// \brief Write a vector, using 10 bytes instead of 12. - /// \details Loses accuracy to about 3/10ths and only saves 2 bytes, - /// so only use if accuracy is not important. - /// \param[in] x x - /// \param[in] y y - /// \param[in] z z - template // templateType for this function must be a float or double - void WriteVector( templateType x, templateType y, templateType z ); - - /// \brief Write a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy. - /// \param[in] w w - /// \param[in] x x - /// \param[in] y y - /// \param[in] z z - template // templateType for this function must be a float or double - void WriteNormQuat( templateType w, templateType x, templateType y, templateType z); - - /// \brief Write an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each. - /// \details Use 6 bytes instead of 36 - /// Lossy, although the result is renormalized - template // templateType for this function must be a float or double - void WriteOrthMatrix( - templateType m00, templateType m01, templateType m02, - templateType m10, templateType m11, templateType m12, - templateType m20, templateType m21, templateType m22 ); - - /// \brief Read an array or casted stream of byte. - /// \details The array is raw data. There is no automatic endian conversion with this function - /// \param[in] output The result byte array. It should be larger than @em numberOfBytes. - /// \param[in] numberOfBytes The number of byte to read - /// \return true on success false if there is some missing bytes. - bool Read( char* output, const unsigned int numberOfBytes ); - - /// \brief Read a float into 2 bytes, spanning the range between \a floatMin and \a floatMax - /// \param[in] outFloat The float to read - /// \param[in] floatMin Predetermined minimum value of f - /// \param[in] floatMax Predetermined maximum value of f - bool ReadFloat16( float &outFloat, float floatMin, float floatMax ); - - /// Read one type serialized to another (smaller) type, to save bandwidth - /// serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t - /// Example: int num; ReadCasted(num); would read 1 bytefrom the stream, and put the value in an integer - /// \param[in] value The value to write - template - bool ReadCasted( sourceType &value ); - - /// Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range - /// Then read only those bits - /// \note A static is used so that the required number of bits for (maximum-minimum) is only calculated once. This does require that \a minimum and \maximum are fixed values for a given line of code for the life of the program - /// \param[in] value Integer value to read, which should be between \a minimum and \a maximum - /// \param[in] minimum Minimum value of \a value - /// \param[in] maximum Maximum value of \a value - /// \param[in] allowOutsideRange If true, all sends will take an extra bit, however value can deviate from outside \a minimum and \a maximum. If false, will assert if the value deviates. This should match the corresponding value passed to Write(). - template - bool ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange=false ); - /// \param[in] requiredBits Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum - template - bool ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange=false ); - - /// \brief Read a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. - /// \details Will further compress y or z axis aligned vectors. - /// Accurate to 1/32767.5. - /// \param[in] x x - /// \param[in] y y - /// \param[in] z z - /// \return true on success, false on failure. - template // templateType for this function must be a float or double - bool ReadNormVector( templateType &x, templateType &y, templateType &z ); - - /// \brief Read 3 floats or doubles, using 10 bytes, where those float or doubles comprise a vector. - /// \details Loses accuracy to about 3/10ths and only saves 2 bytes, - /// so only use if accuracy is not important. - /// \param[in] x x - /// \param[in] y y - /// \param[in] z z - /// \return true on success, false on failure. - template // templateType for this function must be a float or double - bool ReadVector( templateType &x, templateType &y, templateType &z ); - - /// \brief Read a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. - /// \param[in] w w - /// \param[in] x x - /// \param[in] y y - /// \param[in] z z - /// \return true on success, false on failure. - template // templateType for this function must be a float or double - bool ReadNormQuat( templateType &w, templateType &x, templateType &y, templateType &z); - - /// \brief Read an orthogonal matrix from a quaternion, reading 3 components of the quaternion in 2 bytes each and extrapolatig the 4th. - /// \details Use 6 bytes instead of 36 - /// Lossy, although the result is renormalized - /// \return true on success, false on failure. - template // templateType for this function must be a float or double - bool ReadOrthMatrix( - templateType &m00, templateType &m01, templateType &m02, - templateType &m10, templateType &m11, templateType &m12, - templateType &m20, templateType &m21, templateType &m22 ); - - /// \brief Sets the read pointer back to the beginning of your data. - void ResetReadPointer( void ); - - /// \brief Sets the write pointer back to the beginning of your data. - void ResetWritePointer( void ); - - /// \brief This is good to call when you are done with the stream to make - /// sure you didn't leave any data left over void - void AssertStreamEmpty( void ); - - /// \brief RAKNET_DEBUG_PRINTF the bits in the stream. Great for debugging. - void PrintBits( char *out ) const; - void PrintBits( char *out, size_t outLength ) const; - void PrintBits( void ) const; - void PrintHex( char *out) const; - void PrintHex( char *out, size_t outLength ) const; - void PrintHex( void ) const; - - /// \brief Ignore data we don't intend to read - /// \param[in] numberOfBits The number of bits to ignore - void IgnoreBits( const BitSize_t numberOfBits ); - - /// \brief Ignore data we don't intend to read - /// \param[in] numberOfBits The number of bytes to ignore - void IgnoreBytes( const unsigned int numberOfBytes ); - - /// \brief Move the write pointer to a position on the array. - /// \param[in] offset the offset from the start of the array. - /// \attention - /// \details Dangerous if you don't know what you are doing! - /// For efficiency reasons you can only write mid-stream if your data is byte aligned. - void SetWriteOffset( const BitSize_t offset ); - - /// \brief Returns the length in bits of the stream - inline BitSize_t GetNumberOfBitsUsed( void ) const {return GetWriteOffset();} - inline BitSize_t GetWriteOffset( void ) const {return numberOfBitsUsed;} - - /// \brief Returns the length in bytes of the stream - inline BitSize_t GetNumberOfBytesUsed( void ) const {return BITS_TO_BYTES( numberOfBitsUsed );} - - /// \brief Returns the number of bits into the stream that we have read - inline BitSize_t GetReadOffset( void ) const {return readOffset;} - - /// \brief Sets the read bit index - void SetReadOffset(const BitSize_t newReadOffset); - - /// \brief Returns the number of bits left in the stream that haven't been read - inline BitSize_t GetNumberOfUnreadBits( void ) const { return readOffset > numberOfBitsUsed ? 0 : numberOfBitsUsed - readOffset; } - - /// \brief Makes a copy of the internal data for you \a _data will point to - /// the stream. Partial bytes are left aligned. - /// \param[out] _data The allocated copy of GetData() - /// \return The length in bits of the stream. - BitSize_t CopyData( unsigned char** _data ) const; - - /// \internal - /// Set the stream to some initial data. - void SetData( unsigned char *inByteArray ); - - /// Gets the data that BitStream is writing to / reading from. - /// Partial bytes are left aligned. - /// \return A pointer to the internal state - inline unsigned char* GetData( void ) const {return data;} - - /// \brief Write numberToWrite bits from the input source. - /// \details Right aligned data means in the case of a partial byte, the bits are aligned - /// from the right (bit 0) rather than the left (as in the normal - /// internal representation) You would set this to true when - /// writing user data, and false when copying bitstream data, such - /// as writing one bitstream to another. - /// \param[in] inByteArray The data - /// \param[in] numberOfBitsToWrite The number of bits to write - /// \param[in] rightAlignedBits if true data will be right aligned - void WriteBits( const unsigned char* inByteArray, BitSize_t numberOfBitsToWrite, const bool rightAlignedBits = true ); - - /// \brief Align the bitstream to the byte boundary and then write the - /// specified number of bits. - /// \details This is faster than WriteBits but - /// wastes the bits to do the alignment and requires you to call - /// ReadAlignedBits at the corresponding read position. - /// \param[in] inByteArray The data - /// \param[in] numberOfBytesToWrite The size of input. - void WriteAlignedBytes( const unsigned char *inByteArray, const unsigned int numberOfBytesToWrite ); - - // Endian swap bytes already in the bitstream - void EndianSwapBytes( int byteOffset, int length ); - - /// \brief Aligns the bitstream, writes inputLength, and writes input. Won't write beyond maxBytesToWrite - /// \param[in] inByteArray The data - /// \param[in] inputLength The size of input. - /// \param[in] maxBytesToWrite Max bytes to write - void WriteAlignedBytesSafe( const char *inByteArray, const unsigned int inputLength, const unsigned int maxBytesToWrite ); - - /// \brief Read bits, starting at the next aligned bits. - /// \details Note that the modulus 8 starting offset of the sequence must be the same as - /// was used with WriteBits. This will be a problem with packet - /// coalescence unless you byte align the coalesced packets. - /// \param[in] inOutByteArray The byte array larger than @em numberOfBytesToRead - /// \param[in] numberOfBytesToRead The number of byte to read from the internal state - /// \return true if there is enough byte. - bool ReadAlignedBytes( unsigned char *inOutByteArray, const unsigned int numberOfBytesToRead ); - - /// \brief Reads what was written by WriteAlignedBytesSafe. - /// \param[in] inOutByteArray The data - /// \param[in] maxBytesToRead Maximum number of bytes to read - /// \return true on success, false on failure. - bool ReadAlignedBytesSafe( char *inOutByteArray, int &inputLength, const int maxBytesToRead ); - bool ReadAlignedBytesSafe( char *inOutByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead ); - - /// \brief Same as ReadAlignedBytesSafe() but allocates the memory for you using new, rather than assuming it is safe to write to - /// \param[in] outByteArray outByteArray will be deleted if it is not a pointer to 0 - /// \return true on success, false on failure. - bool ReadAlignedBytesSafeAlloc( char **outByteArray, int &inputLength, const unsigned int maxBytesToRead ); - bool ReadAlignedBytesSafeAlloc( char **outByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead ); - - /// \brief Align the next write and/or read to a byte boundary. - /// \details This can be used to 'waste' bits to byte align for efficiency reasons It - /// can also be used to force coalesced bitstreams to start on byte - /// boundaries so so WriteAlignedBits and ReadAlignedBits both - /// calculate the same offset when aligning. - inline void AlignWriteToByteBoundary( void ) {numberOfBitsUsed += 8 - ( (( numberOfBitsUsed - 1 ) & 7) + 1 );} - - /// \brief Align the next write and/or read to a byte boundary. - /// \details This can be used to 'waste' bits to byte align for efficiency reasons It - /// can also be used to force coalesced bitstreams to start on byte - /// boundaries so so WriteAlignedBits and ReadAlignedBits both - /// calculate the same offset when aligning. - void AlignReadToByteBoundary(void); - - /// \brief Read \a numberOfBitsToRead bits to the output source. - /// \details alignBitsToRight should be set to true to convert internal - /// bitstream data to userdata. It should be false if you used - /// WriteBits with rightAlignedBits false - /// \param[in] inOutByteArray The resulting bits array - /// \param[in] numberOfBitsToRead The number of bits to read - /// \param[in] alignBitsToRight if true bits will be right aligned. - /// \return true if there is enough bits to read - bool ReadBits( unsigned char *inOutByteArray, BitSize_t numberOfBitsToRead, const bool alignBitsToRight = true ); - - /// \brief Write a 0 - void Write0( void ); - - /// \brief Write a 1 - void Write1( void ); - - /// \brief Reads 1 bit and returns true if that bit is 1 and false if it is 0. - bool ReadBit( void ); - - /// \brief If we used the constructor version with copy data off, this - /// *makes sure it is set to on and the data pointed to is copied. - void AssertCopyData( void ); - - /// \brief Use this if you pass a pointer copy to the constructor - /// *(_copyData==false) and want to overallocate to prevent - /// reallocation. - void SetNumberOfBitsAllocated( const BitSize_t lengthInBits ); - - /// \brief Reallocates (if necessary) in preparation of writing numberOfBitsToWrite - void AddBitsAndReallocate( const BitSize_t numberOfBitsToWrite ); - - /// \internal - /// \return How many bits have been allocated internally - BitSize_t GetNumberOfBitsAllocated(void) const; - - /// \brief Read strings, non reference. - bool Read(char *varString); - bool Read(unsigned char *varString); - - /// Write zeros until the bitstream is filled up to \a bytes - void PadWithZeroToByteLength( unsigned int bytes ); - - /// Get the number of leading zeros for a number - /// \param[in] x Number to test - static int NumberOfLeadingZeroes( uint8_t x ); - static int NumberOfLeadingZeroes( uint16_t x ); - static int NumberOfLeadingZeroes( uint32_t x ); - static int NumberOfLeadingZeroes( uint64_t x ); - static int NumberOfLeadingZeroes( int8_t x ); - static int NumberOfLeadingZeroes( int16_t x ); - static int NumberOfLeadingZeroes( int32_t x ); - static int NumberOfLeadingZeroes( int64_t x ); - - /// \internal Unrolled inner loop, for when performance is critical - void WriteAlignedVar8(const char *inByteArray); - /// \internal Unrolled inner loop, for when performance is critical - bool ReadAlignedVar8(char *inOutByteArray); - /// \internal Unrolled inner loop, for when performance is critical - void WriteAlignedVar16(const char *inByteArray); - /// \internal Unrolled inner loop, for when performance is critical - bool ReadAlignedVar16(char *inOutByteArray); - /// \internal Unrolled inner loop, for when performance is critical - void WriteAlignedVar32(const char *inByteArray); - /// \internal Unrolled inner loop, for when performance is critical - bool ReadAlignedVar32(char *inOutByteArray); - - inline void Write(const char * const inStringVar) - { - RakString::Serialize(inStringVar, this); - } - inline void Write(const wchar_t * const inStringVar) - { - RakWString::Serialize(inStringVar, this); - } - inline void Write(const unsigned char * const inTemplateVar) - { - Write((const char*)inTemplateVar); - } - inline void Write(char * const inTemplateVar) - { - Write((const char*)inTemplateVar); - } - inline void Write(unsigned char * const inTemplateVar) - { - Write((const char*)inTemplateVar); - } - inline void WriteCompressed(const char * const inStringVar) - { - RakString::SerializeCompressed(inStringVar,this,0,false); - } - inline void WriteCompressed(const wchar_t * const inStringVar) - { - RakWString::Serialize(inStringVar,this); - } - inline void WriteCompressed(const unsigned char * const inTemplateVar) - { - WriteCompressed((const char*) inTemplateVar); - } - inline void WriteCompressed(char * const inTemplateVar) - { - WriteCompressed((const char*) inTemplateVar); - } - inline void WriteCompressed(unsigned char * const inTemplateVar) - { - WriteCompressed((const char*) inTemplateVar); - } - - /// ---- Member function template specialization declarations ---- - inline static bool DoEndianSwap(void) { -#ifndef __BITSTREAM_NATIVE_END - return IsNetworkOrder()==false; -#else - return false; -#endif - } - inline static bool IsBigEndian(void) - { - return IsNetworkOrder(); - } - inline static bool IsNetworkOrder(void) {bool r = IsNetworkOrderInternal(); return r;} - // Not inline, won't compile on PC due to winsock include errors - static bool IsNetworkOrderInternal(void); - static void ReverseBytes(unsigned char *inByteArray, unsigned char *inOutByteArray, const unsigned int length); - static void ReverseBytesInPlace(unsigned char *inOutData,const unsigned int length); - - private: - - BitStream( const BitStream &invalid) { - (void) invalid; - RakAssert(0); - } - - BitStream& operator = ( const BitStream& invalid ) { - (void) invalid; - RakAssert(0); - static BitStream i; - return i; - } - - /// \brief Assume the input source points to a native type, compress and write it. - void WriteCompressed( const unsigned char* inByteArray, const unsigned int size, const bool unsignedData ); - - /// \brief Assume the input source points to a compressed native type. Decompress and read it. - bool ReadCompressed( unsigned char* inOutByteArray, const unsigned int size, const bool unsignedData ); - - - BitSize_t numberOfBitsUsed; - - BitSize_t numberOfBitsAllocated; - - BitSize_t readOffset; - - unsigned char *data; - - /// true if the internal buffer is copy of the data passed to the constructor - bool copyData; - - /// BitStreams that use less than BITSTREAM_STACK_ALLOCATION_SIZE use the stack, rather than the heap to store data. It switches over if BITSTREAM_STACK_ALLOCATION_SIZE is exceeded - unsigned char stackData[BITSTREAM_STACK_ALLOCATION_SIZE]; - }; - - template - inline bool BitStream::Serialize(bool writeToBitstream, templateType &inOutTemplateVar) - { - if (writeToBitstream) - Write(inOutTemplateVar); - else - return Read(inOutTemplateVar); - return true; - } - - template - inline bool BitStream::SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue) - { - if (writeToBitstream) - WriteDelta(inOutCurrentValue, lastValue); - else - return ReadDelta(inOutCurrentValue); - return true; - } - - template - inline bool BitStream::SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue) - { - if (writeToBitstream) - WriteDelta(inOutCurrentValue); - else - return ReadDelta(inOutCurrentValue); - return true; - } - - template - inline bool BitStream::SerializeCompressed(bool writeToBitstream, templateType &inOutTemplateVar) - { - if (writeToBitstream) - WriteCompressed(inOutTemplateVar); - else - return ReadCompressed(inOutTemplateVar); - return true; - } - - template - inline bool BitStream::SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue) - { - if (writeToBitstream) - WriteCompressedDelta(inOutCurrentValue,lastValue); - else - return ReadCompressedDelta(inOutCurrentValue); - return true; - } -//Stoppedhere - template - inline bool BitStream::SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue) - { - if (writeToBitstream) - WriteCompressedDelta(inOutCurrentValue); - else - return ReadCompressedDelta(inOutCurrentValue); - return true; - } - - inline bool BitStream::Serialize(bool writeToBitstream, char* inOutByteArray, const unsigned int numberOfBytes ) - { - if (writeToBitstream) - Write(inOutByteArray, numberOfBytes); - else - return Read(inOutByteArray, numberOfBytes); - return true; - } - - template - bool BitStream::SerializeCasted( bool writeToBitstream, sourceType &value ) - { - if (writeToBitstream) WriteCasted(value); - else return ReadCasted(value); - return true; - } - - template - bool BitStream::SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange ) - { - int requiredBits=BYTES_TO_BITS(sizeof(templateType))-NumberOfLeadingZeroes(templateType(maximum-minimum)); - return SerializeBitsFromIntegerRange(writeToBitstream,value,minimum,maximum,requiredBits,allowOutsideRange); - } - template - bool BitStream::SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange ) - { - if (writeToBitstream) WriteBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange); - else return ReadBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange); - return true; - } - - template - inline bool BitStream::SerializeNormVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ) - { - if (writeToBitstream) - WriteNormVector(x,y,z); - else - return ReadNormVector(x,y,z); - return true; - } - - template - inline bool BitStream::SerializeVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ) - { - if (writeToBitstream) - WriteVector(x,y,z); - else - return ReadVector(x,y,z); - return true; - } - - template - inline bool BitStream::SerializeNormQuat(bool writeToBitstream, templateType &w, templateType &x, templateType &y, templateType &z) - { - if (writeToBitstream) - WriteNormQuat(w,x,y,z); - else - return ReadNormQuat(w,x,y,z); - return true; - } - - template - inline bool BitStream::SerializeOrthMatrix( - bool writeToBitstream, - templateType &m00, templateType &m01, templateType &m02, - templateType &m10, templateType &m11, templateType &m12, - templateType &m20, templateType &m21, templateType &m22 ) - { - if (writeToBitstream) - WriteOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); - else - return ReadOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); - return true; - } - - inline bool BitStream::SerializeBits(bool writeToBitstream, unsigned char* inOutByteArray, const BitSize_t numberOfBitsToSerialize, const bool rightAlignedBits ) - { - if (writeToBitstream) - WriteBits(inOutByteArray,numberOfBitsToSerialize,rightAlignedBits); - else - return ReadBits(inOutByteArray,numberOfBitsToSerialize,rightAlignedBits); - return true; - } - - template - inline void BitStream::Write(const templateType &inTemplateVar) - { - static_assert(std::is_trivially_copyable::value, - "BitStream::Write cannot serialize this type: the generic template " - "copies the raw object representation, which is only valid for " - "trivially-copyable types. Serializing a type that owns memory " - "(e.g. std::string, std::vector, or any class with pointers) this " - "way corrupts memory on deserialize. Provide a BitStream::Write/Read " - "specialization for the type, or serialize its members explicitly."); -#ifdef _MSC_VER -#pragma warning(disable:4127) // conditional expression is constant -#endif - if (sizeof(inTemplateVar)==1) - WriteBits( ( unsigned char* ) & inTemplateVar, sizeof( templateType ) * 8, true ); - else - { -#ifndef __BITSTREAM_NATIVE_END - if (DoEndianSwap()) - { - unsigned char output[sizeof(templateType)]; - ReverseBytes((unsigned char*)&inTemplateVar, output, sizeof(templateType)); - WriteBits( ( unsigned char* ) output, sizeof(templateType) * 8, true ); - } - else -#endif - WriteBits( ( unsigned char* ) & inTemplateVar, sizeof(templateType) * 8, true ); - } - } - - template - inline void BitStream::WritePtr(templateType *inTemplateVar) - { - static_assert(std::is_trivially_copyable::value, - "BitStream::WritePtr cannot serialize this type: it copies the raw " - "object representation, which is only valid for trivially-copyable " - "types. Provide a BitStream::Write/Read specialization or serialize " - "the members explicitly."); -#ifdef _MSC_VER -#pragma warning(disable:4127) // conditional expression is constant -#endif - if (sizeof(templateType)==1) - WriteBits( ( unsigned char* ) inTemplateVar, sizeof( templateType ) * 8, true ); - else - { -#ifndef __BITSTREAM_NATIVE_END - if (DoEndianSwap()) - { - unsigned char output[sizeof(templateType)]; - ReverseBytes((unsigned char*) inTemplateVar, output, sizeof(templateType)); - WriteBits( ( unsigned char* ) output, sizeof(templateType) * 8, true ); - } - else -#endif - WriteBits( ( unsigned char* ) inTemplateVar, sizeof(templateType) * 8, true ); - } - } - - /// \brief Write a bool to a bitstream. - /// \param[in] inTemplateVar The value to write - template <> - inline void BitStream::Write(const bool &inTemplateVar) - { - if ( inTemplateVar ) - Write1(); - else - Write0(); - } - - - /// \brief Write a systemAddress to a bitstream. - /// \param[in] inTemplateVar The value to write - template <> - inline void BitStream::Write(const SystemAddress &inTemplateVar) - { - Write(inTemplateVar.GetIPVersion()); - if (inTemplateVar.GetIPVersion()==4) - { - // Hide the address so routers don't modify it - SystemAddress var2=inTemplateVar; - uint32_t binaryAddress=~inTemplateVar.address.addr4.sin_addr.s_addr; - // Don't endian swap the address or port - WriteBits((unsigned char*)&binaryAddress, sizeof(binaryAddress)*8, true); - unsigned short p = var2.GetPortNetworkOrder(); - WriteBits((unsigned char*)&p, sizeof(unsigned short)*8, true); - } - else - { -#if RAKNET_SUPPORT_IPV6==1 - // Don't endian swap - WriteBits((const unsigned char*) &inTemplateVar.address.addr6, sizeof(inTemplateVar.address.addr6)*8, true); -#endif - } - } - - template <> - inline void BitStream::Write(const uint24_t &inTemplateVar) - { - AlignWriteToByteBoundary(); - AddBitsAndReallocate(3*8); - - if (IsBigEndian()==false) - { - data[( numberOfBitsUsed >> 3 ) + 0] = ((unsigned char *)&inTemplateVar.val)[0]; - data[( numberOfBitsUsed >> 3 ) + 1] = ((unsigned char *)&inTemplateVar.val)[1]; - data[( numberOfBitsUsed >> 3 ) + 2] = ((unsigned char *)&inTemplateVar.val)[2]; - } - else - { - data[( numberOfBitsUsed >> 3 ) + 0] = ((unsigned char *)&inTemplateVar.val)[3]; - data[( numberOfBitsUsed >> 3 ) + 1] = ((unsigned char *)&inTemplateVar.val)[2]; - data[( numberOfBitsUsed >> 3 ) + 2] = ((unsigned char *)&inTemplateVar.val)[1]; - } - - numberOfBitsUsed+=3*8; - } - - template <> - inline void BitStream::Write(const RakNetGUID &inTemplateVar) - { - Write(inTemplateVar.g); - } - - /// \brief Write a string to a bitstream. - /// \param[in] var The value to write - template <> - inline void BitStream::Write(const RakString &inTemplateVar) - { - inTemplateVar.Serialize(this); - } - template <> - inline void BitStream::Write(const RakWString &inTemplateVar) - { - inTemplateVar.Serialize(this); - } - template <> - inline void BitStream::Write(const char * const &inStringVar) - { - RakString::Serialize(inStringVar, this); - } - template <> - inline void BitStream::Write(const wchar_t * const &inStringVar) - { - RakWString::Serialize(inStringVar, this); - } - template <> - inline void BitStream::Write(const unsigned char * const &inTemplateVar) - { - Write((const char*)inTemplateVar); - } - template <> - inline void BitStream::Write(char * const &inTemplateVar) - { - Write((const char*)inTemplateVar); - } - template <> - inline void BitStream::Write(unsigned char * const &inTemplateVar) - { - Write((const char*)inTemplateVar); - } - /// \brief Write a std::string to a bitstream by value. - /// \details Uses the same length-prefixed wire format as RakString (an - /// unsigned short length followed by the raw bytes), so std::string and - /// RakString are interchangeable on the wire. This specialization exists so - /// std::string does NOT fall through to the catch-all template, which would - /// raw-copy the object representation (pointer/size/capacity) and corrupt - /// memory on deserialize. - /// \param[in] inStringVar The value to write - template <> - inline void BitStream::Write(const std::string &inStringVar) - { - // The length is sent as an unsigned short, matching RakString's wire - // format; strings longer than that would be silently truncated. - RakAssert(inStringVar.length() <= 0xFFFF); - const unsigned short l = (unsigned short) inStringVar.length(); - Write(l); - WriteAlignedBytes((const unsigned char*) inStringVar.c_str(), l); - } - - /// \brief Write any integral type to a bitstream. - /// \details If the current value is different from the last value - /// the current value will be written. Otherwise, a single bit will be written - /// \param[in] currentValue The current value to write - /// \param[in] lastValue The last value to compare against - template - inline void BitStream::WriteDelta(const templateType ¤tValue, const templateType &lastValue) - { - if (currentValue==lastValue) - { - Write(false); - } - else - { - Write(true); - Write(currentValue); - } - } - - /// \brief Write a bool delta. Same thing as just calling Write - /// \param[in] currentValue The current value to write - /// \param[in] lastValue The last value to compare against - template <> - inline void BitStream::WriteDelta(const bool ¤tValue, const bool &lastValue) - { - (void) lastValue; - - Write(currentValue); - } - - /// \brief WriteDelta when you don't know what the last value is, or there is no last value. - /// \param[in] currentValue The current value to write - template - inline void BitStream::WriteDelta(const templateType ¤tValue) - { - Write(true); - Write(currentValue); - } - - /// \brief Write any integral type to a bitstream. - /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. - /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. - /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type - /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte - /// \param[in] inTemplateVar The value to write - template - inline void BitStream::WriteCompressed(const templateType &inTemplateVar) - { -#ifdef _MSC_VER -#pragma warning(disable:4127) // conditional expression is constant -#endif - if (sizeof(inTemplateVar)==1) - WriteCompressed( ( unsigned char* ) & inTemplateVar, sizeof( templateType ) * 8, true ); - else - { -#ifndef __BITSTREAM_NATIVE_END - if (DoEndianSwap()) - { - unsigned char output[sizeof(templateType)]; - ReverseBytes((unsigned char*)&inTemplateVar, output, sizeof(templateType)); - WriteCompressed( ( unsigned char* ) output, sizeof(templateType) * 8, true ); - } - else -#endif - WriteCompressed( ( unsigned char* ) & inTemplateVar, sizeof(templateType) * 8, true ); - } - } - - template <> - inline void BitStream::WriteCompressed(const SystemAddress &inTemplateVar) - { - Write(inTemplateVar); - } - - template <> - inline void BitStream::WriteCompressed(const RakNetGUID &inTemplateVar) - { - Write(inTemplateVar); - } - - template <> - inline void BitStream::WriteCompressed(const uint24_t &var) - { - Write(var); - } - - template <> - inline void BitStream::WriteCompressed(const bool &inTemplateVar) - { - Write(inTemplateVar); - } - - /// For values between -1 and 1 - template <> - inline void BitStream::WriteCompressed(const float &inTemplateVar) - { - RakAssert(inTemplateVar > -1.01f && inTemplateVar < 1.01f); - float varCopy=inTemplateVar; - if (varCopy < -1.0f) - varCopy=-1.0f; - if (varCopy > 1.0f) - varCopy=1.0f; - Write((unsigned short)((varCopy+1.0f)*32767.5f)); - } - - /// For values between -1 and 1 - template <> - inline void BitStream::WriteCompressed(const double &inTemplateVar) - { - RakAssert(inTemplateVar > -1.01 && inTemplateVar < 1.01); - double varCopy=inTemplateVar; - if (varCopy < -1.0f) - varCopy=-1.0f; - if (varCopy > 1.0f) - varCopy=1.0f; - Write((uint32_t)((varCopy+1.0)*2147483648.0)); - } - - /// Compress the string - template <> - inline void BitStream::WriteCompressed(const RakString &inTemplateVar) - { - inTemplateVar.SerializeCompressed(this,0,false); - } - template <> - inline void BitStream::WriteCompressed(const RakWString &inTemplateVar) - { - inTemplateVar.Serialize(this); - } - template <> - inline void BitStream::WriteCompressed(const char * const &inStringVar) - { - RakString::SerializeCompressed(inStringVar,this,0,false); - } - template <> - inline void BitStream::WriteCompressed(const wchar_t * const &inStringVar) - { - RakWString::Serialize(inStringVar,this); - } - template <> - inline void BitStream::WriteCompressed(const unsigned char * const &inTemplateVar) - { - WriteCompressed((const char*) inTemplateVar); - } - template <> - inline void BitStream::WriteCompressed(char * const &inTemplateVar) - { - WriteCompressed((const char*) inTemplateVar); - } - template <> - inline void BitStream::WriteCompressed(unsigned char * const &inTemplateVar) - { - WriteCompressed((const char*) inTemplateVar); - } - - - /// \brief Write any integral type to a bitstream. - /// \details If the current value is different from the last value - /// the current value will be written. Otherwise, a single bit will be written - /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. - /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type - /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte - /// \param[in] currentValue The current value to write - /// \param[in] lastValue The last value to compare against - template - inline void BitStream::WriteCompressedDelta(const templateType ¤tValue, const templateType &lastValue) - { - if (currentValue==lastValue) - { - Write(false); - } - else - { - Write(true); - WriteCompressed(currentValue); - } - } - - /// \brief Write a bool delta. Same thing as just calling Write - /// \param[in] currentValue The current value to write - /// \param[in] lastValue The last value to compare against - template <> - inline void BitStream::WriteCompressedDelta(const bool ¤tValue, const bool &lastValue) - { - (void) lastValue; - - Write(currentValue); - } - - /// \brief Save as WriteCompressedDelta(const templateType ¤tValue, const templateType &lastValue) - /// when we have an unknown second parameter - template - inline void BitStream::WriteCompressedDelta(const templateType ¤tValue) - { - Write(true); - WriteCompressed(currentValue); - } - - /// \brief Save as WriteCompressedDelta(bool currentValue, const templateType &lastValue) - /// when we have an unknown second bool - template <> - inline void BitStream::WriteCompressedDelta(const bool ¤tValue) - { - Write(currentValue); - } - - /// \brief Read any integral type from a bitstream. Define __BITSTREAM_NATIVE_END if you need endian swapping. - /// \param[in] outTemplateVar The value to read - template - inline bool BitStream::Read(templateType &outTemplateVar) - { - static_assert(std::is_trivially_copyable::value, - "BitStream::Read cannot deserialize this type: the generic template " - "overwrites the raw object representation, which is only valid for " - "trivially-copyable types. Reading into a type that owns memory " - "(e.g. std::string, std::vector, or any class with pointers) this " - "way corrupts memory. Provide a BitStream::Write/Read specialization " - "for the type, or deserialize its members explicitly."); -#ifdef _MSC_VER -#pragma warning(disable:4127) // conditional expression is constant -#endif - if (sizeof(outTemplateVar)==1) - return ReadBits( ( unsigned char* ) &outTemplateVar, sizeof(templateType) * 8, true ); - else - { -#ifndef __BITSTREAM_NATIVE_END - if (DoEndianSwap()) - { - unsigned char output[sizeof(templateType)]; - if (ReadBits( ( unsigned char* ) output, sizeof(templateType) * 8, true )) - { - ReverseBytes(output, (unsigned char*)&outTemplateVar, sizeof(templateType)); - return true; - } - return false; - } - else -#endif - return ReadBits( ( unsigned char* ) & outTemplateVar, sizeof(templateType) * 8, true ); - } - } - - /// \brief Read a bool from a bitstream. - /// \param[in] outTemplateVar The value to read - template <> - inline bool BitStream::Read(bool &outTemplateVar) - { - if (GetNumberOfUnreadBits() == 0) - return false; - - if ( data[ readOffset >> 3 ] & ( 0x80 >> ( readOffset & 7 ) ) ) // Is it faster to just write it out here? - outTemplateVar = true; - else - outTemplateVar = false; - - // Has to be on a different line for Mac - readOffset++; - - return true; - } - - /// \brief Read a systemAddress from a bitstream. - /// \param[in] outTemplateVar The value to read - template <> - inline bool BitStream::Read(SystemAddress &outTemplateVar) - { - unsigned char ipVersion; - Read(ipVersion); - if (ipVersion==4) - { - outTemplateVar.address.addr4.sin_family=AF_INET; - // Read(var.binaryAddress); - // Don't endian swap the address or port - uint32_t binaryAddress; - ReadBits( ( unsigned char* ) & binaryAddress, sizeof(binaryAddress) * 8, true ); - // Unhide the IP address, done to prevent routers from changing it - outTemplateVar.address.addr4.sin_addr.s_addr=~binaryAddress; - bool b = ReadBits(( unsigned char* ) & outTemplateVar.address.addr4.sin_port, sizeof(outTemplateVar.address.addr4.sin_port) * 8, true); - outTemplateVar.debugPort=ntohs(outTemplateVar.address.addr4.sin_port); - return b; - } - else - { -#if RAKNET_SUPPORT_IPV6==1 - bool b = ReadBits((unsigned char*) &outTemplateVar.address.addr6, sizeof(outTemplateVar.address.addr6)*8, true); - outTemplateVar.debugPort=ntohs(outTemplateVar.address.addr6.sin6_port); - return b; -#else - return false; -#endif - } - } - - template <> - inline bool BitStream::Read(uint24_t &outTemplateVar) - { - AlignReadToByteBoundary(); - if (GetNumberOfUnreadBits() < 3*8) - return false; - - if (IsBigEndian()==false) - { - ((unsigned char *)&outTemplateVar.val)[0]=data[ (readOffset >> 3) + 0]; - ((unsigned char *)&outTemplateVar.val)[1]=data[ (readOffset >> 3) + 1]; - ((unsigned char *)&outTemplateVar.val)[2]=data[ (readOffset >> 3) + 2]; - ((unsigned char *)&outTemplateVar.val)[3]=0; - } - else - { - - ((unsigned char *)&outTemplateVar.val)[3]=data[ (readOffset >> 3) + 0]; - ((unsigned char *)&outTemplateVar.val)[2]=data[ (readOffset >> 3) + 1]; - ((unsigned char *)&outTemplateVar.val)[1]=data[ (readOffset >> 3) + 2]; - ((unsigned char *)&outTemplateVar.val)[0]=0; - } - - readOffset+=3*8; - return true; - } - - template <> - inline bool BitStream::Read(RakNetGUID &outTemplateVar) - { - return Read(outTemplateVar.g); - } - - - template <> - inline bool BitStream::Read(RakString &outTemplateVar) - { - return outTemplateVar.Deserialize(this); - } - template <> - inline bool BitStream::Read(RakWString &outTemplateVar) - { - return outTemplateVar.Deserialize(this); - } - template <> - inline bool BitStream::Read(char *&varString) - { - return RakString::Deserialize(varString,this); - } - inline bool BitStream::Read(wchar_t *&varString) - { - return RakWString::Deserialize(varString, this); - } - inline bool BitStream::Read(wchar_t *&varString, size_t varStringLength) - { - return RakWString::Deserialize(varString,varStringLength,this); - } - template <> - inline bool BitStream::Read(unsigned char *&varString) - { - return RakString::Deserialize((char*) varString,this); - } - template <> - inline bool BitStream::Read(std::string &outStringVar) - { - unsigned short l; - if (Read(l)==false) - return false; - outStringVar.resize(l); - if (l>0) - return ReadAlignedBytes((unsigned char*) &outStringVar[0], l); - AlignReadToByteBoundary(); - return true; - } - - /// \brief Read any integral type from a bitstream. - /// \details If the written value differed from the value compared against in the write function, - /// var will be updated. Otherwise it will retain the current value. - /// ReadDelta is only valid from a previous call to WriteDelta - /// \param[in] outTemplateVar The value to read - template - inline bool BitStream::ReadDelta(templateType &outTemplateVar) - { - bool dataWritten; - bool success; - success=Read(dataWritten); - if (dataWritten) - success=Read(outTemplateVar); - return success; - } - - /// \brief Read a bool from a bitstream. - /// \param[in] outTemplateVar The value to read - template <> - inline bool BitStream::ReadDelta(bool &outTemplateVar) - { - return Read(outTemplateVar); - } - - /// \brief Read any integral type from a bitstream. - /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. - /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. - /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type - /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte - /// \param[in] outTemplateVar The value to read - template - inline bool BitStream::ReadCompressed(templateType &outTemplateVar) - { -#ifdef _MSC_VER -#pragma warning(disable:4127) // conditional expression is constant -#endif - if (sizeof(outTemplateVar)==1) - return ReadCompressed( ( unsigned char* ) &outTemplateVar, sizeof(templateType) * 8, true ); - else - { -#ifndef __BITSTREAM_NATIVE_END - if (DoEndianSwap()) - { - unsigned char output[sizeof(templateType)]; - if (ReadCompressed( ( unsigned char* ) output, sizeof(templateType) * 8, true )) - { - ReverseBytes(output, (unsigned char*)&outTemplateVar, sizeof(templateType)); - return true; - } - return false; - } - else -#endif - return ReadCompressed( ( unsigned char* ) & outTemplateVar, sizeof(templateType) * 8, true ); - } - } - - template <> - inline bool BitStream::ReadCompressed(SystemAddress &outTemplateVar) - { - return Read(outTemplateVar); - } - - template <> - inline bool BitStream::ReadCompressed(uint24_t &outTemplateVar) - { - return Read(outTemplateVar); - } - - template <> - inline bool BitStream::ReadCompressed(RakNetGUID &outTemplateVar) - { - return Read(outTemplateVar); - } - - template <> - inline bool BitStream::ReadCompressed(bool &outTemplateVar) - { - return Read(outTemplateVar); - } - - /// For values between -1 and 1 - template <> - inline bool BitStream::ReadCompressed(float &outTemplateVar) - { - unsigned short compressedFloat; - if (Read(compressedFloat)) - { - outTemplateVar = ((float)compressedFloat / 32767.5f - 1.0f); - return true; - } - return false; - } - - /// For values between -1 and 1 - template <> - inline bool BitStream::ReadCompressed(double &outTemplateVar) - { - uint32_t compressedFloat; - if (Read(compressedFloat)) - { - outTemplateVar = ((double)compressedFloat / 2147483648.0 - 1.0); - return true; - } - return false; - } - - /// For strings - template <> - inline bool BitStream::ReadCompressed(RakString &outTemplateVar) - { - return outTemplateVar.DeserializeCompressed(this,false); - } - template <> - inline bool BitStream::ReadCompressed(RakWString &outTemplateVar) - { - return outTemplateVar.Deserialize(this); - } - template <> - inline bool BitStream::ReadCompressed(char *&outTemplateVar) - { - return RakString::DeserializeCompressed(outTemplateVar,this,false); - } - inline bool BitStream::ReadCompressed(wchar_t *&outTemplateVar) - { - return RakWString::Deserialize(outTemplateVar, this); - } - inline bool BitStream::ReadCompressed(wchar_t *&outTemplateVar, size_t varStringLength) - { - return RakWString::Deserialize(outTemplateVar,varStringLength,this); - } - template <> - inline bool BitStream::ReadCompressed(unsigned char *&outTemplateVar) - { - return RakString::DeserializeCompressed((char*) outTemplateVar,this,false); - } - - /// \brief Read any integral type from a bitstream. - /// \details If the written value differed from the value compared against in the write function, - /// var will be updated. Otherwise it will retain the current value. - /// the current value will be updated. - /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. - /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type - /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte - /// ReadCompressedDelta is only valid from a previous call to WriteDelta - /// \param[in] outTemplateVar The value to read - template - inline bool BitStream::ReadCompressedDelta(templateType &outTemplateVar) - { - bool dataWritten; - bool success; - success=Read(dataWritten); - if (dataWritten) - success=ReadCompressed(outTemplateVar); - return success; - } - - /// \brief Read a bool from a bitstream. - /// \param[in] outTemplateVar The value to read - template <> - inline bool BitStream::ReadCompressedDelta(bool &outTemplateVar) - { - return Read(outTemplateVar); - } - - template - void BitStream::WriteCasted( const sourceType &value ) - { - destinationType val = (destinationType) value; - Write(val); - } - - template - void BitStream::WriteBitsFromIntegerRange( const templateType value, const templateType minimum,const templateType maximum, bool allowOutsideRange ) - { - int requiredBits=BYTES_TO_BITS(sizeof(templateType))-NumberOfLeadingZeroes(templateType(maximum-minimum)); - WriteBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange); - } - template - void BitStream::WriteBitsFromIntegerRange( const templateType value, const templateType minimum,const templateType maximum, const int requiredBits, bool allowOutsideRange ) - { - RakAssert(maximum>=minimum); - RakAssert(allowOutsideRange==true || (value>=minimum && value<=maximum)); - if (allowOutsideRange) - { - if (valuemaximum) - { - Write(true); - Write(value); - return; - } - Write(false); - } - templateType valueOffMin=value-minimum; - if (IsBigEndian()==true) - { - unsigned char output[sizeof(templateType)]; - ReverseBytes((unsigned char*)&valueOffMin, output, sizeof(templateType)); - WriteBits(output,requiredBits); - } - else - { - WriteBits((unsigned char*) &valueOffMin,requiredBits); - } - } - - template // templateType for this function must be a float or double - void BitStream::WriteNormVector( templateType x, templateType y, templateType z ) - { -#ifdef _DEBUG - RakAssert(x <= 1.01 && y <= 1.01 && z <= 1.01 && x >= -1.01 && y >= -1.01 && z >= -1.01); -#endif - - WriteFloat16((float)x,-1.0f,1.0f); - WriteFloat16((float)y,-1.0f,1.0f); - WriteFloat16((float)z,-1.0f,1.0f); - } - - template // templateType for this function must be a float or double - void BitStream::WriteVector( templateType x, templateType y, templateType z ) - { - templateType magnitude = sqrt(x * x + y * y + z * z); - Write((float)magnitude); - if (magnitude > 0.00001f) - { - WriteCompressed((float)(x/magnitude)); - WriteCompressed((float)(y/magnitude)); - WriteCompressed((float)(z/magnitude)); - // Write((unsigned short)((x/magnitude+1.0f)*32767.5f)); - // Write((unsigned short)((y/magnitude+1.0f)*32767.5f)); - // Write((unsigned short)((z/magnitude+1.0f)*32767.5f)); - } - } - - template // templateType for this function must be a float or double - void BitStream::WriteNormQuat( templateType w, templateType x, templateType y, templateType z) - { - Write((bool)(w<0.0)); - Write((bool)(x<0.0)); - Write((bool)(y<0.0)); - Write((bool)(z<0.0)); - Write((unsigned short)(fabs(x)*65535.0)); - Write((unsigned short)(fabs(y)*65535.0)); - Write((unsigned short)(fabs(z)*65535.0)); - // Leave out w and calculate it on the target - } - - template // templateType for this function must be a float or double - void BitStream::WriteOrthMatrix( - templateType m00, templateType m01, templateType m02, - templateType m10, templateType m11, templateType m12, - templateType m20, templateType m21, templateType m22 ) - { - - double qw; - double qx; - double qy; - double qz; - - // Convert matrix to quat - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ - float sum; - sum = 1 + m00 + m11 + m22; - if (sum < 0.0f) sum=0.0f; - qw = sqrt( sum ) / 2; - sum = 1 + m00 - m11 - m22; - if (sum < 0.0f) sum=0.0f; - qx = sqrt( sum ) / 2; - sum = 1 - m00 + m11 - m22; - if (sum < 0.0f) sum=0.0f; - qy = sqrt( sum ) / 2; - sum = 1 - m00 - m11 + m22; - if (sum < 0.0f) sum=0.0f; - qz = sqrt( sum ) / 2; - if (qw < 0.0) qw=0.0; - if (qx < 0.0) qx=0.0; - if (qy < 0.0) qy=0.0; - if (qz < 0.0) qz=0.0; - qx = _copysign( (double) qx, (double) (m21 - m12) ); - qy = _copysign( (double) qy, (double) (m02 - m20) ); - qz = _copysign( (double) qz, (double) (m10 - m01) ); - - WriteNormQuat(qw,qx,qy,qz); - } - - template - bool BitStream::ReadCasted( sourceType &value ) - { - serializationType val; - bool success = Read(val); - value=(sourceType) val; - return success; - } - - template - bool BitStream::ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange ) - { - int requiredBits=BYTES_TO_BITS(sizeof(templateType))-NumberOfLeadingZeroes(templateType(maximum-minimum)); - return ReadBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange); - } - template - bool BitStream::ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange ) - { - RakAssert(maximum>=minimum); - if (allowOutsideRange) - { - bool isOutsideRange; - Read(isOutsideRange); - if (isOutsideRange) - return Read(value); - } - unsigned char output[sizeof(templateType)]; - memset(output,0,sizeof(output)); - bool success = ReadBits(output,requiredBits); - if (success) - { - if (IsBigEndian()==true) - ReverseBytesInPlace(output,sizeof(output)); - memcpy(&value,output,sizeof(output)); - - value+=minimum; - } - - return success; - } - - template // templateType for this function must be a float or double - bool BitStream::ReadNormVector( templateType &x, templateType &y, templateType &z ) - { - float xIn,yIn,zIn; - ReadFloat16(xIn,-1.0f,1.0f); - ReadFloat16(yIn,-1.0f,1.0f); - ReadFloat16(zIn,-1.0f,1.0f); - x=xIn; - y=yIn; - z=zIn; - return true; - } - - template // templateType for this function must be a float or double - bool BitStream::ReadVector( templateType &x, templateType &y, templateType &z ) - { - float magnitude; - //unsigned short sx,sy,sz; - if (!Read(magnitude)) - return false; - if (magnitude>0.00001f) - { - // Read(sx); - // Read(sy); - // if (!Read(sz)) - // return false; - // x=((float)sx / 32767.5f - 1.0f) * magnitude; - // y=((float)sy / 32767.5f - 1.0f) * magnitude; - // z=((float)sz / 32767.5f - 1.0f) * magnitude; - float cx=0.0f,cy=0.0f,cz=0.0f; - ReadCompressed(cx); - ReadCompressed(cy); - if (!ReadCompressed(cz)) - return false; - x=cx; - y=cy; - z=cz; - x*=magnitude; - y*=magnitude; - z*=magnitude; - } - else - { - x=0.0; - y=0.0; - z=0.0; - } - return true; - } - - template // templateType for this function must be a float or double - bool BitStream::ReadNormQuat( templateType &w, templateType &x, templateType &y, templateType &z) - { - bool cwNeg=false, cxNeg=false, cyNeg=false, czNeg=false; - unsigned short cx,cy,cz; - Read(cwNeg); - Read(cxNeg); - Read(cyNeg); - Read(czNeg); - Read(cx); - Read(cy); - if (!Read(cz)) - return false; - - // Calculate w from x,y,z - x=(templateType)(cx/65535.0); - y=(templateType)(cy/65535.0); - z=(templateType)(cz/65535.0); - if (cxNeg) x=-x; - if (cyNeg) y=-y; - if (czNeg) z=-z; - float difference = 1.0f - x*x - y*y - z*z; - if (difference < 0.0f) - difference=0.0f; - w = (templateType)(sqrt(difference)); - if (cwNeg) - w=-w; - - return true; - } - - template // templateType for this function must be a float or double - bool BitStream::ReadOrthMatrix( - templateType &m00, templateType &m01, templateType &m02, - templateType &m10, templateType &m11, templateType &m12, - templateType &m20, templateType &m21, templateType &m22 ) - { - float qw,qx,qy,qz; - if (!ReadNormQuat(qw,qx,qy,qz)) - return false; - - // Quat to orthogonal rotation matrix - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToMatrix/index.htm - double sqw = (double)qw*(double)qw; - double sqx = (double)qx*(double)qx; - double sqy = (double)qy*(double)qy; - double sqz = (double)qz*(double)qz; - m00 = (templateType)(sqx - sqy - sqz + sqw); // since sqw + sqx + sqy + sqz =1 - m11 = (templateType)(-sqx + sqy - sqz + sqw); - m22 = (templateType)(-sqx - sqy + sqz + sqw); - - double tmp1 = (double)qx*(double)qy; - double tmp2 = (double)qz*(double)qw; - m10 = (templateType)(2.0 * (tmp1 + tmp2)); - m01 = (templateType)(2.0 * (tmp1 - tmp2)); - - tmp1 = (double)qx*(double)qz; - tmp2 = (double)qy*(double)qw; - m20 =(templateType)(2.0 * (tmp1 - tmp2)); - m02 = (templateType)(2.0 * (tmp1 + tmp2)); - tmp1 = (double)qy*(double)qz; - tmp2 = (double)qx*(double)qw; - m21 = (templateType)(2.0 * (tmp1 + tmp2)); - m12 = (templateType)(2.0 * (tmp1 - tmp2)); - - return true; - } - - template - BitStream& operator<<(BitStream& out, const templateType& c) - { - out.Write(c); - return out; - } - template - BitStream& operator>>(BitStream& in, templateType& c) - { - bool success = in.Read(c); - (void)success; - - RakAssert(success); - return in; - } - -} - -#ifdef _MSC_VER -#pragma warning( pop ) -#endif - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/CCRakNetSlidingWindow.h b/vendors/mafianet/Source/include/mafianet/CCRakNetSlidingWindow.h deleted file mode 100644 index bb6458a1a..000000000 --- a/vendors/mafianet/Source/include/mafianet/CCRakNetSlidingWindow.h +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/* -http://www.ssfnet.org/Exchange/tcp/tcpTutorialNotes.html - -cwnd=max bytes allowed on wire at once - -Start: -cwnd=mtu -ssthresh=unlimited - -Slow start: -On ack cwnd*=2 - -congestion avoidance: -On ack during new period -cwnd+=mtu*mtu/cwnd - -on loss or duplicate ack during period: -sshtresh=cwnd/2 -cwnd=MTU -This reenters slow start - -If cwnd < ssthresh, then use slow start -else use congestion avoidance - - -*/ - -#include "defines.h" - -#if USE_SLIDING_WINDOW_CONGESTION_CONTROL==1 - -#ifndef __CONGESTION_CONTROL_SLIDING_WINDOW_H -#define __CONGESTION_CONTROL_SLIDING_WINDOW_H - -#include "NativeTypes.h" -#include "time.h" -#include "types.h" -#include "DS_Queue.h" - -/// Sizeof an UDP header in byte -#define UDP_HEADER_SIZE 28 - -#define CC_DEBUG_PRINTF_1(x) -#define CC_DEBUG_PRINTF_2(x,y) -#define CC_DEBUG_PRINTF_3(x,y,z) -#define CC_DEBUG_PRINTF_4(x,y,z,a) -#define CC_DEBUG_PRINTF_5(x,y,z,a,b) -//#define CC_DEBUG_PRINTF_1(x) printf(x) -//#define CC_DEBUG_PRINTF_2(x,y) printf(x,y) -//#define CC_DEBUG_PRINTF_3(x,y,z) printf(x,y,z) -//#define CC_DEBUG_PRINTF_4(x,y,z,a) printf(x,y,z,a) -//#define CC_DEBUG_PRINTF_5(x,y,z,a,b) printf(x,y,z,a,b) - -/// Set to 4 if you are using the iPod Touch TG. See http://www.jenkinssoftware.com/forum/index.php?topic=2717.0 -#define CC_TIME_TYPE_BYTES 8 - -#if CC_TIME_TYPE_BYTES==8 -typedef MafiaNet::TimeUS CCTimeType; -#else -typedef MafiaNet::TimeMS CCTimeType; -#endif - -typedef MafiaNet::uint24_t DatagramSequenceNumberType; -typedef double BytesPerMicrosecond; -typedef double BytesPerSecond; -typedef double MicrosecondsPerByte; - -namespace MafiaNet -{ - -class CCRakNetSlidingWindow -{ - public: - - CCRakNetSlidingWindow(); - ~CCRakNetSlidingWindow(); - - /// Reset all variables to their initial states, for a new connection - void Init(CCTimeType curTime, uint32_t maxDatagramPayload); - - /// Update over time - void Update(CCTimeType curTime, bool hasDataToSendOrResend); - - int GetRetransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend); - int GetTransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend); - - /// Acks do not have to be sent immediately. Instead, they can be buffered up such that groups of acks are sent at a time - /// This reduces overall bandwidth usage - /// How long they can be buffered depends on the retransmit time of the sender - /// Should call once per update tick, and send if needed - bool ShouldSendACKs(CCTimeType curTime, CCTimeType estimatedTimeToNextTick); - - /// Every data packet sent must contain a sequence number - /// Call this function to get it. The sequence number is passed into OnGotPacketPair() - DatagramSequenceNumberType GetAndIncrementNextDatagramSequenceNumber(void); - DatagramSequenceNumberType GetNextDatagramSequenceNumber(void); - - /// Call this when you send packets - /// Every 15th and 16th packets should be sent as a packet pair if possible - /// When packets marked as a packet pair arrive, pass to OnGotPacketPair() - /// When any packets arrive, (additionally) pass to OnGotPacket - /// Packets should contain our system time, so we can pass rtt to OnNonDuplicateAck() - void OnSendBytes(CCTimeType curTime, uint32_t numBytes); - - /// Call this when you get a packet pair - void OnGotPacketPair(DatagramSequenceNumberType datagramSequenceNumber, uint32_t sizeInBytes, CCTimeType curTime); - - /// Call this when you get a packet (including packet pairs) - /// If the DatagramSequenceNumberType is out of order, skippedMessageCount will be non-zero - /// In that case, send a NAK for every sequence number up to that count - bool OnGotPacket(DatagramSequenceNumberType datagramSequenceNumber, bool isContinuousSend, CCTimeType curTime, uint32_t sizeInBytes, uint32_t *skippedMessageCount); - - /// Call when you get a NAK, with the sequence number of the lost message - /// Affects the congestion control - void OnResend(CCTimeType curTime, MafiaNet::TimeUS nextActionTime); - void OnNAK(CCTimeType curTime, DatagramSequenceNumberType nakSequenceNumber); - - /// Call this when an ACK arrives. - /// hasBAndAS are possibly written with the ack, see OnSendAck() - /// B and AS are used in the calculations in UpdateWindowSizeAndAckOnAckPerSyn - /// B and AS are updated at most once per SYN - void OnAck(CCTimeType curTime, CCTimeType rtt, bool hasBAndAS, BytesPerMicrosecond _B, BytesPerMicrosecond _AS, double totalUserDataBytesAcked, bool isContinuousSend, DatagramSequenceNumberType sequenceNumber ); - void OnDuplicateAck( CCTimeType curTime, DatagramSequenceNumberType sequenceNumber ); - - /// Call when you send an ack, to see if the ack should have the B and AS parameters transmitted - /// Call before calling OnSendAck() - void OnSendAckGetBAndAS(CCTimeType curTime, bool *hasBAndAS, BytesPerMicrosecond *_B, BytesPerMicrosecond *_AS); - - /// Call when we send an ack, to write B and AS if needed - /// B and AS are only written once per SYN, to prevent slow calculations - /// Also updates SND, the period between sends, since data is written out - /// Be sure to call OnSendAckGetBAndAS() before calling OnSendAck(), since whether you write it or not affects \a numBytes - void OnSendAck(CCTimeType curTime, uint32_t numBytes); - - /// Call when we send a NACK - /// Also updates SND, the period between sends, since data is written out - void OnSendNACK(CCTimeType curTime, uint32_t numBytes); - - /// Retransmission time out for the sender - /// If the time difference between when a message was last transmitted, and the current time is greater than RTO then packet is eligible for retransmission, pending congestion control - /// RTO = (RTT + 4 * RTTVar) + SYN - /// If we have been continuously sending for the last RTO, and no ACK or NAK at all, SND*=2; - /// This is per message, which is different from UDT, but RakNet supports packetloss with continuing data where UDT is only MafiaNet::Reliability::ReliableOrdered - /// Minimum value is 100 milliseconds - CCTimeType GetRTOForRetransmission(unsigned char timesSent) const; - - /// Set the maximum amount of data that can be sent in one datagram - /// Default to MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE - void SetMTU(uint32_t bytes); - - /// Return what was set by SetMTU() - uint32_t GetMTU(void) const; - - /// Query for statistics - BytesPerMicrosecond GetLocalSendRate(void) const {return 0;} - BytesPerMicrosecond GetLocalReceiveRate(CCTimeType currentTime) const; - BytesPerMicrosecond GetRemoveReceiveRate(void) const {return 0;} - //BytesPerMicrosecond GetEstimatedBandwidth(void) const {return B;} - BytesPerMicrosecond GetEstimatedBandwidth(void) const {return GetLinkCapacityBytesPerSecond()*1000000.0;} - double GetLinkCapacityBytesPerSecond(void) const {return 0;} - - /// Query for statistics - double GetRTT(void) const; - - bool GetIsInSlowStart(void) const {return IsInSlowStart();} - uint32_t GetCWNDLimit(void) const {return (uint32_t) 0;} - - - /// Is a > b, accounting for variable overflow? - static bool GreaterThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b); - /// Is a < b, accounting for variable overflow? - static bool LessThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b); -// void SetTimeBetweenSendsLimit(unsigned int bitsPerSecond); - uint64_t GetBytesPerSecondLimitByCongestionControl(void) const; - - protected: - - // Maximum amount of bytes that the user can send, e.g. the size of one full datagram - uint32_t MAXIMUM_MTU_INCLUDING_UDP_HEADER; - - double cwnd; // max bytes on wire - double ssThresh; // Threshhold between slow start and congestion avoidance - - /// When we get an ack, if oldestUnsentAck==0, set it to the current time - /// When we send out acks, set oldestUnsentAck to 0 - CCTimeType oldestUnsentAck; - - CCTimeType GetSenderRTOForACK(void) const; - - /// Every outgoing datagram is assigned a sequence number, which increments by 1 every assignment - DatagramSequenceNumberType nextDatagramSequenceNumber; - DatagramSequenceNumberType nextCongestionControlBlock; - bool backoffThisBlock, speedUpThisBlock; - /// Track which datagram sequence numbers have arrived. - /// If a sequence number is skipped, send a NAK for all skipped messages - DatagramSequenceNumberType expectedNextSequenceNumber; - - bool _isContinuousSend; - - bool IsInSlowStart(void) const; - - double lastRtt, estimatedRTT, deviationRtt; - -}; - -} - -#endif - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/CCRakNetUDT.h b/vendors/mafianet/Source/include/mafianet/CCRakNetUDT.h deleted file mode 100644 index 8e168a442..000000000 --- a/vendors/mafianet/Source/include/mafianet/CCRakNetUDT.h +++ /dev/null @@ -1,409 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "defines.h" - -#if USE_SLIDING_WINDOW_CONGESTION_CONTROL!=1 - -#ifndef __CONGESTION_CONTROL_UDT_H -#define __CONGESTION_CONTROL_UDT_H - -#include "NativeTypes.h" -#include "time.h" -#include "types.h" -#include "DS_Queue.h" - -/// Set to 4 if you are using the iPod Touch TG. See http://www.jenkinssoftware.com/forum/index.php?topic=2717.0 -#define CC_TIME_TYPE_BYTES 8 - -namespace MafiaNet -{ - -#if CC_TIME_TYPE_BYTES==8 -typedef uint64_t CCTimeType; -#else -typedef uint32_t CCTimeType; -#endif - -typedef uint24_t DatagramSequenceNumberType; -typedef double BytesPerMicrosecond; -typedef double BytesPerSecond; -typedef double MicrosecondsPerByte; - -/// CC_RAKNET_UDT_PACKET_HISTORY_LENGTH should be a power of 2 for the writeIndex variables to wrap properly -#define CC_RAKNET_UDT_PACKET_HISTORY_LENGTH 64 -#define RTT_HISTORY_LENGTH 64 - -/// Sizeof an UDP header in byte -#define UDP_HEADER_SIZE 28 - -#define CC_DEBUG_PRINTF_1(x) -#define CC_DEBUG_PRINTF_2(x,y) -#define CC_DEBUG_PRINTF_3(x,y,z) -#define CC_DEBUG_PRINTF_4(x,y,z,a) -#define CC_DEBUG_PRINTF_5(x,y,z,a,b) -//#define CC_DEBUG_PRINTF_1(x) printf(x) -//#define CC_DEBUG_PRINTF_2(x,y) printf(x,y) -//#define CC_DEBUG_PRINTF_3(x,y,z) printf(x,y,z) -//#define CC_DEBUG_PRINTF_4(x,y,z,a) printf(x,y,z,a) -//#define CC_DEBUG_PRINTF_5(x,y,z,a,b) printf(x,y,z,a,b) - -/// \brief Encapsulates UDT congestion control, as used by RakNet -/// Requirements: -///
    -///
  1. Each datagram is no more than MAXIMUM_MTU_SIZE, after accounting for the UDP header -///
  2. Each datagram containing a user message has a sequence number which is set after calling OnSendBytes(). Set it by calling GetAndIncrementNextDatagramSequenceNumber() -///
  3. System is designed to be used from a single thread. -///
  4. Each packet should have a timeout time based on GetSenderRTOForACK(). If this time elapses, add the packet to the head of the send list for retransmission. -///
-/// -/// Recommended: -///
    -///
  1. Call sendto in its own thread. This takes a significant amount of time in high speed networks. -///
-/// -/// Algorithm: -///
    -///
  1. On a new connection, call Init() -///
  2. On a periodic interval (SYN time is the best) call Update(). Also call ShouldSendACKs(), and send buffered ACKS if it returns true. -///
  3. Call OnSendAck() when sending acks. -///
  4. When you want to send or resend data, call GetNumberOfBytesToSend(). It will return you enough bytes to keep you busy for \a estimatedTimeToNextTick. You can send more than this to fill out a datagram, or to send packet pairs -///
  5. Call OnSendBytes() when sending datagrams. -///
  6. When data arrives, record the sequence number and buffer an ACK for it, to be sent from Update() if ShouldSendACKs() returns true -///
  7. Every 16 packets that you send, send two of them back to back (a packet pair) as long as both packets are the same size. If you don't have two packets the same size, it is fine to defer this until you do. -///
  8. When you get a packet, call OnGotPacket(). If the packet is also either of a packet pair, call OnGotPacketPair() -///
  9. If you get a packet, and the sequence number is not 1 + the last sequence number, send a NAK. On the remote system, call OnNAK() and resend that message. -///
  10. If you get an ACK, remove that message from retransmission. Call OnNonDuplicateAck(). -///
  11. If a message is not ACKed for GetRTOForRetransmission(), resend it. -///
-class CCRakNetUDT -{ - public: - - CCRakNetUDT(); - ~CCRakNetUDT(); - - /// Reset all variables to their initial states, for a new connection - void Init(CCTimeType curTime, uint32_t maxDatagramPayload); - - /// Update over time - void Update(CCTimeType curTime, bool hasDataToSendOrResend); - - int GetRetransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend); - int GetTransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend); - - /// Acks do not have to be sent immediately. Instead, they can be buffered up such that groups of acks are sent at a time - /// This reduces overall bandwidth usage - /// How long they can be buffered depends on the retransmit time of the sender - /// Should call once per update tick, and send if needed - bool ShouldSendACKs(CCTimeType curTime, CCTimeType estimatedTimeToNextTick); - - /// Every data packet sent must contain a sequence number - /// Call this function to get it. The sequence number is passed into OnGotPacketPair() - DatagramSequenceNumberType GetAndIncrementNextDatagramSequenceNumber(void); - DatagramSequenceNumberType GetNextDatagramSequenceNumber(void); - - /// Call this when you send packets - /// Every 15th and 16th packets should be sent as a packet pair if possible - /// When packets marked as a packet pair arrive, pass to OnGotPacketPair() - /// When any packets arrive, (additionally) pass to OnGotPacket - /// Packets should contain our system time, so we can pass rtt to OnNonDuplicateAck() - void OnSendBytes(CCTimeType curTime, uint32_t numBytes); - - /// Call this when you get a packet pair - void OnGotPacketPair(DatagramSequenceNumberType datagramSequenceNumber, uint32_t sizeInBytes, CCTimeType curTime); - - /// Call this when you get a packet (including packet pairs) - /// If the DatagramSequenceNumberType is out of order, skippedMessageCount will be non-zero - /// In that case, send a NAK for every sequence number up to that count - bool OnGotPacket(DatagramSequenceNumberType datagramSequenceNumber, bool isContinuousSend, CCTimeType curTime, uint32_t sizeInBytes, uint32_t *skippedMessageCount); - - /// Call when you get a NAK, with the sequence number of the lost message - /// Affects the congestion control - void OnResend(CCTimeType curTime, MafiaNet::TimeUS nextActionTime); - void OnNAK(CCTimeType curTime, DatagramSequenceNumberType nakSequenceNumber); - - /// Call this when an ACK arrives. - /// hasBAndAS are possibly written with the ack, see OnSendAck() - /// B and AS are used in the calculations in UpdateWindowSizeAndAckOnAckPerSyn - /// B and AS are updated at most once per SYN - void OnAck(CCTimeType curTime, CCTimeType rtt, bool hasBAndAS, BytesPerMicrosecond _B, BytesPerMicrosecond _AS, double totalUserDataBytesAcked, bool isContinuousSend, DatagramSequenceNumberType sequenceNumber ); - void OnDuplicateAck( CCTimeType curTime, DatagramSequenceNumberType sequenceNumber ) {} - - /// Call when you send an ack, to see if the ack should have the B and AS parameters transmitted - /// Call before calling OnSendAck() - void OnSendAckGetBAndAS(CCTimeType curTime, bool *hasBAndAS, BytesPerMicrosecond *_B, BytesPerMicrosecond *_AS); - - /// Call when we send an ack, to write B and AS if needed - /// B and AS are only written once per SYN, to prevent slow calculations - /// Also updates SND, the period between sends, since data is written out - /// Be sure to call OnSendAckGetBAndAS() before calling OnSendAck(), since whether you write it or not affects \a numBytes - void OnSendAck(CCTimeType curTime, uint32_t numBytes); - - /// Call when we send a NACK - /// Also updates SND, the period between sends, since data is written out - void OnSendNACK(CCTimeType curTime, uint32_t numBytes); - - /// Retransmission time out for the sender - /// If the time difference between when a message was last transmitted, and the current time is greater than RTO then packet is eligible for retransmission, pending congestion control - /// RTO = (RTT + 4 * RTTVar) + SYN - /// If we have been continuously sending for the last RTO, and no ACK or NAK at all, SND*=2; - /// This is per message, which is different from UDT, but RakNet supports packetloss with continuing data where UDT is only MafiaNet::Reliability::ReliableOrdered - /// Minimum value is 100 milliseconds - CCTimeType GetRTOForRetransmission(unsigned char timesSent) const; - - /// Set the maximum amount of data that can be sent in one datagram - /// Default to MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE - void SetMTU(uint32_t bytes); - - /// Return what was set by SetMTU() - uint32_t GetMTU(void) const; - - /// Query for statistics - BytesPerMicrosecond GetLocalSendRate(void) const {return 1.0 / SND;} - BytesPerMicrosecond GetLocalReceiveRate(CCTimeType currentTime) const; - BytesPerMicrosecond GetRemoveReceiveRate(void) const {return AS;} - //BytesPerMicrosecond GetEstimatedBandwidth(void) const {return B;} - BytesPerMicrosecond GetEstimatedBandwidth(void) const {return GetLinkCapacityBytesPerSecond()*1000000.0;} - double GetLinkCapacityBytesPerSecond(void) const {return estimatedLinkCapacityBytesPerSecond;}; - - /// Query for statistics - double GetRTT(void) const; - - bool GetIsInSlowStart(void) const {return isInSlowStart;} - uint32_t GetCWNDLimit(void) const {return (uint32_t) (CWND*MAXIMUM_MTU_INCLUDING_UDP_HEADER);} - - - /// Is a > b, accounting for variable overflow? - static bool GreaterThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b); - /// Is a < b, accounting for variable overflow? - static bool LessThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b); -// void SetTimeBetweenSendsLimit(unsigned int bitsPerSecond); - uint64_t GetBytesPerSecondLimitByCongestionControl(void) const; - - protected: - // --------------------------- PROTECTED VARIABLES --------------------------- - /// time interval between bytes, in microseconds. - /// Only used when slowStart==false - /// Increased over time as we continually get messages - /// Decreased on NAK and timeout - /// Starts at 0 (invalid) - MicrosecondsPerByte SND; - - /// Supportive window mechanism, controlling the maximum number of in-flight packets - /// Used both during and after slow-start, but primarily during slow-start - /// Starts at 2, which is also the low threshhold - /// Max is the socket receive buffer / MTU - /// CWND = AS * (RTT + SYN) + 16 - double CWND; - - /// When we do an update process on the SYN interval, nextSYNUpdate is set to the next time we should update - /// Normally this is nextSYNUpdate+=SYN, in order to update on a consistent schedule - /// However, if this would result in an immediate update yet again, it is set to SYN microseconds past the current time (in case the thread did not update for a long time) - CCTimeType nextSYNUpdate; - - - /// Index into packetPairRecieptHistory where we will next write - /// The history is always full (starting with default values) so no read index is needed - int packetPairRecieptHistoryWriteIndex; - - /// Sent to the sender by the receiver from packetPairRecieptHistory whenever a back to back packet arrives on the receiver - /// Updated by B = B * .875 + incomingB * .125 - //BytesPerMicrosecond B; - - /// Running round trip time (ping*2) - /// Only sender needs to know this - /// Initialized to UNSET - /// Set to rtt on first calculation - /// Updated gradually by RTT = RTT * 0.875 + rtt * 0.125 - double RTT; - - /// Round trip time variance - /// Only sender needs to know this - /// Initialized to UNSET - /// Set to rtt on first calculation - // double RTTVar; - /// Update: Use min/max, RTTVar follows current variance too closely resulting in packetloss - double minRTT, maxRTT; - - /// Used to calculate packet arrival rate (in UDT) but data arrival rate (in RakNet, where not all datagrams are the same size) - /// Filter is used to cull lowest half of values for bytesPerMicrosecond, to discount spikes and inactivity - /// Referred to in the documentation as AS, data arrival rate - /// AS is sent to the sender and calculated every 10th ack - /// Each node represents (curTime-lastPacketArrivalTime)/bytes - /// Used with ReceiverCalculateDataArrivalRate(); - BytesPerMicrosecond packetArrivalHistory[CC_RAKNET_UDT_PACKET_HISTORY_LENGTH]; - BytesPerMicrosecond packetArrivalHistoryContinuousGaps[CC_RAKNET_UDT_PACKET_HISTORY_LENGTH]; - unsigned char packetArrivalHistoryContinuousGapsIndex; - uint64_t continuousBytesReceived; - CCTimeType continuousBytesReceivedStartTime; - unsigned int packetArrivalHistoryWriteCount; - - /// Index into packetArrivalHistory where we will next write - /// The history is always full (starting with default values) so no read index is needed - int packetArrivalHistoryWriteIndex; - - /// Tracks the time the last packet that arrived, so BytesPerMicrosecond can be calculated for packetArrivalHistory when a new packet arrives - CCTimeType lastPacketArrivalTime; - - /// Data arrival rate from the sender to the receiver, as told to us by the receiver - /// Used to calculate initial sending rate when slow start stops - BytesPerMicrosecond AS; - - /// When the receiver last calculated and send B and AS, from packetArrivalHistory and packetPairRecieptHistory - /// Used to prevent it from being calculated and send too frequently, as they are slow operations - CCTimeType lastTransmitOfBAndAS; - - /// New connections start in slow start - /// During slow start, SND is not used, only CWND - /// Slow start ends when we get a NAK, or the maximum size of CWND is reached - /// SND is initialized to the inverse of the receiver's packet arrival rate when slow start ends - bool isInSlowStart; - - /// How many NAKs arrived this congestion period - /// Initialized to 1 when the congestion period starts - uint32_t NAKCount; - - /// How many NAKs do you get on average during a congestion period? - /// Starts at 1 - /// Used to generate a random number, DecRandom, between 1 and AvgNAKNum - uint32_t AvgNAKNum; - - /// How many times we have decremented SND this congestion period. Used to limit the number of decrements to 5 - uint32_t DecCount; - - /// Every DecInterval NAKs per congestion period, we decrease the send rate - uint32_t DecInterval; - - /// Every outgoing datagram is assigned a sequence number, which increments by 1 every assignment - DatagramSequenceNumberType nextDatagramSequenceNumber; - - /// If a packet is marked as a packet pair, lastPacketPairPacketArrivalTime is set to the time it arrives - /// This is used so when the 2nd packet of the pair arrives, we can calculate the time interval between the two - CCTimeType lastPacketPairPacketArrivalTime; - - /// If a packet is marked as a packet pair, lastPacketPairSequenceNumber is checked to see if the last packet we got - /// was the packet immediately before the one that arrived - /// If so, we can use lastPacketPairPacketArrivalTime to get the time between the two packets, and thus estimate the link capacity - /// Initialized to -1, so the first packet of a packet pair won't be treated as the second - DatagramSequenceNumberType lastPacketPairSequenceNumber; - - /// Used to cap UpdateWindowSizeAndAckOnAckPerSyn() to once speed increase per SYN - /// This is to prevent speeding up faster than congestion control can compensate for - CCTimeType lastUpdateWindowSizeAndAck; - - /// Every time SND is halved due to timeout, the RTO is increased - /// This is to prevent massive retransmissions to an unresponsive system - /// Reset on any data arriving - double ExpCount; - - /// Total number of user data bytes sent - /// Used to adjust the window size, on ACK, during slow start - uint64_t totalUserDataBytesSent; - - /// When we get an ack, if oldestUnsentAck==0, set it to the current time - /// When we send out acks, set oldestUnsentAck to 0 - CCTimeType oldestUnsentAck; - - // Maximum amount of bytes that the user can send, e.g. the size of one full datagram - uint32_t MAXIMUM_MTU_INCLUDING_UDP_HEADER; - - // Max window size - double CWND_MAX_THRESHOLD; - - /// Track which datagram sequence numbers have arrived. - /// If a sequence number is skipped, send a NAK for all skipped messages - DatagramSequenceNumberType expectedNextSequenceNumber; - - // How many times have we sent B and AS? Used to force it to send at least CC_RAKNET_UDT_PACKET_HISTORY_LENGTH times - // Otherwise, the default values in the array generate inaccuracy - uint32_t sendBAndASCount; - - /// Most recent values read into the corresponding lists - /// Used during the beginning of a connection, when the median filter is still inaccurate - BytesPerMicrosecond mostRecentPacketArrivalHistory; - - bool hasWrittenToPacketPairReceiptHistory; - -// uint32_t rttHistory[RTT_HISTORY_LENGTH]; -// uint32_t rttHistoryIndex; -// uint32_t rttHistoryWriteCount; -// uint32_t rttSum, rttLow; -// CCTimeType lastSndUpdateTime; - double estimatedLinkCapacityBytesPerSecond; - - // --------------------------- PROTECTED METHODS --------------------------- - /// Update nextSYNUpdate by SYN, or the same amount past the current time if no updates have occurred for a long time - void SetNextSYNUpdate(CCTimeType currentTime); - - /// Returns the rate of data arrival, based on packets arriving on the sender. - BytesPerMicrosecond ReceiverCalculateDataArrivalRate(CCTimeType curTime) const; - /// Returns the median of the data arrival rate - BytesPerMicrosecond ReceiverCalculateDataArrivalRateMedian(void) const; - - /// Calculates the median an array of BytesPerMicrosecond - static BytesPerMicrosecond CalculateListMedianRecursive(const BytesPerMicrosecond inputList[CC_RAKNET_UDT_PACKET_HISTORY_LENGTH], int inputListLength, int lessThanSum, int greaterThanSum); -// static uint32_t CalculateListMedianRecursive(const uint32_t inputList[RTT_HISTORY_LENGTH], int inputListLength, int lessThanSum, int greaterThanSum); - - /// Same as GetRTOForRetransmission, but does not factor in ExpCount - /// This is because the receiver does not know ExpCount for the sender, and even if it did, acks shouldn't be delayed for this reason - CCTimeType GetSenderRTOForACK(void) const; - - /// Stop slow start, and enter normal transfer rate - void EndSlowStart(void); - - /// Does the named conversion - inline double BytesPerMicrosecondToPacketsPerMillisecond(BytesPerMicrosecond in); - - /// Update the round trip time, from ACK or ACK2 - //void UpdateRTT(CCTimeType rtt); - - /// Update the corresponding variables pre-slow start - void UpdateWindowSizeAndAckOnAckPreSlowStart(double totalUserDataBytesAcked); - - /// Update the corresponding variables post-slow start - void UpdateWindowSizeAndAckOnAckPerSyn(CCTimeType curTime, CCTimeType rtt, bool isContinuousSend, DatagramSequenceNumberType sequenceNumber); - - - /// Sets halveSNDOnNoDataTime to the future, and also resets ExpCount, which is used to multiple the RTO on no data arriving at all - void ResetOnDataArrivalHalveSNDOnNoDataTime(CCTimeType curTime); - - // Init array - void InitPacketArrivalHistory(void); - - // Printf - void PrintLowBandwidthWarning(void); - - // Bug: SND can sometimes get super high - have seen 11693 - void CapMinSnd(const char *file, int line); - - void DecreaseTimeBetweenSends(void); - void IncreaseTimeBetweenSends(void); - - int bytesCanSendThisTick; - - CCTimeType lastRttOnIncreaseSendRate; - CCTimeType lastRtt; - - DatagramSequenceNumberType nextCongestionControlBlock; - bool hadPacketlossThisBlock; - DataStructures::Queue pingsLastInterval; -}; - -} - -#endif - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/CheckSum.h b/vendors/mafianet/Source/include/mafianet/CheckSum.h deleted file mode 100644 index d4ab2f97f..000000000 --- a/vendors/mafianet/Source/include/mafianet/CheckSum.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// -/// \file CheckSum.cpp -/// \brief [Internal] CheckSum implementation from http://www.flounder.com/checksum.htm -/// - -#ifndef __CHECKSUM_H -#define __CHECKSUM_H - -#include "memoryoverride.h" - -/// Generates and validates checksums -class CheckSum -{ - -public: - - /// Default constructor - - CheckSum() - { - Clear(); - } - - void Clear() - { - sum = 0; - r = 55665; - c1 = 52845; - c2 = 22719; - } - - void Add ( unsigned int w ); - - - void Add ( unsigned short w ); - - void Add ( unsigned char* b, unsigned int length ); - - void Add ( unsigned char b ); - - unsigned int Get () - { - return sum; - } - -protected: - unsigned short r; - unsigned short c1; - unsigned short c2; - unsigned int sum; -}; - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/CloudClient.h b/vendors/mafianet/Source/include/mafianet/CloudClient.h deleted file mode 100644 index 19f909eaa..000000000 --- a/vendors/mafianet/Source/include/mafianet/CloudClient.h +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file CloudClient.h -/// \brief Queries CloudMemoryServer to download data that other clients have uploaded -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_CloudClient==1 - -#ifndef __CLOUD_CLIENT_H -#define __CLOUD_CLIENT_H - -#include "PluginInterface2.h" -#include "CloudCommon.h" -#include "memoryoverride.h" -#include "DS_Hash.h" - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; -class CloudClientCallback; - -/// \defgroup CLOUD_GROUP CloudComputing -/// \brief Contains the CloudClient and CloudServer plugins -/// \details The CloudServer plugins operates on requests from the CloudClient plugin. The servers are in a fully connected mesh topology, which the clients are connected to any server. Clients can interact with each other by posting and subscribing to memory updates, without being directly connected or even knowing about each other. -/// \ingroup PLUGINS_GROUP - -/// \brief Performs Post() and Get() operations on CloudMemoryServer -/// \details A CloudClient is a computer connected to one or more servers in a cloud configuration. Operations by one CloudClient can be received and subscribed to by other instances of CloudClient, without those clients being connected, even on different servers. -/// \ingroup CLOUD_GROUP -class RAK_DLL_EXPORT CloudClient : public PluginInterface2 -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(CloudClient) - - CloudClient(); - virtual ~CloudClient(); - - /// \brief Set the default callbacks for OnGetReponse(), OnSubscriptionNotification(), and OnSubscriptionDataDeleted() - /// \details Pointers to CloudAllocator and CloudClientCallback can be stored by the system if desired. If a callback is not provided to OnGetReponse(), OnSubscriptionNotification(), OnSubscriptionDataDeleted(), the callback passed here will be used instead. - /// \param[in] _allocator An instance of CloudAllocator - /// \param[in] _callback An instance of CloudClientCallback - virtual void SetDefaultCallbacks(CloudAllocator *_allocator, CloudClientCallback *_callback); - - /// \brief Uploads data to the cloud - /// \details Data uploaded to the cloud will be stored by the server sent to, identified by \a systemIdentifier. - /// As long as you are connected to this server, the data will persist. Queries for that data by the Get() operation will - /// return the RakNetGUID and SystemAddress of the uploader, as well as the data itself. - /// Furthermore, if any clients are subscribed to the particular CloudKey passed, those clients will get update notices that the data has changed - /// Passing data with the same \a cloudKey more than once will overwrite the prior value. - /// This call will silently fail if CloudServer::SetMaxUploadBytesPerClient() is exceeded - /// \param[in] cloudKey Identifies the data being uploaded - /// \param[in] data A pointer to data to upload. This pointer does not need to persist past the call - /// \param[in] dataLengthBytes The length in bytes of \a data - /// \param[in] systemIdentifier A remote system running CloudServer that we are already connected to. - virtual void Post(CloudKey *cloudKey, const unsigned char *data, uint32_t dataLengthBytes, RakNetGUID systemIdentifier); - - /// \brief Releases one or more data previously uploaded with Post() - /// \details If a remote system has subscribed to one or more of the \a keys uploaded, they will get ID_CLOUD_SUBSCRIPTION_NOTIFICATION notifications containing the last value uploaded before deletions - /// \param[in] cloudKey Identifies the data to release. It is possible to remove uploads from multiple Post() calls at once. - /// \param[in] systemIdentifier A remote system running CloudServer that we are already connected to. - virtual void Release(DataStructures::List &keys, RakNetGUID systemIdentifier); - - /// \brief Gets data from the cloud - /// \details For a given query containing one or more keys, return data that matches those keys. - /// The values will be returned in the ID_CLOUD_GET_RESPONSE packet, which should be passed to OnGetReponse() and will invoke CloudClientCallback::OnGet() - /// CloudQuery::startingRowIndex is used to skip the first n values that would normally be returned.. - /// CloudQuery::maxRowsToReturn is used to limit the number of rows returned. The number of rows returned may also be limited by CloudServer::SetMaxBytesPerDownload(); - /// CloudQuery::subscribeToResults if set to true, will cause ID_CLOUD_SUBSCRIPTION_NOTIFICATION to be returned to us when any of the keys in the query are updated or are deleted. - /// ID_CLOUD_GET_RESPONSE will be returned even if subscribing to the result list. Only later updates will return ID_CLOUD_SUBSCRIPTION_NOTIFICATION. - /// Calling Get() with CloudQuery::subscribeToResults false, when you are already subscribed, does not remove the subscription. Use Unsubscribe() for this. - /// Resubscribing using the same CloudKey but a different or no \a specificSystems overwrites the subscribed systems for those keys. - /// \param[in] cloudQuery One or more keys, and optional parameters to perform with the Get - /// \param[in] systemIdentifier A remote system running CloudServer that we are already connected to. - /// \param[in] specificSystems It is possible to get or subscribe to updates only for specific uploading CloudClient instances. Pass the desired instances here. The overload that does not have the specificSystems parameter is treated as subscribing to all updates from all clients. - virtual bool Get(CloudQuery *cloudQuery, RakNetGUID systemIdentifier); - virtual bool Get(CloudQuery *cloudQuery, DataStructures::List &specificSystems, RakNetGUID systemIdentifier); - virtual bool Get(CloudQuery *cloudQuery, DataStructures::List &specificSystems, RakNetGUID systemIdentifier); - - /// \brief Unsubscribe from updates previously subscribed to using Get() with the CloudQuery::subscribeToResults set to true - /// The \a keys and \a specificSystems parameters are logically treated as AND when checking subscriptions on the server - /// The overload that does not take specificSystems unsubscribes to all passed keys, regardless of system - /// You cannot unsubscribe specific systems when previously subscribed to updates from any system. To do this, first Unsubscribe() from all systems, and call Get() with the \a specificSystems parameter explicilty listing the systems you want to subscribe to. - virtual void Unsubscribe(DataStructures::List &keys, RakNetGUID systemIdentifier); - virtual void Unsubscribe(DataStructures::List &keys, DataStructures::List &specificSystems, RakNetGUID systemIdentifier); - virtual void Unsubscribe(DataStructures::List &keys, DataStructures::List &specificSystems, RakNetGUID systemIdentifier); - - /// \brief Call this when you get ID_CLOUD_GET_RESPONSE - /// If \a callback or \a allocator are 0, the default callbacks passed to SetDefaultCallbacks() are used - /// \param[in] packet Packet structure returned from RakPeerInterface - /// \param[in] _callback Callback to be called from the function containing output parameters. If 0, default is used. - /// \param[in] _allocator Allocator to be used to allocate data. If 0, default is used. - virtual void OnGetReponse(Packet *packet, CloudClientCallback *_callback=0, CloudAllocator *_allocator=0); - - /// \brief Call this when you get ID_CLOUD_GET_RESPONSE - /// Different form of OnGetReponse that returns to a structure that you pass, instead of using a callback - /// You are responsible for deallocation with this form - /// If \a allocator is 0, the default callback passed to SetDefaultCallbacks() are used - /// \param[out] cloudQueryResult A pointer to a structure that will be filled out with data - /// \param[in] packet Packet structure returned from RakPeerInterface - /// \param[in] _allocator Allocator to be used to allocate data. If 0, default is used. - virtual void OnGetReponse(CloudQueryResult *cloudQueryResult, Packet *packet, CloudAllocator *_allocator=0); - - /// \brief Call this when you get ID_CLOUD_SUBSCRIPTION_NOTIFICATION - /// If \a callback or \a allocator are 0, the default callbacks passed to SetDefaultCallbacks() are used - /// \param[in] packet Packet structure returned from RakPeerInterface - /// \param[in] _callback Callback to be called from the function containing output parameters. If 0, default is used. - /// \param[in] _allocator Allocator to be used to allocate data. If 0, default is used. - virtual void OnSubscriptionNotification(Packet *packet, CloudClientCallback *_callback=0, CloudAllocator *_allocator=0); - - /// \brief Call this when you get ID_CLOUD_SUBSCRIPTION_NOTIFICATION - /// Different form of OnSubscriptionNotification that returns to a structure that you pass, instead of using a callback - /// You are responsible for deallocation with this form - /// If \a allocator is 0, the default callback passed to SetDefaultCallbacks() are used - /// \param[out] wasUpdated If true, the row was updated. If false, it was deleted. \a result will contain the last value just before deletion - /// \param[out] row A pointer to a structure that will be filled out with data - /// \param[in] packet Packet structure returned from RakPeerInterface - /// \param[in] _allocator Allocator to be used to allocate data. If 0, default is used. - virtual void OnSubscriptionNotification(bool *wasUpdated, CloudQueryRow *row, Packet *packet, CloudAllocator *_allocator=0); - - /// If you never specified an allocator, and used the non-callback form of OnGetReponse(), deallocate cloudQueryResult with this function - virtual void DeallocateWithDefaultAllocator(CloudQueryResult *cloudQueryResult); - - /// If you never specified an allocator, and used the non-callback form of OnSubscriptionNotification(), deallocate row with this function - virtual void DeallocateWithDefaultAllocator(CloudQueryRow *row); - -protected: - PluginReceiveResult OnReceive(Packet *packet); - - CloudClientCallback *callback; - CloudAllocator *allocator; - - CloudAllocator unsetDefaultAllocator; -}; - -/// \ingroup CLOUD_GROUP -/// Parses ID_CLOUD_GET_RESPONSE and ID_CLOUD_SUBSCRIPTION_NOTIFICATION in a convenient callback form -class RAK_DLL_EXPORT CloudClientCallback -{ -public: - CloudClientCallback() {} - virtual ~CloudClientCallback() {} - - /// \brief Called in response to ID_CLOUD_GET_RESPONSE - /// \param[out] result Contains the original query passed to Get(), and a list of rows returned. - /// \param[out] deallocateRowsAfterReturn CloudQueryResult::rowsReturned will be deallocated after the function returns by default. Set to false to not deallocate these pointers. The pointers are allocated through CloudAllocator. - virtual void OnGet(MafiaNet::CloudQueryResult *result, bool *deallocateRowsAfterReturn) {(void) result; (void) deallocateRowsAfterReturn;} - - /// \brief Called in response to ID_CLOUD_SUBSCRIPTION_NOTIFICATION - /// \param[out] result Contains the row updated - /// \param[out] wasUpdated If true, the row was updated. If false, it was deleted. \a result will contain the last value just before deletion - /// \param[out] deallocateRowAfterReturn \a result will be deallocated after the function returns by default. Set to false to not deallocate these pointers. The pointers are allocated through CloudAllocator. - virtual void OnSubscriptionNotification(MafiaNet::CloudQueryRow *result, bool wasUpdated, bool *deallocateRowAfterReturn) {(void) result; (void) wasUpdated; (void) deallocateRowAfterReturn;} -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/CloudCommon.h b/vendors/mafianet/Source/include/mafianet/CloudCommon.h deleted file mode 100644 index 7ddb130e8..000000000 --- a/vendors/mafianet/Source/include/mafianet/CloudCommon.h +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_CloudClient==1 || _RAKNET_SUPPORT_CloudServer==1 - -#ifndef __CLOUD_COMMON_H -#define __CLOUD_COMMON_H - -#include "types.h" -#include "string.h" - -namespace MafiaNet -{ - -class BitStream; -struct CloudQueryRow; - -/// Allocates CloudQueryRow and the row data. Override to use derived classes or different allocators -/// \ingroup CLOUD_GROUP -class RAK_DLL_EXPORT CloudAllocator -{ -public: - CloudAllocator() {} - virtual ~CloudAllocator() {} - - /// \brief Allocate a row - virtual CloudQueryRow* AllocateCloudQueryRow(void); - /// \brief Free a row - virtual void DeallocateCloudQueryRow(CloudQueryRow *row); - /// \brief Allocate CloudQueryRow::data - virtual unsigned char *AllocateRowData(uint32_t bytesNeededForData); - /// \brief Free CloudQueryRow::data - virtual void DeallocateRowData(void *data); -}; - -/// Serves as a key to identify data uploaded to or queried from the server. -/// \ingroup CLOUD_GROUP -struct RAK_DLL_EXPORT CloudKey -{ - CloudKey() {} - CloudKey(MafiaNet::RakString _primaryKey, uint32_t _secondaryKey) : primaryKey(_primaryKey), secondaryKey(_secondaryKey) {} - ~CloudKey() {} - - /// Identifies the primary key. This is intended to be a major category, such as the name of the application - /// Must be non-empty - MafiaNet::RakString primaryKey; - - /// Identifies the secondary key. This is intended to be a subcategory enumeration, such as PLAYER_LIST or RUNNING_SCORES - uint32_t secondaryKey; - - /// \internal - void Serialize(bool writeToBitstream, BitStream *bitStream); -}; - -/// \internal -int CloudKeyComp(const CloudKey &key, const CloudKey &data); - -/// Data members used to query the cloud -/// \ingroup CLOUD_GROUP -struct RAK_DLL_EXPORT CloudQuery -{ - CloudQuery() {startingRowIndex=0; maxRowsToReturn=0; subscribeToResults=false;} - - /// List of keys to query. Must be at least of length 1. - /// This query is run on uploads from all clients, and those that match the combination of primaryKey and secondaryKey are potentially returned - /// If you pass more than one key at a time, the results are concatenated so if you need to differentiate between queries then send two different queries - DataStructures::List keys; - - /// If limiting the number of rows to return, this is the starting offset into the list. Has no effect unless maxRowsToReturn is > 0 - uint32_t startingRowIndex; - - /// Maximum number of rows to return. Actual number may still be less than this. Pass 0 to mean no-limit. - uint32_t maxRowsToReturn; - - /// If true, automatically get updates as the results returned to you change. Unsubscribe with CloudMemoryClient::Unsubscribe() - bool subscribeToResults; - - /// \internal - void Serialize(bool writeToBitstream, BitStream *bitStream); -}; - -/// \ingroup CLOUD_GROUP -struct RAK_DLL_EXPORT CloudQueryRow -{ - /// Key used to identify this data - CloudKey key; - - /// Data uploaded - unsigned char *data; - - /// Length of data uploaded - uint32_t length; - - /// System address of server that is holding this data, and the client is connected to - SystemAddress serverSystemAddress; - - /// System address of client that uploaded this data - SystemAddress clientSystemAddress; - - /// RakNetGUID of server that is holding this data, and the client is connected to - RakNetGUID serverGUID; - - /// RakNetGUID of client that uploaded this data - RakNetGUID clientGUID; - - /// \internal - void Serialize(bool writeToBitstream, BitStream *bitStream, CloudAllocator *allocator); -}; - -/// \ingroup CLOUD_GROUP -struct RAK_DLL_EXPORT CloudQueryResult -{ - /// Query originally passed to Download() - CloudQuery cloudQuery; - - /// Results returned from query. If there were multiple keys in CloudQuery::keys then see resultKeyIndices - DataStructures::List rowsReturned; - - /// If there were multiple keys in CloudQuery::keys, then each key is processed in order and the result concatenated to rowsReturned - /// The starting index of each query is written to resultKeyIndices - /// For example, if CloudQuery::keys had 4 keys, returning 3 rows, 0, rows, 5 rows, and 12 rows then - /// resultKeyIndices would be 0, 3, 3, 8 - DataStructures::List resultKeyIndices; - - /// Whatever was passed to CloudClient::Get() as CloudQuery::subscribeToResults - bool subscribeToResults; - - /// \internal - void Serialize(bool writeToBitstream, BitStream *bitStream, CloudAllocator *allocator); - /// \internal - void SerializeHeader(bool writeToBitstream, BitStream *bitStream); - /// \internal - void SerializeNumRows(bool writeToBitstream, uint32_t &numRows, BitStream *bitStream); - /// \internal - void SerializeCloudQueryRows(bool writeToBitstream, uint32_t &numRows, BitStream *bitStream, CloudAllocator *allocator); -}; - -} // Namespace MafiaNet - -#endif // __CLOUD_COMMON_H - -#endif // #if _RAKNET_SUPPORT_CloudClient==1 || _RAKNET_SUPPORT_CloudServer==1 diff --git a/vendors/mafianet/Source/include/mafianet/CloudServer.h b/vendors/mafianet/Source/include/mafianet/CloudServer.h deleted file mode 100644 index 75d7917bd..000000000 --- a/vendors/mafianet/Source/include/mafianet/CloudServer.h +++ /dev/null @@ -1,388 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file CloudServer.h -/// \brief Stores client data, and allows cross-server communication to retrieve this data -/// \details TODO -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_CloudServer==1 - -#ifndef __CLOUD_SERVER_H -#define __CLOUD_SERVER_H - -#include "PluginInterface2.h" -#include "memoryoverride.h" -#include "NativeTypes.h" -#include "string.h" -#include "DS_Hash.h" -#include "CloudCommon.h" -#include "DS_OrderedList.h" - -/// If the data is smaller than this value, an allocation is avoid. However, this value exists for every row -#define CLOUD_SERVER_DATA_STACK_SIZE 32 - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; - -/// \brief Zero or more instances of CloudServerQueryFilter can be attached to CloudServer to restrict client queries -/// All attached instances of CloudServerQueryFilter on each corresponding operation, from all directly connected clients -/// If any attached instance returns false for a given operation, that operation is silently rejected -/// \ingroup CLOUD_GROUP -class RAK_DLL_EXPORT CloudServerQueryFilter -{ -public: - CloudServerQueryFilter() {} - virtual ~CloudServerQueryFilter() {} - - /// Called when a local client wants to post data - /// \return true to allow, false to reject - virtual bool OnPostRequest(RakNetGUID clientGuid, SystemAddress clientAddress, CloudKey key, uint32_t dataLength, const char *data)=0; - - /// Called when a local client wants to release data that it has previously uploaded - /// \return true to allow, false to reject - virtual bool OnReleaseRequest(RakNetGUID clientGuid, SystemAddress clientAddress, DataStructures::List &cloudKeys)=0; - - /// Called when a local client wants to query data - /// If you return false, the client will get no response at all - /// \return true to allow, false to reject - virtual bool OnGetRequest(RakNetGUID clientGuid, SystemAddress clientAddress, CloudQuery &query, DataStructures::List &specificSystems)=0; - - /// Called when a local client wants to stop getting updates for data - /// If you return false, the client will keep getting updates for that data - /// \return true to allow, false to reject - virtual bool OnUnsubscribeRequest(RakNetGUID clientGuid, SystemAddress clientAddress, DataStructures::List &cloudKeys, DataStructures::List &specificSystems)=0; -}; - -/// \brief Stores client data, and allows cross-server communication to retrieve this data -/// \ingroup CLOUD_GROUP -class RAK_DLL_EXPORT CloudServer : public PluginInterface2, CloudAllocator -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(CloudServer) - - CloudServer(); - virtual ~CloudServer(); - - /// \brief Max bytes a client can upload - /// Data in excess of this value is silently ignored - /// defaults to 0 (unlimited) - /// \param[in] bytes Max bytes a client can upload. 0 means unlimited. - void SetMaxUploadBytesPerClient(uint64_t bytes); - - /// \brief Max bytes returned by a download. If the number of bytes would exceed this amount, the returned list is truncated - /// However, if this would result in no rows downloaded, then one row will be returned. - /// \param[in] bytes Max bytes a client can download from a single Get(). 0 means unlimited. - void SetMaxBytesPerDownload(uint64_t bytes); - - /// \brief Add a server, which is assumed to be connected in a fully connected mesh to all other servers and also running the CloudServer plugin - /// The other system must also call AddServer before getting the subscription data, or it will be rejected. - /// Sending a message telling the other system to call AddServer(), followed by calling AddServer() locally, would be sufficient for this to work. - /// \note This sends subscription data to the other system, using MafiaNet::Reliability::ReliableOrdered on channel 0 - /// \param[in] systemIdentifier Identifier of the remote system - void AddServer(RakNetGUID systemIdentifier); - - /// \brief Removes a server added through AddServer() - /// \param[in] systemIdentifier Identifier of the remote system - void RemoveServer(RakNetGUID systemIdentifier); - - /// Return list of servers added with AddServer() - /// \param[out] remoteServers List of servers added - void GetRemoteServers(DataStructures::List &remoteServersOut); - - /// \brief Frees all memory. Does not remove query filters - void Clear(void); - - /// \brief Report the specified SystemAddress to client queries, rather than what RakPeer reads. - /// This is useful if you already know your public IP - /// This only applies to future updates, so call it before updating to apply to all queries - /// \param[in] forcedAddress The systmeAddress to return in queries. Use UNASSIGNED_SYSTEM_ADDRESS (default) to use what RakPeer returns - void ForceExternalSystemAddress(SystemAddress forcedAddress); - - /// \brief Adds a callback called on each query. If all filters returns true for an operation, the operation is allowed. - /// If the filter was already added, the function silently fails - /// \param[in] filter An externally allocated instance of CloudServerQueryFilter. The instance must remain valid until it is removed with RemoveQueryFilter() or RemoveAllQueryFilters() - void AddQueryFilter(CloudServerQueryFilter* filter); - - /// \brief Removes a callback added with AddQueryFilter() - /// The instance is not deleted, only unreferenced. It is up to the user to delete the instance, if necessary - /// \param[in] filter An externally allocated instance of CloudServerQueryFilter. The instance must remain valid until it is removed with RemoveQueryFilter() or RemoveAllQueryFilters() - void RemoveQueryFilter(CloudServerQueryFilter* filter); - - /// \brief Removes all instances of CloudServerQueryFilter added with AddQueryFilter(). - /// The instances are not deleted, only unreferenced. It is up to the user to delete the instances, if necessary - void RemoveAllQueryFilters(void); - -protected: - virtual void Update(void); - virtual PluginReceiveResult OnReceive(Packet *packet); - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - virtual void OnRakPeerShutdown(void); - - - virtual void OnPostRequest(Packet *packet); - virtual void OnReleaseRequest(Packet *packet); - virtual void OnGetRequest(Packet *packet); - virtual void OnUnsubscribeRequest(Packet *packet); - virtual void OnServerToServerGetRequest(Packet *packet); - virtual void OnServerToServerGetResponse(Packet *packet); - - uint64_t maxUploadBytesPerClient, maxBytesPerDowload; - - // ---------------------------------------------------------------------------- - // For a given data key, quickly look up one or all systems that have uploaded - // ---------------------------------------------------------------------------- - struct CloudData - { - CloudData() {} - ~CloudData() {if (allocatedData) rakFree_Ex(allocatedData, _FILE_AND_LINE_);} - bool IsUnused(void) const {return isUploaded==false && specificSubscribers.Size()==0;} - void Clear(void) {if (dataPtr==allocatedData) rakFree_Ex(allocatedData, _FILE_AND_LINE_); allocatedData=0; dataPtr=0; dataLengthBytes=0; isUploaded=false;} - - unsigned char stackData[CLOUD_SERVER_DATA_STACK_SIZE]; - unsigned char *allocatedData; // Uses allocatedData instead of stackData if length of data exceeds CLOUD_SERVER_DATA_STACK_SIZE - unsigned char *dataPtr; // Points to either stackData or allocatedData - uint32_t dataLengthBytes; - bool isUploaded; - - /// System address of server that is holding this data, and the client is connected to - SystemAddress serverSystemAddress; - - /// System address of client that uploaded this data - SystemAddress clientSystemAddress; - - /// RakNetGUID of server that is holding this data, and the client is connected to - RakNetGUID serverGUID; - - /// RakNetGUID of client that uploaded this data - RakNetGUID clientGUID; - - /// When the key data changes from this particular system, notify these subscribers - /// This list mutually exclusive with CloudDataList::nonSpecificSubscribers - DataStructures::OrderedList specificSubscribers; - }; - void WriteCloudQueryRowFromResultList(unsigned int i, DataStructures::List &cloudDataResultList, DataStructures::List &cloudKeyResultList, BitStream *bsOut); - void WriteCloudQueryRowFromResultList(DataStructures::List &cloudDataResultList, DataStructures::List &cloudKeyResultList, BitStream *bsOut); - - static int KeyDataPtrComp( const RakNetGUID &key, CloudData* const &data ); - struct CloudDataList - { - bool IsUnused(void) const {return keyData.Size()==0 && nonSpecificSubscribers.Size()==0;} - bool IsNotUploaded(void) const {return uploaderCount==0;} - bool RemoveSubscriber(RakNetGUID g) { - bool objectExists; - unsigned int index; - index = nonSpecificSubscribers.GetIndexFromKey(g, &objectExists); - if (objectExists) - { - subscriberCount--; - nonSpecificSubscribers.RemoveAtIndex(index); - return true; - } - return false; - } - - unsigned int uploaderCount, subscriberCount; - CloudKey key; - - // Data uploaded from or subscribed to for various systems - DataStructures::OrderedList keyData; - - /// When the key data changes from any system, notify these subscribers - /// This list mutually exclusive with CloudData::specificSubscribers - DataStructures::OrderedList nonSpecificSubscribers; - }; - - static int KeyDataListComp( const CloudKey &key, CloudDataList * const &data ); - DataStructures::OrderedList dataRepository; - - struct KeySubscriberID - { - CloudKey key; - DataStructures::OrderedList specificSystemsSubscribedTo; - }; - static int KeySubscriberIDComp(const CloudKey &key, KeySubscriberID * const &data ); - - // Remote systems - struct RemoteCloudClient - { - bool IsUnused(void) const {return uploadedKeys.Size()==0 && subscribedKeys.Size()==0;} - - DataStructures::OrderedList uploadedKeys; - DataStructures::OrderedList subscribedKeys; - uint64_t uploadedBytes; - }; - DataStructures::Hash remoteSystems; - - // For a given user, release all subscribed and uploaded keys - void ReleaseSystem(RakNetGUID clientAddress ); - - // For a given user, release a set of keys - void ReleaseKeys(RakNetGUID clientAddress, DataStructures::List &keys ); - - void NotifyClientSubscribersOfDataChange( CloudData *cloudData, CloudKey &key, DataStructures::OrderedList &subscribers, bool wasUpdated ); - void NotifyClientSubscribersOfDataChange( CloudQueryRow *row, DataStructures::OrderedList &subscribers, bool wasUpdated ); - void NotifyServerSubscribersOfDataChange( CloudData *cloudData, CloudKey &key, bool wasUpdated ); - - struct RemoteServer - { - RakNetGUID serverAddress; - // This server needs to know about these keys when they are updated or deleted - DataStructures::OrderedList subscribedKeys; - // This server has uploaded these keys, and needs to know about Get() requests - DataStructures::OrderedList uploadedKeys; - - // Just for processing - bool workingFlag; - - // If false, we don't know what keys they have yet, so send everything - bool gotSubscribedAndUploadedKeys; - }; - - static int RemoteServerComp(const RakNetGUID &key, RemoteServer* const &data ); - DataStructures::OrderedList remoteServers; - - struct BufferedGetResponseFromServer - { - void Clear(CloudAllocator *allocator); - - RakNetGUID serverAddress; - CloudQueryResult queryResult; - bool gotResult; - }; - - struct CloudQueryWithAddresses - { - // Inputs - CloudQuery cloudQuery; - DataStructures::List specificSystems; - - void Serialize(bool writeToBitstream, BitStream *bitStream); - }; - - static int BufferedGetResponseFromServerComp(const RakNetGUID &key, BufferedGetResponseFromServer* const &data ); - struct GetRequest - { - void Clear(CloudAllocator *allocator); - bool AllRemoteServersHaveResponded(void) const; - CloudQueryWithAddresses cloudQueryWithAddresses; - - // When request started. If takes too long for a response from another system, can abort remaining systems - MafiaNet::Time requestStartTime; - - // Assigned by server that gets the request to identify response. See nextGetRequestId - uint32_t requestId; - - RakNetGUID requestingClient; - - DataStructures::OrderedList remoteServerResponses; - }; - static int GetRequestComp(const uint32_t &key, GetRequest* const &data ); - DataStructures::OrderedList getRequests; - MafiaNet::Time nextGetRequestsCheck; - - uint32_t nextGetRequestId; - - void ProcessAndTransmitGetRequest(GetRequest *getRequest); - - void ProcessCloudQueryWithAddresses( - CloudServer::CloudQueryWithAddresses &cloudQueryWithAddresses, - DataStructures::List &cloudDataResultList, - DataStructures::List &cloudKeyResultList - ); - - void SendUploadedAndSubscribedKeysToServer( RakNetGUID systemAddress ); - void SendUploadedKeyToServers( CloudKey &cloudKey ); - void SendSubscribedKeyToServers( CloudKey &cloudKey ); - void RemoveUploadedKeyFromServers( CloudKey &cloudKey ); - void RemoveSubscribedKeyFromServers( CloudKey &cloudKey ); - - void OnSendUploadedAndSubscribedKeysToServer( Packet *packet ); - void OnSendUploadedKeyToServers( Packet *packet ); - void OnSendSubscribedKeyToServers( Packet *packet ); - void OnRemoveUploadedKeyFromServers( Packet *packet ); - void OnRemoveSubscribedKeyFromServers( Packet *packet ); - void OnServerDataChanged( Packet *packet ); - - void GetServersWithUploadedKeys( - DataStructures::List &keys, - DataStructures::List &remoteServersWithData - ); - - CloudServer::CloudDataList *GetOrAllocateCloudDataList(CloudKey key, bool *dataRepositoryExists, unsigned int &dataRepositoryIndex); - - void UnsubscribeFromKey(RemoteCloudClient *remoteCloudClient, RakNetGUID remoteCloudClientGuid, unsigned int keySubscriberIndex, CloudKey &cloudKey, DataStructures::List &specificSystems); - void RemoveSpecificSubscriber(RakNetGUID specificSubscriber, CloudDataList *cloudDataList, RakNetGUID remoteCloudClientGuid); - - DataStructures::List queryFilters; - - SystemAddress forceAddress; -}; - - -} // namespace MafiaNet - -#endif - - -// Key subscription -// -// A given system can subscribe to one or more keys. -// The subscription can be further be defined as only subscribing to keys uploaded by or changed by a given system. -// It is possible to subscribe to keys not yet uploaded, or uploaded to another system -// -// Operations: -// -// 1. SubscribeToKey() - Get() operation with subscription -// A. Add to key subscription list for the client, which contains a keyId / specificUploaderList pair -// B. Send to remote servers that for this key, they should send us updates -// C. (Done, get operation returns current values) -// -// 2. UpdateData() - Post() operation -// A. Find all subscribers to this data, for the uploading system. -// B. Send them the uploaded data -// C. Find all servers that subscribe to this data -// D. Send them the uploaded data -// -// 3. DeleteData() - Release() operation -// A. Find all subscribers to this data, for the deleting system. -// B. Inform them of the deletion -// C. Find all servers that subscribe to this data -// D. Inform them of the deletion -// -// 4. Unsubscribe() -// A. Find this subscriber, and remove their subscription -// B. If no one else is subscribing to this key for any system, notify remote servers we no longer need subscription updates -// -// Internal operations: -// -// 1. Find if any connected client has subscribed to a given key -// A. This is used add and remove our subscription for this key to remote servers -// -// 2. For a given key and updating address, find all connected clients that care -// A. First find connected clients that have subscribed to this key, regardless of address -// B. Then find connected clients that have subscribed to this key for this particular address -// -// 3. Find all remote servers that have subscribed to a given key -// A. This is so when the key is updated or deleted, we know who to send it to -// -// 4. For a given client (such as on disconnect), remove all records of their subscriptions - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/CommandParserInterface.h b/vendors/mafianet/Source/include/mafianet/CommandParserInterface.h deleted file mode 100644 index 17f9312c5..000000000 --- a/vendors/mafianet/Source/include/mafianet/CommandParserInterface.h +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file CommandParserInterface.h -/// \brief Contains CommandParserInterface , from which you derive custom command parsers -/// - - -#ifndef __COMMAND_PARSER_INTERFACE -#define __COMMAND_PARSER_INTERFACE - -#include "memoryoverride.h" -#include "types.h" -#include "DS_OrderedList.h" -#include "Export.h" - -namespace MafiaNet -{ -/// Forward declarations -class TransportInterface; - -/// \internal -/// Contains the information related to one command registered with RegisterCommand() -/// Implemented so I can have an automatic help system via SendCommandList() -struct RAK_DLL_EXPORT RegisteredCommand -{ - const char *command; - const char *commandHelp; - unsigned char parameterCount; -}; - -/// List of commands registered with RegisterCommand() -int RAK_DLL_EXPORT RegisteredCommandComp( const char* const & key, const RegisteredCommand &data ); - -/// \brief The interface used by command parsers. -/// \details CommandParserInterface provides a set of functions and interfaces that plug into the ConsoleServer class. -/// Each CommandParserInterface works at the same time as other interfaces in the system. -class RAK_DLL_EXPORT CommandParserInterface -{ -public: - CommandParserInterface(); - virtual ~CommandParserInterface(); - - /// You are responsible for overriding this function and returning a static string, which will identifier your parser. - /// This should return a static string - /// \return The name that you return. - virtual const char *GetName(void) const=0; - - /// \brief A callback for when \a systemAddress has connected to us. - /// \param[in] systemAddress The player that has connected. - /// \param[in] transport The transport interface that sent us this information. Can be used to send messages to this or other players. - virtual void OnNewIncomingConnection(const SystemAddress &systemAddress, TransportInterface *transport); - - /// \brief A callback for when \a systemAddress has disconnected, either gracefully or forcefully - /// \param[in] systemAddress The player that has disconnected. - /// \param[in] transport The transport interface that sent us this information. - virtual void OnConnectionLost(const SystemAddress &systemAddress, TransportInterface *transport); - - /// \brief A callback for when you are expected to send a brief description of your parser to \a systemAddress - /// \param[in] transport The transport interface we can use to write to - /// \param[in] systemAddress The player that requested help. - virtual void SendHelp(TransportInterface *transport, const SystemAddress &systemAddress)=0; - - /// \brief Given \a command with parameters \a parameterList , do whatever processing you wish. - /// \param[in] command The command to process - /// \param[in] numParameters How many parameters were passed along with the command - /// \param[in] parameterList The list of parameters. parameterList[0] is the first parameter and so on. - /// \param[in] transport The transport interface we can use to write to - /// \param[in] systemAddress The player that sent this command. - /// \param[in] originalString The string that was actually sent over the network, in case you want to do your own parsing - virtual bool OnCommand(const char *command, unsigned numParameters, char **parameterList, TransportInterface *transport, const SystemAddress &systemAddress, const char *originalString)=0; - - /// \brief This is called every time transport interface is registered. - /// \details If you want to save a copy of the TransportInterface pointer - /// This is the place to do it - /// \param[in] transport The new TransportInterface - virtual void OnTransportChange(TransportInterface *transport); - - /// \internal - /// Scan commandList and return the associated array - /// \param[in] command The string to find - /// \param[out] rc Contains the result of this operation - /// \return True if we found the command, false otherwise - virtual bool GetRegisteredCommand(const char *command, RegisteredCommand *rc); - - /// \internal - /// Goes through str, replacing the delineating character with 0's. - /// \param[in] str The string sent by the transport interface - /// \param[in] delineator The character to scan for to use as a delineator - /// \param[in] delineatorToggle When encountered the delineator replacement is toggled on and off - /// \param[out] numParameters How many pointers were written to \a parameterList - /// \param[out] parameterList An array of pointers to characters. Will hold pointers to locations inside \a str - /// \param[in] parameterListLength How big the \a parameterList array is - static void ParseConsoleString(char *str, const char delineator, unsigned char delineatorToggle, unsigned *numParameters, char **parameterList, unsigned parameterListLength); - - /// \internal - /// Goes through the variable commandList and sends the command portion of each struct - /// \param[in] transport The transport interface we can use to write to - /// \param[in] systemAddress The player to write to - virtual void SendCommandList(TransportInterface *transport, const SystemAddress &systemAddress); - - static const unsigned char VARIABLE_NUMBER_OF_PARAMETERS; - - // Currently only takes static strings - doesn't make a copy of what you pass. - // parameterCount is the number of parameters that the sender has to include with the command. - // Pass 255 to parameterCount to indicate variable number of parameters - - /// Registers a command. - /// \param[in] parameterCount How many parameters your command requires. If you want to accept a variable number of commands, pass CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS - /// \param[in] command A pointer to a STATIC string that has your command. I keep a copy of the pointer here so don't deallocate the string. - /// \param[in] commandHelp A pointer to a STATIC string that has the help information for your command. I keep a copy of the pointer here so don't deallocate the string. - virtual void RegisterCommand(unsigned char parameterCount, const char *command, const char *commandHelp); - - /// \brief Just writes a string to the remote system based on the result ( \a res ) of your operation - /// \details This is not necessary to call, but makes it easier to return results of function calls. - /// \param[in] res The result to write - /// \param[in] command The command that this result came from - /// \param[in] transport The transport interface that will be written to - /// \param[in] systemAddress The player this result will be sent to - virtual void ReturnResult(bool res, const char *command, TransportInterface *transport, const SystemAddress &systemAddress); - virtual void ReturnResult(char *res, const char *command, TransportInterface *transport, const SystemAddress &systemAddress); - virtual void ReturnResult(SystemAddress res, const char *command, TransportInterface *transport, const SystemAddress &systemAddress); - virtual void ReturnResult(int res, const char *command,TransportInterface *transport, const SystemAddress &systemAddress); - - /// \brief Just writes a string to the remote system when you are calling a function that has no return value. - /// \details This is not necessary to call, but makes it easier to return results of function calls. - /// \param[in] res The result to write - /// \param[in] command The command that this result came from - /// \param[in] transport The transport interface that will be written to - /// \param[in] systemAddress The player this result will be sent to - virtual void ReturnResult(const char *command,TransportInterface *transport, const SystemAddress &systemAddress); - -protected: - DataStructures::OrderedList commandList; -}; - -} // namespace MafiaNet - -#endif - diff --git a/vendors/mafianet/Source/include/mafianet/ConnectionGraph2.h b/vendors/mafianet/Source/include/mafianet/ConnectionGraph2.h deleted file mode 100644 index 42b61c927..000000000 --- a/vendors/mafianet/Source/include/mafianet/ConnectionGraph2.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file ConnectionGraph2.h -/// \brief Connection graph plugin, version 2. Tells new systems about existing and new connections -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_ConnectionGraph2==1 - -#ifndef __CONNECTION_GRAPH_2_H -#define __CONNECTION_GRAPH_2_H - -#include "memoryoverride.h" -#include "types.h" -#include "PluginInterface2.h" -#include "DS_List.h" -#include "DS_WeightedGraph.h" -#include "GetTime.h" -#include "Export.h" - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; - -/// \brief A one hop connection graph. -/// \details Sends ID_REMOTE_CONNECTION_LOST, ID_REMOTE_DISCONNECTION_NOTIFICATION, ID_REMOTE_NEW_INCOMING_CONNECTION
-/// All identifiers are followed by SystemAddress, then RakNetGUID -/// Also stores the list for you, which you can access with GetConnectionListForRemoteSystem -/// \ingroup CONNECTION_GRAPH_GROUP -class RAK_DLL_EXPORT ConnectionGraph2 : public PluginInterface2 -{ -public: - - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(ConnectionGraph2) - - ConnectionGraph2(); - ~ConnectionGraph2(); - - /// \brief Given a remote system identified by RakNetGUID, return the list of SystemAddresses and RakNetGUIDs they are connected to - /// \param[in] remoteSystemGuid Which system we are referring to. This only works for remote systems, not ourselves. - /// \param[out] saOut A preallocated array to hold the output list of SystemAddress. Can be 0 if you don't care. - /// \param[out] guidOut A preallocated array to hold the output list of RakNetGUID. Can be 0 if you don't care. - /// \param[in,out] outLength On input, the size of \a saOut and \a guidOut. On output, modified to reflect the number of elements actually written - /// \return True if \a remoteSystemGuid was found. Otherwise false, and \a saOut, \a guidOut remain unchanged. \a outLength will be set to 0. - bool GetConnectionListForRemoteSystem(RakNetGUID remoteSystemGuid, SystemAddress *saOut, RakNetGUID *guidOut, unsigned int *outLength); - - /// Returns if g1 is connected to g2 - bool ConnectionExists(RakNetGUID g1, RakNetGUID g2); - - /// Returns the average ping between two systems in the connection graph. Returns -1 if no connection exists between those systems - uint16_t GetPingBetweenSystems(RakNetGUID g1, RakNetGUID g2) const; - - /// Returns the system with the lowest average ping among all its connections. - /// If you need one system in the peer to peer group to relay data, have the FullyConnectedMesh2 host call this function after host migration, and use that system - RakNetGUID GetLowestAveragePingSystem(void) const; - - /// \brief If called with false, then new connections are only added to the connection graph when you call ProcessNewConnection(); - /// \details This is useful if you want to perform validation before connecting a system to a mesh, or if you want a submesh (for example a server cloud) - /// \param[in] b True to automatically call ProcessNewConnection() on any new connection, false to not do so. Defaults to true. - void SetAutoProcessNewConnections(bool b); - - /// \brief Returns value passed to SetAutoProcessNewConnections() - /// \return Value passed to SetAutoProcessNewConnections(), or the default of true if it was never called - bool GetAutoProcessNewConnections(void) const; - - /// \brief If you call SetAutoProcessNewConnections(false);, then you will need to manually call ProcessNewConnection() on new connections - /// \details On ID_NEW_INCOMING_CONNECTION or ID_CONNECTION_REQUEST_ACCEPTED, adds that system to the graph - /// Do not call ProcessNewConnection() manually otherwise - /// \param[in] The packet->SystemAddress member - /// \param[in] The packet->guid member - void AddParticipant(const SystemAddress &systemAddress, RakNetGUID rakNetGUID); - - /// Get the participants added with AddParticipant() - /// \param[out] participantList Participants added with AddParticipant(); - void GetParticipantList(DataStructures::OrderedList &participantList); - - /// \internal - struct SystemAddressAndGuid - { - SystemAddress systemAddress; - RakNetGUID guid; - uint16_t sendersPingToThatSystem; - }; - /// \internal - static int SystemAddressAndGuidComp( const SystemAddressAndGuid &key, const SystemAddressAndGuid &data ); - - /// \internal - struct RemoteSystem - { - DataStructures::OrderedList remoteConnections; - RakNetGUID guid; - }; - /// \internal - static int RemoteSystemComp( const RakNetGUID &key, RemoteSystem * const &data ); - -protected: - /// \internal - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - /// \internal - virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); - /// \internal - virtual PluginReceiveResult OnReceive(Packet *packet); - - // List of systems I am connected to, which in turn stores which systems they are connected to - DataStructures::OrderedList remoteSystems; - - bool autoProcessNewConnections; - -}; - -} // namespace MafiaNet - -#endif // #ifndef __CONNECTION_GRAPH_2_H - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/ConsoleServer.h b/vendors/mafianet/Source/include/mafianet/ConsoleServer.h deleted file mode 100644 index ed7ec1564..000000000 --- a/vendors/mafianet/Source/include/mafianet/ConsoleServer.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file ConsoleServer.h -/// \brief Contains ConsoleServer , used to plugin to your game to accept remote console-based connections -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_ConsoleServer==1 - -#ifndef __CONSOLE_SERVER_H -#define __CONSOLE_SERVER_H - -#include "memoryoverride.h" -#include "DS_List.h" -#include "types.h" -#include "Export.h" - -namespace MafiaNet -{ -/// Forward declarations -class TransportInterface; -class CommandParserInterface; - - -/// \brief The main entry point for the server portion of your remote console application support. -/// \details ConsoleServer takes one TransportInterface and one or more CommandParserInterface (s) -/// The TransportInterface will be used to send data between the server and the client. The connecting client must support the -/// protocol used by your derivation of TransportInterface . TelnetTransport and RakNetTransport are two such derivations . -/// When a command is sent by a remote console, it will be processed by your implementations of CommandParserInterface -class RAK_DLL_EXPORT ConsoleServer -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(ConsoleServer) - - ConsoleServer(); - ~ConsoleServer(); - - /// \brief Call this with a derivation of TransportInterface so that the console server can send and receive commands - /// \param[in] transportInterface Your interface to use. - /// \param[in] port The port to host on. Telnet uses port 23 by default. RakNet can use whatever you want. - void SetTransportProvider(TransportInterface *transportInterface, unsigned short port); - - /// \brief Add an implementation of CommandParserInterface to the list of command parsers. - /// \param[in] commandParserInterface The command parser referred to - void AddCommandParser(CommandParserInterface *commandParserInterface); - - /// \brief Remove an implementation of CommandParserInterface previously added with AddCommandParser(). - /// \param[in] commandParserInterface The command parser referred to - void RemoveCommandParser(CommandParserInterface *commandParserInterface); - - /// \brief Call update to read packet sent from your TransportInterface. - /// You should do this fairly frequently. - void Update(void); - - /// \brief Sets a prompt to show when waiting for user input. - /// \details Pass an empty string to clear the prompt - /// Defaults to no prompt - /// \param[in] _prompt Null-terminated string of the prompt to use. If you want a newline, be sure to use /r/n - void SetPrompt(const char *_prompt); - -protected: - void ListParsers(SystemAddress systemAddress); - void ShowPrompt(SystemAddress systemAddress); - TransportInterface *transport; - DataStructures::List commandParserList; - char* password[256]; - char *prompt; -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/DR_SHA1.h b/vendors/mafianet/Source/include/mafianet/DR_SHA1.h deleted file mode 100644 index beac1112c..000000000 --- a/vendors/mafianet/Source/include/mafianet/DR_SHA1.h +++ /dev/null @@ -1,311 +0,0 @@ -/* - 100% free public domain implementation of the SHA-1 algorithm - by Dominik Reichl - Web: http://www.dominik-reichl.de/ - - Version 2.1 - 2012-06-19 - - Deconstructor (resetting internal variables) is now only - implemented if SHA1_WIPE_VARIABLES is defined (which is the - default). - - Renamed inclusion guard to contain a GUID. - - Demo application is now using C++/STL objects and functions. - - Unicode build of the demo application now outputs the hashes of both - the ANSI and Unicode representations of strings. - - Various other demo application improvements. - - Version 2.0 - 2012-06-14 - - Added 'limits.h' include. - - Renamed inclusion guard and macros for compliancy (names beginning - with an underscore are reserved). - - Version 1.9 - 2011-11-10 - - Added Unicode test vectors. - - Improved support for hashing files using the HashFile method that - are larger than 4 GB. - - Improved file hashing performance (by using a larger buffer). - - Disabled unnecessary compiler warnings. - - Internal variables are now private. - - Version 1.8 - 2009-03-16 - - Converted project files to Visual Studio 2008 format. - - Added Unicode support for HashFile utility method. - - Added support for hashing files using the HashFile method that are - larger than 2 GB. - - HashFile now returns an error code instead of copying an error - message into the output buffer. - - GetHash now returns an error code and validates the input parameter. - - Added ReportHashStl STL utility method. - - Added REPORT_HEX_SHORT reporting mode. - - Improved Linux compatibility of test program. - - Version 1.7 - 2006-12-21 - - Fixed buffer underrun warning that appeared when compiling with - Borland C Builder (thanks to Rex Bloom and Tim Gallagher for the - patch). - - Breaking change: ReportHash writes the final hash to the start - of the buffer, i.e. it's not appending it to the string anymore. - - Made some function parameters const. - - Added Visual Studio 2005 project files to demo project. - - Version 1.6 - 2005-02-07 (thanks to Howard Kapustein for patches) - - You can set the endianness in your files, no need to modify the - header file of the CSHA1 class anymore. - - Aligned data support. - - Made support/compilation of the utility functions (ReportHash and - HashFile) optional (useful when bytes count, for example in embedded - environments). - - Version 1.5 - 2005-01-01 - - 64-bit compiler compatibility added. - - Made variable wiping optional (define SHA1_WIPE_VARIABLES). - - Removed unnecessary variable initializations. - - ROL32 improvement for the Microsoft compiler (using _rotl). - - Version 1.4 - 2004-07-22 - - CSHA1 now compiles fine with GCC 3.3 under Mac OS X (thanks to Larry - Hastings). - - Version 1.3 - 2003-08-17 - - Fixed a small memory bug and made a buffer array a class member to - ensure correct working when using multiple CSHA1 class instances at - one time. - - Version 1.2 - 2002-11-16 - - Borlands C++ compiler seems to have problems with string addition - using sprintf. Fixed the bug which caused the digest report function - not to work properly. CSHA1 is now Borland compatible. - - Version 1.1 - 2002-10-11 - - Removed two unnecessary header file includes and changed BOOL to - bool. Fixed some minor bugs in the web page contents. - - Version 1.0 - 2002-06-20 - - First official release. - - ================ Test Vectors ================ - - SHA1("abc" in ANSI) = - A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D - SHA1("abc" in Unicode LE) = - 9F04F41A 84851416 2050E3D6 8C1A7ABB 441DC2B5 - - SHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" - in ANSI) = - 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 - SHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" - in Unicode LE) = - 51D7D876 9AC72C40 9C5B0E3F 69C60ADC 9A039014 - - SHA1(A million repetitions of "a" in ANSI) = - 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F - SHA1(A million repetitions of "a" in Unicode LE) = - C4609560 A108A0C6 26AA7F2B 38A65566 739353C5 -*/ - -/* - * This file was taken from RakNet 4.082. - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications in this file are put under the public domain. - * Alternatively you are permitted to license the modifications under the MIT license, if you so desire. The - * license can be found in the license.txt file in the root directory of this source tree. - */ - -#ifndef SHA1_H_A545E61D43E9404E8D736869AB3CBFE7 -#define SHA1_H_A545E61D43E9404E8D736869AB3CBFE7 - -// KevinJ: -#include "memoryoverride.h" -#include // Needed for file access - -#include // Needed for memset and memcpy - -#include // Needed for strcat and strcpy -#include "Export.h" -//#define MAX_FILE_READ_BUFFER 8000 -#define SHA1_LENGTH 20 - - - -#if !defined(SHA1_UTILITY_FUNCTIONS) && !defined(SHA1_NO_UTILITY_FUNCTIONS) -#define SHA1_UTILITY_FUNCTIONS -#endif - -#if !defined(SHA1_STL_FUNCTIONS) && !defined(SHA1_NO_STL_FUNCTIONS) -#define SHA1_STL_FUNCTIONS -#if !defined(SHA1_UTILITY_FUNCTIONS) -#error STL functions require SHA1_UTILITY_FUNCTIONS. -#endif -#endif - - -#include - -#include - -#ifdef SHA1_UTILITY_FUNCTIONS -#include -#include -#endif - -#ifdef SHA1_STL_FUNCTIONS -#include -#endif - -#ifdef _MSC_VER -#include -#endif - -// You can define the endian mode in your files without modifying the SHA-1 -// source files. Just #define SHA1_LITTLE_ENDIAN or #define SHA1_BIG_ENDIAN -// in your files, before including the DR_SHA1.h header file. If you don't -// define anything, the class defaults to little endian. -#if !defined(SHA1_LITTLE_ENDIAN) && !defined(SHA1_BIG_ENDIAN) -#define SHA1_LITTLE_ENDIAN -#endif - -// If you want variable wiping, #define SHA1_WIPE_VARIABLES, if not, -// #define SHA1_NO_WIPE_VARIABLES. If you don't define anything, it -// defaults to wiping. -#if !defined(SHA1_WIPE_VARIABLES) && !defined(SHA1_NO_WIPE_VARIABLES) -#define SHA1_WIPE_VARIABLES -#endif - -#if defined(SHA1_HAS_TCHAR) -#include -#else -#ifdef _MSC_VER -#include -#else -#ifndef TCHAR -#define TCHAR char -#endif -#ifndef _T -#define _T(__x) (__x) -#define _tmain main -#define _tprintf printf -#define _getts gets -#define _tcslen strlen -#define _tfopen fopen -#define _tcscpy strcpy -#define _tcscat strcat -#define _sntprintf snprintf -#endif -#endif -#endif - -/////////////////////////////////////////////////////////////////////////// -// Define variable types - -#ifndef UINT_8 -#ifdef _MSC_VER // Compiling with Microsoft compiler -#define UINT_8 unsigned __int8 -#else // !_MSC_VER -#define UINT_8 unsigned char -#endif // _MSC_VER -#endif - -#ifndef UINT_32 -#ifdef _MSC_VER // Compiling with Microsoft compiler -#define UINT_32 unsigned __int32 -#else // !_MSC_VER -#if (ULONG_MAX == 0xFFFFFFFFUL) -#define UINT_32 unsigned long -#else -#define UINT_32 unsigned int -#endif -#endif // _MSC_VER -#endif // UINT_32 - -#ifndef INT_64 -#ifdef _MSC_VER // Compiling with Microsoft compiler -#define INT_64 __int64 -#else // !_MSC_VER -#define INT_64 long long -#endif // _MSC_VER -#endif // INT_64 - -#ifndef UINT_64 -#ifdef _MSC_VER // Compiling with Microsoft compiler -#define UINT_64 unsigned __int64 -#else // !_MSC_VER -#define UINT_64 unsigned long long -#endif // _MSC_VER -#endif // UINT_64 - -/////////////////////////////////////////////////////////////////////////// -// Declare SHA-1 workspace - -typedef union -{ - UINT_8 c[64]; - UINT_32 l[16]; -} SHA1_WORKSPACE_BLOCK; - -class RAK_DLL_EXPORT CSHA1 -{ -public: -#ifdef SHA1_UTILITY_FUNCTIONS - // Different formats for ReportHash(Stl) - enum REPORT_TYPE - { - REPORT_HEX = 0, - REPORT_DIGIT = 1, - REPORT_HEX_SHORT = 2 - }; -#endif - - // Constructor and destructor - CSHA1(); - -#ifdef SHA1_WIPE_VARIABLES - ~CSHA1(); -#endif - - void Reset(); - - // Hash in binary data and strings - void Update(const UINT_8* pbData, UINT_32 uLen); - -#ifdef SHA1_UTILITY_FUNCTIONS - // Hash in file contents - bool HashFile(const TCHAR* tszFileName); -#endif - - // Finalize hash; call it before using ReportHash(Stl) - void Final(); - -#ifdef SHA1_UTILITY_FUNCTIONS - bool ReportHash(TCHAR* tszReport, REPORT_TYPE rtReportType = REPORT_HEX) const; -#endif - -#ifdef SHA1_STL_FUNCTIONS - bool ReportHashStl(std::basic_string& strOut, REPORT_TYPE rtReportType = - REPORT_HEX) const; -#endif - - // Get the raw message digest (20 bytes) - bool GetHash(UINT_8* pbDest20) const; - -unsigned char * GetHash( void ) const; -// KevinJ: http://cseweb.ucsd.edu/~mihir/papers/hmac-cb.pdf - static void HMAC(unsigned char *sharedKey, int sharedKeyLength, unsigned char *data, int dataLength, unsigned char output[SHA1_LENGTH]); - -private: - // Private SHA-1 transformation - void Transform(UINT_32* pState, const UINT_8* pBuffer); - - // Member variables - UINT_32 m_state[5]; - UINT_32 m_count[2]; - UINT_32 m_reserved0[1]; // Memory alignment padding - UINT_8 m_buffer[64]; - UINT_8 m_digest[20]; - UINT_32 m_reserved1[3]; // Memory alignment padding - - UINT_8 m_workspace[64]; - SHA1_WORKSPACE_BLOCK* m_block; // SHA1 pointer to the byte array above -}; - -#endif // SHA1_H_A545E61D43E9404E8D736869AB3CBFE7 diff --git a/vendors/mafianet/Source/include/mafianet/DS_BPlusTree.h b/vendors/mafianet/Source/include/mafianet/DS_BPlusTree.h deleted file mode 100644 index 8de09b3e2..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_BPlusTree.h +++ /dev/null @@ -1,1157 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_BPlusTree.h -/// - - -#ifndef __B_PLUS_TREE_CPP -#define __B_PLUS_TREE_CPP - -#include "DS_MemoryPool.h" -#include "DS_Queue.h" -#include -#include "Export.h" - -// Java -// http://www.seanster.com/BplusTree/BplusTree.html - -// Overview -// http://babbage.clarku.edu/~achou/cs160/B+Trees/B+Trees.htm - -// Deletion -// http://dbpubs.stanford.edu:8090/pub/1995-19 - -#ifdef _MSC_VER -#pragma warning( push ) -#endif - -#include "memoryoverride.h" - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - /// Used in the BPlusTree. Used for both leaf and index nodes. - /// Don't use a constructor or destructor, due to the memory pool I am using - template - struct RAK_DLL_EXPORT Page - { - // We use the same data structure for both leaf and index nodes. - // It uses a little more memory for index nodes but reduces - // memory fragmentation, allocations, and deallocations. - bool isLeaf; - - // Used for both leaf and index nodes. - // For a leaf it means the number of elements in data - // For an index it means the number of keys and is one less than the number of children pointers. - int size; - - // Used for both leaf and index nodes. - KeyType keys[order]; - - // Used only for leaf nodes. Data is the actual data, while next is the pointer to the next leaf (for B+) - DataType data[order]; - Page *next; - Page *previous; - - // Used only for index nodes. Pointers to the children of this node. - Page *children[order+1]; - }; - - /// A BPlus tree - /// Written with efficiency and speed in mind. - template - class RAK_DLL_EXPORT BPlusTree - { - public: - struct ReturnAction - { - KeyType key1; - KeyType key2; - enum - { - NO_ACTION, - REPLACE_KEY1_WITH_KEY2, - PUSH_KEY_TO_PARENT, - SET_BRANCH_KEY, - } action; // 0=none, 1=replace key1 with key2 - }; - - BPlusTree(); - ~BPlusTree(); - void SetPoolPageSize(int size); // Set the page size for the memory pool. Optionsl - bool Get(const KeyType key, DataType &out) const; - bool Delete(const KeyType key); - bool Delete(const KeyType key, DataType &out); - bool Insert(const KeyType key, const DataType &data); - void Clear(void); - unsigned Size(void) const; - bool IsEmpty(void) const; - Page *GetListHead(void) const; - DataType GetDataHead(void) const; - void PrintLeaves(void); - void ForEachLeaf(void (*func)(Page * leaf, int index)); - void ForEachData(void (*func)(DataType input, int index)); - void PrintGraph(void); - protected: - void ValidateTreeRecursive(Page *cur); - void DeleteFromPageAtIndex(const int index, Page *cur); - static void PrintLeaf(Page * leaf, int index); - void FreePages(void); - bool GetIndexOf(const KeyType key, Page *page, int *out) const; - void ShiftKeysLeft(Page *cur); - bool CanRotateLeft(Page *cur, int childIndex); - bool CanRotateRight(Page *cur, int childIndex); - void RotateRight(Page *cur, int childIndex, ReturnAction *returnAction); - void RotateLeft(Page *cur, int childIndex, ReturnAction *returnAction); - Page* InsertIntoNode(const KeyType key, const DataType &childData, int insertionIndex, Page *nodeData, Page *cur, ReturnAction* returnAction); - Page* InsertBranchDown(const KeyType key, const DataType &data,Page *cur, ReturnAction* returnAction, bool *success); - Page* GetLeafFromKey(const KeyType key) const; - bool FindDeleteRebalance(const KeyType key, Page *cur, bool *underflow, KeyType rightRootKey, ReturnAction *returnAction, DataType &out); - bool FixUnderflow(int branchIndex, Page *cur, KeyType rightRootKey, ReturnAction *returnAction); - void ShiftNodeLeft(Page *cur); - void ShiftNodeRight(Page *cur); - - MemoryPool > pagePool; - Page *root, *leftmostLeaf; - }; - - template - BPlusTree::BPlusTree () - { - RakAssert(order>1); - root=0; - leftmostLeaf=0; - } - template - BPlusTree::~BPlusTree () - { - Clear(); - } - template - void BPlusTree::SetPoolPageSize(int size) - { - pagePool.SetPageSize(size); - } - template - bool BPlusTree::Get(const KeyType key, DataType &out) const - { - if (root==0) - return false; - - Page* leaf = GetLeafFromKey(key); - int childIndex; - - if (GetIndexOf(key, leaf, &childIndex)) - { - out=leaf->data[childIndex]; - return true; - } - return false; - } - template - void BPlusTree::DeleteFromPageAtIndex(const int index, Page *cur) - { - int i; - for (i=index; i < cur->size-1; i++) - cur->keys[i]=cur->keys[i+1]; - if (cur->isLeaf) - { - for (i=index; i < cur->size-1; i++) - cur->data[i]=cur->data[i+1]; - } - else - { - for (i=index; i < cur->size-1; i++) - cur->children[i+1]=cur->children[i+2]; - } - cur->size--; - } - template - bool BPlusTree::Delete(const KeyType key) - { - DataType temp; - return Delete(key, temp); - } - template - bool BPlusTree::Delete(const KeyType key, DataType &out) - { - if (root==0) - return false; - - ReturnAction returnAction; - returnAction.action=ReturnAction::NO_ACTION; - int childIndex; - bool underflow=false; - if (root==leftmostLeaf) - { - if (GetIndexOf(key, root, &childIndex)==false) - return false; - out=root->data[childIndex]; - DeleteFromPageAtIndex(childIndex,root); - if (root->size==0) - { - pagePool.Release(root, _FILE_AND_LINE_); - root=0; - leftmostLeaf=0; - } - return true; - } - else if (FindDeleteRebalance(key, root, &underflow,root->keys[0], &returnAction, out)==false) - return false; - -// RakAssert(returnAction.action==ReturnAction::NO_ACTION); - - if (underflow && root->size==0) - { - // Move the root down. - Page *oldRoot=root; - root=root->children[0]; - pagePool.Release(oldRoot, _FILE_AND_LINE_); - // memset(oldRoot,0,sizeof(root)); - } - - return true; - } - template - bool BPlusTree::FindDeleteRebalance(const KeyType key, Page *cur, bool *underflow, KeyType rightRootKey, ReturnAction *returnAction, DataType &out) - { - // Get index of child to follow. - int branchIndex, childIndex; - if (GetIndexOf(key, cur, &childIndex)) - branchIndex=childIndex+1; - else - branchIndex=childIndex; - - // If child is not a leaf, call recursively - if (cur->children[branchIndex]->isLeaf==false) - { - if (branchIndexsize) - rightRootKey=cur->keys[branchIndex]; // Shift right to left - else - rightRootKey=cur->keys[branchIndex-1]; // Shift center to left - - if (FindDeleteRebalance(key, cur->children[branchIndex], underflow, rightRootKey, returnAction, out)==false) - return false; - - // Call again in case the root key changed - if (branchIndexsize) - rightRootKey=cur->keys[branchIndex]; // Shift right to left - else - rightRootKey=cur->keys[branchIndex-1]; // Shift center to left - - if (returnAction->action==ReturnAction::SET_BRANCH_KEY && branchIndex!=childIndex) - { - returnAction->action=ReturnAction::NO_ACTION; - cur->keys[childIndex]=returnAction->key1; - - if (branchIndexsize) - rightRootKey=cur->keys[branchIndex]; // Shift right to left - else - rightRootKey=cur->keys[branchIndex-1]; // Shift center to left - } - } - else - { - // If child is a leaf, get the index of the key. If the item is not found, cancel delete. - if (GetIndexOf(key, cur->children[branchIndex], &childIndex)==false) - return false; - - // Delete: - // Remove childIndex from the child at branchIndex - out=cur->children[branchIndex]->data[childIndex]; - DeleteFromPageAtIndex(childIndex, cur->children[branchIndex]); - - if (childIndex==0) - { - if (branchIndex>0) - cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0]; - - if (branchIndex==0) - { - returnAction->action=ReturnAction::SET_BRANCH_KEY; - returnAction->key1=cur->children[0]->keys[0]; - } - } - - if (cur->children[branchIndex]->size < order/2) - *underflow=true; - else - *underflow=false; - } - - // Fix underflow: - if (*underflow) - { - *underflow=FixUnderflow(branchIndex, cur, rightRootKey, returnAction); - } - - return true; - } - template - bool BPlusTree::FixUnderflow(int branchIndex, Page *cur, KeyType rightRootKey, ReturnAction *returnAction) - { - // Borrow from a neighbor that has excess. - Page *source; - Page *dest; - - if (branchIndex>0 && cur->children[branchIndex-1]->size > order/2) - { - dest=cur->children[branchIndex]; - source=cur->children[branchIndex-1]; - - // Left has excess - ShiftNodeRight(dest); - if (dest->isLeaf) - { - dest->keys[0]=source->keys[source->size-1]; - dest->data[0]=source->data[source->size-1]; - } - else - { - dest->children[0]=source->children[source->size]; - dest->keys[0]=cur->keys[branchIndex-1]; - } - // Update the parent key for the child (middle) - cur->keys[branchIndex-1]=source->keys[source->size-1]; - source->size--; - - // if (branchIndex==0) - // { - // returnAction->action=ReturnAction::SET_BRANCH_KEY; - // returnAction->key1=dest->keys[0]; - // } - - // No underflow - return false; - } - else if (branchIndexsize && cur->children[branchIndex+1]->size > order/2) - { - dest=cur->children[branchIndex]; - source=cur->children[branchIndex+1]; - - // Right has excess - if (dest->isLeaf) - { - dest->keys[dest->size]=source->keys[0]; - dest->data[dest->size]=source->data[0]; - - // The first key in the leaf after shifting is the parent key for the right branch - cur->keys[branchIndex]=source->keys[1]; - -#ifdef _MSC_VER -#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant -#endif - if (order<=3 && dest->size==0) - { - if (branchIndex==0) - { - returnAction->action=ReturnAction::SET_BRANCH_KEY; - returnAction->key1=dest->keys[0]; - } - else - cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0]; - } - } - else - { - if (returnAction->action==ReturnAction::NO_ACTION) - { - returnAction->action=ReturnAction::SET_BRANCH_KEY; - returnAction->key1=dest->keys[0]; - } - - dest->keys[dest->size]=rightRootKey; - dest->children[dest->size+1]=source->children[0]; - - // The shifted off key is the leftmost key for a node - cur->keys[branchIndex]=source->keys[0]; - } - - - dest->size++; - ShiftNodeLeft(source); - - //cur->keys[branchIndex]=source->keys[0]; - -// returnAction->action=ReturnAction::SET_BRANCH_KEY; -// returnAction->key1=dest->keys[dest->size-1]; - - // No underflow - return false; - } - else - { - int sourceIndex; - - // If no neighbors have excess, merge two branches. - // - // To merge two leaves, just copy the data and keys over. - // - // To merge two branches, copy the pointers and keys over, using rightRootKey as the key for the extra pointer - if (branchIndexsize) - { - // Merge right child to current child and delete right child. - dest=cur->children[branchIndex]; - source=cur->children[branchIndex+1]; - } - else - { - // Move current child to left and delete current child - dest=cur->children[branchIndex-1]; - source=cur->children[branchIndex]; - } - - // Merge - if (dest->isLeaf) - { - for (sourceIndex=0; sourceIndexsize; sourceIndex++) - { - dest->keys[dest->size]=source->keys[sourceIndex]; - dest->data[dest->size++]=source->data[sourceIndex]; - } - } - else - { - // We want the tree root key of the source, not the current. - dest->keys[dest->size]=rightRootKey; - dest->children[dest->size++ + 1]=source->children[0]; - for (sourceIndex=0; sourceIndexsize; sourceIndex++) - { - dest->keys[dest->size]=source->keys[sourceIndex]; - dest->children[dest->size++ + 1]=source->children[sourceIndex + 1]; - } - } - -#ifdef _MSC_VER -#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant -#endif - if (order<=3 && branchIndex>0 && cur->children[branchIndex]->isLeaf) // With order==2 it is possible to delete data[0], which is not possible with higher orders. - cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0]; - - if (branchIndexsize) - { - // Update the parent key, removing the source (right) - DeleteFromPageAtIndex(branchIndex, cur); - } - else - { - if (branchIndex>0) - { - // Update parent key, removing the source (current) - DeleteFromPageAtIndex(branchIndex-1, cur); - } - } - - if (branchIndex==0 && dest->isLeaf) - { - returnAction->action=ReturnAction::SET_BRANCH_KEY; - returnAction->key1=dest->keys[0]; - } - - if (source==leftmostLeaf) - leftmostLeaf=source->next; - - if (source->isLeaf) - { - if (source->previous) - source->previous->next=source->next; - if (source->next) - source->next->previous=source->previous; - } - - // Free the source node - pagePool.Release(source, _FILE_AND_LINE_); - // memset(source,0,sizeof(root)); - - // Return underflow or not of parent. - return cur->size < order/2; - } - } - template - void BPlusTree::ShiftNodeRight(Page *cur) - { - int i; - for (i=cur->size; i>0; i--) - cur->keys[i]=cur->keys[i-1]; - if (cur->isLeaf) - { - for (i=cur->size; i>0; i--) - cur->data[i]=cur->data[i-1]; - } - else - { - for (i=cur->size+1; i>0; i--) - cur->children[i]=cur->children[i-1]; - } - - cur->size++; - } - template - void BPlusTree::ShiftNodeLeft(Page *cur) - { - int i; - for (i=0; i < cur->size-1; i++) - cur->keys[i]=cur->keys[i+1]; - if (cur->isLeaf) - { - for (i=0; i < cur->size; i++) - cur->data[i]=cur->data[i+1]; - } - else - { - for (i=0; i < cur->size; i++) - cur->children[i]=cur->children[i+1]; - } - cur->size--; - } - template - Page* BPlusTree::InsertIntoNode(const KeyType key, const DataType &leafData, int insertionIndex, Page *nodeData, Page *cur, ReturnAction* returnAction) - { - int i; - if (cur->size < order) - { - for (i=cur->size; i > insertionIndex; i--) - cur->keys[i]=cur->keys[i-1]; - if (cur->isLeaf) - { - for (i=cur->size; i > insertionIndex; i--) - cur->data[i]=cur->data[i-1]; - } - else - { - for (i=cur->size+1; i > insertionIndex+1; i--) - cur->children[i]=cur->children[i-1]; - } - cur->keys[insertionIndex]=key; - if (cur->isLeaf) - cur->data[insertionIndex]=leafData; - else - cur->children[insertionIndex+1]=nodeData; - - cur->size++; - } - else - { - Page* newPage = pagePool.Allocate( _FILE_AND_LINE_ ); - newPage->isLeaf=cur->isLeaf; - if (cur->isLeaf) - { - newPage->next=cur->next; - if (cur->next) - cur->next->previous=newPage; - newPage->previous=cur; - cur->next=newPage; - } - - int destIndex, sourceIndex; - - if (insertionIndex>=(order+1)/2) - { - destIndex=0; - sourceIndex=order/2; - - for (; sourceIndex < insertionIndex; sourceIndex++, destIndex++) - { - newPage->keys[destIndex]=cur->keys[sourceIndex]; - } - newPage->keys[destIndex++]=key; - for (; sourceIndex < order; sourceIndex++, destIndex++) - { - newPage->keys[destIndex]=cur->keys[sourceIndex]; - } - - destIndex=0; - sourceIndex=order/2; - if (cur->isLeaf) - { - for (; sourceIndex < insertionIndex; sourceIndex++, destIndex++) - { - newPage->data[destIndex]=cur->data[sourceIndex]; - } - newPage->data[destIndex++]=leafData; - for (; sourceIndex < order; sourceIndex++, destIndex++) - { - newPage->data[destIndex]=cur->data[sourceIndex]; - } - } - else - { - - for (; sourceIndex < insertionIndex; sourceIndex++, destIndex++) - { - newPage->children[destIndex]=cur->children[sourceIndex+1]; - } - newPage->children[destIndex++]=nodeData; - - // sourceIndex+1 is sort of a hack but it works - because there is one extra child than keys - // skip past the last child for cur - for (; sourceIndex+1 < cur->size+1; sourceIndex++, destIndex++) - { - newPage->children[destIndex]=cur->children[sourceIndex+1]; - } - - // the first key is the middle key. Remove it from the page and push it to the parent - returnAction->action=ReturnAction::PUSH_KEY_TO_PARENT; - returnAction->key1=newPage->keys[0]; - for (int j=0; j < destIndex-1; j++) - newPage->keys[j]=newPage->keys[j+1]; - - } - cur->size=order/2; - } - else - { - destIndex=0; - sourceIndex=(order+1)/2-1; - for (; sourceIndex < order; sourceIndex++, destIndex++) - newPage->keys[destIndex]=cur->keys[sourceIndex]; - destIndex=0; - if (cur->isLeaf) - { - sourceIndex=(order+1)/2-1; - for (; sourceIndex < order; sourceIndex++, destIndex++) - newPage->data[destIndex]=cur->data[sourceIndex]; - } - else - { - sourceIndex=(order+1)/2; - for (; sourceIndex < order+1; sourceIndex++, destIndex++) - newPage->children[destIndex]=cur->children[sourceIndex]; - - // the first key is the middle key. Remove it from the page and push it to the parent - returnAction->action=ReturnAction::PUSH_KEY_TO_PARENT; - returnAction->key1=newPage->keys[0]; - for (int j=0; j < destIndex-1; j++) - newPage->keys[j]=newPage->keys[j+1]; - } - cur->size=(order+1)/2-1; - if (cur->size) - { - bool b = GetIndexOf(key, cur, &insertionIndex); - (void) b; - RakAssert(b==false); - } - else - insertionIndex=0; - InsertIntoNode(key, leafData, insertionIndex, nodeData, cur, returnAction); - } - - newPage->size=destIndex; - - return newPage; - } - - return 0; - } - - template - bool BPlusTree::CanRotateLeft(Page *cur, int childIndex) - { - return childIndex>0 && cur->children[childIndex-1]->size - void BPlusTree::RotateLeft(Page *cur, int childIndex, ReturnAction *returnAction) - { - Page *dest = cur->children[childIndex-1]; - Page *source = cur->children[childIndex]; - returnAction->key1=source->keys[0]; - dest->keys[dest->size]=source->keys[0]; - dest->data[dest->size]=source->data[0]; - dest->size++; - for (int i=0; i < source->size-1; i++) - { - source->keys[i]=source->keys[i+1]; - source->data[i]=source->data[i+1]; - } - source->size--; - cur->keys[childIndex-1]=source->keys[0]; - returnAction->key2=source->keys[0]; - } - - template - bool BPlusTree::CanRotateRight(Page *cur, int childIndex) - { - return childIndex < cur->size && cur->children[childIndex+1]->size - void BPlusTree::RotateRight(Page *cur, int childIndex, ReturnAction *returnAction) - { - Page *dest = cur->children[childIndex+1]; - Page *source = cur->children[childIndex]; - returnAction->key1=dest->keys[0]; - for (int i= dest->size; i > 0; i--) - { - dest->keys[i]=dest->keys[i-1]; - dest->data[i]=dest->data[i-1]; - } - dest->keys[0]=source->keys[source->size-1]; - dest->data[0]=source->data[source->size-1]; - dest->size++; - source->size--; - - cur->keys[childIndex]=dest->keys[0]; - returnAction->key2=dest->keys[0]; - } - template - Page* BPlusTree::GetLeafFromKey(const KeyType key) const - { - Page* cur = root; - int childIndex; - while (cur->isLeaf==false) - { - // When searching, if we match the exact key we go down the pointer after that index - if (GetIndexOf(key, cur, &childIndex)) - childIndex++; - cur = cur->children[childIndex]; - } - return cur; - } - - template - Page* BPlusTree::InsertBranchDown(const KeyType key, const DataType &data,Page *cur, ReturnAction *returnAction, bool *success) - { - int childIndex; - int branchIndex; - if (GetIndexOf(key, cur, &childIndex)) - branchIndex=childIndex+1; - else - branchIndex=childIndex; - Page* newPage; - if (cur->isLeaf==false) - { - if (cur->children[branchIndex]->isLeaf==true && cur->children[branchIndex]->size==order) - { - if (branchIndex==childIndex+1) - { - *success=false; - return 0; // Already exists - } - - if (CanRotateLeft(cur, branchIndex)) - { - returnAction->action=ReturnAction::REPLACE_KEY1_WITH_KEY2; - if (key > cur->children[branchIndex]->keys[0]) - { - RotateLeft(cur, branchIndex, returnAction); - - int insertionIndex; - GetIndexOf(key, cur->children[branchIndex], &insertionIndex); - InsertIntoNode(key, data, insertionIndex, 0, cur->children[branchIndex], 0); - } - else - { - // Move head element to left and replace it with key,data - Page* dest=cur->children[branchIndex-1]; - Page* source=cur->children[branchIndex]; - returnAction->key1=source->keys[0]; - returnAction->key2=key; - dest->keys[dest->size]=source->keys[0]; - dest->data[dest->size]=source->data[0]; - dest->size++; - source->keys[0]=key; - source->data[0]=data; - } - cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0]; - - return 0; - } - else if (CanRotateRight(cur, branchIndex)) - { - returnAction->action=ReturnAction::REPLACE_KEY1_WITH_KEY2; - - if (key < cur->children[branchIndex]->keys[cur->children[branchIndex]->size-1]) - { - RotateRight(cur, branchIndex, returnAction); - - int insertionIndex; - GetIndexOf(key, cur->children[branchIndex], &insertionIndex); - InsertIntoNode(key, data, insertionIndex, 0, cur->children[branchIndex], 0); - - } - else - { - // Insert to the head of the right leaf instead and change our key - returnAction->key1=cur->children[branchIndex+1]->keys[0]; - InsertIntoNode(key, data, 0, 0, cur->children[branchIndex+1], 0); - returnAction->key2=key; - } - cur->keys[branchIndex]=cur->children[branchIndex+1]->keys[0]; - return 0; - } - } - - newPage=InsertBranchDown(key,data,cur->children[branchIndex], returnAction, success); - if (returnAction->action==ReturnAction::REPLACE_KEY1_WITH_KEY2) - { - if (branchIndex>0 && cur->keys[branchIndex-1]==returnAction->key1) - cur->keys[branchIndex-1]=returnAction->key2; - } - if (newPage) - { - if (newPage->isLeaf==false) - { - RakAssert(returnAction->action==ReturnAction::PUSH_KEY_TO_PARENT); - newPage->size--; - return InsertIntoNode(returnAction->key1, data, branchIndex, newPage, cur, returnAction); - } - else - { - return InsertIntoNode(newPage->keys[0], data, branchIndex, newPage, cur, returnAction); - } - } - } - else - { - if (branchIndex==childIndex+1) - { - *success=false; - return 0; // Already exists - } - else - { - return InsertIntoNode(key, data, branchIndex, 0, cur, returnAction); - } - } - - return 0; - } - template - bool BPlusTree::Insert(const KeyType key, const DataType &data) - { - if (root==0) - { - // Allocate root and make root a leaf - root = pagePool.Allocate( _FILE_AND_LINE_ ); - root->isLeaf=true; - leftmostLeaf=root; - root->size=1; - root->keys[0]=key; - root->data[0]=data; - root->next=0; - root->previous=0; - } - else - { - bool success=true; - ReturnAction returnAction; - returnAction.action=ReturnAction::NO_ACTION; - Page* newPage = InsertBranchDown(key, data, root, &returnAction, &success); - if (success==false) - return false; - if (newPage) - { - KeyType newKey; - if (newPage->isLeaf==false) - { - // One key is pushed up through the stack. I store that at keys[0] but it has to be removed for the page to be correct - RakAssert(returnAction.action==ReturnAction::PUSH_KEY_TO_PARENT); - newKey=returnAction.key1; - newPage->size--; - } - else - newKey = newPage->keys[0]; - // propagate the root - Page* newRoot = pagePool.Allocate( _FILE_AND_LINE_ ); - newRoot->isLeaf=false; - newRoot->size=1; - newRoot->keys[0]=newKey; - newRoot->children[0]=root; - newRoot->children[1]=newPage; - root=newRoot; - } - } - - return true; - } - template - void BPlusTree::ShiftKeysLeft(Page *cur) - { - int i; - for (i=0; i < cur->size; i++) - cur->keys[i]=cur->keys[i+1]; - } - template - void BPlusTree::Clear(void) - { - if (root) - { - FreePages(); - leftmostLeaf=0; - root=0; - } - pagePool.Clear(_FILE_AND_LINE_); - } - template - unsigned BPlusTree::Size(void) const - { - unsigned int count=0; - DataStructures::Page *cur = GetListHead(); - while (cur) - { - count+=cur->size; - cur=cur->next; - } - return count; - } - template - bool BPlusTree::IsEmpty(void) const - { - return root==0; - } - template - bool BPlusTree::GetIndexOf(const KeyType key, Page *page, int *out) const - { - RakAssert(page->size>0); - int index, upperBound, lowerBound; - upperBound=page->size-1; - lowerBound=0; - index = page->size/2; - - for(;;) - { - if (key==page->keys[index]) - { - *out=index; - return true; - } - else if (keykeys[index]) - upperBound=index-1; - else - lowerBound=index+1; - - index=lowerBound+(upperBound-lowerBound)/2; - - if (lowerBound>upperBound) - { - *out=lowerBound; - return false; // No match - } - } - } - template - void BPlusTree::FreePages(void) - { - DataStructures::Queue *> queue; - DataStructures::Page *ptr; - int i; - queue.Push(root, _FILE_AND_LINE_ ); - while (queue.Size()) - { - ptr=queue.Pop(); - if (ptr->isLeaf==false) - { - for (i=0; i < ptr->size+1; i++) - queue.Push(ptr->children[i], _FILE_AND_LINE_ ); - } - pagePool.Release(ptr, _FILE_AND_LINE_); - // memset(ptr,0,sizeof(root)); - }; - } - template - Page *BPlusTree::GetListHead(void) const - { - return leftmostLeaf; - } - template - DataType BPlusTree::GetDataHead(void) const - { - return leftmostLeaf->data[0]; - } - template - void BPlusTree::ForEachLeaf(void (*func)(Page * leaf, int index)) - { - int count=0; - DataStructures::Page *cur = GetListHead(); - while (cur) - { - func(cur, count++); - cur=cur->next; - } - } - template - void BPlusTree::ForEachData(void (*func)(DataType input, int index)) - { - int count=0,i; - DataStructures::Page *cur = GetListHead(); - while (cur) - { - for (i=0; i < cur->size; i++) - func(cur->data[i], count++); - cur=cur->next; - } - } - template - void BPlusTree::PrintLeaf(Page * leaf, int index) - { - int i; - RAKNET_DEBUG_PRINTF("%i] SELF=%p\n", index+1, leaf); - for (i=0; i < leaf->size; i++) - // #med - need to adjust printf-format specified based on the actual datatype - RAKNET_DEBUG_PRINTF(" %i. %p\n", i+1, leaf->data[i]); - } - template - void BPlusTree::PrintLeaves(void) - { - ForEachLeaf(PrintLeaf); - } - - template - void BPlusTree::ValidateTreeRecursive(Page *cur) - { - RakAssert(cur==root || cur->size>=order/2); - - if (cur->children[0]->isLeaf) - { - RakAssert(cur->children[0]->keys[0] < cur->keys[0]); - for (int i=0; i < cur->size; i++) - { - RakAssert(cur->children[i+1]->keys[0]==cur->keys[i]); - } - } - else - { - for (int i=0; i < cur->size+1; i++) - ValidateTreeRecursive(cur->children[i]); - } - } - - template - void BPlusTree::PrintGraph(void) - { - DataStructures::Queue *> queue; - queue.Push(root,_FILE_AND_LINE_); - queue.Push(0,_FILE_AND_LINE_); - DataStructures::Page *ptr; - int i,j; - if (root) - { - RAKNET_DEBUG_PRINTF("%p(", root); - for (i=0; i < root->size; i++) - { - RAKNET_DEBUG_PRINTF("%i ", root->keys[i]); - } - RAKNET_DEBUG_PRINTF(") "); - RAKNET_DEBUG_PRINTF("\n"); - } - while (queue.Size()) - { - ptr=queue.Pop(); - if (ptr==0) - RAKNET_DEBUG_PRINTF("\n"); - else if (ptr->isLeaf==false) - { - for (i=0; i < ptr->size+1; i++) - { - RAKNET_DEBUG_PRINTF("%p(", ptr->children[i]); - //RAKNET_DEBUG_PRINTF("(", ptr->children[i]); - for (j=0; j < ptr->children[i]->size; j++) - RAKNET_DEBUG_PRINTF("%i ", ptr->children[i]->keys[j]); - RAKNET_DEBUG_PRINTF(") "); - queue.Push(ptr->children[i],_FILE_AND_LINE_); - } - queue.Push(0,_FILE_AND_LINE_); - RAKNET_DEBUG_PRINTF(" -- "); - } - } - RAKNET_DEBUG_PRINTF("\n"); - } -} -#ifdef _MSC_VER -#pragma warning( pop ) -#endif - -#endif - -// Code to test this hellish data structure. -/* -#include "DS_BPlusTree.h" -#include - -// Handle underflow on root. If there is only one item left then I can go downwards. -// Make sure I keep the leftmost pointer valid by traversing it -// When I free a leaf, be sure to adjust the pointers around it. - -#include "Rand.h" - -void main(void) -{ - DataStructures::BPlusTree btree; - DataStructures::List haveList, removedList; - int temp; - int i, j, index; - int testSize; - bool b; - - for (testSize=0; testSize < 514; testSize++) - { - RAKNET_DEBUG_PRINTF("TestSize=%i\n", testSize); - - for (i=0; i < testSize; i++) - haveList.Insert(i); - - for (i=0; i < testSize; i++) - { - index=i+randomMT()%(testSize-i); - temp=haveList[index]; - haveList[index]=haveList[i]; - haveList[i]=temp; - } - - for (i=0; i - * - * OR - * - * AVLBalancedBinarySearchTree - * - * Use the AVL balanced tree if you want the tree to be balanced after every deletion and addition. This avoids the potential - * worst case scenario where ordered input to a binary search tree gives linear search time results. It's not needed - * if input will be evenly distributed, in which case the search time is O (log n). The search time for the AVL - * balanced binary tree is O (log n) irregardless of input. - * - * Has the following member functions - * unsigned int Height() - Returns the height of the tree at the optional specified starting index. Default is the root - * add(element) - adds an element to the BinarySearchTree - * bool del(element) - deletes the node containing element if the element is in the tree as defined by a comparison with the == operator. Returns true on success, false if the element is not found - * bool IsInelement) - returns true if element is in the tree as defined by a comparison with the == operator. Otherwise returns false - * DisplayInorder(array) - Fills an array with an inorder search of the elements in the tree. USER IS REPONSIBLE FOR ALLOCATING THE ARRAY!. - * DisplayPreorder(array) - Fills an array with an preorder search of the elements in the tree. USER IS REPONSIBLE FOR ALLOCATING THE ARRAY!. - * DisplayPostorder(array) - Fills an array with an postorder search of the elements in the tree. USER IS REPONSIBLE FOR ALLOCATING THE ARRAY!. - * DisplayBreadthFirstSearch(array) - Fills an array with a breadth first search of the elements in the tree. USER IS REPONSIBLE FOR ALLOCATING THE ARRAY!. - * clear - Destroys the tree. Same as calling the destructor - * unsigned int Height() - Returns the height of the tree - * unsigned int size() - returns the size of the BinarySearchTree - * GetPointerToNode(element) - returns a pointer to the comparision element in the tree, allowing for direct modification when necessary with complex data types. - * Be warned, it is possible to corrupt the tree if the element used for comparisons is modified. Returns nullptr if the item is not found - * - * - * EXAMPLE - * @code - * BinarySearchTree A; - * A.Add(10); - * A.Add(15); - * A.Add(5); - * int* array = MafiaNet::OP_NEW(A.Size(), _FILE_AND_LINE_ ); - * A.DisplayInorder(array); - * array[0]; // returns 5 - * array[1]; // returns 10 - * array[2]; // returns 15 - * @endcode - * compress - reallocates memory to fit the number of elements. Best used when the number of elements decreases - * - * clear - empties the BinarySearchTree and returns storage - * The assignment and copy constructors are defined - * - * \note The template type must have the copy constructor and - * assignment operator defined and must work with >, <, and == All - * elements in the tree MUST be distinct The assignment operator is - * defined between BinarySearchTree and AVLBalancedBinarySearchTree - * as long as they are of the same template type. However, passing a - * BinarySearchTree to an AVLBalancedBinarySearchTree will lose its - * structure unless it happened to be AVL balanced to begin with - * Requires queue_linked_list.cpp for the breadth first search used - * in the copy constructor, overloaded assignment operator, and - * display_breadth_first_search. - * - * - */ - template - class RAK_DLL_EXPORT BinarySearchTree - { - - public: - - struct node - { - BinarySearchTreeType* item; - node* left; - node* right; - }; - - BinarySearchTree(); - virtual ~BinarySearchTree(); - BinarySearchTree( const BinarySearchTree& original_type ); - BinarySearchTree& operator= ( const BinarySearchTree& original_copy ); - unsigned int Size( void ); - void Clear( const char *file, unsigned int line ); - unsigned int Height( node* starting_node = 0 ); - node* Add ( const BinarySearchTreeType& input, const char *file, unsigned int line ); - node* Del( const BinarySearchTreeType& input, const char *file, unsigned int line ); - bool IsIn( const BinarySearchTreeType& input ); - void DisplayInorder( BinarySearchTreeType* return_array ); - void DisplayPreorder( BinarySearchTreeType* return_array ); - void DisplayPostorder( BinarySearchTreeType* return_array ); - void DisplayBreadthFirstSearch( BinarySearchTreeType* return_array ); - BinarySearchTreeType*& GetPointerToNode( const BinarySearchTreeType& element ); - - protected: - - node* root; - - enum Direction_Types - { - NOT_FOUND, LEFT, RIGHT, ROOT - } direction; - unsigned int HeightRecursive( node* current ); - unsigned int BinarySearchTree_size; - node*& Find( const BinarySearchTreeType& element, node** parent ); - node*& FindParent( const BinarySearchTreeType& element ); - void DisplayPostorderRecursive( node* current, BinarySearchTreeType* return_array, unsigned int& index ); - void FixTree( node* current ); - - }; - - /// An AVLBalancedBinarySearchTree is a binary tree that is always balanced - template - class RAK_DLL_EXPORT AVLBalancedBinarySearchTree : public BinarySearchTree - { - - public: - AVLBalancedBinarySearchTree() {} - virtual ~AVLBalancedBinarySearchTree(); - void Add ( const BinarySearchTreeType& input ); - void Del( const BinarySearchTreeType& input ); - BinarySearchTree& operator= ( BinarySearchTree& original_copy ) - { - return BinarySearchTree::operator= ( original_copy ); - } - - private: - void BalanceTree( typename BinarySearchTree::node* current, bool rotateOnce ); - void RotateRight( typename BinarySearchTree::node *C ); - void RotateLeft( typename BinarySearchTree::node* C ); - void DoubleRotateRight( typename BinarySearchTree::node *A ); - void DoubleRotateLeft( typename BinarySearchTree::node* A ); - bool RightHigher( typename BinarySearchTree::node* A ); - bool LeftHigher( typename BinarySearchTree::node* A ); - }; - - template - void AVLBalancedBinarySearchTree::BalanceTree( typename BinarySearchTree::node* current, bool rotateOnce ) - { - int left_height, right_height; - - while ( current ) - { - if ( current->left == 0 ) - left_height = 0; - else - left_height = Height( current->left ); - - if ( current->right == 0 ) - right_height = 0; - else - right_height = Height( current->right ); - - if ( right_height - left_height == 2 ) - { - if ( RightHigher( current->right ) ) - RotateLeft( current->right ); - else - DoubleRotateLeft( current ); - - if ( rotateOnce ) - break; - } - - else - if ( right_height - left_height == -2 ) - { - if ( LeftHigher( current->left ) ) - RotateRight( current->left ); - else - DoubleRotateRight( current ); - - if ( rotateOnce ) - break; - } - - if ( current == this->root ) - break; - - current = FindParent( *( current->item ) ); - - } - } - - template - void AVLBalancedBinarySearchTree::Add ( const BinarySearchTreeType& input ) - { - - typename BinarySearchTree::node * current = BinarySearchTree::Add ( input, _FILE_AND_LINE_ ); - BalanceTree( current, true ); - } - - template - void AVLBalancedBinarySearchTree::Del( const BinarySearchTreeType& input ) - { - typename BinarySearchTree::node * current = BinarySearchTree::Del( input, _FILE_AND_LINE_ ); - BalanceTree( current, false ); - - } - - template - bool AVLBalancedBinarySearchTree::RightHigher( typename BinarySearchTree::node *A ) - { - if ( A == 0 ) - return false; - - return Height( A->right ) > Height( A->left ); - } - - template - bool AVLBalancedBinarySearchTree::LeftHigher( typename BinarySearchTree::node *A ) - { - if ( A == 0 ) - return false; - - return Height( A->left ) > Height( A->right ); - } - - template - void AVLBalancedBinarySearchTree::RotateRight( typename BinarySearchTree::node *C ) - { - typename BinarySearchTree::node * A, *B, *D; - /* - RIGHT ROTATION - - A = parent(b) - b= parent(c) - c = node to rotate around - - A - | // Either direction - B - / \ - C - / \ - D - - TO - - A - | // Either Direction - C - / \ - B - / \ - D - - - - - */ - - B = FindParent( *( C->item ) ); - A = FindParent( *( B->item ) ); - D = C->right; - - if ( A ) - { - // Direction was set by the last find_parent call - - if ( this->direction == this->LEFT ) - A->left = C; - else - A->right = C; - } - - else - this->root = C; // If B has no parent parent then B must have been the root node - - B->left = D; - - C->right = B; - } - - template - void AVLBalancedBinarySearchTree::DoubleRotateRight( typename BinarySearchTree::node *A ) - { - // The left side of the left child must be higher for the tree to balance with a right rotation. If it isn't, rotate it left before the normal rotation so it is. - RotateLeft( A->left->right ); - RotateRight( A->left ); - } - - template - void AVLBalancedBinarySearchTree::RotateLeft( typename BinarySearchTree::node *C ) - { - typename BinarySearchTree::node * A, *B, *D; - /* - RIGHT ROTATION - - A = parent(b) - b= parent(c) - c = node to rotate around - - A - | // Either direction - B - / \ - C - / \ - D - - TO - - A - | // Either Direction - C - / \ - B - / \ - D - - - - - */ - - B = FindParent( *( C->item ) ); - A = FindParent( *( B->item ) ); - D = C->left; - - if ( A ) - { - // Direction was set by the last find_parent call - - if ( this->direction == this->LEFT ) - A->left = C; - else - A->right = C; - } - - else - this->root = C; // If B has no parent parent then B must have been the root node - - B->right = D; - - C->left = B; - } - - template - void AVLBalancedBinarySearchTree::DoubleRotateLeft( typename BinarySearchTree::node *A ) - { - // The left side of the right child must be higher for the tree to balance with a left rotation. If it isn't, rotate it right before the normal rotation so it is. - RotateRight( A->right->left ); - RotateLeft( A->right ); - } - - template - AVLBalancedBinarySearchTree::~AVLBalancedBinarySearchTree() - { - this->Clear(_FILE_AND_LINE_); - } - - template - unsigned int BinarySearchTree::Size( void ) - { - return BinarySearchTree_size; - } - - template - unsigned int BinarySearchTree::Height( typename BinarySearchTree::node* starting_node ) - { - if ( BinarySearchTree_size == 0 || starting_node == 0 ) - return 0; - else - return HeightRecursive( starting_node ); - } - - // Recursively return the height of a binary tree - template - unsigned int BinarySearchTree::HeightRecursive( typename BinarySearchTree::node* current ) - { - unsigned int left_height = 0, right_height = 0; - - if ( ( current->left == 0 ) && ( current->right == 0 ) ) - return 1; // Leaf - - if ( current->left != 0 ) - left_height = 1 + HeightRecursive( current->left ); - - if ( current->right != 0 ) - right_height = 1 + HeightRecursive( current->right ); - - if ( left_height > right_height ) - return left_height; - else - return right_height; - } - - template - BinarySearchTree::BinarySearchTree() - { - BinarySearchTree_size = 0; - root = 0; - } - - template - BinarySearchTree::~BinarySearchTree() - { - this->Clear(_FILE_AND_LINE_); - } - - template - BinarySearchTreeType*& BinarySearchTree::GetPointerToNode( const BinarySearchTreeType& element ) - { - static typename BinarySearchTree::node * tempnode; - static BinarySearchTreeType* dummyptr = 0; - tempnode = Find ( element, &tempnode ); - - if ( this->direction == this->NOT_FOUND ) - return dummyptr; - - return tempnode->item; - } - - template - typename BinarySearchTree::node*& BinarySearchTree::Find( const BinarySearchTreeType& element, typename BinarySearchTree::node** parent ) - { - static typename BinarySearchTree::node * current; - - current = this->root; - *parent = 0; - this->direction = this->ROOT; - - if ( BinarySearchTree_size == 0 ) - { - this->direction = this->NOT_FOUND; - return current = 0; - } - - // Check if the item is at the root - if ( element == *( current->item ) ) - { - this->direction = this->ROOT; - return current; - } - - for (;;) - { - // Move pointer - - if ( element < *( current->item ) ) - { - *parent = current; - this->direction = this->LEFT; - current = current->left; - } - - else - if ( element > *( current->item ) ) - { - *parent = current; - this->direction = this->RIGHT; - current = current->right; - } - - if ( current == 0 ) - break; - - // Check if new position holds the item - if ( element == *( current->item ) ) - { - return current; - } - } - - - this->direction = this->NOT_FOUND; - return current = 0; - } - - template - typename BinarySearchTree::node*& BinarySearchTree::FindParent( const BinarySearchTreeType& element ) - { - static typename BinarySearchTree::node * parent; - Find ( element, &parent ); - return parent; - } - - // Performs a series of value swaps starting with current to fix the tree if needed - template - void BinarySearchTree::FixTree( typename BinarySearchTree::node* current ) - { - BinarySearchTreeType temp; - - while ( 1 ) - { - if ( ( ( current->left ) != 0 ) && ( *( current->item ) < *( current->left->item ) ) ) - { - // Swap the current value with the one to the left - temp = *( current->left->item ); - *( current->left->item ) = *( current->item ); - *( current->item ) = temp; - current = current->left; - } - - else - if ( ( ( current->right ) != 0 ) && ( *( current->item ) > *( current->right->item ) ) ) - { - // Swap the current value with the one to the right - temp = *( current->right->item ); - *( current->right->item ) = *( current->item ); - *( current->item ) = temp; - current = current->right; - } - - else - break; // current points to the right place so quit - } - } - - template - typename BinarySearchTree::node* BinarySearchTree::Del( const BinarySearchTreeType& input, const char *file, unsigned int line ) - { - typename BinarySearchTree::node * node_to_delete, *current, *parent; - - if ( BinarySearchTree_size == 0 ) - return 0; - - if ( BinarySearchTree_size == 1 ) - { - Clear(file, line); - return 0; - } - - node_to_delete = Find( input, &parent ); - - if ( direction == NOT_FOUND ) - return 0; // Couldn't find the element - - current = node_to_delete; - - // Replace the deleted node with the appropriate value - if ( ( current->right ) == 0 && ( current->left ) == 0 ) // Leaf node, just remove it - { - - if ( parent ) - { - if ( direction == LEFT ) - parent->left = 0; - else - parent->right = 0; - } - - MafiaNet::OP_DELETE(node_to_delete->item, file, line); - MafiaNet::OP_DELETE(node_to_delete, file, line); - BinarySearchTree_size--; - return parent; - } - else - if ( ( current->right ) != 0 && ( current->left ) == 0 ) // Node has only one child, delete it and cause the parent to point to that child - { - - if ( parent ) - { - if ( direction == RIGHT ) - parent->right = current->right; - else - parent->left = current->right; - } - - else - root = current->right; // Without a parent this must be the root node - - MafiaNet::OP_DELETE(node_to_delete->item, file, line); - - MafiaNet::OP_DELETE(node_to_delete, file, line); - - BinarySearchTree_size--; - - return parent; - } - else - if ( ( current->right ) == 0 && ( current->left ) != 0 ) // Node has only one child, delete it and cause the parent to point to that child - { - - if ( parent ) - { - if ( direction == RIGHT ) - parent->right = current->left; - else - parent->left = current->left; - } - - else - root = current->left; // Without a parent this must be the root node - - MafiaNet::OP_DELETE(node_to_delete->item, file, line); - - MafiaNet::OP_DELETE(node_to_delete, file, line); - - BinarySearchTree_size--; - - return parent; - } - else // Go right, then as left as far as you can - { - parent = current; - direction = RIGHT; - current = current->right; // Must have a right branch because the if statements above indicated that it has 2 branches - - while ( current->left ) - { - direction = LEFT; - parent = current; - current = current->left; - } - - // Replace the value held by the node to MafiaNet::OP_DELETE(with the value pointed to by current, _FILE_AND_LINE_); - *( node_to_delete->item ) = *( current->item ); - - // Delete current. - // If it is a leaf node just delete it - if ( current->right == 0 ) - { - if ( direction == RIGHT ) - parent->right = 0; - else - parent->left = 0; - - MafiaNet::OP_DELETE(current->item, file, line); - - MafiaNet::OP_DELETE(current, file, line); - - BinarySearchTree_size--; - - return parent; - } - - else - { - // Skip this node and make its parent point to its right branch - - if ( direction == RIGHT ) - parent->right = current->right; - else - parent->left = current->right; - - MafiaNet::OP_DELETE(current->item, file, line); - - MafiaNet::OP_DELETE(current, file, line); - - BinarySearchTree_size--; - - return parent; - } - } - } - - template - typename BinarySearchTree::node* BinarySearchTree::Add ( const BinarySearchTreeType& input, const char *file, unsigned int line ) - { - typename BinarySearchTree::node * current; - - // Add the new element to the tree according to the following alogrithm: - // 1. If the current node is empty add the new leaf - // 2. If the element is less than the current node then go down the left branch - // 3. If the element is greater than the current node then go down the right branch - - if ( BinarySearchTree_size == 0 ) - { - BinarySearchTree_size = 1; - root = MafiaNet::OP_NEW( file, line ); - root->item = MafiaNet::OP_NEW( file, line ); - *( root->item ) = input; - root->left = 0; - root->right = 0; - - return root; - } - - else - { - // start at the root - current = root; - - for(;;) // This loop traverses the tree to find a spot for insertion - { - - if ( input < *( current->item ) ) - { - if ( current->left == 0 ) - { - current->left = MafiaNet::OP_NEW( file, line ); - current->left->item = MafiaNet::OP_NEW( file, line ); - current = current->left; - current->left = 0; - current->right = 0; - *( current->item ) = input; - - BinarySearchTree_size++; - return current; - } - - else - { - current = current->left; - } - } - - else - if ( input > *( current->item ) ) - { - if ( current->right == 0 ) - { - current->right = MafiaNet::OP_NEW( file, line ); - current->right->item = MafiaNet::OP_NEW( file, line ); - current = current->right; - current->left = 0; - current->right = 0; - *( current->item ) = input; - - BinarySearchTree_size++; - return current; - } - - else - { - current = current->right; - } - } - - else - return 0; // ((input == current->item) == true) which is not allowed since the tree only takes discrete values. Do nothing - } - } - } - - template - bool BinarySearchTree::IsIn( const BinarySearchTreeType& input ) - { - typename BinarySearchTree::node * parent; - find( input, &parent ); - - if ( direction != NOT_FOUND ) - return true; - else - return false; - } - - - template - void BinarySearchTree::DisplayInorder( BinarySearchTreeType* return_array ) - { - typename BinarySearchTree::node * current, *parent; - bool just_printed = false; - - unsigned int index = 0; - - current = root; - - if ( BinarySearchTree_size == 0 ) - return ; // Do nothing for an empty tree - - else - if ( BinarySearchTree_size == 1 ) - { - return_array[ 0 ] = *( root->item ); - return ; - } - - - direction = ROOT; // Reset the direction - - while ( index != BinarySearchTree_size ) - { - // direction is set by the find function and holds the direction of the parent to the last node visited. It is used to prevent revisiting nodes - - if ( ( current->left != 0 ) && ( direction != LEFT ) && ( direction != RIGHT ) ) - { - // Go left if the following 2 conditions are true - // I can go left - // I did not just move up from a right child - // I did not just move up from a left child - - current = current->left; - direction = ROOT; // Reset the direction - } - - else - if ( ( direction != RIGHT ) && ( just_printed == false ) ) - { - // Otherwise, print the current node if the following 3 conditions are true: - // I did not just move up from a right child - // I did not print this ndoe last cycle - - return_array[ index++ ] = *( current->item ); - just_printed = true; - } - - else - if ( ( current->right != 0 ) && ( direction != RIGHT ) ) - { - // Otherwise, go right if the following 2 conditions are true - // I did not just move up from a right child - // I can go right - - current = current->right; - direction = ROOT; // Reset the direction - just_printed = false; - } - - else - { - // Otherwise I've done everything I can. Move up the tree one node - parent = FindParent( *( current->item ) ); - current = parent; - just_printed = false; - } - } - } - - template - void BinarySearchTree::DisplayPreorder( BinarySearchTreeType* return_array ) - { - typename BinarySearchTree::node * current, *parent; - - unsigned int index = 0; - - current = root; - - if ( BinarySearchTree_size == 0 ) - return ; // Do nothing for an empty tree - - else - if ( BinarySearchTree_size == 1 ) - { - return_array[ 0 ] = *( root->item ); - return ; - } - - - direction = ROOT; // Reset the direction - return_array[ index++ ] = *( current->item ); - - while ( index != BinarySearchTree_size ) - { - // direction is set by the find function and holds the direction of the parent to the last node visited. It is used to prevent revisiting nodes - - if ( ( current->left != 0 ) && ( direction != LEFT ) && ( direction != RIGHT ) ) - { - - current = current->left; - direction = ROOT; - - // Everytime you move a node print it - return_array[ index++ ] = *( current->item ); - } - - else - if ( ( current->right != 0 ) && ( direction != RIGHT ) ) - { - current = current->right; - direction = ROOT; - - // Everytime you move a node print it - return_array[ index++ ] = *( current->item ); - } - - else - { - // Otherwise I've done everything I can. Move up the tree one node - parent = FindParent( *( current->item ) ); - current = parent; - } - } - } - - template - inline void BinarySearchTree::DisplayPostorder( BinarySearchTreeType* return_array ) - { - unsigned int index = 0; - - if ( BinarySearchTree_size == 0 ) - return ; // Do nothing for an empty tree - - else - if ( BinarySearchTree_size == 1 ) - { - return_array[ 0 ] = *( root->item ); - return ; - } - - DisplayPostorderRecursive( root, return_array, index ); - } - - - // Recursively do a postorder traversal - template - void BinarySearchTree::DisplayPostorderRecursive( typename BinarySearchTree::node* current, BinarySearchTreeType* return_array, unsigned int& index ) - { - if ( current->left != 0 ) - DisplayPostorderRecursive( current->left, return_array, index ); - - if ( current->right != 0 ) - DisplayPostorderRecursive( current->right, return_array, index ); - - return_array[ index++ ] = *( current->item ); - - } - - - template - void BinarySearchTree::DisplayBreadthFirstSearch( BinarySearchTreeType* return_array ) - { - typename BinarySearchTree::node * current; - unsigned int index = 0; - - // Display the tree using a breadth first search - // Put the children of the current node into the queue - // Pop the queue, put its children into the queue, repeat until queue is empty - - if ( BinarySearchTree_size == 0 ) - return ; // Do nothing for an empty tree - - else - if ( BinarySearchTree_size == 1 ) - { - return_array[ 0 ] = *( root->item ); - return ; - } - - else - { - DataStructures::QueueLinkedList tree_queue; - - // Add the root of the tree I am copying from - tree_queue.Push( root ); - - do - { - current = tree_queue.Pop(); - return_array[ index++ ] = *( current->item ); - - // Add the child or children of the tree I am copying from to the queue - - if ( current->left != 0 ) - tree_queue.Push( current->left ); - - if ( current->right != 0 ) - tree_queue.Push( current->right ); - - } - - while ( tree_queue.Size() > 0 ); - } - } - - - template - BinarySearchTree::BinarySearchTree( const BinarySearchTree& original_copy ) - { - typename BinarySearchTree::node * current; - // Copy the tree using a breadth first search - // Put the children of the current node into the queue - // Pop the queue, put its children into the queue, repeat until queue is empty - - // This is a copy of the constructor. A bug in Visual C++ made it so if I just put the constructor call here the variable assignments were ignored. - BinarySearchTree_size = 0; - root = 0; - - if ( original_copy.BinarySearchTree_size == 0 ) - { - BinarySearchTree_size = 0; - } - - else - { - DataStructures::QueueLinkedList tree_queue; - - // Add the root of the tree I am copying from - tree_queue.Push( original_copy.root ); - - do - { - current = tree_queue.Pop(); - - Add ( *( current->item ), _FILE_AND_LINE_ ) - - ; - - // Add the child or children of the tree I am copying from to the queue - if ( current->left != 0 ) - tree_queue.Push( current->left ); - - if ( current->right != 0 ) - tree_queue.Push( current->right ); - - } - - while ( tree_queue.Size() > 0 ); - } - } - - template - BinarySearchTree& BinarySearchTree::operator= ( const BinarySearchTree& original_copy ) - { - typename BinarySearchTree::node * current; - - if ( ( &original_copy ) == this ) - return *this; - - Clear( _FILE_AND_LINE_ ); // Remove the current tree - - // This is a copy of the constructor. A bug in Visual C++ made it so if I just put the constructor call here the variable assignments were ignored. - BinarySearchTree_size = 0; - - root = 0; - - - // Copy the tree using a breadth first search - // Put the children of the current node into the queue - // Pop the queue, put its children into the queue, repeat until queue is empty - if ( original_copy.BinarySearchTree_size == 0 ) - { - BinarySearchTree_size = 0; - } - - else - { - DataStructures::QueueLinkedList tree_queue; - - // Add the root of the tree I am copying from - tree_queue.Push( original_copy.root ); - - do - { - current = tree_queue.Pop(); - - Add ( *( current->item ), _FILE_AND_LINE_ ) - - ; - - // Add the child or children of the tree I am copying from to the queue - if ( current->left != 0 ) - tree_queue.Push( current->left ); - - if ( current->right != 0 ) - tree_queue.Push( current->right ); - - } - - while ( tree_queue.Size() > 0 ); - } - - return *this; - } - - template - inline void BinarySearchTree::Clear ( const char *file, unsigned int line ) - { - typename BinarySearchTree::node * current, *parent; - - current = root; - - while ( BinarySearchTree_size > 0 ) - { - if ( BinarySearchTree_size == 1 ) - { - MafiaNet::OP_DELETE(root->item, file, line); - MafiaNet::OP_DELETE(root, file, line); - root = 0; - BinarySearchTree_size = 0; - } - - else - { - if ( current->left != 0 ) - { - current = current->left; - } - - else - if ( current->right != 0 ) - { - current = current->right; - } - - else // leaf - { - // Not root node so must have a parent - parent = FindParent( *( current->item ) ); - - if ( ( parent->left ) == current ) - parent->left = 0; - else - parent->right = 0; - - MafiaNet::OP_DELETE(current->item, file, line); - - MafiaNet::OP_DELETE(current, file, line); - - current = parent; - - BinarySearchTree_size--; - } - } - } - } - -} // End namespace - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_BytePool.h b/vendors/mafianet/Source/include/mafianet/DS_BytePool.h deleted file mode 100644 index a8d8a8bc9..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_BytePool.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_BytePool.h -/// - - -#ifndef __BYTE_POOL_H -#define __BYTE_POOL_H - -#include "memoryoverride.h" -#include "DS_MemoryPool.h" -#include "Export.h" -#include "SimpleMutex.h" -#include "assert.h" - -// #define _DISABLE_BYTE_POOL -// #define _THREADSAFE_BYTE_POOL - -namespace DataStructures -{ - // Allocate some number of bytes from pools. Uses the heap if necessary. - class RAK_DLL_EXPORT BytePool - { - public: - BytePool(); - ~BytePool(); - // Should be at least 8 times bigger than 8192 - void SetPageSize(int size); - unsigned char* Allocate(int bytesWanted, const char *file, unsigned int line); - void Release(unsigned char *data, const char *file, unsigned int line); - void Clear(const char *file, unsigned int line); - protected: - MemoryPool pool128; - MemoryPool pool512; - MemoryPool pool2048; - MemoryPool pool8192; -#ifdef _THREADSAFE_BYTE_POOL - SimpleMutex mutex128; - SimpleMutex mutex512; - SimpleMutex mutex2048; - SimpleMutex mutex8192; -#endif - }; -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_ByteQueue.h b/vendors/mafianet/Source/include/mafianet/DS_ByteQueue.h deleted file mode 100644 index 263c4b299..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_ByteQueue.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_ByteQueue.h -/// \internal -/// \brief Byte queue -/// - - -#ifndef __BYTE_QUEUE_H -#define __BYTE_QUEUE_H - -#include "memoryoverride.h" -#include "Export.h" - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - class ByteQueue - { - public: - ByteQueue(); - ~ByteQueue(); - void WriteBytes(const char *in, unsigned length, const char *file, unsigned int line); - bool ReadBytes(char *out, unsigned maxLengthToRead, bool peek); - unsigned GetBytesWritten(void) const; - char* PeekContiguousBytes(unsigned int *outLength) const; - void IncrementReadOffset(unsigned length); - void DecrementReadOffset(unsigned length); - void Clear(const char *file, unsigned int line); - void Print(void); - - protected: - char *data; - unsigned readOffset, writeOffset, lengthAllocated; - }; -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_Hash.h b/vendors/mafianet/Source/include/mafianet/DS_Hash.h deleted file mode 100644 index 7bf5be45b..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_Hash.h +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \internal -/// \brief Hashing container -/// - - -#ifndef __HASH_H -#define __HASH_H - -#include "assert.h" -#include // memmove -#include "Export.h" -#include "memoryoverride.h" -#include "string.h" - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - struct HashIndex - { - unsigned int primaryIndex; - unsigned int secondaryIndex; - bool IsInvalid(void) const {return primaryIndex==(unsigned int) -1;} - void SetInvalid(void) {primaryIndex=(unsigned int) -1; secondaryIndex=(unsigned int) -1;} - }; - - /// \brief Using a string as a identifier for a node, store an allocated pointer to that node - template - class RAK_DLL_EXPORT Hash - { - public: - /// Default constructor - Hash(); - - // Destructor - ~Hash(); - - void Push(key_type key, const data_type &input, const char *file, unsigned int line ); - data_type* Peek(key_type key ); - bool Pop(data_type& out, key_type key, const char *file, unsigned int line ); - bool RemoveAtIndex(HashIndex index, const char *file, unsigned int line ); - bool Remove(key_type key, const char *file, unsigned int line ); - HashIndex GetIndexOf(key_type key); - bool HasData(key_type key); - data_type& ItemAtIndex(const HashIndex &index); - key_type KeyAtIndex(const HashIndex &index); - void GetAsList(DataStructures::List &itemList,DataStructures::List &keyList,const char *file, unsigned int line) const; - unsigned int Size(void) const; - - /// \brief Clear the list - void Clear( const char *file, unsigned int line ); - - struct Node - { - Node(key_type strIn, const data_type &_data) {string=strIn; data=_data;} - key_type string; - data_type data; - // Next in the list for this key - Node *next; - }; - - protected: - void ClearIndex(unsigned int index,const char *file, unsigned int line); - Node **nodeList; - unsigned int size; - }; - - template - Hash::Hash() - { - nodeList=0; - size=0; - } - - template - Hash::~Hash() - { - Clear(_FILE_AND_LINE_); - } - - template - void Hash::Push(key_type key, const data_type &input, const char *file, unsigned int line ) - { - unsigned long hashIndex = (*hashFunction)(key) % HASH_SIZE; - if (nodeList==0) - { - nodeList= MafiaNet::OP_NEW_ARRAY(HASH_SIZE,file,line); - memset(nodeList,0,sizeof(Node *)*HASH_SIZE); - } - - Node *newNode= MafiaNet::OP_NEW_2(file,line,key,input); - newNode->next=nodeList[hashIndex]; - nodeList[hashIndex]=newNode; - - size++; - } - - template - data_type* Hash::Peek(key_type key ) - { - if (nodeList==0) - return 0; - - unsigned long hashIndex = (*hashFunction)(key) % HASH_SIZE; - Node *node = nodeList[hashIndex]; - while (node!=0) - { - if (node->string==key) - return &node->data; - node=node->next; - } - return 0; - } - - template - bool Hash::Pop(data_type& out, key_type key, const char *file, unsigned int line ) - { - if (nodeList==0) - return false; - - unsigned long hashIndex = (*hashFunction)(key) % HASH_SIZE; - Node *node = nodeList[hashIndex]; - if (node==0) - return false; - if (node->next==0) - { - // Only one item. - if (node->string==key) - { - // Delete last item - out=node->data; - ClearIndex(hashIndex,_FILE_AND_LINE_); - return true; - } - else - { - // Single item doesn't match - return false; - } - } - else if (node->string==key) - { - // First item does match, but more than one item - out=node->data; - nodeList[hashIndex]=node->next; - MafiaNet::OP_DELETE(node,file,line); - size--; - return true; - } - - Node *last=node; - node=node->next; - - while (node!=0) - { - // First item does not match, but subsequent item might - if (node->string==key) - { - out=node->data; - // Skip over subsequent item - last->next=node->next; - // Delete existing item - MafiaNet::OP_DELETE(node,file,line); - size--; - return true; - } - last=node; - node=node->next; - } - return false; - } - - template - bool Hash::RemoveAtIndex(HashIndex index, const char *file, unsigned int line ) - { - if (index.IsInvalid()) - return false; - - Node *node = nodeList[index.primaryIndex]; - if (node==0) - return false; - if (node->next==0) - { - // Delete last item - ClearIndex(index.primaryIndex,file,line); - return true; - } - else if (index.secondaryIndex==0) - { - // First item does match, but more than one item - nodeList[index.primaryIndex]=node->next; - MafiaNet::OP_DELETE(node,file,line); - size--; - return true; - } - - Node *last=node; - node=node->next; - --index.secondaryIndex; - - while (index.secondaryIndex!=0) - { - last=node; - node=node->next; - --index.secondaryIndex; - } - - // Skip over subsequent item - last->next=node->next; - // Delete existing item - MafiaNet::OP_DELETE(node,file,line); - size--; - return true; - } - - template - bool Hash::Remove(key_type key, const char *file, unsigned int line ) - { - return RemoveAtIndex(GetIndexOf(key),file,line); - } - - template - HashIndex Hash::GetIndexOf(key_type key) - { - if (nodeList==0) - { - HashIndex temp; - temp.SetInvalid(); - return temp; - } - HashIndex idx; - idx.primaryIndex=(*hashFunction)(key) % HASH_SIZE; - Node *node = nodeList[idx.primaryIndex]; - if (node==0) - { - idx.SetInvalid(); - return idx; - } - idx.secondaryIndex=0; - while (node!=0) - { - if (node->string==key) - { - return idx; - } - node=node->next; - idx.secondaryIndex++; - } - - idx.SetInvalid(); - return idx; - } - - template - bool Hash::HasData(key_type key) - { - return GetIndexOf(key).IsInvalid()==false; - } - - template - data_type& Hash::ItemAtIndex(const HashIndex &index) - { - Node *node = nodeList[index.primaryIndex]; - RakAssert(node); - unsigned int i; - for (i=0; i < index.secondaryIndex; i++) - { - node=node->next; - RakAssert(node); - } - return node->data; - } - - template - key_type Hash::KeyAtIndex(const HashIndex &index) - { - Node *node = nodeList[index.primaryIndex]; - RakAssert(node); - unsigned int i; - for (i=0; i < index.secondaryIndex; i++) - { - node=node->next; - RakAssert(node); - } - return node->string; - } - - template - void Hash::Clear(const char *file, unsigned int line) - { - if (nodeList) - { - unsigned int i; - for (i=0; i < HASH_SIZE; i++) - ClearIndex(i,file,line); - MafiaNet::OP_DELETE_ARRAY(nodeList,file,line); - nodeList=0; - size=0; - } - } - - template - void Hash::ClearIndex(unsigned int index,const char *file, unsigned int line) - { - Node *node = nodeList[index]; - Node *next; - while (node) - { - next=node->next; - MafiaNet::OP_DELETE(node,file,line); - node=next; - size--; - } - nodeList[index]=0; - } - - template - void Hash::GetAsList(DataStructures::List &itemList,DataStructures::List &keyList,const char *file, unsigned int line) const - { - if (nodeList==0) - return; - itemList.Clear(false,_FILE_AND_LINE_); - keyList.Clear(false,_FILE_AND_LINE_); - - Node *node; - unsigned int i; - for (i=0; i < HASH_SIZE; i++) - { - if (nodeList[i]) - { - node=nodeList[i]; - while (node) - { - itemList.Push(node->data,file,line); - keyList.Push(node->string,file,line); - node=node->next; - } - } - } - } - template - unsigned int Hash::Size(void) const - { - return size; - } -} -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_Heap.h b/vendors/mafianet/Source/include/mafianet/DS_Heap.h deleted file mode 100644 index 3e08c51b6..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_Heap.h +++ /dev/null @@ -1,310 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_Heap.h -/// \internal -/// \brief Heap (Also serves as a priority queue) -/// - - - -#ifndef __RAKNET_HEAP_H -#define __RAKNET_HEAP_H - -#include "memoryoverride.h" -#include "DS_List.h" -#include "Export.h" -#include "assert.h" - -#ifdef _MSC_VER -#pragma warning( push ) -#endif - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - template - class RAK_DLL_EXPORT Heap - { - public: - struct HeapNode - { - HeapNode() {} - HeapNode(const weight_type &w, const data_type &d) : weight(w), data(d) {} - weight_type weight; // I'm assuming key is a native numerical type - float or int - data_type data; - }; - - Heap(); - ~Heap(); - void Push(const weight_type &weight, const data_type &data, const char *file, unsigned int line); - /// Call before calling PushSeries, for a new series of items - void StartSeries(void) {optimizeNextSeriesPush=false;} - /// If you are going to push a list of items, where the weights of the items on the list are in order and follow the heap order, PushSeries is faster than Push() - void PushSeries(const weight_type &weight, const data_type &data, const char *file, unsigned int line); - data_type Pop(const unsigned startingIndex); - data_type Peek(const unsigned startingIndex=0) const; - weight_type PeekWeight(const unsigned startingIndex=0) const; - void Clear(bool doNotDeallocateSmallBlocks, const char *file, unsigned int line); - data_type& operator[] ( const unsigned int position ) const; - unsigned Size(void) const; - - protected: - unsigned LeftChild(const unsigned i) const; - unsigned RightChild(const unsigned i) const; - unsigned Parent(const unsigned i) const; - void Swap(const unsigned i, const unsigned j); - DataStructures::List heap; - bool optimizeNextSeriesPush; - }; - - template - Heap::Heap() - { - optimizeNextSeriesPush=false; - } - - template - Heap::~Heap() - { - //Clear(true, _FILE_AND_LINE_); - } - - template - void Heap::PushSeries(const weight_type &weight, const data_type &data, const char *file, unsigned int line) - { - if (optimizeNextSeriesPush==false) - { - // If the weight of what we are inserting is greater than / less than in order of the heap of every sibling and sibling of parent, then can optimize next push - unsigned currentIndex = heap.Size(); - unsigned parentIndex; - if (currentIndex>0) - { - for (parentIndex = Parent(currentIndex); parentIndex < currentIndex; parentIndex++) - { -#ifdef _MSC_VER -#pragma warning(disable:4127) // conditional expression is constant -#endif - if (isMaxHeap) - { - // Every child is less than its parent - if (weight>heap[parentIndex].weight) - { - // Can't optimize - Push(weight,data,file,line); - return; - } - } - else - { - // Every child is greater than than its parent - if (weight - void Heap::Push(const weight_type &weight, const data_type &data, const char *file, unsigned int line) - { - unsigned currentIndex = heap.Size(); - unsigned parentIndex; - heap.Insert(HeapNode(weight, data), file, line); - while (currentIndex!=0) - { - parentIndex = Parent(currentIndex); -#ifdef _MSC_VER -#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant -#endif - if (isMaxHeap) - { - if (heap[parentIndex].weight < weight) - { - Swap(currentIndex, parentIndex); - currentIndex=parentIndex; - } - else - break; - } - else - { - if (heap[parentIndex].weight > weight) - { - Swap(currentIndex, parentIndex); - currentIndex=parentIndex; - } - else - break; - } - } - } - - template - data_type Heap::Pop(const unsigned startingIndex) - { - // While we have children, swap out with the larger of the two children. - - // This line will assert on an empty heap - data_type returnValue=heap[startingIndex].data; - - // Move the last element to the head, and re-heapify - heap[startingIndex]=heap[heap.Size()-1]; - - unsigned currentIndex,leftChild,rightChild; - weight_type currentWeight; - currentIndex=startingIndex; - currentWeight=heap[startingIndex].weight; - heap.RemoveFromEnd(); - -#ifdef _MSC_VER -#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant -#endif - for(;;) - { - leftChild=LeftChild(currentIndex); - rightChild=RightChild(currentIndex); - if (leftChild >= heap.Size()) - { - // Done - return returnValue; - } - if (rightChild >= heap.Size()) - { - // Only left node. - if ((isMaxHeap==true && currentWeight < heap[leftChild].weight) || - (isMaxHeap==false && currentWeight > heap[leftChild].weight)) - Swap(leftChild, currentIndex); - - return returnValue; - } - else - { - // Swap with the bigger/smaller of the two children and continue - if (isMaxHeap) - { - if (heap[leftChild].weight <= currentWeight && heap[rightChild].weight <= currentWeight) - return returnValue; - - if (heap[leftChild].weight > heap[rightChild].weight) - { - Swap(leftChild, currentIndex); - currentIndex=leftChild; - } - else - { - Swap(rightChild, currentIndex); - currentIndex=rightChild; - } - } - else - { - if (heap[leftChild].weight >= currentWeight && heap[rightChild].weight >= currentWeight) - return returnValue; - - if (heap[leftChild].weight < heap[rightChild].weight) - { - Swap(leftChild, currentIndex); - currentIndex=leftChild; - } - else - { - Swap(rightChild, currentIndex); - currentIndex=rightChild; - } - } - } - } - } - - template - inline data_type Heap::Peek(const unsigned startingIndex) const - { - return heap[startingIndex].data; - } - - template - inline weight_type Heap::PeekWeight(const unsigned startingIndex) const - { - return heap[startingIndex].weight; - } - - template - void Heap::Clear(bool doNotDeallocateSmallBlocks, const char *file, unsigned int line) - { - heap.Clear(doNotDeallocateSmallBlocks, file, line); - } - - template - inline data_type& Heap::operator[] ( const unsigned int position ) const - { - return heap[position].data; - } - template - unsigned Heap::Size(void) const - { - return heap.Size(); - } - - template - inline unsigned Heap::LeftChild(const unsigned i) const - { - return i*2+1; - } - - template - inline unsigned Heap::RightChild(const unsigned i) const - { - return i*2+2; - } - - template - inline unsigned Heap::Parent(const unsigned i) const - { -#ifdef _DEBUG - RakAssert(i!=0); -#endif - return (i-1)/2; - } - - template - void Heap::Swap(const unsigned i, const unsigned j) - { - HeapNode temp; - temp=heap[i]; - heap[i]=heap[j]; - heap[j]=temp; - } -} - -#ifdef _MSC_VER -#pragma warning( pop ) -#endif - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_HuffmanEncodingTree.h b/vendors/mafianet/Source/include/mafianet/DS_HuffmanEncodingTree.h deleted file mode 100644 index 4f362f937..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_HuffmanEncodingTree.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_HuffmanEncodingTree.h -/// \brief \b [Internal] Generates a huffman encoding tree, used for string and global compression. -/// - - -#ifndef __HUFFMAN_ENCODING_TREE -#define __HUFFMAN_ENCODING_TREE - -#include "memoryoverride.h" -#include "DS_HuffmanEncodingTreeNode.h" -#include "BitStream.h" -#include "Export.h" -#include "DS_LinkedList.h" - -namespace MafiaNet -{ - -/// This generates special cases of the huffman encoding tree using 8 bit keys with the additional condition that unused combinations of 8 bits are treated as a frequency of 1 -class RAK_DLL_EXPORT HuffmanEncodingTree -{ - -public: - HuffmanEncodingTree(); - ~HuffmanEncodingTree(); - - /// \brief Pass an array of bytes to array and a preallocated BitStream to receive the output. - /// \param [in] input Array of bytes to encode - /// \param [in] sizeInBytes size of \a input - /// \param [out] output The bitstream to write to - void EncodeArray( unsigned char *input, size_t sizeInBytes, MafiaNet::BitStream * output ); - - // \brief Decodes an array encoded by EncodeArray(). - unsigned DecodeArray(MafiaNet::BitStream * input, BitSize_t sizeInBits, size_t maxCharsToWrite, unsigned char *output ); - void DecodeArray( unsigned char *input, BitSize_t sizeInBits, MafiaNet::BitStream * output ); - - /// \brief Given a frequency table of 256 elements, all with a frequency of 1 or more, generate the tree. - void GenerateFromFrequencyTable( unsigned int frequencyTable[ 256 ] ); - - /// \brief Free the memory used by the tree. - void FreeMemory( void ); - -private: - - /// The root node of the tree - - HuffmanEncodingTreeNode *root; - - /// Used to hold bit encoding for one character - - - struct CharacterEncoding - { - unsigned char* encoding; - unsigned short bitLength; - }; - - CharacterEncoding encodingTable[ 256 ]; - - void InsertNodeIntoSortedList( HuffmanEncodingTreeNode * node, DataStructures::LinkedList *huffmanEncodingTreeNodeList ) const; -}; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_HuffmanEncodingTreeFactory.h b/vendors/mafianet/Source/include/mafianet/DS_HuffmanEncodingTreeFactory.h deleted file mode 100644 index 8bc5f201e..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_HuffmanEncodingTreeFactory.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_HuffmanEncodingTreeFactory.h -/// \internal -/// \brief Creates instances of the class HuffmanEncodingTree -/// - - -#ifndef __HUFFMAN_ENCODING_TREE_FACTORY -#define __HUFFMAN_ENCODING_TREE_FACTORY - -#include "memoryoverride.h" - -namespace MafiaNet { -/// Forward declarations -class HuffmanEncodingTree; - -/// \brief Creates instances of the class HuffmanEncodingTree -/// \details This class takes a frequency table and given that frequence table, will generate an instance of HuffmanEncodingTree -class HuffmanEncodingTreeFactory -{ -public: - /// Default constructor - HuffmanEncodingTreeFactory(); - - /// \brief Reset the frequency table. - /// \details You don't need to call this unless you want to reuse the class for a new tree - void Reset( void ); - - /// \brief Pass an array of bytes to this to add those elements to the frequency table. - /// \param[in] array the data to insert into the frequency table - /// \param[in] size the size of the data to insert - void AddToFrequencyTable( unsigned char *array, int size ); - - /// \brief Copies the frequency table to the array passed. Retrieve the frequency table. - /// \param[in] _frequency The frequency table used currently - void GetFrequencyTable( unsigned int _frequency[ 256 ] ); - - /// \brief Returns the frequency table as a pointer. - /// \return the address of the frenquency table - unsigned int * GetFrequencyTable( void ); - - /// \brief Generate a HuffmanEncodingTree. - /// \details You can also use GetFrequencyTable and GenerateFromFrequencyTable in the tree itself - /// \return The generated instance of HuffmanEncodingTree - HuffmanEncodingTree * GenerateTree( void ); - -private: - - /// Frequency table - unsigned int frequency[ 256 ]; -}; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_HuffmanEncodingTreeNode.h b/vendors/mafianet/Source/include/mafianet/DS_HuffmanEncodingTreeNode.h deleted file mode 100644 index 8af099d5c..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_HuffmanEncodingTreeNode.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -/// \file -/// \brief \b [Internal] A single node in the Huffman Encoding Tree. -/// - -#ifndef __HUFFMAN_ENCODING_TREE_NODE -#define __HUFFMAN_ENCODING_TREE_NODE - -struct HuffmanEncodingTreeNode -{ - unsigned char value; - unsigned weight; - HuffmanEncodingTreeNode *left; - HuffmanEncodingTreeNode *right; - HuffmanEncodingTreeNode *parent; -}; - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_LinkedList.h b/vendors/mafianet/Source/include/mafianet/DS_LinkedList.h deleted file mode 100644 index c4ddc7529..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_LinkedList.h +++ /dev/null @@ -1,1249 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_LinkedList.h -/// \internal -/// \brief Straightforward linked list data structure. -/// - - -#ifndef __LINKED_LIST_H -#define __LINKED_LIST_H - -#include "Export.h" -#include "memoryoverride.h" - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - // Prototype to prevent error in CircularLinkedList class when a reference is made to a LinkedList class - template - class RAK_DLL_EXPORT LinkedList; - - /** - * \brief (Circular) Linked List ADT (Doubly Linked Pointer to Node Style) - - * - * \details - * Initilize with the following command - * LinkedList - * OR - * CircularLinkedList - * - * Has the following member functions - * - size: returns number of elements in the linked list - * - insert(item): inserts @em item at the current position in - * the LinkedList. - * - add(item): inserts @em item after the current position in - * the LinkedList. Does not increment the position - * - replace(item): replaces the element at the current position @em item. - * - peek: returns the element at the current position - * - pop: returns the element at the current position and deletes it - * - del: deletes the current element. Does nothing for an empty list. - * - clear: empties the LinkedList and returns storage - * - bool IsInitem): Does a linear search for @em item. Does not set - * the position to it, only returns true on item found, false otherwise - * - bool find(item): Does a linear search for @em item and sets the current - * position to point to it if and only if the item is found. Returns true - * on item found, false otherwise - * - sort: Sorts the elements of the list with a mergesort and sets the - * current pointer to the first element - * - concatenate(list L): This appends L to the current list - * - ++(prefix): moves the pointer one element up in the list and returns the - * appropriate copy of the element in the list - * - --(prefix): moves the pointer one element back in the list and returns - * the appropriate copy of the element in the list - * - beginning - moves the pointer to the start of the list. For circular - * linked lists this is first 'position' created. You should call this - * after the sort function to read the first value. - * - end - moves the pointer to the end of the list. For circular linked - * lists this is one less than the first 'position' created - * The assignment and copy constructor operators are defined - * - * \note - * 1. LinkedList and CircularLinkedList are exactly the same except LinkedList - * won't let you wrap around the root and lets you jump to two positions - * relative to the root/ - * 2. Postfix ++ and -- can be used but simply call the prefix versions. - * - * - * EXAMPLE: - * @code - * LinkedList A; // Creates a Linked List of integers called A - * CircularLinkedList B; // Creates a Circular Linked List of - * // integers called B - * - * A.Insert(20); // Adds 20 to A. A: 20 - current is 20 - * A.Insert(5); // Adds 5 to A. A: 5 20 - current is 5 - * A.Insert(1); // Adds 1 to A. A: 1 5 20 - current is 1 - * - * A.IsIn1); // returns true - * A.IsIn200); // returns false - * A.Find(5); // returns true and sets current to 5 - * A.Peek(); // returns 5 - * A.Find(1); // returns true and sets current to 1 - * - * (++A).Peek(); // Returns 5 - * A.Peek(); // Returns 5 - * - * A.Replace(10); // Replaces 5 with 10. - * A.Peek(); // Returns 10 - * - * A.Beginning(); // Current points to the beginning of the list at 1 - * - * (++A).Peek(); // Returns 5 - * A.Peek(); // Returns 10 - * - * A.Del(); // Deletes 10. Current points to the next element, which is 20 - * A.Peek(); // Returns 20 - * - * A.Beginning(); // Current points to the beginning of the list at 1 - * - * (++A).Peek(); // Returns 5 - * A.Peek(); // Returns 20 - * - * A.Clear(_FILE_AND_LINE_); // Deletes all nodes in A - * - * A.Insert(5); // A: 5 - current is 5 - * A.Insert(6); // A: 6 5 - current is 6 - * A.Insert(7); // A: 7 6 5 - current is 7 - * - * A.Clear(_FILE_AND_LINE_); - * B.Clear(_FILE_AND_LINE_); - * - * B.Add(10); - * B.Add(20); - * B.Add(30); - * B.Add(5); - * B.Add(2); - * B.Add(25); - * // Sorts the numbers in the list and sets the current pointer to the - * // first element - * B.sort(); - * - * // Postfix ++ just calls the prefix version and has no functional - * // difference. - * B.Peek(); // Returns 2 - * B++; - * B.Peek(); // Returns 5 - * B++; - * B.Peek(); // Returns 10 - * B++; - * B.Peek(); // Returns 20 - * B++; - * B.Peek(); // Returns 25 - * B++; - * B.Peek(); // Returns 30 - * @endcode - */ - template - - class CircularLinkedList - { - - public: - - struct node - { - CircularLinkedListType item; - - node* previous; - node* next; - }; - - CircularLinkedList(); - ~CircularLinkedList(); - CircularLinkedList( const CircularLinkedList& original_copy ); - // CircularLinkedList(LinkedList original_copy) {CircularLinkedList(original_copy);} // Converts linked list to circular type - bool operator= ( const CircularLinkedList& original_copy ); - CircularLinkedList& operator++(); // CircularLinkedList A; ++A; - CircularLinkedList& operator++( int ); // Circular_Linked List A; A++; - CircularLinkedList& operator--(); // CircularLinkedList A; --A; - CircularLinkedList& operator--( int ); // Circular_Linked List A; A--; - bool IsIn( const CircularLinkedListType& input ); - bool Find( const CircularLinkedListType& input ); - void Insert( const CircularLinkedListType& input ); - - CircularLinkedListType& Add ( const CircularLinkedListType& input ) - - ; // Adds after the current position - void Replace( const CircularLinkedListType& input ); - - void Del( void ); - - unsigned int Size( void ); - - CircularLinkedListType& Peek( void ); - - CircularLinkedListType Pop( void ); - - void Clear( void ); - - void Sort( void ); - - void Beginning( void ); - - void End( void ); - - void Concatenate( const CircularLinkedList& L ); - - protected: - unsigned int list_size; - - node *root; - - node *position; - - node* FindPointer( const CircularLinkedListType& input ); - - private: - CircularLinkedList Merge( CircularLinkedList L1, CircularLinkedList L2 ); - - CircularLinkedList Mergesort( const CircularLinkedList& L ); - }; - - template - - class LinkedList : public CircularLinkedList - { - - public: - LinkedList() - {} - - LinkedList( const LinkedList& original_copy ); - ~LinkedList(); - bool operator= ( const LinkedList& original_copy ); - LinkedList& operator++(); // LinkedList A; ++A; - LinkedList& operator++( int ); // Linked List A; A++; - LinkedList& operator--(); // LinkedList A; --A; - LinkedList& operator--( int ); // Linked List A; A--; - - private: - LinkedList Merge( LinkedList L1, LinkedList L2 ); - LinkedList Mergesort( const LinkedList& L ); - - }; - - - template - inline void CircularLinkedList::Beginning( void ) - { - if ( this->root ) - this->position = this->root; - } - - template - inline void CircularLinkedList::End( void ) - { - if ( this->root ) - this->position = this->root->previous; - } - - template - bool LinkedList::operator= ( const LinkedList& original_copy ) - { - typename LinkedList::node * original_copy_pointer, *last, *save_position; - - if ( ( &original_copy ) != this ) - { - - this->Clear(); - - - if ( original_copy.list_size == 0 ) - { - this->root = 0; - this->position = 0; - this->list_size = 0; - } - - else - if ( original_copy.list_size == 1 ) - { - this->root = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // root->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - this->root->next = this->root; - this->root->previous = this->root; - this->list_size = 1; - this->position = this->root; - // *(root->item)=*((original_copy.root)->item); - this->root->item = original_copy.root->item; - } - - else - { - // Setup the first part of the root node - original_copy_pointer = original_copy.root; - this->root = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // root->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - this->position = this->root; - // *(root->item)=*((original_copy.root)->item); - this->root->item = original_copy.root->item; - - if ( original_copy_pointer == original_copy.position ) - save_position = this->position; - - do - { - - - // Save the current element - last = this->position; - - // Point to the next node in the source list - original_copy_pointer = original_copy_pointer->next; - - // Create a new node and point position to it - this->position = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // position->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - - // Copy the item to the new node - // *(position->item)=*(original_copy_pointer->item); - this->position->item = original_copy_pointer->item; - - if ( original_copy_pointer == original_copy.position ) - save_position = this->position; - - - // Set the previous pointer for the new node - ( this->position->previous ) = last; - - // Set the next pointer for the old node to the new node - ( last->next ) = this->position; - - } - - while ( ( original_copy_pointer->next ) != ( original_copy.root ) ); - - // Complete the circle. Set the next pointer of the newest node to the root and the previous pointer of the root to the newest node - this->position->next = this->root; - - this->root->previous = this->position; - - this->list_size = original_copy.list_size; - - this->position = save_position; - } - } - - return true; - } - - - template - CircularLinkedList::CircularLinkedList() - { - this->root = 0; - this->position = 0; - this->list_size = 0; - } - - template - CircularLinkedList::~CircularLinkedList() - { - this->Clear(); - } - - template - LinkedList::~LinkedList() - { - this->Clear(); - } - - template - LinkedList::LinkedList( const LinkedList& original_copy ) - { - typename LinkedList::node * original_copy_pointer, *last, *save_position; - - if ( original_copy.list_size == 0 ) - { - this->root = 0; - this->position = 0; - this->list_size = 0; - return ; - } - - else - if ( original_copy.list_size == 1 ) - { - this->root = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // root->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - this->root->next = this->root; - this->root->previous = this->root; - this->list_size = 1; - this->position = this->root; - // *(root->item) = *((original_copy.root)->item); - this->root->item = original_copy.root->item; - } - - else - { - // Setup the first part of the root node - original_copy_pointer = original_copy.root; - this->root = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // root->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - this->position = this->root; - // *(root->item)=*((original_copy.root)->item); - this->root->item = original_copy.root->item; - - if ( original_copy_pointer == original_copy.position ) - save_position = this->position; - - do - { - // Save the current element - last = this->position; - - // Point to the next node in the source list - original_copy_pointer = original_copy_pointer->next; - - // Create a new node and point position to it - this->position = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // position->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - - // Copy the item to the new node - // *(position->item)=*(original_copy_pointer->item); - this->position->item = original_copy_pointer->item; - - if ( original_copy_pointer == original_copy.position ) - save_position = this->position; - - // Set the previous pointer for the new node - ( this->position->previous ) = last; - - // Set the next pointer for the old node to the new node - ( last->next ) = this->position; - - } - - while ( ( original_copy_pointer->next ) != ( original_copy.root ) ); - - // Complete the circle. Set the next pointer of the newest node to the root and the previous pointer of the root to the newest node - this->position->next = this->root; - - this->root->previous = this->position; - - this->list_size = original_copy.list_size; - - this->position = save_position; - } - } - - template - CircularLinkedList::CircularLinkedList( const CircularLinkedList& original_copy ) - { - node * original_copy_pointer; - node *last; - node *save_position = nullptr; - - if ( original_copy.list_size == 0 ) - { - this->root = 0; - this->position = 0; - this->list_size = 0; - return ; - } - - else - if ( original_copy.list_size == 1 ) - { - this->root = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // root->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - this->root->next = this->root; - this->root->previous = this->root; - this->list_size = 1; - this->position = this->root; - // *(root->item) = *((original_copy.root)->item); - this->root->item = original_copy.root->item; - } - - else - { - // Setup the first part of the root node - original_copy_pointer = original_copy.root; - this->root = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // root->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - this->position = this->root; - // *(root->item)=*((original_copy.root)->item); - this->root->item = original_copy.root->item; - - if ( original_copy_pointer == original_copy.position ) - save_position = this->position; - - do - { - - - // Save the current element - last = this->position; - - // Point to the next node in the source list - original_copy_pointer = original_copy_pointer->next; - - // Create a new node and point position to it - this->position = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // position->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - - // Copy the item to the new node - // *(position->item)=*(original_copy_pointer->item); - this->position->item = original_copy_pointer->item; - - if ( original_copy_pointer == original_copy.position ) - save_position = position; - - // Set the previous pointer for the new node - ( this->position->previous ) = last; - - // Set the next pointer for the old node to the new node - ( last->next ) = this->position; - - } - - while ( ( original_copy_pointer->next ) != ( original_copy.root ) ); - - // Complete the circle. Set the next pointer of the newest node to the root and the previous pointer of the root to the newest node - this->position->next = this->root; - - this->root->previous = position; - - this->list_size = original_copy.list_size; - - this->position = save_position; - } - } - - template - bool CircularLinkedList::operator= ( const CircularLinkedList& original_copy ) - { - node * original_copy_pointer; - node *last; - node *save_position = nullptr; - - if ( ( &original_copy ) != this ) - { - - this->Clear(); - - - if ( original_copy.list_size == 0 ) - { - this->root = 0; - this->position = 0; - this->list_size = 0; - } - - else - if ( original_copy.list_size == 1 ) - { - this->root = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // root->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - this->root->next = this->root; - this->root->previous = this->root; - this->list_size = 1; - this->position = this->root; - // *(root->item)=*((original_copy.root)->item); - this->root->item = original_copy.root->item; - } - - else - { - // Setup the first part of the root node - original_copy_pointer = original_copy.root; - this->root = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // root->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - this->position = this->root; - // *(root->item)=*((original_copy.root)->item); - this->root->item = original_copy.root->item; - - if ( original_copy_pointer == original_copy.position ) - save_position = this->position; - - do - { - // Save the current element - last = this->position; - - // Point to the next node in the source list - original_copy_pointer = original_copy_pointer->next; - - // Create a new node and point position to it - this->position = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // position->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - - // Copy the item to the new node - // *(position->item)=*(original_copy_pointer->item); - this->position->item = original_copy_pointer->item; - - if ( original_copy_pointer == original_copy.position ) - save_position = this->position; - - // Set the previous pointer for the new node - ( this->position->previous ) = last; - - // Set the next pointer for the old node to the new node - ( last->next ) = this->position; - - } - - while ( ( original_copy_pointer->next ) != ( original_copy.root ) ); - - // Complete the circle. Set the next pointer of the newest node to the root and the previous pointer of the root to the newest node - this->position->next = this->root; - - this->root->previous = this->position; - - this->list_size = original_copy.list_size; - - this->position = save_position; - } - } - - return true; - } - - template - void CircularLinkedList::Insert( const CircularLinkedListType& input ) - { - node * new_node; - - if ( list_size == 0 ) - { - this->root = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // root->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - //*(root->item)=input; - this->root->item = input; - this->root->next = this->root; - this->root->previous = this->root; - this->list_size = 1; - this->position = this->root; - } - - else - if ( list_size == 1 ) - { - this->position = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // position->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - this->root->next = this->position; - this->root->previous = this->position; - this->position->previous = this->root; - this->position->next = this->root; - // *(position->item)=input; - this->position->item = input; - this->root = this->position; // Since we're inserting into a 1 element list the old root is now the second item - this->list_size = 2; - } - - else - { - /* - - B - | - A --- C - - position->previous=A - new_node=B - position=C - - Note that the order of the following statements is important */ - - new_node = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // new_node->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - - // *(new_node->item)=input; - new_node->item = input; - - // Point next of A to B - ( this->position->previous ) ->next = new_node; - - // Point last of B to A - new_node->previous = this->position->previous; - - // Point last of C to B - this->position->previous = new_node; - - // Point next of B to C - new_node->next = this->position; - - // Since the root pointer is bound to a node rather than an index this moves it back if you insert an element at the root - - if ( this->position == this->root ) - { - this->root = new_node; - this->position = this->root; - } - - // Increase the recorded size of the list by one - this->list_size++; - } - } - - template - CircularLinkedListType& CircularLinkedList::Add ( const CircularLinkedListType& input ) - { - node * new_node; - - if ( this->list_size == 0 ) - { - this->root = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // root->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // *(root->item)=input; - this->root->item = input; - this->root->next = this->root; - this->root->previous = this->root; - this->list_size = 1; - this->position = this->root; - // return *(position->item); - return this->position->item; - } - - else - if ( list_size == 1 ) - { - this->position = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // position->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - this->root->next = this->position; - this->root->previous = this->position; - this->position->previous = this->root; - this->position->next = this->root; - // *(position->item)=input; - this->position->item = input; - this->list_size = 2; - this->position = this->root; // Don't move the position from the root - // return *(position->item); - return this->position->item; - } - - else - { - /* - - B - | - A --- C - - new_node=B - position=A - position->next=C - - Note that the order of the following statements is important */ - - new_node = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - // new_node->item = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - - // *(new_node->item)=input; - new_node->item = input; - - // Point last of B to A - new_node->previous = this->position; - - // Point next of B to C - new_node->next = ( this->position->next ); - - // Point last of C to B - ( this->position->next ) ->previous = new_node; - - // Point next of A to B - ( this->position->next ) = new_node; - - // Increase the recorded size of the list by one - this->list_size++; - - // return *(new_node->item); - return new_node->item; - } - } - - template - inline void CircularLinkedList::Replace( const CircularLinkedListType& input ) - { - if ( this->list_size > 0 ) - // *(position->item)=input; - this->position->item = input; - } - - template - void CircularLinkedList::Del() - { - node * new_position; - - if ( this->list_size == 0 ) - return ; - - else - if ( this->list_size == 1 ) - { - // MafiaNet::OP_DELETE(root->item, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(this->root, _FILE_AND_LINE_); - this->root = this->position = 0; - this->list_size = 0; - } - - else - { - ( this->position->previous ) ->next = this->position->next; - ( this->position->next ) ->previous = this->position->previous; - new_position = this->position->next; - - if ( this->position == this->root ) - this->root = new_position; - - // MafiaNet::OP_DELETE(position->item, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(this->position, _FILE_AND_LINE_); - - this->position = new_position; - - this->list_size--; - } - } - - template - bool CircularLinkedList::IsIn(const CircularLinkedListType& input ) - { - node * return_value, *old_position; - - old_position = this->position; - - return_value = FindPointer( input ); - this->position = old_position; - - if ( return_value != 0 ) - return true; - else - return false; // Can't find the item don't do anything - } - - template - bool CircularLinkedList::Find( const CircularLinkedListType& input ) - { - node * return_value; - - return_value = FindPointer( input ); - - if ( return_value != 0 ) - { - this->position = return_value; - return true; - } - - else - return false; // Can't find the item don't do anything - } - - template - typename CircularLinkedList::node* CircularLinkedList::FindPointer( const CircularLinkedListType& input ) - { - node * current; - - if ( this->list_size == 0 ) - return 0; - - current = this->root; - - // Search for the item starting from the root node and incrementing the pointer after every check - // If you wind up pointing at the root again you looped around the list so didn't find the item, in which case return 0 - do - { - // if (*(current->item) == input) return current; - - if ( current->item == input ) - return current; - - current = current->next; - } - - while ( current != this->root ); - - return 0; - - } - - template - inline unsigned int CircularLinkedList::Size( void ) - { - return this->list_size; - } - - template - inline CircularLinkedListType& CircularLinkedList::Peek( void ) - { - // return *(position->item); - return this->position->item; - } - - template - CircularLinkedListType CircularLinkedList::Pop( void ) - { - CircularLinkedListType element; - element = Peek(); - Del(); - return CircularLinkedListType( element ); // return temporary - } - - // Prefix - template - CircularLinkedList& CircularLinkedList::operator++() - { - if ( this->list_size != 0 ) - position = position->next; - - return *this; - } - - /* - // Postfix - template - CircularLinkedList& CircularLinkedList::operator++(int) - { - CircularLinkedList before; - before=*this; - operator++(); - return before; - } - */ - - template - CircularLinkedList& CircularLinkedList::operator++( int ) - { - return this->operator++(); - } - - // Prefix - template - CircularLinkedList& CircularLinkedList::operator--() - { - if ( this->list_size != 0 ) - this->position = this->position->previous; - - return *this; - } - - /* - // Postfix - template - CircularLinkedList& CircularLinkedList::operator--(int) - { - CircularLinkedList before; - before=*this; - operator--(); - return before; - } - */ - - template - CircularLinkedList& CircularLinkedList::operator--( int ) - { - return this->operator--(); - } - - template - void CircularLinkedList::Clear( void ) - { - if ( this->list_size == 0 ) - return ; - else - if ( this->list_size == 1 ) // {MafiaNet::OP_DELETE(root->item); MafiaNet::OP_DELETE(root, _FILE_AND_LINE_);} - { - MafiaNet::OP_DELETE(this->root, _FILE_AND_LINE_); - } - - else - { - node* current; - node* temp; - - current = this->root; - - do - { - temp = current; - current = current->next; - // MafiaNet::OP_DELETE(temp->item, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(temp, _FILE_AND_LINE_); - } - - while ( current != this->root ); - } - - this->list_size = 0; - this->root = 0; - this->position = 0; - } - - template - inline void CircularLinkedList::Concatenate( const CircularLinkedList& L ) - { - unsigned int counter; - node* ptr; - - if ( L.list_size == 0 ) - return ; - - if ( this->list_size == 0 ) - * this = L; - - ptr = L.root; - - this->position = this->root->previous; - - // Cycle through each element in L and add it to the current list - for ( counter = 0; counter < L.list_size; counter++ ) - { - // Add item after the current item pointed to - // add(*(ptr->item)); - - Add ( ptr->item ); - - // Update pointers. Moving ptr keeps the current pointer at the end of the list since the add function does not move the pointer - ptr = ptr->next; - - this->position = this->position->next; - } - } - - template - inline void CircularLinkedList::Sort( void ) - { - if ( this->list_size <= 1 ) - return ; - - // Call equal operator to assign result of mergesort to current object - *this = Mergesort( *this ); - - this->position = this->root; - } - - template - CircularLinkedList CircularLinkedList::Mergesort( const CircularLinkedList& L ) - { - unsigned int counter; - node* location; - CircularLinkedList L1; - CircularLinkedList L2; - - location = L.root; - - // Split the list into two equal size sublists, L1 and L2 - - for ( counter = 0; counter < L.list_size / 2; counter++ ) - { - // L1.add (*(location->item)); - L1.Add ( location->item ); - location = location->next; - } - - for ( ;counter < L.list_size; counter++ ) - { - // L2.Add(*(location->item)); - L2.Add ( location->item ); - location = location->next; - } - - // Recursively sort the sublists - if ( L1.list_size > 1 ) - L1 = Mergesort( L1 ); - - if ( L2.list_size > 1 ) - L2 = Mergesort( L2 ); - - // Merge the two sublists - return Merge( L1, L2 ); - } - - template - CircularLinkedList CircularLinkedList::Merge( CircularLinkedList L1, CircularLinkedList L2 ) - { - CircularLinkedList X; - CircularLinkedListType element; - L1.position = L1.root; - L2.position = L2.root; - - // While neither list is empty - - while ( ( L1.list_size != 0 ) && ( L2.list_size != 0 ) ) - { - // Compare the first items of L1 and L2 - // Remove the smaller of the two items from the list - - if ( ( ( L1.root ) ->item ) < ( ( L2.root ) ->item ) ) - // if ((*((L1.root)->item)) < (*((L2.root)->item))) - { - // element = *((L1.root)->item); - element = ( L1.root ) ->item; - L1.Del(); - } - else - { - // element = *((L2.root)->item); - element = ( L2.root ) ->item; - L2.Del(); - } - - // Add this item to the end of X - X.Add( element ); - - X++; - } - - // Add the remaining list to X - if ( L1.list_size != 0 ) - X.Concatenate( L1 ); - else - X.Concatenate( L2 ); - - return X; - } - - template - LinkedList LinkedList::Mergesort( const LinkedList& L ) - { - unsigned int counter; - typename LinkedList::node* location; - LinkedList L1; - LinkedList L2; - - location = L.root; - - // Split the list into two equal size sublists, L1 and L2 - - for ( counter = 0; counter < L.LinkedList_size / 2; counter++ ) - { - // L1.add (*(location->item)); - L1.Add ( location->item ); - location = location->next; - } - - for ( ;counter < L.LinkedList_size; counter++ ) - { - // L2.Add(*(location->item)); - L2.Add ( location->item ); - location = location->next; - } - - // Recursively sort the sublists - if ( L1.list_size > 1 ) - L1 = Mergesort( L1 ); - - if ( L2.list_size > 1 ) - L2 = Mergesort( L2 ); - - // Merge the two sublists - return Merge( L1, L2 ); - } - - template - LinkedList LinkedList::Merge( LinkedList L1, LinkedList L2 ) - { - LinkedList X; - LinkedListType element; - L1.position = L1.root; - L2.position = L2.root; - - // While neither list is empty - - while ( ( L1.LinkedList_size != 0 ) && ( L2.LinkedList_size != 0 ) ) - { - // Compare the first items of L1 and L2 - // Remove the smaller of the two items from the list - - if ( ( ( L1.root ) ->item ) < ( ( L2.root ) ->item ) ) - // if ((*((L1.root)->item)) < (*((L2.root)->item))) - { - element = ( L1.root ) ->item; - // element = *((L1.root)->item); - L1.Del(); - } - else - { - element = ( L2.root ) ->item; - // element = *((L2.root)->item); - L2.Del(); - } - - // Add this item to the end of X - X.Add( element ); - } - - // Add the remaining list to X - if ( L1.LinkedList_size != 0 ) - X.concatenate( L1 ); - else - X.concatenate( L2 ); - - return X; - } - - - // Prefix - template - LinkedList& LinkedList::operator++() - { - if ( ( this->list_size != 0 ) && ( this->position->next != this->root ) ) - this->position = this->position->next; - - return *this; - } - - /* - // Postfix - template - LinkedList& LinkedList::operator++(int) - { - LinkedList before; - before=*this; - operator++(); - return before; - } - */ - // Postfix - template - LinkedList& LinkedList::operator++( int ) - { - return this->operator++(); - } - - // Prefix - template - LinkedList& LinkedList::operator--() - { - if ( ( this->list_size != 0 ) && ( this->position != this->root ) ) - this->position = this->position->previous; - - return *this; - } - - /* - // Postfix - template - LinkedList& LinkedList::operator--(int) - { - LinkedList before; - before=*this; - operator--(); - return before; - } - */ - - // Postfix - template - LinkedList& LinkedList::operator--( int ) - { - return this->operator--(); - } - -} // End namespace - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_List.h b/vendors/mafianet/Source/include/mafianet/DS_List.h deleted file mode 100644 index e4b893eba..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_List.h +++ /dev/null @@ -1,525 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_List.h -/// \internal -/// \brief Array based list. -/// \details Usually the Queue class is used instead, since it has all the same functionality and is only worse at random access. -/// - - -#ifndef __LIST_H -#define __LIST_H - -#include "assert.h" -#include // memmove -#include "Export.h" -#include "memoryoverride.h" - -/// Maximum unsigned long -static const unsigned int MAX_UNSIGNED_LONG = 4294967295U; - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - /// \brief Array based implementation of a list. - /// \note ONLY USE THIS FOR SHALLOW COPIES. I don't bother with operator= to improve performance. - template - class RAK_DLL_EXPORT List - { - public: - /// Default constructor - List(); - - // Destructor - ~List(); - - /// \brief Copy constructor. - /// \param[in] original_copy The list to duplicate - List( const List& original_copy ); - - /// \brief Assign one list to another. - List& operator= ( const List& original_copy ); - - /// \brief Access an element by its index in the array. - /// \param[in] position The index into the array. - /// \return The element at position \a position. - list_type& operator[] ( const unsigned int position ) const; - - /// \brief Access an element by its index in the array. - /// \param[in] position The index into the array. - /// \return The element at position \a position. - list_type& Get ( const unsigned int position ) const; - - /// \brief Push an element at the end of the stack. - /// \param[in] input The new element. - void Push(const list_type &input, const char *file, unsigned int line ); - - /// \brief Pop an element from the end of the stack. - /// \pre Size()>0 - /// \return The element at the end. - list_type& Pop(void); - - /// \brief Insert an element at position \a position in the list. - /// \param[in] input The new element. - /// \param[in] position The position of the new element. - void Insert( const list_type &input, const unsigned int position, const char *file, unsigned int line ); - - /// \brief Insert at the end of the list. - /// \param[in] input The new element. - void Insert( const list_type &input, const char *file, unsigned int line ); - - /// \brief Replace the value at \a position by \a input. - /// \details If the size of the list is less than @em position, it increase the capacity of - /// the list and fill slot with @em filler. - /// \param[in] input The element to replace at position @em position. - /// \param[in] filler The element use to fill new allocated capacity. - /// \param[in] position The position of input in the list. - void Replace( const list_type &input, const list_type filler, const unsigned int position, const char *file, unsigned int line ); - - /// \brief Replace the last element of the list by \a input. - /// \param[in] input The element used to replace the last element. - void Replace( const list_type &input ); - - /// \brief Delete the element at position \a position. - /// \param[in] position The index of the element to delete - void RemoveAtIndex( const unsigned int position ); - - /// \brief Delete the element at position \a position. - /// \note - swaps middle with end of list, only use if list order does not matter - /// \param[in] position The index of the element to delete - void RemoveAtIndexFast( const unsigned int position ); - - /// \brief Delete the element at the end of the list. - void RemoveFromEnd(const unsigned num=1); - - /// \brief Returns the index of the specified item or MAX_UNSIGNED_LONG if not found. - /// \param[in] input The element to check for - /// \return The index or position of @em input in the list. - /// \retval MAX_UNSIGNED_LONG The object is not in the list - /// \retval [Integer] The index of the element in the list - unsigned int GetIndexOf( const list_type &input ) const; - - /// \return The number of elements in the list - unsigned int Size( void ) const; - - /// \brief Clear the list - void Clear( bool doNotDeallocateSmallBlocks, const char *file, unsigned int line ); - - /// \brief Preallocate the list, so it needs fewer reallocations at runtime. - void Preallocate( unsigned countNeeded, const char *file, unsigned int line ); - - /// \brief Frees overallocated members, to use the minimum memory necessary. - /// \attention - /// This is a slow operation - void Compress( const char *file, unsigned int line ); - - private: - /// An array of user values - list_type* listArray; - - /// Number of elements in the list - unsigned int list_size; - - /// Size of \a array - unsigned int allocation_size; - }; - template - List::List() - { - allocation_size = 0; - listArray = 0; - list_size = 0; - } - - template - List::~List() - { - if (allocation_size>0) - MafiaNet::OP_DELETE_ARRAY(listArray, _FILE_AND_LINE_); - } - - - template - List::List( const List& original_copy ) - { - // Allocate memory for copy - - if ( original_copy.list_size == 0 ) - { - list_size = 0; - allocation_size = 0; - } - else - { - listArray = MafiaNet::OP_NEW_ARRAY( original_copy.list_size , _FILE_AND_LINE_ ); - - for ( unsigned int counter = 0; counter < original_copy.list_size; ++counter ) - listArray[ counter ] = original_copy.listArray[ counter ]; - - // Don't call constructors, assignment operators, etc. - //memcpy(listArray, original_copy.listArray, original_copy.list_size*sizeof(list_type)); - - list_size = allocation_size = original_copy.list_size; - } - } - - template - List& List::operator= ( const List& original_copy ) - { - if ( ( &original_copy ) != this ) - { - Clear( false, _FILE_AND_LINE_ ); - - // Allocate memory for copy - - if ( original_copy.list_size == 0 ) - { - list_size = 0; - allocation_size = 0; - } - - else - { - listArray = MafiaNet::OP_NEW_ARRAY( original_copy.list_size , _FILE_AND_LINE_ ); - - for ( unsigned int counter = 0; counter < original_copy.list_size; ++counter ) - listArray[ counter ] = original_copy.listArray[ counter ]; - // Don't call constructors, assignment operators, etc. - //memcpy(listArray, original_copy.listArray, original_copy.list_size*sizeof(list_type)); - - list_size = allocation_size = original_copy.list_size; - } - } - - return *this; - } - - - template - inline list_type& List::operator[] ( const unsigned int position ) const - { - #ifdef _DEBUG - if (position>=list_size) - { - RakAssert ( position < list_size ); - } - #endif - return listArray[ position ]; - } - - // Just here for debugging - template - inline list_type& List::Get ( const unsigned int position ) const - { - return listArray[ position ]; - } - - template - void List::Push(const list_type &input, const char *file, unsigned int line) - { - Insert(input, file, line); - } - - template - inline list_type& List::Pop(void) - { -#ifdef _DEBUG - RakAssert(list_size>0); -#endif - --list_size; - return listArray[list_size]; - } - - template - void List::Insert( const list_type &input, const unsigned int position, const char *file, unsigned int line ) - { - RakAssert( position <= list_size ); - - // Reallocate list if necessary - if ( list_size == allocation_size ) - { - // allocate twice the currently allocated memory - list_type * new_array; - - if ( allocation_size == 0 ) - allocation_size = 16; - else - allocation_size *= 2; - - new_array = MafiaNet::OP_NEW_ARRAY( allocation_size , file, line ); - - // copy old array over - for ( unsigned int counter = 0; counter < list_size; ++counter ) - new_array[ counter ] = listArray[ counter ]; - - // Don't call constructors, assignment operators, etc. - //memcpy(new_array, listArray, list_size*sizeof(list_type)); - - // set old array to point to the newly allocated and twice as large array - MafiaNet::OP_DELETE_ARRAY(listArray, file, line); - - listArray = new_array; - } - - // Move the elements in the list to make room - for ( unsigned int counter = list_size; counter != position; counter-- ) - listArray[ counter ] = listArray[ counter - 1 ]; - - // Don't call constructors, assignment operators, etc. - //memmove(listArray+position+1, listArray+position, (list_size-position)*sizeof(list_type)); - - // Insert the new item at the correct spot - listArray[ position ] = input; - - ++list_size; - - } - - - template - void List::Insert( const list_type &input, const char *file, unsigned int line ) - { - // Reallocate list if necessary - - if ( list_size == allocation_size ) - { - // allocate twice the currently allocated memory - list_type * new_array; - - if ( allocation_size == 0 ) - allocation_size = 16; - else - allocation_size *= 2; - - new_array = MafiaNet::OP_NEW_ARRAY( allocation_size , file, line ); - - if (listArray) - { - // copy old array over - for ( unsigned int counter = 0; counter < list_size; ++counter ) - new_array[ counter ] = listArray[ counter ]; - - // Don't call constructors, assignment operators, etc. - //memcpy(new_array, listArray, list_size*sizeof(list_type)); - - // set old array to point to the newly allocated and twice as large array - MafiaNet::OP_DELETE_ARRAY(listArray, file, line); - } - - listArray = new_array; - } - - // Insert the new item at the correct spot - listArray[ list_size ] = input; - - ++list_size; - } - - template - inline void List::Replace( const list_type &input, const list_type filler, const unsigned int position, const char *file, unsigned int line ) - { - if ( ( list_size > 0 ) && ( position < list_size ) ) - { - // Direct replacement - listArray[ position ] = input; - } - else - { - if ( position >= allocation_size ) - { - // Reallocate the list to size position and fill in blanks with filler - list_type * new_array; - allocation_size = position + 1; - - new_array = MafiaNet::OP_NEW_ARRAY( allocation_size , file, line ); - - // copy old array over - - for ( unsigned int counter = 0; counter < list_size; ++counter ) - new_array[ counter ] = listArray[ counter ]; - - // Don't call constructors, assignment operators, etc. - //memcpy(new_array, listArray, list_size*sizeof(list_type)); - - // set old array to point to the newly allocated array - MafiaNet::OP_DELETE_ARRAY(listArray, file, line); - - listArray = new_array; - } - - // Fill in holes with filler - while ( list_size < position ) - listArray[ list_size++ ] = filler; - - // Fill in the last element with the new item - listArray[ list_size++ ] = input; - -#ifdef _DEBUG - - RakAssert( list_size == position + 1 ); - -#endif - - } - } - - template - inline void List::Replace( const list_type &input ) - { - if ( list_size > 0 ) - listArray[ list_size - 1 ] = input; - } - - template - void List::RemoveAtIndex( const unsigned int position ) - { -#ifdef _DEBUG - if (position >= list_size) - { - RakAssert( position < list_size ); - return; - } -#endif - - if ( position < list_size ) - { - // Compress the array - for ( unsigned int counter = position; counter < list_size - 1 ; ++counter ) - listArray[ counter ] = listArray[ counter + 1 ]; - // Don't call constructors, assignment operators, etc. - // memmove(listArray+position, listArray+position+1, (list_size-1-position) * sizeof(list_type)); - - RemoveFromEnd(); - } - } - - template - void List::RemoveAtIndexFast( const unsigned int position ) - { -#ifdef _DEBUG - if (position >= list_size) - { - RakAssert( position < list_size ); - return; - } -#endif - --list_size; - listArray[position]=listArray[list_size]; - } - - template - inline void List::RemoveFromEnd( const unsigned num ) - { - // Delete the last elements on the list. No compression needed -#ifdef _DEBUG - RakAssert(list_size>=num); -#endif - list_size-=num; - } - - template - unsigned int List::GetIndexOf( const list_type &input ) const - { - for ( unsigned int i = 0; i < list_size; ++i ) - if ( listArray[ i ] == input ) - return i; - - return MAX_UNSIGNED_LONG; - } - - template - inline unsigned int List::Size( void ) const - { - return list_size; - } - - template - void List::Clear( bool doNotDeallocateSmallBlocks, const char *file, unsigned int line ) - { - if ( allocation_size == 0 ) - return; - - if (allocation_size>512 || doNotDeallocateSmallBlocks==false) - { - MafiaNet::OP_DELETE_ARRAY(listArray, file, line); - allocation_size = 0; - listArray = 0; - } - list_size = 0; - } - - template - void List::Compress( const char *file, unsigned int line ) - { - list_type * new_array; - - if ( allocation_size == 0 ) - return ; - - new_array = MafiaNet::OP_NEW_ARRAY( allocation_size , file, line ); - - // copy old array over - for ( unsigned int counter = 0; counter < list_size; ++counter ) - new_array[ counter ] = listArray[ counter ]; - - // Don't call constructors, assignment operators, etc. - //memcpy(new_array, listArray, list_size*sizeof(list_type)); - - // set old array to point to the newly allocated array - MafiaNet::OP_DELETE_ARRAY(listArray, file, line); - - listArray = new_array; - } - - template - void List::Preallocate( unsigned countNeeded, const char *file, unsigned int line ) - { - unsigned amountToAllocate = allocation_size; - if (allocation_size==0) - amountToAllocate=16; - while (amountToAllocate < countNeeded) - amountToAllocate<<=1; - - if ( allocation_size < amountToAllocate) - { - // allocate twice the currently allocated memory - list_type * new_array; - - allocation_size=amountToAllocate; - - new_array = MafiaNet::OP_NEW_ARRAY< list_type >( allocation_size , file, line ); - - if (listArray) - { - // copy old array over - for ( unsigned int counter = 0; counter < list_size; ++counter ) - new_array[ counter ] = listArray[ counter ]; - - // Don't call constructors, assignment operators, etc. - //memcpy(new_array, listArray, list_size*sizeof(list_type)); - - // set old array to point to the newly allocated and twice as large array - MafiaNet::OP_DELETE_ARRAY(listArray, file, line); - } - - listArray = new_array; - } - } - -} // End namespace - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_Map.h b/vendors/mafianet/Source/include/mafianet/DS_Map.h deleted file mode 100644 index 06581bb82..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_Map.h +++ /dev/null @@ -1,330 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_Map.h -/// \internal -/// \brief Map -/// - - -#ifndef __RAKNET_MAP_H -#define __RAKNET_MAP_H - -#include "DS_OrderedList.h" -#include "Export.h" -#include "memoryoverride.h" -#include "assert.h" - -// If I want to change this to a red-black tree, this is a good site: http://www.cs.auckland.ac.nz/software/AlgAnim/red_black.html -// This makes insertions and deletions faster. But then traversals are slow, while they are currently fast. - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - /// The default comparison has to be first so it can be called as a default parameter. - /// It then is followed by MapNode, followed by NodeComparisonFunc - template - int defaultMapKeyComparison(const key_type &a, const key_type &b) - { - if (a > - class RAK_DLL_EXPORT Map - { - public: - static void IMPLEMENT_DEFAULT_COMPARISON(void) {DataStructures::defaultMapKeyComparison(key_type(),key_type());} - - struct MapNode - { - MapNode() {} - MapNode(key_type _key, data_type _data) : mapNodeKey(_key), mapNodeData(_data) {} - MapNode& operator = ( const MapNode& input ) {mapNodeKey=input.mapNodeKey; mapNodeData=input.mapNodeData; return *this;} - MapNode( const MapNode & input) {mapNodeKey=input.mapNodeKey; mapNodeData=input.mapNodeData;} - key_type mapNodeKey; - data_type mapNodeData; - }; - - // Has to be a static because the comparison callback for DataStructures::OrderedList is a C function - static int NodeComparisonFunc(const key_type &a, const MapNode &b) - { - return key_comparison_func(a, b.mapNodeKey); - } - - Map(); - ~Map(); - Map( const Map& original_copy ); - Map& operator= ( const Map& original_copy ); - - data_type& Get(const key_type &key) const; - data_type Pop(const key_type &key); - // Add if needed - void Set(const key_type &key, const data_type &data); - // Must already exist - void SetExisting(const key_type &key, const data_type &data); - // Must add - void SetNew(const key_type &key, const data_type &data); - bool Has(const key_type &key) const; - bool Delete(const key_type &key); - data_type& operator[] ( const unsigned int position ) const; - key_type GetKeyAtIndex( const unsigned int position ) const; - unsigned GetIndexAtKey( const key_type &key ); - void RemoveAtIndex(const unsigned index); - void Clear(void); - unsigned Size(void) const; - - protected: - DataStructures::OrderedList< key_type,MapNode,&Map::NodeComparisonFunc > mapNodeList; - - void SaveLastSearch(const key_type &key, unsigned index) const; - bool HasSavedSearchResult(const key_type &key) const; - - unsigned lastSearchIndex; - key_type lastSearchKey; - bool lastSearchIndexValid; - }; - - template - Map::Map() - { - lastSearchIndexValid=false; - } - - template - Map::~Map() - { - Clear(); - } - - template - Map::Map( const Map& original_copy ) - { - mapNodeList=original_copy.mapNodeList; - lastSearchIndex=original_copy.lastSearchIndex; - lastSearchKey=original_copy.lastSearchKey; - lastSearchIndexValid=original_copy.lastSearchIndexValid; - } - - template - Map& Map::operator= ( const Map& original_copy ) - { - mapNodeList=original_copy.mapNodeList; - lastSearchIndex=original_copy.lastSearchIndex; - lastSearchKey=original_copy.lastSearchKey; - lastSearchIndexValid=original_copy.lastSearchIndexValid; - return *this; - } - - template - data_type& Map::Get(const key_type &key) const - { - if (HasSavedSearchResult(key)) - return mapNodeList[lastSearchIndex].mapNodeData; - - bool objectExists; - unsigned index; - index=mapNodeList.GetIndexFromKey(key, &objectExists); - RakAssert(objectExists); - SaveLastSearch(key,index); - return mapNodeList[index].mapNodeData; - } - - template - unsigned Map::GetIndexAtKey( const key_type &key ) - { - if (HasSavedSearchResult(key)) - return lastSearchIndex; - - bool objectExists; - unsigned index; - index=mapNodeList.GetIndexFromKey(key, &objectExists); - if (objectExists==false) - { - RakAssert(objectExists); - } - SaveLastSearch(key,index); - return index; - } - - template - void Map::RemoveAtIndex(const unsigned index) - { - mapNodeList.RemoveAtIndex(index); - lastSearchIndexValid=false; - } - - template - data_type Map::Pop(const key_type &key) - { - bool objectExists; - unsigned index; - if (HasSavedSearchResult(key)) - index=lastSearchIndex; - else - { - index=mapNodeList.GetIndexFromKey(key, &objectExists); - RakAssert(objectExists); - } - data_type tmp = mapNodeList[index].mapNodeData; - mapNodeList.RemoveAtIndex(index); - lastSearchIndexValid=false; - return tmp; - } - - template - void Map::Set(const key_type &key, const data_type &data) - { - bool objectExists; - unsigned index; - - if (HasSavedSearchResult(key)) - { - mapNodeList[lastSearchIndex].mapNodeData=data; - return; - } - - index=mapNodeList.GetIndexFromKey(key, &objectExists); - - if (objectExists) - { - SaveLastSearch(key,index); - mapNodeList[index].mapNodeData=data; - } - else - { - SaveLastSearch(key,mapNodeList.Insert(key,MapNode(key,data), true, _FILE_AND_LINE_)); - } - } - - template - void Map::SetExisting(const key_type &key, const data_type &data) - { - bool objectExists; - unsigned index; - - if (HasSavedSearchResult(key)) - { - index=lastSearchIndex; - } - else - { - index=mapNodeList.GetIndexFromKey(key, &objectExists); - RakAssert(objectExists); - SaveLastSearch(key,index); - } - - mapNodeList[index].mapNodeData=data; - } - - template - void Map::SetNew(const key_type &key, const data_type &data) - { -#ifdef _DEBUG - bool objectExists; - mapNodeList.GetIndexFromKey(key, &objectExists); - RakAssert(objectExists==false); -#endif - SaveLastSearch(key,mapNodeList.Insert(key,MapNode(key,data), true, _FILE_AND_LINE_)); - } - - template - bool Map::Has(const key_type &key) const - { - if (HasSavedSearchResult(key)) - return true; - - bool objectExists; - unsigned index; - index=mapNodeList.GetIndexFromKey(key, &objectExists); - if (objectExists) - SaveLastSearch(key,index); - return objectExists; - } - - template - bool Map::Delete(const key_type &key) - { - if (HasSavedSearchResult(key)) - { - lastSearchIndexValid=false; - mapNodeList.RemoveAtIndex(lastSearchIndex); - return true; - } - - bool objectExists; - unsigned index; - index=mapNodeList.GetIndexFromKey(key, &objectExists); - if (objectExists) - { - lastSearchIndexValid=false; - mapNodeList.RemoveAtIndex(index); - return true; - } - else - return false; - } - - template - void Map::Clear(void) - { - lastSearchIndexValid=false; - mapNodeList.Clear(false, _FILE_AND_LINE_); - } - - template - data_type& Map::operator[]( const unsigned int position ) const - { - return mapNodeList[position].mapNodeData; - } - - template - key_type Map::GetKeyAtIndex( const unsigned int position ) const - { - return mapNodeList[position].mapNodeKey; - } - - template - unsigned Map::Size(void) const - { - return mapNodeList.Size(); - } - - template - void Map::SaveLastSearch(const key_type &key, const unsigned index) const - { - (void) key; - (void) index; - - /* - lastSearchIndex=index; - lastSearchKey=key; - lastSearchIndexValid=true; - */ - } - - template - bool Map::HasSavedSearchResult(const key_type &key) const - { - (void) key; - - // Not threadsafe! - return false; - // return lastSearchIndexValid && key_comparison_func(key,lastSearchKey)==0; - } -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_MemoryPool.h b/vendors/mafianet/Source/include/mafianet/DS_MemoryPool.h deleted file mode 100644 index 5b2e7c59b..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_MemoryPool.h +++ /dev/null @@ -1,358 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_MemoryPool.h -/// - - -#ifndef __MEMORY_POOL_H -#define __MEMORY_POOL_H - -#ifndef __APPLE__ -// Use stdlib and not malloc for compatibility -#include -#endif -#include "assert.h" -#include "Export.h" - -#include "memoryoverride.h" - -// DS_MEMORY_POOL_MAX_FREE_PAGES must be > 1 -#define DS_MEMORY_POOL_MAX_FREE_PAGES 4 - -//#define _DISABLE_MEMORY_POOL - -namespace DataStructures -{ - /// Very fast memory pool for allocating and deallocating structures that don't have constructors or destructors. - /// Contains a list of pages, each of which has an array of the user structures - template - class RAK_DLL_EXPORT MemoryPool - { - public: - struct Page; - struct MemoryWithPage - { - MemoryBlockType userMemory; - Page *parentPage; - }; - struct Page - { - MemoryWithPage** availableStack; - int availableStackSize; - MemoryWithPage* block; - Page *next, *prev; - }; - - MemoryPool(); - ~MemoryPool(); - void SetPageSize(int size); // Defaults to 16384 bytes - MemoryBlockType *Allocate(const char *file, unsigned int line); - void Release(MemoryBlockType *m, const char *file, unsigned int line); - void Clear(const char *file, unsigned int line); - - int GetAvailablePagesSize(void) const {return availablePagesSize;} - int GetUnavailablePagesSize(void) const {return unavailablePagesSize;} - int GetMemoryPoolPageSize(void) const {return memoryPoolPageSize;} - protected: - int BlocksPerPage(void) const; - void AllocateFirst(void); - bool InitPage(Page *page, Page *prev, const char *file, unsigned int line); - - // availablePages contains pages which have room to give the user new blocks. We return these blocks from the head of the list - // unavailablePages are pages which are totally full, and from which we do not return new blocks. - // Pages move from the head of unavailablePages to the tail of availablePages, and from the head of availablePages to the tail of unavailablePages - Page *availablePages, *unavailablePages; - int availablePagesSize, unavailablePagesSize; - int memoryPoolPageSize; - }; - - template - MemoryPool::MemoryPool() - { -#ifndef _DISABLE_MEMORY_POOL - //AllocateFirst(); - availablePagesSize=0; - unavailablePagesSize=0; - memoryPoolPageSize=16384; -#endif - } - template - MemoryPool::~MemoryPool() - { -#ifndef _DISABLE_MEMORY_POOL - Clear(_FILE_AND_LINE_); -#endif - } - - template - void MemoryPool::SetPageSize(int size) - { - memoryPoolPageSize=size; - } - - template - MemoryBlockType* MemoryPool::Allocate(const char *file, unsigned int line) - { -#ifdef _DISABLE_MEMORY_POOL - return (MemoryBlockType*) rakMalloc_Ex(sizeof(MemoryBlockType), file, line); -#else - - if (availablePagesSize>0) - { - MemoryBlockType *retVal; - Page *curPage; - curPage=availablePages; - retVal = (MemoryBlockType*) curPage->availableStack[--(curPage->availableStackSize)]; - if (curPage->availableStackSize==0) - { - --availablePagesSize; - availablePages=curPage->next; - RakAssert(availablePagesSize==0 || availablePages->availableStackSize>0); - curPage->next->prev=curPage->prev; - curPage->prev->next=curPage->next; - - if (unavailablePagesSize++==0) - { - unavailablePages=curPage; - curPage->next=curPage; - curPage->prev=curPage; - } - else - { - curPage->next=unavailablePages; - curPage->prev=unavailablePages->prev; - unavailablePages->prev->next=curPage; - unavailablePages->prev=curPage; - } - } - - RakAssert(availablePagesSize==0 || availablePages->availableStackSize>0); - return retVal; - } - - availablePages = (Page *) rakMalloc_Ex(sizeof(Page), file, line); - if (availablePages==0) - return 0; - availablePagesSize=1; - if (InitPage(availablePages, availablePages, file, line)==false) - return 0; - // If this assert hits, we couldn't allocate even 1 block per page. Increase the page size - RakAssert(availablePages->availableStackSize>1); - - return (MemoryBlockType *) availablePages->availableStack[--availablePages->availableStackSize]; -#endif - } - template - void MemoryPool::Release(MemoryBlockType *m, const char *file, unsigned int line) - { -#ifdef _DISABLE_MEMORY_POOL - rakFree_Ex(m, file, line); - return; -#else - // Find the page this block is in and return it. - Page *curPage; - MemoryWithPage *memoryWithPage = (MemoryWithPage*)m; - curPage=memoryWithPage->parentPage; - - if (curPage->availableStackSize==0) - { - // The page is in the unavailable list so move it to the available list - curPage->availableStack[curPage->availableStackSize++]=memoryWithPage; - unavailablePagesSize--; - - // As this page is no longer totally empty, move it to the end of available pages - curPage->next->prev=curPage->prev; - curPage->prev->next=curPage->next; - - if (unavailablePagesSize>0 && curPage==unavailablePages) - unavailablePages=unavailablePages->next; - - if (availablePagesSize++==0) - { - availablePages=curPage; - curPage->next=curPage; - curPage->prev=curPage; - } - else - { - curPage->next=availablePages; - curPage->prev=availablePages->prev; - availablePages->prev->next=curPage; - availablePages->prev=curPage; - } - } - else - { - curPage->availableStack[curPage->availableStackSize++]=memoryWithPage; - - if (curPage->availableStackSize==BlocksPerPage() && - availablePagesSize>=DS_MEMORY_POOL_MAX_FREE_PAGES) - { - // After a certain point, just deallocate empty pages rather than keep them around - if (curPage==availablePages) - { - availablePages=curPage->next; - RakAssert(availablePages->availableStackSize>0); - } - curPage->prev->next=curPage->next; - curPage->next->prev=curPage->prev; - availablePagesSize--; - rakFree_Ex(curPage->availableStack, file, line ); - rakFree_Ex(curPage->block, file, line ); - rakFree_Ex(curPage, file, line ); - } - } -#endif - } - template - void MemoryPool::Clear(const char *file, unsigned int line) - { -#ifdef _DISABLE_MEMORY_POOL - return; -#else - Page *cur, *freed; - - if (availablePagesSize>0) - { - cur = availablePages; - for (;;) - // do - { - rakFree_Ex(cur->availableStack, file, line ); - rakFree_Ex(cur->block, file, line ); - freed=cur; - cur=cur->next; - if (cur==availablePages) - { - rakFree_Ex(freed, file, line ); - break; - } - rakFree_Ex(freed, file, line ); - }// while(cur!=availablePages); - } - - if (unavailablePagesSize>0) - { - cur = unavailablePages; - for(;;) - //do - { - rakFree_Ex(cur->availableStack, file, line ); - rakFree_Ex(cur->block, file, line ); - freed=cur; - cur=cur->next; - if (cur==unavailablePages) - { - rakFree_Ex(freed, file, line ); - break; - } - rakFree_Ex(freed, file, line ); - } // while(cur!=unavailablePages); - } - - availablePagesSize=0; - unavailablePagesSize=0; -#endif - } - template - int MemoryPool::BlocksPerPage(void) const - { - return memoryPoolPageSize / sizeof(MemoryWithPage); - } - template - bool MemoryPool::InitPage(Page *page, Page *prev, const char *file, unsigned int line) - { - int i=0; - const int bpp = BlocksPerPage(); - page->block=(MemoryWithPage*) rakMalloc_Ex(memoryPoolPageSize, file, line); - if (page->block==0) - return false; - page->availableStack=(MemoryWithPage**)rakMalloc_Ex(sizeof(MemoryWithPage*)*bpp, file, line); - if (page->availableStack==0) - { - rakFree_Ex(page->block, file, line ); - return false; - } - MemoryWithPage *curBlock = page->block; - MemoryWithPage **curStack = page->availableStack; - while (i < bpp) - { - curBlock->parentPage=page; - curStack[i]=curBlock++; - i++; - } - page->availableStackSize=bpp; - page->next=availablePages; - page->prev=prev; - return true; - } -} - -#endif - -/* -#include "DS_MemoryPool.h" -#include "DS_List.h" - -struct TestMemoryPool -{ - int allocationId; -}; - -int main(void) -{ - DataStructures::MemoryPool memoryPool; - DataStructures::List returnList; - - for (int i=0; i < 100000; i++) - returnList.Push(memoryPool.Allocate(_FILE_AND_LINE_), _FILE_AND_LINE_); - for (int i=0; i < returnList.Size(); i+=2) - { - memoryPool.Release(returnList[i], _FILE_AND_LINE_); - returnList.RemoveAtIndexFast(i); - } - for (int i=0; i < 100000; i++) - returnList.Push(memoryPool.Allocate(_FILE_AND_LINE_), _FILE_AND_LINE_); - while (returnList.Size()) - { - memoryPool.Release(returnList[returnList.Size()-1], _FILE_AND_LINE_); - returnList.RemoveAtIndex(returnList.Size()-1); - } - for (int i=0; i < 100000; i++) - returnList.Push(memoryPool.Allocate(_FILE_AND_LINE_), _FILE_AND_LINE_); - while (returnList.Size()) - { - memoryPool.Release(returnList[returnList.Size()-1], _FILE_AND_LINE_); - returnList.RemoveAtIndex(returnList.Size()-1); - } - for (int i=0; i < 100000; i++) - returnList.Push(memoryPool.Allocate(_FILE_AND_LINE_), _FILE_AND_LINE_); - for (int i=100000-1; i <= 0; i-=2) - { - memoryPool.Release(returnList[i], _FILE_AND_LINE_); - returnList.RemoveAtIndexFast(i); - } - for (int i=0; i < 100000; i++) - returnList.Push(memoryPool.Allocate(_FILE_AND_LINE_), _FILE_AND_LINE_); - while (returnList.Size()) - { - memoryPool.Release(returnList[returnList.Size()-1], _FILE_AND_LINE_); - returnList.RemoveAtIndex(returnList.Size()-1); - } - - return 0; -} -*/ diff --git a/vendors/mafianet/Source/include/mafianet/DS_Multilist.h b/vendors/mafianet/Source/include/mafianet/DS_Multilist.h deleted file mode 100644 index c7f1dda80..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_Multilist.h +++ /dev/null @@ -1,1660 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_Multilist.h -/// \internal -/// \brief ADT that can represent an unordered list, ordered list, stack, or queue with a common interface -/// - -#ifndef __MULTILIST_H -#define __MULTILIST_H - -#include "assert.h" -#include // memmove -#include "Export.h" -#include "memoryoverride.h" -#include "NativeTypes.h" - - -/// What algorithm to use to store the data for the Multilist -enum MultilistType -{ - /// Removing from the middle of the list will swap the end of the list rather than shift the elements. Push and Pop operate on the tail. - ML_UNORDERED_LIST, - /// A normal list, with the list order preserved. Push and Pop operate on the tail. - ML_STACK, - /// A queue. Push and Pop operate on the head - ML_QUEUE, - /// A list that is always kept in order. Elements must be unique, and compare against each other consistently using <, ==, and > - ML_ORDERED_LIST, - /// A list whose type can change at runtime - ML_VARIABLE_DURING_RUNTIME -}; - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - /// Can be used with Multilist::ForEach - /// Assuming the Multilist holds pointers, will delete those pointers - template - void DeletePtr_RakNet(templateType &ptr, const char *file, unsigned int line ) { MafiaNet::OP_DELETE(ptr, file, line);} - - /// Can be used with Multilist::ForEach - /// Assuming the Multilist holds pointers, will delete those pointers - template - void DeletePtr(templateType &ptr) {delete ptr;} - - /// The following is invalid. - /// bool operator<( const MyClass *myClass, const int &inputKey ) {return myClass->value < inputKey;} - /// At least one type has to be a reference to a class - /// MLKeyRef is a helper class to turn a native type into a class, so you can compare that native type against a pointer to a different class - /// Used for he Multilist, when _DataType != _KeyType - template < class templateType > - class MLKeyRef - { - public: - MLKeyRef(const templateType& input) : val(input) {} - const templateType &Get(void) const {return val;} - bool operator<( const templateType &right ) {return val < right;} - bool operator>( const templateType &right ) {return val > right;} - bool operator==( const templateType &right ) {return val == right;} - protected: - const templateType &val; - private: - // MLKeyRef is not copy-assignable - MLKeyRef& operator=(const MLKeyRef& master); - }; - - /// For the Multilist, when _DataType != _KeyType, you must define the comparison operators between the key and the data - /// This is non-trivial due to the need to use MLKeyRef in case the type held is a pointer to a structure or class and the key type is not a class - /// For convenience, this macro will implement the comparison operators under the following conditions - /// 1. _DataType is a pointer to a class or structure - /// 2. The key is a member variable of _DataType - #define DEFINE_MULTILIST_PTR_TO_MEMBER_COMPARISONS( _CLASS_NAME_, _KEY_TYPE_, _MEMBER_VARIABLE_NAME_ ) \ - bool operator<( const DataStructures::MLKeyRef<_KEY_TYPE_> &inputKey, const _CLASS_NAME_ *cls ) {return inputKey.Get() < cls->_MEMBER_VARIABLE_NAME_;} \ - bool operator>( const DataStructures::MLKeyRef<_KEY_TYPE_> &inputKey, const _CLASS_NAME_ *cls ) {return inputKey.Get() > cls->_MEMBER_VARIABLE_NAME_;} \ - bool operator==( const DataStructures::MLKeyRef<_KEY_TYPE_> &inputKey, const _CLASS_NAME_ *cls ) {return inputKey.Get() == cls->_MEMBER_VARIABLE_NAME_;} - - typedef uint32_t DefaultIndexType; - - /// \brief The multilist, representing an abstract data type that generally holds lists. - /// \param[in] _MultilistType What type of list this is, \sa MultilistType - /// \param[in] _DataType What type of data this list holds. - /// \param[in] _KeyType If a function takes a key to sort on, what type of key this is. The comparison operator between _DataType and _KeyType must be defined - /// \param[in] _IndexType What variable type to use for indices - template - class RAK_DLL_EXPORT Multilist - { - public: - Multilist(); - ~Multilist(); - Multilist( const Multilist& source ); - Multilist& operator= ( const Multilist& source ); - _DataType& operator[] ( const _IndexType position ) const; - /// Unordered list, stack is LIFO - /// QUEUE is FIFO - /// Ordered list is inserted in order - void Push(const _DataType &d, const char *file=__FILE__, unsigned int line=__LINE__ ); - void Push(const _DataType &d, const _KeyType &key, const char *file=__FILE__, unsigned int line=__LINE__ ); - - /// \brief Gets or removes and gets an element from the list, according to the same rules as Push(). - /// Ordered list is LIFO for the purposes of Pop and Peek. - _DataType &Pop(const char *file=__FILE__, unsigned int line=__LINE__); - _DataType &Peek(void) const; - - /// \brief Same as Push(), except FIFO and LIFO are reversed. - /// Ordered list still inserts in order. - void PushOpposite(const _DataType &d, const char *file=__FILE__, unsigned int line=__LINE__ ); - void PushOpposite(const _DataType &d, const _KeyType &key, const char *file=__FILE__, unsigned int line=__LINE__ ); - - /// \brief Same as Pop() and Peek(), except FIFO and LIFO are reversed. - _DataType &PopOpposite(const char *file=__FILE__, unsigned int line=__LINE__); - _DataType &PeekOpposite(void) const; - - /// \brief Stack,Queue: Inserts at index indicated, elements are shifted. - /// Ordered list: Inserts, position is ignored - void InsertAtIndex(const _DataType &d, _IndexType index, const char *file=__FILE__, unsigned int line=__LINE__); - - /// \brief Unordered list, removes at index indicated, swaps last element with that element. - /// Otherwise, array is shifted left to overwrite removed element - /// \details Index[0] returns the same as Pop() for a queue. - /// Same as PopOpposite() for the list and ordered list - void RemoveAtIndex(_IndexType position, const char *file=__FILE__, unsigned int line=__LINE__); - - /// \brief Find the index of \a key, and remove at that index. - bool RemoveAtKey(_KeyType key, bool assertIfDoesNotExist, const char *file=__FILE__, unsigned int line=__LINE__); - - /// \brief Finds the index of \a key. Return -1 if the key is not found. - _IndexType GetIndexOf(_KeyType key) const; - - /// \brief Returns where in the list we should insert the item, to preserve list order. - /// Returns -1 if the item is already in the list - _IndexType GetInsertionIndex(_KeyType key) const; - - /// \brief Finds the index of \a key. Return 0 if the key is not found. Useful if _DataType is always non-zero pointers. - _DataType GetPtr(_KeyType key) const; - - /// \brief Iterate over the list, calling the function pointer on each element. - void ForEach(void (*func)(_DataType &item, const char *file, unsigned int line), const char *file, unsigned int line); - void ForEach(void (*func)(_DataType &item)); - - /// \brief Returns if the list is empty. - bool IsEmpty(void) const; - - /// \brief Returns the number of elements used in the list. - _IndexType GetSize(void) const; - - /// \brief Empties the list. The list is not deallocated if it is small, - /// unless \a deallocateSmallBlocks is true - void Clear( bool deallocateSmallBlocks=true, const char *file=__FILE__, unsigned int line=__LINE__ ); - - /// \brief Empties the list, first calling MafiaNet::OP_Delete on all items. - /// \details The list is not deallocated if it is small, unless \a deallocateSmallBlocks is true - void ClearPointers( bool deallocateSmallBlocks=true, const char *file=__FILE__, unsigned int line=__LINE__ ); - - /// \brief Empty one item from the list, first calling MafiaNet::OP_Delete on that item. - void ClearPointer( _KeyType key, const char *file=__FILE__, unsigned int line=__LINE__ ); - - /// \brief Reverses the elements in the list, and flips the sort order - /// returned by GetSortOrder() if IsSorted() returns true at the time the function is called - void ReverseList(void); - - /// \brief Reallocates the list to a larger size. - /// If \a size is smaller than the value returned by GetSize(), the call does nothing. - void Reallocate(_IndexType size, const char *file=__FILE__, unsigned int line=__LINE__); - - /// \brief Sorts the list unless it is an ordered list, in which it does nothing as the list is assumed to already be sorted. - /// \details However, if \a force is true, it will also resort the ordered list, useful if the comparison operator between _KeyType and _DataType would now return different results - /// Once the list is sorted, further operations to lookup by key will be log2(n) until the list is modified - void Sort(bool force); - - /// \brief Sets the list to be remembered as sorted. - /// \details Optimization if the source is sorted already - void TagSorted(void); - - /// \brief Defaults to ascending. - /// \details Used by Sort(), and by ML_ORDERED_LIST - void SetSortOrder(bool ascending); - - /// \brief Returns true if ascending. - bool GetSortOrder(void) const; - - /// \brief Returns true if the list is currently believed to be in a sorted state. - /// \details Doesn't actually check for sortedness, just if Sort() - /// was recently called, or MultilistType is ML_ORDERED_LIST - bool IsSorted(void) const; - - /// Returns what type of list this is - MultilistType GetMultilistType(void) const; - - /// \brief Changes what type of list this is. - /// \pre Template must be defined with ML_VARIABLE_DURING_RUNTIME for this to do anything - /// \param[in] mlType Any value of the enum MultilistType, except ML_VARIABLE_DURING_RUNTIME - void SetMultilistType(MultilistType newType); - - /// \brief Returns the intersection of two lists. - /// Intersection is items common to both lists. - static void FindIntersection( - Multilist& source1, - Multilist& source2, - Multilist& intersection, - Multilist& uniqueToSource1, - Multilist& uniqueToSource2); - - protected: - void ReallocateIfNeeded(const char *file, unsigned int line); - void DeallocateIfNeeded(const char *file, unsigned int line); - void ReallocToSize(_IndexType newAllocationSize, const char *file, unsigned int line); - void ReverseListInternal(void); - void InsertInOrderedList(const _DataType &d, const _KeyType &key); - _IndexType GetIndexFromKeyInSortedList(const _KeyType &key, bool *objectExists) const; - void InsertShiftArrayRight(const _DataType &d, _IndexType index); - void DeleteShiftArrayLeft(_IndexType index); - void QSortAscending(_IndexType left, _IndexType right); - void QSortDescending(_IndexType left, _IndexType right); - void CopySource( const Multilist& source ); - - /// An array of user values - _DataType* data; - - /// Number of elements in the list - _IndexType dataSize; - - /// Size of \a array - _IndexType allocationSize; - - /// Array index for the head of the queue - _IndexType queueHead; - - /// Array index for the tail of the queue - _IndexType queueTail; - - /// How many bytes the user chose to preallocate - /// Won't automatically deallocate below this - _IndexType preallocationSize; - - enum - { - ML_UNSORTED, - ML_SORTED_ASCENDING, - ML_SORTED_DESCENDING - } sortState; - - bool ascendingSort; - - // In case we are using the variable type multilist - MultilistType variableMultilistType; - }; - - template - Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Multilist() - { - data=0; - dataSize=0; - allocationSize=0; - ascendingSort=true; - sortState=ML_UNSORTED; - queueHead=0; - queueTail=0; - preallocationSize=0; - -#pragma warning( push ) -#pragma warning(disable:4127) // conditional expression is constant - if (_MultilistType==ML_ORDERED_LIST) - sortState=ML_SORTED_ASCENDING; - else - sortState=ML_UNSORTED; - - if (_MultilistType==ML_VARIABLE_DURING_RUNTIME) - variableMultilistType=ML_UNORDERED_LIST; -#pragma warning( pop ) - } - - template - Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::~Multilist() - { - if (data!=0) - MafiaNet::OP_DELETE_ARRAY(data, _FILE_AND_LINE_); - } - - template - Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Multilist( const Multilist& source ) - { - CopySource(source); - } - - template - Multilist<_MultilistType, _DataType, _KeyType, _IndexType>& Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::operator= ( const Multilist& source ) - { - Clear(true); - CopySource(source); - return *this; - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::CopySource( const Multilist& source ) - { - dataSize=source.GetSize(); - ascendingSort=source.ascendingSort; - sortState=source.sortState; - queueHead=0; - queueTail=dataSize; - preallocationSize=source.preallocationSize; - variableMultilistType=source.variableMultilistType; - if (source.data==0) - { - data=0; - allocationSize=0; - } - else - { - allocationSize=dataSize; - data = MafiaNet::OP_NEW_ARRAY<_DataType>(dataSize,_FILE_AND_LINE_); - _IndexType i; - for (i=0; i < dataSize; i++) - data[i]=source[i]; - } - } - - template - _DataType& Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::operator[] ( const _IndexType position ) const - { - RakAssert(position= allocationSize ) - return data[ queueHead + position - allocationSize ]; - else - return data[ queueHead + position ]; - } - - return data[position]; - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Push(const _DataType &d, const char *file, unsigned int line ) - { - Push(d,d,file,line); - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Push(const _DataType &d, const _KeyType &key, const char *file, unsigned int line ) - { - ReallocateIfNeeded(file,line); - - if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK) - { - data[dataSize]=d; - dataSize++; - } - else if (GetMultilistType()==ML_QUEUE) - { - data[queueTail++] = d; - - if ( queueTail == allocationSize ) - queueTail = 0; - dataSize++; - } - else - { - RakAssert(GetMultilistType()==ML_ORDERED_LIST); - InsertInOrderedList(d,key); - } - - if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK || GetMultilistType()==ML_QUEUE) - { - // Break sort if no longer sorted - if (sortState!=ML_UNSORTED && dataSize>1) - { - if (ascendingSort) - { - if ( MLKeyRef<_KeyType>(key) < operator[](dataSize-2) ) - sortState=ML_UNSORTED; - } - else - { - if ( MLKeyRef<_KeyType>(key) > operator[](dataSize-2) ) - sortState=ML_UNSORTED; - } - - sortState=ML_UNSORTED; - } - } - } - - template - _DataType &Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Pop(const char *file, unsigned int line) - { - RakAssert(IsEmpty()==false); - DeallocateIfNeeded(file,line); - if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK || GetMultilistType()==ML_ORDERED_LIST) - { - dataSize--; - return data[dataSize]; - } - else - { - RakAssert(GetMultilistType()==ML_QUEUE); - - if ( ++queueHead == allocationSize ) - queueHead = 0; - - if ( queueHead == 0 ) - return data[ allocationSize -1 ]; - - dataSize--; - return data[ queueHead -1 ]; - } - } - - template - _DataType &Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Peek(void) const - { - RakAssert(IsEmpty()==false); - if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK || GetMultilistType()==ML_ORDERED_LIST) - { - return data[dataSize-1]; - } - else - { - RakAssert(GetMultilistType()==ML_QUEUE); - return data[ queueHead ]; - } - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::PushOpposite(const _DataType &d, const char *file, unsigned int line ) - { - PushOpposite(d,d,file,line); - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::PushOpposite(const _DataType &d, const _KeyType &key, const char *file, unsigned int line ) - { - ReallocateIfNeeded(file,line); - - // Unordered list Push at back - if (GetMultilistType()==ML_UNORDERED_LIST) - { - data[dataSize]=d; - dataSize++; - } - else if (GetMultilistType()==ML_STACK) - { - // Stack push at front of the list, instead of back as normal - InsertAtIndex(d,0,file,line); - } - else if (GetMultilistType()==ML_QUEUE) - { - // Queue push at front of the list, instead of back as normal - InsertAtIndex(d,0,file,line); - } - else - { - RakAssert(GetMultilistType()==ML_ORDERED_LIST); - InsertInOrderedList(d,key); - } - - if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK || GetMultilistType()==ML_QUEUE) - { - // Break sort if no longer sorted - if (sortState!=ML_UNSORTED && dataSize>1) - { - if (ascendingSort) - { - if ( MLKeyRef<_KeyType>(key) > operator[](1) ) - sortState=ML_UNSORTED; - } - else - { - if ( MLKeyRef<_KeyType>(key) < operator[](1) ) - sortState=ML_UNSORTED; - } - } - } - } - - template - _DataType &Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::PopOpposite(const char *file, unsigned int line) - { - RakAssert(IsEmpty()==false); - if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK || GetMultilistType()==ML_ORDERED_LIST) - { - // Copy leftmost to end - ReallocateIfNeeded(file,line); - data[dataSize]=data[0]; - DeleteShiftArrayLeft(0); - --dataSize; - // Assuming still leaves at least one element past the end of the list allocated - DeallocateIfNeeded(file,line); - // Return end - return data[dataSize+1]; - } - else - { - RakAssert(GetMultilistType()==ML_QUEUE); - // Deallocate first, since we are returning off the existing list - DeallocateIfNeeded(file,line); - dataSize--; - - if (queueTail==0) - queueTail=allocationSize-1; - else - --queueTail; - - return data[queueTail]; - } - } - - template - _DataType &Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::PeekOpposite(void) const - { - RakAssert(IsEmpty()==false); - if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK || GetMultilistType()==ML_ORDERED_LIST) - { - return data[0]; - } - else - { - RakAssert(GetMultilistType()==ML_QUEUE); - _IndexType priorIndex; - if (queueTail==0) - priorIndex=allocationSize-1; - else - priorIndex=queueTail-1; - - return data[priorIndex]; - } - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::InsertAtIndex(const _DataType &d, _IndexType index, const char *file, unsigned int line) - { - ReallocateIfNeeded(file,line); - - if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK || GetMultilistType()==ML_ORDERED_LIST) - { - if (index>=dataSize) - { - // insert at end - data[dataSize]=d; - - dataSize++; - } - else - { - // insert at index - InsertShiftArrayRight(d,index); - } - } - else - { - data[queueTail++] = d; - - if ( queueTail == allocationSize ) - queueTail = 0; - - ++dataSize; - - if (dataSize==1) - return; - - _IndexType writeIndex, readIndex, trueWriteIndex, trueReadIndex; - writeIndex=dataSize-1; - readIndex=writeIndex-1; - while (readIndex >= index) - { - if ( queueHead + writeIndex >= allocationSize ) - trueWriteIndex = queueHead + writeIndex - allocationSize; - else - trueWriteIndex = queueHead + writeIndex; - - if ( queueHead + readIndex >= allocationSize ) - trueReadIndex = queueHead + readIndex - allocationSize; - else - trueReadIndex = queueHead + readIndex; - - data[trueWriteIndex]=data[trueReadIndex]; - - if (readIndex==0) - break; - writeIndex--; - readIndex--; - } - - if ( queueHead + index >= allocationSize ) - trueWriteIndex = queueHead + index - allocationSize; - else - trueWriteIndex = queueHead + index; - - data[trueWriteIndex]=d; - } - - // #med - use different approach here (template specialization?) -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4127) // conditional expression is constant -#endif - if (_MultilistType != ML_ORDERED_LIST) -#ifdef _MSC_VER -#pragma warning(pop) -#endif - sortState=ML_UNSORTED; - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::RemoveAtIndex(_IndexType position, const char *file, unsigned int line) - { - RakAssert(position < dataSize); - RakAssert(IsEmpty()==false); - - if (GetMultilistType()==ML_UNORDERED_LIST) - { - // Copy tail to current - data[position]=data[dataSize-1]; - } - else if (GetMultilistType()==ML_STACK || GetMultilistType()==ML_ORDERED_LIST) - { - DeleteShiftArrayLeft(position); - } - else - { - RakAssert(GetMultilistType()==ML_QUEUE); - - _IndexType index, next; - - if ( queueHead + position >= allocationSize ) - index = queueHead + position - allocationSize; - else - index = queueHead + position; - - next = index + 1; - - if ( next == allocationSize ) - next = 0; - - while ( next != queueTail ) - { - // Overwrite the previous element - data[ index ] = data[ next ]; - index = next; - //next = (next + 1) % allocationSize; - - if ( ++next == allocationSize ) - next = 0; - } - - // Move the queueTail back - if ( queueTail == 0 ) - queueTail = allocationSize - 1; - else - --queueTail; - } - - - dataSize--; - DeallocateIfNeeded(file,line); - } - - template - bool Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::RemoveAtKey(_KeyType key, bool assertIfDoesNotExist, const char *file, unsigned int line) - { - _IndexType index = GetIndexOf(key); - if (index==(_IndexType)-1) - { - RakAssert(assertIfDoesNotExist==false && "RemoveAtKey element not found"); - return false; - } - RemoveAtIndex(index,file,line); - return true; - } - - template - _IndexType Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::GetIndexOf(_KeyType key) const - { - _IndexType i; - if (IsSorted()) - { - bool objectExists; - i=GetIndexFromKeyInSortedList(key, &objectExists); - if (objectExists) - return i; - return (_IndexType)-1; - } - else if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK) - { - for (i=0; i < dataSize; i++) - { - if (MLKeyRef<_KeyType>(key)==data[i]) - return i; - } - return (_IndexType)-1; - } - else - { - RakAssert( GetMultilistType()==ML_QUEUE ); - - for (i=0; i < dataSize; i++) - { - if (MLKeyRef<_KeyType>(key)==operator[](i)) - return i; - } - return (_IndexType)-1; - } - } - - template - _IndexType Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::GetInsertionIndex(_KeyType key) const - { - _IndexType i; - if (IsSorted()) - { - bool objectExists; - i=GetIndexFromKeyInSortedList(key, &objectExists); - if (objectExists) - return (_IndexType)-1; - return i; - } - else if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK) - { - for (i=0; i < dataSize; i++) - { - if (MLKeyRef<_KeyType>(key)==data[i]) - return (_IndexType)-1; - } - return dataSize; - } - else - { - RakAssert( GetMultilistType()==ML_QUEUE ); - - for (i=0; i < dataSize; i++) - { - if (MLKeyRef<_KeyType>(key)==operator[](i)) - return (_IndexType)-1; - } - return dataSize; - } - } - - template - _DataType Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::GetPtr(_KeyType key) const - { - _IndexType i = GetIndexOf(key); - if (i==(_IndexType)-1) - return 0; - return data[i]; - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ForEach(void (*func)(_DataType &item, const char *file, unsigned int line), const char *file, unsigned int line) - { - _IndexType i; - for (i=0; i < dataSize; i++) - func(operator[](i), file, line); - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ForEach(void (*func)(_DataType &item)) - { - _IndexType i; - for (i=0; i < dataSize; i++) - func(operator[](i)); - } - - template - bool Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::IsEmpty(void) const - { - return dataSize==0; - } - - template - _IndexType Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::GetSize(void) const - { - return dataSize; - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Clear( bool deallocateSmallBlocks, const char *file, unsigned int line ) - { - dataSize=0; - if (GetMultilistType()==ML_ORDERED_LIST) - if (ascendingSort) - sortState=ML_SORTED_ASCENDING; - else - sortState=ML_SORTED_DESCENDING; - else - sortState=ML_UNSORTED; - queueHead=0; - queueTail=0; - - if (deallocateSmallBlocks && allocationSize < 128 && data) - { - MafiaNet::OP_DELETE_ARRAY(data,file,line); - data=0; - allocationSize=0; - } - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ClearPointers( bool deallocateSmallBlocks, const char *file, unsigned int line ) - { - _IndexType i; - for (i=0; i < dataSize; i++) - MafiaNet::OP_DELETE(operator[](i), file, line); - Clear(deallocateSmallBlocks, file, line); - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ClearPointer( _KeyType key, const char *file, unsigned int line ) - { - _IndexType i; - i = GetIndexOf(key); - if (i!=-1) - { - MafiaNet::OP_DELETE(operator[](i), file, line); - RemoveAtIndex(i); - } - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ReverseList(void) - { - if (IsSorted()) - ascendingSort=!ascendingSort; - - ReverseListInternal(); - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Reallocate(_IndexType size, const char *file, unsigned int line) - { - _IndexType newAllocationSize; - if (size < dataSize) - newAllocationSize=dataSize; - else - newAllocationSize=size; - preallocationSize=size; - ReallocToSize(newAllocationSize,file,line); - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Sort(bool force) - { - if (IsSorted() && force==false) - return; - - if (dataSize>1) - { - if (ascendingSort) - QSortAscending(0,dataSize-1); - else - QSortDescending(0,dataSize-1); - } - - TagSorted(); - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::TagSorted(void) - { - if (ascendingSort) - sortState=ML_SORTED_ASCENDING; - else - sortState=ML_SORTED_DESCENDING; - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::QSortAscending(_IndexType leftEdge, _IndexType rightEdge) - { - _DataType temp; - _IndexType left=leftEdge; - _IndexType right=rightEdge; - _IndexType pivotIndex=left++; - - while (left data[pivotIndex]) - { - --left; - - data[pivotIndex]=data[left]; - data[left]=temp; - } - else - { - data[pivotIndex]=data[left]; - data[left]=temp; - - --left; - } - - if (left!=leftEdge) - QSortAscending(leftEdge, left); - - if (right!=rightEdge) - QSortAscending(right, rightEdge); - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::QSortDescending(_IndexType leftEdge, _IndexType rightEdge) - { - _DataType temp; - _IndexType left=leftEdge; - _IndexType right=rightEdge; - _IndexType pivotIndex=left++; - - while (left= data[pivotIndex]) - { - ++left; - } - else - { - temp=data[left]; - data[left]=data[right]; - data[right]=temp; - --right; - } - } - - temp=data[pivotIndex]; - - // Move pivot to center - if (data[left] < data[pivotIndex]) - { - --left; - - data[pivotIndex]=data[left]; - data[left]=temp; - } - else - { - data[pivotIndex]=data[left]; - data[left]=temp; - - --left; - } - - if (left!=leftEdge) - QSortDescending(leftEdge, left); - - if (right!=rightEdge) - QSortDescending(right, rightEdge); - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::SetSortOrder(bool ascending) - { - if (ascendingSort!=ascending && IsSorted()) - { - ascendingSort=ascending; - // List is sorted, and the sort order has changed. So reverse the list - ReverseListInternal(); - } - else - ascendingSort=ascending; - } - - template - bool Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::GetSortOrder(void) const - { - return ascendingSort; - } - - template - bool Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::IsSorted(void) const - { - return GetMultilistType()==ML_ORDERED_LIST || sortState!=ML_UNSORTED; - } - - template - MultilistType Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::GetMultilistType(void) const - { -#pragma warning( push ) -#pragma warning(disable:4127) // conditional expression is constant - if (_MultilistType==ML_VARIABLE_DURING_RUNTIME) -#pragma warning( pop ) - return variableMultilistType; - return _MultilistType; - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::SetMultilistType(MultilistType newType) - { - RakAssert(_MultilistType==ML_VARIABLE_DURING_RUNTIME); - switch (variableMultilistType) - { - case ML_UNORDERED_LIST: - switch (newType) - { - case ML_UNORDERED_LIST: - // No change - break; - case ML_STACK: - // Same data format - break; - case ML_QUEUE: - queueHead=0; - queueTail=dataSize; - break; - case ML_ORDERED_LIST: - Sort(false); - break; - } - break; - case ML_STACK: - switch (newType) - { - case ML_UNORDERED_LIST: - // Same data format - break; - case ML_STACK: - // No change - break; - case ML_QUEUE: - queueHead=0; - queueTail=dataSize; - break; - case ML_ORDERED_LIST: - Sort(false); - break; - } - break; - case ML_QUEUE: - switch (newType) - { - case ML_UNORDERED_LIST: - case ML_STACK: - case ML_ORDERED_LIST: - if (queueTail < queueHead) - { - // Realign data if wrapped - ReallocToSize(dataSize, _FILE_AND_LINE_); - } - else - { - // Else can just copy starting at head - _IndexType i; - for (i=0; i < dataSize; i++) - data[i]=operator[](i); - } - if (newType==ML_ORDERED_LIST) - Sort(false); - break; - case ML_QUEUE: - // No change - break; - } - break; - case ML_ORDERED_LIST: - switch (newType) - { - case ML_UNORDERED_LIST: - case ML_STACK: - case ML_QUEUE: - // Same data format - // Tag as sorted - if (ascendingSort) - sortState=ML_SORTED_ASCENDING; - else - sortState=ML_SORTED_DESCENDING; - if (newType==ML_QUEUE) - { - queueHead=0; - queueTail=dataSize; - } - break; - case ML_ORDERED_LIST: - // No change - break; - } - break; - } - - variableMultilistType=newType; - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::FindIntersection( - Multilist& source1, - Multilist& source2, - Multilist& intersection, - Multilist& uniqueToSource1, - Multilist& uniqueToSource2) - { - _IndexType index1=0, index2=0; - source1.SetSortOrder(true); - source2.SetSortOrder(true); - source1.Sort(false); - source2.Sort(false); - intersection.Clear(true,_FILE_AND_LINE_); - uniqueToSource1.Clear(true,_FILE_AND_LINE_); - uniqueToSource2.Clear(true,_FILE_AND_LINE_); - - while (index1 < source1.GetSize() && index2 < source2.GetSize()) - { - if (source1[index1] - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ReallocateIfNeeded(const char *file, unsigned int line) - { - if (dataSize65536) - newAllocationSize=allocationSize+65536; - else - { - newAllocationSize=allocationSize<<1; // * 2 - // Protect against underflow - if (newAllocationSize < allocationSize) - newAllocationSize=allocationSize+65536; - } - - ReallocToSize(newAllocationSize,file,line); - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::DeallocateIfNeeded(const char *file, unsigned int line) - { - if (allocationSize<512) - return; - if (dataSize >= allocationSize/3 ) - return; - if (dataSize <= preallocationSize ) - return; - - _IndexType newAllocationSize = dataSize<<1; // * 2 - - ReallocToSize(newAllocationSize,file,line); - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ReallocToSize(_IndexType newAllocationSize, const char *file, unsigned int line) - { - _DataType* newData = MafiaNet::OP_NEW_ARRAY<_DataType>(newAllocationSize,file,line); - _IndexType i; - for (i=0; i < dataSize; i++) - newData[i]=operator[](i); - if (dataSize>0) - { - MafiaNet::OP_DELETE_ARRAY(data,file,line); - if (GetMultilistType()==ML_QUEUE) - { - queueHead=0; - queueTail=dataSize; - } - } - data=newData; - allocationSize=newAllocationSize; - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ReverseListInternal(void) - { - _DataType temp; - _IndexType i; - for (i=0; i < dataSize/2; i++) - { - temp=operator[](i); - operator[](i)=operator[](dataSize-1-i); - operator[](dataSize-1-i)=temp; - } - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::InsertInOrderedList(const _DataType &d, const _KeyType &key) - { - RakAssert(GetMultilistType()==ML_ORDERED_LIST); - - bool objectExists; - _IndexType index; - index = GetIndexFromKeyInSortedList(key, &objectExists); - - // if (objectExists) - // { - // Ordered list only allows unique insertions - // RakAssert("Duplicate insertion into ordered list" && false); - // return; - // } - - if (index>=dataSize) - { - // insert at end - data[dataSize]=d; - dataSize++; - } - else - { - // insert at index - InsertShiftArrayRight(d,index); - } - } - - template - _IndexType Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::GetIndexFromKeyInSortedList(const _KeyType &key, bool *objectExists) const - { - RakAssert(IsSorted()); - _IndexType index, upperBound, lowerBound; - - if (dataSize==0) - { - *objectExists=false; - return 0; - } - - upperBound=dataSize-1; - lowerBound=0; - index = dataSize/2; - - for(;;) - { - if (MLKeyRef<_KeyType>(key) > operator[](index) ) - { - if (ascendingSort) - lowerBound=index+1; - else - upperBound=index-1; - } - else if (MLKeyRef<_KeyType>(key) < operator[](index) ) - { - if (ascendingSort) - upperBound=index-1; - else - lowerBound=index+1; - } - else - { - // == - *objectExists=true; - return index; - } - - index=lowerBound+(upperBound-lowerBound)/2; - - if (lowerBound>upperBound || upperBound==(_IndexType)-1) - { - *objectExists=false; - return lowerBound; // No match - } - } - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::InsertShiftArrayRight(const _DataType &d, _IndexType index) - { - RakAssert(_MultilistType!=ML_QUEUE); - - // Move the elements in the list to make room - _IndexType i; - for ( i = dataSize; i != index; i-- ) - data[ i ] = data[ i - 1 ]; - - // Insert the new item at the correct spot - data[ index ] = d; - - ++dataSize; - } - - template - void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::DeleteShiftArrayLeft( _IndexType index ) - { - RakAssert(index < dataSize); - RakAssert(_MultilistType!=ML_QUEUE); - - _IndexType i; - for ( i = index; i < dataSize-1; i++ ) - data[i]=data[i+1]; - } -}; - -/* -struct KeyAndValue -{ - int key; - short value; -}; - -DEFINE_MULTILIST_PTR_TO_MEMBER_COMPARISONS(KeyAndValue,int,key) - -void MultilistUnitTest(void) -{ - DataStructures::DefaultIndexType oldSize; - DataStructures::Multilist ml1; - ml1.Reallocate(64); - RakAssert(ml1.IsEmpty()); - ml1.Push(53); - RakAssert(ml1.Peek()==53); - RakAssert(ml1.IsEmpty()==false); - RakAssert(ml1.Pop()==53); - RakAssert(ml1.IsEmpty()==true); - for (int i=0; i < 512; i++) - ml1.Push(i); - RakAssert(ml1.GetIndexOf(200)==200); - RakAssert(ml1.PeekOpposite()==0); - RakAssert(ml1.PopOpposite()==0); - RakAssert(ml1.PeekOpposite()==1); - RakAssert(ml1.Peek()==511); - ml1.ReverseList(); - for (int i=0; i < 511; i++) - RakAssert(ml1[i]==511-i); - RakAssert(ml1.PeekOpposite()==511); - RakAssert(ml1.Peek()==1); - oldSize = ml1.GetSize(); - ml1.RemoveAtIndex(0); - RakAssert(ml1.GetSize()==oldSize-1); - RakAssert(ml1.PeekOpposite()==1); - ml1.Clear(_FILE_AND_LINE_); - RakAssert(ml1.IsEmpty()==true); - - ml1.Sort(true); - ml1.Clear(_FILE_AND_LINE_); - - ml1.Push(100); - ml1.Sort(true); - ml1.Clear(_FILE_AND_LINE_); - - ml1.Push(50); - ml1.Push(100); - ml1.Sort(true); - ml1.Clear(_FILE_AND_LINE_); - - ml1.Push(100); - ml1.Push(50); - ml1.Sort(true); - ml1.Clear(_FILE_AND_LINE_); - - ml1.Push(100); - ml1.Push(50); - ml1.Push(150); - ml1.Push(25); - ml1.Push(175); - ml1.Sort(true); - RakAssert(ml1[0]==25); - RakAssert(ml1[1]==50); - RakAssert(ml1[2]==100); - RakAssert(ml1[3]==150); - RakAssert(ml1[4]==175); - RakAssert(ml1.GetIndexOf(25)==0); - RakAssert(ml1.GetIndexOf(50)==1); - RakAssert(ml1.GetIndexOf(100)==2); - RakAssert(ml1.GetIndexOf(150)==3); - RakAssert(ml1.GetIndexOf(175)==4); - ml1.Clear(_FILE_AND_LINE_); - - ml1.Push(1); - ml1.Push(2); - ml1.Push(3); - ml1.Push(4); - ml1.Push(5); - ml1.Sort(true); - RakAssert(ml1[0]==1); - RakAssert(ml1[1]==2); - RakAssert(ml1[2]==3); - RakAssert(ml1[3]==4); - RakAssert(ml1[4]==5); - RakAssert(ml1.GetIndexOf(1)==0); - RakAssert(ml1.GetIndexOf(2)==1); - RakAssert(ml1.GetIndexOf(3)==2); - RakAssert(ml1.GetIndexOf(4)==3); - RakAssert(ml1.GetIndexOf(5)==4); - ml1.Clear(_FILE_AND_LINE_); - - ml1.Push(5); - ml1.Push(4); - ml1.Push(3); - ml1.Push(2); - ml1.Push(1); - ml1.Sort(true); - RakAssert(ml1[0]==1); - RakAssert(ml1[1]==2); - RakAssert(ml1[2]==3); - RakAssert(ml1[3]==4); - RakAssert(ml1[4]==5); - RakAssert(ml1.GetIndexOf(1)==0); - RakAssert(ml1.GetIndexOf(2)==1); - RakAssert(ml1.GetIndexOf(3)==2); - RakAssert(ml1.GetIndexOf(4)==3); - RakAssert(ml1.GetIndexOf(5)==4); - ml1.Sort(true); - RakAssert(ml1[0]==1); - RakAssert(ml1[1]==2); - RakAssert(ml1[2]==3); - RakAssert(ml1[3]==4); - RakAssert(ml1[4]==5); - RakAssert(ml1.GetIndexOf(1)==0); - RakAssert(ml1.GetIndexOf(2)==1); - RakAssert(ml1.GetIndexOf(3)==2); - RakAssert(ml1.GetIndexOf(4)==3); - RakAssert(ml1.GetIndexOf(5)==4); - ml1.Clear(_FILE_AND_LINE_); - - DataStructures::Multilist ml2; - ml2.Reallocate(64); - RakAssert(ml2.IsEmpty()); - ml2.Push(53); - RakAssert(ml2.Peek()==53); - RakAssert(ml2.IsEmpty()==false); - RakAssert(ml2.Pop()==53); - RakAssert(ml2.IsEmpty()==true); - for (int i=0; i < 512; i++) - ml2.Push(i); - RakAssert(ml2.GetIndexOf(200)==200); - RakAssert(ml2.PeekOpposite()==0); - RakAssert(ml2.PopOpposite()==0); - RakAssert(ml2.PeekOpposite()==1); - RakAssert(ml2.Peek()==511); - ml2.ReverseList(); - for (int i=0; i < 511; i++) - RakAssert(ml2[i]==511-i); - RakAssert(ml2.PeekOpposite()==511); - RakAssert(ml2.Peek()==1); - oldSize = ml2.GetSize(); - ml2.RemoveAtIndex(0); - RakAssert(ml2.GetSize()==oldSize-1); - RakAssert(ml2.Peek()==1); - RakAssert(ml2.PeekOpposite()==510); - ml2.Clear(_FILE_AND_LINE_); - RakAssert(ml2.IsEmpty()==true); - - DataStructures::Multilist ml3; - RakAssert(ml3.IsEmpty()); - ml3.Push(53); - RakAssert(ml3.Peek()==53); - RakAssert(ml3.IsEmpty()==false); - RakAssert(ml3.Pop()==53); - RakAssert(ml3.IsEmpty()==true); - for (int i=0; i < 512; i++) - ml3.Push(i); - RakAssert(ml3.GetIndexOf(200)==200); - RakAssert(ml3.PeekOpposite()==511); - RakAssert(ml3.PopOpposite()==511); - RakAssert(ml3.PeekOpposite()==510); - RakAssert(ml3.Peek()==0); - ml3.ReverseList(); - for (int i=0; i < 511; i++) - RakAssert(ml3[i]==511-1-i); - RakAssert(ml3.PeekOpposite()==0); - RakAssert(ml3.Peek()==510); - oldSize = ml3.GetSize(); - ml3.RemoveAtIndex(0); - RakAssert(ml3.GetSize()==oldSize-1); - RakAssert(ml3.Peek()==509); - RakAssert(ml3.PeekOpposite()==0); - ml3.Clear(_FILE_AND_LINE_); - RakAssert(ml3.IsEmpty()==true); - - ml3.PushOpposite(100); - ml3.PushOpposite(50); - ml3.PushOpposite(150); - ml3.PushOpposite(25); - ml3.PushOpposite(175); - ml3.Sort(true); - RakAssert(ml3[0]==25); - RakAssert(ml3[1]==50); - RakAssert(ml3[2]==100); - RakAssert(ml3[3]==150); - RakAssert(ml3[4]==175); - RakAssert(ml3.GetIndexOf(25)==0); - RakAssert(ml3.GetIndexOf(50)==1); - RakAssert(ml3.GetIndexOf(100)==2); - RakAssert(ml3.GetIndexOf(150)==3); - RakAssert(ml3.GetIndexOf(175)==4); - ml3.Clear(_FILE_AND_LINE_); - - ml3.PushOpposite(1); - ml3.PushOpposite(2); - ml3.PushOpposite(3); - ml3.PushOpposite(4); - ml3.PushOpposite(5); - ml3.Sort(true); - RakAssert(ml3[0]==1); - RakAssert(ml3[1]==2); - RakAssert(ml3[2]==3); - RakAssert(ml3[3]==4); - RakAssert(ml3[4]==5); - RakAssert(ml3.GetIndexOf(1)==0); - RakAssert(ml3.GetIndexOf(2)==1); - RakAssert(ml3.GetIndexOf(3)==2); - RakAssert(ml3.GetIndexOf(4)==3); - RakAssert(ml3.GetIndexOf(5)==4); - ml3.Clear(_FILE_AND_LINE_); - - ml3.PushOpposite(5); - ml3.PushOpposite(4); - ml3.PushOpposite(3); - ml3.PushOpposite(2); - ml3.PushOpposite(1); - ml3.Sort(true); - RakAssert(ml3[0]==1); - RakAssert(ml3[1]==2); - RakAssert(ml3[2]==3); - RakAssert(ml3[3]==4); - RakAssert(ml3[4]==5); - RakAssert(ml3.GetIndexOf(1)==0); - RakAssert(ml3.GetIndexOf(2)==1); - RakAssert(ml3.GetIndexOf(3)==2); - RakAssert(ml3.GetIndexOf(4)==3); - RakAssert(ml3.GetIndexOf(5)==4); - ml3.Sort(true); - RakAssert(ml3[0]==1); - RakAssert(ml3[1]==2); - RakAssert(ml3[2]==3); - RakAssert(ml3[3]==4); - RakAssert(ml3[4]==5); - RakAssert(ml3.GetIndexOf(1)==0); - RakAssert(ml3.GetIndexOf(2)==1); - RakAssert(ml3.GetIndexOf(3)==2); - RakAssert(ml3.GetIndexOf(4)==3); - RakAssert(ml3.GetIndexOf(5)==4); - - ml3.SetSortOrder(false); - ml3.Sort(false); - RakAssert(ml3[0]==5); - RakAssert(ml3[1]==4); - RakAssert(ml3[2]==3); - RakAssert(ml3[3]==2); - RakAssert(ml3[4]==1); - RakAssert(ml3.GetIndexOf(1)==4); - RakAssert(ml3.GetIndexOf(2)==3); - RakAssert(ml3.GetIndexOf(3)==2); - RakAssert(ml3.GetIndexOf(4)==1); - RakAssert(ml3.GetIndexOf(5)==0); - - ml3.Clear(_FILE_AND_LINE_); - - DataStructures::Multilist ml4; - ml4.Reallocate(64); - RakAssert(ml4.IsEmpty()); - ml4.Push(53); - RakAssert(ml4.Peek()==53); - RakAssert(ml4.IsEmpty()==false); - RakAssert(ml4.Pop()==53); - RakAssert(ml4.IsEmpty()==true); - for (int i=0; i < 512; i++) - ml4.Push(i); - RakAssert(ml4.GetIndexOf(200)==200); - RakAssert(ml4.PeekOpposite()==0); - RakAssert(ml4.PopOpposite()==0); - RakAssert(ml4.PeekOpposite()==1); - RakAssert(ml4.Peek()==511); - ml4.ReverseList(); - for (int i=0; i < 511; i++) - RakAssert(ml4[i]==511-i); - RakAssert(ml4.PeekOpposite()==511); - RakAssert(ml4.Peek()==1); - oldSize = ml4.GetSize(); - ml4.RemoveAtIndex(0); - RakAssert(ml4.GetSize()==oldSize-1); - RakAssert(ml4.Peek()==1); - RakAssert(ml4.PeekOpposite()==510); - ml4.Clear(_FILE_AND_LINE_); - RakAssert(ml4.IsEmpty()==true); - - DataStructures::Multilist ml5; - - for (int i=0; i < 16; i++) - { - KeyAndValue *kav = new KeyAndValue; - kav->key=i; - kav->value=i+100; - ml5.Push(kav,kav->key); - } - - RakAssert(ml5.GetIndexOf(0)==0); - RakAssert(ml5.GetIndexOf(5)==5); - RakAssert(ml5.GetIndexOf(15)==15); - RakAssert(ml5.GetIndexOf(16)==-1); - ml5.RemoveAtKey(0,true); - RakAssert(ml5.GetIndexOf(1)==0); - KeyAndValue *iPtr = ml5.GetPtr(5); - RakAssert(iPtr); - RakAssert(iPtr->value=105); - iPtr = ml5.GetPtr(1234); - RakAssert(iPtr==0); - ml5.ForEach(DataStructures::DeletePtr); - - - DataStructures::Multilist ml6; - ml6.Push(2); - ml6.Push(1); - ml6.Push(6); - ml6.Push(3); - RakAssert(ml6.Peek()==3); - ml6.SetMultilistType(ML_STACK); - RakAssert(ml6.Peek()==3); - ml6.SetMultilistType(ML_QUEUE); - RakAssert(ml6.Peek()==2); - ml6.SetMultilistType(ML_ORDERED_LIST); - RakAssert(ml6.Peek()=6); - ml6.SetMultilistType(ML_STACK); - RakAssert(ml6.Peek()==6); - ml6.SetMultilistType(ML_QUEUE); - RakAssert(ml6.Peek()==1); -} - -*/ - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_OrderedChannelHeap.h b/vendors/mafianet/Source/include/mafianet/DS_OrderedChannelHeap.h deleted file mode 100644 index a967c7050..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_OrderedChannelHeap.h +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_OrderedChannelHeap.h -/// \internal -/// \brief Ordered Channel Heap . This is a heap where you add to it on multiple ordered channels, with each channel having a different weight. -/// - - -#ifndef __RAKNET_ORDERED_CHANNEL_HEAP_H -#define __RAKNET_ORDERED_CHANNEL_HEAP_H - -#include "DS_Heap.h" -#include "DS_Map.h" -#include "DS_Queue.h" -#include "Export.h" -#include "assert.h" -#include "Rand.h" - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - template > - class RAK_DLL_EXPORT OrderedChannelHeap - { - public: - static void IMPLEMENT_DEFAULT_COMPARISON(void) {DataStructures::defaultMapKeyComparison(channel_key_type(),channel_key_type());} - - OrderedChannelHeap(); - ~OrderedChannelHeap(); - void Push(const channel_key_type &channelID, const heap_data_type &data); - void PushAtHead(const unsigned index, const channel_key_type &channelID, const heap_data_type &data); - heap_data_type Pop(const unsigned startingIndex=0); - heap_data_type Peek(const unsigned startingIndex) const; - void AddChannel(const channel_key_type &channelID, const double weight); - void RemoveChannel(channel_key_type channelID); - void Clear(void); - heap_data_type& operator[] ( const unsigned int position ) const; - unsigned ChannelSize(const channel_key_type &channelID); - unsigned Size(void) const; - - struct QueueAndWeight - { - DataStructures::Queue randResultQueue; - double weight; - bool signalDeletion; - }; - - struct HeapChannelAndData - { - HeapChannelAndData() {} - HeapChannelAndData(const channel_key_type &_channel, const heap_data_type &_data) : data(_data), channel(_channel) {} - heap_data_type data; - channel_key_type channel; - }; - - protected: - DataStructures::Map map; - DataStructures::Heap heap; - void GreatestRandResult(void); - }; - - template - OrderedChannelHeap::OrderedChannelHeap() - { - } - - template - OrderedChannelHeap::~OrderedChannelHeap() - { - Clear(); - } - - template - void OrderedChannelHeap::Push(const channel_key_type &channelID, const heap_data_type &data) - { - PushAtHead(MAX_UNSIGNED_LONG, channelID, data); - } - - template - void OrderedChannelHeap::GreatestRandResult(void) - { - double greatest; - unsigned i; - greatest=0.0; - for (i=0; i < map.Size(); i++) - { - if (map[i]->randResultQueue.Size() && map[i]->randResultQueue[0]>greatest) - greatest=map[i]->randResultQueue[0]; - } - return greatest; - } - - template - void OrderedChannelHeap::PushAtHead(const unsigned index, const channel_key_type &channelID, const heap_data_type &data) - { - // If an assert hits here then this is an unknown channel. Call AddChannel first. - QueueAndWeight *queueAndWeight=map.Get(channelID); - double maxRange, minRange, rnd; - if (queueAndWeight->randResultQueue.Size()==0) - { - // Set maxRange to the greatest random number waiting to be returned, rather than 1.0 necessarily - // This is so weights are scaled similarly among channels. For example, if the head weight for a used channel was .25 - // and then we added another channel, the new channel would need to choose between .25 and 0 - // If we chose between 1.0 and 0, it would be 1/.25 (4x) more likely to be at the head of the heap than it should be - maxRange=GreatestRandResult(); - if (maxRange==0.0) - maxRange=1.0; - minRange=0.0; - } - else if (index >= queueAndWeight->randResultQueue.Size()) - { - maxRange=queueAndWeight->randResultQueue[queueAndWeight->randResultQueue.Size()-1]*.99999999; - minRange=0.0; - } - else - { - if (index==0) - { - maxRange=GreatestRandResult(); - if (maxRange==queueAndWeight->randResultQueue[0]) - maxRange=1.0; - } - else if (index >= queueAndWeight->randResultQueue.Size()) - maxRange=queueAndWeight->randResultQueue[queueAndWeight->randResultQueue.Size()-1]*.99999999; - else - maxRange=queueAndWeight->randResultQueue[index-1]*.99999999; - - minRange=maxRange=queueAndWeight->randResultQueue[index]*1.00000001; - } - -#ifdef _DEBUG - RakAssert(maxRange!=0.0); -#endif - rnd=frandomMT() * (maxRange - minRange); - if (rnd==0.0) - rnd=maxRange/2.0; - - if (index >= queueAndWeight->randResultQueue.Size()) - queueAndWeight->randResultQueue.Push(rnd); - else - queueAndWeight->randResultQueue.PushAtHead(rnd, index); - - heap.Push(rnd*queueAndWeight->weight, HeapChannelAndData(channelID, data)); - } - - template - heap_data_type OrderedChannelHeap::Pop(const unsigned startingIndex) - { - RakAssert(startingIndex < heap.Size()); - - QueueAndWeight *queueAndWeight=map.Get(heap[startingIndex].channel); - if (startingIndex!=0) - { - // Ugly - have to count in the heap how many nodes have the same channel, so we know where to delete from in the queue - unsigned indiceCount=0; - unsigned i; - for (i=0; i < startingIndex; i++) - if (channel_key_comparison_func(heap[i].channel,heap[startingIndex].channel)==0) - indiceCount++; - queueAndWeight->randResultQueue.RemoveAtIndex(indiceCount); - } - else - { - // TODO - ordered channel heap uses progressively lower values as items are inserted. But this won't give relative ordering among channels. I have to renormalize after every pop. - queueAndWeight->randResultQueue.Pop(); - } - - // Try to remove the channel after every pop, because doing so is not valid while there are elements in the list. - if (queueAndWeight->signalDeletion) - RemoveChannel(heap[startingIndex].channel); - - return heap.Pop(startingIndex).data; - } - - template - heap_data_type OrderedChannelHeap::Peek(const unsigned startingIndex) const - { - HeapChannelAndData heapChannelAndData = heap.Peek(startingIndex); - return heapChannelAndData.data; - } - - template - void OrderedChannelHeap::AddChannel(const channel_key_type &channelID, const double weight) - { - QueueAndWeight *qaw = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - qaw->weight=weight; - qaw->signalDeletion=false; - map.SetNew(channelID, qaw); - } - - template - void OrderedChannelHeap::RemoveChannel(channel_key_type channelID) - { - if (map.Has(channelID)) - { - unsigned i; - i=map.GetIndexAtKey(channelID); - if (map[i]->randResultQueue.Size()==0) - { - MafiaNet::OP_DELETE(map[i], _FILE_AND_LINE_); - map.RemoveAtIndex(i); - } - else - { - // Signal this channel for deletion later, because the heap has nodes with this channel right now - map[i]->signalDeletion=true; - } - } - } - - template - unsigned OrderedChannelHeap::Size(void) const - { - return heap.Size(); - } - - template - heap_data_type& OrderedChannelHeap::operator[]( const unsigned int position ) const - { - return heap[position].data; - } - - - template - unsigned OrderedChannelHeap::ChannelSize(const channel_key_type &channelID) - { - QueueAndWeight *queueAndWeight=map.Get(channelID); - return queueAndWeight->randResultQueue.Size(); - } - - template - void OrderedChannelHeap::Clear(void) - { - unsigned i; - for (i=0; i < map.Size(); i++) - MafiaNet::OP_DELETE(map[i], _FILE_AND_LINE_); - map.Clear(_FILE_AND_LINE_); - heap.Clear(_FILE_AND_LINE_); - } -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_OrderedList.h b/vendors/mafianet/Source/include/mafianet/DS_OrderedList.h deleted file mode 100644 index 8d5cfe775..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_OrderedList.h +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_OrderedList.h -/// \internal -/// \brief Quicksort ordered list. -/// - -#include "DS_List.h" -#include "memoryoverride.h" -#include "Export.h" - -#ifndef __ORDERED_LIST_H -#define __ORDERED_LIST_H - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - template - int defaultOrderedListComparison(const key_type &a, const data_type &b) - { - if (a > - class RAK_DLL_EXPORT OrderedList - { - public: - static void IMPLEMENT_DEFAULT_COMPARISON(void) {DataStructures::defaultOrderedListComparison(key_type(),data_type());} - - OrderedList(); - ~OrderedList(); - OrderedList( const OrderedList& original_copy ); - OrderedList& operator= ( const OrderedList& original_copy ); - - /// comparisonFunction must take a key_type and a data_type and return <0, ==0, or >0 - /// If the data type has comparison operators already defined then you can just use defaultComparison - bool HasData(const key_type &key, int (*cf)(const key_type&, const data_type&)=default_comparison_function) const; - // GetIndexFromKey returns where the insert should go at the same time checks if it is there - unsigned GetIndexFromKey(const key_type &key, bool *objectExists, int (*cf)(const key_type&, const data_type&)=default_comparison_function) const; - data_type GetElementFromKey(const key_type &key, int (*cf)(const key_type&, const data_type&)=default_comparison_function) const; - bool GetElementFromKey(const key_type &key, data_type &element, int (*cf)(const key_type&, const data_type&)=default_comparison_function) const; - unsigned Insert(const key_type &key, const data_type &data, bool assertOnDuplicate, const char *file, unsigned int line, int (*cf)(const key_type&, const data_type&)=default_comparison_function); - unsigned Remove(const key_type &key, int (*cf)(const key_type&, const data_type&)=default_comparison_function); - unsigned RemoveIfExists(const key_type &key, int (*cf)(const key_type&, const data_type&)=default_comparison_function); - data_type& operator[] ( const unsigned int position ) const; - void RemoveAtIndex(const unsigned index); - void InsertAtIndex(const data_type &data, const unsigned index, const char *file, unsigned int line); - void InsertAtEnd(const data_type &data, const char *file, unsigned int line); - void RemoveFromEnd(const unsigned num=1); - void Clear(bool doNotDeallocate, const char *file, unsigned int line); - unsigned Size(void) const; - - protected: - DataStructures::List orderedList; - }; - - template - OrderedList::OrderedList() - { - } - - template - OrderedList::~OrderedList() - { - Clear(false, _FILE_AND_LINE_); - } - - template - OrderedList::OrderedList( const OrderedList& original_copy ) - { - orderedList=original_copy.orderedList; - } - - template - OrderedList& OrderedList::operator= ( const OrderedList& original_copy ) - { - orderedList=original_copy.orderedList; - return *this; - } - - template - bool OrderedList::HasData(const key_type &key, int (*cf)(const key_type&, const data_type&)) const - { - bool objectExists; - GetIndexFromKey(key, &objectExists, cf); - return objectExists; - } - - template - data_type OrderedList::GetElementFromKey(const key_type &key, int (*cf)(const key_type&, const data_type&)) const - { - bool objectExists; - unsigned index; - index = GetIndexFromKey(key, &objectExists, cf); - RakAssert(objectExists); - return orderedList[index]; - } - template - bool OrderedList::GetElementFromKey(const key_type &key, data_type &element, int (*cf)(const key_type&, const data_type&)) const - { - bool objectExists; - unsigned index; - index = GetIndexFromKey(key, &objectExists, cf); - if (objectExists) - element = orderedList[index]; - return objectExists; - } - template - unsigned OrderedList::GetIndexFromKey(const key_type &key, bool *objectExists, int (*cf)(const key_type&, const data_type&)) const - { - int index, upperBound, lowerBound; - int res; - - if (orderedList.Size()==0) - { - *objectExists=false; - return 0; - } - - upperBound=(int)orderedList.Size()-1; - lowerBound=0; - index = (int)orderedList.Size()/2; - - for(;;) - { - res = cf(key,orderedList[index]); - if (res==0) - { - *objectExists=true; - return (unsigned)index; - } - else if (res<0) - { - upperBound=index-1; - } - else// if (res>0) - { - - lowerBound=index+1; - } - - index=lowerBound+(upperBound-lowerBound)/2; - - if (lowerBound>upperBound) - { - *objectExists=false; - return (unsigned)lowerBound; // No match - } - - if (index < 0 || index >= (int) orderedList.Size()) - { - // This should never hit unless the comparison function was inconsistent - RakAssert(index && 0); - *objectExists=false; - return 0; - } - } - } - - template - unsigned OrderedList::Insert(const key_type &key, const data_type &data, bool assertOnDuplicate, const char *file, unsigned int line, int (*cf)(const key_type&, const data_type&)) - { - (void) assertOnDuplicate; - bool objectExists; - unsigned index; - index = GetIndexFromKey(key, &objectExists, cf); - - // Don't allow duplicate insertion. - if (objectExists) - { - // This is usually a bug! - RakAssert(assertOnDuplicate==false); - return (unsigned)-1; - } - - if (index>=orderedList.Size()) - { - orderedList.Insert(data, file, line); - return orderedList.Size()-1; - } - else - { - orderedList.Insert(data, index, file, line); - return index; - } - } - - template - unsigned OrderedList::Remove(const key_type &key, int (*cf)(const key_type&, const data_type&)) - { - bool objectExists; - unsigned index; - index = GetIndexFromKey(key, &objectExists, cf); - - // Can't find the element to remove if this assert hits - // RakAssert(objectExists==true); - if (objectExists==false) - { - RakAssert(objectExists==true); - return 0; - } - - orderedList.RemoveAtIndex(index); - return index; - } - - template - unsigned OrderedList::RemoveIfExists(const key_type &key, int (*cf)(const key_type&, const data_type&)) - { - bool objectExists; - unsigned index; - index = GetIndexFromKey(key, &objectExists, cf); - - // Can't find the element to remove if this assert hits - if (objectExists==false) - return 0; - - orderedList.RemoveAtIndex(index); - return index; - } - - template - void OrderedList::RemoveAtIndex(const unsigned index) - { - orderedList.RemoveAtIndex(index); - } - - template - void OrderedList::InsertAtIndex(const data_type &data, const unsigned index, const char *file, unsigned int line) - { - orderedList.Insert(data, index, file, line); - } - - template - void OrderedList::InsertAtEnd(const data_type &data, const char *file, unsigned int line) - { - orderedList.Insert(data, file, line); - } - - template - void OrderedList::RemoveFromEnd(const unsigned num) - { - orderedList.RemoveFromEnd(num); - } - - template - void OrderedList::Clear(bool doNotDeallocate, const char *file, unsigned int line) - { - orderedList.Clear(doNotDeallocate, file, line); - } - - template - data_type& OrderedList::operator[]( const unsigned int position ) const - { - return orderedList[position]; - } - - template - unsigned OrderedList::Size(void) const - { - return orderedList.Size(); - } -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_Queue.h b/vendors/mafianet/Source/include/mafianet/DS_Queue.h deleted file mode 100644 index f222177e4..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_Queue.h +++ /dev/null @@ -1,466 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_Queue.h -/// \internal -/// \brief A queue used by RakNet. -/// - - -#ifndef __QUEUE_H -#define __QUEUE_H - -// Template classes have to have all the code in the header file -#include "assert.h" -#include "Export.h" -#include "memoryoverride.h" - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - /// \brief A queue implemented as an array with a read and write index. - template - class RAK_DLL_EXPORT Queue - { - public: - Queue(); - ~Queue(); - Queue( const Queue& original_copy ); - bool operator= ( const Queue& original_copy ); - void Push( const queue_type& input, const char *file, unsigned int line ); - void PushAtHead( const queue_type& input, unsigned index, const char *file, unsigned int line ); - queue_type& operator[] ( unsigned int position ) const; // Not a normal thing you do with a queue but can be used for efficiency - void RemoveAtIndex( unsigned int position ); // Not a normal thing you do with a queue but can be used for efficiency - inline queue_type Peek( void ) const; - inline queue_type PeekTail( void ) const; - inline queue_type Pop( void ); - inline queue_type PopTail( void ); - // Debug: Set pointer to 0, for memory leak detection - inline queue_type PopDeref( void ); - inline unsigned int Size( void ) const; - inline bool IsEmpty(void) const; - inline unsigned int AllocationSize( void ) const; - inline void Clear( const char *file, unsigned int line ); - void Compress( const char *file, unsigned int line ); - bool Find ( const queue_type& q ); - void ClearAndForceAllocation( int size, const char *file, unsigned int line ); // Force a memory allocation to a certain larger size - - private: - queue_type* array; - unsigned int head; // Array index for the head of the queue - unsigned int tail; // Array index for the tail of the queue - unsigned int allocation_size; - }; - - - template - inline unsigned int Queue::Size( void ) const - { - if ( head <= tail ) - return tail -head; - else - return allocation_size -head + tail; - } - - template - inline bool Queue::IsEmpty(void) const - { - return head==tail; - } - - template - inline unsigned int Queue::AllocationSize( void ) const - { - return allocation_size; - } - - template - Queue::Queue() - { - //allocation_size = 16; - //array = MafiaNet::OP_NEW_ARRAY(allocation_size, _FILE_AND_LINE_ ); - allocation_size = 0; - array=0; - head = 0; - tail = 0; - } - - template - Queue::~Queue() - { - if (allocation_size>0) - MafiaNet::OP_DELETE_ARRAY(array, _FILE_AND_LINE_); - } - - template - inline queue_type Queue::Pop( void ) - { -#ifdef _DEBUG - RakAssert( head != tail); -#endif - //head=(head+1) % allocation_size; - - if ( ++head == allocation_size ) - head = 0; - - if ( head == 0 ) - return ( queue_type ) array[ allocation_size -1 ]; - - return ( queue_type ) array[ head -1 ]; - } - - template - inline queue_type Queue::PopTail( void ) - { -#ifdef _DEBUG - RakAssert( head != tail ); -#endif - if (tail!=0) - { - --tail; - return ( queue_type ) array[ tail ]; - } - else - { - tail=allocation_size-1; - return ( queue_type ) array[ tail ]; - } - } - - template - inline queue_type Queue::PopDeref( void ) - { - if ( ++head == allocation_size ) - head = 0; - - queue_type q; - if ( head == 0 ) - { - q=array[ allocation_size -1 ]; - array[ allocation_size -1 ]=0; - return q; - } - - q=array[ head -1 ]; - array[ head -1 ]=0; - return q; - } - - template - void Queue::PushAtHead( const queue_type& input, unsigned index, const char *file, unsigned int line ) - { - RakAssert(index <= Size()); - - // Just force a reallocation, will be overwritten - Push(input, file, line ); - - if (Size()==1) - return; - - unsigned writeIndex, readIndex, trueWriteIndex, trueReadIndex; - writeIndex=Size()-1; - readIndex=writeIndex-1; - while (readIndex >= index) - { - if ( head + writeIndex >= allocation_size ) - trueWriteIndex = head + writeIndex - allocation_size; - else - trueWriteIndex = head + writeIndex; - - if ( head + readIndex >= allocation_size ) - trueReadIndex = head + readIndex - allocation_size; - else - trueReadIndex = head + readIndex; - - array[trueWriteIndex]=array[trueReadIndex]; - - if (readIndex==0) - break; - writeIndex--; - readIndex--; - } - - if ( head + index >= allocation_size ) - trueWriteIndex = head + index - allocation_size; - else - trueWriteIndex = head + index; - - array[trueWriteIndex]=input; - } - - - template - inline queue_type Queue::Peek( void ) const - { -#ifdef _DEBUG - RakAssert( head != tail ); -#endif - - return ( queue_type ) array[ head ]; - } - - template - inline queue_type Queue::PeekTail( void ) const - { -#ifdef _DEBUG - RakAssert( head != tail ); -#endif - if (tail!=0) - return ( queue_type ) array[ tail-1 ]; - else - return ( queue_type ) array[ allocation_size-1 ]; - } - - template - void Queue::Push( const queue_type& input, const char *file, unsigned int line ) - { - if ( allocation_size == 0 ) - { - array = MafiaNet::OP_NEW_ARRAY(16, file, line ); - head = 0; - tail = 1; - array[ 0 ] = input; - allocation_size = 16; - return ; - } - - array[ tail++ ] = input; - - if ( tail == allocation_size ) - tail = 0; - - if ( tail == head ) - { - // unsigned int index=tail; - - // Need to allocate more memory. - queue_type * new_array; - new_array = MafiaNet::OP_NEW_ARRAY((int)allocation_size * 2, file, line ); -#ifdef _DEBUG - RakAssert( new_array ); -#endif - if (new_array==0) - return; - - for ( unsigned int counter = 0; counter < allocation_size; ++counter ) - new_array[ counter ] = array[ ( head + counter ) % ( allocation_size ) ]; - - head = 0; - - tail = allocation_size; - - allocation_size *= 2; - - // Delete the old array and move the pointer to the new array - MafiaNet::OP_DELETE_ARRAY(array, file, line); - - array = new_array; - } - - } - - template - Queue::Queue( const Queue& original_copy ) - { - // Allocate memory for copy - - if ( original_copy.Size() == 0 ) - { - allocation_size = 0; - } - - else - { - array = MafiaNet::OP_NEW_ARRAY( original_copy.Size() + 1 , _FILE_AND_LINE_ ); - - for ( unsigned int counter = 0; counter < original_copy.Size(); ++counter ) - array[ counter ] = original_copy.array[ ( original_copy.head + counter ) % ( original_copy.allocation_size ) ]; - - head = 0; - - tail = original_copy.Size(); - - allocation_size = original_copy.Size() + 1; - } - } - - template - bool Queue::operator= ( const Queue& original_copy ) - { - if ( ( &original_copy ) == this ) - return false; - - Clear(_FILE_AND_LINE_); - - // Allocate memory for copy - if ( original_copy.Size() == 0 ) - { - allocation_size = 0; - } - - else - { - array = MafiaNet::OP_NEW_ARRAY( original_copy.Size() + 1 , _FILE_AND_LINE_ ); - - for ( unsigned int counter = 0; counter < original_copy.Size(); ++counter ) - array[ counter ] = original_copy.array[ ( original_copy.head + counter ) % ( original_copy.allocation_size ) ]; - - head = 0; - - tail = original_copy.Size(); - - allocation_size = original_copy.Size() + 1; - } - - return true; - } - - template - inline void Queue::Clear ( const char *file, unsigned int line ) - { - if ( allocation_size == 0 ) - return ; - - if (allocation_size > 32) - { - MafiaNet::OP_DELETE_ARRAY(array, file, line); - allocation_size = 0; - } - - head = 0; - tail = 0; - } - - template - void Queue::Compress ( const char *file, unsigned int line ) - { - queue_type* new_array; - unsigned int newAllocationSize; - if (allocation_size==0) - return; - - newAllocationSize=1; - while (newAllocationSize <= Size()) - newAllocationSize<<=1; // Must be a better way to do this but I'm too dumb to figure it out quickly :) - - new_array = MafiaNet::OP_NEW_ARRAY(newAllocationSize, file, line ); - - for (unsigned int counter=0; counter < Size(); ++counter) - new_array[counter] = array[(head + counter)%(allocation_size)]; - - tail=Size(); - allocation_size=newAllocationSize; - head=0; - - // Delete the old array and move the pointer to the new array - MafiaNet::OP_DELETE_ARRAY(array, file, line); - array=new_array; - } - - template - bool Queue::Find ( const queue_type &q ) - { - if ( allocation_size == 0 ) - return false; - - unsigned int counter = head; - - while ( counter != tail ) - { - if ( array[ counter ] == q ) - return true; - - counter = ( counter + 1 ) % allocation_size; - } - - return false; - } - - template - void Queue::ClearAndForceAllocation( int size, const char *file, unsigned int line ) - { - MafiaNet::OP_DELETE_ARRAY(array, file, line); - if (size>0) - array = MafiaNet::OP_NEW_ARRAY(size, file, line ); - else - array=0; - allocation_size = size; - head = 0; - tail = 0; - } - - template - inline queue_type& Queue::operator[] ( unsigned int position ) const - { -#ifdef _DEBUG - RakAssert( position < Size() ); -#endif - //return array[(head + position) % allocation_size]; - - if ( head + position >= allocation_size ) - return array[ head + position - allocation_size ]; - else - return array[ head + position ]; - } - - template - void Queue::RemoveAtIndex( unsigned int position ) - { -#ifdef _DEBUG - RakAssert( position < Size() ); - RakAssert( head != tail ); -#endif - - if ( head == tail || position >= Size() ) - return ; - - unsigned int index; - - unsigned int next; - - //index = (head + position) % allocation_size; - if ( head + position >= allocation_size ) - index = head + position - allocation_size; - else - index = head + position; - - //next = (index + 1) % allocation_size; - next = index + 1; - - if ( next == allocation_size ) - next = 0; - - while ( next != tail ) - { - // Overwrite the previous element - array[ index ] = array[ next ]; - index = next; - //next = (next + 1) % allocation_size; - - if ( ++next == allocation_size ) - next = 0; - } - - // Move the tail back - if ( tail == 0 ) - tail = allocation_size - 1; - else - --tail; - } -} // End namespace - -#endif - diff --git a/vendors/mafianet/Source/include/mafianet/DS_QueueLinkedList.h b/vendors/mafianet/Source/include/mafianet/DS_QueueLinkedList.h deleted file mode 100644 index b8f83c21d..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_QueueLinkedList.h +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_QueueLinkedList.h -/// \internal -/// \brief A queue implemented as a linked list. -/// - - -#ifndef __QUEUE_LINKED_LIST_H -#define __QUEUE_LINKED_LIST_H - -#include "DS_LinkedList.h" -#include "Export.h" -#include "memoryoverride.h" - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - /// \brief A queue implemented using a linked list. Rarely used. - template - class RAK_DLL_EXPORT QueueLinkedList - { - - public: - QueueLinkedList(); - QueueLinkedList( const QueueLinkedList& original_copy ); - bool operator= ( const QueueLinkedList& original_copy ); - QueueType Pop( void ); - QueueType& Peek( void ); - QueueType& EndPeek( void ); - void Push( const QueueType& input ); - unsigned int Size( void ); - void Clear( void ); - void Compress( void ); - - private: - LinkedList data; - }; - - template - QueueLinkedList::QueueLinkedList() - { - } - - template - inline unsigned int QueueLinkedList::Size() - { - return data.Size(); - } - - template - inline QueueType QueueLinkedList::Pop( void ) - { - data.Beginning(); - return ( QueueType ) data.Pop(); - } - - template - inline QueueType& QueueLinkedList::Peek( void ) - { - data.Beginning(); - return ( QueueType ) data.Peek(); - } - - template - inline QueueType& QueueLinkedList::EndPeek( void ) - { - data.End(); - return ( QueueType ) data.Peek(); - } - - template - void QueueLinkedList::Push( const QueueType& input ) - { - data.End(); - data.Add( input ); - } - - template - QueueLinkedList::QueueLinkedList( const QueueLinkedList& original_copy ) - { - data = original_copy.data; - } - - template - bool QueueLinkedList::operator= ( const QueueLinkedList& original_copy ) - { - if ( ( &original_copy ) == this ) - return false; - - data = original_copy.data; - } - - template - void QueueLinkedList::Clear ( void ) - { - data.Clear(); - } -} // End namespace - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_RangeList.h b/vendors/mafianet/Source/include/mafianet/DS_RangeList.h deleted file mode 100644 index ca609c4a4..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_RangeList.h +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_RangeList.h -/// \internal -/// \brief A queue implemented as a linked list. -/// - - -#ifndef __RANGE_LIST_H -#define __RANGE_LIST_H - -#include "DS_OrderedList.h" -#include "BitStream.h" -#include "memoryoverride.h" -#include "assert.h" - -namespace DataStructures -{ - template - struct RangeNode - { - RangeNode() {} - ~RangeNode() {} - RangeNode(range_type min, range_type max) {minIndex=min; maxIndex=max;} - range_type minIndex; - range_type maxIndex; - }; - - - template - int RangeNodeComp(const range_type &a, const RangeNode &b) - { - if (a < b.minIndex) { - return -1; - } - if (a > b.maxIndex) { - return 1; - } - return 0; - } - - template - class RAK_DLL_EXPORT RangeList - { - public: - RangeList(); - ~RangeList(); - void Insert(range_type index); - void Clear(void); - bool IsWithinRange(range_type value) const; - unsigned Size(void) const; - unsigned RangeSum(void) const; - MafiaNet::BitSize_t Serialize(MafiaNet::BitStream *in, MafiaNet::BitSize_t maxBits, bool clearSerialized); - bool Deserialize(MafiaNet::BitStream *out); - - DataStructures::OrderedList, RangeNodeComp> ranges; - - // internal helpers - private: - static bool DeserializeSingleRange(MafiaNet::BitStream *out, range_type& min, range_type& max); - }; - - template - MafiaNet::BitSize_t RangeList::Serialize(MafiaNet::BitStream *in, MafiaNet::BitSize_t maxBits, bool clearSerialized) - { - RakAssert(ranges.Size() < (unsigned short)-1); - MafiaNet::BitStream tempBS; - MafiaNet::BitSize_t bitsWritten; - unsigned short countWritten; - unsigned i; - countWritten=0; - bitsWritten=0; - for (i=0; i < ranges.Size(); i++) { - // #med - review this calculation --- shouldn't this be +8 rather than +1 due to minEqualsMax being 1 byte? - if ((int)sizeof(unsigned short)*8+bitsWritten+(int)sizeof(range_type)*8*2+1>maxBits) { - break; - } - unsigned char minEqualsMax; - if (ranges[i].minIndex==ranges[i].maxIndex) { - minEqualsMax=1; - } else { - minEqualsMax=0; - } - tempBS.Write(minEqualsMax); // Use one byte, instead of one bit, for speed, as this is done a lot - tempBS.Write(ranges[i].minIndex); - bitsWritten+=sizeof(range_type)*8+8; - if (ranges[i].minIndex!=ranges[i].maxIndex) { - tempBS.Write(ranges[i].maxIndex); - bitsWritten+=sizeof(range_type)*8; - } - countWritten++; - } - - in->AlignWriteToByteBoundary(); - MafiaNet::BitSize_t before=in->GetWriteOffset(); - in->Write(countWritten); - bitsWritten+=in->GetWriteOffset()-before; - // RAKNET_DEBUG_PRINTF("%i ", in->GetNumberOfBitsUsed()); - in->Write(&tempBS, tempBS.GetNumberOfBitsUsed()); - // RAKNET_DEBUG_PRINTF("%i %i \n", tempBS.GetNumberOfBitsUsed(),in->GetNumberOfBitsUsed()); - - if (clearSerialized && countWritten) { - unsigned rangeSize=ranges.Size(); - for (i=0; i < rangeSize-countWritten; i++) { - ranges[i]=ranges[i+countWritten]; - } - ranges.RemoveFromEnd(countWritten); - } - - return bitsWritten; - } - - template - bool RangeList::Deserialize(MafiaNet::BitStream *out) - { - ranges.Clear(true, _FILE_AND_LINE_); - unsigned short count; - out->AlignReadToByteBoundary(); - if (!out->Read(count)) { - return false; - } - range_type absMin; - range_type min, max; - - if (count == 0) { - return true; - } - - if (!DeserializeSingleRange(out, min, max)) { - return false; - } - ranges.InsertAtEnd(RangeNode(min, max), _FILE_AND_LINE_); - - for (unsigned short i = 1; i < count; i++) { - absMin = max; - - if (!DeserializeSingleRange(out, min, max)) { - return false; - } - if (min <= absMin) { - return false; - } - ranges.InsertAtEnd(RangeNode(min, max), _FILE_AND_LINE_); - } - return true; - } - - template - bool RangeList::DeserializeSingleRange(MafiaNet::BitStream *out, range_type& min, range_type& max) - { - unsigned char maxEqualToMin; - - if (!out->Read(maxEqualToMin)) { - return false; - } - if (!out->Read(min)) { - return false; - } - if (maxEqualToMin == 0) { - if (!out->Read(max)) { - return false; - } - if (max <= min) { - return false; - } - } else { - max = min; - } - - return true; - } - - template - RangeList::RangeList() - { - RangeNodeComp(0, RangeNode()); - } - - template - RangeList::~RangeList() - { - Clear(); - } - - template - void RangeList::Insert(range_type index) - { - if (ranges.Size()==0) { - ranges.Insert(index, RangeNode(index, index), true, _FILE_AND_LINE_); - return; - } - - bool objectExists; - unsigned insertionIndex=ranges.GetIndexFromKey(index, &objectExists); - if (objectExists) { - return; // index already covered by a range entry - do not create a duplicated entry - } - - // index > maxIndex on entire range list - if (insertionIndex==ranges.Size()) { - if (index == ranges[insertionIndex-1].maxIndex+(range_type)1) { - ranges[insertionIndex-1].maxIndex++; - } else if (index > ranges[insertionIndex-1].maxIndex+(range_type)1) { - // Insert at end - ranges.Insert(index, RangeNode(index, index), true, _FILE_AND_LINE_); - } - return; - } - - // verify it's really not within the current range (otherwise objectExists should have been true) - RakAssert(index < ranges[insertionIndex].minIndex || index > ranges[insertionIndex].maxIndex); - - if (index < ranges[insertionIndex].minIndex-(range_type)1) - { - // Insert here - ranges.InsertAtIndex(RangeNode(index, index), insertionIndex, _FILE_AND_LINE_); - return; - } - - if (index == ranges[insertionIndex].minIndex-(range_type)1) - { - // Decrease minIndex and join left - ranges[insertionIndex].minIndex--; - if (insertionIndex>0 && ranges[insertionIndex-1].maxIndex+(range_type)1==ranges[insertionIndex].minIndex) - { - ranges[insertionIndex-1].maxIndex=ranges[insertionIndex].maxIndex; - ranges.RemoveAtIndex(insertionIndex); - } - return; - } - - if (index == ranges[insertionIndex].maxIndex+(range_type)1) - { - // Increase maxIndex and join right - ranges[insertionIndex].maxIndex++; - if (insertionIndex - void RangeList::Clear(void) - { - ranges.Clear(true, _FILE_AND_LINE_); - } - - template - bool RangeList::IsWithinRange(range_type value) const - { - bool objectExists; - // not interested in the return value - (void)ranges.GetIndexFromKey(value, &objectExists); - return objectExists; - } - - template - unsigned RangeList::Size(void) const - { - return ranges.Size(); - } - - template - unsigned RangeList::RangeSum(void) const - { - unsigned sum = 0, i; - for (i = 0; i < ranges.Size(); i++) { - sum += ranges[i].maxIndex-ranges[i].minIndex + 1; - } - return sum; - } - -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_Table.h b/vendors/mafianet/Source/include/mafianet/DS_Table.h deleted file mode 100644 index 0b71890e4..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_Table.h +++ /dev/null @@ -1,350 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_Table.h -/// - - -#ifndef __TABLE_H -#define __TABLE_H - -#include "DS_List.h" -#include "DS_BPlusTree.h" -#include "memoryoverride.h" -#include "Export.h" -#include "string.h" - -#define _TABLE_BPLUS_TREE_ORDER 16 -#define _TABLE_MAX_COLUMN_NAME_LENGTH 64 - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - - /// \brief Holds a set of columns, a set of rows, and rows times columns cells. - /// \details The table data structure is useful if you want to store a set of structures and perform queries on those structures.
- /// This is a relatively simple and fast implementation of the types of tables commonly used in databases.
- /// See TableSerializer to serialize data members of the table.
- /// See LightweightDatabaseClient and LightweightDatabaseServer to transmit the table over the network. - class RAK_DLL_EXPORT Table - { - public: - - enum ColumnType - { - // Cell::i used - NUMERIC, - - // Cell::c used to hold a null terminated string. - STRING, - - // Cell::c holds data. Cell::i holds data length of c in bytes. - BINARY, - - // Cell::c holds data. Not deallocated. Set manually by assigning ptr. - POINTER, - }; - - - /// Holds the actual data in the table - // Note: If this structure is changed the struct in the swig files need to be changed as well - struct RAK_DLL_EXPORT Cell - { - Cell(); - ~Cell(); - Cell(double numericValue, char *charValue, void *ptr, ColumnType type); - void SetByType(double numericValue, char *charValue, void *inPtr, ColumnType type); - void Clear(void); - - /// Numeric - void Set(int input); - void Set(unsigned int input); - void Set(double input); - - /// String - void Set(const char *input); - - /// Binary - void Set(const char *input, int inputLength); - - /// Pointer - void SetPtr(void* p); - - /// Numeric - void Get(int *output); - void Get(double *output); - - /// String - void Get(char *output); - void Get(char *output, size_t outputLength); - - /// Binary - void Get(char *output, int *outputLength); - - MafiaNet::RakString ToString(ColumnType columnType); - - // assignment operator and copy constructor - Cell& operator = ( const Cell& input ); - Cell( const Cell & input); - - ColumnType EstimateColumnType(void) const; - - bool isEmpty; - double i; - char *c; - void *ptr; - }; - - /// Stores the name and type of the column - /// \internal - // Note: If this structure is changed the struct in the swig files need to be changed as well - struct RAK_DLL_EXPORT ColumnDescriptor - { - ColumnDescriptor(); - ~ColumnDescriptor(); - ColumnDescriptor(const char cn[_TABLE_MAX_COLUMN_NAME_LENGTH],ColumnType ct); - - char columnName[_TABLE_MAX_COLUMN_NAME_LENGTH]; - ColumnType columnType; - }; - - /// Stores the list of cells for this row, and a special flag used for internal sorting - // Note: If this structure is changed the struct in the swig files need to be changed as well - struct RAK_DLL_EXPORT Row - { - // list of cells - DataStructures::List cells; - - /// Numeric - void UpdateCell(unsigned columnIndex, double value); - - /// String - void UpdateCell(unsigned columnIndex, const char *str); - - /// Binary - void UpdateCell(unsigned columnIndex, int byteLength, const char *data); - }; - - // Operations to perform for cell comparison - enum FilterQueryType - { - QF_EQUAL, - QF_NOT_EQUAL, - QF_GREATER_THAN, - QF_GREATER_THAN_EQ, - QF_LESS_THAN, - QF_LESS_THAN_EQ, - QF_IS_EMPTY, - QF_NOT_EMPTY, - }; - - // Compare the cell value for a row at columnName to the cellValue using operation. - // Note: If this structure is changed the struct in the swig files need to be changed as well - struct RAK_DLL_EXPORT FilterQuery - { - FilterQuery(); - ~FilterQuery(); - FilterQuery(unsigned column, Cell *cell, FilterQueryType op); - - // If columnName is specified, columnIndex will be looked up using it. - char columnName[_TABLE_MAX_COLUMN_NAME_LENGTH]; - unsigned columnIndex; - Cell *cellValue; - FilterQueryType operation; - }; - - /// Increasing or decreasing sort order - enum SortQueryType - { - QS_INCREASING_ORDER, - QS_DECREASING_ORDER, - }; - - // Sort on increasing or decreasing order for a particular column - // Note: If this structure is changed the struct in the swig files need to be changed as well - struct RAK_DLL_EXPORT SortQuery - { - /// The index of the table column we are sorting on - unsigned columnIndex; - - /// See SortQueryType - SortQueryType operation; - }; - - // Constructor - Table(); - - // Destructor - ~Table(); - - /// \brief Adds a column to the table - /// \param[in] columnName The name of the column - /// \param[in] columnType What type of data this column will hold - /// \return The index of the new column - unsigned AddColumn(const char columnName[_TABLE_MAX_COLUMN_NAME_LENGTH], ColumnType columnType); - - /// \brief Removes a column by index - /// \param[in] columnIndex The index of the column to remove - void RemoveColumn(unsigned columnIndex); - - /// \brief Gets the index of a column by name - /// \details Column indices are stored in the order they are added. - /// \param[in] columnName The name of the column - /// \return The index of the column, or (unsigned)-1 if no such column - unsigned ColumnIndex(char columnName[_TABLE_MAX_COLUMN_NAME_LENGTH]) const; - unsigned ColumnIndex(const char *columnName) const; - - /// \brief Gives the string name of the column at a certain index - /// \param[in] index The index of the column - /// \return The name of the column, or 0 if an invalid index - char* ColumnName(unsigned index) const; - - /// \brief Returns the type of a column, referenced by index - /// \param[in] index The index of the column - /// \return The type of the column - ColumnType GetColumnType(unsigned index) const; - - /// Returns the number of columns - /// \return The number of columns in the table - unsigned GetColumnCount(void) const; - - /// Returns the number of rows - /// \return The number of rows in the table - unsigned GetRowCount(void) const; - - /// \brief Adds a row to the table - /// \details New rows are added with empty values for all cells. However, if you specify initialCelLValues you can specify initial values - /// It's up to you to ensure that the values in the specific cells match the type of data used by that row - /// rowId can be considered the primary key for the row. It is much faster to lookup a row by its rowId than by searching keys. - /// rowId must be unique - /// Rows are stored in sorted order in the table, using rowId as the sort key - /// \param[in] rowId The UNIQUE primary key for the row. This can never be changed. - /// \param[in] initialCellValues Initial values to give the row (optional) - /// \return The newly added row - Table::Row* AddRow(unsigned rowId); - Table::Row* AddRow(unsigned rowId, DataStructures::List &initialCellValues); - Table::Row* AddRow(unsigned rowId, DataStructures::List &initialCellValues, bool copyCells=false); - - /// \brief Removes a row specified by rowId. - /// \param[in] rowId The ID of the row - /// \return true if the row was deleted. False if not. - bool RemoveRow(unsigned rowId); - - /// \brief Removes all the rows with IDs that the specified table also has. - /// \param[in] tableContainingRowIDs The IDs of the rows - void RemoveRows(Table *tableContainingRowIDs); - - /// \brief Updates a particular cell in the table. - /// \note If you are going to update many cells of a particular row, it is more efficient to call GetRow and perform the operations on the row directly. - /// \note Row pointers do not change, so you can also write directly to the rows for more efficiency. - /// \param[in] rowId The ID of the row - /// \param[in] columnIndex The column of the cell - /// \param[in] value The data to set - bool UpdateCell(unsigned rowId, unsigned columnIndex, int value); - bool UpdateCell(unsigned rowId, unsigned columnIndex, char *str); - bool UpdateCell(unsigned rowId, unsigned columnIndex, int byteLength, char *data); - bool UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, int value); - bool UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, char *str); - bool UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, int byteLength, char *data); - - /// \brief Note this is much less efficient to call than GetRow, then working with the cells directly. - /// Numeric, string, binary - void GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, int *output); - void GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, char *output); - void GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, char *output, size_t outputLength); - void GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, char *output, int *outputLength); - - /// \brief Gets a row. More efficient to do this and access Row::cells than to repeatedly call GetCell. - /// You can also update cells in rows from this function. - /// \param[in] rowId The ID of the row - /// \return The desired row, or 0 if no such row. - Row* GetRowByID(unsigned rowId) const; - - /// \brief Gets a row at a specific index. - /// rowIndex should be less than GetRowCount() - /// \param[in] rowIndex The index of the row - /// \param[out] key The ID of the row returned - /// \return The desired row, or 0 if no such row. - Row* GetRowByIndex(unsigned rowIndex, unsigned *key) const; - - /// \brief Queries the table, optionally returning only a subset of columns and rows. - /// \param[in] columnSubset An array of column indices. Only columns in this array are returned. Pass 0 for all columns - /// \param[in] numColumnSubset The number of elements in \a columnSubset - /// \param[in] inclusionFilters An array of FilterQuery. All filters must pass for the row to be returned. - /// \param[in] numInclusionFilters The number of elements in \a inclusionFilters - /// \param[in] rowIds An arrow of row IDs. Only these rows with these IDs are returned. Pass 0 for all rows. - /// \param[in] numRowIDs The number of elements in \a rowIds - /// \param[out] result The result of the query. If no rows are returned, the table will only have columns. - void QueryTable(unsigned *columnIndicesSubset, unsigned numColumnSubset, FilterQuery *inclusionFilters, unsigned numInclusionFilters, unsigned *rowIds, unsigned numRowIDs, Table *result); - - /// \brief Sorts the table by rows - /// \details You can sort the table in ascending or descending order on one or more columns - /// Columns have precedence in the order they appear in the \a sortQueries array - /// If a row cell on column n has the same value as a a different row on column n, then the row will be compared on column n+1 - /// \param[in] sortQueries A list of SortQuery structures, defining the sorts to perform on the table - /// \param[in] numColumnSubset The number of elements in \a numSortQueries - /// \param[out] out The address of an array of Rows, which will receive the sorted output. The array must be long enough to contain all returned rows, up to GetRowCount() - void SortTable(Table::SortQuery *sortQueries, unsigned numSortQueries, Table::Row** out); - - /// \brief Frees all memory in the table. - void Clear(void); - - /// \brief Prints out the names of all the columns. - /// \param[out] out A pointer to an array of bytes which will hold the output. - /// \param[in] outLength The size of the \a out array - /// \param[in] columnDelineator What character to print to delineate columns - void PrintColumnHeaders(char *out, int outLength, char columnDelineator) const; - - /// \brief Writes a text representation of the row to \a out. - /// \param[out] out A pointer to an array of bytes which will hold the output. - /// \param[in] outLength The size of the \a out array - /// \param[in] columnDelineator What character to print to delineate columns - /// \param[in] printDelineatorForBinary Binary output is not printed. True to still print the delineator. - /// \param[in] inputRow The row to print - void PrintRow(char *out, int outLength, char columnDelineator, bool printDelineatorForBinary, Table::Row* inputRow) const; - - /// \brief Direct access to make things easier. - const DataStructures::List& GetColumns(void) const; - - /// \brief Direct access to make things easier. - const DataStructures::BPlusTree& GetRows(void) const; - - /// \brief Get the head of a linked list containing all the row data. - DataStructures::Page * GetListHead(void); - - /// \brief Get the first free row id. - /// This could be made more efficient. - unsigned GetAvailableRowId(void) const; - - Table& operator = ( const Table& input ); - - protected: - Table::Row* AddRowColumns(unsigned rowId, Row *row, DataStructures::List columnIndices); - - void DeleteRow(Row *row); - - void QueryRow(DataStructures::List &inclusionFilterColumnIndices, DataStructures::List &columnIndicesToReturn, unsigned key, Table::Row* row, FilterQuery *inclusionFilters, Table *result); - - // 16 is arbitrary and is the order of the BPlus tree. Higher orders are better for searching while lower orders are better for - // Insertions and deletions. - DataStructures::BPlusTree rows; - - // Columns in the table. - DataStructures::List columns; - }; -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_ThreadsafeAllocatingQueue.h b/vendors/mafianet/Source/include/mafianet/DS_ThreadsafeAllocatingQueue.h deleted file mode 100644 index 7247f43bf..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_ThreadsafeAllocatingQueue.h +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_ThreadsafeAllocatingQueue.h -/// \internal -/// A threadsafe queue, that also uses a memory pool for allocation - -#ifndef __THREADSAFE_ALLOCATING_QUEUE -#define __THREADSAFE_ALLOCATING_QUEUE - -#include "DS_Queue.h" -#include "SimpleMutex.h" -#include "DS_MemoryPool.h" - -// #if defined(new) -// #pragma push_macro("new") -// #undef new -// #define RMO_NEW_UNDEF_ALLOCATING_QUEUE -// #endif - -namespace DataStructures -{ - -template -class RAK_DLL_EXPORT ThreadsafeAllocatingQueue -{ -public: - // Queue operations - void Push(structureType *s); - structureType *PopInaccurate(void); - structureType *Pop(void); - void SetPageSize(int size); - bool IsEmpty(void); - structureType * operator[] ( unsigned int position ); - void RemoveAtIndex( unsigned int position ); - unsigned int Size( void ); - - // Memory pool operations - structureType *Allocate(const char *file, unsigned int line); - void Deallocate(structureType *s, const char *file, unsigned int line); - void Clear(const char *file, unsigned int line); -protected: - - mutable MemoryPool memoryPool; - MafiaNet::SimpleMutex memoryPoolMutex; - Queue queue; - MafiaNet::SimpleMutex queueMutex; -}; - -template -void ThreadsafeAllocatingQueue::Push(structureType *s) -{ - queueMutex.Lock(); - queue.Push(s, _FILE_AND_LINE_ ); - queueMutex.Unlock(); -} - -template -structureType *ThreadsafeAllocatingQueue::PopInaccurate(void) -{ - structureType *s; - if (queue.IsEmpty()) - return 0; - queueMutex.Lock(); - if (queue.IsEmpty()==false) - s=queue.Pop(); - else - s=0; - queueMutex.Unlock(); - return s; -} - -template -structureType *ThreadsafeAllocatingQueue::Pop(void) -{ - structureType *s; - queueMutex.Lock(); - if (queue.IsEmpty()) - { - queueMutex.Unlock(); - return 0; - } - s=queue.Pop(); - queueMutex.Unlock(); - return s; -} - -template -structureType *ThreadsafeAllocatingQueue::Allocate(const char *file, unsigned int line) -{ - structureType *s; - memoryPoolMutex.Lock(); - s=memoryPool.Allocate(file, line); - memoryPoolMutex.Unlock(); - // Call new operator, memoryPool doesn't do this - s = new ((void*)s) structureType; - return s; -} -template -void ThreadsafeAllocatingQueue::Deallocate(structureType *s, const char *file, unsigned int line) -{ - // Call delete operator, memory pool doesn't do this - s->~structureType(); - memoryPoolMutex.Lock(); - memoryPool.Release(s, file, line); - memoryPoolMutex.Unlock(); -} - -template -void ThreadsafeAllocatingQueue::Clear(const char *file, unsigned int line) -{ - memoryPoolMutex.Lock(); - for (unsigned int i=0; i < queue.Size(); i++) - { - queue[i]->~structureType(); - memoryPool.Release(queue[i], file, line); - } - queue.Clear(file, line); - memoryPoolMutex.Unlock(); - memoryPoolMutex.Lock(); - memoryPool.Clear(file, line); - memoryPoolMutex.Unlock(); -} - -template -void ThreadsafeAllocatingQueue::SetPageSize(int size) -{ - memoryPool.SetPageSize(size); -} - -template -bool ThreadsafeAllocatingQueue::IsEmpty(void) -{ - bool isEmpty; - queueMutex.Lock(); - isEmpty=queue.IsEmpty(); - queueMutex.Unlock(); - return isEmpty; -} - -template -structureType * ThreadsafeAllocatingQueue::operator[] ( unsigned int position ) -{ - structureType *s; - queueMutex.Lock(); - s=queue[position]; - queueMutex.Unlock(); - return s; -} - -template -void ThreadsafeAllocatingQueue::RemoveAtIndex( unsigned int position ) -{ - queueMutex.Lock(); - queue.RemoveAtIndex(position); - queueMutex.Unlock(); -} - -template -unsigned int ThreadsafeAllocatingQueue::Size( void ) -{ - unsigned int s; - queueMutex.Lock(); - s=queue.Size(); - queueMutex.Unlock(); - return s; -} - -} - - -// #if defined(RMO_NEW_UNDEF_ALLOCATING_QUEUE) -// #pragma pop_macro("new") -// #undef RMO_NEW_UNDEF_ALLOCATING_QUEUE -// #endif - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_Tree.h b/vendors/mafianet/Source/include/mafianet/DS_Tree.h deleted file mode 100644 index afcb7a7e5..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_Tree.h +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_Tree.h -/// \internal -/// \brief Just a regular tree -/// - - - -#ifndef __DS_TREE_H -#define __DS_TREE_H - -#include "Export.h" -#include "DS_List.h" -#include "DS_Queue.h" -#include "memoryoverride.h" - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - template - class RAK_DLL_EXPORT Tree - { - public: - Tree(); - Tree(TreeType &inputData); - ~Tree(); - void LevelOrderTraversal(DataStructures::List &output); - void AddChild(TreeType &newData); - void DeleteDecendants(void); - - TreeType data; - DataStructures::List children; - }; - - template - Tree::Tree() - { - - } - - template - Tree::Tree(TreeType &inputData) - { - data=inputData; - } - - template - Tree::~Tree() - { - DeleteDecendants(); - } - - template - void Tree::LevelOrderTraversal(DataStructures::List &output) - { - unsigned i; - Tree *node; - DataStructures::Queue*> queue; - - for (i=0; i < children.Size(); i++) - queue.Push(children[i]); - - while (queue.Size()) - { - node=queue.Pop(); - output.Insert(node, _FILE_AND_LINE_); - for (i=0; i < node->children.Size(); i++) - queue.Push(node->children[i]); - } - } - - template - void Tree::AddChild(TreeType &newData) - { - children.Insert(MafiaNet::OP_NEW(newData, _FILE_AND_LINE_)); - } - - template - void Tree::DeleteDecendants(void) - { - /* - DataStructures::List output; - LevelOrderTraversal(output); - unsigned i; - for (i=0; i < output.Size(); i++) - MafiaNet::OP_DELETE(output[i], _FILE_AND_LINE_); -*/ - - // Already recursive to do this - unsigned int i; - for (i=0; i < children.Size(); i++) - MafiaNet::OP_DELETE(children[i], _FILE_AND_LINE_); - } -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DS_WeightedGraph.h b/vendors/mafianet/Source/include/mafianet/DS_WeightedGraph.h deleted file mode 100644 index b77e5fcc4..000000000 --- a/vendors/mafianet/Source/include/mafianet/DS_WeightedGraph.h +++ /dev/null @@ -1,546 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DS_WeightedGraph.h -/// \internal -/// \brief Weighted graph. -/// \details I'm assuming the indices are complex map types, rather than sequential numbers (which could be implemented much more efficiently). -/// - - -#ifndef __WEIGHTED_GRAPH_H -#define __WEIGHTED_GRAPH_H - -#include "DS_OrderedList.h" -#include "DS_Map.h" -#include "DS_Heap.h" -#include "DS_Queue.h" -#include "DS_Tree.h" -#include "assert.h" -#include "memoryoverride.h" -#ifdef _DEBUG -#include -#endif - -#ifdef _MSC_VER -#pragma warning( push ) -#endif - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - template - class RAK_DLL_EXPORT WeightedGraph - { - public: - static void IMPLEMENT_DEFAULT_COMPARISON(void) {DataStructures::defaultMapKeyComparison(node_type(),node_type());} - - WeightedGraph(); - ~WeightedGraph(); - WeightedGraph( const WeightedGraph& original_copy ); - WeightedGraph& operator= ( const WeightedGraph& original_copy ); - void AddNode(const node_type &node); - void RemoveNode(const node_type &node); - void AddConnection(const node_type &node1, const node_type &node2, weight_type weight); - void RemoveConnection(const node_type &node1, const node_type &node2); - bool HasConnection(const node_type &node1, const node_type &node2); - void Print(void); - void Clear(void); - bool GetShortestPath(DataStructures::List &path, node_type startNode, node_type endNode, weight_type INFINITE_WEIGHT); - bool GetSpanningTree(DataStructures::Tree &outTree, DataStructures::List *inputNodes, node_type startNode, weight_type INFINITE_WEIGHT ); - unsigned GetNodeCount(void) const; - unsigned GetConnectionCount(unsigned nodeIndex) const; - void GetConnectionAtIndex(unsigned nodeIndex, unsigned connectionIndex, node_type &outNode, weight_type &outWeight) const; - node_type GetNodeAtIndex(unsigned nodeIndex) const; - - protected: - void ClearDijkstra(void); - void GenerateDisjktraMatrix(node_type startNode, weight_type INFINITE_WEIGHT); - - DataStructures::Map *> adjacencyLists; - - // All these variables are for path finding with Dijkstra - // 08/23/06 Won't compile as a DLL inside this struct - // struct - // { - bool isValidPath; - node_type rootNode; - DataStructures::OrderedList costMatrixIndices; - weight_type *costMatrix; - node_type *leastNodeArray; - // } dijkstra; - - struct NodeAndParent - { - DataStructures::Tree*node; - DataStructures::Tree*parent; - }; - }; - - template - WeightedGraph::WeightedGraph() - { - isValidPath=false; - costMatrix=0; - } - - template - WeightedGraph::~WeightedGraph() - { - Clear(); - } - - template - WeightedGraph::WeightedGraph( const WeightedGraph& original_copy ) - { - adjacencyLists=original_copy.adjacencyLists; - - isValidPath=original_copy.isValidPath; - if (isValidPath) - { - rootNode=original_copy.rootNode; - costMatrixIndices=original_copy.costMatrixIndices; - costMatrix = MafiaNet::OP_NEW_ARRAY(costMatrixIndices.Size() * costMatrixIndices.Size(), _FILE_AND_LINE_ ); - leastNodeArray = MafiaNet::OP_NEW_ARRAY(costMatrixIndices.Size(), _FILE_AND_LINE_ ); - memcpy(costMatrix, original_copy.costMatrix, costMatrixIndices.Size() * costMatrixIndices.Size() * sizeof(weight_type)); - memcpy(leastNodeArray, original_copy.leastNodeArray, costMatrixIndices.Size() * sizeof(weight_type)); - } - } - - template - WeightedGraph& WeightedGraph::operator=( const WeightedGraph& original_copy ) - { - adjacencyLists=original_copy.adjacencyLists; - - isValidPath=original_copy.isValidPath; - if (isValidPath) - { - rootNode=original_copy.rootNode; - costMatrixIndices=original_copy.costMatrixIndices; - costMatrix = MafiaNet::OP_NEW_ARRAY(costMatrixIndices.Size() * costMatrixIndices.Size(), _FILE_AND_LINE_ ); - leastNodeArray = MafiaNet::OP_NEW_ARRAY(costMatrixIndices.Size(), _FILE_AND_LINE_ ); - memcpy(costMatrix, original_copy.costMatrix, costMatrixIndices.Size() * costMatrixIndices.Size() * sizeof(weight_type)); - memcpy(leastNodeArray, original_copy.leastNodeArray, costMatrixIndices.Size() * sizeof(weight_type)); - } - - return *this; - } - - template - void WeightedGraph::AddNode(const node_type &node) - { - adjacencyLists.SetNew(node, MafiaNet::OP_NEW >( _FILE_AND_LINE_) ); - } - - template - void WeightedGraph::RemoveNode(const node_type &node) - { - unsigned i; - DataStructures::Queue removeNodeQueue; - - removeNodeQueue.Push(node, _FILE_AND_LINE_ ); - while (removeNodeQueue.Size()) - { - MafiaNet::OP_DELETE(adjacencyLists.Pop(removeNodeQueue.Pop()), _FILE_AND_LINE_); - - // Remove this node from all of the other lists as well - for (i=0; i < adjacencyLists.Size(); i++) - { - adjacencyLists[i]->Delete(node); - -#ifdef _MSC_VER -#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant -#endif - if (allow_unlinkedNodes==false && adjacencyLists[i]->Size()==0) - removeNodeQueue.Push(adjacencyLists.GetKeyAtIndex(i), _FILE_AND_LINE_ ); - } - } - - ClearDijkstra(); - } - - template - bool WeightedGraph::HasConnection(const node_type &node1, const node_type &node2) - { - if (node1==node2) - return false; - if (adjacencyLists.Has(node1)==false) - return false; - return adjacencyLists.Get(node1)->Has(node2); - } - - template - void WeightedGraph::AddConnection(const node_type &node1, const node_type &node2, weight_type weight) - { - if (node1==node2) - return; - - if (adjacencyLists.Has(node1)==false) - AddNode(node1); - adjacencyLists.Get(node1)->Set(node2, weight); - if (adjacencyLists.Has(node2)==false) - AddNode(node2); - adjacencyLists.Get(node2)->Set(node1, weight); - } - - template - void WeightedGraph::RemoveConnection(const node_type &node1, const node_type &node2) - { - adjacencyLists.Get(node2)->Delete(node1); - adjacencyLists.Get(node1)->Delete(node2); - -#ifdef _MSC_VER -#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant -#endif - if (allow_unlinkedNodes==false) // If we do not allow _unlinked nodes, then if there are no connections, remove the node - { - if (adjacencyLists.Get(node1)->Size()==0) - RemoveNode(node1); // Will also remove node1 from the adjacency list of node2 - if (adjacencyLists.Has(node2) && adjacencyLists.Get(node2)->Size()==0) - RemoveNode(node2); - } - - ClearDijkstra(); - } - - template - void WeightedGraph::Clear(void) - { - unsigned i; - for (i=0; i < adjacencyLists.Size(); i++) - MafiaNet::OP_DELETE(adjacencyLists[i], _FILE_AND_LINE_); - adjacencyLists.Clear(); - - ClearDijkstra(); - } - - template - bool WeightedGraph::GetShortestPath(DataStructures::List &path, node_type startNode, node_type endNode, weight_type INFINITE_WEIGHT) - { - path.Clear(false, _FILE_AND_LINE_); - if (startNode==endNode) - { - path.Insert(startNode, _FILE_AND_LINE_); - path.Insert(endNode, _FILE_AND_LINE_); - return true; - } - - if (isValidPath==false || rootNode!=startNode) - { - ClearDijkstra(); - GenerateDisjktraMatrix(startNode, INFINITE_WEIGHT); - } - - // return the results - bool objectExists; - unsigned col,row; - weight_type currentWeight; - DataStructures::Queue outputQueue; - col=costMatrixIndices.GetIndexFromKey(endNode, &objectExists); - if (costMatrixIndices.Size()<2) - { - return false; - } - if (objectExists==false) - { - return false; - } - node_type vertex; - row=costMatrixIndices.Size()-2; - if (row==0) - { - path.Insert(startNode, _FILE_AND_LINE_); - path.Insert(endNode, _FILE_AND_LINE_); - return true; - } - currentWeight=costMatrix[row*adjacencyLists.Size() + col]; - if (currentWeight==INFINITE_WEIGHT) - { - // No path - return true; - } - vertex=endNode; - outputQueue.PushAtHead(vertex, 0, _FILE_AND_LINE_); - row--; - for(;;) - { - while (costMatrix[row*adjacencyLists.Size() + col] == currentWeight) - { - if (row==0) - { - path.Insert(startNode, _FILE_AND_LINE_); - while(!outputQueue.IsEmpty()) - path.Insert(outputQueue.Pop(), _FILE_AND_LINE_); - return true; - } - --row; - } - - vertex=leastNodeArray[row]; - outputQueue.PushAtHead(vertex, 0, _FILE_AND_LINE_); - if (row==0) - break; - col=costMatrixIndices.GetIndexFromKey(vertex, &objectExists); - currentWeight=costMatrix[row*adjacencyLists.Size() + col]; - } - - path.Insert(startNode, _FILE_AND_LINE_); - while(!outputQueue.IsEmpty()) - path.Insert(outputQueue.Pop(), _FILE_AND_LINE_); - return true; - } - - template - node_type WeightedGraph::GetNodeAtIndex(unsigned nodeIndex) const - { - return adjacencyLists.GetKeyAtIndex(nodeIndex); - } - - template - unsigned WeightedGraph::GetNodeCount(void) const - { - return adjacencyLists.Size(); - } - - template - unsigned WeightedGraph::GetConnectionCount(unsigned nodeIndex) const - { - return adjacencyLists[nodeIndex]->Size(); - } - - template - void WeightedGraph::GetConnectionAtIndex(unsigned nodeIndex, unsigned connectionIndex, node_type &outNode, weight_type &outWeight) const - { - outWeight=adjacencyLists[nodeIndex]->operator[](connectionIndex); - outNode=adjacencyLists[nodeIndex]->GetKeyAtIndex(connectionIndex); - } - - template - bool WeightedGraph::GetSpanningTree(DataStructures::Tree &outTree, DataStructures::List *inputNodes, node_type startNode, weight_type INFINITE_WEIGHT ) - { - // Find the shortest path from the start node to each of the input nodes. Add this path to a new WeightedGraph if the result is reachable - DataStructures::List path; - DataStructures::WeightedGraph outGraph; - bool res; - unsigned i,j; - for (i=0; i < inputNodes->Size(); i++) - { - res=GetShortestPath(path, startNode, (*inputNodes)[i], INFINITE_WEIGHT); - if (res && path.Size()>0) - { - for (j=0; j < path.Size()-1; j++) - { - // Don't bother looking up the weight - outGraph.AddConnection(path[j], path[j+1], INFINITE_WEIGHT); - } - } - } - - // Copy the graph to a tree. - DataStructures::Queue nodesToProcess; - DataStructures::Tree *current; - DataStructures::Map *adjacencyList; - node_type key; - NodeAndParent nap, nap2; - outTree.DeleteDecendants(); - outTree.data=startNode; - current=&outTree; - if (outGraph.adjacencyLists.Has(startNode)==false) - return false; - adjacencyList = outGraph.adjacencyLists.Get(startNode); - - for (i=0; i < adjacencyList->Size(); i++) - { - nap2.node= MafiaNet::OP_NEW >( _FILE_AND_LINE_ ); - nap2.node->data=adjacencyList->GetKeyAtIndex(i); - nap2.parent=current; - nodesToProcess.Push(nap2, _FILE_AND_LINE_ ); - current->children.Insert(nap2.node, _FILE_AND_LINE_); - } - - while (nodesToProcess.Size()) - { - nap=nodesToProcess.Pop(); - current=nap.node; - adjacencyList = outGraph.adjacencyLists.Get(nap.node->data); - - for (i=0; i < adjacencyList->Size(); i++) - { - key=adjacencyList->GetKeyAtIndex(i); - if (key!=nap.parent->data) - { - nap2.node= MafiaNet::OP_NEW >( _FILE_AND_LINE_ ); - nap2.node->data=key; - nap2.parent=current; - nodesToProcess.Push(nap2, _FILE_AND_LINE_ ); - current->children.Insert(nap2.node, _FILE_AND_LINE_); - } - } - } - - return true; - } - - template - void WeightedGraph::GenerateDisjktraMatrix(node_type startNode, weight_type INFINITE_WEIGHT) - { - if (adjacencyLists.Size()==0) - return; - - costMatrix = MafiaNet::OP_NEW_ARRAY(adjacencyLists.Size() * adjacencyLists.Size(), _FILE_AND_LINE_ ); - leastNodeArray = MafiaNet::OP_NEW_ARRAY(adjacencyLists.Size(), _FILE_AND_LINE_ ); - - node_type currentNode; - unsigned col, row, row2, openSetIndex; - node_type adjacentKey; - unsigned adjacentIndex; - weight_type edgeWeight, currentNodeWeight, adjacentNodeWeight; - DataStructures::Map *adjacencyList; - DataStructures::Heap minHeap; - DataStructures::Map openSet; - - for (col=0; col < adjacencyLists.Size(); col++) - { - // This should be already sorted, so it's a bit inefficient to do an insertion sort, but what the heck - costMatrixIndices.Insert(adjacencyLists.GetKeyAtIndex(col),adjacencyLists.GetKeyAtIndex(col), true, _FILE_AND_LINE_); - } - for (col=0; col < adjacencyLists.Size() * adjacencyLists.Size(); col++) - costMatrix[col]=INFINITE_WEIGHT; - currentNode=startNode; - row=0; - currentNodeWeight=0; - rootNode=startNode; - - // Clear the starting node column - if (adjacencyLists.Size()) - { - adjacentIndex=adjacencyLists.GetIndexAtKey(startNode); - for (row2=0; row2 < adjacencyLists.Size(); row2++) - costMatrix[row2*adjacencyLists.Size() + adjacentIndex]=0; - } - - while (row < adjacencyLists.Size()-1) - { - adjacencyList = adjacencyLists.Get(currentNode); - // Go through all connections from the current node. If the new weight is less than the current weight, then update that weight. - for (col=0; col < adjacencyList->Size(); col++) - { - edgeWeight=(*adjacencyList)[col]; - adjacentKey=adjacencyList->GetKeyAtIndex(col); - adjacentIndex=adjacencyLists.GetIndexAtKey(adjacentKey); - adjacentNodeWeight=costMatrix[row*adjacencyLists.Size() + adjacentIndex]; - - if (currentNodeWeight + edgeWeight < adjacentNodeWeight) - { - // Update the weight for the adjacent node - for (row2=row; row2 < adjacencyLists.Size(); row2++) - costMatrix[row2*adjacencyLists.Size() + adjacentIndex]=currentNodeWeight + edgeWeight; - openSet.Set(adjacentKey, currentNodeWeight + edgeWeight); - } - } - - // Find the lowest in the open set - minHeap.Clear(true,_FILE_AND_LINE_); - for (openSetIndex=0; openSetIndex < openSet.Size(); openSetIndex++) - minHeap.Push(openSet[openSetIndex], openSet.GetKeyAtIndex(openSetIndex),_FILE_AND_LINE_); - - /* - unsigned i,j; - for (i=0; i < adjacencyLists.Size()-1; i++) - { - for (j=0; j < adjacencyLists.Size(); j++) - { - RAKNET_DEBUG_PRINTF("%2i ", costMatrix[i*adjacencyLists.Size() + j]); - } - RAKNET_DEBUG_PRINTF("Node=%i", leastNodeArray[i]); - RAKNET_DEBUG_PRINTF("\n"); - } - */ - - if (minHeap.Size()==0) - { - // Unreachable nodes - isValidPath=true; - return; - } - - currentNodeWeight=minHeap.PeekWeight(0); - leastNodeArray[row]=minHeap.Pop(0); - currentNode=leastNodeArray[row]; - openSet.Delete(currentNode); - row++; - } - - /* -#ifdef _DEBUG - unsigned i,j; - for (i=0; i < adjacencyLists.Size()-1; i++) - { - for (j=0; j < adjacencyLists.Size(); j++) - { - RAKNET_DEBUG_PRINTF("%2i ", costMatrix[i*adjacencyLists.Size() + j]); - } - RAKNET_DEBUG_PRINTF("Node=%i", leastNodeArray[i]); - RAKNET_DEBUG_PRINTF("\n"); - } -#endif - */ - - isValidPath=true; - } - - template - void WeightedGraph::ClearDijkstra(void) - { - if (isValidPath) - { - isValidPath=false; - MafiaNet::OP_DELETE_ARRAY(costMatrix, _FILE_AND_LINE_); - MafiaNet::OP_DELETE_ARRAY(leastNodeArray, _FILE_AND_LINE_); - costMatrixIndices.Clear(false, _FILE_AND_LINE_); - } - } - - template - void WeightedGraph::Print(void) - { -#ifdef _DEBUG - unsigned i,j; - for (i=0; i < adjacencyLists.Size(); i++) - { - //RAKNET_DEBUG_PRINTF("%i connected to ", i); - RAKNET_DEBUG_PRINTF("%s connected to ", adjacencyLists.GetKeyAtIndex(i).systemAddress.ToString()); - - if (adjacencyLists[i]->Size()==0) - RAKNET_DEBUG_PRINTF(""); - else - { - for (j=0; j < adjacencyLists[i]->Size(); j++) - // RAKNET_DEBUG_PRINTF("%i (%.2f) ", adjacencyLists.GetIndexAtKey(adjacencyLists[i]->GetKeyAtIndex(j)), (float) adjacencyLists[i]->operator[](j) ); - RAKNET_DEBUG_PRINTF("%s (%.2f) ", adjacencyLists[i]->GetKeyAtIndex(j).systemAddress.ToString(), (float) adjacencyLists[i]->operator[](j) ); - } - - RAKNET_DEBUG_PRINTF("\n"); - } -#endif - } -} - -#ifdef _MSC_VER -#pragma warning( pop ) -#endif - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DataCompressor.h b/vendors/mafianet/Source/include/mafianet/DataCompressor.h deleted file mode 100644 index e81004f82..000000000 --- a/vendors/mafianet/Source/include/mafianet/DataCompressor.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DataCompressor.h -/// \brief DataCompressor does compression on a block of data. -/// \details Not very good compression, but it's small and fast so is something you can use per-message at runtime. -/// - - -#ifndef __DATA_COMPRESSOR_H -#define __DATA_COMPRESSOR_H - -#include "memoryoverride.h" -#include "DS_HuffmanEncodingTree.h" -#include "Export.h" - -namespace MafiaNet -{ - -/// \brief Does compression on a block of data. Not very good compression, but it's small and fast so is something you can compute at runtime. -class RAK_DLL_EXPORT DataCompressor -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(DataCompressor) - - static void Compress( unsigned char *userData, unsigned sizeInBytes, MafiaNet::BitStream * output ); - static unsigned DecompressAndAllocate(MafiaNet::BitStream * input, unsigned char **output ); -}; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/DirectoryDeltaTransfer.h b/vendors/mafianet/Source/include/mafianet/DirectoryDeltaTransfer.h deleted file mode 100644 index ffae76d58..000000000 --- a/vendors/mafianet/Source/include/mafianet/DirectoryDeltaTransfer.h +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DirectoryDeltaTransfer.h -/// \brief Simple class to send changes between directories. -/// \details In essence, a simple autopatcher that can be used for transmitting levels, skins, etc. -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_DirectoryDeltaTransfer==1 && _RAKNET_SUPPORT_FileOperations==1 - -#ifndef __DIRECTORY_DELTA_TRANSFER_H -#define __DIRECTORY_DELTA_TRANSFER_H - -#include "memoryoverride.h" -#include "types.h" -#include "Export.h" -#include "PluginInterface2.h" -#include "DS_Map.h" -#include "PacketPriority.h" - -/// \defgroup DIRECTORY_DELTA_TRANSFER_GROUP DirectoryDeltaTransfer -/// \brief Simple class to send changes between directories -/// \details -/// \ingroup PLUGINS_GROUP - -/// \brief Simple class to send changes between directories. In essence, a simple autopatcher that can be used for transmitting levels, skins, etc. -/// \details -/// \sa AutopatcherClient class for database driven patching, including binary deltas and search by date. -/// -/// To use, first set the path to your application. For example "C:/Games/MyRPG/"
-/// To allow other systems to download files, call AddUploadsFromSubdirectory, where the parameter is a path relative
-/// to the path to your application. This includes subdirectories.
-/// For example:
-/// SetApplicationDirectory("C:/Games/MyRPG/");
-/// AddUploadsFromSubdirectory("Mods/Skins/");
-/// would allow downloads from
-/// "C:/Games/MyRPG/Mods/Skins/*.*" as well as "C:/Games/MyRPG/Mods/Skins/Level1/*.*"
-/// It would NOT allow downloads from C:/Games/MyRPG/Levels, nor would it allow downloads from C:/Windows
-/// While pathToApplication can be anything you want, applicationSubdirectory must match either partially or fully between systems. -/// \ingroup DIRECTORY_DELTA_TRANSFER_GROUP - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; -class FileList; -struct Packet; -struct InternalPacket; -struct DownloadRequest; -class FileListTransfer; -class FileListTransferCBInterface; -class FileListProgress; -class IncrementalReadInterface; - -class RAK_DLL_EXPORT DirectoryDeltaTransfer : public PluginInterface2 -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(DirectoryDeltaTransfer) - - // Constructor - DirectoryDeltaTransfer(); - - // Destructor - virtual ~DirectoryDeltaTransfer(); - - /// \brief This plugin has a dependency on the FileListTransfer plugin, which it uses to actually send the files. - /// \details So you need an instance of that plugin registered with RakPeerInterface, and a pointer to that interface should be passed here. - /// \param[in] flt A pointer to a registered instance of FileListTransfer - void SetFileListTransferPlugin(FileListTransfer *flt); - - /// \brief Set the local root directory to base all file uploads and downloads off of. - /// \param[in] pathToApplication This path will be prepended to \a applicationSubdirectory in AddUploadsFromSubdirectory to find the actual path on disk. - void SetApplicationDirectory(const char *pathToApplication); - - /// \brief What parameters to use for the RakPeerInterface::Send() call when uploading files. - /// \param[in] _priority See RakPeerInterface::Send() - /// \param[in] _orderingChannel See RakPeerInterface::Send() - void SetUploadSendParameters(MafiaNet::Priority _priority, char _orderingChannel); - - /// \brief Add all files in the specified subdirectory recursively. - /// \details \a subdir is appended to \a pathToApplication in SetApplicationDirectory(). - /// All files in the resultant directory and subdirectories are then hashed so that users can download them. - /// \pre You must call SetFileListTransferPlugin with a valid FileListTransfer plugin - /// \param[in] subdir Concatenated with pathToApplication to form the final path from which to allow uploads. - void AddUploadsFromSubdirectory(const char *subdir); - - /// - /// Add a specific file to the file list - /// - /// relative path to the file - /// name of the particular file, without path - void AddFile(const char *filePath, const char *fileName); - - /// \brief Downloads files from the matching parameter \a subdir in AddUploadsFromSubdirectory. - /// \details \a subdir must contain all starting characters in \a subdir in AddUploadsFromSubdirectory - /// Therefore, - /// AddUploadsFromSubdirectory("Levels/Level1/"); would allow you to download using DownloadFromSubdirectory("Levels/Level1/Textures/"... - /// but it would NOT allow you to download from DownloadFromSubdirectory("Levels/"... or DownloadFromSubdirectory("Levels/Level2/"... - /// \pre You must call SetFileListTransferPlugin with a valid FileListTransfer plugin - /// \note Blocking. Will block while hashes of the local files are generated - /// \param[in] subdir A directory passed to AddUploadsFromSubdirectory on the remote system. The passed dir can be more specific than the remote dir. - /// \param[in] outputSubdir The directory to write the output to. Usually this will match \a subdir but it can be different if you want. - /// \param[in] prependAppDirToOutputSubdir True to prepend outputSubdir with pathToApplication when determining the final output path. Usually you want this to be true. - /// \param[in] host The address of the remote system to send the message to. - /// \param[in] onFileCallback Callback to call per-file (optional). When fileIndex+1==setCount in the callback then the download is done - /// \param[in] _priority See RakPeerInterface::Send() - /// \param[in] _orderingChannel See RakPeerInterface::Send() - /// \param[in] cb Callback to get progress updates. Pass 0 to not use. - /// \return A set ID, identifying this download set. Returns 65535 on host unreachable. - unsigned short DownloadFromSubdirectory(const char *subdir, const char *outputSubdir, bool prependAppDirToOutputSubdir, SystemAddress host, FileListTransferCBInterface *onFileCallback, MafiaNet::Priority _priority, char _orderingChannel, FileListProgress *cb); - - /// \brief Downloads files from the matching parameter \a subdir in AddUploadsFromSubdirectory. - /// \details \a subdir must contain all starting characters in \a subdir in AddUploadsFromSubdirectory - /// Therefore, - /// AddUploadsFromSubdirectory("Levels/Level1/"); would allow you to download using DownloadFromSubdirectory("Levels/Level1/Textures/"... - /// but it would NOT allow you to download from DownloadFromSubdirectory("Levels/"... or DownloadFromSubdirectory("Levels/Level2/"... - /// \pre You must call SetFileListTransferPlugin with a valid FileListTransfer plugin - /// \note Nonblocking, but requires call to GenerateHashes() - /// \param[in] localFiles Hashes of local files already on the harddrive. Populate with GenerateHashes(), which you may wish to call from a thread - /// \param[in] subdir A directory passed to AddUploadsFromSubdirectory on the remote system. The passed dir can be more specific than the remote dir. - /// \param[in] outputSubdir The directory to write the output to. Usually this will match \a subdir but it can be different if you want. - /// \param[in] prependAppDirToOutputSubdir True to prepend outputSubdir with pathToApplication when determining the final output path. Usually you want this to be true. - /// \param[in] host The address of the remote system to send the message to. - /// \param[in] onFileCallback Callback to call per-file (optional). When fileIndex+1==setCount in the callback then the download is done - /// \param[in] _priority See RakPeerInterface::Send() - /// \param[in] _orderingChannel See RakPeerInterface::Send() - /// \param[in] cb Callback to get progress updates. Pass 0 to not use. - /// \return A set ID, identifying this download set. Returns 65535 on host unreachable. - unsigned short DownloadFromSubdirectory(FileList &localFiles, const char *subdir, const char *outputSubdir, bool prependAppDirToOutputSubdir, SystemAddress host, FileListTransferCBInterface *onFileCallback, MafiaNet::Priority _priority, char _orderingChannel, FileListProgress *cb); - - /// Hash files already on the harddrive, in preparation for a call to DownloadFromSubdirectory(). Passed to second version of DownloadFromSubdirectory() - /// This is slow, and it is exposed so you can call it from a thread before calling DownloadFromSubdirectory() - /// \param[out] localFiles List of hashed files populated from \a outputSubdir and \a prependAppDirToOutputSubdir - /// \param[in] outputSubdir The directory to write the output to. Usually this will match \a subdir but it can be different if you want. - /// \param[in] prependAppDirToOutputSubdir True to prepend outputSubdir with pathToApplication when determining the final output path. Usually you want this to be true. - void GenerateHashes(FileList &localFiles, const char *outputSubdir, bool prependAppDirToOutputSubdir); - - /// \brief Clear all allowed uploads previously set with AddUploadsFromSubdirectory - void ClearUploads(void); - - /// \brief Returns how many files are available for upload - /// \return How many files are available for upload - unsigned GetNumberOfFilesForUpload(void) const; - - /// \brief Normally, if a remote system requests files, those files are all loaded into memory and sent immediately. - /// \details This function allows the files to be read in incremental chunks, saving memory - /// \param[in] _incrementalReadInterface If a file in \a fileList has no data, filePullInterface will be used to read the file in chunks of size \a chunkSize - /// \param[in] _chunkSize How large of a block of a file to send at once - void SetDownloadRequestIncrementalReadInterface(IncrementalReadInterface *_incrementalReadInterface, unsigned int _chunkSize); - - /// \internal For plugin handling - virtual PluginReceiveResult OnReceive(Packet *packet); -protected: - void OnDownloadRequest(Packet *packet); - - char applicationDirectory[512]; - FileListTransfer *fileListTransfer; - FileList *availableUploads; - MafiaNet::Priority priority; - char orderingChannel; - IncrementalReadInterface *incrementalReadInterface; - unsigned int chunkSize; -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/DynDNS.h b/vendors/mafianet/Source/include/mafianet/DynDNS.h deleted file mode 100644 index 09dce0cd0..000000000 --- a/vendors/mafianet/Source/include/mafianet/DynDNS.h +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file DynDNS.h -/// \brief Helper to class to update DynDNS -/// This can be used to determine what permissions are should be allowed to the other system -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_DynDNS==1 && _RAKNET_SUPPORT_TCPInterface==1 - -#ifndef __DYN_DNS_H -#define __DYN_DNS_H - -#include "string.h" - -namespace MafiaNet -{ - -class TCPInterface; - -enum DynDnsResultCode -{ - // ----- Success ----- - RC_SUCCESS, - RC_DNS_ALREADY_SET, // RakNet detects no action is needed - - // ----- Ignorable failure (treat same as success) ----- - RC_NO_CHANGE, // DynDNS detects no action is needed (treated as abuse though) - - // ----- User error ----- - RC_NOT_DONATOR, // You have to pay to do this - RC_NO_HOST, // This host does not exist at all - RC_BAD_AUTH, // You set the wrong password - RC_NOT_YOURS, // This is not your host - - // ----- Permanent failure ----- - RC_ABUSE, // Your host has been blocked, too many failures disable your account - RC_TCP_FAILED_TO_START, // TCP port already in use - RC_TCP_DID_NOT_CONNECT, // DynDNS down? - RC_UNKNOWN_RESULT, // DynDNS returned a result code that was not documented as of 12/4/2010 on http://www.dyndns.com/developers/specs/flow.pdf - RC_PARSING_FAILURE, // Can't read the result returned, format change? - RC_CONNECTION_LOST_WITHOUT_RESPONSE, // Lost the connection to DynDNS while communicating - RC_BAD_AGENT, // ??? - RC_BAD_SYS, // ??? - RC_DNS_ERROR, // ??? - RC_NOT_FQDN, // ??? - RC_NUM_HOST, // ??? - RC_911, // ??? - RC_DYNDNS_TIMEOUT // DynDNS did not respond -}; - -// Can only process one at a time with the current implementation -class RAK_DLL_EXPORT DynDNS -{ -public: - DynDNS(); - ~DynDNS(); - - // Pass 0 for newIPAddress to autodetect whatever you are uploading from - // usernameAndPassword should be in the format username:password - void UpdateHostIPAsynch(const char *dnsHost, const char *newIPAddress, const char *usernameAndPassword ); - void Update(void); - - // Output - bool IsRunning(void) const {return connectPhase!=CP_IDLE;} - bool IsCompleted(void) const {return connectPhase==CP_IDLE;} - MafiaNet::DynDnsResultCode GetCompletedResultCode(void) {return result;} - const char *GetCompletedDescription(void) const {return resultDescription;} - bool WasResultSuccessful(void) const {return result==RC_SUCCESS || result==RC_DNS_ALREADY_SET || result==RC_NO_CHANGE;} - char *GetMyPublicIP(void) const {return (char*) myIPStr;} // We get our public IP as part of the process. This is valid once completed - -protected: - void Stop(void); - void SetCompleted(MafiaNet::DynDnsResultCode _result, const char *_resultDescription) {Stop(); result=_result; resultDescription=_resultDescription;} - - enum ConnectPhase - { - CP_CONNECTING_TO_CHECKIP, - CP_WAITING_FOR_CHECKIP_RESPONSE, - CP_CONNECTING_TO_DYNDNS, - CP_WAITING_FOR_DYNDNS_RESPONSE, - CP_IDLE - }; - - TCPInterface *tcp; - MafiaNet::RakString getString; - SystemAddress serverAddress; - ConnectPhase connectPhase; - MafiaNet::RakString host; - MafiaNet::Time phaseTimeout; - SystemAddress checkIpAddress; - const char *resultDescription; - MafiaNet::DynDnsResultCode result; - char myIPStr[32]; -}; - -} // namespace MafiaNet - -#endif // __DYN_DNS_H - -#endif // _RAKNET_SUPPORT_DynDNS diff --git a/vendors/mafianet/Source/include/mafianet/EmailSender.h b/vendors/mafianet/Source/include/mafianet/EmailSender.h deleted file mode 100644 index 0501ce7e4..000000000 --- a/vendors/mafianet/Source/include/mafianet/EmailSender.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file EmailSender.h -/// \brief Rudimentary class to send email from code. Don't expect anything fancy. -/// - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_EmailSender==1 && _RAKNET_SUPPORT_TCPInterface==1 && _RAKNET_SUPPORT_FileOperations==1 - -#ifndef __EMAIL_SENDER_H -#define __EMAIL_SENDER_H - -#include "types.h" -#include "memoryoverride.h" -#include "Export.h" -#include "Rand.h" -#include "TCPInterface.h" - -namespace MafiaNet -{ -/// Forward declarations -class FileList; -class TCPInterface; - -/// \brief Rudimentary class to send email from code. -class RAK_DLL_EXPORT EmailSender -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(EmailSender) - - /// \brief Sends an email. - /// \param[in] hostAddress The address of the email server. - /// \param[in] hostPort The port of the email server (usually 25) - /// \param[in] sender The email address you are sending from. - /// \param[in] recipient The email address you are sending to. - /// \param[in] senderName The email address you claim to be sending from - /// \param[in] recipientName The email address you claim to be sending to - /// \param[in] subject Email subject - /// \param[in] body Email body - /// \param[in] attachedFiles List of files to attach to the email. (Can be 0 to send none). - /// \param[in] doPrintf true to output SMTP info to console(for debugging?) - /// \param[in] password Used if the server uses AUTHENTICATE PLAIN over TLS (such as gmail) - /// \return 0 on success, otherwise a string indicating the error message - const char *Send(const char *hostAddress, unsigned short hostPort, const char *sender, const char *recipient, const char *senderName, const char *recipientName, const char *subject, const char *body, FileList *attachedFiles, bool doPrintf, const char *password); - -protected: - const char *GetResponse(TCPInterface *tcpInterface, const SystemAddress &emailServer, bool doPrintf); - RakNetRandom rakNetRandom; -}; - -} // namespace MafiaNet - -#endif - - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/EmptyHeader.h b/vendors/mafianet/Source/include/mafianet/EmptyHeader.h deleted file mode 100644 index 066128368..000000000 --- a/vendors/mafianet/Source/include/mafianet/EmptyHeader.h +++ /dev/null @@ -1,6 +0,0 @@ -/* - * This file was taken from RakNet 4.082 without any modifications. - * Please see licenses/RakNet license.txt for the underlying license and related copyright. - */ - -// This is here to remove Missing #include header? in the Unreal Engine diff --git a/vendors/mafianet/Source/include/mafianet/EpochTimeToString.h b/vendors/mafianet/Source/include/mafianet/EpochTimeToString.h deleted file mode 100644 index 94043f135..000000000 --- a/vendors/mafianet/Source/include/mafianet/EpochTimeToString.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - - -/// \file EpochTimeToString.h -/// - - -#ifndef __EPOCH_TIME_TO_STRING_H -#define __EPOCH_TIME_TO_STRING_H - -#include "Export.h" - -RAK_DLL_EXPORT char * EpochTimeToString(long long time); - -#endif - diff --git a/vendors/mafianet/Source/include/mafianet/Export.h b/vendors/mafianet/Source/include/mafianet/Export.h deleted file mode 100644 index 3ae92b488..000000000 --- a/vendors/mafianet/Source/include/mafianet/Export.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "defines.h" - -#if defined(_WIN32) && !(defined(__GNUC__) || defined(__GCCXML__)) && !defined(_MAFIANET_LIB) && defined(_MAFIANET_DLL) -#define RAK_DLL_EXPORT __declspec(dllexport) -#else -#define RAK_DLL_EXPORT -#endif - -#define STATIC_FACTORY_DECLARATIONS(x) static x* GetInstance(void); \ -static void DestroyInstance( x *i); - -#define STATIC_FACTORY_DEFINITIONS(x,y) x* x::GetInstance(void) {return MafiaNet::OP_NEW( _FILE_AND_LINE_ );} \ -void x::DestroyInstance( x *i) {MafiaNet::OP_DELETE(( y* ) i, _FILE_AND_LINE_);} diff --git a/vendors/mafianet/Source/include/mafianet/FileList.h b/vendors/mafianet/Source/include/mafianet/FileList.h deleted file mode 100644 index 58d342594..000000000 --- a/vendors/mafianet/Source/include/mafianet/FileList.h +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file FileList.h -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_FileOperations==1 - -#ifndef __FILE_LIST -#define __FILE_LIST - -#include "Export.h" -#include "DS_List.h" -#include "memoryoverride.h" -#include "types.h" -#include "FileListNodeContext.h" -#include "string.h" - -namespace MafiaNet -{ - class BitStream; -} - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; -class FileList; - - -/// Represents once instance of a file -struct FileListNode -{ - /// Name of the file - MafiaNet::RakString filename; - - /// Full path to the file, which may be different than filename - MafiaNet::RakString fullPathToFile; - - /// File data (may be null if not ready) - char *data; - - /// Length of \a data. May be greater than fileLength if prepended with a file hash - BitSize_t dataLengthBytes; - - /// Length of the file - unsigned fileLengthBytes; - - /// User specific data for whatever, describing this file. - FileListNodeContext context; - - /// If true, data and dataLengthBytes should be empty. This is just storing the filename - bool isAReference; -}; - -/// Callback interface set with FileList::SetCallback() in case you want progress notifications when FileList::AddFilesFromDirectory() is called -class RAK_DLL_EXPORT FileListProgress -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(FileListProgress) - - FileListProgress() {} - virtual ~FileListProgress() {} - - /// First callback called when FileList::AddFilesFromDirectory() starts - virtual void OnAddFilesFromDirectoryStarted(FileList *fileList, char *dir) { - (void) fileList; - (void) dir; - } - - /// Called for each directory, when that directory begins processing - virtual void OnDirectory(FileList *fileList, char *dir, unsigned int directoriesRemaining) { - (void) fileList; - (void) dir; - (void) directoriesRemaining; - } - - /// Called for each file, when that file begins processing - virtual void OnFile(FileList *fileList, char *dir, char *fileName, unsigned int fileSize) { - (void) fileList; - (void) dir; - (void) fileName; - (void) fileSize; - } - - /// \brief This function is called when we are sending a file to a remote system. - /// \param[in] fileName The name of the file being sent - /// \param[in] fileLengthBytes How long the file is - /// \param[in] offset The offset in bytes into the file that we are sending - /// \param[in] bytesBeingSent How many bytes we are sending this push - /// \param[in] done If this file is now done with this push - /// \param[in] targetSystem Who we are sending to - virtual void OnFilePush(const char *fileName, unsigned int fileLengthBytes, unsigned int offset, unsigned int bytesBeingSent, bool done, SystemAddress targetSystem, unsigned short setId) - { - (void) fileName; - (void) fileLengthBytes; - (void) offset; - (void) bytesBeingSent; - (void) done; - (void) targetSystem; - (void) setId; - } - - /// \brief This function is called when all files have been read and are being transferred to a remote system - virtual void OnFilePushesComplete( SystemAddress systemAddress, unsigned short setId ) - { - (void) systemAddress; - (void) setId; - } - - /// \brief This function is called when a send to a system was aborted (probably due to disconnection) - virtual void OnSendAborted( SystemAddress systemAddress ) - { - (void) systemAddress; - } -}; - -/// Implementation of FileListProgress to use RAKNET_DEBUG_PRINTF -class RAK_DLL_EXPORT FLP_Printf : public FileListProgress -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(FLP_Printf) - - FLP_Printf() {} - virtual ~FLP_Printf() {} - - /// First callback called when FileList::AddFilesFromDirectory() starts - virtual void OnAddFilesFromDirectoryStarted(FileList *fileList, char *dir); - - /// Called for each directory, when that directory begins processing - virtual void OnDirectory(FileList *fileList, char *dir, unsigned int directoriesRemaining); - - /// \brief This function is called when all files have been transferred to a particular remote system - virtual void OnFilePushesComplete( SystemAddress systemAddress, unsigned short setID ); - - /// \brief This function is called when a send to a system was aborted (probably due to disconnection) - virtual void OnSendAborted( SystemAddress systemAddress ); -}; - -class RAK_DLL_EXPORT FileList -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(FileList) - - FileList(); - ~FileList(); - /// \brief Add all the files at a given directory. - /// \param[in] applicationDirectory The first part of the path. This is not stored as part of the filename. Use \ as the path delineator. - /// \param[in] subDirectory The rest of the path to the file. This is stored as a prefix to the filename - /// \param[in] writeHash The first 4 bytes is a hash of the file, with the remainder the actual file data (should \a writeData be true) - /// \param[in] writeData Write the contents of each file - /// \param[in] recursive Whether or not to visit subdirectories - /// \param[in] context User defined byte to store with each file. Use for whatever you want. - void AddFilesFromDirectory(const char *applicationDirectory, const char *subDirectory, bool writeHash, bool writeData, bool recursive, FileListNodeContext context); - - /// Deallocate all memory - void Clear(void); - - /// Write all encoded data into a bitstream - void Serialize(MafiaNet::BitStream *outBitStream); - - /// Read all encoded data from a bitstream. Clear() is called before deserializing. - bool Deserialize(MafiaNet::BitStream *inBitStream); - - /// \brief Given the existing set of files, search applicationDirectory for the same files. - /// \details For each file that is missing or different, add that file to \a missingOrChangedFiles. Note: the file contents are not written, and only the hash if written if \a alwaysWriteHash is true - /// alwaysWriteHash and neverWriteHash are optimizations to avoid reading the file contents to generate the hash if not necessary because the file is missing or has different lengths anyway. - /// \param[in] applicationDirectory The first part of the path. This is not stored as part of the filename. Use \ as the path delineator. - /// \param[out] missingOrChangedFiles Output list written to - /// \param[in] alwaysWriteHash If true, and neverWriteHash is false, will hash the file content of the file on disk, and write that as the file data with a length of SHA1_LENGTH bytes. If false, if the file length is different, will only write the filename. - /// \param[in] neverWriteHash If true, will never write the hash, even if available. If false, will write the hash if the file lengths are the same and it was forced to do a comparison. - void ListMissingOrChangedFiles(const char *applicationDirectory, FileList *missingOrChangedFiles, bool alwaysWriteHash, bool neverWriteHash); - - /// \brief Return the files that need to be written to make \a input match this current FileList. - /// \details Specify dirSubset to only consider files that start with this path - /// specify remoteSubdir to assume that all filenames in input start with this path, so strip it off when comparing filenames. - /// \param[in] input Full list of files - /// \param[out] output Files that we need to match input - /// \param[in] dirSubset If the filename does not start with this path, just skip this file. - /// \param[in] remoteSubdir Remove this from the filenames of \a input when comparing to existing filenames. - void GetDeltaToCurrent(FileList *input, FileList *output, const char *dirSubset, const char *remoteSubdir); - - /// \brief Assuming FileList contains a list of filenames presumably without data, read the data for these filenames - /// \param[in] applicationDirectory Prepend this path to each filename. Trailing slash will be added if necessary. Use \ as the path delineator. - /// \param[in] writeFileData True to read and store the file data. The first SHA1_LENGTH bytes will contain the hash if \a writeFileHash is true - /// \param[in] writeFileHash True to read and store the hash of the file data. The first SHA1_LENGTH bytes will contain the hash if \a writeFileHash is true - /// \param[in] removeUnknownFiles If a file does not exist on disk but is in the file list, remove it from the file list? - void PopulateDataFromDisk(const char *applicationDirectory, bool writeFileData, bool writeFileHash, bool removeUnknownFiles); - - /// By default, GetDeltaToCurrent tags files as non-references, meaning they are assumed to be populated later - /// This tags all files as references, required for IncrementalReadInterface to process them incrementally - void FlagFilesAsReferences(void); - - /// \brief Write all files to disk, prefixing the paths with applicationDirectory - /// \param[in] applicationDirectory path prefix - void WriteDataToDisk(const char *applicationDirectory); - - /// \brief Add a file, given data already in memory. - /// \param[in] filename Name of a file, optionally prefixed with a partial or complete path. Use \ as the path delineator. - /// \param[in] fullPathToFile Full path to the file on disk - /// \param[in] data Contents to write - /// \param[in] dataLength length of the data, which may be greater than fileLength should you prefix extra data, such as the hash - /// \param[in] fileLength Length of the file - /// \param[in] context User defined byte to store with each file. Use for whatever you want. - /// \param[in] isAReference Means that this is just a reference to a file elsewhere - does not actually have any data - /// \param[in] takeDataPointer If true, do not allocate dataLength. Just take the pointer passed to the \a data parameter - void AddFile(const char *filename, const char *fullPathToFile, const char *data, const unsigned dataLength, const unsigned fileLength, FileListNodeContext context, bool isAReference=false, bool takeDataPointer=false); - - /// \brief Add a file, reading it from disk. - /// \param[in] filepath Complete path to the file, including the filename itself - /// \param[in] filename filename to store internally, anything you want, but usually either the complete path or a subset of the complete path. - /// \param[in] context User defined byte to store with each file. Use for whatever you want. - void AddFile(const char *filepath, const char *filename, FileListNodeContext context); - - /// \brief Delete all files stored in the file list. - /// \param[in] applicationDirectory Prefixed to the path to each filename. Use \ as the path delineator. - void DeleteFiles(const char *applicationDirectory); - - /// \brief Adds a callback to get progress reports about what the file list instances do. - /// \param[in] cb A pointer to an externally defined instance of FileListProgress. This pointer is held internally, so should remain valid as long as this class is valid. - void AddCallback(FileListProgress *cb); - - /// \brief Removes a callback - /// \param[in] cb A pointer to an externally defined instance of FileListProgress that was previously added with AddCallback() - void RemoveCallback(FileListProgress *cb); - - /// \brief Removes all callbacks - void ClearCallbacks(void); - - /// Returns all callbacks added with AddCallback() - /// \param[out] callbacks The list is set to the list of callbacks - void GetCallbacks(DataStructures::List &callbacks); - - // Here so you can read it, but don't modify it - DataStructures::List fileList; - - static bool FixEndingSlash(char *str); - static bool FixEndingSlash(char *str, size_t strLength); -protected: - DataStructures::List fileListProgressCallbacks; -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_FileOperations diff --git a/vendors/mafianet/Source/include/mafianet/FileListNodeContext.h b/vendors/mafianet/Source/include/mafianet/FileListNodeContext.h deleted file mode 100644 index 9061ae0aa..000000000 --- a/vendors/mafianet/Source/include/mafianet/FileListNodeContext.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file FileListNodeContext.h -/// - - -#ifndef __FILE_LIST_NODE_CONTEXT_H -#define __FILE_LIST_NODE_CONTEXT_H - -#include "BitStream.h" - -struct FileListNodeContext -{ - FileListNodeContext() {dataPtr=0; dataLength=0;} - FileListNodeContext(unsigned char o, uint32_t f1, uint32_t f2, uint32_t f3) : op(o), flnc_extraData1(f1), flnc_extraData2(f2), flnc_extraData3(f3) {dataPtr=0; dataLength=0;} - ~FileListNodeContext() {} - - unsigned char op; - uint32_t flnc_extraData1; - uint32_t flnc_extraData2; - uint32_t flnc_extraData3; - void *dataPtr; - unsigned int dataLength; -}; - -inline MafiaNet::BitStream& operator<<(MafiaNet::BitStream& out, FileListNodeContext& in) -{ - out.Write(in.op); - out.Write(in.flnc_extraData1); - out.Write(in.flnc_extraData2); - out.Write(in.flnc_extraData3); - return out; -} -inline MafiaNet::BitStream& operator>>(MafiaNet::BitStream& in, FileListNodeContext& out) -{ - in.Read(out.op); - bool success = in.Read(out.flnc_extraData1); - (void) success; - assert(success); - success = in.Read(out.flnc_extraData2); - (void) success; - assert(success); - success = in.Read(out.flnc_extraData3); - (void) success; - assert(success); - return in; -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/FileListTransfer.h b/vendors/mafianet/Source/include/mafianet/FileListTransfer.h deleted file mode 100644 index 369361213..000000000 --- a/vendors/mafianet/Source/include/mafianet/FileListTransfer.h +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file FileListTransfer.h -/// \brief A plugin to provide a simple way to compress and incrementally send the files in the FileList structure. -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_FileListTransfer==1 && _RAKNET_SUPPORT_FileOperations==1 - -#ifndef __FILE_LIST_TRANFER_H -#define __FILE_LIST_TRANFER_H - -#include "types.h" -#include "Export.h" -#include "PluginInterface2.h" -#include "DS_Map.h" -#include "types.h" -#include "PacketPriority.h" -#include "memoryoverride.h" -#include "FileList.h" -#include "DS_Queue.h" -#include "SimpleMutex.h" -#include "ThreadPool.h" - -namespace MafiaNet -{ -/// Forward declarations -class IncrementalReadInterface; -class FileListTransferCBInterface; -class FileListProgress; -struct FileListReceiver; - -/// \defgroup FILE_LIST_TRANSFER_GROUP FileListTransfer -/// \brief A plugin to provide a simple way to compress and incrementally send the files in the FileList structure. -/// \details -/// \ingroup PLUGINS_GROUP - -/// \brief A plugin to provide a simple way to compress and incrementally send the files in the FileList structure. -/// \details Similar to the DirectoryDeltaTransfer plugin, except that it doesn't send deltas based on pre-existing files or actually write the files to disk. -/// -/// Usage: -/// Call SetupReceive to allow one file set to arrive. The value returned by FileListTransfer::SetupReceive()
-/// is the setID that is allowed.
-/// It's up to you to transmit this value to the other system, along with information indicating what kind of files you want to get.
-/// The other system should then prepare a FileList and call FileListTransfer::Send(), passing the return value of FileListTransfer::SetupReceive()
-/// as the \a setID parameter to FileListTransfer::Send() -/// \ingroup FILE_LIST_TRANSFER_GROUP -class RAK_DLL_EXPORT FileListTransfer : public PluginInterface2 -{ -public: - - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(FileListTransfer) - - FileListTransfer(); - virtual ~FileListTransfer(); - - /// \brief Optionally start worker threads when using _incrementalReadInterface for the Send() operation - /// \param[in] numThreads how many worker threads to start - /// \param[in] threadPriority Passed to the thread creation routine. Use THREAD_PRIORITY_NORMAL for Windows. For Linux based systems, you MUST pass something reasonable based on the thread priorities for your application. - void StartIncrementalReadThreads(int numThreads, int threadPriority=-99999); - - /// \brief Allows one corresponding Send() call from another system to arrive. - /// \param[in] handler The class to call on each file - /// \param[in] deleteHandler True to delete the handler when it is no longer needed. False to not do so. - /// \param[in] allowedSender Which system to allow files from. - /// \return A set ID value, which should be passed as the \a setID value to the Send() call on the other system. This value will be returned in the callback and is unique per file set. Returns 65535 on failure (not connected to sender) - unsigned short SetupReceive(FileListTransferCBInterface *handler, bool deleteHandler, SystemAddress allowedSender); - - /// \brief Send the FileList structure to another system, which must have previously called SetupReceive(). - /// \param[in] fileList A list of files. The data contained in FileList::data will be sent incrementally and compressed among all files in the set - /// \param[in] rakPeer The instance of RakNet to use to send the message. Pass 0 to use the instance the plugin is attached to - /// \param[in] recipient The address of the system to send to - /// \param[in] setID The return value of SetupReceive() which was previously called on \a recipient - /// \param[in] priority Passed to RakPeerInterface::Send() - /// \param[in] orderingChannel Passed to RakPeerInterface::Send() - /// \param[in] _incrementalReadInterface If a file in \a fileList has no data, _incrementalReadInterface will be used to read the file in chunks of size \a chunkSize - /// \param[in] _chunkSize How large of a block of a file to read/send at once. Large values use more memory but transfer slightly faster. - void Send(FileList *fileList, MafiaNet::RakPeerInterface *rakPeer, SystemAddress recipient, unsigned short setID, MafiaNet::Priority priority, char orderingChannel, IncrementalReadInterface *_incrementalReadInterface=0, unsigned int _chunkSize=262144*4*16); - - /// Return number of files waiting to go out to a particular address - unsigned int GetPendingFilesToAddress(SystemAddress recipient); - - /// \brief Stop a download. - void CancelReceive(unsigned short inSetId); - - /// \brief Remove all handlers associated with a particular system address. - void RemoveReceiver(SystemAddress systemAddress); - - /// \brief Is a handler passed to SetupReceive still running? - bool IsHandlerActive(unsigned short inSetId); - - /// \brief Adds a callback to get progress reports about what the file list instances do. - /// \param[in] cb A pointer to an externally defined instance of FileListProgress. This pointer is held internally, so should remain valid as long as this class is valid. - void AddCallback(FileListProgress *cb); - - /// \brief Removes a callback - /// \param[in] cb A pointer to an externally defined instance of FileListProgress that was previously added with AddCallback() - void RemoveCallback(FileListProgress *cb); - - /// \brief Removes all callbacks - void ClearCallbacks(void); - - /// Returns all callbacks added with AddCallback() - /// \param[out] callbacks The list is set to the list of callbacks - void GetCallbacks(DataStructures::List &callbacks); - - /// \internal For plugin handling - virtual PluginReceiveResult OnReceive(Packet *packet); - /// \internal For plugin handling - virtual void OnRakPeerShutdown(void); - /// \internal For plugin handling - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - /// \internal For plugin handling - virtual void Update(void); - -protected: - bool DecodeSetHeader(Packet *packet); - bool DecodeFile(Packet *packet, bool fullFile); - - void Clear(void); - - void OnReferencePush(Packet *packet, bool fullFile); - void OnReferencePushAck(Packet *packet); - void SendIRIToAddress(SystemAddress systemAddress, unsigned short inSetId); - - DataStructures::Map fileListReceivers; - unsigned short setId; - DataStructures::List fileListProgressCallbacks; - - struct FileToPush - { - FileListNode fileListNode; - MafiaNet::Priority packetPriority; - char orderingChannel; - unsigned int currentOffset; - ////unsigned short setID; - unsigned int setIndex; - IncrementalReadInterface *incrementalReadInterface; - unsigned int chunkSize; - }; - struct FileToPushRecipient - { - unsigned int refCount; - SimpleMutex refCountMutex; - void DeleteThis(void); - void AddRef(void); - void Deref(void); - - SystemAddress systemAddress; - unsigned short setId; - - //// SimpleMutex filesToPushMutex; - DataStructures::Queue filesToPush; - }; - DataStructures::List< FileToPushRecipient* > fileToPushRecipientList; - SimpleMutex fileToPushRecipientListMutex; - void RemoveFromList(FileToPushRecipient *ftpr); - - struct ThreadData - { - FileListTransfer *fileListTransfer; - SystemAddress systemAddress; - unsigned short setId; - }; - - ThreadPool threadPool; - - friend int SendIRIToAddressCB(FileListTransfer::ThreadData threadData, bool *returnOutput, void* perThreadData); -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/FileListTransferCBInterface.h b/vendors/mafianet/Source/include/mafianet/FileListTransferCBInterface.h deleted file mode 100644 index ade0309ac..000000000 --- a/vendors/mafianet/Source/include/mafianet/FileListTransferCBInterface.h +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file FileListTransferCBInterface.h -/// - - -#ifndef __FILE_LIST_TRANSFER_CALLBACK_INTERFACE_H -#define __FILE_LIST_TRANSFER_CALLBACK_INTERFACE_H - -#include "memoryoverride.h" -#include "FileListNodeContext.h" - -namespace MafiaNet -{ - -/// \brief Used by FileListTransfer plugin as a callback for when we get a file. -/// \details You get the last file when fileIndex==numberOfFilesInThisSet -/// \sa FileListTransfer -class FileListTransferCBInterface -{ -public: - // Note: If this structure is changed the struct in the swig files need to be changed as well - struct OnFileStruct - { - /// \brief The index into the set of files, from 0 to numberOfFilesInThisSet - unsigned fileIndex; - - /// \brief The name of the file - char fileName[512]; - - /// \brief The data pointed to by the file - char *fileData; - - /// \brief The amount of data to be downloaded for this file - BitSize_t byteLengthOfThisFile; - - /// \brief How many bytes of this file has been downloaded - BitSize_t bytesDownloadedForThisFile; - - /// \brief Files are transmitted in sets, where more than one set of files can be transmitted at the same time. - /// \details This is the identifier for the set, which is returned by FileListTransfer::SetupReceive - unsigned short setID; - - /// \brief The number of files that are in this set. - unsigned numberOfFilesInThisSet; - - /// \brief The total length of the transmitted files for this set, after being uncompressed - unsigned byteLengthOfThisSet; - - /// \brief The total length, in bytes, downloaded for this set. - unsigned bytesDownloadedForThisSet; - - /// \brief User data passed to one of the functions in the FileList class. - /// \details However, on error, this is instead changed to one of the enumerations in the PatchContext structure. - FileListNodeContext context; - - /// \brief Who sent this file - SystemAddress senderSystemAddress; - - /// \brief Who sent this file. Not valid when using TCP, only RakPeer (UDP) - RakNetGUID senderGuid; - }; - - // Note: If this structure is changed the struct in the swig files need to be changed as well - struct FileProgressStruct - { - /// \param[out] onFileStruct General information about this file, such as the filename and the first \a partLength bytes. You do NOT need to save this data yourself. The complete file will arrive normally. - OnFileStruct *onFileStruct; - /// \param[out] partCount The zero based index into partTotal. The percentage complete done of this file is 100 * (partCount+1)/partTotal - unsigned int partCount; - /// \param[out] partTotal The total number of parts this file was split into. Each part will be roughly the MTU size, minus the UDP header and RakNet headers - unsigned int partTotal; - /// \param[out] dataChunkLength How many bytes long firstDataChunk and iriDataChunk are - unsigned int dataChunkLength; - /// \param[out] firstDataChunk The first \a partLength of the final file. If you store identifying information about the file in the first \a partLength bytes, you can read them while the download is taking place. If this hasn't arrived yet, firstDataChunk will be 0 - char *firstDataChunk; - /// \param[out] iriDataChunk If the remote system is sending this file using IncrementalReadInterface, then this is the chunk we just downloaded. It will not exist in memory after this callback. You should either store this to disk, or in memory. If it is 0, then the file is smaller than one chunk, and will be held in memory automatically - char *iriDataChunk; - /// \param[out] iriWriteOffset Offset in bytes from the start of the file for the data pointed to by iriDataChunk - unsigned int iriWriteOffset; - /// \param[out] Who sent this file - SystemAddress senderSystemAddress; - /// \param[out] Who sent this file. Not valid when using TCP, only RakPeer (UDP) - RakNetGUID senderGuid; - /// \param[in] allocateIrIDataChunkAutomatically If true, then RakNet will hold iriDataChunk for you and return it in OnFile. Defaults to true - bool allocateIrIDataChunkAutomatically; - }; - - struct DownloadCompleteStruct - { - /// \brief Files are transmitted in sets, where more than one set of files can be transmitted at the same time. - /// \details This is the identifier for the set, which is returned by FileListTransfer::SetupReceive - unsigned short setID; - - /// \brief The number of files that are in this set. - unsigned numberOfFilesInThisSet; - - /// \brief The total length of the transmitted files for this set, after being uncompressed - unsigned byteLengthOfThisSet; - - /// \brief Who sent this file - SystemAddress senderSystemAddress; - - /// \brief Who sent this file. Not valid when using TCP, only RakPeer (UDP) - RakNetGUID senderGuid; - }; - - FileListTransferCBInterface() {} - virtual ~FileListTransferCBInterface() {} - - /// \brief Got a file. - /// \details This structure is only valid for the duration of this function call. - /// \return Return true to have RakNet delete the memory allocated to hold this file for this function call. - virtual bool OnFile(OnFileStruct *onFileStruct)=0; - - /// \brief Got part of a big file internally in RakNet - /// \details This is called in one of two circumstances: Either the transport layer is returning ID_PROGRESS_NOTIFICATION, or you got a block via IncrementalReadInterface - /// If the transport layer is returning ID_PROGRESS_NOTIFICATION (see RakPeer::SetSplitMessageProgressInterval()) then FileProgressStruct::iriDataChunk will be 0. - /// If this is a block via IncrementalReadInterface, then iriDataChunk will point to the block just downloaded. - /// If not using IncrementalReadInterface, then you only care about partCount and partTotal to tell how far the download has progressed. YOu can use firstDataChunk to read the first part of the file if desired. The file is usable when you get the OnFile callback. - /// If using IncrementalReadInterface and you let RakNet buffer the files in memory (default), then it is the same as above. The file is usable when you get the OnFile callback. - /// If using IncrementalReadInterface and you do not let RakNet buffer the files in memory, then set allocateIrIDataChunkAutomatically to false. Write the file to disk whenever you get OnFileProgress and iriDataChunk is not 0, and ignore OnFile. - virtual void OnFileProgress(FileProgressStruct *fps)=0; - - /// \brief Called while the handler is active by FileListTransfer - /// \details Return false when you are done with the class. - /// At that point OnDereference will be called and the class will no longer be maintained by the FileListTransfer plugin. - virtual bool Update(void) {return true;} - - /// \brief Called when the download is completed. - /// \details If you are finished with this class, return false. - /// At that point OnDereference will be called and the class will no longer be maintained by the FileListTransfer plugin. - /// Otherwise return true, and Update will continue to be called. - virtual bool OnDownloadComplete(DownloadCompleteStruct *dcs) {(void) dcs; return false;} - - /// \brief This function is called when this instance is about to be dereferenced by the FileListTransfer plugin. - /// \details Update will no longer be called. - /// It will will be deleted automatically if true was passed to FileListTransfer::SetupReceive::deleteHandler - /// Otherwise it is up to you to delete it yourself. - virtual void OnDereference(void) {} -}; - -} // namespace MafiaNet - -#endif - diff --git a/vendors/mafianet/Source/include/mafianet/FileOperations.h b/vendors/mafianet/Source/include/mafianet/FileOperations.h deleted file mode 100644 index 901a73fc4..000000000 --- a/vendors/mafianet/Source/include/mafianet/FileOperations.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -/// \file FileOperations.h -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_FileOperations==1 - -#ifndef __FILE_OPERATIONS_H -#define __FILE_OPERATIONS_H - -#include "Export.h" - -bool RAK_DLL_EXPORT WriteFileWithDirectories( const char *path, char *data, unsigned dataLength ); -bool RAK_DLL_EXPORT IsSlash(unsigned char c); -void RAK_DLL_EXPORT AddSlash( char *input ); -void RAK_DLL_EXPORT QuoteIfSpaces(char *str); -bool RAK_DLL_EXPORT DirectoryExists(const char *directory); -unsigned int RAK_DLL_EXPORT GetFileLength(const char *path); - -#endif - -#endif // _RAKNET_SUPPORT_FileOperations diff --git a/vendors/mafianet/Source/include/mafianet/FormatString.h b/vendors/mafianet/Source/include/mafianet/FormatString.h deleted file mode 100644 index 952ecae3c..000000000 --- a/vendors/mafianet/Source/include/mafianet/FormatString.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -/// \file FormatString.h -/// - - -#ifndef __FORMAT_STRING_H -#define __FORMAT_STRING_H - -#include "Export.h" - -extern "C" { -char * FormatString(const char *format, ...); -} -// Threadsafe -extern "C" { -char * FormatStringTS(char *output, const char *format, ...); -} - - -#endif - diff --git a/vendors/mafianet/Source/include/mafianet/FullyConnectedMesh2.h b/vendors/mafianet/Source/include/mafianet/FullyConnectedMesh2.h deleted file mode 100644 index 6c81b49a0..000000000 --- a/vendors/mafianet/Source/include/mafianet/FullyConnectedMesh2.h +++ /dev/null @@ -1,430 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file FullyConnectedMesh2.h -/// \brief Fully connected mesh plugin, revision 2. -/// \details This will connect RakPeer to all connecting peers, and all peers the connecting peer knows about. -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_FullyConnectedMesh2==1 - -#ifndef __FULLY_CONNECTED_MESH_2_H -#define __FULLY_CONNECTED_MESH_2_H - -#include "PluginInterface2.h" -#include "memoryoverride.h" -#include "NativeTypes.h" -#include "DS_List.h" -#include "string.h" -#include "BitStream.h" - -typedef int64_t FCM2Guid; - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; - -/// \brief Fully connected mesh plugin, revision 2 -/// \details This will connect RakPeer to all connecting peers, and all peers the connecting peer knows about.
-/// It will also calculate which system has been running longest, to find out who should be host, if you need one system to act as a host -/// \pre You must also install the ConnectionGraph2 plugin in order to use SetConnectOnNewRemoteConnection() -/// \ingroup FULLY_CONNECTED_MESH_GROUP -class RAK_DLL_EXPORT FullyConnectedMesh2 : public PluginInterface2 -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(FullyConnectedMesh2) - - FullyConnectedMesh2(); - virtual ~FullyConnectedMesh2(); - - /// When the message ID_REMOTE_NEW_INCOMING_CONNECTION arrives, we try to connect to that system - /// If \a attemptConnection is false, you can manually connect to all systems listed in ID_REMOTE_NEW_INCOMING_CONNECTION with ConnectToRemoteNewIncomingConnections() - /// \note This will not work on any console. It will also not work if NAT punchthrough is needed. Generally, this should be false and you should connect manually. It is here for legacy reasons. - /// \param[in] attemptConnection If true, we try to connect to any systems we are notified about with ID_REMOTE_NEW_INCOMING_CONNECTION, which comes from the ConnectionGraph2 plugin. Defaults to true. - /// \param[in] pw The password to use to connect with. Only used if \a attemptConnection is true - void SetConnectOnNewRemoteConnection(bool attemptConnection, MafiaNet::RakString pw); - - /// \brief The connected host is whichever system we are connected to that has been running the longest. - /// \details Will return UNASSIGNED_RAKNET_GUID if we are not connected to anyone, or if we are connected and are calculating the host - /// If includeCalculating is true, will return the estimated calculated host as long as the calculation is nearly complete - /// includeCalculating should be true if you are taking action based on another system becoming host, because not all host calculations may complete at the exact same time - /// \sa ConnectionGraph2::GetLowestAveragePingSystem() . If you need one system in the peer to peer group to relay data, have the host call this function after host migration, and use that system - /// \return System address of whichever system is host. - RakNetGUID GetConnectedHost(void) const; - SystemAddress GetConnectedHostAddr(void) const; - - /// \return System address of whichever system is host. Always returns something, even though it may be our own system. - RakNetGUID GetHostSystem(void) const; - - /// \return If our system is host - bool IsHostSystem(void) const; - - /// Get the list of connected systems, from oldest connected to newest - /// This is also the order that the hosts will be chosen in - void GetHostOrder(DataStructures::List &hostList); - - /// \param[in] includeCalculating If true, and we are currently calculating a new host, return the new host if the calculation is nearly complete - /// \return If our system is host - bool IsConnectedHost(void) const; - - /// \brief Automatically add new connections to the fully connected mesh. - /// Each remote system that you want to check should be added as a participant, either through SetAutoparticipateConnections() or by calling this function - /// \details Defaults to true. - /// \param[in] b As stated - void SetAutoparticipateConnections(bool b); - - /// Clear our own host order, and recalculate as if we had just reconnected - /// Call this to reset the running time of the host just before joining/creating a game room for networking - void ResetHostCalculation(void); - - /// \brief if SetAutoparticipateConnections() is called with false, then you need to use AddParticipant before these systems will be added to the mesh - /// FullyConnectedMesh2 will track who is the who host among a fully connected mesh of participants - /// Each remote system that you want to check should be added as a participant, either through SetAutoparticipateConnections() or by calling this function - /// \param[in] participant The new participant - /// \param[in] userContext Static data to be passed around with each participant, which can be queried with GetParticipantData(). - /// \sa StartVerifiedJoin() - void AddParticipant(RakNetGUID rakNetGuid); - - /// Get the participants added with AddParticipant() - /// \param[out] participantList Participants added with AddParticipant(); - void GetParticipantList(DataStructures::List &participantList); - - /// \brief Returns if a participant is in the participant list - /// \param[in] RakNetGUID of the participant to query - /// \return True if in the list - bool HasParticipant(RakNetGUID participantGuid); - - /// \brief Reads userData written with SetMyContext() - /// \param[in] RakNetGUID of the participant to query - /// \param[out] userContext Pointer to BitStream to be written to - /// \return True if data was written - // bool GetParticipantContext(RakNetGUID participantGuid, BitStream *userContext); - - /// Set data for other systems to read with GetParticipantContext - /// \param[in] userContext Pointer to BitStream to be read from - // void SetMyContext(BitStream *userContext); - - /// Connect to all systems from ID_REMOTE_NEW_INCOMING_CONNECTION - /// You can call this if SetConnectOnNewRemoteConnection is false - /// \param[in] packet The packet containing ID_REMOTE_NEW_INCOMING_CONNECTION - /// \param[in] connectionPassword Password passed to RakPeerInterface::Connect() - /// \param[in] connectionPasswordLength Password length passed to RakPeerInterface::Connect() - void ConnectToRemoteNewIncomingConnections(Packet *packet); - - /// \brief Clear all memory and reset everything - void Clear(void); - - unsigned int GetParticipantCount(void) const; - void GetParticipantCount(unsigned int *participantListSize) const; - - /// In the simple case of forming a peer to peer mesh: - /// - /// 1. AddParticipant() is called on the host whenever you get a new connection - /// 2. The host sends all participants to the new client - /// 3. The client connects to the participant list - /// - /// However, the above steps assumes connections to all systems in the mesh always complete. - /// When there is a risk of failure, such as if relying on NATPunchthroughClient, you may not want to call AddParticipant() until are connections have completed to all other particpants - /// StartVerifiedJoin() can manage the overhead of the negotiation involved so the programmer only has to deal with overall success or failure - /// - /// Processing: - /// 1. Send the RakNetGUID and SystemAddress values of GetParticipantList() to the client with ID_FCM2_VERIFIED_JOIN_START - /// 2. The client, on ID_FCM2_VERIFIED_JOIN_START, can execute NatPunchthroughClient::OpenNAT() (optional), followed by RakPeerInterface::Connect() if punchthrough success, for each system returned from GetVerifiedJoinRequiredProcessingList() - /// 3. After all participants in step 2 have connected, failed to connect, or failed NatPunchthrough, the client automatically sends the results to the server. - /// 4. The server compares the results of the operations in step 2 with the values from GetParticpantList(). - /// 4A. If the client failed to connect to a current participant, return ID_FCM2_VERIFIED_JOIN_FAILED to the client. CloseConnection() is automatically called on the client for the failed participants. - /// 4B. If AddParticipant() was called between steps 1 and 4, go back to step 1, transmitting new participants. - /// 4C. If the client successfully connected to all participants, the server gets ID_FCM2_VERIFIED_JOIN_CAPABLE. The server programmer, on the same frame, should execute RespondOnVerifiedJoinCapable() to either accept or reject the client. - /// 5. If the client got ID_FCM2_VERIFIED_JOIN_ACCEPTED, AddParticipant() is automatically called for each system in the mesh. - /// 6. If the client got ID_FCM2_VERIFIED_JOIN_REJECTED, CloseConnection() is automatically called for each system in the mesh. The connection is NOT automatically closed to the original host that sent StartVerifiedJoin(). - /// 7. If the client's connection to the server was lost before getting ID_FCM2_VERIFIED_JOIN_ACCEPTED or ID_FCM2_VERIFIED_JOIN_REJECTED, return to the programmer ID_FCM2_VERIFIED_JOIN_FAILED and call RakPeerInterface::CloseConnection() - /// - /// \brief Notify the client of GetParticipantList() in order to connect to each of those systems until the mesh has been completed - /// \param[in] client The system to send ID_FCM2_VERIFIED_JOIN_START to - virtual void StartVerifiedJoin(RakNetGUID client); - - /// \brief On ID_FCM2_VERIFIED_JOIN_CAPABLE , accept or reject the new connection - /// \code - /// fullyConnectedMesh->RespondOnVerifiedJoinCapable(packet, true, 0); - /// \endcode - /// \param[in] packet The system that sent ID_FCM2_VERIFIED_JOIN_CAPABLE. Based on \accept, ID_FCM2_VERIFIED_JOIN_ACCEPTED or ID_FCM2_VERIFIED_JOIN_REJECTED will be sent in reply - /// \param[in] accept True to accept, and thereby automatically call AddParticipant() on all systems on the mesh. False to reject, and call CloseConnection() to all mesh systems on the target - /// \param[in] additionalData Any additional data you want to add to the ID_FCM2_VERIFIED_JOIN_ACCEPTED or ID_FCM2_VERIFIED_JOIN_REJECTED messages - /// \sa WriteVJCUserData() - virtual void RespondOnVerifiedJoinCapable(Packet *packet, bool accept, BitStream *additionalData); - - /// \brief On ID_FCM2_VERIFIED_JOIN_START, read the SystemAddress and RakNetGUID values of each system to connect to - /// \code - /// DataStructures::List addresses; - /// DataStructures::List guids; - /// fullyConnectedMesh->GetVerifiedJoinRequiredProcessingList(packet->guid, addresses, guids); - /// for (unsigned int i=0; i < addresses.Size(); i++) - /// rakPeer[i]->Connect(addresses[i].ToString(false), addresses[i].GetPort(), 0, 0); - /// \endcode - /// \param[in] host Which system sent ID_FCM2_VERIFIED_JOIN_START - /// \param[out] addresses SystemAddress values of systems to connect to. List has the same number and order as \a guids - /// \param[out] guids RakNetGUID values of systems to connect to. List has the same number and order as \a guids - /// \param[out] userData What was written with WriteVJSUserData - virtual void GetVerifiedJoinRequiredProcessingList(RakNetGUID host, - DataStructures::List &addresses, - DataStructures::List &guids, - DataStructures::List &userData); - - /// \brief On ID_FCM2_VERIFIED_JOIN_ACCEPTED, read additional data passed to RespondOnVerifiedJoinCapable() - /// \code - /// bool thisSystemAccepted; - /// DataStructures::List systemsAccepted; - /// MafiaNet::BitStream additionalData; - /// fullyConnectedMesh->GetVerifiedJoinAcceptedAdditionalData(packet, &thisSystemAccepted, systemsAccepted, &additionalData); - /// \endcode - /// \param[in] packet Packet containing the ID_FCM2_VERIFIED_JOIN_ACCEPTED message - /// \param[out] thisSystemAccepted If true, it was this instance of RakPeerInterface that was accepted. If false, this is notification for another system - /// \param[out] systemsAccepted Which system(s) were added with AddParticipant(). If \a thisSystemAccepted is false, this list will only have length 1 - /// \param[out] additionalData \a additionalData parameter passed to RespondOnVerifiedJoinCapable() - virtual void GetVerifiedJoinAcceptedAdditionalData(Packet *packet, bool *thisSystemAccepted, DataStructures::List &systemsAccepted, BitStream *additionalData); - - /// \brief On ID_FCM2_VERIFIED_JOIN_REJECTED, read additional data passed to RespondOnVerifiedJoinCapable() - /// \details This does not automatically close the connection. The following code will do so: - /// \code - /// rakPeer[i]->CloseConnection(packet->guid, true); - /// \endcode - /// \param[in] packet Packet containing the ID_FCM2_VERIFIED_JOIN_REJECTED message - /// \param[out] additionalData \a additionalData parameter passed to RespondOnVerifiedJoinCapable(). - virtual void GetVerifiedJoinRejectedAdditionalData(Packet *packet, BitStream *additionalData); - - /// Override to write data when ID_FCM2_VERIFIED_JOIN_CAPABLE is sent - virtual void WriteVJCUserData(MafiaNet::BitStream *bsOut) {(void) bsOut;} - - /// Use to read data written from WriteVJCUserData() - /// \code - /// MafiaNet::BitStream bsIn(packet->data,packet->length,false); - /// FullyConnectedMesh2::SkipToVJCUserData(&bsIn); - /// // Your code here - /// \endcode - static void SkipToVJCUserData(MafiaNet::BitStream *bsIn); - - /// Write custom user data to be sent with ID_FCM2_VERIFIED_JOIN_START, per user - /// \param[out] bsOut Write your data here, if any. Has to match what is read by ReadVJSUserData - /// \param[in] userGuid The RakNetGuid of the user you are writing for - /// \param[in] userContext The data set with SetMyContext() for that system. May be empty. To properly write userContext, you will need to first write userContext->GetNumberOfBitsUsed(), followed by bsOut->Write(userContext); - //virtual void WriteVJSUserData(MafiaNet::BitStream *bsOut, RakNetGUID userGuid, BitStream *userContext) {(void) bsOut; (void) userGuid; (void) userContext;} - virtual void WriteVJSUserData(MafiaNet::BitStream *bsOut, RakNetGUID userGuid) {(void) bsOut; (void) userGuid;} - - /// \internal - MafiaNet::TimeUS GetElapsedRuntime(void); - - /// \internal - virtual PluginReceiveResult OnReceive(Packet *packet); - /// \internal - virtual void OnRakPeerStartup(void); - /// \internal - virtual void OnAttach(void); - /// \internal - virtual void OnRakPeerShutdown(void); - /// \internal - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - /// \internal - virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); - /// \internal - virtual void OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason); - - /// \internal - struct FCM2Participant - { - FCM2Participant() {} - FCM2Participant(const FCM2Guid &_fcm2Guid, const RakNetGUID &_rakNetGuid) : fcm2Guid(_fcm2Guid), rakNetGuid(_rakNetGuid) {} - - // Low half is a random number. - // High half is the order we connected in (totalConnectionCount) - FCM2Guid fcm2Guid; - RakNetGUID rakNetGuid; - // BitStream userContext; - }; - - enum JoinInProgressState - { - JIPS_PROCESSING, - JIPS_FAILED, - JIPS_CONNECTED, - JIPS_UNNECESSARY, - }; - - struct VerifiedJoinInProgressMember - { - SystemAddress systemAddress; - RakNetGUID guid; - JoinInProgressState joinInProgressState; - BitStream *userData; - - bool workingFlag; - }; - - /// \internal - struct VerifiedJoinInProgress - { - RakNetGUID requester; - DataStructures::List vjipMembers; - //bool sentResults; - }; - - /// \internal for debugging - unsigned int GetTotalConnectionCount(void) const; - -protected: - void PushNewHost(const RakNetGUID &guid, RakNetGUID oldHost); - void SendOurFCMGuid(SystemAddress addr); - void SendFCMGuidRequest(RakNetGUID rakNetGuid); - void SendConnectionCountResponse(SystemAddress addr, unsigned int responseTotalConnectionCount); - void OnRequestFCMGuid(Packet *packet); - //void OnUpdateUserContext(Packet *packet); - void OnRespondConnectionCount(Packet *packet); - void OnInformFCMGuid(Packet *packet); - void OnUpdateMinTotalConnectionCount(Packet *packet); - void AssignOurFCMGuid(void); - void CalculateHost(RakNetGUID *rakNetGuid, FCM2Guid *fcm2Guid); - // bool AddParticipantInternal( RakNetGUID rakNetGuid, FCM2Guid theirFCMGuid, BitStream *userContext ); - bool AddParticipantInternal( RakNetGUID rakNetGuid, FCM2Guid theirFCMGuid ); - void CalculateAndPushHost(void); - bool ParticipantListComplete(void); - void IncrementTotalConnectionCount(unsigned int i); - PluginReceiveResult OnVerifiedJoinStart(Packet *packet); - PluginReceiveResult OnVerifiedJoinCapable(Packet *packet); - virtual void OnVerifiedJoinFailed(RakNetGUID hostGuid, bool callCloseConnection); - virtual void OnVerifiedJoinAccepted(Packet *packet); - virtual void OnVerifiedJoinRejected(Packet *packet); - unsigned int GetJoinsInProgressIndex(RakNetGUID requester) const; - void UpdateVerifiedJoinInProgressMember(const AddressOrGUID systemIdentifier, RakNetGUID guidToAssign, JoinInProgressState newState); - bool ProcessVerifiedJoinInProgressIfCompleted(VerifiedJoinInProgress *vjip); - void ReadVerifiedJoinInProgressMember(MafiaNet::BitStream *bsIn, VerifiedJoinInProgressMember *vjipm); - unsigned int GetVerifiedJoinInProgressMemberIndex(const AddressOrGUID systemIdentifier, VerifiedJoinInProgress *vjip); - void DecomposeJoinCapable(Packet *packet, VerifiedJoinInProgress *vjip); - void WriteVerifiedJoinCapable(MafiaNet::BitStream *bsOut, VerifiedJoinInProgress *vjip); - void CategorizeVJIP(VerifiedJoinInProgress *vjip, - DataStructures::List &participatingMembersOnClientSucceeded, - DataStructures::List &participatingMembersOnClientFailed, - DataStructures::List &participatingMembersNotOnClient, - DataStructures::List &clientMembersNotParticipatingSucceeded, - DataStructures::List &clientMembersNotParticipatingFailed); - - // Used to track how long RakNet has been running. This is so we know who has been running longest - MafiaNet::TimeUS startupTime; - - // Option for SetAutoparticipateConnections - bool autoParticipateConnections; - - // totalConnectionCount is roughly maintained across all systems, and increments by 1 each time a new system connects to the mesh - // It is always kept at the highest known value - // It is used as the high 4 bytes for new FCMGuids. This causes newer values of FCM2Guid to be higher than lower values. The lowest value is the host. - unsigned int totalConnectionCount; - - // Our own ourFCMGuid. Starts at unassigned (0). Assigned once we send ID_FCM2_REQUEST_FCMGUID and get back ID_FCM2_RESPOND_CONNECTION_COUNT - FCM2Guid ourFCMGuid; - - /// List of systems we know the FCM2Guid for - DataStructures::List fcm2ParticipantList; - - RakNetGUID lastPushedHost; - - // Optimization: Store last calculated host in these variables. - RakNetGUID hostRakNetGuid; - FCM2Guid hostFCM2Guid; - - MafiaNet::RakString connectionPassword; - bool connectOnNewRemoteConnections; - - DataStructures::List joinsInProgress; - BitStream myContext; -}; - -} // namespace MafiaNet - -/* -Startup() -ourFCMGuid=unknown -totalConnectionCount=0 -Set startupTime - -AddParticipant() -if (sender by guid is a participant) -return; -AddParticipantInternal(guid); -if (ourFCMGuid==unknown) -Send to that system a request for their fcmGuid, totalConnectionCount. Inform startupTime. -else -Send to that system a request for their fcmGuid. Inform total connection count, our fcmGuid - -OnRequestGuid() -if (sender by guid is not a participant) -{ - // They added us as a participant, but we didn't add them. This can be caused by lag where both participants are not added at the same time. - // It doesn't affect the outcome as long as we still process the data - AddParticipantInternal(guid); -} -if (ourFCMGuid==unknown) -{ - if (includedStartupTime) - { - // Nobody has a fcmGuid - - if (their startup time is greater than our startup time) - ReplyConnectionCount(1); - else - ReplyConnectionCount(2); - } - else - { - // They have a fcmGuid, we do not - - SetMaxTotalConnectionCount(remoteCount); - AssignTheirGuid() - GenerateOurGuid(); - SendOurGuid(all); - } -} -else -{ - if (includedStartupTime) - { - // We have a fcmGuid they do not - - ReplyConnectionCount(totalConnectionCount+1); - SendOurGuid(sender); - } - else - { - // We both have fcmGuids - - SetMaxTotalConnectionCount(remoteCount); - AssignTheirGuid(); - SendOurGuid(sender); - } -} - -OnReplyConnectionCount() -SetMaxTotalConnectionCount(remoteCount); -GenerateOurGuid(); -SendOurGuid(allParticipants); - -OnReceiveTheirGuid() -AssignTheirGuid() -*/ - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/GetTime.h b/vendors/mafianet/Source/include/mafianet/GetTime.h deleted file mode 100644 index d57243ef9..000000000 --- a/vendors/mafianet/Source/include/mafianet/GetTime.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file GetTime.h -/// \brief Returns the value from QueryPerformanceCounter. This is the function RakNet uses to represent time. This time won't match the time returned by GetTimeCount(). See http://www.jenkinssoftware.com/forum/index.php?topic=2798.0 -/// - - -#ifndef __GET_TIME_H -#define __GET_TIME_H - -#include "Export.h" -#include "time.h" // For MafiaNet::TimeMS - -namespace MafiaNet -{ - /// Same as GetTimeMS - /// Holds the time in either a 32 or 64 bit variable, depending on __GET_TIME_64BIT - MafiaNet::Time RAK_DLL_EXPORT GetTime( void ); - - /// Return the time as 32 bit - /// \note The maximum delta between returned calls is 1 second - however, RakNet calls this constantly anyway. See NormalizeTime() in the cpp. - MafiaNet::TimeMS RAK_DLL_EXPORT GetTimeMS( void ); - - /// Return the time as 64 bit - /// \note The maximum delta between returned calls is 1 second - however, RakNet calls this constantly anyway. See NormalizeTime() in the cpp. - MafiaNet::TimeUS RAK_DLL_EXPORT GetTimeUS( void ); - - /// a > b? - extern RAK_DLL_EXPORT bool GreaterThan(MafiaNet::Time a, MafiaNet::Time b); - /// a < b? - extern RAK_DLL_EXPORT bool LessThan(MafiaNet::Time a, MafiaNet::Time b); -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/Getche.h b/vendors/mafianet/Source/include/mafianet/Getche.h deleted file mode 100644 index 7875303b6..000000000 --- a/vendors/mafianet/Source/include/mafianet/Getche.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#if defined(_WIN32) -#include /* _getche() */ - -#else -#include -#include -#include -char _getche(); -#endif diff --git a/vendors/mafianet/Source/include/mafianet/Gets.h b/vendors/mafianet/Source/include/mafianet/Gets.h deleted file mode 100644 index 226e1ae0c..000000000 --- a/vendors/mafianet/Source/include/mafianet/Gets.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -#ifndef __GETS__H_ -#define __GETS__H_ - -#ifdef __cplusplus -extern "C" { -#endif - -char * Gets ( char * str, int num ); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/GridSectorizer.h b/vendors/mafianet/Source/include/mafianet/GridSectorizer.h deleted file mode 100644 index 3890fcc02..000000000 --- a/vendors/mafianet/Source/include/mafianet/GridSectorizer.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef _GRID_SECTORIZER_H -#define _GRID_SECTORIZER_H - -//#define _USE_ORDERED_LIST - -#include "memoryoverride.h" - -#ifdef _USE_ORDERED_LIST -#include "DS_OrderedList.h" -#else -#include "DS_List.h" -#endif - -class GridSectorizer -{ -public: - GridSectorizer(); - ~GridSectorizer(); - - // _cellWidth, _cellHeight is the width and height of each cell in world units - // minX, minY, maxX, maxY are the world dimensions (can be changed to dynamically allocate later if needed) - void Init(const float _maxCellWidth, const float _maxCellHeight, const float minX, const float minY, const float maxX, const float maxY); - - // Adds a pointer to the grid with bounding rectangle dimensions - void AddEntry(void *entry, const float minX, const float minY, const float maxX, const float maxY); - -#ifdef _USE_ORDERED_LIST - - // Removes a pointer, as above - void RemoveEntry(void *entry, const float minX, const float minY, const float maxX, const float maxY); - - // Adds and removes in one pass, more efficient than calling both functions consecutively - void MoveEntry(void *entry, const float sourceMinX, const float sourceMinY, const float sourceMaxX, const float sourceMaxY, - const float destMinX, const float destMinY, const float destMaxX, const float destMaxY); - -#endif - - // Adds to intersectionList all entries in a certain radius - void GetEntries(DataStructures::List& intersectionList, const float minX, const float minY, const float maxX, const float maxY); - - void Clear(void); - -protected: - int WorldToCellX(const float input) const; - int WorldToCellY(const float input) const; - int WorldToCellXOffsetAndClamped(const float input) const; - int WorldToCellYOffsetAndClamped(const float input) const; - - // Returns true or false if a position crosses cells in the grid. If false, you don't need to move entries - bool PositionCrossesCells(const float originX, const float originY, const float destinationX, const float destinationY) const; - - float cellOriginX, cellOriginY; - float cellWidth, cellHeight; - float invCellWidth, invCellHeight; - float gridWidth, gridHeight; - int gridCellWidthCount, gridCellHeightCount; - - - // int gridWidth, gridHeight; - -#ifdef _USE_ORDERED_LIST - DataStructures::OrderedList* grid; -#else - DataStructures::List* grid; -#endif -}; - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/HTTPConnection.h b/vendors/mafianet/Source/include/mafianet/HTTPConnection.h deleted file mode 100644 index 52bae2b8f..000000000 --- a/vendors/mafianet/Source/include/mafianet/HTTPConnection.h +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file HTTPConnection.h -/// \brief Contains HTTPConnection, used to communicate with web servers -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_HTTPConnection==1 && _RAKNET_SUPPORT_TCPInterface==1 - -#ifndef __HTTP_CONNECTION -#define __HTTP_CONNECTION - -#include "Export.h" -#include "string.h" -#include "memoryoverride.h" -#include "types.h" -#include "DS_Queue.h" - -namespace MafiaNet -{ -/// Forward declarations -class TCPInterface; -struct SystemAddress; - -/// \brief Use HTTPConnection to communicate with a web server. -/// \details Start an instance of TCPInterface via the Start() command. -/// Instantiate a new instance of HTTPConnection, and associate TCPInterface with the class in the constructor. -/// Use Post() to send commands to the web server, and ProcessDataPacket() to update the connection with packets returned from TCPInterface that have the system address of the web server -/// This class will handle connecting and reconnecting as necessary. -/// -/// Note that only one Post() can be handled at a time. -/// \deprecated, use HTTPConnection2 -class RAK_DLL_EXPORT HTTPConnection -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(HTTPConnection) - - /// Returns a HTTP object associated with this tcp connection - HTTPConnection(); - virtual ~HTTPConnection(); - - /// \pre tcp should already be started - void Init(TCPInterface *_tcp, const char *host, unsigned short port=80); - - /// Submit data to the HTTP server - /// HTTP only allows one request at a time per connection - /// - /// \pre IsBusy()==false - /// \param path the path on the remote server you want to POST to. For example "index.html" - /// \param data A null-terminated string to submit to the server - /// \param contentType "Content-Type:" passed to post. - void Post(const char *path, const char *data, const char *_contentType="application/x-www-form-urlencoded"); - - /// Get a file from a webserver - /// \param path the path on the remote server you want to GET from. For example "index.html" - void Get(const char *path); - - /// Is there a Read result ready? - bool HasRead(void) const; - - /// Get one result from the server - /// \pre HasResult must return true - MafiaNet::RakString Read(void); - - /// Call periodically to do time-based updates - void Update(void); - - /// Returns the address of the server we are connected to - SystemAddress GetServerAddress(void) const; - - /// Process an HTTP data packet returned from TCPInterface - /// Returns true when we have gotten all the data from the HTTP server. - /// If this returns true then it's safe to Post() another request - /// Deallocate the packet as usual via TCPInterface - /// \param packet nullptr or a packet associated with our host and port - void ProcessTCPPacket(Packet *packet); - - /// Results of HTTP requests. Standard response codes are < 999 - /// ( define HTTP codes and our internal codes as needed ) - enum ResponseCodes { NoBody=1001, OK=200, Deleted=1002 }; - - HTTPConnection& operator=(const HTTPConnection& rhs){(void) rhs; return *this;} - - /// Encapsulates a raw HTTP response and response code - struct BadResponse - { - public: - BadResponse() {code=0;} - - BadResponse(const unsigned char *_data, int _code) - : data((const char *)_data), code(_code) {} - - BadResponse(const char *_data, int _code) - : data(_data), code(_code) {} - - operator int () const { return code; } - - MafiaNet::RakString data; - int code; // ResponseCodes - }; - - /// Queued events of failed exchanges with the HTTP server - bool HasBadResponse(int *code, MafiaNet::RakString *data); - - /// Returns false if the connection is not doing anything else - bool IsBusy(void) const; - - /// \internal - int GetState(void) const; - - struct OutgoingCommand - { - MafiaNet::RakString remotePath; - MafiaNet::RakString data; - MafiaNet::RakString contentType; - bool isPost; - }; - - DataStructures::Queue outgoingCommand; - OutgoingCommand currentProcessingCommand; - -private: - SystemAddress server; - TCPInterface *tcp; - MafiaNet::RakString host; - unsigned short port; - DataStructures::Queue badResponses; - - enum ConnectionState - { - CS_NONE, - CS_DISCONNECTING, - CS_CONNECTING, - CS_CONNECTED, - CS_PROCESSING, - } connectionState; - - MafiaNet::RakString incomingData; - DataStructures::Queue results; - - void CloseConnection(); - - /* - enum { RAK_HTTP_INITIAL, - RAK_HTTP_STARTING, - RAK_HTTP_CONNECTING, - RAK_HTTP_ESTABLISHED, - RAK_HTTP_REQUEST_SENT, - RAK_HTTP_IDLE } state; - - MafiaNet::RakString outgoing, incoming, path, contentType; - void Process(Packet *packet); // the workhorse - - // this helps check the various status lists in TCPInterface - typedef SystemAddress (TCPInterface::*StatusCheckFunction)(void); - bool InList(StatusCheckFunction func); - */ - -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/HTTPConnection2.h b/vendors/mafianet/Source/include/mafianet/HTTPConnection2.h deleted file mode 100644 index 9511de97b..000000000 --- a/vendors/mafianet/Source/include/mafianet/HTTPConnection2.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file HTTPConnection2.h -/// \brief Contains HTTPConnection2, used to communicate with web servers -/// - -#include - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_HTTPConnection2==1 && _RAKNET_SUPPORT_TCPInterface==1 - -#ifndef __HTTP_CONNECTION_2 -#define __HTTP_CONNECTION_2 - -#include "Export.h" -#include "string.h" -#include "memoryoverride.h" -#include "types.h" -#include "DS_List.h" -#include "DS_Queue.h" -#include "PluginInterface2.h" -#include "SimpleMutex.h" - -namespace MafiaNet -{ -/// Forward declarations -class TCPInterface; -struct SystemAddress; - -/// \brief Use HTTPConnection2 to communicate with a web server. -/// \details Start an instance of TCPInterface via the Start() command. -/// This class will handle connecting to transmit a request -class RAK_DLL_EXPORT HTTPConnection2 : public PluginInterface2 -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(HTTPConnection2) - - HTTPConnection2(); - virtual ~HTTPConnection2(); - - /// \brief Connect to, then transmit a request to a TCP based server - /// \param[in] tcp An instance of TCPInterface that previously had TCPInterface::Start() called - /// \param[in] stringToTransmit What string to transmit. See RakString::FormatForPOST(), RakString::FormatForGET(), RakString::FormatForDELETE() - /// \param[in] host The IP address to connect to - /// \param[in] port The port to connect to - /// \param[in] useSSL If to use SSL to connect. OPEN_SSL_CLIENT_SUPPORT must be defined to 1 in defines.h or defineoverrides.h - /// \param[in] ipVersion 4 for IPV4, 6 for IPV6 - /// \param[in] useAddress Assume we are connected to this address and send to it, rather than do a lookup - /// \param[in] userData - /// \return false if host is not a valid IP address or domain name - bool TransmitRequest(const char* stringToTransmit, const char* host, unsigned short port=80, bool useSSL=false, int ipVersion=4, SystemAddress useAddress=UNASSIGNED_SYSTEM_ADDRESS, void *userData=0); - - /// \brief Check for and return a response from a prior call to TransmitRequest() - /// As TCP is stream based, you may get a webserver reply over several calls to TCPInterface::Receive() - /// HTTPConnection2 will store Packet::data and return the response to you either when the connection to the webserver is lost, or enough data has been received() - /// This will only potentially return true after a call to ProcessTCPPacket() or OnLostConnection() - /// \param[out] stringTransmitted The original string transmitted - /// \param[out] hostTransmitted The parameter of the same name passed to TransmitRequest() - /// \param[out] responseReceived The response, if any - /// \param[out] hostReceived The SystemAddress from ProcessTCPPacket() or OnLostConnection() - /// \param[out] contentOffset The offset from the start of responseReceived to the data body. Equivalent to searching for \r\n\r\n in responseReceived. - /// \param[out] userData Whatever you passed to TransmitRequest - /// \return true if there was a response. false if not. - bool GetResponse( RakString &stringTransmitted, RakString &hostTransmitted, RakString &responseReceived, SystemAddress &hostReceived, ptrdiff_t &contentOffset, void **userData ); - bool GetResponse( RakString &stringTransmitted, RakString &hostTransmitted, RakString &responseReceived, SystemAddress &hostReceived, ptrdiff_t &contentOffset ); - - /// \brief Return if any requests are pending - bool IsBusy(void) const; - - /// \brief Return if any requests are waiting to be read by the user - bool HasResponse(void) const; - - struct Request - { - RakString stringToTransmit; - RakString stringReceived; - RakString host; - SystemAddress hostEstimatedAddress; - SystemAddress hostCompletedAddress; - unsigned short port; - bool useSSL; - ptrdiff_t contentOffset; - int contentLength; - int ipVersion; - void *userData; - bool chunked; - size_t thisChunkSize; - size_t bytesReadForThisChunk; - }; - - /// \internal - virtual PluginReceiveResult OnReceive(Packet *packet); - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); - virtual void OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason); - -protected: - - bool IsConnected(SystemAddress sa); - void SendRequest(Request *request); - void RemovePendingRequest(SystemAddress sa); - void SendNextPendingRequest(void); - void SendPendingRequestToConnectedSystem(SystemAddress sa); - - DataStructures::Queue pendingRequests; - DataStructures::List sentRequests; - DataStructures::List completedRequests; - - SimpleMutex pendingRequestsMutex, sentRequestsMutex, completedRequestsMutex; - -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/IncrementalReadInterface.h b/vendors/mafianet/Source/include/mafianet/IncrementalReadInterface.h deleted file mode 100644 index 6df7c7300..000000000 --- a/vendors/mafianet/Source/include/mafianet/IncrementalReadInterface.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __INCREMENTAL_READ_INTERFACE_H -#define __INCREMENTAL_READ_INTERFACE_H - -#include "FileListNodeContext.h" -#include "Export.h" - -namespace MafiaNet -{ - -class RAK_DLL_EXPORT IncrementalReadInterface -{ -public: - IncrementalReadInterface() {} - virtual ~IncrementalReadInterface() {} - - /// Read part of a file into \a destination - /// Return the number of bytes written. Return 0 when file is done. - /// \param[in] filename Filename to read - /// \param[in] startReadBytes What offset from the start of the file to read from - /// \param[in] numBytesToRead How many bytes to read. This is also how many bytes have been allocated to preallocatedDestination - /// \param[out] preallocatedDestination Write your data here - /// \return The number of bytes read, or 0 if none - virtual unsigned int GetFilePart( const char *filename, unsigned int startReadBytes, unsigned int numBytesToRead, void *preallocatedDestination, FileListNodeContext context); -}; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/InternalPacket.h b/vendors/mafianet/Source/include/mafianet/InternalPacket.h deleted file mode 100644 index 53312c502..000000000 --- a/vendors/mafianet/Source/include/mafianet/InternalPacket.h +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief \b [Internal] A class which stores a user message, and all information associated with sending and receiving that message. -/// - -#ifndef __INTERNAL_PACKET_H -#define __INTERNAL_PACKET_H - -#include "PacketPriority.h" -#include "types.h" -#include "memoryoverride.h" -#include "defines.h" -#include "NativeTypes.h" -#include "defines.h" -#if USE_SLIDING_WINDOW_CONGESTION_CONTROL!=1 -#include "CCRakNetUDT.h" -#else -#include "CCRakNetSlidingWindow.h" -#endif - -namespace MafiaNet { - -typedef uint16_t SplitPacketIdType; -typedef uint32_t SplitPacketIndexType; - -/// This is the counter used for holding packet numbers, so we can detect duplicate packets. It should be large enough that if the variables -/// Internally assumed to be 4 bytes, but written as 3 bytes in ReliabilityLayer::WriteToBitStreamFromInternalPacket -typedef uint24_t MessageNumberType; - -/// This is the counter used for holding ordered packet numbers, so we can detect out-of-order packets. It should be large enough that if the variables -/// were to wrap, the newly wrapped values would no longer be in use. Warning: Too large of a value wastes bandwidth! -typedef MessageNumberType OrderingIndexType; - -typedef MafiaNet::TimeUS RemoteSystemTimeType; - -struct InternalPacketFixedSizeTransmissionHeader -{ - /// A unique numerical identifier given to this user message. Used to identify reliable messages on the network - MessageNumberType reliableMessageNumber; - ///The ID used as identification for ordering messages. Also included in sequenced messages - OrderingIndexType orderingIndex; - // Used only with sequenced messages - OrderingIndexType sequencingIndex; - ///What ordering channel this packet is on, if the reliability type uses ordering channels - unsigned char orderingChannel; - ///The ID of the split packet, if we have split packets. This is the maximum number of split messages we can send simultaneously per connection. - SplitPacketIdType splitPacketId; - ///If this is a split packet, the index into the array of subsplit packets - SplitPacketIndexType splitPacketIndex; - ///The size of the array of subsplit packets - SplitPacketIndexType splitPacketCount;; - ///How many bits long the data is - BitSize_t dataBitLength; - ///What type of reliability algorithm to use with this packet - MafiaNet::Reliability reliability; - // Not endian safe - // unsigned char priority : 3; - // unsigned char reliability : 5; -}; - -/// Used in InternalPacket when pointing to sharedDataBlock, rather than allocating itself -struct InternalPacketRefCountedData -{ - unsigned char *sharedDataBlock; - unsigned int refCount; -}; - -/// Holds a user message, and related information -/// Don't use a constructor or destructor, due to the memory pool I am using -struct InternalPacket : public InternalPacketFixedSizeTransmissionHeader -{ - /// Identifies the order in which this number was sent. Used locally - MessageNumberType messageInternalOrder; - /// Has this message number been assigned yet? We don't assign until the message is actually sent. - /// This fixes a bug where pre-determining message numbers and then sending a message on a different channel creates a huge gap. - /// This causes performance problems and causes those messages to timeout. - bool messageNumberAssigned; - /// Was this packet number used this update to track windowing drops or increases? Each packet number is only used once per update. -// bool allowWindowUpdate; - ///When this packet was created - MafiaNet::TimeUS creationTime; - ///The resendNext time to take action on this packet - MafiaNet::TimeUS nextActionTime; - // For debugging - MafiaNet::TimeUS retransmissionTime; - // Size of the header when encoded into a bitstream - BitSize_t headerLength; - /// Buffer is a pointer to the actual data, assuming this packet has data at all - unsigned char *data; - /// How to alloc and delete the data member - enum AllocationScheme - { - /// Data is allocated using rakMalloc. Just free it - NORMAL, - - /// data points to a larger block of data, where the larger block is reference counted. internalPacketRefCountedData is used in this case - REF_COUNTED, - - /// If allocation scheme is STACK, data points to stackData and should not be deallocated - /// This is only used when sending. Received packets are deallocated in RakPeer - STACK - } allocationScheme; - InternalPacketRefCountedData *refCountedData; - /// How many attempts we made at sending this message - unsigned char timesSent; - /// The priority level of this packet - MafiaNet::Priority priority; - /// If the reliability type requires a receipt, then return this number with it - uint32_t sendReceiptSerial; - - // Used for the resend queue - // Linked list implementation so I can remove from the list via a pointer, without finding it in the list - InternalPacket *resendPrev, *resendNext,*unreliablePrev,*unreliableNext; - - unsigned char stackData[128]; -}; - -} // namespace MafiaNet - -#endif - diff --git a/vendors/mafianet/Source/include/mafianet/Itoa.h b/vendors/mafianet/Source/include/mafianet/Itoa.h deleted file mode 100644 index af2d57d10..000000000 --- a/vendors/mafianet/Source/include/mafianet/Itoa.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -#ifndef __RAK_ITOA_H -#define __RAK_ITOA_H - -#ifdef __cplusplus -extern "C" { -#endif - -char* Itoa( int value, char* result, int base ); - -#ifdef __cplusplus -} -#endif - - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/Kbhit.h b/vendors/mafianet/Source/include/mafianet/Kbhit.h deleted file mode 100644 index 38e098ad9..000000000 --- a/vendors/mafianet/Source/include/mafianet/Kbhit.h +++ /dev/null @@ -1,92 +0,0 @@ -/***************************************************************************** -_kbhit() and _getch() for Linux/UNIX -Chris Giese http://my.execpc.com/~geezer -Release date: ? -This code is public domain (no copyright). -You can do whatever you want with it. -*****************************************************************************/ -/* - * Modified work: Copyright (c) 2016-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications in this file are put under the public domain. - * Alternatively you are permitted to license the modifications under the MIT license, if you so desire. The - * license can be found in the license.txt file in the root directory of this source tree. - */ - -#if defined(_WIN32) -#include /* _kbhit(), _getch() */ - -#else -#include /* struct timeval, select() */ -/* ICANON, ECHO, TCSANOW, struct termios */ -#include /* tcgetattr(), tcsetattr() */ -#include /* atexit(), exit() */ -#include /* read() */ -#include /* printf() */ -#include /* memcpy */ - -static struct termios g_old_kbd_mode; -/***************************************************************************** -*****************************************************************************/ -static void cooked(void) -{ - tcsetattr(0, TCSANOW, &g_old_kbd_mode); -} -/***************************************************************************** -*****************************************************************************/ -static void raw(void) -{ - static char init; -/**/ - struct termios new_kbd_mode; - - if(init) - return; -/* put keyboard (stdin, actually) in raw, unbuffered mode */ - tcgetattr(0, &g_old_kbd_mode); - memcpy(&new_kbd_mode, &g_old_kbd_mode, sizeof(struct termios)); - new_kbd_mode.c_lflag &= ~(ICANON /*| ECHO */ ); - new_kbd_mode.c_cc[VTIME] = 0; - new_kbd_mode.c_cc[VMIN] = 1; - tcsetattr(0, TCSANOW, &new_kbd_mode); -/* when we exit, go back to normal, "cooked" mode */ - atexit(cooked); - - init = 1; -} -/***************************************************************************** -*****************************************************************************/ -static int _kbhit(void) -{ - struct timeval timeout; - fd_set read_handles; - int status; - - raw(); -/* check stdin (fd 0) for activity */ - FD_ZERO(&read_handles); - FD_SET(0, &read_handles); - timeout.tv_sec = timeout.tv_usec = 0; - status = select(0 + 1, &read_handles, nullptr, nullptr, &timeout); - if(status < 0) - { - printf("select() failed in _kbhit()\n"); - exit(1); - } - return status; -} -/***************************************************************************** -*****************************************************************************/ -static int _getch(void) -{ - unsigned char temp; - - raw(); -/* stdin = fd 0 */ - if(read(0, &temp, 1) != 1) - return 0; - return temp; -} -#endif - - diff --git a/vendors/mafianet/Source/include/mafianet/LinuxStrings.h b/vendors/mafianet/Source/include/mafianet/LinuxStrings.h deleted file mode 100644 index c0fd72bee..000000000 --- a/vendors/mafianet/Source/include/mafianet/LinuxStrings.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef _GCC_WIN_STRINGS -#define _GCC_WIN_STRINGS - -#if defined(__native_client__) - #ifndef _stricmp - int _stricmp(const char* s1, const char* s2); - #endif - int _strnicmp(const char* s1, const char* s2, size_t n); - char *_strlwr(char * str ); -#else - #if (defined(__GNUC__) || defined(__GCCXML__) || defined(__S3E__) ) && !defined(_WIN32) - #ifndef _stricmp - int _stricmp(const char* s1, const char* s2); - #endif - int _strnicmp(const char* s1, const char* s2, size_t n); - // http://www.jenkinssoftware.com/forum/index.php?topic=5010.msg20920#msg20920 -#ifndef __APPLE__ - char *_strlwr(char * str ); //this won't compile on OSX for some reason -#endif - - - - #endif -#endif - -#endif // _GCC_WIN_STRINGS diff --git a/vendors/mafianet/Source/include/mafianet/LocklessTypes.h b/vendors/mafianet/Source/include/mafianet/LocklessTypes.h deleted file mode 100644 index 89249ef73..000000000 --- a/vendors/mafianet/Source/include/mafianet/LocklessTypes.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __LOCKLESS_TYPES_H -#define __LOCKLESS_TYPES_H - -#include "Export.h" -#include "NativeTypes.h" -#include "WindowsIncludes.h" -#if defined(ANDROID) || defined(__S3E__) || defined(__APPLE__) -// __sync_fetch_and_add not supported apparently -#include "SimpleMutex.h" -#endif - -namespace MafiaNet -{ - -class RAK_DLL_EXPORT LocklessUint32_t -{ -public: - LocklessUint32_t(); - explicit LocklessUint32_t(uint32_t initial); - // Returns variable value after changing it - uint32_t Increment(void); - // Returns variable value after changing it - uint32_t Decrement(void); - uint32_t GetValue(void) const {return value;} - -protected: -#ifdef _WIN32 - volatile LONG value; -#elif defined(ANDROID) || defined(__S3E__) || defined(__APPLE__) - // __sync_fetch_and_add not supported apparently - SimpleMutex mutex; - uint32_t value; -#else - volatile uint32_t value; -#endif -}; - -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/LogCommandParser.h b/vendors/mafianet/Source/include/mafianet/LogCommandParser.h deleted file mode 100644 index 422772d23..000000000 --- a/vendors/mafianet/Source/include/mafianet/LogCommandParser.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Contains LogCommandParser , Used to send logs to connected consoles -/// - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_LogCommandParser==1 - -#ifndef __LOG_COMMAND_PARSER -#define __LOG_COMMAND_PARSER - -#include "CommandParserInterface.h" -#include "Export.h" - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; - -/// \brief Adds the ability to send logging output to a remote console -class RAK_DLL_EXPORT LogCommandParser : public CommandParserInterface -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(LogCommandParser) - - LogCommandParser(); - ~LogCommandParser(); - - /// Given \a command with parameters \a parameterList , do whatever processing you wish. - /// \param[in] command The command to process - /// \param[in] numParameters How many parameters were passed along with the command - /// \param[in] parameterList The list of parameters. parameterList[0] is the first parameter and so on. - /// \param[in] transport The transport interface we can use to write to - /// \param[in] systemAddress The player that sent this command. - /// \param[in] originalString The string that was actually sent over the network, in case you want to do your own parsing - bool OnCommand(const char *command, unsigned numParameters, char **parameterList, TransportInterface *transport, const SystemAddress &systemAddress, const char *originalString); - - /// You are responsible for overriding this function and returning a static string, which will identifier your parser. - /// This should return a static string - /// \return The name that you return. - const char *GetName(void) const; - - /// A callback for when you are expected to send a brief description of your parser to \a systemAddress - /// \param[in] transport The transport interface we can use to write to - /// \param[in] systemAddress The player that requested help. - void SendHelp(TransportInterface *transport, const SystemAddress &systemAddress); - - /// All logs must be associated with a channel. This is a filter so that remote clients only get logs for a system they care about. - // If you call Log with a channel that is unknown, that channel will automatically be added - /// \param[in] channelName A persistent string naming the channel. Don't deallocate this string. - void AddChannel(const char *channelName); - - /// Write a log to a channel. - /// Logs are not buffered, so only remote consoles connected and subscribing at the time you write will get the output. - /// \param[in] format Same as RAKNET_DEBUG_PRINTF() - /// \param[in] ... Same as RAKNET_DEBUG_PRINTF() - void WriteLog(const char *channelName, const char *format, ...); - - /// A callback for when \a systemAddress has connected to us. - /// \param[in] systemAddress The player that has connected. - /// \param[in] transport The transport interface that sent us this information. Can be used to send messages to this or other players. - void OnNewIncomingConnection(const SystemAddress &systemAddress, TransportInterface *transport); - - /// A callback for when \a systemAddress has disconnected, either gracefully or forcefully - /// \param[in] systemAddress The player that has disconnected. - /// \param[in] transport The transport interface that sent us this information. - void OnConnectionLost(const SystemAddress &systemAddress, TransportInterface *transport); - - /// This is called every time transport interface is registered. If you want to save a copy of the TransportInterface pointer - /// This is the place to do it - /// \param[in] transport The new TransportInterface - void OnTransportChange(TransportInterface *transport); -protected: - /// Sends the currently active channels to the user - /// \param[in] systemAddress The player to send to - /// \param[in] transport The transport interface to use to send the channels - void PrintChannels(const SystemAddress &systemAddress, TransportInterface *transport) const; - - /// Unsubscribe a user from a channel (or from all channels) - /// \param[in] systemAddress The player to unsubscribe to - /// \param[in] channelName If 0, then unsubscribe from all channels. Otherwise unsubscribe from the named channel - unsigned Unsubscribe(const SystemAddress &systemAddress, const char *channelName); - - /// Subscribe a user to a channel (or to all channels) - /// \param[in] systemAddress The player to subscribe to - /// \param[in] channelName If 0, then subscribe from all channels. Otherwise subscribe to the named channel - unsigned Subscribe(const SystemAddress &systemAddress, const char *channelName); - - /// Given the name of a channel, return the index into channelNames where it is located - /// \param[in] channelName The name of the channel - unsigned GetChannelIndexFromName(const char *channelName); - - /// One of these structures is created per player - struct SystemAddressAndChannel - { - /// The ID of the player - SystemAddress systemAddress; - - /// Bitwise representations of the channels subscribed to. If bit 0 is set, then we subscribe to channelNames[0] and so on. - unsigned channels; - }; - - /// The list of remote users. Added to when users subscribe, removed when they disconnect or unsubscribe - DataStructures::List remoteUsers; - - /// Names of the channels at each bit, or 0 for an unused channel - const char *channelNames[32]; - - /// This is so I can save the current transport provider, solely so I can use it without having the user pass it to Log - TransportInterface *trans; -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/MTUSize.h b/vendors/mafianet/Source/include/mafianet/MTUSize.h deleted file mode 100644 index b35a8f37d..000000000 --- a/vendors/mafianet/Source/include/mafianet/MTUSize.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -/// \file -/// \brief \b [Internal] Defines the default maximum transfer unit. -/// - - -#ifndef MAXIMUM_MTU_SIZE - -/// \li \em 17914 16 Mbit/Sec Token Ring -/// \li \em 4464 4 Mbits/Sec Token Ring -/// \li \em 4352 FDDI -/// \li \em 1500. The largest Ethernet packet size \b recommended. This is the typical setting for non-PPPoE, non-VPN connections. The default value for NETGEAR routers, adapters and switches. -/// \li \em 1492. The size PPPoE prefers. -/// \li \em 1472. Maximum size to use for pinging. (Bigger packets are fragmented.) -/// \li \em 1468. The size DHCP prefers. -/// \li \em 1460. Usable by AOL if you don't have large email attachments, etc. -/// \li \em 1430. The size VPN and PPTP prefer. -/// \li \em 1400. Maximum size for AOL DSL. -/// \li \em 576. Typical value to connect to dial-up ISPs. -/// The largest value for an UDP datagram - - - -#define MAXIMUM_MTU_SIZE 1492 - - -#define MINIMUM_MTU_SIZE 400 - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/MessageFilter.h b/vendors/mafianet/Source/include/mafianet/MessageFilter.h deleted file mode 100644 index dd670b870..000000000 --- a/vendors/mafianet/Source/include/mafianet/MessageFilter.h +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Message filter plugin. Assigns systems to FilterSets. Each FilterSet limits what messages are allowed. This is a security related plugin. -/// - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_MessageFilter==1 - -#ifndef __MESSAGE_FILTER_PLUGIN_H -#define __MESSAGE_FILTER_PLUGIN_H - -#include "types.h" -#include "PluginInterface2.h" -#include "DS_OrderedList.h" -#include "DS_Hash.h" -#include "Export.h" - -/// MessageIdentifier (ID_*) values shoudln't go higher than this. Change it if you do. -#define MESSAGE_FILTER_MAX_MESSAGE_ID 256 - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; - -/// \internal Has to be public so some of the shittier compilers can use it. -int RAK_DLL_EXPORT MessageFilterStrComp( char *const &key,char *const &data ); - -/// \internal Has to be public so some of the shittier compilers can use it. -struct FilterSet -{ - bool banOnFilterTimeExceed; - bool kickOnDisallowedMessage; - bool banOnDisallowedMessage; - MafiaNet::TimeMS disallowedMessageBanTimeMS; - MafiaNet::TimeMS timeExceedBanTimeMS; - MafiaNet::TimeMS maxMemberTimeMS; - void (*invalidMessageCallback)(RakPeerInterface *peer, AddressOrGUID systemAddress, int filterSetID, void *userData, unsigned char messageID); - void *disallowedCallbackUserData; - void (*timeoutCallback)(RakPeerInterface *peer, AddressOrGUID systemAddress, int filterSetID, void *userData); - void *timeoutUserData; - int filterSetID; - bool allowedIDs[MESSAGE_FILTER_MAX_MESSAGE_ID]; - DataStructures::OrderedList allowedRPC4; -}; - -/// \internal Has to be public so some of the shittier compilers can use it. -int RAK_DLL_EXPORT FilterSetComp( const int &key, FilterSet * const &data ); - -/// \internal Has to be public so some of the shittier compilers can use it. -struct FilteredSystem -{ - FilterSet *filter; - MafiaNet::TimeMS timeEnteredThisSet; -}; - -/// \defgroup MESSAGEFILTER_GROUP MessageFilter -/// \brief Remote incoming packets from unauthorized systems -/// \details -/// \ingroup PLUGINS_GROUP - -/// \brief Assigns systems to FilterSets. Each FilterSet limits what kinds of messages are allowed. -/// \details The MessageFilter plugin is used for security where you limit what systems can send what kind of messages.
-/// You implicitly define FilterSets, and add allowed message IDs to these FilterSets.
-/// You then add systems to these filters, such that those systems are limited to sending what the filters allows.
-/// You can automatically assign systems to a filter.
-/// You can automatically kick and possibly ban users that stay in a filter too long, or send the wrong message.
-/// Each system is a member of either zero or one filters.
-/// Add this plugin before any plugin you wish to filter (most likely just add this plugin before any other). -/// \ingroup MESSAGEFILTER_GROUP -class RAK_DLL_EXPORT MessageFilter : public PluginInterface2 -{ -public: - - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(MessageFilter) - - MessageFilter(); - virtual ~MessageFilter(); - - // -------------------------------------------------------------------------------------------- - // User functions - // -------------------------------------------------------------------------------------------- - - /// Automatically add all new systems to a particular filter - /// Defaults to -1 - /// \param[in] filterSetID Which filter to add new systems to. <0 for do not add. - void SetAutoAddNewConnectionsToFilter(int filterSetID); - - /// Allow a range of message IDs - /// Always allowed by default: ID_CONNECTION_REQUEST_ACCEPTED through ID_DOWNLOAD_PROGRESS - /// Usually you specify a range to make it easier to add new enumerations without having to constantly refer back to this function. - /// \param[in] allow True to allow this message ID, false to disallow. By default, all messageIDs except the noted types are disallowed. This includes messages from other plugins! - /// \param[in] messageIDStart The first ID_* message to allow in the range. Inclusive. - /// \param[in] messageIDEnd The last ID_* message to allow in the range. Inclusive. - /// \param[in] filterSetID A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings. - void SetAllowMessageID(bool allow, int messageIDStart, int messageIDEnd,int filterSetID); - - /// Allow a specific RPC4 call - /// \pre MessageFilter must be attached before RPC4 - /// \param[in] uniqueID Identifier passed to RegisterFunction() - /// \param[in] filterSetID A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings. - void SetAllowRPC4(bool allow, const char* uniqueID, int filterSetID); - - /// What action to take on a disallowed message. You can kick or not. You can add them to the ban list for some time - /// By default no action is taken. The message is simply ignored. - /// param[in] 0 for permanent ban, >0 for ban time in milliseconds. - /// \param[in] kickOnDisallowed kick the system that sent a disallowed message. - /// \param[in] banOnDisallowed ban the system that sent a disallowed message. See \a banTimeMS for the ban duration - /// \param[in] banTimeMS Passed to the milliseconds parameter of RakPeer::AddToBanList. - /// \param[in] filterSetID A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings. - void SetActionOnDisallowedMessage(bool kickOnDisallowed, bool banOnDisallowed, MafiaNet::TimeMS banTimeMS, int filterSetID); - - /// Set a user callback to be called on an invalid message for a particular filterSet - /// \param[in] filterSetID A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings. - /// \param[in] userData A pointer passed with the callback - /// \param[in] invalidMessageCallback A pointer to a C function to be called back with the specified parameters. - void SetDisallowedMessageCallback(int filterSetID, void *userData, void (*invalidMessageCallback)(RakPeerInterface *peer, AddressOrGUID addressOrGUID, int filterSetID, void *userData, unsigned char messageID)); - - /// Set a user callback to be called when a user is disconnected due to SetFilterMaxTime - /// \param[in] filterSetID A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings. - /// \param[in] userData A pointer passed with the callback - /// \param[in] invalidMessageCallback A pointer to a C function to be called back with the specified parameters. - void SetTimeoutCallback(int filterSetID, void *userData, void (*invalidMessageCallback)(RakPeerInterface *peer, AddressOrGUID addressOrGUID, int filterSetID, void *userData)); - - /// Limit how long a connection can stay in a particular filterSetID. After this time, the connection is kicked and possibly banned. - /// By default there is no limit to how long a connection can stay in a particular filter set. - /// \param[in] allowedTimeMS How many milliseconds to allow a connection to stay in this filter set. - /// \param[in] banOnExceed True or false to ban the system, or not, when \a allowedTimeMS is exceeded - /// \param[in] banTimeMS Passed to the milliseconds parameter of RakPeer::AddToBanList. - /// \param[in] filterSetID A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings. - void SetFilterMaxTime(int allowedTimeMS, bool banOnExceed, MafiaNet::TimeMS banTimeMS, int filterSetID); - - /// Get the filterSetID a system is using. Returns -1 for none. - /// \param[in] addressOrGUID The system we are referring to - int GetSystemFilterSet(AddressOrGUID addressOrGUID); - - /// Assign a system to a filter set. - /// Systems are automatically added to filter sets (or not) based on SetAutoAddNewConnectionsToFilter() - /// This function is used to change the filter set a system is using, to add it to a new filter set, or to remove it from all existin filter sets. - /// \param[in] addressOrGUID The system we are referring to - /// \param[in] filterSetID A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings. If -1, the system will be removed from all filter sets. - void SetSystemFilterSet(AddressOrGUID addressOrGUID, int filterSetID); - - /// Returns the number of systems subscribed to a particular filter set - /// Using anything other than -1 for \a filterSetID is slow, so you should store the returned value. - /// \param[in] filterSetID The filter set to limit to. Use -1 for none (just returns the total number of filter systems in that case). - unsigned GetSystemCount(int filterSetID) const; - - /// Returns the total number of filter sets. - /// \return The total number of filter sets. - unsigned GetFilterSetCount(void) const; - - /// Returns the ID of a filter set, by index - /// \param[in] An index between 0 and GetFilterSetCount()-1 inclusive - int GetFilterSetIDByIndex(unsigned index); - - /// Delete a FilterSet. All systems formerly subscribed to this filter are now unrestricted. - /// \param[in] filterSetID The ID of the filter set to delete. - void DeleteFilterSet(int filterSetID); - - // -------------------------------------------------------------------------------------------- - // Packet handling functions - // -------------------------------------------------------------------------------------------- - virtual void Update(void); - virtual PluginReceiveResult OnReceive(Packet *packet); - virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - -protected: - - void Clear(void); - void DeallocateFilterSet(FilterSet *filterSet); - FilterSet* GetFilterSetByID(int filterSetID); - void OnInvalidMessage(FilterSet *filterSet, AddressOrGUID systemAddress, unsigned char messageID); - - DataStructures::OrderedList filterList; - // Change to guid - DataStructures::Hash systemList; - - int autoAddNewConnectionsToFilter; - MafiaNet::Time whenLastTimeoutCheck; -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/MessageIdentifiers.h b/vendors/mafianet/Source/include/mafianet/MessageIdentifiers.h deleted file mode 100644 index 32ac4dd23..000000000 --- a/vendors/mafianet/Source/include/mafianet/MessageIdentifiers.h +++ /dev/null @@ -1,442 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief All the message identifiers used by RakNet. Message identifiers comprise the first byte of any message. -/// - - -#ifndef __MESSAGE_IDENTIFIERS_H -#define __MESSAGE_IDENTIFIERS_H - -#if defined(RAKNET_USE_CUSTOM_PACKET_IDS) -#include "CustomPacketIdentifiers.h" -#else - -enum OutOfBandIdentifiers -{ - ID_NAT_ESTABLISH_UNIDIRECTIONAL, - ID_NAT_ESTABLISH_BIDIRECTIONAL, - ID_NAT_TYPE_DETECT, - ID_ROUTER_2_REPLY_TO_SENDER_PORT, - ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT, - ID_ROUTER_2_MINI_PUNCH_REPLY, - ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE, - ID_XBOX_360_VOICE, - ID_XBOX_360_GET_NETWORK_ROOM, - ID_XBOX_360_RETURN_NETWORK_ROOM, - ID_NAT_PING, - ID_NAT_PONG, -}; - -/// You should not edit the file MessageIdentifiers.h as it is a part of RakNet static library -/// To define your own message id, define an enum following the code example that follows. -/// -/// \code -/// enum { -/// ID_MYPROJECT_MSG_1 = ID_USER_PACKET_ENUM, -/// ID_MYPROJECT_MSG_2, -/// ... -/// }; -/// \endcode -/// -/// \note All these enumerations should be casted to (unsigned char) before writing them to MafiaNet::BitStream -enum DefaultMessageIDTypes -{ - // - // RESERVED TYPES - DO NOT CHANGE THESE - // All types from RakPeer - // - /// These types are never returned to the user. - /// Ping from a connected system. Update timestamps (internal use only) - ID_CONNECTED_PING, - /// Ping from an unconnected system. Reply but do not update timestamps. (internal use only) - ID_UNCONNECTED_PING, - /// Ping from an unconnected system. Only reply if we have open connections. Do not update timestamps. (internal use only) - ID_UNCONNECTED_PING_OPEN_CONNECTIONS, - /// Pong from a connected system. Update timestamps (internal use only) - ID_CONNECTED_PONG, - /// A reliable packet to detect lost connections (internal use only) - ID_DETECT_LOST_CONNECTIONS, - /// C2S: Initial query: Header(1), OfflineMesageID(16), Protocol number(1), Pad(toMTU), sent with no fragment set. - /// If protocol fails on server, returns ID_INCOMPATIBLE_PROTOCOL_VERSION to client - ID_OPEN_CONNECTION_REQUEST_1, - /// S2C: Header(1), OfflineMesageID(16), server GUID(8), HasSecurity(1), Cookie(4, if HasSecurity) - /// , public key (if do security is true), MTU(2). If public key fails on client, returns ID_PUBLIC_KEY_MISMATCH - ID_OPEN_CONNECTION_REPLY_1, - /// C2S: Header(1), OfflineMesageID(16), Cookie(4, if HasSecurity is true on the server), clientSupportsSecurity(1 bit), - /// handshakeChallenge (if has security on both server and client), remoteBindingAddress(6), MTU(2), client GUID(8) - /// Connection slot allocated if cookie is valid, server is not full, GUID and IP not already in use. - ID_OPEN_CONNECTION_REQUEST_2, - /// S2C: Header(1), OfflineMesageID(16), server GUID(8), mtu(2), doSecurity(1 bit), handshakeAnswer (if do security is true) - ID_OPEN_CONNECTION_REPLY_2, - /// C2S: Header(1), GUID(8), Timestamp, HasSecurity(1), Proof(32) - ID_CONNECTION_REQUEST, - /// RakPeer - Remote system requires secure connections, pass a public key to RakPeerInterface::Connect() - ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY, - /// RakPeer - We passed a public key to RakPeerInterface::Connect(), but the other system did not have security turned on - ID_OUR_SYSTEM_REQUIRES_SECURITY, - /// RakPeer - Wrong public key passed to RakPeerInterface::Connect() - ID_PUBLIC_KEY_MISMATCH, - /// RakPeer - Same as ID_ADVERTISE_SYSTEM, but intended for internal use rather than being passed to the user. - /// Second byte indicates type. Used currently for NAT punchthrough for receiver port advertisement. See ID_NAT_ADVERTISE_RECIPIENT_PORT - ID_OUT_OF_BAND_INTERNAL, - /// If RakPeerInterface::Send() is called with one of the MafiaNet::Reliability ...WithAckReceipt values, then on a later call to - /// RakPeerInterface::Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS. The message will be 5 bytes long, - /// and bytes 1-4 inclusive will contain a number in native order containing a number that identifies this message. - /// This number will be returned by RakPeerInterface::Send() or RakPeerInterface::SendList(). ID_SND_RECEIPT_ACKED means that - /// the message arrived - ID_SND_RECEIPT_ACKED, - /// If RakPeerInterface::Send() is called where MafiaNet::Reliability contains MafiaNet::Reliability::UnreliableWithAckReceipt, then on a later call to - /// RakPeerInterface::Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS. The message will be 5 bytes long, - /// and bytes 1-4 inclusive will contain a number in native order containing a number that identifies this message. This number - /// will be returned by RakPeerInterface::Send() or RakPeerInterface::SendList(). ID_SND_RECEIPT_LOSS means that an ack for the - /// message did not arrive (it may or may not have been delivered, probably not). On disconnect or shutdown, you will not get - /// ID_SND_RECEIPT_LOSS for unsent messages, you should consider those messages as all lost. - ID_SND_RECEIPT_LOSS, - - - // - // USER TYPES - DO NOT CHANGE THESE - // - - /// RakPeer - In a client/server environment, our connection request to the server has been accepted. - ID_CONNECTION_REQUEST_ACCEPTED, - /// RakPeer - Sent to the player when a connection request cannot be completed due to inability to connect. - ID_CONNECTION_ATTEMPT_FAILED, - /// RakPeer - Sent a connect request to a system we are currently connected to. - ID_ALREADY_CONNECTED, - /// RakPeer - A remote system has successfully connected. - ID_NEW_INCOMING_CONNECTION, - /// RakPeer - The system we attempted to connect to is not accepting new connections. - ID_NO_FREE_INCOMING_CONNECTIONS, - /// RakPeer - The system specified in Packet::systemAddress has disconnected from us. For the client, this would mean the - /// server has shutdown. - ID_DISCONNECTION_NOTIFICATION, - /// RakPeer - Reliable packets cannot be delivered to the system specified in Packet::systemAddress. The connection to that - /// system has been closed. - ID_CONNECTION_LOST, - /// RakPeer - We are banned from the system we attempted to connect to. - ID_CONNECTION_BANNED, - /// RakPeer - The remote system is using a password and has refused our connection because we did not set the correct password. - ID_INVALID_PASSWORD, - // RAKNET_PROTOCOL_VERSION in version.h does not match on the remote system what we have on our system - // This means the two systems cannot communicate. - // The 2nd byte of the message contains the value of RAKNET_PROTOCOL_VERSION for the remote system - ID_INCOMPATIBLE_PROTOCOL_VERSION, - // Means that this IP address connected recently, and can't connect again as a security measure. See - /// RakPeer::SetLimitIPConnectionFrequency() - ID_IP_RECENTLY_CONNECTED, - /// RakPeer - The sizeof(RakNetTime) bytes following this byte represent a value which is automatically modified by the difference - /// in system times between the sender and the recipient. Requires that you call SetOccasionalPing. - ID_TIMESTAMP, - /// RakPeer - Pong from an unconnected system. First byte is ID_UNCONNECTED_PONG, second sizeof(MafiaNet::TimeMS) bytes is the ping, - /// following bytes is system specific enumeration data. - /// Read using bitstreams - ID_UNCONNECTED_PONG, - /// RakPeer - Inform a remote system of our IP/Port. On the recipient, all data past ID_ADVERTISE_SYSTEM is whatever was passed to - /// the data parameter - ID_ADVERTISE_SYSTEM, - // RakPeer - Downloading a large message. Format is ID_DOWNLOAD_PROGRESS (MessageID), partCount (unsigned int), - /// partTotal (unsigned int), - /// partLength (unsigned int), first part data (length <= MAX_MTU_SIZE). See the three parameters partCount, partTotal - /// and partLength in OnFileProgress in FileListTransferCBInterface.h - ID_DOWNLOAD_PROGRESS, - - /// ConnectionGraph2 plugin - In a client/server environment, a client other than ourselves has disconnected gracefully. - /// Packet::systemAddress is modified to reflect the systemAddress of this client. - ID_REMOTE_DISCONNECTION_NOTIFICATION, - /// ConnectionGraph2 plugin - In a client/server environment, a client other than ourselves has been forcefully dropped. - /// Packet::systemAddress is modified to reflect the systemAddress of this client. - ID_REMOTE_CONNECTION_LOST, - /// ConnectionGraph2 plugin: Bytes 1-4 = count. for (count items) contains {SystemAddress, RakNetGUID, 2 byte ping} - ID_REMOTE_NEW_INCOMING_CONNECTION, - - /// FileListTransfer plugin - Setup data - ID_FILE_LIST_TRANSFER_HEADER, - /// FileListTransfer plugin - A file - ID_FILE_LIST_TRANSFER_FILE, - // Ack for reference push, to send more of the file - ID_FILE_LIST_REFERENCE_PUSH_ACK, - - /// DirectoryDeltaTransfer plugin - Request from a remote system for a download of a directory - ID_DDT_DOWNLOAD_REQUEST, - - /// RakNetTransport plugin - Transport provider message, used for remote console - ID_TRANSPORT_STRING, - - /// ReplicaManager plugin - Create an object - ID_REPLICA_MANAGER_CONSTRUCTION, - /// ReplicaManager plugin - Changed scope of an object - ID_REPLICA_MANAGER_SCOPE_CHANGE, - /// ReplicaManager plugin - Serialized data of an object - ID_REPLICA_MANAGER_SERIALIZE, - /// ReplicaManager plugin - New connection, about to send all world objects - ID_REPLICA_MANAGER_DOWNLOAD_STARTED, - /// ReplicaManager plugin - Finished downloading all serialized objects - ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE, - - /// RakVoice plugin - Open a communication channel - ID_RAKVOICE_OPEN_CHANNEL_REQUEST, - /// RakVoice plugin - Communication channel accepted - ID_RAKVOICE_OPEN_CHANNEL_REPLY, - /// RakVoice plugin - Close a communication channel - ID_RAKVOICE_CLOSE_CHANNEL, - /// RakVoice plugin - Voice data - ID_RAKVOICE_DATA, - - /// Autopatcher plugin - Get a list of files that have changed since a certain date - ID_AUTOPATCHER_GET_CHANGELIST_SINCE_DATE, - /// Autopatcher plugin - A list of files to create - ID_AUTOPATCHER_CREATION_LIST, - /// Autopatcher plugin - A list of files to delete - ID_AUTOPATCHER_DELETION_LIST, - /// Autopatcher plugin - A list of files to get patches for - ID_AUTOPATCHER_GET_PATCH, - /// Autopatcher plugin - A list of patches for a list of files - ID_AUTOPATCHER_PATCH_LIST, - /// Autopatcher plugin - Returned to the user: An error from the database repository for the autopatcher. - ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR, - /// Autopatcher plugin - Returned to the user: The server does not allow downloading unmodified game files. - ID_AUTOPATCHER_CANNOT_DOWNLOAD_ORIGINAL_UNMODIFIED_FILES, - /// Autopatcher plugin - Finished getting all files from the autopatcher - ID_AUTOPATCHER_FINISHED_INTERNAL, - ID_AUTOPATCHER_FINISHED, - /// Autopatcher plugin - Returned to the user: You must restart the application to finish patching. - ID_AUTOPATCHER_RESTART_APPLICATION, - - /// NATPunchthrough plugin: internal - ID_NAT_PUNCHTHROUGH_REQUEST, - /// NATPunchthrough plugin: internal - //ID_NAT_GROUP_PUNCHTHROUGH_REQUEST, - /// NATPunchthrough plugin: internal - //ID_NAT_GROUP_PUNCHTHROUGH_REPLY, - /// NATPunchthrough plugin: internal - ID_NAT_CONNECT_AT_TIME, - /// NATPunchthrough plugin: internal - ID_NAT_GET_MOST_RECENT_PORT, - /// NATPunchthrough plugin: internal - ID_NAT_CLIENT_READY, - /// NATPunchthrough plugin: internal - //ID_NAT_GROUP_PUNCHTHROUGH_FAILURE_NOTIFICATION, - - /// NATPunchthrough plugin: Destination system is not connected to the server. Bytes starting at offset 1 contains the - /// RakNetGUID destination field of NatPunchthroughClient::OpenNAT(). - ID_NAT_TARGET_NOT_CONNECTED, - /// NATPunchthrough plugin: Destination system is not responding to ID_NAT_GET_MOST_RECENT_PORT. Possibly the plugin is not installed. - /// Bytes starting at offset 1 contains the RakNetGUID destination field of NatPunchthroughClient::OpenNAT(). - ID_NAT_TARGET_UNRESPONSIVE, - /// NATPunchthrough plugin: The server lost the connection to the destination system while setting up punchthrough. - /// Possibly the plugin is not installed. Bytes starting at offset 1 contains the RakNetGUID destination - /// field of NatPunchthroughClient::OpenNAT(). - ID_NAT_CONNECTION_TO_TARGET_LOST, - /// NATPunchthrough plugin: This punchthrough is already in progress. Possibly the plugin is not installed. - /// Bytes starting at offset 1 contains the RakNetGUID destination field of NatPunchthroughClient::OpenNAT(). - ID_NAT_ALREADY_IN_PROGRESS, - /// NATPunchthrough plugin: This message is generated on the local system, and does not come from the network. - /// packet::guid contains the destination field of NatPunchthroughClient::OpenNAT(). Byte 1 contains 1 if you are the sender, 0 if not - ID_NAT_PUNCHTHROUGH_FAILED, - /// NATPunchthrough plugin: Punchthrough succeeded. See packet::systemAddress and packet::guid. Byte 1 contains 1 if you are the sender, - /// 0 if not. You can now use RakPeer::Connect() or other calls to communicate with this system. - ID_NAT_PUNCHTHROUGH_SUCCEEDED, - - /// ReadyEvent plugin - Set the ready state for a particular system - /// First 4 bytes after the message contains the id - ID_READY_EVENT_SET, - /// ReadyEvent plugin - Unset the ready state for a particular system - /// First 4 bytes after the message contains the id - ID_READY_EVENT_UNSET, - /// All systems are in state ID_READY_EVENT_SET - /// First 4 bytes after the message contains the id - ID_READY_EVENT_ALL_SET, - /// \internal, do not process in your game - /// ReadyEvent plugin - Request of ready event state - used for pulling data when newly connecting - ID_READY_EVENT_QUERY, - - /// Lobby packets. Second byte indicates type. - ID_LOBBY_GENERAL, - - // RPC3, RPC4 error - ID_RPC_REMOTE_ERROR, - /// Plugin based replacement for RPC system - ID_RPC_PLUGIN, - - /// FileListTransfer transferring large files in chunks that are read only when needed, to save memory - ID_FILE_LIST_REFERENCE_PUSH, - /// Force the ready event to all set - ID_READY_EVENT_FORCE_ALL_SET, - - /// Rooms function - ID_ROOMS_EXECUTE_FUNC, - ID_ROOMS_LOGON_STATUS, - ID_ROOMS_HANDLE_CHANGE, - - /// Lobby2 message - ID_LOBBY2_SEND_MESSAGE, - ID_LOBBY2_SERVER_ERROR, - - /// Informs user of a new host GUID. Packet::Guid contains this new host RakNetGuid. The old host can be read out using BitStream->Read(RakNetGuid) starting on byte 1 - /// This is not returned until connected to a remote system - /// If the oldHost is UNASSIGNED_RAKNET_GUID, then this is the first time the host has been determined - ID_FCM2_NEW_HOST, - /// \internal For FullyConnectedMesh2 plugin - ID_FCM2_REQUEST_FCMGUID, - /// \internal For FullyConnectedMesh2 plugin - ID_FCM2_RESPOND_CONNECTION_COUNT, - /// \internal For FullyConnectedMesh2 plugin - ID_FCM2_INFORM_FCMGUID, - /// \internal For FullyConnectedMesh2 plugin - ID_FCM2_UPDATE_MIN_TOTAL_CONNECTION_COUNT, - /// A remote system (not necessarily the host) called FullyConnectedMesh2::StartVerifiedJoin() with our system as the client - /// Use FullyConnectedMesh2::GetVerifiedJoinRequiredProcessingList() to read systems - /// For each system, attempt NatPunchthroughClient::OpenNAT() and/or RakPeerInterface::Connect() - /// When this has been done for all systems, the remote system will automatically be informed of the results - /// \note Only the designated client gets this message - /// \note You won't get this message if you are already connected to all target systems - /// \note If you fail to connect to a system, this does not automatically mean you will get ID_FCM2_VERIFIED_JOIN_FAILED as that system may have been shutting down from the host too - /// \sa FullyConnectedMesh2::StartVerifiedJoin() - ID_FCM2_VERIFIED_JOIN_START, - /// \internal The client has completed processing for all systems designated in ID_FCM2_VERIFIED_JOIN_START - ID_FCM2_VERIFIED_JOIN_CAPABLE, - /// Client failed to connect to a required systems notified via FullyConnectedMesh2::StartVerifiedJoin() - /// RakPeerInterface::CloseConnection() was automatically called for all systems connected due to ID_FCM2_VERIFIED_JOIN_START - /// Programmer should inform the player via the UI that they cannot join this session, and to choose a different session - /// \note Server normally sends us this message, however if connection to the server was lost, message will be returned locally - /// \note Only the designated client gets this message - ID_FCM2_VERIFIED_JOIN_FAILED, - /// The system that called StartVerifiedJoin() got ID_FCM2_VERIFIED_JOIN_CAPABLE from the client and then called RespondOnVerifiedJoinCapable() with true - /// AddParticipant() has automatically been called for this system - /// Use GetVerifiedJoinAcceptedAdditionalData() to read any additional data passed to RespondOnVerifiedJoinCapable() - /// \note All systems in the mesh get this message - /// \sa RespondOnVerifiedJoinCapable() - ID_FCM2_VERIFIED_JOIN_ACCEPTED, - /// The system that called StartVerifiedJoin() got ID_FCM2_VERIFIED_JOIN_CAPABLE from the client and then called RespondOnVerifiedJoinCapable() with false - /// CloseConnection() has been automatically called for each system connected to since ID_FCM2_VERIFIED_JOIN_START. - /// The connection is NOT automatically closed to the original host that sent StartVerifiedJoin() - /// Use GetVerifiedJoinRejectedAdditionalData() to read any additional data passed to RespondOnVerifiedJoinCapable() - /// \note Only the designated client gets this message - /// \sa RespondOnVerifiedJoinCapable() - ID_FCM2_VERIFIED_JOIN_REJECTED, - - /// UDP proxy messages. Second byte indicates type. - ID_UDP_PROXY_GENERAL, - - /// SQLite3Plugin - execute - ID_SQLite3_EXEC, - /// SQLite3Plugin - Remote database is unknown - ID_SQLite3_UNKNOWN_DB, - /// Events happening with SQLiteClientLoggerPlugin - ID_SQLLITE_LOGGER, - - /// Sent to NatTypeDetectionServer - ID_NAT_TYPE_DETECTION_REQUEST, - /// Sent to NatTypeDetectionClient. Byte 1 contains the type of NAT detected. - ID_NAT_TYPE_DETECTION_RESULT, - - /// Used by the router2 plugin - ID_ROUTER_2_INTERNAL, - /// No path is available or can be established to the remote system - /// Packet::guid contains the endpoint guid that we were trying to reach - ID_ROUTER_2_FORWARDING_NO_PATH, - /// \brief You can now call connect, ping, or other operations to the destination system. - /// - /// Connect as follows: - /// - /// MafiaNet::BitStream bs(packet->data, packet->length, false); - /// bs.IgnoreBytes(sizeof(MessageID)); - /// RakNetGUID endpointGuid; - /// bs.Read(endpointGuid); - /// unsigned short sourceToDestPort; - /// bs.Read(sourceToDestPort); - /// char ipAddressString[32]; - /// packet->systemAddress.ToString(false, ipAddressString); - /// rakPeerInterface->Connect(ipAddressString, sourceToDestPort, 0,0); - ID_ROUTER_2_FORWARDING_ESTABLISHED, - /// The IP address for a forwarded connection has changed - /// Read endpointGuid and port as per ID_ROUTER_2_FORWARDING_ESTABLISHED - ID_ROUTER_2_REROUTED, - - /// \internal Used by the team balancer plugin - ID_TEAM_BALANCER_INTERNAL, - /// Cannot switch to the desired team because it is full. However, if someone on that team leaves, you will - /// get ID_TEAM_BALANCER_TEAM_ASSIGNED later. - /// For TeamBalancer: Byte 1 contains the team you requested to join. Following bytes contain NetworkID of which member - ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, - /// Cannot switch to the desired team because all teams are locked. However, if someone on that team leaves, - /// you will get ID_TEAM_BALANCER_SET_TEAM later. - /// For TeamBalancer: Byte 1 contains the team you requested to join. - ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED, - ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED, - /// Team balancer plugin informing you of your team. Byte 1 contains the team you requested to join. Following bytes contain NetworkID of which member. - ID_TEAM_BALANCER_TEAM_ASSIGNED, - - /// Gamebryo Lightspeed integration - ID_LIGHTSPEED_INTEGRATION, - - /// XBOX integration - ID_XBOX_LOBBY, - - /// The password we used to challenge the other system passed, meaning the other system has called TwoWayAuthentication::AddPassword() with the same password we passed to TwoWayAuthentication::Challenge() - /// You can read the identifier used to challenge as follows: - /// MafiaNet::BitStream bs(packet->data, packet->length, false); bs.IgnoreBytes(sizeof(MafiaNet::MessageID)); MafiaNet::RakString password; bs.Read(password); - ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_SUCCESS, - ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_SUCCESS, - /// A remote system sent us a challenge using TwoWayAuthentication::Challenge(), and the challenge failed. - /// If the other system must pass the challenge to stay connected, you should call RakPeer::CloseConnection() to terminate the connection to the other system. - ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_FAILURE, - /// The other system did not add the password we used to TwoWayAuthentication::AddPassword() - /// You can read the identifier used to challenge as follows: - /// MafiaNet::BitStream bs(packet->data, packet->length, false); bs.IgnoreBytes(sizeof(MessageID)); MafiaNet::RakString password; bs.Read(password); - ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_FAILURE, - /// The other system did not respond within a timeout threshhold. Either the other system is not running the plugin or the other system was blocking on some operation for a long time. - /// You can read the identifier used to challenge as follows: - /// MafiaNet::BitStream bs(packet->data, packet->length, false); bs.IgnoreBytes(sizeof(MessageID)); MafiaNet::RakString password; bs.Read(password); - ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT, - /// \internal - ID_TWO_WAY_AUTHENTICATION_NEGOTIATION, - - /// CloudClient / CloudServer - ID_CLOUD_POST_REQUEST, - ID_CLOUD_RELEASE_REQUEST, - ID_CLOUD_GET_REQUEST, - ID_CLOUD_GET_RESPONSE, - ID_CLOUD_UNSUBSCRIBE_REQUEST, - ID_CLOUD_SERVER_TO_SERVER_COMMAND, - ID_CLOUD_SUBSCRIPTION_NOTIFICATION, - - // LibVoice - ID_LIB_VOICE, - - ID_RELAY_PLUGIN, - ID_NAT_REQUEST_BOUND_ADDRESSES, - ID_NAT_RESPOND_BOUND_ADDRESSES, - ID_FCM2_UPDATE_USER_CONTEXT, - ID_RESERVED_3, - ID_RESERVED_4, - ID_RESERVED_5, - ID_RESERVED_6, - ID_RESERVED_7, - ID_RESERVED_8, - ID_RESERVED_9, - - // For the user to use. Start your first enumeration at this value. - ID_USER_PACKET_ENUM - //------------------------------------------------------------------------------------------------------------- - -}; - -#endif // RAKNET_USE_CUSTOM_PACKET_IDS - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/NatPunchthroughClient.h b/vendors/mafianet/Source/include/mafianet/NatPunchthroughClient.h deleted file mode 100644 index f6c1a2181..000000000 --- a/vendors/mafianet/Source/include/mafianet/NatPunchthroughClient.h +++ /dev/null @@ -1,311 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Contains the NAT-punchthrough plugin for the client. -/// - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_NatPunchthroughClient==1 - -#ifndef __NAT_PUNCHTHROUGH_CLIENT_H -#define __NAT_PUNCHTHROUGH_CLIENT_H - -#include "types.h" -#include "Export.h" -#include "PluginInterface2.h" -#include "PacketPriority.h" -#include "SocketIncludes.h" -#include "DS_List.h" -#include "string.h" -#include "DS_Queue.h" - -// Trendnet TEW-632BRP sometimes starts at port 1024 and increments sequentially. -// Zonnet zsr1134we. Replies go out on the net, but are always absorbed by the remote router?? -// Dlink ebr2310 to Trendnet ok -// Trendnet TEW-652BRP to Trendnet 632BRP OK -// Trendnet TEW-632BRP to Trendnet 632BRP OK -// Buffalo WHR-HP-G54 OK -// Netgear WGR614 ok - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; -struct Packet; -#if _RAKNET_SUPPORT_PacketLogger==1 -class PacketLogger; -#endif - -/// \ingroup NAT_PUNCHTHROUGH_GROUP -struct RAK_DLL_EXPORT PunchthroughConfiguration -{ - /// internal: (15 ms * 2 tries + 30 wait) * 5 ports * 8 players = 2.4 seconds - /// external: (50 ms * 8 sends + 200 wait) * 2 port * 8 players = 9.6 seconds - /// Total: 8 seconds - PunchthroughConfiguration() { - TIME_BETWEEN_PUNCH_ATTEMPTS_INTERNAL=15; - TIME_BETWEEN_PUNCH_ATTEMPTS_EXTERNAL=50; - UDP_SENDS_PER_PORT_INTERNAL=2; - UDP_SENDS_PER_PORT_EXTERNAL=8; - INTERNAL_IP_WAIT_AFTER_ATTEMPTS=30; - MAXIMUM_NUMBER_OF_INTERNAL_IDS_TO_CHECK=5; /// set to 0 to not do lan connects - MAX_PREDICTIVE_PORT_RANGE=2; - EXTERNAL_IP_WAIT_BETWEEN_PORTS=200; - EXTERNAL_IP_WAIT_AFTER_FIRST_TTL=100; - EXTERNAL_IP_WAIT_AFTER_ALL_ATTEMPTS=EXTERNAL_IP_WAIT_BETWEEN_PORTS; - retryOnFailure=false; - } - - /// How much time between each UDP send - MafiaNet::Time TIME_BETWEEN_PUNCH_ATTEMPTS_INTERNAL; - MafiaNet::Time TIME_BETWEEN_PUNCH_ATTEMPTS_EXTERNAL; - - /// How many tries for one port before giving up and going to the next port - int UDP_SENDS_PER_PORT_INTERNAL; - int UDP_SENDS_PER_PORT_EXTERNAL; - - /// After giving up on one internal port, how long to wait before trying the next port - int INTERNAL_IP_WAIT_AFTER_ATTEMPTS; - - /// How many external ports to try past the last known starting port - int MAX_PREDICTIVE_PORT_RANGE; - - /// After sending TTL, how long to wait until first punch attempt - int EXTERNAL_IP_WAIT_AFTER_FIRST_TTL; - - /// After giving up on one external port, how long to wait before trying the next port - int EXTERNAL_IP_WAIT_BETWEEN_PORTS; - - /// After trying all external ports, how long to wait before returning ID_NAT_PUNCHTHROUGH_FAILED - int EXTERNAL_IP_WAIT_AFTER_ALL_ATTEMPTS; - - /// Maximum number of internal IP address to try to connect to. - /// Cannot be greater than MAXIMUM_NUMBER_OF_INTERNAL_IDS - /// Should be high enough to try all internal IP addresses on the majority of computers - int MAXIMUM_NUMBER_OF_INTERNAL_IDS_TO_CHECK; - - /// If the first punchthrough attempt fails, try again - /// This sometimes works because the remote router was looking for an incoming message on a higher numbered port before responding to a lower numbered port from the other system - bool retryOnFailure; -}; - -/// \ingroup NAT_PUNCHTHROUGH_GROUP -struct RAK_DLL_EXPORT NatPunchthroughDebugInterface -{ - NatPunchthroughDebugInterface() {} - virtual ~NatPunchthroughDebugInterface() {} - virtual void OnClientMessage(const char *msg)=0; -}; - -/// \ingroup NAT_PUNCHTHROUGH_GROUP -struct RAK_DLL_EXPORT NatPunchthroughDebugInterface_Printf : public NatPunchthroughDebugInterface -{ - virtual void OnClientMessage(const char *msg); -}; - -#if _RAKNET_SUPPORT_PacketLogger==1 -/// \ingroup NAT_PUNCHTHROUGH_GROUP -struct RAK_DLL_EXPORT NatPunchthroughDebugInterface_PacketLogger : public NatPunchthroughDebugInterface -{ - // Set to non-zero to write to the packetlogger! - PacketLogger *pl; - - NatPunchthroughDebugInterface_PacketLogger() {pl=0;} - ~NatPunchthroughDebugInterface_PacketLogger() {} - virtual void OnClientMessage(const char *msg); -}; -#endif - -/// \brief Client code for NATPunchthrough -/// \details Maintain connection to NatPunchthroughServer to process incoming connection attempts through NatPunchthroughClient
-/// Client will send datagrams to port to estimate next port
-/// Will simultaneously connect with another client once ports are estimated. -/// \sa NatTypeDetectionClient -/// See also http://www.jenkinssoftware.com/raknet/manual/natpunchthrough.html -/// \ingroup NAT_PUNCHTHROUGH_GROUP -class RAK_DLL_EXPORT NatPunchthroughClient : public PluginInterface2 -{ -public: - - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(NatPunchthroughClient) - - NatPunchthroughClient(); - ~NatPunchthroughClient(); - - /// If the instance of RakPeer running NATPunchthroughServer was bound to two IP addresses, then you can call FindRouterPortStride() - /// This will determine the stride that your router uses when assigning ports, if your router is full-cone - /// This function is also called automatically when you call OpenNAT - however, calling it earlier when you are connected to the facilitator will speed up the process - /// \param[in] destination The system to punch. Must already be connected to \a facilitator - void FindRouterPortStride(const SystemAddress &facilitator); - - /// Punchthrough a NAT. Doesn't connect, just tries to setup the routing table - /// \param[in] destination The system to punch. Must already be connected to \a facilitator - /// \param[in] facilitator A system we are already connected to running the NatPunchthroughServer plugin - /// \sa OpenNATGroup() - /// You will get ID_NAT_PUNCHTHROUGH_SUCCEEDED on success - /// You will get ID_NAT_TARGET_NOT_CONNECTED, ID_NAT_TARGET_UNRESPONSIVE, ID_NAT_CONNECTION_TO_TARGET_LOST, ID_NAT_ALREADY_IN_PROGRESS, or ID_NAT_PUNCHTHROUGH_FAILED on failures of various types - /// However, if you lose connection to the facilitator, you may not necessarily get above - bool OpenNAT(RakNetGUID destination, const SystemAddress &facilitator); - - /* - /// \deprecated See FullyConnectedMesh2::StartVerifiedJoin() which is more flexible - /// Same as calling OpenNAT for a list of systems, but reply is delayed until all systems pass. - /// This is useful for peer to peer games where you want to connect to every system in the remote session, not just one particular system - /// \note For cloud computing, all systems in the group must be connected to the same facilitator since we're only specifying one - /// You will get ID_NAT_GROUP_PUNCH_SUCCEEDED on success - /// You will get ID_NAT_TARGET_NOT_CONNECTED, ID_NAT_ALREADY_IN_PROGRESS, or ID_NAT_GROUP_PUNCH_FAILED on failures of various types - /// However, if you lose connection to the facilitator, you may not necessarily get above - bool OpenNATGroup(DataStructures::List destinationSystems, const SystemAddress &facilitator); - */ - - /// Modify the system configuration if desired - /// Don't modify the variables in the structure while punchthrough is in progress - PunchthroughConfiguration* GetPunchthroughConfiguration(void); - - /// Sets a callback to be called with debug messages - /// \param[in] i Pointer to an interface. The pointer is stored, so don't delete it while in progress. Pass 0 to clear. - void SetDebugInterface(NatPunchthroughDebugInterface *i); - - /// Get the port mappings you should pass to UPNP (for miniupnpc-1.6.20120410, for the function UPNP_AddPortMapping) - void GetUPNPPortMappings(char *externalPort, char *internalPort, const SystemAddress &natPunchthroughServerAddress); - - /// \internal For plugin handling - virtual void Update(void); - - /// \internal For plugin handling - virtual PluginReceiveResult OnReceive(Packet *packet); - - /// \internal For plugin handling - virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); - - /// \internal For plugin handling - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - - virtual void OnAttach(void); - virtual void OnDetach(void); - virtual void OnRakPeerShutdown(void); - void Clear(void); - - struct SendPing - { - MafiaNet::Time nextActionTime; - SystemAddress targetAddress; - SystemAddress facilitator; - SystemAddress internalIds[MAXIMUM_NUMBER_OF_INTERNAL_IDS]; - RakNetGUID targetGuid; - bool weAreSender; - int attemptCount; - int retryCount; - int punchingFixedPortAttempts; // only used for TestMode::PUNCHING_FIXED_PORT - uint16_t sessionId; - bool sentTTL; - // Give priority to internal IP addresses because if we are on a LAN, we don't want to try to connect through the internet - enum TestMode - { - TESTING_INTERNAL_IPS, - WAITING_FOR_INTERNAL_IPS_RESPONSE, - //SEND_WITH_TTL, - TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT, - TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT, - TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_1024, - TESTING_EXTERNAL_IPS_1024_TO_1024, - WAITING_AFTER_ALL_ATTEMPTS, - - // The trendnet remaps the remote port to 1024. - // If you continue punching on a different port for the same IP it bans you and the communication becomes unidirectioal - PUNCHING_FIXED_PORT, - - // try port 1024-1028 - } testMode; - } sp; - -protected: - unsigned short mostRecentExternalPort; - //void OnNatGroupPunchthroughRequest(Packet *packet); - void OnFailureNotification(Packet *packet); - //void OnNatGroupPunchthroughReply(Packet *packet); - void OnGetMostRecentPort(Packet *packet); - void OnConnectAtTime(Packet *packet); - unsigned int GetPendingOpenNATIndex(RakNetGUID destination, const SystemAddress &facilitator); - void SendPunchthrough(RakNetGUID destination, const SystemAddress &facilitator); - void QueueOpenNAT(RakNetGUID destination, const SystemAddress &facilitator); - void SendQueuedOpenNAT(void); - void SendTTL(const SystemAddress &sa); - void SendOutOfBand(SystemAddress sa, MessageID oobId); - void OnPunchthroughFailure(void); - void OnReadyForNextPunchthrough(void); - void PushFailure(void); - bool RemoveFromFailureQueue(void); - void PushSuccess(void); - - PunchthroughConfiguration pc; - NatPunchthroughDebugInterface *natPunchthroughDebugInterface; - - // The first time we fail a NAT attempt, we add it to failedAttemptList and try again, since sometimes trying again later fixes the problem - // The second time we fail, we return ID_NAT_PUNCHTHROUGH_FAILED - struct AddrAndGuid - { - SystemAddress addr; - RakNetGUID guid; - }; - DataStructures::List failedAttemptList; - - struct DSTAndFac - { - RakNetGUID destination; - SystemAddress facilitator; - }; - DataStructures::Queue queuedOpenNat; - - void IncrementExternalAttemptCount(MafiaNet::Time time, MafiaNet::Time delta); - unsigned short portStride; - enum - { - HAS_PORT_STRIDE, - UNKNOWN_PORT_STRIDE, - CALCULATING_PORT_STRIDE, - INCAPABLE_PORT_STRIDE - } hasPortStride; - MafiaNet::Time portStrideCalTimeout; - - /* - struct TimeAndGuid - { - MafiaNet::Time time; - RakNetGUID guid; - }; - DataStructures::List groupRequestsInProgress; - - struct GroupPunchRequest - { - SystemAddress facilitator; - DataStructures::List pendingList; - DataStructures::List passedListGuid; - DataStructures::List passedListAddress; - DataStructures::List failedList; - DataStructures::List ignoredList; - }; - DataStructures::List groupPunchRequests; - void UpdateGroupPunchOnNatResult(SystemAddress facilitator, RakNetGUID targetSystem, SystemAddress targetSystemAddress, int result); // 0=failed, 1=success, 2=ignore - */ -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/NatPunchthroughServer.h b/vendors/mafianet/Source/include/mafianet/NatPunchthroughServer.h deleted file mode 100644 index 938e484d3..000000000 --- a/vendors/mafianet/Source/include/mafianet/NatPunchthroughServer.h +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Contains the NAT-punchthrough plugin for the server. -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_NatPunchthroughServer==1 - -#ifndef __NAT_PUNCHTHROUGH_SERVER_H -#define __NAT_PUNCHTHROUGH_SERVER_H - -#include "types.h" -#include "Export.h" -#include "PluginInterface2.h" -#include "PacketPriority.h" -#include "SocketIncludes.h" -#include "DS_OrderedList.h" -#include "string.h" - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; -struct Packet; -#if _RAKNET_SUPPORT_PacketLogger==1 -class PacketLogger; -#endif - -/// \defgroup NAT_PUNCHTHROUGH_GROUP NatPunchthrough -/// \brief Connect systems despite both systems being behind a router -/// \details -/// \ingroup PLUGINS_GROUP - -/// \ingroup NAT_PUNCHTHROUGH_GROUP -struct RAK_DLL_EXPORT NatPunchthroughServerDebugInterface -{ - NatPunchthroughServerDebugInterface() {} - virtual ~NatPunchthroughServerDebugInterface() {} - virtual void OnServerMessage(const char *msg)=0; -}; - -/// \ingroup NAT_PUNCHTHROUGH_GROUP -struct RAK_DLL_EXPORT NatPunchthroughServerDebugInterface_Printf : public NatPunchthroughServerDebugInterface -{ - virtual void OnServerMessage(const char *msg); -}; - -#if _RAKNET_SUPPORT_PacketLogger==1 -/// \ingroup NAT_PUNCHTHROUGH_GROUP -struct RAK_DLL_EXPORT NatPunchthroughServerDebugInterface_PacketLogger : public NatPunchthroughServerDebugInterface -{ - // Set to non-zero to write to the packetlogger! - PacketLogger *pl; - - NatPunchthroughServerDebugInterface_PacketLogger() {pl=0;} - ~NatPunchthroughServerDebugInterface_PacketLogger() {} - virtual void OnServerMessage(const char *msg); -}; -#endif - -/// \brief Server code for NATPunchthrough -/// \details Maintain connection to NatPunchthroughServer to process incoming connection attempts through NatPunchthroughClient
-/// Server maintains two sockets clients can connect to so as to estimate the next port choice
-/// Server tells other client about port estimate, current public port to the server, and a time to start connection attempts -/// \sa NatTypeDetectionClient -/// See also http://www.jenkinssoftware.com/raknet/manual/natpunchthrough.html -/// \ingroup NAT_PUNCHTHROUGH_GROUP -class RAK_DLL_EXPORT NatPunchthroughServer : public PluginInterface2 -{ -public: - - STATIC_FACTORY_DECLARATIONS(NatPunchthroughServer) - - // Constructor - NatPunchthroughServer(); - - // Destructor - virtual ~NatPunchthroughServer(); - - /// Sets a callback to be called with debug messages - /// \param[in] i Pointer to an interface. The pointer is stored, so don't delete it while in progress. Pass 0 to clear. - void SetDebugInterface(NatPunchthroughServerDebugInterface *i); - - /// \internal For plugin handling - virtual void Update(void); - - /// \internal For plugin handling - virtual PluginReceiveResult OnReceive(Packet *packet); - - /// \internal For plugin handling - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); - - // Each connected user has a ready state. Ready means ready for nat punchthrough. - struct User; - struct ConnectionAttempt - { - ConnectionAttempt() {sender=0; recipient=0; startTime=0; attemptPhase=NAT_ATTEMPT_PHASE_NOT_STARTED;} - User *sender, *recipient; - uint16_t sessionId; - MafiaNet::Time startTime; - enum - { - NAT_ATTEMPT_PHASE_NOT_STARTED, - NAT_ATTEMPT_PHASE_GETTING_RECENT_PORTS, - } attemptPhase; - }; - struct User - { - RakNetGUID guid; - SystemAddress systemAddress; - unsigned short mostRecentPort; - bool isReady; - DataStructures::OrderedList groupPunchthroughRequests; - - DataStructures::List connectionAttempts; - bool HasConnectionAttemptToUser(User *user); - void DerefConnectionAttempt(ConnectionAttempt *ca); - void DeleteConnectionAttempt(ConnectionAttempt *ca); - void LogConnectionAttempts(MafiaNet::RakString &rs); - }; - MafiaNet::Time lastUpdate; - static int NatPunchthroughUserComp( const RakNetGUID &key, User * const &data ); -protected: - void OnNATPunchthroughRequest(Packet *packet); - DataStructures::OrderedList users; - - void OnGetMostRecentPort(Packet *packet); - void OnClientReady(Packet *packet); - - void SendTimestamps(void); - void StartPendingPunchthrough(void); - void StartPunchthroughForUser(User*user); - uint16_t sessionId; - NatPunchthroughServerDebugInterface *natPunchthroughServerDebugInterface; - - SystemAddress boundAddresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS]; - unsigned char boundAddressCount; - -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/NatTypeDetectionClient.h b/vendors/mafianet/Source/include/mafianet/NatTypeDetectionClient.h deleted file mode 100644 index a834080fa..000000000 --- a/vendors/mafianet/Source/include/mafianet/NatTypeDetectionClient.h +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Contains the NAT-type detection code for the client -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_NatTypeDetectionClient==1 - -#ifndef __NAT_TYPE_DETECTION_CLIENT_H -#define __NAT_TYPE_DETECTION_CLIENT_H - -#include "types.h" -#include "Export.h" -#include "PluginInterface2.h" -#include "PacketPriority.h" -#include "SocketIncludes.h" -#include "DS_OrderedList.h" -#include "string.h" -#include "NatTypeDetectionCommon.h" - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; -struct Packet; - - /// \brief Client code for NatTypeDetection - /// \details See NatTypeDetectionServer.h for algorithm - /// To use, just connect to the server, and call DetectNAT - /// You will get back ID_NAT_TYPE_DETECTION_RESULT with one of the enumerated values of NATTypeDetectionResult found in NATTypeDetectionCommon.h - /// See also http://www.jenkinssoftware.com/raknet/manual/natpunchthrough.html - /// \sa NatPunchthroughClient - /// \sa NatTypeDetectionServer - /// \ingroup NAT_TYPE_DETECTION_GROUP - class RAK_DLL_EXPORT NatTypeDetectionClient : public PluginInterface2, public RNS2EventHandler - { - public: - - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(NatTypeDetectionClient) - - // Constructor - NatTypeDetectionClient(); - - // Destructor - virtual ~NatTypeDetectionClient(); - - /// Send the message to the server to detect the nat type - /// Server must be running NatTypeDetectionServer - /// We must already be connected to the server - /// \param[in] serverAddress address of the server - void DetectNATType(SystemAddress _serverAddress); - - /// \internal For plugin handling - virtual void Update(void); - - /// \internal For plugin handling - virtual PluginReceiveResult OnReceive(Packet *packet); - - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - virtual void OnRakPeerShutdown(void); - virtual void OnDetach(void); - - virtual void OnRNS2Recv(RNS2RecvStruct *recvStruct); - virtual void DeallocRNS2RecvStruct(RNS2RecvStruct *s, const char *file, unsigned int line); - virtual RNS2RecvStruct *AllocRNS2RecvStruct(const char *file, unsigned int line); - protected: - DataStructures::Queue bufferedPackets; - SimpleMutex bufferedPacketsMutex; - - RakNetSocket2* c2; - //unsigned short c2Port; - void Shutdown(void); - void OnCompletion(NATTypeDetectionResult result); - bool IsInProgress(void) const; - - void OnTestPortRestricted(Packet *packet); - SystemAddress serverAddress; - }; - - -} - - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/NatTypeDetectionCommon.h b/vendors/mafianet/Source/include/mafianet/NatTypeDetectionCommon.h deleted file mode 100644 index d92258f26..000000000 --- a/vendors/mafianet/Source/include/mafianet/NatTypeDetectionCommon.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \defgroup NAT_TYPE_DETECTION_GROUP NatTypeDetection -/// \brief Use a remote server with multiple IP addresses to determine what type of NAT your router is using -/// \details -/// \ingroup PLUGINS_GROUP - -#ifndef __NAT_TYPE_DETECTION_COMMON_H -#define __NAT_TYPE_DETECTION_COMMON_H - -#include "NativeFeatureIncludes.h" - -#if _RAKNET_SUPPORT_NatTypeDetectionServer==1 || _RAKNET_SUPPORT_NatTypeDetectionClient==1 - -#include "SocketIncludes.h" -#include "types.h" -#include "socket2.h" - -namespace MafiaNet -{ - - /// All possible types of NATs (except NAT_TYPE_COUNT, which is an internal value) - enum NATTypeDetectionResult - { - /// Works with anyone - NAT_TYPE_NONE, - /// Accepts any datagrams to a port that has been previously used. Will accept the first datagram from the remote peer. - NAT_TYPE_FULL_CONE, - /// Accepts datagrams to a port as long as the datagram source IP address is a system we have already sent to. Will accept the first datagram if both systems send simultaneously. Otherwise, will accept the first datagram after we have sent one datagram. - NAT_TYPE_ADDRESS_RESTRICTED, - /// Same as address-restricted cone NAT, but we had to send to both the correct remote IP address and correct remote port. The same source address and port to a different destination uses the same mapping. - NAT_TYPE_PORT_RESTRICTED, - /// A different port is chosen for every remote destination. The same source address and port to a different destination uses a different mapping. Since the port will be different, the first external punchthrough attempt will fail. For this to work it requires port-prediction (MAX_PREDICTIVE_PORT_RANGE>1) and that the router chooses ports sequentially. - NAT_TYPE_SYMMETRIC, - /// Hasn't been determined. NATTypeDetectionClient does not use this, but other plugins might - NAT_TYPE_UNKNOWN, - /// In progress. NATTypeDetectionClient does not use this, but other plugins might - NAT_TYPE_DETECTION_IN_PROGRESS, - /// Didn't bother figuring it out, as we support UPNP, so it is equivalent to NAT_TYPE_NONE. NATTypeDetectionClient does not use this, but other plugins might - NAT_TYPE_SUPPORTS_UPNP, - /// \internal Must be last - NAT_TYPE_COUNT - }; - - /// \return Can one system with NATTypeDetectionResult \a type1 connect to \a type2 - bool RAK_DLL_EXPORT CanConnect(NATTypeDetectionResult type1, NATTypeDetectionResult type2); - - /// Return a technical string representin the enumeration - RAK_DLL_EXPORT const char * NATTypeDetectionResultToString(NATTypeDetectionResult type); - - /// Return a friendly string representing the enumeration - /// None and relaxed can connect to anything - /// Moderate can connect to moderate or less - /// Strict can connect to relaxed or less - RAK_DLL_EXPORT const char * NATTypeDetectionResultToStringFriendly(NATTypeDetectionResult type); - - /// \internal - RAK_DLL_EXPORT RakNetSocket2* CreateNonblockingBoundSocket(const char *bindAddr -#ifdef __native_client__ - ,_PP_Instance_ chromeInstance -#endif - , RNS2EventHandler *eventHandler - ); - - /// \internal - //int NatTypeRecvFrom(char *data, RakNetSocket2* socket, SystemAddress &sender, RNS2EventHandler *eventHandler); -} - -#endif // #if _RAKNET_SUPPORT_NatTypeDetectionServer==1 || _RAKNET_SUPPORT_NatTypeDetectionClient==1 - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/NatTypeDetectionServer.h b/vendors/mafianet/Source/include/mafianet/NatTypeDetectionServer.h deleted file mode 100644 index 3b7748037..000000000 --- a/vendors/mafianet/Source/include/mafianet/NatTypeDetectionServer.h +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Contains the NAT-type detection code for the server -/// - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_NatTypeDetectionServer==1 - -#ifndef __NAT_TYPE_DETECTION_SERVER_H -#define __NAT_TYPE_DETECTION_SERVER_H - -#include "types.h" -#include "Export.h" -#include "PluginInterface2.h" -#include "PacketPriority.h" -#include "SocketIncludes.h" -#include "DS_OrderedList.h" -#include "string.h" -#include "NatTypeDetectionCommon.h" - - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; -struct Packet; - -/// \brief Server code for NatTypeDetection -/// \details -/// Sends to a remote system on certain ports and addresses to determine what type of router, if any, that client is behind -/// Requires that the server have 4 external IP addresses -///
    -///
  1. Server has 1 instance of RakNet. Server has four external ip addresses S1 to S4. Five ports are used in total P1 to P5. RakNet is bound to S1P1. Sockets are bound to S1P2, S2P3, S3P4, S4P5 -///
  2. Client with one port using RakNet (C1). Another port not using anything (C2). -///
  3. C1 connects to S1P1 for normal communication. -///
  4. S4P5 sends to C2. If arrived, no NAT. Done. (If didn't arrive, S4P5 potentially banned, do not use again). -///
  5. S2P3 sends to C1 (Different address, different port, to previously used port on client). If received, Full-cone nat. Done. (If didn't arrive, S2P3 potentially banned, do not use again). -///
  6. S1P2 sends to C1 (Same address, different port, to previously used port on client). If received, address-restricted cone nat. Done. -///
  7. Server via RakNet connection tells C1 to send to to S3P4. If address of C1 as seen by S3P4 is the same as the address of C1 as seen by S1P1 (RakNet connection), then port-restricted cone nat. Done -///
  8. Else symmetric nat. Done. -///
-/// See also http://www.jenkinssoftware.com/raknet/manual/natpunchthrough.html -/// \sa NatPunchthroughServer -/// \sa NatTypeDetectionClient -/// \ingroup NAT_TYPE_DETECTION_GROUP -class RAK_DLL_EXPORT NatTypeDetectionServer : public PluginInterface2, public RNS2EventHandler -{ -public: - - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(NatTypeDetectionServer) - - // Constructor - NatTypeDetectionServer(); - - // Destructor - virtual ~NatTypeDetectionServer(); - - /// Start the system, binding to 3 external IPs not already in useS - /// \param[in] nonRakNetIP2 First unused external IP - /// \param[in] nonRakNetIP3 Second unused external IP - /// \param[in] nonRakNetIP4 Third unused external IP - void Startup( - const char *nonRakNetIP2, - const char *nonRakNetIP3, - const char *nonRakNetIP4 -#ifdef __native_client__ - ,_PP_Instance_ chromeInstance -#endif - ); - - // Releases the sockets created in Startup(); - void Shutdown(void); - - /// \internal For plugin handling - virtual void Update(void); - - /// \internal For plugin handling - virtual PluginReceiveResult OnReceive(Packet *packet); - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - - enum NATDetectionState - { - STATE_NONE, - STATE_TESTING_NONE_1, - STATE_TESTING_NONE_2, - STATE_TESTING_FULL_CONE_1, - STATE_TESTING_FULL_CONE_2, - STATE_TESTING_ADDRESS_RESTRICTED_1, - STATE_TESTING_ADDRESS_RESTRICTED_2, - STATE_TESTING_PORT_RESTRICTED_1, - STATE_TESTING_PORT_RESTRICTED_2, - STATE_DONE, - }; - - struct NATDetectionAttempt - { - SystemAddress systemAddress; - NATDetectionState detectionState; - MafiaNet::TimeMS nextStateTime; - MafiaNet::TimeMS timeBetweenAttempts; - unsigned short c2Port; - RakNetGUID guid; - }; - - virtual void OnRNS2Recv(RNS2RecvStruct *recvStruct); - virtual void DeallocRNS2RecvStruct(RNS2RecvStruct *s, const char *file, unsigned int line); - virtual RNS2RecvStruct *AllocRNS2RecvStruct(const char *file, unsigned int line); -protected: - DataStructures::Queue bufferedPackets; - SimpleMutex bufferedPacketsMutex; - - void OnDetectionRequest(Packet *packet); - DataStructures::List natDetectionAttempts; - unsigned int GetDetectionAttemptIndex(const SystemAddress &sa); - unsigned int GetDetectionAttemptIndex(RakNetGUID guid); - - // s1p1 is rakpeer itself - RakNetSocket2 *s1p2,*s2p3,*s3p4,*s4p5; - //unsigned short s1p2Port, s2p3Port, s3p4Port, s4p5Port; - char s3p4Address[64]; -}; -} - - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/NativeFeatureIncludes.h b/vendors/mafianet/Source/include/mafianet/NativeFeatureIncludes.h deleted file mode 100644 index ed965bd51..000000000 --- a/vendors/mafianet/Source/include/mafianet/NativeFeatureIncludes.h +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -// If you want to change these defines, put them in NativeFeatureIncludesOverrides so your changes are not lost when updating RakNet -// The user should not edit this file -#include "NativeFeatureIncludesOverrides.h" - -#ifndef __NATIVE_FEATURE_INCLDUES_H -#define __NATIVE_FEATURE_INCLDUES_H - -// Uncomment below defines, and paste to NativeFeatureIncludesOverrides.h, to exclude plugins that you do not want to build into the static library, or DLL -// These are not all the plugins, only those that are in the core library -// Other plugins are located in DependentExtensions -// #define _RAKNET_SUPPORT_ConnectionGraph2 0 -// #define _RAKNET_SUPPORT_DirectoryDeltaTransfer 0 -// #define _RAKNET_SUPPORT_FileListTransfer 0 -// #define _RAKNET_SUPPORT_FullyConnectedMesh2 0 -// #define _RAKNET_SUPPORT_MessageFilter 0 -// #define _RAKNET_SUPPORT_NatPunchthroughClient 0 -// #define _RAKNET_SUPPORT_NatPunchthroughServer 0 -// #define _RAKNET_SUPPORT_NatTypeDetectionClient 0 -// #define _RAKNET_SUPPORT_NatTypeDetectionServer 0 -// #define _RAKNET_SUPPORT_PacketLogger 0 -// #define _RAKNET_SUPPORT_ReadyEvent 0 -// #define _RAKNET_SUPPORT_ReplicaManager3 0 -// #define _RAKNET_SUPPORT_Router2 0 -// #define _RAKNET_SUPPORT_RPC4Plugin 0 -// #define _RAKNET_SUPPORT_TeamBalancer 0 -// #define _RAKNET_SUPPORT_TeamManager 0 -// #define _RAKNET_SUPPORT_UDPProxyClient 0 -// #define _RAKNET_SUPPORT_UDPProxyCoordinator 0 -// #define _RAKNET_SUPPORT_UDPProxyServer 0 -// #define _RAKNET_SUPPORT_ConsoleServer 0 -// #define _RAKNET_SUPPORT_RakNetTransport 0 -// #define _RAKNET_SUPPORT_TelnetTransport 0 -// #define _RAKNET_SUPPORT_TCPInterface 0 -// #define _RAKNET_SUPPORT_LogCommandParser 0 -// #define _RAKNET_SUPPORT_RakNetCommandParser 0 -// #define _RAKNET_SUPPORT_EmailSender 0 -// #define _RAKNET_SUPPORT_HTTPConnection 0 -// #define _RAKNET_SUPPORT_HTTPConnection2 0 -// #define _RAKNET_SUPPORT_PacketizedTCP 0 -// #define _RAKNET_SUPPORT_TwoWayAuthentication 0 - -// SET DEFAULTS IF UNDEFINED -#ifndef LIBCAT_SECURITY -#define LIBCAT_SECURITY 0 -#endif -#ifndef _RAKNET_SUPPORT_ConnectionGraph2 -#define _RAKNET_SUPPORT_ConnectionGraph2 1 -#endif -#ifndef _RAKNET_SUPPORT_DirectoryDeltaTransfer -#define _RAKNET_SUPPORT_DirectoryDeltaTransfer 1 -#endif -#ifndef _RAKNET_SUPPORT_FileListTransfer -#define _RAKNET_SUPPORT_FileListTransfer 1 -#endif -#ifndef _RAKNET_SUPPORT_FullyConnectedMesh -#define _RAKNET_SUPPORT_FullyConnectedMesh 1 -#endif -#ifndef _RAKNET_SUPPORT_FullyConnectedMesh2 -#define _RAKNET_SUPPORT_FullyConnectedMesh2 1 -#endif -#ifndef _RAKNET_SUPPORT_MessageFilter -#define _RAKNET_SUPPORT_MessageFilter 1 -#endif -#ifndef _RAKNET_SUPPORT_NatPunchthroughClient -#define _RAKNET_SUPPORT_NatPunchthroughClient 1 -#endif -#ifndef _RAKNET_SUPPORT_NatPunchthroughServer -#define _RAKNET_SUPPORT_NatPunchthroughServer 1 -#endif -#ifndef _RAKNET_SUPPORT_NatTypeDetectionClient -#define _RAKNET_SUPPORT_NatTypeDetectionClient 1 -#endif -#ifndef _RAKNET_SUPPORT_NatTypeDetectionServer -#define _RAKNET_SUPPORT_NatTypeDetectionServer 1 -#endif -#ifndef _RAKNET_SUPPORT_PacketLogger -#define _RAKNET_SUPPORT_PacketLogger 1 -#endif -#ifndef _RAKNET_SUPPORT_ReadyEvent -#define _RAKNET_SUPPORT_ReadyEvent 1 -#endif -#ifndef _RAKNET_SUPPORT_ReplicaManager3 -#define _RAKNET_SUPPORT_ReplicaManager3 1 -#endif -#ifndef _RAKNET_SUPPORT_Router2 -#define _RAKNET_SUPPORT_Router2 1 -#endif -#ifndef _RAKNET_SUPPORT_RPC4Plugin -#define _RAKNET_SUPPORT_RPC4Plugin 1 -#endif -#ifndef _RAKNET_SUPPORT_TeamBalancer -#define _RAKNET_SUPPORT_TeamBalancer 1 -#endif -#ifndef _RAKNET_SUPPORT_TeamManager -#define _RAKNET_SUPPORT_TeamManager 1 -#endif -#ifndef _RAKNET_SUPPORT_UDPProxyClient -#define _RAKNET_SUPPORT_UDPProxyClient 1 -#endif -#ifndef _RAKNET_SUPPORT_UDPProxyCoordinator -#define _RAKNET_SUPPORT_UDPProxyCoordinator 1 -#endif -#ifndef _RAKNET_SUPPORT_UDPProxyServer -#define _RAKNET_SUPPORT_UDPProxyServer 1 -#endif -#ifndef _RAKNET_SUPPORT_ConsoleServer -#define _RAKNET_SUPPORT_ConsoleServer 1 -#endif -#ifndef _RAKNET_SUPPORT_RakNetTransport -#define _RAKNET_SUPPORT_RakNetTransport 1 -#endif -#ifndef _RAKNET_SUPPORT_TelnetTransport -#define _RAKNET_SUPPORT_TelnetTransport 1 -#endif -#ifndef _RAKNET_SUPPORT_TCPInterface -#define _RAKNET_SUPPORT_TCPInterface 1 -#endif -#ifndef _RAKNET_SUPPORT_LogCommandParser -#define _RAKNET_SUPPORT_LogCommandParser 1 -#endif -#ifndef _RAKNET_SUPPORT_RakNetCommandParser -#define _RAKNET_SUPPORT_RakNetCommandParser 1 -#endif -#ifndef _RAKNET_SUPPORT_EmailSender -#define _RAKNET_SUPPORT_EmailSender 1 -#endif -#ifndef _RAKNET_SUPPORT_HTTPConnection -#define _RAKNET_SUPPORT_HTTPConnection 1 -#endif -#ifndef _RAKNET_SUPPORT_HTTPConnection2 -#define _RAKNET_SUPPORT_HTTPConnection2 1 -#endif -#ifndef _RAKNET_SUPPORT_PacketizedTCP -#define _RAKNET_SUPPORT_PacketizedTCP 1 -#endif -#ifndef _RAKNET_SUPPORT_TwoWayAuthentication -#define _RAKNET_SUPPORT_TwoWayAuthentication 1 -#endif -#ifndef _RAKNET_SUPPORT_CloudClient -#define _RAKNET_SUPPORT_CloudClient 1 -#endif -#ifndef _RAKNET_SUPPORT_CloudServer -#define _RAKNET_SUPPORT_CloudServer 1 -#endif -#ifndef _RAKNET_SUPPORT_DynDNS -#define _RAKNET_SUPPORT_DynDNS 1 -#endif -#ifndef _RAKNET_SUPPORT_Rackspace -#define _RAKNET_SUPPORT_Rackspace 1 -#endif -#ifndef _RAKNET_SUPPORT_FileOperations -#define _RAKNET_SUPPORT_FileOperations 1 -#endif -#ifndef _RAKNET_SUPPORT_UDPForwarder -#define _RAKNET_SUPPORT_UDPForwarder 1 -#endif -#ifndef _RAKNET_SUPPORT_StatisticsHistory -#define _RAKNET_SUPPORT_StatisticsHistory 1 -#endif -#ifndef _RAKNET_SUPPORT_LibVoice -#define _RAKNET_SUPPORT_LibVoice 0 -#endif -#ifndef _RAKNET_SUPPORT_RelayPlugin -#define _RAKNET_SUPPORT_RelayPlugin 1 -#endif - -// Take care of dependencies -#if _RAKNET_SUPPORT_DirectoryDeltaTransfer==1 -#undef _RAKNET_SUPPORT_FileListTransfer -#define _RAKNET_SUPPORT_FileListTransfer 1 -#endif -#if _RAKNET_SUPPORT_FullyConnectedMesh2==1 -#undef _RAKNET_SUPPORT_ConnectionGraph2 -#define _RAKNET_SUPPORT_ConnectionGraph2 1 -#endif -#if _RAKNET_SUPPORT_TelnetTransport==1 -#undef _RAKNET_SUPPORT_PacketizedTCP -#define _RAKNET_SUPPORT_PacketizedTCP 1 -#endif -#if _RAKNET_SUPPORT_PacketizedTCP==1 || _RAKNET_SUPPORT_EmailSender==1 || _RAKNET_SUPPORT_HTTPConnection==1 -#undef _RAKNET_SUPPORT_TCPInterface -#define _RAKNET_SUPPORT_TCPInterface 1 -#endif - - - - - - - - - - - - -#endif // __NATIVE_FEATURE_INCLDUES_H diff --git a/vendors/mafianet/Source/include/mafianet/NativeFeatureIncludesOverrides.h b/vendors/mafianet/Source/include/mafianet/NativeFeatureIncludesOverrides.h deleted file mode 100644 index d0860857b..000000000 --- a/vendors/mafianet/Source/include/mafianet/NativeFeatureIncludesOverrides.h +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -// USER EDITABLE FILE -// See NativeFeatureIncludes.h - -#ifndef __NATIVE_FEATURE_INCLDUES_OVERRIDES_H -#define __NATIVE_FEATURE_INCLDUES_OVERRIDES_H - -//#define LIBCAT_SECURITY 1 - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/NativeTypes.h b/vendors/mafianet/Source/include/mafianet/NativeTypes.h deleted file mode 100644 index 0b1305e31..000000000 --- a/vendors/mafianet/Source/include/mafianet/NativeTypes.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __NATIVE_TYPES_H -#define __NATIVE_TYPES_H - -#if defined(__GNUC__) || defined(__GCCXML__) || defined(__SNC__) || defined(__S3E__) -#include -#elif !defined(_STDINT_H) && !defined(_SN_STDINT_H) && !defined(_SYS_STDINT_H_) && !defined(_STDINT) && !defined(_MACHTYPES_H_) && !defined(_STDINT_H_) - typedef unsigned char uint8_t; - typedef unsigned short uint16_t; - typedef unsigned __int32 uint32_t; - typedef signed char int8_t; - typedef signed short int16_t; - typedef __int32 int32_t; - typedef unsigned long long int uint64_t; - typedef signed long long int64_t; -#endif - - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/NetworkIDManager.h b/vendors/mafianet/Source/include/mafianet/NetworkIDManager.h deleted file mode 100644 index 24b99bb53..000000000 --- a/vendors/mafianet/Source/include/mafianet/NetworkIDManager.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// - - -#ifndef __NETWORK_ID_MANAGER_H -#define __NETWORK_ID_MANAGER_H - -#include "types.h" -#include "Export.h" -#include "memoryoverride.h" -#include "NetworkIDObject.h" -#include "Rand.h" - -namespace MafiaNet -{ - -/// Increase this value if you plan to have many persistent objects -/// This value must match on all systems -#define NETWORK_ID_MANAGER_HASH_LENGTH 1024 - -/// This class is simply used to generate a unique number for a group of instances of NetworkIDObject -/// An instance of this class is required to use the ObjectID to pointer lookup system -/// You should have one instance of this class per game instance. -/// Call SetIsNetworkIDAuthority before using any functions of this class, or of NetworkIDObject -class RAK_DLL_EXPORT NetworkIDManager -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(NetworkIDManager) - - NetworkIDManager(); - virtual ~NetworkIDManager(void); - - /// Returns the parent object, or this instance if you don't use a parent. - /// Supports NetworkIDObject anywhere in the inheritance hierarchy - /// \pre You must first call SetNetworkIDManager before using this function - template - returnType GET_OBJECT_FROM_ID(NetworkID x) { - NetworkIDObject *nio = GET_BASE_OBJECT_FROM_ID(x); - if (nio==0) - return 0; - if (nio->GetParent()) - return (returnType) nio->GetParent(); - return (returnType) nio; - } - - // Stop tracking all NetworkID objects - void Clear(void); - - /// \internal - NetworkIDObject *GET_BASE_OBJECT_FROM_ID(NetworkID x); - -protected: - /// \internal - void TrackNetworkIDObject(NetworkIDObject *networkIdObject); - void StopTrackingNetworkIDObject(NetworkIDObject *networkIdObject); - - friend class NetworkIDObject; - - NetworkIDObject *networkIdHash[NETWORK_ID_MANAGER_HASH_LENGTH]; - unsigned int NetworkIDToHashIndex(NetworkID networkId); - uint64_t startingOffset; - /// \internal - NetworkID GetNewNetworkID(void); - -}; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/NetworkIDObject.h b/vendors/mafianet/Source/include/mafianet/NetworkIDObject.h deleted file mode 100644 index 9b48f5051..000000000 --- a/vendors/mafianet/Source/include/mafianet/NetworkIDObject.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief A class you can derive from to make it easier to represent every networked object with an integer. This way you can refer to objects over the network. -/// - - -#if !defined(__NETWORK_ID_GENERATOR) -#define __NETWORK_ID_GENERATOR - -#include "types.h" -#include "memoryoverride.h" -#include "Export.h" - -namespace MafiaNet -{ -/// Forward declarations -class NetworkIDManager; - -typedef uint32_t NetworkIDType; - -/// \brief Unique shared ids for each object instance -/// \details A class you can derive from to make it easier to represent every networked object with an integer. This way you can refer to objects over the network. -/// One system should return true for IsNetworkIDAuthority() and the rest should return false. When an object needs to be created, have the the one system create the object. -/// Then have that system send a message to all other systems, and include the value returned from GetNetworkID() in that packet. All other systems should then create the same -/// class of object, and call SetNetworkID() on that class with the NetworkID in the packet. -/// \see the manual for more information on this. -class RAK_DLL_EXPORT NetworkIDObject -{ -public: - // Constructor. NetworkIDs, if IsNetworkIDAuthority() is true, are created here. - NetworkIDObject(); - - // Destructor. Used NetworkIDs, if any, are freed here. - virtual ~NetworkIDObject(); - - /// Sets the manager class from which to request unique network IDs - /// Unlike previous versions, the NetworkIDObject relies on a manager class to provide IDs, rather than using statics, - /// So you can have more than one set of IDs on the same system. - virtual void SetNetworkIDManager( NetworkIDManager *manager); - - /// Returns what was passed to SetNetworkIDManager - virtual NetworkIDManager * GetNetworkIDManager( void ) const; - - /// Returns the NetworkID that you can use to refer to this object over the network. - /// \pre You must first call SetNetworkIDManager before using this function - /// \retval UNASSIGNED_NETWORK_ID UNASSIGNED_NETWORK_ID is returned IsNetworkIDAuthority() is false and SetNetworkID() was not previously called. This is also returned if you call this function in the constructor. - /// \retval 0-65534 Any other value is a valid NetworkID. NetworkIDs start at 0 and go to 65534, wrapping at that point. - virtual NetworkID GetNetworkID( void ); - - /// Sets the NetworkID for this instance. Usually this is called by the clients and determined from the servers. However, if you save multiplayer games you would likely use - /// This on load as well. - virtual void SetNetworkID( NetworkID id ); - - /// Your class does not have to derive from NetworkIDObject, although that is the easiest way to implement this. - /// If you want this to be a member object of another class, rather than inherit, then call SetParent() with a pointer to the parent class instance. - /// GET_OBJECT_FROM_ID will then return the parent rather than this instance. - virtual void SetParent( void *_parent ); - - /// Return what was passed to SetParent - /// \return The value passed to SetParent, or 0 if it was never called. - virtual void* GetParent( void ) const; - -protected: - - /// The network ID of this object - // networkID is assigned when networkIDManager is set. - NetworkID networkID; - NetworkIDManager *networkIDManager; - - /// The parent set by SetParent() - void *parent; - - /// \internal, used by NetworkIDManager - friend class NetworkIDManager; - NetworkIDObject *nextInstanceForNetworkIDManager; -}; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/PS3Includes.h b/vendors/mafianet/Source/include/mafianet/PS3Includes.h deleted file mode 100644 index 8c10bf2a8..000000000 --- a/vendors/mafianet/Source/include/mafianet/PS3Includes.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * This file was taken from RakNet 4.082 without any modifications. - * Please see licenses/RakNet license.txt for the underlying license and related copyright. - */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/vendors/mafianet/Source/include/mafianet/PS4Includes.h b/vendors/mafianet/Source/include/mafianet/PS4Includes.h deleted file mode 100644 index 2fc42cc8c..000000000 --- a/vendors/mafianet/Source/include/mafianet/PS4Includes.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * This file was taken from RakNet 4.082 without any modifications. - * Please see licenses/RakNet license.txt for the underlying license and related copyright. - */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/vendors/mafianet/Source/include/mafianet/PacketConsoleLogger.h b/vendors/mafianet/Source/include/mafianet/PacketConsoleLogger.h deleted file mode 100644 index 11048e4a6..000000000 --- a/vendors/mafianet/Source/include/mafianet/PacketConsoleLogger.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief This will write all incoming and outgoing network messages to the log command parser, which can be accessed through Telnet -/// - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_LogCommandParser==1 && _RAKNET_SUPPORT_PacketLogger==1 - -#ifndef __PACKET_CONSOLE_LOGGER_H_ -#define __PACKET_CONSOLE_LOGGER_H_ - -#include "PacketLogger.h" - -namespace MafiaNet -{ -/// Forward declarations -class LogCommandParser; - -/// \ingroup PACKETLOGGER_GROUP -/// \brief Packetlogger that logs to a remote command console -class RAK_DLL_EXPORT PacketConsoleLogger : public PacketLogger -{ -public: - PacketConsoleLogger(); - // Writes to the command parser used for logging, which is accessed through a secondary communication layer (such as Telnet or RakNet) - See ConsoleServer.h - virtual void SetLogCommandParser(LogCommandParser *lcp); - virtual void WriteLog(const char *str); -protected: - LogCommandParser *logCommandParser; -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/PacketFileLogger.h b/vendors/mafianet/Source/include/mafianet/PacketFileLogger.h deleted file mode 100644 index a7b0e820c..000000000 --- a/vendors/mafianet/Source/include/mafianet/PacketFileLogger.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief This will write all incoming and outgoing network messages to a file -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_PacketLogger==1 - -#ifndef __PACKET_FILE_LOGGER_H_ -#define __PACKET_FILE_LOGGER_H_ - -#include "PacketLogger.h" -#include - -namespace MafiaNet -{ - -/// \ingroup PACKETLOGGER_GROUP -/// \brief Packetlogger that outputs to a file -class RAK_DLL_EXPORT PacketFileLogger : public PacketLogger -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(PacketFileLogger) - - PacketFileLogger(); - virtual ~PacketFileLogger(); - void StartLog(const char *filenamePrefix); - virtual void WriteLog(const char *str); -protected: - FILE *packetLogFile; -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/PacketLogger.h b/vendors/mafianet/Source/include/mafianet/PacketLogger.h deleted file mode 100644 index 638259038..000000000 --- a/vendors/mafianet/Source/include/mafianet/PacketLogger.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief This will write all incoming and outgoing network messages to the local console screen. See derived functions for other outputs -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_PacketLogger==1 - -#ifndef __PACKET_LOGGER_H -#define __PACKET_LOGGER_H - -#include "types.h" -#include "PluginInterface2.h" -#include "Export.h" - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; - -/// \defgroup PACKETLOGGER_GROUP PacketLogger -/// \brief Print out incoming messages to a target destination -/// \details -/// \ingroup PLUGINS_GROUP - -/// \brief Writes incoming and outgoing messages to the screen. -/// This will write all incoming and outgoing messages to the console window, or to a file if you override it and give it this functionality. -/// \ingroup PACKETLOGGER_GROUP -class RAK_DLL_EXPORT PacketLogger : public PluginInterface2 -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(PacketLogger) - - PacketLogger(); - virtual ~PacketLogger(); - - // Translate the supplied parameters into an output line - overloaded version that takes a MessageIdentifier - // and translates it into a string (numeric or textual representation based on printId); this calls the - // second version which takes a const char* argument for the messageIdentifier - virtual void FormatLine(char* into, size_t intoLength, const char* dir, const char* type, unsigned int reliableMessageNumber, unsigned int frame - , unsigned char id, const BitSize_t bitLen, unsigned long long time, const SystemAddress& local, const SystemAddress& remote, - unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex); - virtual void FormatLine(char* into, const char* dir, const char* type, unsigned int reliableMessageNumber, unsigned int frame - , unsigned char id, const BitSize_t bitLen, unsigned long long time, const SystemAddress& local, const SystemAddress& remote, - unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex); - virtual void FormatLine(char* into, size_t intoLength, const char* dir, const char* type, unsigned int reliableMessageNumber, unsigned int frame - , const char* idToPrint, const BitSize_t bitLen, unsigned long long time, const SystemAddress& local, const SystemAddress& remote, - unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex); - virtual void FormatLine(char* into, const char* dir, const char* type, unsigned int reliableMessageNumber, unsigned int frame - , const char* idToPrint, const BitSize_t bitLen, unsigned long long time, const SystemAddress& local, const SystemAddress& remote, - unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex); - - /// Events on low level sends and receives. These functions may be called from different threads at the same time. - virtual void OnDirectSocketSend(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress); - virtual void OnDirectSocketReceive(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress); - virtual void OnReliabilityLayerNotification(const char *errorMessage, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress, bool isError); - virtual void OnInternalPacket(InternalPacket *internalPacket, unsigned frameNumber, SystemAddress remoteSystemAddress, MafiaNet::TimeMS time, int isSend); - virtual void OnAck(unsigned int messageNumber, SystemAddress remoteSystemAddress, MafiaNet::TimeMS time); - virtual void OnPushBackPacket(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress); - - /// Logs out a header for all the data - virtual void LogHeader(void); - - /// Override this to log strings to wherever. Log should be threadsafe - virtual void WriteLog(const char *str); - - // Write informational messages - virtual void WriteMiscellaneous(const char *type, const char *msg); - - - // Set to true to print ID_* instead of numbers - virtual void SetPrintID(bool print); - // Print or hide acks (clears up the screen not to print them but is worse for debugging) - virtual void SetPrintAcks(bool print); - - /// Prepend this string to output logs. - virtual void SetPrefix(const char *_prefix); - - /// Append this string to output logs. (newline is useful here) - virtual void SetSuffix(const char *_suffix); - static const char* BaseIDTOString(unsigned char Id); - - /// Log the direct sends and receives or not. Default true - void SetLogDirectMessages(bool send); -protected: - - virtual bool UsesReliabilityLayer(void) const {return true;} - const char* IDTOString(unsigned char Id); - virtual void AddToLog(const char *str); - // Users should override this - virtual const char* UserIDTOString(unsigned char Id); - void GetLocalTime(char buffer[128]); - bool logDirectMessages; - - bool printId, printAcks; - char prefix[256]; - char suffix[256]; -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/PacketOutputWindowLogger.h b/vendors/mafianet/Source/include/mafianet/PacketOutputWindowLogger.h deleted file mode 100644 index f36082090..000000000 --- a/vendors/mafianet/Source/include/mafianet/PacketOutputWindowLogger.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief This will write all incoming and outgoing network messages to a file -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_PacketLogger==1 - -#ifndef __PACKET_OUTPUT_WINDOW_LOGGER_H_ -#define __PACKET_OUTPUT_WINDOW_LOGGER_H_ - -#include "PacketLogger.h" - -namespace MafiaNet -{ - -/// \ingroup PACKETLOGGER_GROUP -/// \brief Packetlogger that outputs to the output window in the debugger. Windows only. -class RAK_DLL_EXPORT PacketOutputWindowLogger : public PacketLogger -{ -public: - PacketOutputWindowLogger(); - virtual ~PacketOutputWindowLogger(); - virtual void WriteLog(const char *str); -protected: -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/PacketPool.h b/vendors/mafianet/Source/include/mafianet/PacketPool.h deleted file mode 100644 index 23a19793b..000000000 --- a/vendors/mafianet/Source/include/mafianet/PacketPool.h +++ /dev/null @@ -1,6 +0,0 @@ -/* - * This file was taken from RakNet 4.082 without any modifications. - * Please see licenses/RakNet license.txt for the underlying license and related copyright. - */ - -// REMOVEME diff --git a/vendors/mafianet/Source/include/mafianet/PacketPriority.h b/vendors/mafianet/Source/include/mafianet/PacketPriority.h deleted file mode 100644 index 2f54bd52a..000000000 --- a/vendors/mafianet/Source/include/mafianet/PacketPriority.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -/// \file -/// \brief Scoped enumerations for packet priority and reliability. -/// -/// These were historically two unscoped C enums (PacketPriority / -/// PacketReliability) that leaked their enumerators into the global namespace. -/// They are now scoped MafiaNet::Priority / MafiaNet::Reliability enum classes. -/// The enumerator order is preserved, so the underlying integer values are -/// unchanged and remain wire-compatible (reliability is written as a 3-bit -/// field by the reliability layer). - - - -#ifndef __PACKET_PRIORITY_H -#define __PACKET_PRIORITY_H - -namespace MafiaNet -{ - -/// These enumerations are used to describe when packets are delivered. -enum class Priority -{ - /// The highest possible priority. These message trigger sends immediately, and are generally not buffered or aggregated into a single datagram. - Immediate, - - /// For every 2 Immediate messages, 1 High will be sent. - /// Messages at this priority and lower are buffered to be sent in groups at 10 millisecond intervals to reduce UDP overhead and better measure congestion control. - High, - - /// For every 2 High messages, 1 Medium will be sent. - /// Messages at this priority and lower are buffered to be sent in groups at 10 millisecond intervals to reduce UDP overhead and better measure congestion control. - Medium, - - /// For every 2 Medium messages, 1 Low will be sent. - /// Messages at this priority and lower are buffered to be sent in groups at 10 millisecond intervals to reduce UDP overhead and better measure congestion control. - Low -}; - -/// Number of distinct priority levels. (Formerly the NUMBER_OF_PRIORITIES sentinel.) -constexpr unsigned int NUMBER_OF_PRIORITIES = 4; - -/// These enumerations are used to describe how packets are delivered. -/// \note Note to self: I write this with 3 bits in the stream. If I add more remember to change that -/// \note In ReliabilityLayer::WriteToBitStreamFromInternalPacket I assume there are 5 major types -/// \note Do not reorder, I check on >= UnreliableWithAckReceipt -enum class Reliability -{ - /// Same as regular UDP, except that it will also discard duplicate datagrams. RakNet adds (6 to 17) + 21 bits of overhead, 16 of which is used to detect duplicate packets and 6 to 17 of which is used for message length. - Unreliable, - - /// Regular UDP with a sequence counter. Out of order messages will be discarded. - /// Sequenced and ordered messages sent on the same channel will arrive in the order sent. - UnreliableSequenced, - - /// The message is sent reliably, but not necessarily in any order. Same overhead as Unreliable. - Reliable, - - /// This message is reliable and will arrive in the order you sent it. Messages will be delayed while waiting for out of order messages. Same overhead as UnreliableSequenced. - /// Sequenced and ordered messages sent on the same channel will arrive in the order sent. - ReliableOrdered, - - /// This message is reliable and will arrive in the sequence you sent it. Out or order messages will be dropped. Same overhead as UnreliableSequenced. - /// Sequenced and ordered messages sent on the same channel will arrive in the order sent. - ReliableSequenced, - - /// Same as Unreliable, however the user will get either ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS based on the result of sending this message when calling RakPeerInterface::Receive(). Bytes 1-4 will contain the number returned from the Send() function. On disconnect or shutdown, all messages not previously acked should be considered lost. - UnreliableWithAckReceipt, - - // 05/04/10 You can't have sequenced and ack receipts, because you don't know if the other system discarded the message, meaning you don't know if the message was processed - // UnreliableSequencedWithAckReceipt, - - /// Same as Reliable. The user will also get ID_SND_RECEIPT_ACKED after the message is delivered when calling RakPeerInterface::Receive(). ID_SND_RECEIPT_ACKED is returned when the message arrives, not necessarily the order when it was sent. Bytes 1-4 will contain the number returned from the Send() function. On disconnect or shutdown, all messages not previously acked should be considered lost. This does not return ID_SND_RECEIPT_LOSS. - ReliableWithAckReceipt, - - /// Same as ReliableOrdered. The user will also get ID_SND_RECEIPT_ACKED after the message is delivered when calling RakPeerInterface::Receive(). ID_SND_RECEIPT_ACKED is returned when the message arrives, not necessarily the order when it was sent. Bytes 1-4 will contain the number returned from the Send() function. On disconnect or shutdown, all messages not previously acked should be considered lost. This does not return ID_SND_RECEIPT_LOSS. - ReliableOrderedWithAckReceipt - - // 05/04/10 You can't have sequenced and ack receipts, because you don't know if the other system discarded the message, meaning you don't know if the message was processed - // ReliableSequencedWithAckReceipt, -}; - -/// Number of distinct reliability types. (Formerly the NUMBER_OF_RELIABILITIES sentinel.) -constexpr unsigned int NUMBER_OF_RELIABILITIES = 8; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/PacketizedTCP.h b/vendors/mafianet/Source/include/mafianet/PacketizedTCP.h deleted file mode 100644 index f069a84f6..000000000 --- a/vendors/mafianet/Source/include/mafianet/PacketizedTCP.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief A simple TCP based server allowing sends and receives. Can be connected by any TCP client, including telnet. -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 - -#ifndef __PACKETIZED_TCP -#define __PACKETIZED_TCP - -#include "TCPInterface.h" -#include "DS_ByteQueue.h" -#include "DS_Map.h" - -namespace MafiaNet -{ - -class RAK_DLL_EXPORT PacketizedTCP : public TCPInterface -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(PacketizedTCP) - - PacketizedTCP(); - virtual ~PacketizedTCP(); - - /// Stops the TCP server - void Stop(void); - - /// Sends a byte stream - void Send( const char *data, unsigned length, const SystemAddress &systemAddress, bool broadcast ); - - // Sends a concatenated list of byte streams - bool SendList( const char **data, const unsigned int *lengths, const int numParameters, const SystemAddress &systemAddress, bool broadcast ); - - /// Returns data received - Packet* Receive( void ); - - /// Disconnects a player/address - void CloseConnection( SystemAddress systemAddress ); - - /// Has a previous call to connect succeeded? - /// \return UNASSIGNED_SYSTEM_ADDRESS = no. Anything else means yes. - SystemAddress HasCompletedConnectionAttempt(void); - - /// Has a previous call to connect failed? - /// \return UNASSIGNED_SYSTEM_ADDRESS = no. Anything else means yes. - SystemAddress HasFailedConnectionAttempt(void); - - /// Queued events of new incoming connections - SystemAddress HasNewIncomingConnection(void); - - /// Queued events of lost connections - SystemAddress HasLostConnection(void); - -protected: - void ClearAllConnections(void); - void RemoveFromConnectionList(const SystemAddress &sa); - void AddToConnectionList(const SystemAddress &sa); - void PushNotificationsToQueues(void); - Packet *ReturnOutgoingPacket(void); - - // A single TCP recieve may generate multiple split packets. They are stored in the waitingPackets list until Receive is called - DataStructures::Queue waitingPackets; - DataStructures::Map connections; - - // Mirrors single producer / consumer, but processes them in Receive() before returning to user - DataStructures::Queue _newIncomingConnections, _lostConnections, _failedConnectionAttempts, _completedConnectionAttempts; -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/PeerHandle.h b/vendors/mafianet/Source/include/mafianet/PeerHandle.h deleted file mode 100644 index daf2cc76c..000000000 --- a/vendors/mafianet/Source/include/mafianet/PeerHandle.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2026, MafiaHub - * - * This source code is licensed under the MIT-style license found in the - * license.txt file in the root directory of this source tree. - */ - -/// \file PeerHandle.h -/// \brief RAII handles for the two core MafiaNet resources. -/// -/// \ref MafiaNet::Peer owns a RakPeerInterface instance (GetInstance/DestroyInstance); -/// \ref MafiaNet::PacketPtr owns a Packet received from it (Receive/DeallocatePacket). -/// Both are movable, non-copyable and exception-safe. This is purely additive — -/// the raw factory/Receive API remains available and unchanged. - -#pragma once - -#include "mafianet/peerinterface.h" // RakPeerInterface, Receive, DeallocatePacket, GetInstance, DestroyInstance -#include "mafianet/types.h" // Packet -#include "mafianet/Export.h" // RAK_DLL_EXPORT - -namespace MafiaNet { - -/// \brief Owning handle for a Packet returned by RakPeerInterface::Receive(). -/// Calls DeallocatePacket() in its destructor. Movable, non-copyable. -class RAK_DLL_EXPORT PacketPtr { -public: - /// Takes ownership of \a p, which must have been produced by \a owner. - PacketPtr(RakPeerInterface* owner, Packet* p) : owner_(owner), p_(p) {} - ~PacketPtr(); - - PacketPtr(PacketPtr&& o) noexcept; - PacketPtr& operator=(PacketPtr&& o) noexcept; - PacketPtr(const PacketPtr&) = delete; - PacketPtr& operator=(const PacketPtr&) = delete; - - Packet* operator->() const { return p_; } - Packet& operator*() const { return *p_; } - Packet* get() const { return p_; } - explicit operator bool() const { return p_ != nullptr; } - - /// Message identifier, accounting for an ID_TIMESTAMP prefix. - /// Returns 255 when the packet is null or empty. - unsigned char id() const; - -private: - RakPeerInterface* owner_; - Packet* p_; -}; - -/// \brief Owning handle for a RakPeerInterface instance. -/// Calls DestroyInstance() in its destructor. Movable, non-copyable. -class RAK_DLL_EXPORT Peer { -public: - Peer() : raw_(RakPeerInterface::GetInstance()) {} - ~Peer(); - - Peer(Peer&& o) noexcept; - Peer& operator=(Peer&& o) noexcept; - Peer(const Peer&) = delete; - Peer& operator=(const Peer&) = delete; - - RakPeerInterface* operator->() const { return raw_; } - RakPeerInterface* get() const { return raw_; } - /// False only for a moved-from (and thus empty) handle. - explicit operator bool() const { return raw_ != nullptr; } - - /// Receive the next queued packet wrapped in a PacketPtr (may be empty). - PacketPtr receive(); - -private: - RakPeerInterface* raw_; -}; - -} // namespace MafiaNet diff --git a/vendors/mafianet/Source/include/mafianet/PluginInterface2.h b/vendors/mafianet/Source/include/mafianet/PluginInterface2.h deleted file mode 100644 index e07337556..000000000 --- a/vendors/mafianet/Source/include/mafianet/PluginInterface2.h +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief \b RakNet's plugin functionality system, version 2. You can derive from this to create your own plugins. -/// - - -#ifndef __PLUGIN_INTERFACE_2_H -#define __PLUGIN_INTERFACE_2_H - -#include "NativeFeatureIncludes.h" -#include "types.h" -#include "Export.h" -#include "PacketPriority.h" - -namespace MafiaNet { - -/// Forward declarations -class RakPeerInterface; -class TCPInterface; -struct Packet; -struct InternalPacket; - -/// \defgroup PLUGIN_INTERFACE_GROUP PluginInterface2 - -/// \defgroup PLUGINS_GROUP Plugins -/// \ingroup PLUGIN_INTERFACE_GROUP - -/// For each message that arrives on an instance of RakPeer, the plugins get an opportunity to process them first. This enumeration represents what to do with the message -/// \ingroup PLUGIN_INTERFACE_GROUP -enum PluginReceiveResult -{ - /// The plugin used this message and it shouldn't be given to the user. - RR_STOP_PROCESSING_AND_DEALLOCATE=0, - - /// This message will be processed by other plugins, and at last by the user. - RR_CONTINUE_PROCESSING, - - /// The plugin is going to hold on to this message. Do not deallocate it but do not pass it to other plugins either. - RR_STOP_PROCESSING -}; - -/// Reasons why a connection was lost -/// \ingroup PLUGIN_INTERFACE_GROUP -enum PI2_LostConnectionReason -{ - /// Called RakPeer::CloseConnection() - LCR_CLOSED_BY_USER, - - /// Got ID_DISCONNECTION_NOTIFICATION - LCR_DISCONNECTION_NOTIFICATION, - - /// GOT ID_CONNECTION_LOST - LCR_CONNECTION_LOST -}; - -/// Returns why a connection attempt failed -/// \ingroup PLUGIN_INTERFACE_GROUP -enum PI2_FailedConnectionAttemptReason -{ - FCAR_CONNECTION_ATTEMPT_FAILED, - FCAR_ALREADY_CONNECTED, - FCAR_NO_FREE_INCOMING_CONNECTIONS, - FCAR_SECURITY_PUBLIC_KEY_MISMATCH, - FCAR_CONNECTION_BANNED, - FCAR_INVALID_PASSWORD, - FCAR_INCOMPATIBLE_PROTOCOL, - FCAR_IP_RECENTLY_CONNECTED, - FCAR_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY, - FCAR_OUR_SYSTEM_REQUIRES_SECURITY, - FCAR_PUBLIC_KEY_MISMATCH -}; - -/// RakNet's plugin system. Each plugin processes the following events: -/// -Connection attempts -/// -The result of connection attempts -/// -Each incoming message -/// -Updates over time, when RakPeer::Receive() is called -/// -/// \ingroup PLUGIN_INTERFACE_GROUP -class RAK_DLL_EXPORT PluginInterface2 -{ -public: - PluginInterface2(); - virtual ~PluginInterface2(); - - /// Called when the interface is attached - virtual void OnAttach(void) {} - - /// Called when the interface is detached - virtual void OnDetach(void) {} - - /// Update is called every time a packet is checked for . - virtual void Update(void) {} - - /// OnReceive is called for every packet. - /// \param[in] packet the packet that is being returned to the user - /// \return True to allow the game and other plugins to get this message, false to absorb it - virtual PluginReceiveResult OnReceive(Packet *packet) {(void) packet; return RR_CONTINUE_PROCESSING;} - - /// Called when RakPeer is initialized - virtual void OnRakPeerStartup(void) {} - - /// Called when RakPeer is shutdown - virtual void OnRakPeerShutdown(void) {} - - /// Called when a connection is dropped because the user called RakPeer::CloseConnection() for a particular system - /// \param[in] systemAddress The system whose connection was closed - /// \param[in] rakNetGuid The guid of the specified system - /// \param[in] lostConnectionReason How the connection was closed: manually, connection lost, or notification of disconnection - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ){(void) systemAddress; (void) rakNetGUID; (void) lostConnectionReason;} - - /// Called when we got a new connection - /// \param[in] systemAddress Address of the new connection - /// \param[in] rakNetGuid The guid of the specified system - /// \param[in] isIncoming If true, this is ID_NEW_INCOMING_CONNECTION, or the equivalent - virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) {(void) systemAddress; (void) rakNetGUID; (void) isIncoming;} - - /// Called when a connection attempt fails - /// \param[in] packet Packet to be returned to the user - /// \param[in] failedConnectionReason Why the connection failed - virtual void OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason) {(void) packet; (void) failedConnectionAttemptReason;} - - /// Queried when attached to RakPeer - /// Return true to call OnDirectSocketSend(), OnDirectSocketReceive(), OnReliabilityLayerNotification(), OnInternalPacket(), and OnAck() - /// If true, then you cannot call RakPeer::AttachPlugin() or RakPeer::DetachPlugin() for this plugin, while RakPeer is active - virtual bool UsesReliabilityLayer(void) const {return false;} - - /// Called on a send to the socket, per datagram, that does not go through the reliability layer - /// \pre To be called, UsesReliabilityLayer() must return true - /// \param[in] data The data being sent - /// \param[in] bitsUsed How many bits long \a data is - /// \param[in] remoteSystemAddress Which system this message is being sent to - virtual void OnDirectSocketSend(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) {(void) data; (void) bitsUsed; (void) remoteSystemAddress;} - - /// Called on a receive from the socket, per datagram, that does not go through the reliability layer - /// \pre To be called, UsesReliabilityLayer() must return true - /// \param[in] data The data being sent - /// \param[in] bitsUsed How many bits long \a data is - /// \param[in] remoteSystemAddress Which system this message is being sent to - virtual void OnDirectSocketReceive(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) {(void) data; (void) bitsUsed; (void) remoteSystemAddress;} - - /// Called when the reliability layer rejects a send or receive - /// \pre To be called, UsesReliabilityLayer() must return true - /// \param[in] bitsUsed How many bits long \a data is - /// \param[in] remoteSystemAddress Which system this message is being sent to - virtual void OnReliabilityLayerNotification(const char *errorMessage, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress, bool isError) {(void) errorMessage; (void) bitsUsed; (void) remoteSystemAddress; (void) isError;} - - /// Called on a send or receive of a message within the reliability layer - /// \pre To be called, UsesReliabilityLayer() must return true - /// \param[in] internalPacket The user message, along with all send data. - /// \param[in] frameNumber The number of frames sent or received so far for this player depending on \a isSend . Indicates the frame of this user message. - /// \param[in] remoteSystemAddress The player we sent or got this packet from - /// \param[in] time The current time as returned by MafiaNet::GetTimeMS() - /// \param[in] isSend Is this callback representing a send event or receive event? - virtual void OnInternalPacket(InternalPacket *internalPacket, unsigned frameNumber, SystemAddress remoteSystemAddress, MafiaNet::TimeMS time, int isSend) {(void) internalPacket; (void) frameNumber; (void) remoteSystemAddress; (void) time; (void) isSend;} - - /// Called when we get an ack for a message we reliably sent - /// \pre To be called, UsesReliabilityLayer() must return true - /// \param[in] messageNumber The numerical identifier for which message this is - /// \param[in] remoteSystemAddress The player we sent or got this packet from - /// \param[in] time The current time as returned by MafiaNet::GetTimeMS() - virtual void OnAck(unsigned int messageNumber, SystemAddress remoteSystemAddress, MafiaNet::TimeMS time) {(void) messageNumber; (void) remoteSystemAddress; (void) time;} - - /// System called RakPeerInterface::PushBackPacket - /// \param[in] data The data being sent - /// \param[in] bitsUsed How many bits long \a data is - /// \param[in] remoteSystemAddress The player we sent or got this packet from - virtual void OnPushBackPacket(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) {(void) data; (void) bitsUsed; (void) remoteSystemAddress;} - - RakPeerInterface *GetRakPeerInterface(void) const {return rakPeerInterface;} - - RakNetGUID GetMyGUIDUnified(void) const; - - /// \internal - void SetRakPeerInterface( RakPeerInterface *ptr ); - -#if _RAKNET_SUPPORT_TCPInterface==1 - /// \internal - void SetTCPInterface( TCPInterface *ptr ); -#endif - -protected: - // Send through either rakPeerInterface or tcpInterface, whichever is available - void SendUnified( const MafiaNet::BitStream * bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ); - void SendUnified( const char * data, const int length, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ); - bool SendListUnified( const char **data, const int *lengths, const int numParameters, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ); - - Packet *AllocatePacketUnified(unsigned dataSize); - void PushBackPacketUnified(Packet *packet, bool pushAtHead); - void DeallocPacketUnified(Packet *packet); - - // Filled automatically in when attached - RakPeerInterface *rakPeerInterface; -#if _RAKNET_SUPPORT_TCPInterface==1 - TCPInterface *tcpInterface; -#endif -}; - -} // namespace MafiaNet - -#endif - diff --git a/vendors/mafianet/Source/include/mafianet/PointGridSectorizer.h b/vendors/mafianet/Source/include/mafianet/PointGridSectorizer.h deleted file mode 100644 index 386973d50..000000000 --- a/vendors/mafianet/Source/include/mafianet/PointGridSectorizer.h +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2026, MafiaHub - * - * This source code is licensed under the MIT-style license found in the - * license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Uniform grid spatial index over point entries with incremental -/// add/remove/move, intended as the server-side interest-management index. -/// -/// Unlike GridSectorizer — whose compiled-in per-cell storage is append-only, -/// forcing consumers to Clear() and rebuild the whole grid to evict anything — -/// PointGridSectorizer keeps a per-entry record (cell + slot) in a -/// runtime-sized open-addressing table, so entries can be removed or moved -/// individually in amortized O(1), independent of the cell count and the total -/// entry count. Entries are points, not boxes: each entry occupies exactly one -/// cell, so GetEntries() never returns duplicates and callers do not need to -/// dedup (GridSectorizer could return one entry once per cell its box spanned). - -#ifndef MAFIANET_POINT_GRID_SECTORIZER_H -#define MAFIANET_POINT_GRID_SECTORIZER_H - -#include "Export.h" -#include "memoryoverride.h" -#include "DS_List.h" - -namespace MafiaNet -{ - -/// \brief Spatial grid over point entries with O(1) incremental updates. -/// \details One entry per pointer: AddEntry() and MoveEntry() are the same -/// upsert operation, so position writes can be forwarded to the grid blindly -/// without tracking membership. All positions (entries and query rectangles) -/// are clamped to the world bounds given to Init() — out-of-bounds, even -/// non-finite, positions land in the edge cells (NaN maps to the minimum edge -/// cell), they never assert, drop, or invoke undefined behavior. Before a -/// successful Init() every operation is a defined no-op. Queries return the -/// contents of every cell overlapping the rectangle, i.e. a cell-granularity -/// superset of the exact matches; callers post-filter, as with GridSectorizer. -/// Not thread-safe; intended for single-threaded use from the update loop. -class RAK_DLL_EXPORT PointGridSectorizer -{ -public: - PointGridSectorizer(); - ~PointGridSectorizer(); - - // Owns raw memory (cell lists and the entry-record table); a memberwise - // copy would double-free it. - PointGridSectorizer(const PointGridSectorizer&) = delete; - PointGridSectorizer& operator=(const PointGridSectorizer&) = delete; - - /// (Re-)initializes the grid, discarding any current entries. - /// \param[in] _cellWidth, _cellHeight Size of each cell in world units - /// \param[in] minX, minY, maxX, maxY World bounds; positions outside clamp to the edge cells - /// \return False — leaving the grid inert (all operations no-op) until a - /// valid re-Init — if the cell sizes or bounds are not positive and finite, - /// or the resulting cell count would not fit in an int. - bool Init(const float _cellWidth, const float _cellHeight, const float minX, const float minY, const float maxX, const float maxY); - - /// Adds a point entry at (x,y), clamped to the world bounds. Amortized O(1). - /// If \a entry is already in the grid this relocates it (same as MoveEntry). - /// \pre \a entry must be non-null (null is rejected as a no-op). - /// \return True if the entry was inserted or changed cell, false if it - /// stayed in its current cell (or the grid is uninitialized / entry null). - bool AddEntry(void *entry, const float x, const float y); - - /// Removes an entry. O(1) via swap-remove within its cell. - /// \return True if the entry was in the grid, false if absent (no-op). - bool RemoveEntry(void *entry); - - /// Moves an entry to (x,y), clamped to the world bounds. Amortized O(1); - /// if the new position is in the entry's current cell this is a cheap - /// early-out (the hot case for small per-tick movement). Inserts the entry - /// if absent. - /// \return True if the entry was inserted or changed cell — the signal an - /// event-driven consumer needs to recompute interest sets — false if it - /// stayed in its current cell (or the grid is uninitialized / entry null). - bool MoveEntry(void *entry, const float x, const float y); - - /// Resets \a intersectionList (size 0, capacity kept for reuse) and fills - /// it with every entry in the cells overlapping the rectangle, each exactly - /// once. O(cells overlapped + entries returned). - void GetEntries(DataStructures::List &intersectionList, const float minX, const float minY, const float maxX, const float maxY) const; - - /// Returns whether the entry is currently in the grid. O(1). - bool HasEntry(void *entry) const; - - /// Number of entries in the grid. O(1). - unsigned int Size(void) const; - - /// Removes all entries; the grid stays initialized and every allocation is - /// kept for reuse. O(cell count + record-table capacity). - void Clear(void); - -protected: - /// \internal Where an entry lives. Doubles as an open-addressing table - /// slot: a null \a entry marks the slot empty. - struct EntryRecord - { - void *entry; - int cellIndex; - unsigned int slotIndex; - }; - - EntryRecord* FindRecord(void *entry) const; - void InsertRecord(void *entry, const int cellIndex, const unsigned int slotIndex); - void EraseRecord(EntryRecord *record); - void GrowRecordTable(void); - - unsigned int PushIntoCell(void *entry, const int cellIndex); - void RemoveFromCell(const EntryRecord &record); - - int WorldToCellXClamped(const float input) const; - int WorldToCellYClamped(const float input) const; - int WorldToCellIndexClamped(const float x, const float y) const; - - float cellOriginX, cellOriginY; - float invCellWidth, invCellHeight; - int gridCellWidthCount, gridCellHeightCount; - - /// Per-cell unordered entry lists; removal swaps the last element into the - /// freed slot, so order within a cell is not meaningful. - DataStructures::List *grid; - - /// Open-addressing record table (linear probing, backward-shift deletion). - /// Power-of-two capacity, grown with the entry count, never shrunk. - EntryRecord *records; - unsigned int recordCapacity; - unsigned int recordCount; -}; - -} // namespace MafiaNet - -#endif // MAFIANET_POINT_GRID_SECTORIZER_H diff --git a/vendors/mafianet/Source/include/mafianet/RPC4Plugin.h b/vendors/mafianet/Source/include/mafianet/RPC4Plugin.h deleted file mode 100644 index 04dcfa08c..000000000 --- a/vendors/mafianet/Source/include/mafianet/RPC4Plugin.h +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Remote procedure call, supporting C functions only. No external dependencies required. -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_RPC4Plugin==1 - -#ifndef __RPC_4_PLUGIN_H -#define __RPC_4_PLUGIN_H - -#include "PluginInterface2.h" -#include "PacketPriority.h" -#include "types.h" -#include "BitStream.h" -#include "string.h" -#include "NetworkIDObject.h" -#include "DS_Hash.h" -#include "DS_OrderedList.h" - -/// \defgroup RPC_PLUGIN_GROUP RPC -/// \brief Remote procedure calls, without external dependencies. -/// \details This should not be used at the same time as RPC3. This is a less functional version of RPC3, and is here for users that do not want the Boost dependency of RPC3. -/// \ingroup PLUGINS_GROUP - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; -class NetworkIDManager; - - /// \brief Error codes returned by a remote system as to why an RPC function call cannot execute - /// \details Error code follows packet ID ID_RPC_REMOTE_ERROR, that is packet->data[1]
- /// Name of the function will be appended starting at packet->data[2] - /// \ingroup RPC_PLUGIN_GROUP - enum RPCErrorCodes - { - /// Named function was not registered with RegisterFunction(). Check your spelling. - RPC_ERROR_FUNCTION_NOT_REGISTERED, - }; - - /// \brief Instantiate this class globally if you want to register a function with RPC4 at the global space - class RAK_DLL_EXPORT RPC4GlobalRegistration - { - public: - /// \brief Queue a call to RPC4::RegisterFunction() globally. Actual call occurs once RPC4 is attached to an instance of RakPeer or TCPInterface. - /// \param[in] context Opaque user pointer passed back to the handler on every invocation. Used to route the call to an object instance without a global. - RPC4GlobalRegistration(const char* uniqueID, void ( *functionPointer ) (MafiaNet::BitStream *userData, Packet *packet, void *context ), void *context); - - /// \brief Queue a call to RPC4::RegisterSlot() globally. Actual call occurs once RPC4 is attached to an instance of RakPeer or TCPInterface. - /// \param[in] context Opaque user pointer passed back to the handler on every invocation. - RPC4GlobalRegistration(const char* uniqueID, void ( *functionPointer ) (MafiaNet::BitStream *userData, Packet *packet, void *context ), void *context, int callPriority); - - /// \brief Queue a call to RPC4::RegisterBlockingFunction() globally. Actual call occurs once RPC4 is attached to an instance of RakPeer or TCPInterface. - /// \param[in] context Opaque user pointer passed back to the handler on every invocation. - RPC4GlobalRegistration(const char* uniqueID, void ( *functionPointer ) (MafiaNet::BitStream *userData, MafiaNet::BitStream *returnData, Packet *packet, void *context ), void *context); - - /// \brief Queue a call to RPC4::RegisterLocalCallback() globally. Actual call occurs once RPC4 is attached to an instance of RakPeer or TCPInterface. - RPC4GlobalRegistration(const char* uniqueID, MessageID messageId); - }; - - /// \brief The RPC4 plugin is just an association between a C function pointer and a string. - /// \details It is for users that want to use RPC, but do not want to use boost. - /// You do not have the automatic serialization or other features of RPC3, and C++ member calls are not supported. - /// \note You cannot use RPC4 at the same time as RPC3Plugin - /// \ingroup RPC_PLUGIN_GROUP - class RAK_DLL_EXPORT RPC4 : public PluginInterface2 - { - public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(RPC4) - - // Constructor - RPC4(); - - // Destructor - virtual ~RPC4(); - - /// \deprecated Use RegisterSlot - /// \brief Register a function pointer to be callable from a remote system - /// \details The hash of the function name will be stored as an association with the function pointer - /// When a call is made to call this function from the \a Call() or CallLoopback() function, the function pointer will be invoked with the passed bitStream to Call() and the actual Packet that RakNet got. - /// \sa RegisterPacketCallback() - /// \param[in] uniqueID Identifier to be associated with \a functionPointer. If this identifier is already in use, the call will return false. - /// \param[in] functionPointer C function pointer to be called - /// \param[in] context Opaque user pointer passed back to \a functionPointer on every invocation. Lets the handler recover its owning object instance without a file-static global. The pointer is not owned by RPC4; keep it valid until the function is unregistered. - /// \return True if the hash of uniqueID is not in use, false otherwise. - bool RegisterFunction(const char* uniqueID, void ( *functionPointer ) (MafiaNet::BitStream *userData, Packet *packet, void *context ), void *context); - - /// Register a slot, which is a function pointer to one or more implementations that supports this function signature - /// When a signal occurs, all slots with the same identifier are called. - /// \param[in] sharedIdentifier A string to identify the slot. Recommended to be the same as the name of the function. - /// \param[in] functionPtr Pointer to the function. For C, just pass the name of the function. For C++, use ARPC_REGISTER_CPP_FUNCTION - /// \param[in] context Opaque user pointer passed back to \a functionPointer on every invocation. Each registration carries its own context, so the same handler may be registered under one identifier for several object instances. Not owned by RPC4; keep it valid until the slot is unregistered. - /// \param[in] callPriority Slots are called by order of the highest callPriority first. For slots with the same priority, they are called in the order they are registered - void RegisterSlot(const char *sharedIdentifier, void ( *functionPointer ) (MafiaNet::BitStream *userData, Packet *packet, void *context ), void *context, int callPriority); - - /// \brief Same as \a RegisterFunction, but is called with CallBlocking() instead of Call() and returns a value to the caller - /// \param[in] context Opaque user pointer passed back to \a functionPointer on every invocation. Not owned by RPC4; keep it valid until the function is unregistered. - bool RegisterBlockingFunction(const char* uniqueID, void ( *functionPointer ) (MafiaNet::BitStream *userData, MafiaNet::BitStream *returnData, Packet *packet, void *context ), void *context); - - /// \deprecated Use RegisterSlot and invoke on self only when the packet you want arrives - /// When a RakNet Packet with the specified identifier is returned, execute CallLoopback() on a function previously registered with RegisterFunction() - /// For example, you could call "OnClosedConnection" whenever you get ID_DISCONNECTION_NOTIFICATION or ID_CONNECTION_LOST - /// \param[in] uniqueID Identifier passed to RegisterFunction() - /// \param[in] messageId What RakNet packet ID to call on, for example ID_DISCONNECTION_NOTIFICATION or ID_CONNECTION_LOST - void RegisterLocalCallback(const char* uniqueID, MessageID messageId); - - /// \brief Unregister a function pointer previously registered with RegisterFunction() - /// \param[in] Identifier originally passed to RegisterFunction() - /// \return True if the hash of uniqueID was in use, and hence removed. false otherwise. - bool UnregisterFunction(const char* uniqueID); - - /// \brief Same as UnregisterFunction, except for a blocking function - bool UnregisterBlockingFunction(const char* uniqueID); - - /// Remove the association created with RegisterPacketCallback() - /// \param[in] uniqueID Identifier passed as uniqueID to RegisterLocalCallback() - /// \param[in] messageId Identifier passed as messageId to RegisterLocalCallback() - /// \return True if the combination of uniqueID and messageId was in use, and hence removed - bool UnregisterLocalCallback(const char* uniqueID, MessageID messageId); - - /// Remove the association created with RegisterSlot() - /// \param[in] sharedIdentifier Identifier passed as sharedIdentifier to RegisterSlot() - bool UnregisterSlot(const char* sharedIdentifier); - - /// \deprecated Use RegisterSlot() and Signal() with your own RakNetGUID as the send target - /// Send to the attached instance of RakPeer. See RakPeerInterface::SendLoopback() - /// \param[in] Identifier originally passed to RegisterFunction() on the local system - /// \param[in] bitStream bitStream encoded data to send to the function callback - void CallLoopback( const char* uniqueID, MafiaNet::BitStream * bitStream ); - - /// \deprecated, use Signal() - /// Send to the specified remote instance of RakPeer. - /// \param[in] uniqueID Identifier originally passed to RegisterFunction() on the remote system(s) - /// \param[in] bitStream bitStream encoded data to send to the function callback - /// \param[in] priority See RakPeerInterface::Send() - /// \param[in] reliability See RakPeerInterface::Send() - /// \param[in] orderingChannel See RakPeerInterface::Send() - /// \param[in] systemIdentifier See RakPeerInterface::Send() - /// \param[in] broadcast See RakPeerInterface::Send() - void Call( const char* uniqueID, MafiaNet::BitStream * bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ); - - /// \brief Same as call, but don't return until the remote system replies. - /// Broadcasting parameter does not exist, this can only call one remote system - /// \note This function does not return until the remote system responds, disconnects, or was never connected to begin with - /// \param[in] Identifier originally passed to RegisterBlockingFunction() on the remote system(s) - /// \param[in] bitStream bitStream encoded data to send to the function callback - /// \param[in] priority See RakPeerInterface::Send() - /// \param[in] reliability See RakPeerInterface::Send() - /// \param[in] orderingChannel See RakPeerInterface::Send() - /// \param[in] systemIdentifier See RakPeerInterface::Send() - /// \param[out] returnData Written to by the function registered with RegisterBlockingFunction. - /// \return true if successfully called. False on disconnect, function not registered, or not connected to begin with - bool CallBlocking( const char* uniqueID, MafiaNet::BitStream * bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, MafiaNet::BitStream *returnData ); - - /// Calls zero or more functions identified by sharedIdentifier registered with RegisterSlot() - /// \param[in] sharedIdentifier parameter of the same name passed to RegisterSlot() on the remote system - /// \param[in] bitStream bitStream encoded data to send to the function callback - /// \param[in] priority See RakPeerInterface::Send() - /// \param[in] reliability See RakPeerInterface::Send() - /// \param[in] orderingChannel See RakPeerInterface::Send() - /// \param[in] systemIdentifier See RakPeerInterface::Send() - /// \param[in] broadcast See RakPeerInterface::Send() - /// \param[in] invokeLocal If true, also sends to self. - void Signal(const char *sharedIdentifier, MafiaNet::BitStream * bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, bool invokeLocal); - - /// If called while processing a slot, no further slots for the currently executing signal will be executed - void InterruptSignal(void); - - /// \internal - struct LocalCallback - { - MessageID messageId; - DataStructures::OrderedList functions; - }; - static int LocalCallbackComp(const MessageID &key, LocalCallback* const &data ); - - /// \internal - // Callable object, along with priority to call relative to other objects - struct LocalSlotObject - { - LocalSlotObject() {} - LocalSlotObject(unsigned int _registrationCount,int _callPriority, void ( *_functionPointer ) (MafiaNet::BitStream *userData, Packet *packet, void *context ), void *_context) - {registrationCount=_registrationCount;callPriority=_callPriority;functionPointer=_functionPointer;context=_context;} - ~LocalSlotObject() {} - - // Used so slots are called in the order they are registered - unsigned int registrationCount; - int callPriority; - void ( *functionPointer ) (MafiaNet::BitStream *userData, Packet *packet, void *context ); - // Opaque user pointer passed back to functionPointer on invocation - void *context; - }; - - static int LocalSlotObjectComp( const LocalSlotObject &key, const LocalSlotObject &data ); - - /// \internal - struct LocalSlot - { - DataStructures::OrderedList slotObjects; - }; - DataStructures::Hash localSlots; - - protected: - - // -------------------------------------------------------------------------------------------- - // Packet handling functions - // -------------------------------------------------------------------------------------------- - virtual void OnAttach(void); - virtual PluginReceiveResult OnReceive(Packet *packet); - - /// \internal A registered nonblocking function paired with its user context - struct RegisteredNonblockingFunction - { - void ( *functionPointer ) (MafiaNet::BitStream *userData, Packet *packet, void *context ); - void *context; - }; - /// \internal A registered blocking function paired with its user context - struct RegisteredBlockingFunction - { - void ( *functionPointer ) (MafiaNet::BitStream *userData, MafiaNet::BitStream *returnData, Packet *packet, void *context ); - void *context; - }; - - DataStructures::Hash registeredNonblockingFunctions; - DataStructures::Hash registeredBlockingFunctions; - DataStructures::OrderedList localCallbacks; - - MafiaNet::BitStream blockingReturnValue; - bool gotBlockingReturnValue; - - DataStructures::HashIndex GetLocalSlotIndex(const char *sharedIdentifier); - - /// Used so slots are called in the order they are registered - unsigned int nextSlotRegistrationCount; - - bool interruptSignal; - - void InvokeSignal(DataStructures::HashIndex functionIndex, MafiaNet::BitStream *serializedParameters, Packet *packet); - }; - -} // End namespace - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/Rackspace.h b/vendors/mafianet/Source/include/mafianet/Rackspace.h deleted file mode 100644 index aecadbdd1..000000000 --- a/vendors/mafianet/Source/include/mafianet/Rackspace.h +++ /dev/null @@ -1,418 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file Rackspace.h -/// \brief Helper to class to manage Rackspace servers -/// - - -#include "NativeFeatureIncludes.h" - -#if _RAKNET_SUPPORT_Rackspace==1 && _RAKNET_SUPPORT_TCPInterface==1 - -#include "Export.h" -#include "DS_List.h" -#include "types.h" -#include "DS_Queue.h" -#include "string.h" - -#ifndef __RACKSPACE_H -#define __RACKSPACE_H - -namespace MafiaNet -{ - - class TCPInterface; - struct Packet; - - /// \brief Result codes for Rackspace commands - /// /sa Rackspace::EventTypeToString() - enum RackspaceEventType - { - RET_Success_200, - RET_Success_201, - RET_Success_202, - RET_Success_203, - RET_Success_204, - RET_Cloud_Servers_Fault_500, - RET_Service_Unavailable_503, - RET_Unauthorized_401, - RET_Bad_Request_400, - RET_Over_Limit_413, - RET_Bad_Media_Type_415, - RET_Item_Not_Found_404, - RET_Build_In_Progress_409, - RET_Resize_Not_Allowed_403, - RET_Connection_Closed_Without_Reponse, - RET_Unknown_Failure, - }; - - /// \internal - enum RackspaceOperationType - { - RO_CONNECT_AND_AUTHENTICATE, - RO_LIST_SERVERS, - RO_LIST_SERVERS_WITH_DETAILS, - RO_CREATE_SERVER, - RO_GET_SERVER_DETAILS, - RO_UPDATE_SERVER_NAME_OR_PASSWORD, - RO_DELETE_SERVER, - RO_LIST_SERVER_ADDRESSES, - RO_SHARE_SERVER_ADDRESS, - RO_DELETE_SERVER_ADDRESS, - RO_REBOOT_SERVER, - RO_REBUILD_SERVER, - RO_RESIZE_SERVER, - RO_CONFIRM_RESIZED_SERVER, - RO_REVERT_RESIZED_SERVER, - RO_LIST_FLAVORS, - RO_GET_FLAVOR_DETAILS, - RO_LIST_IMAGES, - RO_CREATE_IMAGE, - RO_GET_IMAGE_DETAILS, - RO_DELETE_IMAGE, - RO_LIST_SHARED_IP_GROUPS, - RO_LIST_SHARED_IP_GROUPS_WITH_DETAILS, - RO_CREATE_SHARED_IP_GROUP, - RO_GET_SHARED_IP_GROUP_DETAILS, - RO_DELETE_SHARED_IP_GROUP, - - RO_NONE, - }; - - /// \brief Callback interface to receive the results of operations - class RAK_DLL_EXPORT Rackspace2EventCallback - { - public: - Rackspace2EventCallback() {} - virtual ~Rackspace2EventCallback() {} - virtual void OnAuthenticationResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnListServersResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnListServersWithDetailsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnCreateServerResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnGetServerDetails(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnUpdateServerNameOrPassword(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnDeleteServer(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnListServerAddresses(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnShareServerAddress(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnDeleteServerAddress(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnRebootServer(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnRebuildServer(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnResizeServer(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnConfirmResizedServer(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnRevertResizedServer(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnListFlavorsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnGetFlavorDetailsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnListImagesResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnCreateImageResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnGetImageDetailsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnDeleteImageResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnListSharedIPGroups(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnListSharedIPGroupsWithDetails(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnCreateSharedIPGroup(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnGetSharedIPGroupDetails(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - virtual void OnDeleteSharedIPGroup(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; - - virtual void OnConnectionAttemptFailure(RackspaceOperationType operationType, const char *url)=0; - }; - - /// \brief Callback interface to receive the results of operations, with a default result - class RAK_DLL_EXPORT RackspaceEventCallback_Default : public Rackspace2EventCallback - { - public: - virtual void ExecuteDefault(const char *callbackName, RackspaceEventType eventType, const char *htmlAdditionalInfo) {(void) callbackName; (void) eventType; (void) htmlAdditionalInfo;} - - virtual void OnAuthenticationResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnAuthenticationResult", eventType, htmlAdditionalInfo);} - virtual void OnListServersResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnListServersResult", eventType, htmlAdditionalInfo);} - virtual void OnListServersWithDetailsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnListServersWithDetailsResult", eventType, htmlAdditionalInfo);} - virtual void OnCreateServerResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnCreateServerResult", eventType, htmlAdditionalInfo);} - virtual void OnGetServerDetails(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnGetServerDetails", eventType, htmlAdditionalInfo);} - virtual void OnUpdateServerNameOrPassword(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnUpdateServerNameOrPassword", eventType, htmlAdditionalInfo);} - virtual void OnDeleteServer(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnDeleteServer", eventType, htmlAdditionalInfo);} - virtual void OnListServerAddresses(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnListServerAddresses", eventType, htmlAdditionalInfo);} - virtual void OnShareServerAddress(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnShareServerAddress", eventType, htmlAdditionalInfo);} - virtual void OnDeleteServerAddress(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnDeleteServerAddress", eventType, htmlAdditionalInfo);} - virtual void OnRebootServer(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnRebootServer", eventType, htmlAdditionalInfo);} - virtual void OnRebuildServer(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnRebuildServer", eventType, htmlAdditionalInfo);} - virtual void OnResizeServer(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnResizeServer", eventType, htmlAdditionalInfo);} - virtual void OnConfirmResizedServer(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnConfirmResizedServer", eventType, htmlAdditionalInfo);} - virtual void OnRevertResizedServer(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnRevertResizedServer", eventType, htmlAdditionalInfo);} - virtual void OnListFlavorsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnListFlavorsResult", eventType, htmlAdditionalInfo);} - virtual void OnGetFlavorDetailsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnGetFlavorDetailsResult", eventType, htmlAdditionalInfo);} - virtual void OnListImagesResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnListImagesResult", eventType, htmlAdditionalInfo);} - virtual void OnCreateImageResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnCreateImageResult", eventType, htmlAdditionalInfo);} - virtual void OnGetImageDetailsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnGetImageDetailsResult", eventType, htmlAdditionalInfo);} - virtual void OnDeleteImageResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnDeleteImageResult", eventType, htmlAdditionalInfo);} - virtual void OnListSharedIPGroups(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnListSharedIPGroups", eventType, htmlAdditionalInfo);} - virtual void OnListSharedIPGroupsWithDetails(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnListSharedIPGroupsWithDetails", eventType, htmlAdditionalInfo);} - virtual void OnCreateSharedIPGroup(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnCreateSharedIPGroup", eventType, htmlAdditionalInfo);} - virtual void OnGetSharedIPGroupDetails(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnGetSharedIPGroupDetails", eventType, htmlAdditionalInfo);} - virtual void OnDeleteSharedIPGroup(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnDeleteSharedIPGroup", eventType, htmlAdditionalInfo);} - - virtual void OnConnectionAttemptFailure(RackspaceOperationType operationType, const char *url) {(void) operationType; (void) url;} - }; - - /// \brief Code that uses the TCPInterface class to communicate with the Rackspace API servers - /// \pre Compile RakNet with OPEN_SSL_CLIENT_SUPPORT set to 1 - /// \pre Packets returned from TCPInterface::OnReceive() must be passed to Rackspace::OnReceive() - /// \pre Packets returned from TCPInterface::HasLostConnection() must be passed to Rackspace::OnClosedConnection() - class RAK_DLL_EXPORT Rackspace - { - public: - Rackspace(); - ~Rackspace(); - - /// \brief Authenticate with Rackspace servers, required before executing any commands. - /// \details All requests to authenticate and operate against Cloud Servers are performed using SSL over HTTP (HTTPS) on TCP port 443. - /// Times out after 24 hours - if you get RET_Authenticate_Unauthorized in the RackspaceEventCallback callback, call again - /// \sa RackspaceEventCallback::OnAuthenticationResult() - /// \param[in] _tcpInterface An instance of TCPInterface, build with OPEN_SSL_CLIENT_SUPPORT 1 and already started - /// \param[in] _authenticationURL See http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf . US-based accounts authenticate through auth.api.rackspacecloud.com. UK-based accounts authenticate through lon.auth.api.rackspacecloud.com - /// \param[in] _rackspaceCloudUsername Username you registered with Rackspace on their website - /// \param[in] _apiAccessKey Obtain your API access key from the Rackspace Cloud Control Panel in the Your Account API Access section. - /// \return The address of the authentication server, or UNASSIGNED_SYSTEM_ADDRESS if the connection attempt failed - SystemAddress Authenticate(TCPInterface *_tcpInterface, const char *_authenticationURL, const char *_rackspaceCloudUsername, const char *_apiAccessKey); - - /// \brief Get a list of running servers - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnListServersResult() - void ListServers(void); - - /// \brief Get a list of running servers, with extended details on each server - /// \sa GetServerDetails() - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnListServersWithDetailsResult() - void ListServersWithDetails(void); - - /// \brief Create a server - /// \details Create a server with a given image (harddrive contents) and flavor (hardware configuration) - /// Get the available images with ListImages() - /// Get the available flavors with ListFlavors() - /// It is possible to configure the server in more detail. See the XML schema at http://docs.rackspacecloud.com/servers/api/v1.0 - /// You can execute such a custom command by calling AddOperation() manually. See the implementation of CreateServer for how to do so. - /// The server takes a while to build. Call GetServerDetails() to get the current build status. Server id to pass to GetServerDetails() is returned in the field - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnCreateServerResult() - /// \param[in] name Name of the server. Only alphanumeric characters, periods, and hyphens are valid. Server Name cannot start or end with a period or hyphen. - /// \param[in] imageId Which image (harddrive contents, including OS) to use - /// \param[in] flavorId Which flavor (hardware config) to use, primarily how much memory is available. - void CreateServer(MafiaNet::RakString name, MafiaNet::RakString imageId, MafiaNet::RakString flavorId); - - /// \brief Get details on a particular server - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnGetServerDetailsResult() - /// \param[in] serverId Which server to get details on. You can call ListServers() to get the list of active servers. - void GetServerDetails(MafiaNet::RakString serverId); - - /// \brief Changes the name or password for a server - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnUpdateServerNameOrPasswordResult() - /// \param[in] serverId Which server to get details on. You can call ListServers() to get the list of active servers. - /// \param[in] newName The new server name. Leave blank to leave unchanged. Only alphanumeric characters, periods, and hyphens are valid. Server Name cannot start or end with a period or hyphen. - /// \param[in] newPassword The new server password. Leave blank to leave unchanged. - void UpdateServerNameOrPassword(MafiaNet::RakString serverId, MafiaNet::RakString newName, MafiaNet::RakString newPassword); - - /// \brief Deletes a server - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnDeleteServerResult() - /// \param[in] serverId Which server to get details on. You can call ListServers() to get the list of active servers. - void DeleteServer(MafiaNet::RakString serverId); - - /// \brief Lists the IP addresses available to a server - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnListServerAddressesResult() - /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. - void ListServerAddresses(MafiaNet::RakString serverId); - - /// \brief Shares an IP address with a server - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnShareServerAddressResult() - /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. - /// \param[in] ipAddress Which IP address. You can call ListServerAddresses() to get the list of addresses for the specified server - void ShareServerAddress(MafiaNet::RakString serverId, MafiaNet::RakString ipAddress); - - /// \brief Stops sharing an IP address with a server - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnDeleteServerAddressResult() - /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. - /// \param[in] ipAddress Which IP address. You can call ListServerAddresses() to get the list of addresses for the specified server - void DeleteServerAddress(MafiaNet::RakString serverId, MafiaNet::RakString ipAddress); - - /// \brief Reboots a server - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnRebootServerResult() - /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. - /// \param[in] rebootType Should be either "HARD" or "SOFT" - void RebootServer(MafiaNet::RakString serverId, MafiaNet::RakString rebootType); - - /// \brief Rebuilds a server with a different image (harddrive contents) - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnRebuildServerResult() - /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. - /// \param[in] imageId Which image (harddrive contents, including OS) to use - void RebuildServer(MafiaNet::RakString serverId, MafiaNet::RakString imageId); - - /// \brief Changes the hardware configuration of a server. This does not take effect until you call ConfirmResizedServer() - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnResizeServerResult() - /// \sa RevertResizedServer() - /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. - /// \param[in] flavorId Which flavor (hardware config) to use, primarily how much memory is available. - void ResizeServer(MafiaNet::RakString serverId, MafiaNet::RakString flavorId); - - /// \brief Confirm a resize for the specified server - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnConfirmResizedServerResult() - /// \sa ResizeServer() - /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. - void ConfirmResizedServer(MafiaNet::RakString serverId); - - /// \brief Reverts a resize for the specified server - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnRevertResizedServerResult() - /// \sa ResizeServer() - /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. - void RevertResizedServer(MafiaNet::RakString serverId); - - /// \brief List all flavors (hardware configs, primarily memory) - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnListFlavorsResult() - void ListFlavors(void); - - /// \brief Get extended details about a specific flavor - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnGetFlavorDetailsResult() - /// \sa ListFlavors() - /// \param[in] flavorId Which flavor (hardware config) - void GetFlavorDetails(MafiaNet::RakString flavorId); - - /// \brief List all images (software configs, including operating systems), which includes images you create yourself - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnListImagesResult() - /// \sa CreateImage() - void ListImages(void); - - /// \brief Images a running server. This essentially copies the harddrive, and lets you start a server with the same harddrive contents later - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnCreateImageResult() - /// \sa ListImages() - /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. - /// \param[in] imageName What to call this image - void CreateImage(MafiaNet::RakString serverId, MafiaNet::RakString imageName); - - /// \brief Get extended details about a particular image - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnGetImageDetailsResult() - /// \sa ListImages() - /// \param[in] imageId Which image - void GetImageDetails(MafiaNet::RakString imageId); - - /// \brief Delete a custom image created with CreateImage() - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnDeleteImageResult() - /// \sa ListImages() - /// \param[in] imageId Which image - void DeleteImage(MafiaNet::RakString imageId); - - /// \brief List IP groups - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnListSharedIPGroupsResult() - void ListSharedIPGroups(void); - - /// \brief List IP groups with extended details - /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf - /// \sa RackspaceEventCallback::OnListSharedIPGroupsWithDetailsResult() - void ListSharedIPGroupsWithDetails(void); - - // I don't know what this does - void CreateSharedIPGroup(MafiaNet::RakString name, MafiaNet::RakString optionalServerId); - // I don't know what this does - void GetSharedIPGroupDetails(MafiaNet::RakString groupId); - // I don't know what this does - void DeleteSharedIPGroup(MafiaNet::RakString groupId); - - /// \brief Adds a callback to the list of callbacks to be called when any of the above functions finish executing - /// The callbacks are called in the order they are added - void AddEventCallback(Rackspace2EventCallback *callback); - /// \brief Removes a callback from the list of callbacks to be called when any of the above functions finish executing - /// The callbacks are called in the order they are added - void RemoveEventCallback(Rackspace2EventCallback *callback); - /// \brief Removes all callbacks - void ClearEventCallbacks(void); - - /// Call this anytime TCPInterface returns a packet - void OnReceive(Packet *packet); - - /// Call this when TCPInterface returns something other than UNASSIGNED_SYSTEM_ADDRESS from HasLostConnection() - void OnClosedConnection(SystemAddress systemAddress); - - /// String representation of each RackspaceEventType - static const char * EventTypeToString(RackspaceEventType eventType); - - /// \brief Mostly for internal use, but you can use it to execute an operation with more complex xml if desired - /// See the Rackspace.cpp on how to use it - void AddOperation(RackspaceOperationType type, MafiaNet::RakString httpCommand, MafiaNet::RakString operation, MafiaNet::RakString xml); - protected: - - DataStructures::List eventCallbacks; - - struct RackspaceOperation - { - RackspaceOperationType type; - // MafiaNet::RakString stringInfo; - SystemAddress connectionAddress; - bool isPendingAuthentication; - MafiaNet::RakString incomingStream; - MafiaNet::RakString httpCommand; - MafiaNet::RakString operation; - MafiaNet::RakString xml; - }; - - TCPInterface *tcpInterface; - - // RackspaceOperationType currentOperation; - // DataStructures::Queue nextOperationQueue; - - DataStructures::List operations; - bool HasOperationOfType(RackspaceOperationType t); - unsigned int GetOperationOfTypeIndex(RackspaceOperationType t); - - MafiaNet::RakString serverManagementURL; - MafiaNet::RakString serverManagementDomain; - MafiaNet::RakString serverManagementPath; - MafiaNet::RakString storageURL; - MafiaNet::RakString storageDomain; - MafiaNet::RakString storagePath; - MafiaNet::RakString cdnManagementURL; - MafiaNet::RakString cdnManagementDomain; - MafiaNet::RakString cdnManagementPath; - - MafiaNet::RakString storageToken; - MafiaNet::RakString authToken; - MafiaNet::RakString rackspaceCloudUsername; - MafiaNet::RakString apiAccessKey; - - bool ExecuteOperation(RackspaceOperation &ro); - void ReadLine(const char *data, const char *stringStart, MafiaNet::RakString &output); - bool ConnectToServerManagementDomain(RackspaceOperation &ro); - - - }; - -} // namespace MafiaNet - -#endif // __RACKSPACE_API_H - -#endif // _RAKNET_SUPPORT_Rackspace diff --git a/vendors/mafianet/Source/include/mafianet/Rand.h b/vendors/mafianet/Source/include/mafianet/Rand.h deleted file mode 100644 index 4118b8219..000000000 --- a/vendors/mafianet/Source/include/mafianet/Rand.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief \b [Internal] Random number generator -/// - - - -#ifndef __RAND_H -#define __RAND_H - -#include "Export.h" - -/// Initialise seed for Random Generator -/// \note not threadSafe, use an instance of RakNetRandom if necessary per thread -/// \param[in] seed The seed value for the random number generator. -extern void RAK_DLL_EXPORT seedMT( unsigned int seed ); - -/// \internal -/// \note not threadSafe, use an instance of RakNetRandom if necessary per thread -extern unsigned int RAK_DLL_EXPORT reloadMT( void ); - -/// Gets a random unsigned int -/// \note not threadSafe, use an instance of RakNetRandom if necessary per thread -/// \return an integer random value. -extern unsigned int RAK_DLL_EXPORT randomMT( void ); - -/// Gets a random float -/// \note not threadSafe, use an instance of RakNetRandom if necessary per thread -/// \return 0 to 1.0f, inclusive -extern float RAK_DLL_EXPORT frandomMT( void ); - -/// Randomizes a buffer -/// \note not threadSafe, use an instance of RakNetRandom if necessary per thread -extern void RAK_DLL_EXPORT fillBufferMT( void *buffer, unsigned int bytes ); - -namespace MafiaNet { - -// Same thing as above functions, but not global -class RAK_DLL_EXPORT RakNetRandom -{ -public: - RakNetRandom(); - ~RakNetRandom(); - void SeedMT( unsigned int seed ); - unsigned int ReloadMT( void ); - unsigned int RandomMT( void ); - float FrandomMT( void ); - void FillBufferMT( void *buffer, unsigned int bytes ); - -protected: - unsigned int state[ 624 + 1 ]; - unsigned int *next; - int left; -}; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/RandSync.h b/vendors/mafianet/Source/include/mafianet/RandSync.h deleted file mode 100644 index 02891e63c..000000000 --- a/vendors/mafianet/Source/include/mafianet/RandSync.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief \b [Internal] Random number generator -/// - - - -#ifndef __RAND_SYNC_H -#define __RAND_SYNC_H - -#include "Export.h" -#include "Rand.h" -#include "DS_Queue.h" -#include "NativeTypes.h" - -namespace MafiaNet { - -class BitStream; - -class RAK_DLL_EXPORT RakNetRandomSync -{ -public: - RakNetRandomSync(); - virtual ~RakNetRandomSync(); - void SeedMT( uint32_t _seed ); - void SeedMT( uint32_t _seed, uint32_t skipValues ); - float FrandomMT( void ); - unsigned int RandomMT( void ); - uint32_t GetSeed( void ) const; - uint32_t GetCallCount( void ) const; - void SetCallCount( uint32_t i ); - - virtual void SerializeConstruction(MafiaNet::BitStream *constructionBitstream); - virtual bool DeserializeConstruction(MafiaNet::BitStream *constructionBitstream); - virtual void Serialize(MafiaNet::BitStream *outputBitstream); - virtual void Deserialize(MafiaNet::BitStream *outputBitstream); - -protected: - void Skip( uint32_t count ); - DataStructures::Queue usedValues; - uint32_t seed; - uint32_t callCount; - uint32_t usedValueBufferCount; - RakNetRandom rnr; -}; -} // namespace MafiaNet - - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/ReadyEvent.h b/vendors/mafianet/Source/include/mafianet/ReadyEvent.h deleted file mode 100644 index 66f340a7c..000000000 --- a/vendors/mafianet/Source/include/mafianet/ReadyEvent.h +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Ready event plugin. This enables a set of systems to create a signal event, set this signal as ready or unready, and to trigger the event when all systems are ready -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_ReadyEvent==1 - -#ifndef __READY_EVENT_H -#define __READY_EVENT_H - -#include "PluginInterface2.h" -#include "DS_OrderedList.h" - -namespace MafiaNet { - -class RakPeerInterface; - -/// \defgroup READY_EVENT_GROUP ReadyEvent -/// \brief Peer to peer synchronized ready and unready events -/// \details -/// \ingroup PLUGINS_GROUP - -/// \ingroup READY_EVENT_GROUP -/// Returns the status of a remote system when querying with ReadyEvent::GetReadyStatus -enum ReadyEventSystemStatus -{ - /// ----------- Normal states --------------- - /// The remote system is not in the wait list, and we have never gotten a ready or complete message from it. - /// This is the default state for valid events - RES_NOT_WAITING, - /// We are waiting for this remote system to call SetEvent(thisEvent,true). - RES_WAITING, - /// The remote system called SetEvent(thisEvent,true), but it still waiting for other systems before completing the ReadyEvent. - RES_READY, - /// The remote system called SetEvent(thisEvent,true), and is no longer waiting for any other systems. - /// This remote system has completed the ReadyEvent - RES_ALL_READY, - - /// Error code, we couldn't look up the system because the event was unknown - RES_UNKNOWN_EVENT, -}; - -/// \brief Peer to peer synchronized ready and unready events -/// \details For peer to peer networks in a fully connected mesh.
-/// Solves the problem of how to tell if all peers, relative to all other peers, are in a certain ready state.
-/// For example, if A is connected to B and C, A may see that B and C are ready, but does not know if B is ready to C, or vice-versa.
-/// This plugin uses two stages to solve that problem, first, everyone I know about is ready. Second, everyone I know about is ready to everyone they know about.
-/// The user will get ID_READY_EVENT_SET and ID_READY_EVENT_UNSET as the signal flag is set or unset
-/// The user will get ID_READY_EVENT_ALL_SET when all systems are done waiting for all other systems, in which case the event is considered complete, and no longer tracked.
-/// \sa FullyConnectedMesh2 -/// \ingroup READY_EVENT_GROUP -class ReadyEvent : public PluginInterface2 -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(ReadyEvent) - - // Constructor - ReadyEvent(); - - // Destructor - virtual ~ReadyEvent(); - - // -------------------------------------------------------------------------------------------- - // User functions - // -------------------------------------------------------------------------------------------- - /// Sets or updates the initial ready state for our local system. - /// If eventId is an unknown event the event is created. - /// If eventId was previously used and you want to reuse it, call DeleteEvent first, or else you will keep the same event signals from before - /// Systems previously or later added through AddToWaitList() with the same \a eventId when isReady=true will get ID_READY_EVENT_SET - /// Systems previously added through AddToWaitList with the same \a eventId will get ID_READY_EVENT_UNSET - /// For both ID_READY_EVENT_SET and ID_READY_EVENT_UNSET, eventId is encoded in bytes 1 through 1+sizeof(int) - /// \param[in] eventId A user-defined identifier to wait on. This can be a sequence counter, an event identifier, or anything else you want. - /// \param[in] isReady True to signal we are ready to proceed with this event, false to unsignal - /// \return False if event status is ID_READY_EVENT_FORCE_ALL_SET, or if we are setting to a status we are already in (no change). Otherwise true - bool SetEvent(int eventId, bool isReady); - - /// When systems can call SetEvent() with isReady==false, it is possible for one system to return true from IsEventCompleted() while the other systems return false - /// This can occur if a system SetEvent() with isReady==false while the completion message is still being transmitted. - /// If your game has the situation where some action should be taken on all systems when IsEventCompleted() is true for any system, then call ForceCompletion() when the action begins. - /// This will force all systems to return true from IsEventCompleted(). - /// \param[in] eventId A user-defined identifier to immediately set as completed - void ForceCompletion(int eventId); - - /// Deletes an event. We will no longer wait for this event, and any systems that we know have set the event will be forgotten. - /// Call this to clear memory when events are completed and you know you will never need them again. - /// \param[in] eventId A user-defined identifier - /// \return True on success. False (failure) on unknown eventId - bool DeleteEvent(int eventId); - - /// Returns what was passed to SetEvent() - /// \return The value of isReady passed to SetEvent(). Also returns false on unknown event. - bool IsEventSet(int eventId); - - /// Returns if the event is about to be ready and we are negotiating the final packets. - /// This will usually only be true for a very short time, after which IsEventCompleted should return true. - /// While this is true you cannot add to the wait list, or SetEvent() isReady to false anymore. - /// \param[in] eventId A user-defined identifier - /// \return True if any other system has completed processing. Will always be true if IsEventCompleted() is true - bool IsEventCompletionProcessing(int eventId) const; - - /// Returns if the wait list is a subset of the completion list. - /// Call this after all systems you want to wait for have been added with AddToWaitList - /// If you are waiting for a specific number of systems (such as players later connecting), also check GetRemoteWaitListSize(eventId) to be equal to 1 less than the total number of participants. - /// \param[in] eventId A user-defined identifier - /// \return True on completion. False (failure) on unknown eventId, or the set is not completed. - bool IsEventCompleted(int eventId) const; - - /// Returns if this is a known event. - /// Events may be known even if we never ourselves referenced them with SetEvent, because other systems created them via ID_READY_EVENT_SET. - /// \param[in] eventId A user-defined identifier - /// \return true if we have this event, false otherwise - bool HasEvent(int eventId); - - /// Returns the total number of events stored in the system. - /// \return The total number of events stored in the system. - unsigned GetEventListSize(void) const; - - /// Returns the event ID stored at a particular index. EventIDs are stored sorted from least to greatest. - /// \param[in] index Index into the array, from 0 to GetEventListSize() - /// \return The event ID stored at a particular index - int GetEventAtIndex(unsigned index) const; - - /// Adds a system to wait for to signal an event before considering the event complete and returning ID_READY_EVENT_ALL_SET. - /// As we add systems, if this event was previously set to true with SetEvent, these systems will get ID_READY_EVENT_SET. - /// As these systems disconnect (directly or indirectly through the router) they are removed. - /// \note If the event completion process has already started, you cannot add more systems, as this would cause the completion process to fail - /// \param[in] eventId A user-defined number previously passed to SetEvent that has not yet completed - /// \param[in] guid An address to wait for event replies from. Pass UNASSIGNED_SYSTEM_ADDRESS for all currently connected systems. Until all systems in this list have called SetEvent with this ID and true, and have this system in the list, we won't get ID_READY_EVENT_COMPLETE - /// \return True on success, false on unknown eventId (this should be considered an error) - bool AddToWaitList(int eventId, RakNetGUID guid); - - /// Removes systems from the wait list, which should have been previously added with AddToWaitList - /// \note Systems that directly or indirectly disconnect from us are automatically removed from the wait list - /// \param[in] guid The system to remove from the wait list. Pass UNASSIGNED_RAKNET_GUID for all currently connected systems. - /// \return True on success, false on unknown eventId (this should be considered an error) - bool RemoveFromWaitList(int eventId, RakNetGUID guid); - - /// Returns if a particular system is waiting on a particular event. - /// \param[in] eventId A user-defined identifier - /// \param[in] guid The system we are checking up on - /// \return True if this system is waiting on this event, false otherwise. - bool IsInWaitList(int eventId, RakNetGUID guid); - - /// Returns the total number of systems we are waiting on for this event. - /// Does not include yourself - /// \param[in] eventId A user-defined identifier - /// \return The total number of systems we are waiting on for this event. - unsigned GetRemoteWaitListSize(int eventId) const; - - /// Returns the system address of a system at a particular index, for this event. - /// \param[in] eventId A user-defined identifier - /// \param[in] index Index into the array, from 0 to GetWaitListSize() - /// \return The system address of a system at a particular index, for this event. - RakNetGUID GetFromWaitListAtIndex(int eventId, unsigned index) const; - - /// For a remote system, find out what their ready status is (waiting, signaled, complete). - /// \param[in] eventId A user-defined identifier - /// \param[in] guid Which system we are checking up on - /// \return The status of this system, for this particular event. \sa ReadyEventSystemStatus - ReadyEventSystemStatus GetReadyStatus(int eventId, RakNetGUID guid); - - /// This channel will be used for all RakPeer::Send calls - /// \param[in] newChannel The channel to use for internal RakPeer::Send calls from this system. Defaults to 0. - void SetSendChannel(unsigned char newChannel); - - // ---------------------------- ALL INTERNAL AFTER HERE ---------------------------- - /// \internal - /// Status of a remote system - struct RemoteSystem - { - MessageID lastSentStatus, lastReceivedStatus; - RakNetGUID rakNetGuid; - }; - static int RemoteSystemCompByGuid( const RakNetGUID &key, const RemoteSystem &data ); - /// \internal - /// An event, with a set of systems we are waiting for, a set of systems that are signaled, and a set of systems with completed events - struct ReadyEventNode - { - int eventId; // Sorted on this - MessageID eventStatus; - DataStructures::OrderedList systemList; - }; - static int ReadyEventNodeComp( const int &key, ReadyEvent::ReadyEventNode * const &data ); - - -protected: - // -------------------------------------------------------------------------------------------- - // Packet handling functions - // -------------------------------------------------------------------------------------------- - virtual PluginReceiveResult OnReceive(Packet *packet); - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - virtual void OnRakPeerShutdown(void); - - void Clear(void); - /* - bool AnyWaitersCompleted(unsigned eventIndex) const; - bool AllWaitersCompleted(unsigned eventIndex) const; - bool AllWaitersReady(unsigned eventIndex) const; - void SendAllReady(unsigned eventId, RakNetGUID guid); - void BroadcastAllReady(unsigned eventIndex); - void SendReadyStateQuery(unsigned eventId, RakNetGUID guid); - void BroadcastReadyUpdate(unsigned eventIndex); - bool AddToWaitListInternal(unsigned eventIndex, RakNetGUID guid); - bool IsLocked(unsigned eventIndex) const; - bool IsAllReadyByIndex(unsigned eventIndex) const; - */ - - void SendReadyStateQuery(unsigned eventId, RakNetGUID guid); - void SendReadyUpdate(unsigned eventIndex, unsigned systemIndex, bool forceIfNotDefault); - void BroadcastReadyUpdate(unsigned eventIndex, bool forceIfNotDefault); - void RemoveFromAllLists(RakNetGUID guid); - void OnReadyEventQuery(Packet *packet); - void PushCompletionPacket(unsigned eventId); - bool AddToWaitListInternal(unsigned eventIndex, RakNetGUID guid); - void OnReadyEventForceAllSet(Packet *packet); - void OnReadyEventPacketUpdate(Packet *packet); - void UpdateReadyStatus(unsigned eventIndex); - bool IsEventCompletedByIndex(unsigned eventIndex) const; - unsigned CreateNewEvent(int eventId, bool isReady); - bool SetEventByIndex(int eventIndex, bool isReady); - - DataStructures::OrderedList readyEventNodeList; - unsigned char channel; -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/RefCountedObj.h b/vendors/mafianet/Source/include/mafianet/RefCountedObj.h deleted file mode 100644 index 4d5ba7a42..000000000 --- a/vendors/mafianet/Source/include/mafianet/RefCountedObj.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief \b Reference counted object. Very simple class for quick and dirty uses. -/// - - - -#ifndef __REF_COUNTED_OBJ_H -#define __REF_COUNTED_OBJ_H - -#include "memoryoverride.h" - -/// World's simplest class :) -class RefCountedObj -{ - public: - RefCountedObj() {refCount=1;} - virtual ~RefCountedObj() {} - void AddRef(void) {refCount++;} - void Deref(void) {if (--refCount==0) MafiaNet::OP_DELETE(this, _FILE_AND_LINE_);} - int refCount; -}; - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/RelayPlugin.h b/vendors/mafianet/Source/include/mafianet/RelayPlugin.h deleted file mode 100644 index 18fa910e8..000000000 --- a/vendors/mafianet/Source/include/mafianet/RelayPlugin.h +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Contains the class RelayPlugin -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_RelayPlugin==1 - -#ifndef __RELAY_PLUGIN_H -#define __RELAY_PLUGIN_H - -#include "PluginInterface2.h" -#include "string.h" -#include "DS_Hash.h" - -/// \defgroup RELAY_PLUGIN_GROUP RelayPlugin -/// \brief A simple class to relay messages from one system to another through an intermediary -/// \ingroup PLUGINS_GROUP - -namespace MafiaNet -{ - -/// Forward declarations -class RakPeerInterface; - -enum RelayPluginEnums -{ - // Server handled messages - RPE_MESSAGE_TO_SERVER_FROM_CLIENT, - RPE_ADD_CLIENT_REQUEST_FROM_CLIENT, - RPE_REMOVE_CLIENT_REQUEST_FROM_CLIENT, - RPE_GROUP_MESSAGE_FROM_CLIENT, - RPE_JOIN_GROUP_REQUEST_FROM_CLIENT, - RPE_LEAVE_GROUP_REQUEST_FROM_CLIENT, - RPE_GET_GROUP_LIST_REQUEST_FROM_CLIENT, - // Client handled messages - RPE_MESSAGE_TO_CLIENT_FROM_SERVER, - RPE_ADD_CLIENT_NOT_ALLOWED, - RPE_ADD_CLIENT_TARGET_NOT_CONNECTED, - RPE_ADD_CLIENT_NAME_ALREADY_IN_USE, - RPE_ADD_CLIENT_SUCCESS, - RPE_USER_ENTERED_ROOM, - RPE_USER_LEFT_ROOM, - RPE_GROUP_MSG_FROM_SERVER, - RPE_GET_GROUP_LIST_REPLY_FROM_SERVER, - RPE_JOIN_GROUP_SUCCESS, - RPE_JOIN_GROUP_FAILURE, -}; - -/// \brief A simple class to relay messages from one system to another, identifying remote systems by a string. -/// \ingroup RELAY_PLUGIN_GROUP -class RAK_DLL_EXPORT RelayPlugin : public PluginInterface2 -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(RelayPlugin) - - /// Constructor - RelayPlugin(); - - /// Destructor - virtual ~RelayPlugin(); - - /// \brief Forward messages from any system, to the system specified by the combination of key and guid. The sending system only needs to know the key. - /// \param[in] key A string to identify the target's RakNetGUID. This is so the sending system does not need to know the RakNetGUID of the target system. The key should be unique among all guids added. If the key is not unique, only one system will be sent to (at random). - /// \param[in] guid The RakNetGuid of the system to send to. If this system disconnects, it is removed from the internal hash - /// \return RPE_ADD_CLIENT_TARGET_NOT_CONNECTED, RPE_ADD_CLIENT_NAME_ALREADY_IN_USE, or RPE_ADD_CLIENT_OK - RelayPluginEnums AddParticipantOnServer(const RakString &key, const RakNetGUID &guid); - - /// \brief Remove a chat participant - void RemoveParticipantOnServer(const RakNetGUID &guid); - - /// \brief If true, then if the client calls AddParticipantRequestFromClient(), the server will call AddParticipantOnServer() automatically - /// Defaults to false - /// \param[in] accept true to accept, false to not. - void SetAcceptAddParticipantRequests(bool accept); - - /// \brief Request from the client for the server to call AddParticipantOnServer() - /// \pre The server must have called SetAcceptAddParticipantRequests(true) or the request will be ignored - /// \param[in] key A string to identify out system. Passed to \a key on AddParticipantOnServer() - /// \param[in] relayPluginServerGuid the RakNetGUID of the system running RelayPlugin - void AddParticipantRequestFromClient(const RakString &key, const RakNetGUID &relayPluginServerGuid); - - /// \brief Remove yourself as a participant - void RemoveParticipantRequestFromClient(const RakNetGUID &relayPluginServerGuid); - - /// \brief Request that the server relay \a bitStream to the system designated by \a key - /// \param[in] relayPluginServerGuid the RakNetGUID of the system running RelayPlugin - /// \param[in] destinationGuid The key value passed to AddParticipant() earlier on the server. If this was not done, the server will not relay the message (it will be silently discarded). - /// \param[in] bitStream The data to relay - /// \param[in] priority See the parameter of the same name in RakPeerInterface::Send() - /// \param[in] reliability See the parameter of the same name in RakPeerInterface::Send() - /// \param[in] orderingChannel See the parameter of the same name in RakPeerInterface::Send() - void SendToParticipant(const RakNetGUID &relayPluginServerGuid, const RakString &destinationGuid, BitStream *bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel); - - void SendGroupMessage(const RakNetGUID &relayPluginServerGuid, BitStream *bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel); - void JoinGroupRequest(const RakNetGUID &relayPluginServerGuid, RakString groupName); - void LeaveGroup(const RakNetGUID &relayPluginServerGuid); - void GetGroupList(const RakNetGUID &relayPluginServerGuid); - - /// \internal - virtual PluginReceiveResult OnReceive(Packet *packet); - /// \internal - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - - struct StrAndGuidAndRoom - { - RakString str; - RakNetGUID guid; - RakString currentRoom; - }; - - struct StrAndGuid - { - RakString str; - RakNetGUID guid; - }; - - struct RP_Group - { - RakString roomName; - DataStructures::List usersInRoom; - }; - -protected: - - RelayPlugin::RP_Group* JoinGroup(RakNetGUID userGuid, RakString roomName); - RelayPlugin::RP_Group* JoinGroup(RP_Group* room, StrAndGuidAndRoom **strAndGuidSender); - void LeaveGroup(StrAndGuidAndRoom **strAndGuidSender); - void NotifyUsersInRoom(RP_Group *room, int msg, const RakString& message); - void SendMessageToRoom(StrAndGuidAndRoom **strAndGuidSender, BitStream* message); - void SendChatRoomsList(RakNetGUID target); - void OnGroupMessageFromClient(Packet *packet); - void OnJoinGroupRequestFromClient(Packet *packet); - void OnLeaveGroupRequestFromClient(Packet *packet); - - DataStructures::Hash strToGuidHash; - DataStructures::Hash guidToStrHash; - DataStructures::List chatRooms; - bool acceptAddParticipantRequests; - -}; - -} // End namespace - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/ReliabilityLayer.h b/vendors/mafianet/Source/include/mafianet/ReliabilityLayer.h deleted file mode 100644 index 67979d049..000000000 --- a/vendors/mafianet/Source/include/mafianet/ReliabilityLayer.h +++ /dev/null @@ -1,648 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief \b [Internal] Datagram reliable, ordered, unordered and sequenced sends. Flow control. Message splitting, reassembly, and coalescence. -/// - - -#ifndef __RELIABILITY_LAYER_H -#define __RELIABILITY_LAYER_H - -#include "memoryoverride.h" -#include "MTUSize.h" -#include "DS_LinkedList.h" -#include "DS_List.h" -#include "SocketLayer.h" -#include "PacketPriority.h" -#include "DS_Queue.h" -#include "BitStream.h" -#include "InternalPacket.h" -#include "statistics.h" -#include "DR_SHA1.h" -#include "DS_OrderedList.h" -#include "DS_RangeList.h" -#include "DS_BPlusTree.h" -#include "DS_MemoryPool.h" -#include "defines.h" -#include "DS_Heap.h" -#include "BitStream.h" -#include "NativeFeatureIncludes.h" -#include "SecureHandshake.h" -#include "PluginInterface2.h" -#include "Rand.h" -#include "socket2.h" - -#if USE_SLIDING_WINDOW_CONGESTION_CONTROL!=1 -#include "CCRakNetUDT.h" -#define INCLUDE_TIMESTAMP_WITH_DATAGRAMS 1 -#else -#include "CCRakNetSlidingWindow.h" -#define INCLUDE_TIMESTAMP_WITH_DATAGRAMS 0 -#endif - -/// Number of ordered streams available. You can use up to 32 ordered streams -#define NUMBER_OF_ORDERED_STREAMS 32 // 2^5 - -#define RESEND_TREE_ORDER 32 - -namespace MafiaNet { - - /// Forward declarations -class PluginInterface2; -class RakNetRandom; -typedef uint64_t reliabilityHeapWeightType; - -// #med - consider a more suitable name for the class / maybe even make an internal class to SplitPacketChannel? -class SplitPacketSort -{ - // member variables -private: - InternalPacket **m_data; - size_t m_allocationSize; - unsigned int m_addedPacketsCount; - SplitPacketIdType m_packetId; - - // construction/destruction -public: - SplitPacketSort(); - ~SplitPacketSort(); - - // initialization -public: - void Preallocate(InternalPacket *internalPacket, const char *file, unsigned int line); - - // accessors -public: - bool AllPacketsAdded() const; - size_t GetAllocSize() const; - unsigned int GetNumAddedPackets() const; - SplitPacketIdType GetPacketId() const; - - // operators -public: - InternalPacket*& operator[](size_t index); - - // container operations -public: - bool Add(InternalPacket *internalPacket); -}; - -// int SplitPacketIndexComp( SplitPacketIndexType const &key, InternalPacket* const &data ); -struct SplitPacketChannel// -{ - CCTimeType lastUpdateTime; - - SplitPacketSort splitPacketList; - -#if PREALLOCATE_LARGE_MESSAGES==1 - InternalPacket *returnedPacket; - bool gotFirstPacket; - unsigned int stride; - unsigned int splitPacketsArrived; -#else - // This is here for progress notifications, since progress notifications return the first packet data, if available - InternalPacket *firstPacket; -#endif - -}; -int RAK_DLL_EXPORT SplitPacketChannelComp( SplitPacketIdType const &key, SplitPacketChannel* const &data ); - -// Helper class -struct BPSTracker -{ - BPSTracker(); - ~BPSTracker(); - void Reset(const char *file, unsigned int line); - inline void Push1(CCTimeType time, uint64_t value1) {dataQueue.Push(TimeAndValue2(time,value1),_FILE_AND_LINE_); total1+=value1; lastSec1+=value1;} -// void Push2(MafiaNet::TimeUS time, uint64_t value1, uint64_t value2); - inline uint64_t GetBPS1(CCTimeType time) {(void) time; return lastSec1;} - inline uint64_t GetBPS1Threadsafe(CCTimeType time) {(void) time; return lastSec1;} -// uint64_t GetBPS2(RakNetTimeUS time); -// void GetBPS1And2(RakNetTimeUS time, uint64_t &out1, uint64_t &out2); - uint64_t GetTotal1(void) const; -// uint64_t GetTotal2(void) const; - - struct TimeAndValue2 - { - TimeAndValue2(); - ~TimeAndValue2(); - TimeAndValue2(CCTimeType t, uint64_t v1); - // TimeAndValue2(MafiaNet::TimeUS t, uint64_t v1, uint64_t v2); - // uint64_t value1, value2; - uint64_t value1; - CCTimeType time; - }; - - uint64_t total1, lastSec1; -// uint64_t total2, lastSec2; - DataStructures::Queue dataQueue; - void ClearExpired1(CCTimeType time); -// void ClearExpired2(MafiaNet::TimeUS time); -}; - -/// Datagram reliable, ordered, unordered and sequenced sends. Flow control. Message splitting, reassembly, and coalescence. -class ReliabilityLayer// -{ -public: - - // Constructor - ReliabilityLayer(); - - // Destructor - ~ReliabilityLayer(); - - /// Resets the layer for reuse - void Reset(bool resetVariables, int mtuSize, bool _useSecurity); - - /// Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable packet - /// Default time is 10,000 or 10 seconds in release and 30,000 or 30 seconds in debug. - /// \param[in] time Time, in MS - void SetTimeoutTime(MafiaNet::TimeMS time); - - /// Returns the value passed to SetTimeoutTime. or the default if it was never called - /// \param[out] the value passed to SetTimeoutTime - MafiaNet::TimeMS GetTimeoutTime(void); - - /// Packets are read directly from the socket layer and skip the reliability layer because unconnected players do not use the reliability layer - /// This function takes packet data after a player has been confirmed as connected. - /// \param[in] buffer The socket data - /// \param[in] length The length of the socket data - /// \param[in] systemAddress The player that this data is from - /// \param[in] messageHandlerList A list of registered plugins - /// \param[in] mtuSize maximum datagram size - /// \retval true Success - /// \retval false Modified packet - bool HandleSocketReceiveFromConnectedPlayer( - const char *buffer, unsigned int length, SystemAddress &systemAddress, DataStructures::List &messageHandlerList, int mtuSize, - RakNetSocket2 *s, RakNetRandom *rnr, CCTimeType timeRead, BitStream &updateBitStream); - - /// This allocates bytes and writes a user-level message to those bytes. - /// \param[out] data The message - /// \return Returns number of BITS put into the buffer - BitSize_t Receive( unsigned char**data ); - - /// Puts data on the send queue - /// \param[in] data The data to send - /// \param[in] numberOfBitsToSend The length of \a data in bits - /// \param[in] priority The priority level for the send - /// \param[in] reliability The reliability type for the send - /// \param[in] orderingChannel 0 to 31. Specifies what channel to use, for relational ordering and sequencing of packets. - /// \param[in] makeDataCopy If true \a data will be copied. Otherwise, only a pointer will be stored. - /// \param[in] MTUSize maximum datagram size - /// \param[in] currentTime Current time, as per MafiaNet::GetTimeMS() - /// \param[in] receipt This number will be returned back with ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS and is only returned with the reliability types that contain RECEIPT in the name - /// \return True or false for success or failure. - bool Send( char *data, BitSize_t numberOfBitsToSend, MafiaNet::Priority priority, MafiaNet::Reliability reliability, unsigned char orderingChannel, bool makeDataCopy, int MTUSize, CCTimeType currentTime, uint32_t receipt ); - - /// Call once per game cycle. Handles internal lists and actually does the send. - /// \param[in] s the communication end point - /// \param[in] systemAddress The Unique Player Identifier who shouldhave sent some packets - /// \param[in] MTUSize maximum datagram size - /// \param[in] time current system time - /// \param[in] maxBitsPerSecond if non-zero, enforces that outgoing bandwidth does not exceed this amount - /// \param[in] messageHandlerList A list of registered plugins - void Update( RakNetSocket2 *s, SystemAddress &systemAddress, int MTUSize, CCTimeType time, - unsigned bitsPerSecondLimit, - DataStructures::List &messageHandlerList, - RakNetRandom *rnr, BitStream &updateBitStream ); - - // #med 0.2.0 - review whether we'd rather have this defined as a private method and declare RakPeer a friend of ReliabilityLayer - /// @since 0.2.0: added - /// Same as \see Update() except that outstanding ACKs are ensured to be sent. - void UpdateAndForceACKs( RakNetSocket2 *s, SystemAddress &systemAddress, int MTUSize, CCTimeType time, - unsigned bitsPerSecondLimit, - DataStructures::List &messageHandlerList, - RakNetRandom *rnr, BitStream &updateBitStream ); - - /// Were you ever unable to deliver a packet despite retries? - /// \return true means the connection has been lost. Otherwise not. - bool IsDeadConnection( void ) const; - - /// Causes IsDeadConnection to return true - void KillConnection(void); - - /// Get Statistics - /// \return A pointer to a static struct, filled out with current statistical information. - RakNetStatistics * GetStatistics( RakNetStatistics *rns ); - - ///Are we waiting for any data to be sent out or be processed by the player? - bool IsOutgoingDataWaiting(void); - bool AreAcksWaiting(void); - - // Set outgoing lag and packet loss properties - void ApplyNetworkSimulator( double _maxSendBPS, MafiaNet::TimeMS _minExtraPing, MafiaNet::TimeMS _extraPingVariance ); - - /// Returns if you previously called ApplyNetworkSimulator - /// \return If you previously called ApplyNetworkSimulator - bool IsNetworkSimulatorActive( void ); - - void SetSplitMessageProgressInterval(int interval); - void SetUnreliableTimeout(MafiaNet::TimeMS timeoutMS); - /// Has a lot of time passed since the last ack - bool AckTimeout(MafiaNet::Time curTime); - CCTimeType GetNextSendTime(void) const; - CCTimeType GetTimeBetweenPackets(void) const; -#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 - CCTimeType GetAckPing(void) const; -#endif - MafiaNet::TimeMS GetTimeLastDatagramArrived(void) const {return timeLastDatagramArrived;} - - // If true, will update time between packets quickly based on ping calculations - //void SetDoFastThroughputReactions(bool fast); - - // Encoded as numMessages[unsigned int], message1BitLength[unsigned int], message1Data (aligned), ... - //void GetUndeliveredMessages(MafiaNet::BitStream *messages, int MTUSize); - -private: - /// Send the contents of a bitstream to the socket - /// \param[in] s The socket used for sending data - /// \param[in] systemAddress The address and port to send to - /// \param[in] bitStream The data to send. - void SendBitStream( RakNetSocket2 *s, SystemAddress &systemAddress, MafiaNet::BitStream *bitStream, RakNetRandom *rnr, CCTimeType currentTime); - - ///Parse an internalPacket and create a bitstream to represent this data - /// \return Returns number of bits used - BitSize_t WriteToBitStreamFromInternalPacket(MafiaNet::BitStream *bitStream, const InternalPacket *const internalPacket, CCTimeType curTime ); - - - /// Parse a bitstream and create an internal packet to represent this data - InternalPacket* CreateInternalPacketFromBitStream(MafiaNet::BitStream *bitStream, CCTimeType time ); - - /// Does what the function name says - unsigned RemovePacketFromResendListAndDeleteOlderReliableSequenced( const MessageNumberType messageNumber, CCTimeType time, DataStructures::List &messageHandlerList, const SystemAddress &systemAddress ); - - /// Acknowledge receipt of the packet with the specified messageNumber - void SendAcknowledgementPacket( const DatagramSequenceNumberType messageNumber, CCTimeType time); - - /// This will return true if we should not send at this time - bool IsSendThrottled( int MTUSize ); - - /// We lost a packet - void UpdateWindowFromPacketloss( CCTimeType time ); - - /// Increase the window size - void UpdateWindowFromAck( CCTimeType time ); - - /// Parse an internalPacket and figure out how many header bits would be written. Returns that number - BitSize_t GetMaxMessageHeaderLengthBits( void ); - BitSize_t GetMessageHeaderLengthBits( const InternalPacket *const internalPacket ); - - /// Get the SHA1 code - void GetSHA1( unsigned char * const buffer, unsigned int nbytes, char code[ SHA1_LENGTH ] ); - - /// Check the SHA1 code - bool CheckSHA1( char code[ SHA1_LENGTH ], unsigned char * const buffer, unsigned int nbytes ); - - /// Search the specified list for sequenced packets on the specified ordering channel, optionally skipping those with splitPacketId, and delete them -// void DeleteSequencedPacketsInList( unsigned char orderingChannel, DataStructures::List&theList, int splitPacketId = -1 ); - - /// Search the specified list for sequenced packets with a value less than orderingIndex and delete them -// void DeleteSequencedPacketsInList( unsigned char orderingChannel, DataStructures::Queue&theList ); - - /// Returns true if newPacketOrderingIndex is older than the waitingForPacketOrderingIndex - bool IsOlderOrderedPacket( OrderingIndexType newPacketOrderingIndex, OrderingIndexType waitingForPacketOrderingIndex ); - - /// Split the passed packet into chunks under MTU_SIZE bytes (including headers) and save those new chunks - void SplitPacket( InternalPacket *internalPacket ); - - /// Insert a packet into the split packet list - void InsertIntoSplitPacketList( InternalPacket * internalPacket, CCTimeType time ); - - /// Take all split chunks with the specified splitPacketId and try to reconstruct a packet. If we can, allocate and return it. Otherwise return 0 - InternalPacket * BuildPacketFromSplitPacketList( SplitPacketIdType inSplitPacketId, CCTimeType time, - RakNetSocket2 *s, SystemAddress &systemAddress, RakNetRandom *rnr, BitStream &updateBitStream); - InternalPacket * BuildPacketFromSplitPacketList( SplitPacketChannel *splitPacketChannel, CCTimeType time ); - - /// Delete any unreliable split packets that have long since expired - //void DeleteOldUnreliableSplitPackets( CCTimeType time ); - - /// Creates a copy of the specified internal packet with data copied from the original starting at dataByteOffset for dataByteLength bytes. - /// Does not copy any split data parameters as that information is always generated does not have any reason to be copied - InternalPacket * CreateInternalPacketCopy( InternalPacket *original, int dataByteOffset, int dataByteLength, CCTimeType time ); - - /// Get the specified ordering list - // DataStructures::LinkedList *GetOrderingListAtOrderingStream( unsigned char orderingChannel ); - - /// Add the internal packet to the ordering list in order based on order index - // void AddToOrderingList( InternalPacket * internalPacket ); - - /// Inserts a packet into the resend list in order - void InsertPacketIntoResendList( InternalPacket *internalPacket, CCTimeType time, bool firstResend, bool modifyUnacknowledgedBytes ); - - /// Memory handling - void FreeMemory( bool freeAllImmediately ); - - /// Memory handling - void FreeThreadSafeMemory( void ); - - // Initialize the variables - void InitializeVariables( void ); - - /// Given the current time, is this time so old that we should consider it a timeout? - bool IsExpiredTime(unsigned int input, CCTimeType currentTime) const; - - // Make it so we don't do resends within a minimum threshold of time - void UpdateNextActionTime(void); - - void UpdateInternal( RakNetSocket2 *s, SystemAddress &systemAddress, int MTUSize, CCTimeType time, - unsigned bitsPerSecondLimit, - DataStructures::List &messageHandlerList, - RakNetRandom *rnr, BitStream &updateBitStream, bool forceSendACKs ); - - /// Does this packet number represent a packet that was skipped (out of order?) - //unsigned int IsReceivedPacketHole(unsigned int input, MafiaNet::TimeMS currentTime) const; - - /// Skip an element in the received packets list - //unsigned int MakeReceivedPacketHole(unsigned int input) const; - - /// How many elements are waiting to be resent? - unsigned int GetResendListDataSize(void) const; - - /// Update all memory which is not threadsafe - void UpdateThreadedMemory(void); - - void CalculateHistogramAckSize(void); - - // Used ONLY for MafiaNet::Reliability::ReliableOrdered - // MafiaNet::Reliability::ReliableSequenced just returns the newest one - // DataStructures::List*> orderingList; - DataStructures::Queue outputQueue; - int splitMessageProgressInterval; - CCTimeType unreliableTimeout; - - struct MessageNumberNode - { - DatagramSequenceNumberType messageNumber; - MessageNumberNode *next; - }; - struct DatagramHistoryNode - { - DatagramHistoryNode() {} - DatagramHistoryNode(MessageNumberNode *_head, CCTimeType ts - ) : - head(_head), timeSent(ts) - {} - MessageNumberNode *head; - CCTimeType timeSent; - }; - // Queue length is programmatically restricted to DATAGRAM_MESSAGE_ID_ARRAY_LENGTH - // This is essentially an O(1) lookup to get a DatagramHistoryNode given an index - // datagramHistory holds a linked list of MessageNumberNode. Each MessageNumberNode refers to one element in resendList which can be cleared on an ack. - DataStructures::Queue datagramHistory; - DataStructures::MemoryPool datagramHistoryMessagePool; - - struct UnreliableWithAckReceiptNode - { - UnreliableWithAckReceiptNode() {} - UnreliableWithAckReceiptNode(DatagramSequenceNumberType _datagramNumber, uint32_t _sendReceiptSerial, MafiaNet::TimeUS _nextActionTime) : - datagramNumber(_datagramNumber), sendReceiptSerial(_sendReceiptSerial), nextActionTime(_nextActionTime) - {} - DatagramSequenceNumberType datagramNumber; - uint32_t sendReceiptSerial; - MafiaNet::TimeUS nextActionTime; - }; - DataStructures::List unreliableWithAckReceiptHistory; - - void RemoveFromDatagramHistory(DatagramSequenceNumberType index); - MessageNumberNode* GetMessageNumberNodeByDatagramIndex(DatagramSequenceNumberType index, CCTimeType *timeSent); - void AddFirstToDatagramHistory(DatagramSequenceNumberType datagramNumber, CCTimeType timeSent); - MessageNumberNode* AddFirstToDatagramHistory(DatagramSequenceNumberType datagramNumber, DatagramSequenceNumberType messageNumber, CCTimeType timeSent); - MessageNumberNode* AddSubsequentToDatagramHistory(MessageNumberNode *messageNumberNode, DatagramSequenceNumberType messageNumber); - DatagramSequenceNumberType datagramHistoryPopCount; - - DataStructures::MemoryPool internalPacketPool; - // DataStructures::BPlusTree resendTree; - InternalPacket *resendBuffer[RESEND_BUFFER_ARRAY_LENGTH]; - InternalPacket *resendLinkedListHead; - InternalPacket *unreliableLinkedListHead; - void RemoveFromUnreliableLinkedList(InternalPacket *internalPacket); - void AddToUnreliableLinkedList(InternalPacket *internalPacket); -// unsigned int numPacketsOnResendBuffer; - //unsigned int blockWindowIncreaseUntilTime; - // DataStructures::RangeList acknowlegements; - // Resend list is a tree of packets we need to resend - - // Set to the current time when the resend queue is no longer empty - // Set to zero when it becomes empty - // Set to the current time if it is not zero, and we get incoming data - // If the current time - timeResendQueueNonEmpty is greater than a threshold, we are disconnected -// CCTimeType timeResendQueueNonEmpty; - MafiaNet::TimeMS timeLastDatagramArrived; - - - // If we backoff due to packetloss, don't remeasure until all waiting resends have gone out or else we overcount -// bool packetlossThisSample; -// int backoffThisSample; -// unsigned packetlossThisSampleResendCount; -// CCTimeType lastPacketlossTime; - - //DataStructures::Queue sendPacketSet[ MafiaNet::NUMBER_OF_PRIORITIES ]; - DataStructures::Heap outgoingPacketBuffer; - reliabilityHeapWeightType outgoingPacketBufferNextWeights[MafiaNet::NUMBER_OF_PRIORITIES]; - void InitHeapWeights(void); - reliabilityHeapWeightType GetNextWeight(int priorityLevel); -// unsigned int messageInSendBuffer[MafiaNet::NUMBER_OF_PRIORITIES]; -// double bytesInSendBuffer[MafiaNet::NUMBER_OF_PRIORITIES]; - - - DataStructures::OrderedList splitPacketChannelList; - - MessageNumberType sendReliableMessageNumberIndex; - MessageNumberType internalOrderIndex; - //unsigned int windowSize; - //MafiaNet::BitStream updateBitStream; - bool deadConnection, cheater; - SplitPacketIdType splitPacketId; - MafiaNet::TimeMS timeoutTime; // How long to wait in MS before timing someone out - //int MAX_AVERAGE_PACKETS_PER_SECOND; // Name says it all -// int RECEIVED_PACKET_LOG_LENGTH, requestedReceivedPacketLogLength; // How big the receivedPackets array is -// unsigned int *receivedPackets; - RakNetStatistics statistics; - - // Algorithm for blending ordered and sequenced on the same channel: - // 1. Each ordered message transmits OrderingIndexType orderedWriteIndex. There are NUMBER_OF_ORDERED_STREAMS independent values of these. The value - // starts at 0. Every time an ordered message is sent, the value increments by 1 - // 2. Each sequenced message contains the current value of orderedWriteIndex for that channel, and additionally OrderingIndexType sequencedWriteIndex. - // sequencedWriteIndex resets to 0 every time orderedWriteIndex increments. It increments by 1 every time a sequenced message is sent. - // 3. The receiver maintains the next expected value for the orderedWriteIndex, stored in orderedReadIndex. - // 4. As messages arrive: - // If a message has the current ordering index, and is sequenced, and is < the current highest sequence value, discard - // If a message has the current ordering index, and is sequenced, and is >= the current highest sequence value, return immediately - // If a message has a greater ordering index, and is sequenced or ordered, buffer it - // If a message has the current ordering index, and is ordered, buffer, then push off messages from buffer - // 5. Pushing off messages from buffer: - // Messages in buffer are put in a minheap. The value of each node is calculated such that messages are returned: - // A. (lowest ordering index, lowest sequence index) - // B. (lowest ordering index, no sequence index) - // Messages are pushed off until the heap is empty, or the next message to be returned does not preserve the ordered index - // For an empty heap, the heap weight should start at the lowest value based on the next expected ordering index, to avoid variable overflow - - // Sender increments this by 1 for every ordered message sent - OrderingIndexType orderedWriteIndex[NUMBER_OF_ORDERED_STREAMS]; - // Sender increments by 1 for every sequenced message sent. Resets to 0 when an ordered message is sent - OrderingIndexType sequencedWriteIndex[NUMBER_OF_ORDERED_STREAMS]; - // Next expected index for ordered messages. - OrderingIndexType orderedReadIndex[NUMBER_OF_ORDERED_STREAMS]; - // Highest value received for sequencedWriteIndex for the current value of orderedReadIndex on the same channel. - OrderingIndexType highestSequencedReadIndex[NUMBER_OF_ORDERED_STREAMS]; - DataStructures::Heap orderingHeaps[NUMBER_OF_ORDERED_STREAMS]; - OrderingIndexType heapIndexOffsets[NUMBER_OF_ORDERED_STREAMS]; - - - - - - - -// CCTimeType histogramStart; -// unsigned histogramBitsSent; - - - /// Memory-efficient receivedPackets algorithm: - /// receivedPacketsBaseIndex is the packet number we are expecting - /// Everything under receivedPacketsBaseIndex is a packet we already got - /// Everything over receivedPacketsBaseIndex is stored in hasReceivedPacketQueue - /// It stores the time to stop waiting for a particular packet number, where the packet number is receivedPacketsBaseIndex + the index into the queue - /// If 0, we got got that packet. Otherwise, the time to give up waiting for that packet. - /// If we get a packet number where (receivedPacketsBaseIndex-packetNumber) is less than half the range of receivedPacketsBaseIndex then it is a duplicate - /// Otherwise, it is a duplicate packet (and ignore it). - // DataStructures::Queue hasReceivedPacketQueue; - DataStructures::Queue hasReceivedPacketQueue; - DatagramSequenceNumberType receivedPacketsBaseIndex; - bool resetReceivedPackets; - - CCTimeType lastUpdateTime; - CCTimeType timeBetweenPackets, nextSendTime; -#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 - CCTimeType ackPing; -#endif -// CCTimeType ackPingSamples[ACK_PING_SAMPLES_SIZE]; // Must be range of unsigned char to wrap ackPingIndex properly - CCTimeType ackPingSum; - unsigned char ackPingIndex; - //CCTimeType nextLowestPingReset; - RemoteSystemTimeType remoteSystemTime; -// bool continuousSend; -// CCTimeType lastTimeBetweenPacketsIncrease,lastTimeBetweenPacketsDecrease; - // Limit changes in throughput to once per ping - otherwise even if lag starts we don't know about it - // In the meantime the connection is flooded and overrun. - CCTimeType nextAllowedThroughputSample; - bool bandwidthExceededStatistic; - - // If Update::maxBitsPerSecond > 0, then throughputCapCountdown is used as a timer to prevent sends for some amount of time after each send, depending on - // the amount of data sent - long long throughputCapCountdown; - - unsigned receivePacketCount; - -#ifdef _DEBUG - struct DataAndTime// - { - RakNetSocket2 *s; - char data[ MAXIMUM_MTU_SIZE ]; - unsigned int length; - MafiaNet::TimeMS sendTime; - // SystemAddress systemAddress; - unsigned short remotePortRakNetWasStartedOn_PS3; - unsigned int extraSocketOptions; - }; - DataStructures::Queue delayList; - - // Internet simulator - double packetloss; - MafiaNet::TimeMS minExtraPing, extraPingVariance; -#endif - - CCTimeType elapsedTimeSinceLastUpdate; - - CCTimeType nextAckTimeToSend; - - -#if USE_SLIDING_WINDOW_CONGESTION_CONTROL==1 - MafiaNet::CCRakNetSlidingWindow congestionManager; -#else - MafiaNet::CCRakNetUDT congestionManager; -#endif - - - uint32_t unacknowledgedBytes; - - bool ResendBufferOverflow(void) const; - void ValidateResendList(void) const; - void ResetPacketsAndDatagrams(void); - void PushPacket(CCTimeType time, InternalPacket *internalPacket, bool isReliable); - void PushDatagram(void); - bool TagMostRecentPushAsSecondOfPacketPair(void); - void ClearPacketsAndDatagrams(void); - void MoveToListHead(InternalPacket *internalPacket); - void RemoveFromList(InternalPacket *internalPacket, bool modifyUnacknowledgedBytes); - void AddToListTail(InternalPacket *internalPacket, bool modifyUnacknowledgedBytes); - void PopListHead(bool modifyUnacknowledgedBytes); - bool IsResendQueueEmpty(void) const; - void SortSplitPacketList(DataStructures::List &data, unsigned int leftEdge, unsigned int rightEdge) const; - void SendACKs(RakNetSocket2 *s, SystemAddress &systemAddress, CCTimeType time, RakNetRandom *rnr, BitStream &updateBitStream); - - DataStructures::List packetsToSendThisUpdate; - DataStructures::List packetsToDeallocThisUpdate; - // boundary is in packetsToSendThisUpdate, inclusive - DataStructures::List packetsToSendThisUpdateDatagramBoundaries; - DataStructures::List datagramsToSendThisUpdateIsPair; - DataStructures::List datagramSizesInBytes; - BitSize_t datagramSizeSoFar; - BitSize_t allDatagramSizesSoFar; - double totalUserDataBytesAcked; - CCTimeType timeOfLastContinualSend; - CCTimeType timeToNextUnreliableCull; - - // This doesn't need to be a member, but I do it to avoid reallocations - DataStructures::RangeList incomingAcks; - - // Every 16 datagrams, we make sure the 17th datagram goes out the same update tick, and is the same size as the 16th - int countdownToNextPacketPair; - InternalPacket* AllocateFromInternalPacketPool(void); - void ReleaseToInternalPacketPool(InternalPacket *ip); - - DataStructures::RangeList acknowlegements; - DataStructures::RangeList NAKs; - bool remoteSystemNeedsBAndAS; - - unsigned int GetMaxDatagramSizeExcludingMessageHeaderBytes(void); - BitSize_t GetMaxDatagramSizeExcludingMessageHeaderBits(void); - - // ourOffset refers to a section within externallyAllocatedPtr. Do not deallocate externallyAllocatedPtr until all references are lost - void AllocInternalPacketData(InternalPacket *internalPacket, InternalPacketRefCountedData **refCounter, unsigned char *externallyAllocatedPtr, unsigned char *ourOffset); - // Set the data pointer to externallyAllocatedPtr, do not allocate - void AllocInternalPacketData(InternalPacket *internalPacket, unsigned char *externallyAllocatedPtr); - // Allocate new - void AllocInternalPacketData(InternalPacket *internalPacket, unsigned int numBytes, bool allowStack, const char *file, unsigned int line); - void FreeInternalPacketData(InternalPacket *internalPacket, const char *file, unsigned int line); - DataStructures::MemoryPool refCountedDataPool; - - BPSTracker bpsMetrics[RNS_PER_SECOND_METRICS_COUNT]; - CCTimeType lastBpsClear; - -#if LIBCAT_SECURITY==1 -public: - cat::AuthenticatedEncryption* GetAuthenticatedEncryption(void) { return &auth_enc; } - -protected: - cat::AuthenticatedEncryption auth_enc; - bool useSecurity; -#endif // LIBCAT_SECURITY -}; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/ReplicaEnums.h b/vendors/mafianet/Source/include/mafianet/ReplicaEnums.h deleted file mode 100644 index 6716ae06f..000000000 --- a/vendors/mafianet/Source/include/mafianet/ReplicaEnums.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -/// \file -/// \brief Contains enumerations used by the ReplicaManager system. This file is a lightweight header, so you can include it without worrying about linking in lots of other crap -/// - - - -#ifndef __REPLICA_ENUMS_H -#define __REPLICA_ENUMS_H - -/// Replica interface flags, used to enable and disable function calls on the Replica object -/// Passed to ReplicaManager::EnableReplicaInterfaces and ReplicaManager::DisableReplicaInterfaces -enum -{ - REPLICA_RECEIVE_DESTRUCTION=1<<0, - REPLICA_RECEIVE_SERIALIZE=1<<1, - REPLICA_RECEIVE_SCOPE_CHANGE=1<<2, - REPLICA_SEND_CONSTRUCTION=1<<3, - REPLICA_SEND_DESTRUCTION=1<<4, - REPLICA_SEND_SCOPE_CHANGE=1<<5, - REPLICA_SEND_SERIALIZE=1<<6, - REPLICA_SET_ALL = 0xFF // Allow all of the above -}; - -enum ReplicaReturnResult -{ - /// This means call the function again later, with the same parameters - REPLICA_PROCESS_LATER, - /// This means we are done processing (the normal result to return) - REPLICA_PROCESSING_DONE, - /// This means cancel the processing - don't send any network messages and don't change the current state. - REPLICA_CANCEL_PROCESS, - /// Same as REPLICA_PROCESSING_DONE, where a message is sent, but does not clear the send bit. - /// Useful for multi-part sends with different reliability levels. - /// Only currently used by Replica::Serialize - REPLICA_PROCESS_AGAIN, - /// Only returned from the Replica::SendConstruction interface, means act as if the other system had this object but don't actually - /// Send a construction packet. This way you will still send scope and serialize packets to that system - REPLICA_PROCESS_IMPLICIT -}; - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/ReplicaManager3.h b/vendors/mafianet/Source/include/mafianet/ReplicaManager3.h deleted file mode 100644 index 790aead37..000000000 --- a/vendors/mafianet/Source/include/mafianet/ReplicaManager3.h +++ /dev/null @@ -1,1187 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Contains the third iteration of the ReplicaManager class. -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_ReplicaManager3==1 - -#ifndef __REPLICA_MANAGER_3 -#define __REPLICA_MANAGER_3 - -#include "types.h" -#include "time.h" -#include "BitStream.h" -#include "PacketPriority.h" -#include "PluginInterface2.h" -#include "NetworkIDObject.h" -#include "DS_OrderedList.h" -#include "DS_Queue.h" -#include "SimpleMutex.h" -#include "VirtualWorld.h" - -/// \defgroup REPLICA_MANAGER_GROUP3 ReplicaManager3 -/// \brief Third implementation of object replication -/// \details -/// \ingroup PLUGINS_GROUP - -namespace MafiaNet -{ -class Connection_RM3; -class Replica3; -class VirtualWorldReplica3; - -/// \ingroup REPLICA_MANAGER_GROUP3 -/// Used for multiple worlds. World 0 is created automatically by default -typedef uint8_t WorldId; - - -/// \internal -/// \ingroup REPLICA_MANAGER_GROUP3 -struct PRO -{ - /// Passed to RakPeerInterface::Send(). Defaults to ReplicaManager3::SetDefaultPacketPriority(). - MafiaNet::Priority priority; - - /// Passed to RakPeerInterface::Send(). Defaults to ReplicaManager3::SetDefaultPacketReliability(). - MafiaNet::Reliability reliability; - - /// Passed to RakPeerInterface::Send(). Defaults to ReplicaManager3::SetDefaultOrderingChannel(). - char orderingChannel; - - /// Passed to RakPeerInterface::Send(). Defaults to 0. - uint32_t sendReceipt; - - bool operator==( const PRO& right ) const; - bool operator!=( const PRO& right ) const; -}; - - -/// \brief System to help automate game object construction, destruction, and serialization -/// \details ReplicaManager3 tracks your game objects and automates the networking for replicating them across the network
-/// As objects are created, destroyed, or serialized differently, those changes are pushed out to other systems.
-/// To use:
-///
    -///
  1. Derive from Connection_RM3 and implement Connection_RM3::AllocReplica(). This is a factory function where given a user-supplied identifier for a class (such as name) return an instance of that class. Should be able to return any networked object in your game. -///
  2. Derive from ReplicaManager3 and implement AllocConnection() and DeallocConnection() to return the class you created in step 1. -///
  3. Derive your networked game objects from Replica3. All pure virtuals have to be implemented, however defaults are provided for Replica3::QueryConstruction(), Replica3::QueryRemoteConstruction(), and Replica3::QuerySerialization() depending on your network architecture. -///
  4. When a new game object is created on the local system, pass it to ReplicaManager3::Reference(). -///
  5. When a game object is destroyed on the local system, and you want other systems to know about it, call Replica3::BroadcastDestruction() -///
-///
-/// At this point, all new connections will automatically download, get construction messages, get destruction messages, and update serialization automatically. -/// \ingroup REPLICA_MANAGER_GROUP3 -class RAK_DLL_EXPORT ReplicaManager3 : public PluginInterface2 -{ -public: - ReplicaManager3(); - virtual ~ReplicaManager3(); - - /// \brief Implement to return a game specific derivation of Connection_RM3 - /// \details The connection object represents a remote system connected to you that is using the ReplicaManager3 system.
- /// It has functions to perform operations per-connection.
- /// AllocConnection() and DeallocConnection() are factory functions to create and destroy instances of the connection object.
- /// It is used if autoCreate is true via SetAutoManageConnections() (true by default). Otherwise, the function is not called, and you will have to call PushConnection() manually
- /// \note If you do not want a new network connection to immediately download game objects, SetAutoManageConnections() and PushConnection() are how you do this. - /// \sa SetAutoManageConnections() - /// \param[in] systemAddress Address of the system you are adding - /// \param[in] rakNetGUID GUID of the system you are adding. See Packet::rakNetGUID or RakPeerInterface::GetGUIDFromSystemAddress() - /// \return The new connection instance. - virtual Connection_RM3* AllocConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID) const=0; - - /// \brief Implement to destroy a class instanced returned by AllocConnection() - /// \details Most likely just implement as {delete connection;}
- /// It is used if autoDestroy is true via SetAutoManageConnections() (true by default). Otherwise, the function is not called and you would then be responsible for deleting your own connection objects. - /// \param[in] connection The pointer instance to delete - virtual void DeallocConnection(Connection_RM3 *connection) const=0; - - /// \brief Enable or disable automatically assigning connections to new instances of Connection_RM3 - /// \details ReplicaManager3 can automatically create and/or destroy Connection_RM3 as systems connect or disconnect from RakPeerInterface.
- /// By default this is on, to make the system easier to learn and setup.
- /// If you don't want all connections to take part in the game, or you want to delay when a connection downloads the game, set \a autoCreate to false.
- /// If you want to delay deleting a connection that has dropped, set \a autoDestroy to false. If you do this, then you must call PopConnection() to remove that connection from being internally tracked. You'll also have to delete the connection instance on your own.
- /// \param[in] autoCreate Automatically call ReplicaManager3::AllocConnection() for each new connection. Defaults to true. Also see AutoCreateConnectionList() - /// \param[in] autoDestroy Automatically call ReplicaManager3::DeallocConnection() for each dropped connection. Defaults to true. - void SetAutoManageConnections(bool autoCreate, bool autoDestroy); - - /// \return What was passed to the autoCreate parameter of SetAutoManageConnections() - bool GetAutoCreateConnections(void) const; - - /// \return What was passed to the autoDestroy parameter of SetAutoManageConnections() - bool GetAutoDestroyConnections(void) const; - - /// \brief Call AllocConnection() and PushConnection() for each connection in \a participantList - /// \param[in] participantListIn The list of connections to allocate - /// \param[in] participantListOut The connections allocated, if any - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - void AutoCreateConnectionList( - DataStructures::List &participantListIn, - DataStructures::List &participantListOut, - WorldId worldId=0); - - /// \brief Track a new Connection_RM3 instance - /// \details If \a autoCreate is false for SetAutoManageConnections(), then you need this function to add new instances of Connection_RM3 yourself.
- /// You don't need to track this pointer yourself, you can get it with GetConnectionAtIndex(), GetConnectionByGUID(), or GetConnectionBySystemAddress().
- /// \param[in] newConnection The new connection instance to track. - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - bool PushConnection(MafiaNet::Connection_RM3 *newConnection, WorldId worldId=0); - - /// \brief Stop tracking a connection - /// \details On call, for each replica returned by GetReplicasCreatedByGuid(), QueryActionOnPopConnection() will be called. Depending on the return value, this may delete the corresponding replica.
- /// If autoDestroy is true in the call to SetAutoManageConnections() (true by default) then this is called automatically when the connection is lost. In that case, the returned connection instance is deleted.
- /// \param[in] guid of the connection to get. Passed to ReplicaManager3::AllocConnection() originally. - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - MafiaNet::Connection_RM3 * PopConnection(RakNetGUID guid, WorldId worldId=0); - - /// \brief Adds a replicated object to the system. - /// \details Anytime you create a new object that derives from Replica3, and you want ReplicaManager3 to use it, pass it to Reference().
- /// Remote systems already connected will potentially download this object the next time ReplicaManager3::Update() is called, which happens every time you call RakPeerInterface::Receive().
- /// You can also call ReplicaManager3::Update() manually to send referenced objects right away - /// \param[in] replica3 The object to start tracking - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - void Reference(MafiaNet::Replica3 *replica3, WorldId worldId=0); - - /// \brief Removes a replicated object from the system. - /// \details The object is not deallocated, it is up to the caller to do so.
- /// This is called automatically from the destructor of Replica3, so you don't need to call it manually unless you want to stop tracking an object before it is destroyed. - /// \param[in] replica3 The object to stop tracking - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - void Dereference(MafiaNet::Replica3 *replica3, WorldId worldId=0); - - /// \brief Removes multiple replicated objects from the system. - /// \details Same as Dereference(), but for a list of objects.
- /// Useful with the lists returned by GetReplicasCreatedByGuid(), GetReplicasCreatedByMe(), or GetReferencedReplicaList().
- /// \param[in] replicaListIn List of objects - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - void DereferenceList(DataStructures::List &replicaListIn, WorldId worldId=0); - - /// \brief Returns all objects originally created by a particular system - /// \details Originally created is defined as the value of Replica3::creatingSystemGUID, which is automatically assigned in ReplicaManager3::Reference().
- /// You do not have to be directly connected to that system to get the objects originally created by that system.
- /// \param[in] guid GUID of the system we are referring to. Originally passed as the \a guid parameter to ReplicaManager3::AllocConnection() - /// \param[out] List of Replica3 instances to be returned - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - void GetReplicasCreatedByGuid(RakNetGUID guid, DataStructures::List &replicaListOut, WorldId worldId=0); - - /// \brief Returns all objects originally created by your system - /// \details Calls GetReplicasCreatedByGuid() for your own system guid. - /// \param[out] List of Replica3 instances to be returned - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - void GetReplicasCreatedByMe(DataStructures::List &replicaListOut, WorldId worldId=0); - - /// \brief Returns the entire list of Replicas that we know about. - /// \details This is all Replica3 instances passed to Reference, as well as instances we downloaded and created via Connection_RM3::AllocReference() - /// \param[out] List of Replica3 instances to be returned - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - void GetReferencedReplicaList(DataStructures::List &replicaListOut, WorldId worldId=0); - - /// \brief Returns the number of replicas known about - /// \details Returns the size of the list that would be returned by GetReferencedReplicaList() - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - /// \return How many replica objects are in the list of replica objects - unsigned GetReplicaCount(WorldId worldId=0) const; - - /// \brief Returns a replica by index - /// \details Returns one of the items in the list that would be returned by GetReferencedReplicaList() - /// \param[in] index An index, from 0 to GetReplicaCount()-1. - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - /// \return A Replica3 instance - Replica3 *GetReplicaAtIndex(unsigned index, WorldId worldId=0) const; - - /// \brief Returns the number of connections - /// \details Returns the number of connections added with ReplicaManager3::PushConnection(), minus the number removed with ReplicaManager3::PopConnection() - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - /// \return The number of registered connections - unsigned int GetConnectionCount(WorldId worldId=0) const; - - /// \brief Returns a connection pointer previously added with PushConnection() - /// \param[in] index An index, from 0 to GetConnectionCount()-1. - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - /// \return A Connection_RM3 pointer - Connection_RM3* GetConnectionAtIndex(unsigned index, WorldId worldId=0) const; - - /// \brief Returns a connection pointer previously added with PushConnection() - /// \param[in] sa The system address of the connection to return - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - /// \return A Connection_RM3 pointer, or 0 if not found - Connection_RM3* GetConnectionBySystemAddress(const SystemAddress &sa, WorldId worldId=0) const; - - /// \brief Returns a connection pointer previously added with PushConnection.() - /// \param[in] guid The guid of the connection to return - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - /// \return A Connection_RM3 pointer, or 0 if not found - Connection_RM3* GetConnectionByGUID(RakNetGUID guid, WorldId worldId=0) const; - - /// \brief Return the connections (observers) currently in a given virtual world. - /// \details Recipient-filter helper for scoping non-replica traffic (chat, RPC4, - /// raw Send) by virtual world. See VirtualWorld.h for the dimension model. - /// \param[in] virtualWorld The virtual world to match. See SetPlayerVirtualWorld() and Connection_RM3::SetVirtualWorld() - /// \param[out] connectionsOut Populated with the matching connections (cleared first) - /// \param[in] includeGlobal If true, also include observers in VIRTUAL_WORLD_GLOBAL - /// \param[in] worldId Which RM3 world to look in. World 0 by default. See AddWorld() - void GetConnectionsInVirtualWorld(VirtualWorldId virtualWorld, DataStructures::List &connectionsOut, bool includeGlobal=true, WorldId worldId=0) const; - - /// \brief Return the guids of the connections (observers) currently in a given virtual world. - /// \details Same as GetConnectionsInVirtualWorld() but returns guids, convenient for addressing RakPeerInterface::Send(). - /// \param[in] virtualWorld The virtual world to match - /// \param[out] guidsOut Populated with the matching guids (cleared first) - /// \param[in] includeGlobal If true, also include observers in VIRTUAL_WORLD_GLOBAL - /// \param[in] worldId Which RM3 world to look in. World 0 by default. See AddWorld() - void GetGuidsInVirtualWorld(VirtualWorldId virtualWorld, DataStructures::List &guidsOut, bool includeGlobal=true, WorldId worldId=0) const; - - /// \brief Convenience to move a player to a virtual world: sets both the observer's - /// virtual world (what they see) and their avatar entity's virtual world (how others see them). - /// \details RM3 spawns the new world in and the old world out automatically on the next Update() - /// (in the default construction mode). \a avatar may be 0 if the player has no avatar entity yet. - /// \param[in] connection The player's connection (observer side) - /// \param[in] avatar The player's avatar entity, or 0 - /// \param[in] virtualWorld The virtual world to move them to - void SetPlayerVirtualWorld(Connection_RM3 *connection, VirtualWorldReplica3 *avatar, VirtualWorldId virtualWorld); - - /// \param[in] Default ordering channel to use for object creation, destruction, and serializations - void SetDefaultOrderingChannel(char def); - - /// \param[in] Default packet priority to use for object creation, destruction, and serializations - void SetDefaultPacketPriority(MafiaNet::Priority def); - - /// \param[in] Default packet reliability to use for object creation, destruction, and serializations - void SetDefaultPacketReliability(MafiaNet::Reliability def); - - /// \details Every \a intervalMS milliseconds, Connection_RM3::OnAutoserializeInterval() will be called.
- /// Defaults to 30.
- /// Pass with <0 to disable. Pass 0 to Serialize() every time RakPeer::Recieve() is called
- /// If you want to control the update interval with more granularity, use the return values from Replica3::Serialize().
- /// \param[in] intervalMS How frequently to autoserialize all objects. This controls the maximum number of game object updates per second. - void SetAutoSerializeInterval(MafiaNet::Time intervalMS); - - /// \brief Return the connections that we think have an instance of the specified Replica3 instance - /// \details This can be wrong, for example if that system locally deleted the outside the scope of ReplicaManager3, if QueryRemoteConstruction() returned false, or if DeserializeConstruction() returned false. - /// \param[in] replica The replica to check against. - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - /// \param[out] connectionsThatHaveConstructedThisReplica Populated with connection instances that we believe have \a replica allocated - void GetConnectionsThatHaveReplicaConstructed(Replica3 *replica, DataStructures::List &connectionsThatHaveConstructedThisReplica, WorldId worldId=0); - - /// \brief Returns if GetDownloadWasCompleted() returns true for all connections - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - /// \return True when all downloads have been completed - bool GetAllConnectionDownloadsCompleted(WorldId worldId=0) const; - - /// \brief ReplicaManager3 can support multiple worlds, where each world has a separate NetworkIDManager, list of connections, replicas, etc - /// A world with id 0 is created automatically. If you want multiple worlds, use this function, and ReplicaManager3::SetNetworkIDManager() to have a different NetworkIDManager instance per world - /// \param[in] worldId A unique identifier for this world. User-defined - void AddWorld(WorldId worldId); - - /// \brief Deallocate a world added with AddWorld, or the default world with id 0 - /// Deallocating a world will also stop tracking and updating all connections and replicas associated with that world. - /// \param[in] worldId A \a worldId value previously added with AddWorld() - void RemoveWorld(WorldId worldId); - - /// \brief Get one of the WorldId values added with AddWorld() - /// \details WorldId 0 is created by default. Worlds will not necessarily be in the order added with AddWorld(). Edit RemoveWorld() changing RemoveAtIndexFast() to RemoveAtIndex() to preserve order. - /// \param[in] index A value between 0 and GetWorldCount()-1 - /// \return One of the WorldId values added with AddWorld() - WorldId GetWorldIdAtIndex(unsigned int index); - - /// \brief Returns the number of world id specifiers in memory, added with AddWorld() and removed with RemoveWorld() - /// \return The number of worlds added - unsigned int GetWorldCount(void) const; - - /// \details Sets the networkIDManager instance that this plugin relys upon.
- /// Uses whatever instance is attached to RakPeerInterface if unset.
- /// To support multiple worlds, you should set it to a different manager for each instance of the plugin - /// \param[in] _networkIDManager The externally allocated NetworkIDManager instance for this plugin to use. - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - void SetNetworkIDManager(NetworkIDManager *_networkIDManager, WorldId worldId=0); - - /// Returns what was passed to SetNetworkIDManager(), or the instance on RakPeerInterface if unset. - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - NetworkIDManager *GetNetworkIDManager(WorldId worldId=0) const; - - /// \details Send a network command to destroy one or more Replica3 instances - /// Usually you won't need this, but use Replica3::BroadcastDestruction() instead. - /// The objects are unaffected locally - /// \param[in] replicaList List of Replica3 objects to tell other systems to destroy. - /// \param[in] exclusionAddress Which system to not send to. UNASSIGNED_SYSTEM_ADDRESS to send to all. - /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() - void BroadcastDestructionList(DataStructures::List &replicaListSource, const SystemAddress &exclusionAddress, WorldId worldId=0); - - /// \internal - /// \details Tell other systems that have this replica to destroy this replica.
- /// You shouldn't need to call this, as it happens in the Replica3 destructor - void BroadcastDestruction(Replica3 *replica, const SystemAddress &exclusionAddress); - - /// \internal - /// \details Frees internal lists.
- /// \param[in] deleteWorlds True to also delete the worlds added with AddWorld() - /// Externally allocated pointers are not deallocated - void Clear(bool deleteWorlds=false); - - /// \internal - PRO GetDefaultSendParameters(void) const; - - /// Call interfaces, send data - virtual void Update(void); - - /// \internal - struct RM3World - { - RM3World(); - void Clear(ReplicaManager3 *replicaManager3); - - DataStructures::List connectionList; - DataStructures::List userReplicaList; - WorldId worldId; - NetworkIDManager *networkIDManager; - }; -protected: - virtual PluginReceiveResult OnReceive(Packet *packet); - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); - virtual void OnRakPeerShutdown(void); - virtual void OnDetach(void); - - PluginReceiveResult OnConstruction(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, unsigned char packetDataOffset, WorldId worldId); - PluginReceiveResult OnSerialize(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, MafiaNet::Time timestamp, unsigned char packetDataOffset, WorldId worldId); - PluginReceiveResult OnDownloadStarted(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, unsigned char packetDataOffset, WorldId worldId); - PluginReceiveResult OnDownloadComplete(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, unsigned char packetDataOffset, WorldId worldId); - - void DeallocReplicaNoBroadcastDestruction(MafiaNet::Connection_RM3 *connection, MafiaNet::Replica3 *replica3); - MafiaNet::Connection_RM3 * PopConnection(unsigned int index, WorldId worldId); - Replica3* GetReplicaByNetworkID(NetworkID networkId, WorldId worldId); - unsigned int ReferenceInternal(MafiaNet::Replica3 *replica3, WorldId worldId); - - PRO defaultSendParameters; - MafiaNet::Time autoSerializeInterval; - MafiaNet::Time lastAutoSerializeOccurance; - bool autoCreateConnections, autoDestroyConnections; - Replica3 *currentlyDeallocatingReplica; - // Set on the first call to ReferenceInternal(), and should never be changed after that - // Used to lookup in Replica3LSRComp. I don't want to rely on GetNetworkID() in case it changes at runtime - uint32_t nextReferenceIndex; - - // For O(1) lookup - RM3World *worldsArray[255]; - // For fast traversal - DataStructures::List worldsList; -private: - // #med - reconsider visibility here --- should be properly encapsulated so to not allow access to worldsList by derived classes (which could bypass the mutex) - // mutex to ensure thread safe access to worldsList member - SimpleMutex m_WorldListMutex; - - friend class Connection_RM3; -}; - -static const int RM3_NUM_OUTPUT_BITSTREAM_CHANNELS=16; - -/// \ingroup REPLICA_MANAGER_GROUP3 -struct LastSerializationResultBS -{ - MafiaNet::BitStream bitStream[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; - bool indicesToSend[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; -}; - -/// Represents the serialized data for an object the last time it was sent. Used by Connection_RM3::OnAutoserializeInterval() and Connection_RM3::SendSerializeIfChanged() -/// \ingroup REPLICA_MANAGER_GROUP3 -struct LastSerializationResult -{ - LastSerializationResult(); - ~LastSerializationResult(); - - /// The replica instance we serialized - /// \note replica MUST be the first member of this struct because I cast from replica to LastSerializationResult in Update() - MafiaNet::Replica3 *replica; - //bool neverSerialize; -// bool isConstructed; - MafiaNet::Time whenLastSerialized; - - void AllocBS(void); - LastSerializationResultBS* lastSerializationResultBS; -}; - -/// Parameters passed to Replica3::Serialize() -/// \ingroup REPLICA_MANAGER_GROUP3 -struct SerializeParameters -{ - /// Write your output for serialization here - /// If nothing is written, the serialization will not occur - /// Write to any or all of the NUM_OUTPUT_BITSTREAM_CHANNELS channels available. Channels can hold independent data - MafiaNet::BitStream outputBitstream[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; - - /// Last bitstream we sent for this replica to this system. - /// Read, but DO NOT MODIFY - MafiaNet::BitStream* lastSentBitstream[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; - - /// Set to non-zero to transmit a timestamp with this message. - /// Defaults to 0 - /// Use MafiaNet::GetTime() for this - MafiaNet::Time messageTimestamp; - - /// Passed to RakPeerInterface::Send(). Defaults to ReplicaManager3::SetDefaultPacketPriority(). - /// Passed to RakPeerInterface::Send(). Defaults to ReplicaManager3::SetDefaultPacketReliability(). - /// Passed to RakPeerInterface::Send(). Defaults to ReplicaManager3::SetDefaultOrderingChannel(). - PRO pro[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; - - /// Passed to RakPeerInterface::Send(). - MafiaNet::Connection_RM3 *destinationConnection; - - /// For prior serializations this tick, for the same connection, how many bits have we written so far? - /// Use this to limit how many objects you send to update per-tick if desired - BitSize_t bitsWrittenSoFar; - - /// When this object was last serialized to the connection - /// 0 means never - MafiaNet::Time whenLastSerialized; - - /// Current time, in milliseconds. - /// curTime - whenLastSerialized is how long it has been since this object was last sent - MafiaNet::Time curTime; -}; - -/// \ingroup REPLICA_MANAGER_GROUP3 -struct DeserializeParameters -{ - MafiaNet::BitStream serializationBitstream[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; - bool bitstreamWrittenTo[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; - MafiaNet::Time timeStamp; - MafiaNet::Connection_RM3 *sourceConnection; -}; - -/// \ingroup REPLICA_MANAGER_GROUP3 -enum SendSerializeIfChangedResult -{ - SSICR_SENT_DATA, - SSICR_DID_NOT_SEND_DATA, - SSICR_NEVER_SERIALIZE, -}; - -/// \brief Each remote system is represented by Connection_RM3. Used to allocate Replica3 and track which instances have been allocated -/// \details Important function: AllocReplica() - must be overridden to create an object given an identifier for that object, which you define for all objects in your game -/// \ingroup REPLICA_MANAGER_GROUP3 -class RAK_DLL_EXPORT Connection_RM3 -{ -public: - - Connection_RM3(const SystemAddress &_systemAddress, RakNetGUID _guid); - virtual ~Connection_RM3(); - - /// \brief Class factory to create a Replica3 instance, given a user-defined identifier - /// \details Identifier is returned by Replica3::WriteAllocationID() for what type of class to create.
- /// This is called when you download a replica from another system.
- /// See Replica3::Dealloc for the corresponding destruction message.
- /// Return 0 if unable to create the intended object. Note, in that case the other system will still think we have the object and will try to serialize object updates to us. Generally, you should not send objects the other system cannot create.
- /// \sa Replica3::WriteAllocationID(). - /// Sample implementation:
- /// {MafiaNet::RakString typeName; allocationIdBitstream->Read(typeName); if (typeName=="Soldier") return new Soldier; return 0;}
- /// \param[in] allocationIdBitstream user-defined bitstream uniquely identifying a game object type - /// \param[in] replicaManager3 Instance of ReplicaManager3 that controls this connection - /// \return The new replica instance - virtual Replica3 *AllocReplica(MafiaNet::BitStream *allocationIdBitstream, ReplicaManager3 *replicaManager3)=0; - - /// \brief Get list of all replicas that are constructed for this connection - /// \param[out] objectsTheyDoHave Destination list. Returned in sorted ascending order, sorted on the value of the Replica3 pointer. - virtual void GetConstructedReplicas(DataStructures::List &objectsTheyDoHave); - - /// Returns true if we think this remote connection has this replica constructed - /// \param[in] replica3 Which replica we are querying - /// \return True if constructed, false othewise - bool HasReplicaConstructed(MafiaNet::Replica3 *replica); - - /// When a new connection connects, before sending any objects, SerializeOnDownloadStarted() is called - /// \param[out] bitStream Passed to DeserializeOnDownloadStarted() - virtual void SerializeOnDownloadStarted(MafiaNet::BitStream *bitStream) {(void) bitStream;} - - /// Receives whatever was written in SerializeOnDownloadStarted() - /// \param[in] bitStream Written in SerializeOnDownloadStarted() - virtual void DeserializeOnDownloadStarted(MafiaNet::BitStream *bitStream) {(void) bitStream;} - - /// When a new connection connects, after constructing and serialization all objects, SerializeOnDownloadComplete() is called - /// \param[out] bitStream Passed to DeserializeOnDownloadComplete() - virtual void SerializeOnDownloadComplete(MafiaNet::BitStream *bitStream) {(void) bitStream;} - - /// Receives whatever was written in DeserializeOnDownloadComplete() - /// \param[in] bitStream Written in SerializeOnDownloadComplete() - virtual void DeserializeOnDownloadComplete(MafiaNet::BitStream *bitStream) {(void) bitStream;} - - /// \return The system address passed to the constructor of this object - SystemAddress GetSystemAddress(void) const {return systemAddress;} - - /// \return Returns the RakNetGUID passed to the constructor of this object - RakNetGUID GetRakNetGUID(void) const {return guid;} - - /// \brief Set the virtual world (dimension) this observer perceives. - /// \details Entities (VirtualWorldReplica3) are only constructed/serialized to this - /// connection when they share this virtual world (or either side is VIRTUAL_WORLD_GLOBAL). - /// See VirtualWorld.h and ReplicaManager3::SetPlayerVirtualWorld(). - void SetVirtualWorld(VirtualWorldId vw) {virtualWorld=vw;} - - /// \return The virtual world this observer perceives. Defaults to VIRTUAL_WORLD_DEFAULT. - VirtualWorldId GetVirtualWorld(void) const {return virtualWorld;} - - /// \return True if ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE arrived for this connection - bool GetDownloadWasCompleted(void) const {return gotDownloadComplete;} - - /// List of enumerations for how to get the list of valid objects for other systems - enum ConstructionMode - { - /// For every object that does not exist on the remote system, call Replica3::QueryConstruction() every tick. - /// Do not call Replica3::QueryDestruction() - /// Do not call Connection_RM3::QueryReplicaList() - QUERY_REPLICA_FOR_CONSTRUCTION, - - /// For every object that does not exist on the remote system, call Replica3::QueryConstruction() every tick. Based on the call, the object may be sent to the other system. - /// For every object that does exist on the remote system, call Replica3::QueryDestruction() every tick. Based on the call, the object may be deleted on the other system. - /// Do not call Connection_RM3::QueryReplicaList() - QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION, - - /// Do not call Replica3::QueryConstruction() or Replica3::QueryDestruction() - /// Call Connection_RM3::QueryReplicaList() to determine which objects exist on remote systems - /// This can be faster than QUERY_REPLICA_FOR_CONSTRUCTION and QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION for large worlds - /// See GridSectorizer.h under /Source for code that can help with this - QUERY_CONNECTION_FOR_REPLICA_LIST - }; - - /// \brief Return whether or not downloads to our system should all be processed the same tick (call to RakPeer::Receive() ) - /// \details Normally the system will send ID_REPLICA_MANAGER_DOWNLOAD_STARTED, ID_REPLICA_MANAGER_CONSTRUCTION for all downloaded objects, - /// ID_REPLICA_MANAGER_SERIALIZE for each downloaded object, and lastly ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE. - /// This enables the application to show a downloading splash screen on ID_REPLICA_MANAGER_DOWNLOAD_STARTED, a progress bar, and to close the splash screen and activate all objects on ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE - /// However, if the application was not set up for this then it would result in incomplete objects spread out over time, and cause problems - /// If you return true from QueryGroupDownloadMessages(), then these messages will be returned all in one tick, returned only when the download is complete - /// \note ID_REPLICA_MANAGER_DOWNLOAD_STARTED calls the callback DeserializeOnDownloadStarted() - /// \note ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE calls the callback DeserializeOnDownloadComplete() - virtual bool QueryGroupDownloadMessages(void) const {return false;} - - /// \brief Queries how to get the list of objects that exist on remote systems - /// \details The default of calling QueryConstruction for every known object is easy to use, but not efficient, especially for large worlds where many objects are outside of the player's circle of influence.
- /// QueryDestruction is also not necessarily useful or efficient, as object destruction tends to happen in known cases, and can be accomplished by calling Replica3::BroadcastDestruction() - /// QueryConstructionMode() allows you to specify more efficient algorithms than the default when overriden. - /// \return How to get the list of objects that exist on the remote system. You should always return the same value for a given connection - virtual ConstructionMode QueryConstructionMode(void) const {return QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION;} - - /// \brief Callback used when QueryConstructionMode() returns QUERY_CONNECTION_FOR_REPLICA_LIST - /// \details This advantage of this callback is if that there are many objects that a particular connection does not have, then we do not have to iterate through those - /// objects calling QueryConstruction() for each of them.
- ///
- /// See GridSectorizer in the Source directory as a method to find all objects within a certain radius in a fast way.
- ///
- /// \param[out] newReplicasToCreate Anything in this list will be created on the remote system - /// \param[out] existingReplicasToDestroy Anything in this list will be destroyed on the remote system - virtual void QueryReplicaList( - DataStructures::List &newReplicasToCreate, - DataStructures::List &existingReplicasToDestroy) {(void) newReplicasToCreate; (void) existingReplicasToDestroy;} - - /// \brief Override which replicas to serialize and in what order for a connection for a ReplicaManager3::Update() cycle - /// \details By default, Connection_RM3 will iterate through queryToSerializeReplicaList and call QuerySerialization() on each Replica in that list - /// queryToSerializeReplicaList is populated in the order in which ReplicaManager3::Reference() is called for those objects. - /// If you write to to \a replicasToSerialize and return true, you can control in what order and for which replicas to call QuerySerialization() - /// Example use case: - /// We have more data to send then the bandwidth supports, so want to prioritize sends. For example enemies shooting are more important than animation effects - /// When QuerySerializationList(), sort objects by priority, and write the list to \a replicasToSerialize, optionally skipping objects with a lower serialization frequency - /// If you hit your bandwidth limit when checking SerializeParameters::bitsWrittenSoFar, you can return RM3SR_DO_NOT_SERIALIZE for all remaining items - /// \note Only replicas written to replicasToSerialize are transmitted. Even if you returned RM3SR_SERIALIZED_ALWAYS a prior ReplicaManager3::Update() cycle, the replica will not be transmitted if it is not in replicasToSerialize - /// \note If you do not know what objects are candidates for serialization, you can use queryToSerializeReplicaList as a source for your filtering or sorting operations - /// \param[in] replicasToSerialize List of replicas to call QuerySerialization() on - /// \return Return true to use replicasToSerialize (replicasToSerialize may be empty if desired). Otherwise return false. - virtual bool QuerySerializationList(DataStructures::List &replicasToSerialize) {(void) replicasToSerialize; return false;} - - /// \internal This is used internally - however, you can also call it manually to send a data update for a remote replica.
- /// \brief Sends over a serialization update for \a replica.
- /// NetworkID::GetNetworkID() is written automatically, serializationData is the object data.
- /// \param[in] replica Which replica to serialize - /// \param[in] serializationData Serialized object data - /// \param[in] timestamp 0 means no timestamp. Otherwise message is prepended with ID_TIMESTAMP - /// \param[in] sendParameters Parameters on how to send - /// \param[in] rakPeer Instance of RakPeerInterface to send on - /// \param[in] worldId Which world, see ReplicaManager3::AddWorld() - /// \param[in] curTime The current time - virtual SendSerializeIfChangedResult SendSerialize(MafiaNet::Replica3 *replica, bool indicesToSend[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], MafiaNet::BitStream serializationData[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], MafiaNet::Time timestamp, PRO sendParameters[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], MafiaNet::RakPeerInterface *rakPeer, unsigned char worldId, MafiaNet::Time curTime); - - /// \internal - /// \details Calls Connection_RM3::SendSerialize() if Replica3::Serialize() returns a different result than what is contained in \a lastSerializationResult.
- /// Used by autoserialization in Connection_RM3::OnAutoserializeInterval() - /// \param[in] lsr Item in the queryToSerializeReplicaList - /// \param[in] sp Controlling parameters over the serialization - /// \param[in] rakPeer Instance of RakPeerInterface to send on - /// \param[in] worldId Which world, see ReplicaManager3::AddWorld() - /// \param[in] curTime The current time - virtual SendSerializeIfChangedResult SendSerializeIfChanged(LastSerializationResult *lsr, SerializeParameters *sp, MafiaNet::RakPeerInterface *rakPeer, unsigned char worldId, ReplicaManager3 *replicaManager, MafiaNet::Time curTime); - - /// \internal - /// \brief Given a list of objects that were created and destroyed, serialize and send them to another system. - /// \param[in] newObjects Objects to serialize construction - /// \param[in] deletedObjects Objects to serialize destruction - /// \param[in] sendParameters Controlling parameters over the serialization - /// \param[in] rakPeer Instance of RakPeerInterface to send on - /// \param[in] worldId Which world, see ReplicaManager3::AddWorld() - /// \param[in] replicaManager3 ReplicaManager3 instance - virtual void SendConstruction(DataStructures::List &newObjects, DataStructures::List &deletedObjects, PRO sendParameters, MafiaNet::RakPeerInterface *rakPeer, unsigned char worldId, ReplicaManager3 *replicaManager3); - - /// \internal - void SendValidation(MafiaNet::RakPeerInterface *rakPeer, WorldId worldId); - - /// \internal - void AutoConstructByQuery(ReplicaManager3 *replicaManager3, WorldId worldId); - - - // Internal - does the other system have this connection too? Validated means we can now use it - bool isValidated; - // Internal - Used to see if we should send download started - bool isFirstConstruction; - - static int Replica3LSRComp( Replica3 * const &replica3, LastSerializationResult * const &data ); - - // Internal - void ClearDownloadGroup(RakPeerInterface *rakPeerInterface); -protected: - - SystemAddress systemAddress; - RakNetGUID guid; - - // The virtual world (dimension) this observer perceives. See VirtualWorld.h. - VirtualWorldId virtualWorld; - - /* - Operations: - - Locally reference a new replica: - Add to queryToConstructReplicaList for all objects - - Add all objects to queryToConstructReplicaList - - Download: - Add to constructedReplicaList for connection that send the object to us - Add to queryToSerializeReplicaList for connection that send the object to us - Add to queryToConstructReplicaList for all other connections - - Never construct for this connection: - Remove from queryToConstructReplicaList - - Construct to this connection - Remove from queryToConstructReplicaList - Add to constructedReplicaList for this connection - Add to queryToSerializeReplicaList for this connection - - Serialize: - Iterate through queryToSerializeReplicaList - - Never serialize for this connection - Remove from queryToSerializeReplicaList - - Reference (this system has this object already) - Remove from queryToConstructReplicaList - Add to constructedReplicaList for this connection - Add to queryToSerializeReplicaList for this connection - - Downloaded an existing object - if replica is in queryToConstructReplicaList, OnConstructToThisConnection() - else ignore - - Send destruction from query - Remove from queryToDestructReplicaList - Remove from queryToSerializeReplicaList - Remove from constructedReplicaList - Add to queryToConstructReplicaList - - Do not query destruction again - Remove from queryToDestructReplicaList - */ - void OnLocalReference(Replica3* replica3, ReplicaManager3 *replicaManager); - void OnDereference(Replica3* replica3, ReplicaManager3 *replicaManager); - void OnDownloadFromThisSystem(Replica3* replica3, ReplicaManager3 *replicaManager); - void OnDownloadFromOtherSystem(Replica3* replica3, ReplicaManager3 *replicaManager); - void OnNeverConstruct(unsigned int queryToConstructIdx, ReplicaManager3 *replicaManager); - void OnConstructToThisConnection(unsigned int queryToConstructIdx, ReplicaManager3 *replicaManager); - void OnConstructToThisConnection(Replica3 *replica, ReplicaManager3 *replicaManager); - void OnNeverSerialize(LastSerializationResult *lsr, ReplicaManager3 *replicaManager); - void OnReplicaAlreadyExists(unsigned int queryToConstructIdx, ReplicaManager3 *replicaManager); - void OnDownloadExisting(Replica3* replica3, ReplicaManager3 *replicaManager); - void OnSendDestructionFromQuery(unsigned int queryToDestructIdx, ReplicaManager3 *replicaManager); - void OnDoNotQueryDestruction(unsigned int queryToDestructIdx, ReplicaManager3 *replicaManager); - void ValidateLists(ReplicaManager3 *replicaManager) const; - void SendSerializeHeader(MafiaNet::Replica3 *replica, MafiaNet::Time timestamp, MafiaNet::BitStream *bs, WorldId worldId); - - // The list of objects that our local system and this remote system both have - // Either we sent this object to them, or they sent this object to us - // A given Replica can be either in queryToConstructReplicaList or constructedReplicaList but not both at the same time - DataStructures::OrderedList constructedReplicaList; - - // Objects that we have, but this system does not, and we will query each tick to see if it should be sent to them - // If we do send it to them, the replica is moved to constructedReplicaList - // A given Replica can be either in queryToConstructReplicaList or constructedReplicaList but not both at the same time - DataStructures::List queryToConstructReplicaList; - - // Objects that this system has constructed are added at the same time to queryToSerializeReplicaList - // This list is used to serialize all objects that this system has to this connection - DataStructures::List queryToSerializeReplicaList; - - // Objects that are constructed on this system are also queried if they should be destroyed to this system - DataStructures::List queryToDestructReplicaList; - - // Working lists - DataStructures::List constructedReplicasCulled, destroyedReplicasCulled; - - // This is used if QueryGroupDownloadMessages() returns true when ID_REPLICA_MANAGER_DOWNLOAD_STARTED arrives - // Packets will be gathered and not returned until ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE arrives - bool groupConstructionAndSerialize; - DataStructures::Queue downloadGroup; - - // Stores if we got download complete for this connection - bool gotDownloadComplete; - - friend class ReplicaManager3; -private: - Connection_RM3() {}; - - ConstructionMode constructionMode; -}; - -/// \brief Return codes for Connection_RM3::GetConstructionState() and Replica3::QueryConstruction() -/// \details Indicates what state the object should be in for the remote system -/// \ingroup REPLICA_MANAGER_GROUP3 -enum RM3ConstructionState -{ - /// This object should exist on the remote system. Send a construction message if necessary - /// If the NetworkID is already in use, it will not do anything - /// If it is not in use, it will create the object, and then call DeserializeConstruction - RM3CS_SEND_CONSTRUCTION, - - /// This object should exist on the remote system. - /// The other system already has the object, and the object will never be deleted. - /// This is true of objects that are loaded with the level, for example. - /// Treat it as if it existed, without sending a construction message. - /// Will call Serialize() and SerializeConstructionExisting() to the object on the remote system - RM3CS_ALREADY_EXISTS_REMOTELY, - - /// Same as RM3CS_ALREADY_EXISTS_REMOTELY but does not call SerializeConstructionExisting() - RM3CS_ALREADY_EXISTS_REMOTELY_DO_NOT_CONSTRUCT, - - /// This object will never be sent to the target system - /// This object will never be serialized from this system to the target system - RM3CS_NEVER_CONSTRUCT, - - /// Don't do anything this tick. Will query again next tick - RM3CS_NO_ACTION, - - /// Max enum - RM3CS_MAX, -}; - -/// If this object already exists for this system, should it be removed? -/// \ingroup REPLICA_MANAGER_GROUP3 -enum RM3DestructionState -{ - /// This object should not exist on the remote system. Send a destruction message if necessary. - RM3DS_SEND_DESTRUCTION, - - /// This object will never be destroyed by a per-tick query. Don't call again - RM3DS_DO_NOT_QUERY_DESTRUCTION, - - /// Don't do anything this tick. Will query again next tick - RM3DS_NO_ACTION, - - /// Max enum - RM3DS_MAX, -}; - -/// Return codes when constructing an object -/// \ingroup REPLICA_MANAGER_GROUP3 -enum RM3SerializationResult -{ - /// This object serializes identically no matter who we send to - /// We also send it to every connection (broadcast). - /// Efficient for memory, speed, and bandwidth but only if the object is always broadcast identically. - RM3SR_BROADCAST_IDENTICALLY, - - /// Same as RM3SR_BROADCAST_IDENTICALLY, but assume the object needs to be serialized, do not check with a memcmp - /// Assume the object changed, and serialize it - /// Use this if you know exactly when your object needs to change. Can be faster than RM3SR_BROADCAST_IDENTICALLY. - /// An example of this is if every member variable has an accessor, changing a member sets a flag, and you check that flag in Replica3::QuerySerialization() - /// The opposite of this is RM3SR_DO_NOT_SERIALIZE, in case the object did not change - RM3SR_BROADCAST_IDENTICALLY_FORCE_SERIALIZATION, - - /// Either this object serializes differently depending on who we send to or we send it to some systems and not others. - /// Inefficient for memory and speed, but efficient for bandwidth - /// However, if you don't know what to return, return this - RM3SR_SERIALIZED_UNIQUELY, - - /// Do not compare against last sent value. Just send even if the data is the same as the last tick - /// If the data is always changing anyway, or you want to send unreliably, this is a good method of serialization - /// Can send unique data per connection if desired. If same data is sent to all connections, use RM3SR_SERIALIZED_ALWAYS_IDENTICALLY for even better performance - /// Efficient for memory and speed, but not necessarily bandwidth - RM3SR_SERIALIZED_ALWAYS, - - /// \deprecated, use RM3SR_BROADCAST_IDENTICALLY_FORCE_SERIALIZATION - RM3SR_SERIALIZED_ALWAYS_IDENTICALLY, - - /// Do not serialize this object this tick, for this connection. Will query again next autoserialize timer - RM3SR_DO_NOT_SERIALIZE, - - /// Never serialize this object for this connection - /// Useful for objects that are downloaded, and never change again - /// Efficient - RM3SR_NEVER_SERIALIZE_FOR_THIS_CONNECTION, - - /// Max enum - RM3SR_MAX, -}; - -/// First pass at topology to see if an object should be serialized -/// \ingroup REPLICA_MANAGER_GROUP3 -enum RM3QuerySerializationResult -{ - /// Call Serialize() to see if this object should be serializable for this connection - RM3QSR_CALL_SERIALIZE, - /// Do not call Serialize() this tick to see if this object should be serializable for this connection - RM3QSR_DO_NOT_CALL_SERIALIZE, - /// Never call Serialize() for this object and connection. This system will not serialize this object for this topology - RM3QSR_NEVER_CALL_SERIALIZE, - /// Max enum - RM3QSR_MAX, -}; - -/// \ingroup REPLICA_MANAGER_GROUP3 -enum RM3ActionOnPopConnection -{ - RM3AOPC_DO_NOTHING, - RM3AOPC_DELETE_REPLICA, - RM3AOPC_DELETE_REPLICA_AND_BROADCAST_DESTRUCTION, - RM3AOPC_MAX, -}; - -/// \ingroup REPLICA_MANAGER_GROUP3 -/// Used for Replica3::QueryConstruction_PeerToPeer() and Replica3::QuerySerialization_PeerToPeer() to describe how the object replicates between hosts -enum Replica3P2PMode -{ - /// The Replica3 instance is constructed and serialized by one system only. - /// Example: Your avatar. No other player serializes or can create your avatar. - R3P2PM_SINGLE_OWNER, - /// The Replica3 instance is constructed and/or serialized by different systems - /// This system is currently in charge of construction and/or serialization - /// Example: A pickup. When an avatar holds it, that avatar controls it. When it is on the ground, the host controls it. - R3P2PM_MULTI_OWNER_CURRENTLY_AUTHORITATIVE, - /// The Replica3 instance is constructed and/or serialized by different systems - /// Another system is in charge of construction and/or serialization, but this system may be in charge at a later time - /// Example: A pickup held by another player. That player sends creation of that object to new connections, and serializes it until it is dropped. - R3P2PM_MULTI_OWNER_NOT_CURRENTLY_AUTHORITATIVE, - /// The Replica3 instance is a static object (already exists on the remote system). - /// This system is currently in charge of construction and/or serialization - R3P2PM_STATIC_OBJECT_CURRENTLY_AUTHORITATIVE, - /// The Replica3 instance is a static object (already exists on the remote system). - /// Another system is in charge of construction and/or serialization, but this system may be in charge at a later time - R3P2PM_STATIC_OBJECT_NOT_CURRENTLY_AUTHORITATIVE, - -}; - -/// \brief Base class for your replicated objects for the ReplicaManager3 system. -/// \details To use, derive your class, or a member of your class, from Replica3.
-/// \ingroup REPLICA_MANAGER_GROUP3 -class RAK_DLL_EXPORT Replica3 : public NetworkIDObject -{ -public: - Replica3(); - - /// Before deleting a local instance of Replica3, call Replica3::BroadcastDestruction() for the deletion notification to go out on the network. - /// It is not necessary to call ReplicaManager3::Dereference(), as this happens automatically in the destructor - virtual ~Replica3(); - - /// \brief Write a unique identifer that can be read on a remote system to create an object of this same class. - /// \details The value written to \a allocationIdBitstream will be passed to Connection_RM3::AllocReplica().
- /// Sample implementation:
- /// {allocationIdBitstream->Write(MafiaNet::RakString("Soldier");}
- /// \param[out] allocationIdBitstream Bitstream for the user to write to, to identify this class - virtual void WriteAllocationID(MafiaNet::Connection_RM3 *destinationConnection, MafiaNet::BitStream *allocationIdBitstream) const=0; - - /// \brief Ask if this object, which does not exist on \a destinationConnection should (now) be sent to that system. - /// \details If ReplicaManager3::QueryConstructionMode() returns QUERY_CONNECTION_FOR_REPLICA_LIST or QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION (default), - /// then QueyrConstruction() is called once per tick from ReplicaManager3::Update() to determine if an object should exist on a given system.
- /// Based on the return value, a network message may be sent to the other system to create the object.
- /// If QueryConstructionMode() is overriden to return QUERY_CONNECTION_FOR_REPLICA_LIST, this function is unused.
- /// \note Defaults are provided: QueryConstruction_PeerToPeer(), QueryConstruction_ServerConstruction(), QueryConstruction_ClientConstruction(). Return one of these functions for a working default for the relevant topology. - /// \param[in] destinationConnection Which system we will send to - /// \param[in] replicaManager3 Plugin instance for this Replica3 - /// \return What action to take - virtual RM3ConstructionState QueryConstruction(MafiaNet::Connection_RM3 *destinationConnection, ReplicaManager3 *replicaManager3)=0; - - /// \brief Ask if this object, which does exist on \a destinationConnection should be removed from the remote system - /// \details If ReplicaManager3::QueryConstructionMode() returns QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION (default), - /// then QueryDestruction() is called once per tick from ReplicaManager3::Update() to determine if an object that exists on a remote system should be destroyed for a given system.
- /// Based on the return value, a network message may be sent to the other system to destroy the object.
- /// Note that you can also destroy objects with BroadcastDestruction(), so this function is not useful unless you plan to delete objects for only a particular connection.
- /// If QueryConstructionMode() is overriden to return QUERY_CONNECTION_FOR_REPLICA_LIST, this function is unused.
- /// \param[in] destinationConnection Which system we will send to - /// \param[in] replicaManager3 Plugin instance for this Replica3 - /// \return What action to take. Only RM3CS_SEND_DESTRUCTION does anything at this time. - virtual RM3DestructionState QueryDestruction(MafiaNet::Connection_RM3 *destinationConnection, ReplicaManager3 *replicaManager3) {(void) destinationConnection; (void) replicaManager3; return RM3DS_DO_NOT_QUERY_DESTRUCTION;} - - /// \brief We're about to call DeserializeConstruction() on this Replica3. If QueryRemoteConstruction() returns false, this object is deleted instead. - /// \details By default, QueryRemoteConstruction_ServerConstruction() does not allow clients to create objects. The client will get Replica3::DeserializeConstructionRequestRejected().
- /// If you want the client to be able to potentially create objects for client/server, override accordingly.
- /// Other variants of QueryRemoteConstruction_* just return true. - /// \note Defaults are provided: QueryRemoteConstruction_PeerToPeer(), QueryRemoteConstruction_ServerConstruction(), QueryRemoteConstruction_ClientConstruction(). Return one of these functions for a working default for the relevant topology. - /// \param[in] sourceConnection Which system sent us the object creation request message. - /// \return True to allow the object to pass onto DeserializeConstruction() (where it may also be rejected), false to immediately reject the remote construction request - virtual bool QueryRemoteConstruction(MafiaNet::Connection_RM3 *sourceConnection)=0; - - /// \brief We got a message from a connection to destroy this replica - /// Return true to automatically relay the destruction message to all our other connections - /// For a client in client/server, it does not matter what this funtion returns - /// For a server in client/server, this should normally return true - /// For a peer in peer to peer, you can normally return false since the original destroying peer would have told all other peers about the destruction - /// If a system gets a destruction command for an object that was already destroyed, the destruction message is ignored - virtual bool QueryRelayDestruction(Connection_RM3 *sourceConnection) const {(void) sourceConnection; return true;} - - /// \brief Write data to be sent only when the object is constructed on a remote system. - /// \details SerializeConstruction is used to write out data that you need to create this object in the context of your game, such as health, score, name. Use it for data you only need to send when the object is created.
- /// After SerializeConstruction() is called, Serialize() will be called immediately thereafter. However, they are sent in different messages, so Serialize() may arrive a later frame than SerializeConstruction() - /// For that reason, the object should be valid after a call to DeserializeConstruction() for at least a short time.
- /// \note The object's NetworkID and allocation id are handled by the system automatically, you do not need to write these values to \a constructionBitstream - /// \param[out] constructionBitstream Destination bitstream to write your data to - /// \param[in] destinationConnection System that will receive this network message. - virtual void SerializeConstruction(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *destinationConnection)=0; - - /// \brief Read data written by Replica3::SerializeConstruction() - /// \details Reads whatever data was written to \a constructionBitstream in Replica3::SerializeConstruction() - /// \param[out] constructionBitstream Bitstream written to in Replica3::SerializeConstruction() - /// \param[in] sourceConnection System that sent us this network message. - /// \return true to accept construction of the object. false to reject, in which case the object will be deleted via Replica3::DeallocReplica() - virtual bool DeserializeConstruction(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *sourceConnection)=0; - - /// Same as SerializeConstruction(), but for an object that already exists on the remote system. - /// Used if you return RM3CS_ALREADY_EXISTS_REMOTELY from QueryConstruction - virtual void SerializeConstructionExisting(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *destinationConnection) {(void) constructionBitstream; (void) destinationConnection;}; - - /// Same as DeserializeConstruction(), but for an object that already exists on the remote system. - /// Used if you return RM3CS_ALREADY_EXISTS_REMOTELY from QueryConstruction - virtual void DeserializeConstructionExisting(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *sourceConnection) {(void) constructionBitstream; (void) sourceConnection;}; - - /// \brief Write extra data to send with the object deletion event, if desired - /// \details Replica3::SerializeDestruction() will be called to write any object destruction specific data you want to send with this event. - /// \a destructionBitstream can be read in DeserializeDestruction() - /// \param[out] destructionBitstream Bitstream for you to write to - /// \param[in] destinationConnection System that will receive this network message. - virtual void SerializeDestruction(MafiaNet::BitStream *destructionBitstream, MafiaNet::Connection_RM3 *destinationConnection)=0; - - /// \brief Read data written by Replica3::SerializeDestruction() - /// \details Return true to delete the object. BroadcastDestruction() will be called automatically, followed by ReplicaManager3::Dereference.
- /// Return false to not delete it. If you delete it at a later point, you are responsible for calling BroadcastDestruction() yourself. - virtual bool DeserializeDestruction(MafiaNet::BitStream *destructionBitstream, MafiaNet::Connection_RM3 *sourceConnection)=0; - - /// \brief The system is asking what to do with this replica when the connection is dropped - /// \details Return QueryActionOnPopConnection_Client, QueryActionOnPopConnection_Server, or QueryActionOnPopConnection_PeerToPeer - virtual MafiaNet::RM3ActionOnPopConnection QueryActionOnPopConnection(MafiaNet::Connection_RM3 *droppedConnection) const=0; - - /// Notification called for each of our replicas when a connection is popped - virtual void OnPoppedConnection(MafiaNet::Connection_RM3 *droppedConnection) {(void) droppedConnection;} - - /// \brief Override with {delete this;} - /// \details - ///
    - ///
  1. Got a remote message to delete this object which passed DeserializeDestruction(), OR - ///
  2. ReplicaManager3::SetAutoManageConnections() was called autoDestroy true (which is the default setting), and a remote system that owns this object disconnected) OR - /// <\OL> - ///
    - /// Override with {delete this;} to actually delete the object (and any other processing you wish).
    - /// If you don't want to delete the object, just do nothing, however, the system will not know this. You may wish to call Dereference() if the object should no longer be networked, but remain in memory. You are responsible for deleting it yoruself later.
    - /// destructionBitstream may be 0 if the object was deleted locally - virtual void DeallocReplica(MafiaNet::Connection_RM3 *sourceConnection)=0; - - /// \brief Implement with QuerySerialization_ClientSerializable(), QuerySerialization_ServerSerializable(), or QuerySerialization_PeerToPeer() - /// \details QuerySerialization() is a first pass query to check if a given object should serializable to a given system. The intent is that the user implements with one of the defaults for client, server, or peer to peer.
    - /// Without this function, a careless implementation would serialize an object anytime it changed to all systems. This would give you feedback loops as the sender gets the same message back from the recipient it just sent to.
    - /// If more than one system can serialize the same object then you will need to override to return true, and control the serialization result from Replica3::Serialize(). Be careful not to send back the same data to the system that just sent to you! - /// \return True to allow calling Replica3::Serialize() for this connection, false to not call. - virtual MafiaNet::RM3QuerySerializationResult QuerySerialization(MafiaNet::Connection_RM3 *destinationConnection)=0; - - /// \brief Called for each replica owned by the user, once per Serialization tick, before Serialize() is called. - /// If you want to do some kind of operation on the Replica objects that you own, just before Serialization(), then overload this function - virtual void OnUserReplicaPreSerializeTick(void) {} - - /// \brief Serialize our class to a bitstream - /// \details User should implement this function to write the contents of this class to SerializationParamters::serializationBitstream.
    - /// If data only needs to be written once, you can write it to SerializeConstruction() instead for efficiency.
    - /// Transmitted over the network if it changed from the last time we called Serialize().
    - /// Called every time the time interval to ReplicaManager3::SetAutoSerializeInterval() elapses and ReplicaManager3::Update is subsequently called. - /// \param[in/out] serializeParameters Parameters controlling the serialization, including destination bitstream to write to - /// \return Whether to serialize, and if so, how to optimize the results - virtual RM3SerializationResult Serialize(MafiaNet::SerializeParameters *serializeParameters)=0; - - /// \brief Called when the class is actually transmitted via Serialize() - /// \details Use to track how much bandwidth this class it taking - virtual void OnSerializeTransmission(MafiaNet::BitStream *bitStream, MafiaNet::Connection_RM3 *destinationConnection, BitSize_t bitsPerChannel[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], MafiaNet::Time curTime) {(void) bitStream; (void) destinationConnection; (void) bitsPerChannel; (void) curTime;} - - /// \brief Read what was written in Serialize() - /// \details Reads the contents of the class from SerializationParamters::serializationBitstream.
    - /// Called whenever Serialize() is called with different data from the last send. - /// \param[in] serializationBitstream Bitstream passed to Serialize() - /// \param[in] timeStamp 0 if unused, else contains the time the message originated on the remote system - /// \param[in] sourceConnection Which system sent to us - virtual void Deserialize(MafiaNet::DeserializeParameters *deserializeParameters)=0; - - /// \brief Called after SerializeConstruction completes for all objects in a given update tick.
    - /// Writes to PostDeserializeConstruction(), which is called after all objects are created for a given Construction tick(). - /// Override to send data to PostDeserializeConstruction(), such as the NetworkID of other objects to resolve pointers to - virtual void PostSerializeConstruction(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *destinationConnection) {(void) constructionBitstream; (void) destinationConnection;} - - /// Called after DeserializeConstruction completes for all objects in a given update tick.
    - /// This is used to resolve dependency chains, where two objects would refer to each other in DeserializeConstruction, yet one had not been constructed yet - /// In PostDeserializeConstruction(), you know that all objects have already been created, so can resolve NetworkIDs to pointers safely. - /// You can also use it to trigger some sort of event when you know the object has completed deserialization. - /// \param[in] constructionBitstream BitStream written in PostSerializeConstruction() - /// \param[in] sourceConnection System that sent us this network message. - virtual void PostDeserializeConstruction(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *sourceConnection) {(void) constructionBitstream; (void) sourceConnection;} - - /// Same as PostSerializeConstruction(), but for objects that returned RM3CS_ALREADY_EXISTS_REMOTELY from QueryConstruction - virtual void PostSerializeConstructionExisting(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *destinationConnection) {(void) constructionBitstream; (void) destinationConnection;} - - /// Same as PostDeserializeConstruction(), but for objects that returned RM3CS_ALREADY_EXISTS_REMOTELY from QueryConstruction - virtual void PostDeserializeConstructionExisting(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *sourceConnection) {(void) constructionBitstream; (void) sourceConnection;} - - /// Called after DeserializeDestruction completes for the object successfully, but obviously before the object is deleted.
    - /// Override to trigger some sort of event when you know the object has completed destruction. - /// \param[in] sourceConnection System that sent us this network message. - virtual void PreDestruction(MafiaNet::Connection_RM3 *sourceConnection) {(void) sourceConnection;} - - /// \brief Default call for QueryConstruction(). - /// \details Both the client and the server is allowed to create this object. The network topology is client/server - /// \param[in] destinationConnection destinationConnection parameter passed to QueryConstruction() - /// \param[in] isThisTheServer True if this system is the server, false if not. - virtual RM3ConstructionState QueryConstruction_ClientConstruction(MafiaNet::Connection_RM3 *destinationConnection, bool isThisTheServer); - - /// Default call for QueryRemoteConstruction(). - /// \details Both the client and the server is allowed to create this object. The network topology is client/server - /// The code means on the client or the server, allow creation of Replica3 instances - /// \param[in] sourceConnection destinationConnection parameter passed to QueryConstruction() - /// \param[in] isThisTheServer True if this system is the server, false if not. - virtual bool QueryRemoteConstruction_ClientConstruction(MafiaNet::Connection_RM3 *sourceConnection, bool isThisTheServer); - - /// \brief Default call for QueryConstruction(). - /// \details Only the server is allowed to create this object. The network topology is client/server - /// \param[in] destinationConnection destinationConnection parameter passed to QueryConstruction() - /// \param[in] isThisTheServer True if this system is the server, false if not. - virtual RM3ConstructionState QueryConstruction_ServerConstruction(MafiaNet::Connection_RM3 *destinationConnection, bool isThisTheServer); - - /// \brief Default call for QueryRemoteConstruction(). Allow the server to create this object, but not the client. - /// \details Only the server is allowed to create this object. The network topology is client/server - /// The code means if this is the server, and I got a command to create a Replica3 to ignore it. If this is the client, to allow it. - /// \param[in] sourceConnection destinationConnection parameter passed to QueryConstruction() - /// \param[in] isThisTheServer True if this system is the server, false if not. - virtual bool QueryRemoteConstruction_ServerConstruction(MafiaNet::Connection_RM3 *sourceConnection, bool isThisTheServer); - - /// \brief Default call for QueryConstruction(). - /// \details All clients are allowed to create all objects. The object is not relayed when remotely created - /// \param[in] destinationConnection destinationConnection parameter passed to QueryConstruction() - /// \param[in] p2pMode If controlled only by this system ever, pass R3P2PM_SINGLE_OWNER. Otherwise pass R3P2PM_MULTI_OWNER_CURRENTLY_AUTHORITATIVE or R3P2PM_MULTI_OWNER_NOT_CURRENTLY_AUTHORITATIVE - virtual RM3ConstructionState QueryConstruction_PeerToPeer(MafiaNet::Connection_RM3 *destinationConnection, Replica3P2PMode p2pMode=R3P2PM_SINGLE_OWNER); - /// \brief Default call for QueryRemoteConstruction(). - /// \details All clients are allowed to create all objects. The object is not relayed when remotely created - /// \param[in] sourceConnection destinationConnection parameter passed to QueryConstruction() - virtual bool QueryRemoteConstruction_PeerToPeer(MafiaNet::Connection_RM3 *sourceConnection); - - /// \brief Default call for QuerySerialization(). - /// \details Use if the values you are serializing are generated by the client that owns the object. The serialization will be relayed through the server to the other clients. - /// \param[in] destinationConnection destinationConnection parameter passed to QueryConstruction() - /// \param[in] isThisTheServer True if this system is the server, false if not. - virtual MafiaNet::RM3QuerySerializationResult QuerySerialization_ClientSerializable(MafiaNet::Connection_RM3 *destinationConnection, bool isThisTheServer); - /// \brief Default call for QuerySerialization(). - /// \details Use if the values you are serializing are generated only by the server. The serialization will be sent to all clients, but the clients will not send back to the server. - /// \param[in] destinationConnection destinationConnection parameter passed to QueryConstruction() - /// \param[in] isThisTheServer True if this system is the server, false if not. - virtual MafiaNet::RM3QuerySerializationResult QuerySerialization_ServerSerializable(MafiaNet::Connection_RM3 *destinationConnection, bool isThisTheServer); - /// \brief Default call for QuerySerialization(). - /// \details Use if the values you are serializing are on a peer to peer network. The peer that owns the object will send to all. Remote peers will not send. - /// \param[in] destinationConnection destinationConnection parameter passed to QueryConstruction() - /// \param[in] p2pMode If controlled only by this system ever, pass R3P2PM_SINGLE_OWNER. Otherwise pass R3P2PM_MULTI_OWNER_CURRENTLY_AUTHORITATIVE or R3P2PM_MULTI_OWNER_NOT_CURRENTLY_AUTHORITATIVE - virtual MafiaNet::RM3QuerySerializationResult QuerySerialization_PeerToPeer(MafiaNet::Connection_RM3 *destinationConnection, Replica3P2PMode p2pMode=R3P2PM_SINGLE_OWNER); - - /// Default: If we are a client, and the connection is lost, delete the server's objects - virtual RM3ActionOnPopConnection QueryActionOnPopConnection_Client(MafiaNet::Connection_RM3 *droppedConnection) const; - /// Default: If we are a server, and the connection is lost, delete the client's objects and broadcast the destruction - virtual RM3ActionOnPopConnection QueryActionOnPopConnection_Server(MafiaNet::Connection_RM3 *droppedConnection) const; - /// Default: If we are a peer, and the connection is lost, delete the peer's objects - virtual RM3ActionOnPopConnection QueryActionOnPopConnection_PeerToPeer(MafiaNet::Connection_RM3 *droppedConnection) const; - - /// Call to send a network message to delete this object on other systems.
    - /// Call it before deleting the object - virtual void BroadcastDestruction(void); - - /// creatingSystemGUID is set the first time Reference() is called, or if we get the object from another system - /// \return System that originally created this object - RakNetGUID GetCreatingSystemGUID(void) const; - - /// \return If ReplicaManager3::Reference() was called on this object. - bool WasReferenced(void) const {return replicaManager!=0;} - - /// GUID of the system that first called Reference() on this object. - /// Transmitted automatically when the object is constructed - RakNetGUID creatingSystemGUID; - /// GUID of the system that caused the item to send a deletion command over the network - RakNetGUID deletingSystemGUID; - - /// \internal - /// ReplicaManager3 plugin associated with this object - ReplicaManager3 *replicaManager; - - LastSerializationResultBS lastSentSerialization; - bool forceSendUntilNextUpdate; - LastSerializationResult *lsr; - uint32_t referenceIndex; -}; - -/// \brief Use Replica3 through composition instead of inheritance by containing an instance of this templated class -/// Calls to parent class for all functions -/// Parent class must still define and functions though! -/// \pre Parent class must call SetCompositeOwner() on this object -template -class RAK_DLL_EXPORT Replica3Composite : public Replica3 -{ -protected: - parent_type *r3CompositeOwner; -public: - void SetCompositeOwner(parent_type *p) {r3CompositeOwner=p;} - parent_type* GetCompositeOwner(void) const {return r3CompositeOwner;}; - virtual void WriteAllocationID(MafiaNet::Connection_RM3 *destinationConnection, MafiaNet::BitStream *allocationIdBitstream) const {r3CompositeOwner->WriteAllocationID(destinationConnection, allocationIdBitstream);} - virtual MafiaNet::RM3ConstructionState QueryConstruction(MafiaNet::Connection_RM3 *destinationConnection, MafiaNet::ReplicaManager3 *replicaManager3) {return r3CompositeOwner->QueryConstruction(destinationConnection, replicaManager3);} - virtual MafiaNet::RM3DestructionState QueryDestruction(MafiaNet::Connection_RM3 *destinationConnection, MafiaNet::ReplicaManager3 *replicaManager3) {return r3CompositeOwner->QueryDestruction(destinationConnection, replicaManager3);} - virtual bool QueryRemoteConstruction(MafiaNet::Connection_RM3 *sourceConnection) {return r3CompositeOwner->QueryRemoteConstruction(sourceConnection);} - virtual bool QueryRelayDestruction(MafiaNet::Connection_RM3 *sourceConnection) const {return r3CompositeOwner->QueryRelayDestruction(sourceConnection);} - virtual void SerializeConstruction(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *destinationConnection) {r3CompositeOwner->SerializeConstruction(constructionBitstream, destinationConnection);} - virtual bool DeserializeConstruction(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *sourceConnection) {return r3CompositeOwner->DeserializeConstruction(constructionBitstream, sourceConnection);} - virtual void SerializeConstructionExisting(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *destinationConnection) {r3CompositeOwner->SerializeConstructionExisting(constructionBitstream, destinationConnection);} - virtual void DeserializeConstructionExisting(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *sourceConnection) {r3CompositeOwner->DeserializeConstructionExisting(constructionBitstream, sourceConnection);} - virtual void SerializeDestruction(MafiaNet::BitStream *destructionBitstream, MafiaNet::Connection_RM3 *destinationConnection) {r3CompositeOwner->SerializeDestruction(destructionBitstream, destinationConnection);} - virtual bool DeserializeDestruction(MafiaNet::BitStream *destructionBitstream, MafiaNet::Connection_RM3 *sourceConnection) {return r3CompositeOwner->DeserializeDestruction(destructionBitstream, sourceConnection);} - virtual MafiaNet::RM3ActionOnPopConnection QueryActionOnPopConnection(MafiaNet::Connection_RM3 *droppedConnection) const {return r3CompositeOwner->QueryActionOnPopConnection(droppedConnection);} - virtual void OnPoppedConnection(MafiaNet::Connection_RM3 *droppedConnection) {r3CompositeOwner->OnPoppedConnection(droppedConnection);} - virtual void DeallocReplica(MafiaNet::Connection_RM3 *sourceConnection) {r3CompositeOwner->DeallocReplica(sourceConnection);} - virtual MafiaNet::RM3QuerySerializationResult QuerySerialization(MafiaNet::Connection_RM3 *destinationConnection) {return r3CompositeOwner->QuerySerialization(destinationConnection);} - virtual void OnUserReplicaPreSerializeTick(void) {r3CompositeOwner->OnUserReplicaPreSerializeTick();} - virtual MafiaNet::RM3SerializationResult Serialize(MafiaNet::SerializeParameters *serializeParameters) {return r3CompositeOwner->Serialize(serializeParameters);} - virtual void OnSerializeTransmission(MafiaNet::BitStream *bitStream, MafiaNet::Connection_RM3 *destinationConnection, MafiaNet::BitSize_t bitsPerChannel[MafiaNet::RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], MafiaNet::Time curTime) {r3CompositeOwner->OnSerializeTransmission(bitStream, destinationConnection, bitsPerChannel, curTime);} - virtual void Deserialize(MafiaNet::DeserializeParameters *deserializeParameters) {r3CompositeOwner->Deserialize(deserializeParameters);} - virtual void PostSerializeConstruction(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *destinationConnection) {r3CompositeOwner->PostSerializeConstruction(constructionBitstream, destinationConnection);} - virtual void PostDeserializeConstruction(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *sourceConnection) {r3CompositeOwner->PostDeserializeConstruction(constructionBitstream, sourceConnection);} - virtual void PostSerializeConstructionExisting(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *destinationConnection) {r3CompositeOwner->PostSerializeConstructionExisting(constructionBitstream, destinationConnection);} - virtual void PostDeserializeConstructionExisting(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *sourceConnection) {r3CompositeOwner->PostDeserializeConstructionExisting(constructionBitstream, sourceConnection);} - virtual void PreDestruction(MafiaNet::Connection_RM3 *sourceConnection) {r3CompositeOwner->PreDestruction(sourceConnection);} -}; - -} // namespace MafiaNet - - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/Router2.h b/vendors/mafianet/Source/include/mafianet/Router2.h deleted file mode 100644 index 879aa27a4..000000000 --- a/vendors/mafianet/Source/include/mafianet/Router2.h +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Router2 plugin. Allows you to connect to a system by routing packets through another system that is connected to both you and the destination. Useful for getting around NATs. -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_Router2==1 && _RAKNET_SUPPORT_UDPForwarder==1 - -#ifndef __ROUTER_2_PLUGIN_H -#define __ROUTER_2_PLUGIN_H - -#include "types.h" -#include "PluginInterface2.h" -#include "PacketPriority.h" -#include "Export.h" -#include "UDPForwarder.h" -#include "MessageIdentifiers.h" -#include "DS_List.h" -#include "SimpleMutex.h" - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; - -struct Router2DebugInterface -{ - Router2DebugInterface() {} - virtual ~Router2DebugInterface() {} - virtual void ShowFailure(const char *message); - virtual void ShowDiagnostic(const char *message); -}; - -/// \defgroup ROUTER_2_GROUP Router2 -/// \brief Part of the NAT punchthrough solution, allowing you to connect to systems by routing through a shared connection. -/// \details Router2 routes datagrams between two systems that are not directly connected by using the bandwidth of a third system, to which the other two systems were connected -/// It is of benefit when a fully connected mesh topology is desired, but could not be completely established due to routers and/or firewalls -/// As the system address of a remote system will be the system address of the intermediary, it is necessary to use the RakNetGUID object to refer to systems, including with other plugins -/// \ingroup PLUGINS_GROUP - -/// \ingroup ROUTER_2_GROUP -/// \brief Class interface for the Router2 system -/// \details -class RAK_DLL_EXPORT Router2 : public PluginInterface2 -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(Router2) - - Router2(); - virtual ~Router2(); - - /// Sets the socket family to use, either IPV4 or IPV6 - /// \param[in] socketFamily For IPV4, use AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC. - void SetSocketFamily(unsigned short _socketFamily); - - /// \brief Query all connected systems to connect through them to a third system. - /// System will return ID_ROUTER_2_FORWARDING_NO_PATH if unable to connect. - /// Else you will get ID_ROUTER_2_FORWARDING_ESTABLISHED - /// - /// On ID_ROUTER_2_FORWARDING_ESTABLISHED, EstablishRouting as follows: - /// - /// MafiaNet::BitStream bs(packet->data, packet->length, false); - /// bs.IgnoreBytes(sizeof(MessageID)); - /// RakNetGUID endpointGuid; - /// bs.Read(endpointGuid); - /// unsigned short sourceToDestPort; - /// bs.Read(sourceToDestPort); - /// char ipAddressString[32]; - /// packet->systemAddress.ToString(false, ipAddressString); - /// rakPeerInterface->EstablishRouting(ipAddressString, sourceToDestPort, 0,0); - /// - /// \note The SystemAddress for a connection should not be used - always use RakNetGuid as the address can change at any time. - /// When the address changes, you will get ID_ROUTER_2_REROUTED - void EstablishRouting(RakNetGUID endpointGuid); - - /// Set the maximum number of bidirectional connections this system will support - /// Defaults to 0 - void SetMaximumForwardingRequests(int max); - - /// For testing and debugging - void SetDebugInterface(Router2DebugInterface *_debugInterface); - - /// Get the pointer passed to SetDebugInterface() - Router2DebugInterface *GetDebugInterface(void) const; - - // -------------------------------------------------------------------------------------------- - // Packet handling functions - // -------------------------------------------------------------------------------------------- - virtual PluginReceiveResult OnReceive(Packet *packet); - virtual void Update(void); - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - virtual void OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason); - virtual void OnRakPeerShutdown(void); - - - enum Router2RequestStates - { - R2RS_REQUEST_STATE_QUERY_FORWARDING, - REQUEST_STATE_REQUEST_FORWARDING, - }; - - struct ConnectionRequestSystem - { - RakNetGUID guid; - int pingToEndpoint; - unsigned short usedForwardingEntries; - }; - - struct ConnnectRequest - { - ConnnectRequest(); - ~ConnnectRequest(); - - DataStructures::List connectionRequestSystems; - SimpleMutex connectionRequestSystemsMutex; - Router2RequestStates requestState; - MafiaNet::TimeMS pingTimeout; - RakNetGUID endpointGuid; - RakNetGUID lastRequestedForwardingSystem; - bool returnConnectionLostOnFailure; - unsigned int GetGuidIndex(RakNetGUID guid); - }; - - unsigned int GetConnectionRequestIndex(RakNetGUID endpointGuid); - - struct MiniPunchRequest - { - RakNetGUID endpointGuid; - SystemAddress endpointAddress; - bool gotReplyFromEndpoint; - RakNetGUID sourceGuid; - SystemAddress sourceAddress; - bool gotReplyFromSource; - MafiaNet::TimeMS timeout; - MafiaNet::TimeMS nextAction; - unsigned short forwardingPort; - __UDPSOCKET__ forwardingSocket; - }; - - struct ForwardedConnection - { - RakNetGUID endpointGuid; - RakNetGUID intermediaryGuid; - SystemAddress intermediaryAddress; - bool returnConnectionLostOnFailure; - bool weInitiatedForwarding; - }; - -protected: - - bool UpdateForwarding(ConnnectRequest* connectionRequest); - void RemoveConnectionRequest(unsigned int connectionRequestIndex); - void RequestForwarding(ConnnectRequest* connectionRequest); - void OnQueryForwarding(Packet *packet); - void OnQueryForwardingReply(Packet *packet); - void OnRequestForwarding(Packet *packet); - void OnRerouted(Packet *packet); - void OnMiniPunchReply(Packet *packet); - void OnMiniPunchReplyBounce(Packet *packet); - bool OnForwardingSuccess(Packet *packet); - int GetLargestPingAmongConnectedSystems(void) const; - void ReturnToUser(MessageID messageId, RakNetGUID endpointGuid, const SystemAddress &systemAddress, bool wasGeneratedLocally); - bool ConnectInternal(RakNetGUID endpointGuid, bool returnConnectionLostOnFailure); - - UDPForwarder *udpForwarder; - int maximumForwardingRequests; - SimpleMutex connectionRequestsMutex, miniPunchesInProgressMutex, forwardedConnectionListMutex; - DataStructures::List connectionRequests; - DataStructures::List miniPunchesInProgress; - // Forwarding we have initiated - DataStructures::List forwardedConnectionList; - - void ClearConnectionRequests(void); - void ClearMinipunches(void); - void ClearForwardedConnections(void); - void ClearAll(void); - int ReturnFailureOnCannotForward(RakNetGUID sourceGuid, RakNetGUID endpointGuid); - void SendFailureOnCannotForward(RakNetGUID sourceGuid, RakNetGUID endpointGuid); - void SendForwardingSuccess(MessageID messageId, RakNetGUID sourceGuid, RakNetGUID endpointGuid, unsigned short sourceToDstPort); - void SendOOBFromRakNetPort(OutOfBandIdentifiers oob, BitStream *extraData, SystemAddress sa); - void SendOOBFromSpecifiedSocket(OutOfBandIdentifiers oob, SystemAddress sa, __UDPSOCKET__ socket); - void SendOOBMessages(MiniPunchRequest *mpr); - - Router2DebugInterface *debugInterface; - unsigned short socketFamily; -}; - -} - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/SecureHandshake.h b/vendors/mafianet/Source/include/mafianet/SecureHandshake.h deleted file mode 100644 index 391b13f81..000000000 --- a/vendors/mafianet/Source/include/mafianet/SecureHandshake.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -/// \file -/// - - -#ifndef SECURE_HANDSHAKE_H -#define SECURE_HANDSHAKE_H - -#include "NativeFeatureIncludes.h" - -#if LIBCAT_SECURITY==1 - -// If building a MafiaNet DLL, be sure to tweak the CAT_EXPORT macro meaning -#if !defined(_MAFIANET_LIB) && defined(_MAFIANET_DLL) -# define CAT_BUILD_DLL -#else -# define CAT_NEUTER_EXPORT -#endif - -// Include DependentExtensions in your path to include this -#ifdef _M_X64 -#pragma warning(push) -#pragma warning(disable:4838) -#endif -#include "cat/AllTunnel.hpp" -#ifdef _M_X64 -#pragma warning(pop) -#endif - -#endif // LIBCAT_SECURITY - -#endif // SECURE_HANDSHAKE_H diff --git a/vendors/mafianet/Source/include/mafianet/SendToThread.h b/vendors/mafianet/Source/include/mafianet/SendToThread.h deleted file mode 100644 index f097fb6ca..000000000 --- a/vendors/mafianet/Source/include/mafianet/SendToThread.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __SENDTO_THREAD -#define __SENDTO_THREAD - -#include "defines.h" - -#ifdef USE_THREADED_SEND - -#include "InternalPacket.h" -#include "SocketLayer.h" -#include "DS_ThreadsafeAllocatingQueue.h" -#include "ThreadPool.h" - -namespace MafiaNet -{ -class SendToThread -{ -public: - SendToThread(); - ~SendToThread(); - - struct SendToThreadBlock - { - SOCKET s; - SystemAddress systemAddress; - unsigned short remotePortRakNetWasStartedOn_PS3; - unsigned int extraSocketOptions; - char data[MAXIMUM_MTU_SIZE]; - unsigned short dataWriteOffset; - }; - - static SendToThreadBlock* AllocateBlock(void); - static void ProcessBlock(SendToThreadBlock* threadedSend); - - static void AddRef(void); - static void Deref(void); - static DataStructures::ThreadsafeAllocatingQueue objectQueue; -protected: - static int refCount; - static ThreadPool threadPool; - -}; -} - - -#endif - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/SignaledEvent.h b/vendors/mafianet/Source/include/mafianet/SignaledEvent.h deleted file mode 100644 index 75d88b0d3..000000000 --- a/vendors/mafianet/Source/include/mafianet/SignaledEvent.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __SIGNALED_EVENT_H -#define __SIGNALED_EVENT_H - - - -#if defined(_WIN32) -#include "WindowsIncludes.h" - - - -#else - #include - #include - #include "SimpleMutex.h" - - - - -#endif - -#include "Export.h" - -namespace MafiaNet -{ - -class RAK_DLL_EXPORT SignaledEvent -{ -public: - SignaledEvent(); - ~SignaledEvent(); - - void InitEvent(void); - void CloseEvent(void); - void SetEvent(void); - void WaitOnEvent(int timeoutMs); - -protected: -#ifdef _WIN32 - HANDLE eventList; - - - - - -#else - SimpleMutex isSignaledMutex; - bool isSignaled; -#if !defined(ANDROID) - pthread_condattr_t condAttr; -#endif - pthread_cond_t eventList; - pthread_mutex_t hMutex; - pthread_mutexattr_t mutexAttr; -#endif -}; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/SimpleMutex.h b/vendors/mafianet/Source/include/mafianet/SimpleMutex.h deleted file mode 100644 index ed3444f55..000000000 --- a/vendors/mafianet/Source/include/mafianet/SimpleMutex.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief \b [Internal] Encapsulates a mutex -/// - - - -#ifndef __SIMPLE_MUTEX_H -#define __SIMPLE_MUTEX_H - -#include "memoryoverride.h" - - -#if defined(_WIN32) -#include "WindowsIncludes.h" - - -#else -#include -#include -#endif -#include "Export.h" - -namespace MafiaNet -{ - -/// \brief An easy to use mutex. -/// -/// I wrote this because the version that comes with Windows is too complicated and requires too much code to use. -/// @remark Previously I used this everywhere, and in fact for a year or two RakNet was totally threadsafe. While doing profiling, I saw that this function was incredibly slow compared to the blazing performance of everything else, so switched to single producer / consumer everywhere. Now the user thread of RakNet is not threadsafe, but it's 100X faster than before. -class RAK_DLL_EXPORT SimpleMutex -{ -public: - - // Constructor - SimpleMutex(); - - // Destructor - ~SimpleMutex(); - - // Locks the mutex. Slow! - void Lock(void); - - // Unlocks the mutex. - void Unlock(void); - - - - - - - -private: - void Init(void); -#ifdef _WIN32 - CRITICAL_SECTION criticalSection; /// Docs say this is faster than a mutex for single process access - - -#else - pthread_mutex_t hMutex; -#endif - // Not threadsafe - // bool isInitialized; -}; - -} // namespace MafiaNet - -#endif - diff --git a/vendors/mafianet/Source/include/mafianet/SimpleTCPServer.h b/vendors/mafianet/Source/include/mafianet/SimpleTCPServer.h deleted file mode 100644 index 268a51dde..000000000 --- a/vendors/mafianet/Source/include/mafianet/SimpleTCPServer.h +++ /dev/null @@ -1,6 +0,0 @@ -/* - * This file was taken from RakNet 4.082 without any modifications. - * Please see licenses/RakNet license.txt for the underlying license and related copyright. - */ - -// Eraseme diff --git a/vendors/mafianet/Source/include/mafianet/SingleProducerConsumer.h b/vendors/mafianet/Source/include/mafianet/SingleProducerConsumer.h deleted file mode 100644 index 094ebd2ab..000000000 --- a/vendors/mafianet/Source/include/mafianet/SingleProducerConsumer.h +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief \b [Internal] Passes queued data between threads using a circular buffer with read and write pointers -/// - - - -#ifndef __SINGLE_PRODUCER_CONSUMER_H -#define __SINGLE_PRODUCER_CONSUMER_H - -#include "assert.h" - -static const int MINIMUM_LIST_SIZE=8; - -#include "memoryoverride.h" -#include "Export.h" - -/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures -/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. -namespace DataStructures -{ - /// \brief A single producer consumer implementation without critical sections. - template - class RAK_DLL_EXPORT SingleProducerConsumer - { - public: - // Constructor - SingleProducerConsumer(); - - // Destructor - ~SingleProducerConsumer(); - - /// WriteLock must be immediately followed by WriteUnlock. These two functions must be called in the same thread. - /// \return A pointer to a block of data you can write to. - SingleProducerConsumerType* WriteLock(void); - - /// Call if you don't want to write to a block of data from WriteLock() after all. - /// Cancelling locks cancels all locks back up to the data passed. So if you lock twice and cancel using the first lock, the second lock is ignored - /// \param[in] cancelToLocation Which WriteLock() to cancel. - void CancelWriteLock(SingleProducerConsumerType* cancelToLocation); - - /// Call when you are done writing to a block of memory returned by WriteLock() - void WriteUnlock(void); - - /// ReadLock must be immediately followed by ReadUnlock. These two functions must be called in the same thread. - /// \retval 0 No data is availble to read - /// \retval Non-zero The data previously written to, in another thread, by WriteLock followed by WriteUnlock. - SingleProducerConsumerType* ReadLock(void); - - // Cancelling locks cancels all locks back up to the data passed. So if you lock twice and cancel using the first lock, the second lock is ignored - /// param[in] Which ReadLock() to cancel. - void CancelReadLock(SingleProducerConsumerType* cancelToLocation); - - /// Signals that we are done reading the the data from the least recent call of ReadLock. - /// At this point that pointer is no longer valid, and should no longer be read. - void ReadUnlock(void); - - /// Clear is not thread-safe and none of the lock or unlock functions should be called while it is running. - void Clear(void); - - /// This function will estimate how many elements are waiting to be read. It's threadsafe enough that the value returned is stable, but not threadsafe enough to give accurate results. - /// \return An ESTIMATE of how many data elements are waiting to be read - int Size(void) const; - - /// Make sure that the pointer we done reading for the call to ReadUnlock is the right pointer. - /// param[in] A previous pointer returned by ReadLock() - bool CheckReadUnlockOrder(const SingleProducerConsumerType* data) const; - - /// Returns if ReadUnlock was called before ReadLock - /// \return If the read is locked - bool ReadIsLocked(void) const; - - private: - struct DataPlusPtr - { - DataPlusPtr () {readyToRead=false;} - SingleProducerConsumerType object; - - // Ready to read is so we can use an equality boolean comparison, in case the writePointer var is trashed while context switching. - volatile bool readyToRead; - volatile DataPlusPtr *next; - }; - volatile DataPlusPtr *readAheadPointer; - volatile DataPlusPtr *writeAheadPointer; - volatile DataPlusPtr *readPointer; - volatile DataPlusPtr *writePointer; - unsigned readCount, writeCount; - }; - - template - SingleProducerConsumer::SingleProducerConsumer() - { - // Preallocate - readPointer = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - writePointer=readPointer; - readPointer->next = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - int listSize; -#ifdef _DEBUG - RakAssert(MINIMUM_LIST_SIZE>=3); -#endif - for (listSize=2; listSize < MINIMUM_LIST_SIZE; listSize++) - { - readPointer=readPointer->next; - readPointer->next = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - } - readPointer->next->next=writePointer; // last to next = start - readPointer=writePointer; - readAheadPointer=readPointer; - writeAheadPointer=writePointer; - readCount=writeCount=0; - } - - template - SingleProducerConsumer::~SingleProducerConsumer() - { - volatile DataPlusPtr *next; - readPointer=writeAheadPointer->next; - while (readPointer!=writeAheadPointer) - { - next=readPointer->next; - MafiaNet::OP_DELETE((char*) readPointer, _FILE_AND_LINE_); - readPointer=next; - } - MafiaNet::OP_DELETE((char*) readPointer, _FILE_AND_LINE_); - } - - template - SingleProducerConsumerType* SingleProducerConsumer::WriteLock( void ) - { - if (writeAheadPointer->next==readPointer || - writeAheadPointer->next->readyToRead==true) - { - volatile DataPlusPtr *originalNext=writeAheadPointer->next; - writeAheadPointer->next= MafiaNet::OP_NEW(_FILE_AND_LINE_); - RakAssert(writeAheadPointer->next); - writeAheadPointer->next->next=originalNext; - } - - volatile DataPlusPtr *last; - last=writeAheadPointer; - writeAheadPointer=writeAheadPointer->next; - - return (SingleProducerConsumerType*) last; - } - - template - void SingleProducerConsumer::CancelWriteLock( SingleProducerConsumerType* cancelToLocation ) - { - writeAheadPointer=(DataPlusPtr *)cancelToLocation; - } - - template - void SingleProducerConsumer::WriteUnlock( void ) - { - // DataPlusPtr *dataContainer = (DataPlusPtr *)structure; - -#ifdef _DEBUG - RakAssert(writePointer->next!=readPointer); - RakAssert(writePointer!=writeAheadPointer); -#endif - - writeCount++; - // User is done with the data, allow send by updating the write pointer - writePointer->readyToRead=true; - writePointer=writePointer->next; - } - - template - SingleProducerConsumerType* SingleProducerConsumer::ReadLock( void ) - { - if (readAheadPointer==writePointer || - readAheadPointer->readyToRead==false) - { - return 0; - } - - volatile DataPlusPtr *last; - last=readAheadPointer; - readAheadPointer=readAheadPointer->next; - return (SingleProducerConsumerType*)last; - } - - template - void SingleProducerConsumer::CancelReadLock( SingleProducerConsumerType* cancelToLocation ) - { -#ifdef _DEBUG - RakAssert(readPointer!=writePointer); -#endif - readAheadPointer=(DataPlusPtr *)cancelToLocation; - } - - template - void SingleProducerConsumer::ReadUnlock( void ) - { -#ifdef _DEBUG - RakAssert(readAheadPointer!=readPointer); // If hits, then called ReadUnlock before ReadLock - RakAssert(readPointer!=writePointer); // If hits, then called ReadUnlock when Read returns 0 -#endif - readCount++; - - // Allow writes to this memory block - readPointer->readyToRead=false; - readPointer=readPointer->next; - } - - template - void SingleProducerConsumer::Clear( void ) - { - // Shrink the list down to MINIMUM_LIST_SIZE elements - volatile DataPlusPtr *next; - writePointer=readPointer->next; - - int listSize=1; - next=readPointer->next; - while (next!=readPointer) - { - listSize++; - next=next->next; - } - - while (listSize-- > MINIMUM_LIST_SIZE) - { - next=writePointer->next; -#ifdef _DEBUG - RakAssert(writePointer!=readPointer); -#endif - MafiaNet::OP_DELETE((char*) writePointer, _FILE_AND_LINE_); - writePointer=next; - } - - readPointer->next=writePointer; - writePointer=readPointer; - readAheadPointer=readPointer; - writeAheadPointer=writePointer; - readCount=writeCount=0; - } - - template - int SingleProducerConsumer::Size( void ) const - { - return writeCount-readCount; - } - - template - bool SingleProducerConsumer::CheckReadUnlockOrder(const SingleProducerConsumerType* data) const - { - return const_cast(&readPointer->object) == data; - } - - - template - bool SingleProducerConsumer::ReadIsLocked(void) const - { - return readAheadPointer!=readPointer; - } -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/SocketDefines.h b/vendors/mafianet/Source/include/mafianet/SocketDefines.h deleted file mode 100644 index 18f09001c..000000000 --- a/vendors/mafianet/Source/include/mafianet/SocketDefines.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __SOCKET_DEFINES_H -#define __SOCKET_DEFINES_H - -/// Internal - #if defined(_WIN32) - #define closesocket__ closesocket - #define select__ select - #elif defined(__native_client__) - // namespace MafiaNet { void CloseSocket(SOCKET s); } - // #define closesocket__ MafiaNet::CloseSocket - #define select__ select - #else - #define closesocket__ close - #define select__ select - #endif - #define accept__ accept - #define connect__ connect - - - - #define socket__ socket - - #define bind__ bind - #define getsockname__ getsockname - #define getsockopt__ getsockopt - - - - #define ioctlsocket__ ioctlsocket - #define listen__ listen - #define recv__ recv - #define recvfrom__ recvfrom - - - - #define sendto__ sendto - - #define send__ send - - - - #define setsockopt__ setsockopt - - #define shutdown__ shutdown - #define WSASendTo__ WSASendTo -#endif diff --git a/vendors/mafianet/Source/include/mafianet/SocketIncludes.h b/vendors/mafianet/Source/include/mafianet/SocketIncludes.h deleted file mode 100644 index 56ecc2469..000000000 --- a/vendors/mafianet/Source/include/mafianet/SocketIncludes.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - * This file was taken from RakNet 4.082. - * Please see licenses/RakNet license.txt for the underlying license and related copyright. - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef RAKNET_SOCKETINCLUDES_H -#define RAKNET_SOCKETINCLUDES_H - -// All this crap just to include type SOCKET - -#ifdef __native_client__ -#define _PP_Instance_ PP_Instance -#else -#define _PP_Instance_ int -#endif - - - - - - - - - - - - - - - - - - - - -#if defined(_WIN32) - // IP_DONTFRAGMENT is different between winsock 1 and winsock 2. Therefore, Winsock2.h must be linked againt Ws2_32.lib - // winsock.h must be linked against WSock32.lib. If these two are mixed up the flag won't work correctly - // WinRT: http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.sockets - // Sample code: http://stackoverflow.com/questions/10290945/correct-use-of-udp-datagramsocket - #include - typedef SOCKET __UDPSOCKET__; - typedef SOCKET __TCPSOCKET__; - typedef int socklen_t; -#else - #define closesocket close - #include - #include - #include - #include - #include - #include - #include - - #ifdef __native_client__ - #include "ppapi/cpp/private/net_address_private.h" - #include "ppapi/c/pp_bool.h" - #include "ppapi/c/pp_errors.h" - #include "ppapi/cpp/completion_callback.h" - #include "ppapi/cpp/instance_handle.h" - #include "ppapi/cpp/module.h" - #include "ppapi/cpp/module_impl.h" - #include "ppapi/c/pp_errors.h" - #include "ppapi/c/pp_module.h" - #include "ppapi/c/pp_var.h" - #include "ppapi/c/pp_resource.h" - #include "ppapi/c/ppb.h" - #include "ppapi/c/ppb_instance.h" - #include "ppapi/c/ppb_messaging.h" - #include "ppapi/c/ppb_var.h" - #include "ppapi/c/ppp.h" - #include "ppapi/c/ppb_core.h" - #include "ppapi/c/ppp_instance.h" - #include "ppapi/c/ppp_messaging.h" - #include "ppapi/c/pp_input_event.h" - #include "ppapi/c/pp_completion_callback.h" - //UDP specific - the 'private' folder was copied from the chromium src/ppapi/c headers folder - #include "ppapi/c/private/ppb_udp_socket_private.h" - #include "ppapi/cpp/private/net_address_private.h" - typedef PP_Resource __UDPSOCKET__; - typedef PP_Resource __TCPSOCKET__; - #else - //#include "memoryoverride.h" - /// Unix/Linux uses ints for sockets - typedef int __UDPSOCKET__; - typedef int __TCPSOCKET__; - /// Define SOCKET for cross-platform compatibility with Windows code - typedef int SOCKET; - #define INVALID_SOCKET -1 -#endif - -#endif - -#endif // RAKNET_SOCKETINCLUDES_H diff --git a/vendors/mafianet/Source/include/mafianet/SocketLayer.h b/vendors/mafianet/Source/include/mafianet/SocketLayer.h deleted file mode 100644 index 1ef88e71c..000000000 --- a/vendors/mafianet/Source/include/mafianet/SocketLayer.h +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief SocketLayer class implementation -/// - - - - -#ifndef __SOCKET_LAYER_H -#define __SOCKET_LAYER_H - -#include "memoryoverride.h" -#include "types.h" -#include "smartptr.h" -//#include "socket.h" -#include "Export.h" -#include "MTUSize.h" -#include "string.h" - -//#include "ClientContextStruct.h" - -namespace MafiaNet -{ -/// Forward declarations -class RakPeer; - -/* -class RAK_DLL_EXPORT SocketLayerOverride -{ -public: - SocketLayerOverride() {} - virtual ~SocketLayerOverride() {} - - /// Called when SendTo would otherwise occur. - virtual int RakNetSendTo( const char *data, int length, const SystemAddress &systemAddress )=0; - - /// Called when RecvFrom would otherwise occur. Return number of bytes read. Write data into dataOut - // Return -1 to use RakNet's normal recvfrom, 0 to abort RakNet's normal recvfrom, and positive to return data - virtual int RakNetRecvFrom( char dataOut[ MAXIMUM_MTU_SIZE ], SystemAddress *senderOut, bool calledFromMainThread )=0; -}; -*/ - -// A platform independent implementation of Berkeley sockets, with settings used by RakNet -class RAK_DLL_EXPORT SocketLayer -{ - -public: - - /// Default Constructor - SocketLayer(); - - // Destructor - ~SocketLayer(); - - /* - /// Creates a bound socket to listen for incoming connections on the specified port - /// \param[in] port the port number - /// \param[in] blockingSocket - /// \return A new socket used for accepting clients - static RakNetSocket* CreateBoundSocket( RakPeer *peer, unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned int sleepOn10048, unsigned int extraSocketOptions, unsigned short socketFamily, _PP_Instance_ chromeInstance ); - static RakNetSocket* CreateBoundSocket_IPV4( RakPeer *peer, unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned int sleepOn10048, unsigned int extraSocketOptions, _PP_Instance_ chromeInstance ); - #if RAKNET_SUPPORT_IPV6==1 - static RakNetSocket* CreateBoundSocket_SupportIPV4And6( RakPeer *peer, unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned int sleepOn10048, unsigned int extraSocketOptions, unsigned short socketFamily, _PP_Instance_ chromeInstance ); - #endif - static RakNetSocket* CreateBoundSocket_PS3Lobby( unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned short socketFamily ); - static RakNetSocket* CreateBoundSocket_PSP2( unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned short socketFamily ); - */ - - /* - /// Returns if this specified port is in use, for UDP - /// \param[in] port the port number - /// \return If this port is already in use - //static bool IsPortInUse_Old(unsigned short port, const char *hostAddress); - //static bool IsPortInUse(unsigned short port, const char *hostAddress, unsigned short socketFamily ); - static bool IsSocketFamilySupported(const char *hostAddress, unsigned short socketFamily); - */ - -// static const char* DomainNameToIP_Old( const char *domainName ); -// static const char* DomainNameToIP( const char *domainName ); - - /// Write \a data of length \a length to \a writeSocket - /// \param[in] writeSocket The socket to write to - /// \param[in] data The data to write - /// \param[in] length The length of \a data - // static void Write( RakNetSocket*writeSocket, const char* data, const int length ); - - /// Read data from a socket - /// \param[in] s the socket - /// \param[in] rakPeer The instance of rakPeer containing the recvFrom C callback - /// \param[in] errorCode An error code if an error occured . - /// \param[in] connectionSocketIndex Which of the sockets in RakPeer we are using - /// \return Returns true if you successfully read data, false on error. -// static void RecvFromBlocking_IPV4( RakNetSocket *s, RakPeer *rakPeer, char *dataOut, int *bytesReadOut, SystemAddress *systemAddressOut, MafiaNet::TimeUS *timeRead ); -// #if RAKNET_SUPPORT_IPV6==1 -// static void RecvFromBlockingIPV4And6( RakNetSocket *s, RakPeer *rakPeer, char *dataOut, int *bytesReadOut, SystemAddress *systemAddressOut, MafiaNet::TimeUS *timeRead ); -// #endif -// static void RecvFromBlocking( RakNetSocket *s, RakPeer *rakPeer, char *dataOut, int *bytesReadOut, SystemAddress *systemAddressOut, MafiaNet::TimeUS *timeRead ); - - /// Given a socket and IP, retrieves the subnet mask, on linux the socket is unused - /// \param[in] inSock the socket - /// \param[in] inIpString The ip of the interface you wish to retrieve the subnet mask from - /// \return Returns the ip dotted subnet mask if successful, otherwise returns empty string ("") - static MafiaNet::RakString GetSubNetForSocketAndIp(__UDPSOCKET__ inSock, MafiaNet::RakString inIpString); - - - /// Sets the socket flags to nonblocking - /// \param[in] listenSocket the socket to set -// static void SetNonBlocking( RakNetSocket* listenSocket); - - - /// Retrieve all local IP address in a string format. - /// \param[in] s The socket whose port we are referring to - /// \param[in] ipList An array of ip address in dotted notation. - static void GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); - - - /// Call sendto (UDP obviously) - /// \param[in] s the socket - /// \param[in] data The byte buffer to send - /// \param[in] length The length of the \a data in bytes - /// \param[in] ip The address of the remote host in dotted notation. - /// \param[in] port The port number to send to. - /// \return 0 on success, nonzero on failure. -// static int SendTo( UDPSOCKET s, const char *data, int length, const char ip[ 16 ], unsigned short port, unsigned short remotePortRakNetWasStartedOn_PS3, unsigned int extraSocketOptions, const char *file, const long line ); - - /// Call sendto' (UDP obviously) - /// It won't reach the recipient, except on a LAN - /// However, this is good for opening routers / firewalls - /// \param[in] s the socket - /// \param[in] data The byte buffer to send - /// \param[in] length The length of the \a data in bytes - /// \param[in] ip The address of the remote host in dotted notation. - /// \param[in] port The port number to send to. - /// \param[in] ttl Max hops of datagram - /// \return 0 on success, nonzero on failure. -// static int SendToTTL( RakNetSocket *s, const char *data, int length, SystemAddress &systemAddress, int ttl ); - - /// Call sendto (UDP obviously) - /// \param[in] s the socket - /// \param[in] data The byte buffer to send - /// \param[in] length The length of the \a data in bytes - /// \param[in] binaryAddress The address of the remote host in binary format. - /// \param[in] port The port number to send to. - /// \return 0 on success, nonzero on failure. -// static int SendTo( RakNetSocket *s, const char *data, int length, SystemAddress systemAddress, const char *file, const long line ); - -// static unsigned short GetLocalPort(RakNetSocket *s); - static unsigned short GetLocalPort( __UDPSOCKET__ s); -// static void GetSystemAddress_Old ( RakNetSocket *s, SystemAddress *systemAddressOut ); - static void GetSystemAddress_Old ( __UDPSOCKET__ s, SystemAddress *systemAddressOut ); -// static void GetSystemAddress ( RakNetSocket *s, SystemAddress *systemAddressOut ); - static void GetSystemAddress ( __UDPSOCKET__ s, SystemAddress *systemAddressOut ); - -// static void SetSocketLayerOverride(SocketLayerOverride *_slo); -// static SocketLayerOverride* GetSocketLayerOverride(void) {return slo;} - -// static int SendTo_PS3Lobby( RakNetSocket *s, const char *data, int length, const SystemAddress &systemAddress ); -// static int SendTo_PSP2( RakNetSocket *s, const char *data, int length, const SystemAddress &systemAddress ); -// static int SendTo_360( RakNetSocket *s, const char *data, int length, const char *voiceData, int voiceLength, const SystemAddress &systemAddress ); -// static int SendTo_PC( RakNetSocket *s, const char *data, int length, const SystemAddress &systemAddress, const char *file, const long line ); -// -// static void SetDoNotFragment( RakNetSocket* listenSocket, int opt ); -// static void SetSocketOptions( RakNetSocket* listenSocket, bool blockingSocket, bool setBroadcast); - static void SetSocketOptions( __UDPSOCKET__ listenSocket, bool blockingSocket, bool setBroadcast); - - - // AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC. - static bool GetFirstBindableIP(char firstBindable[128], int ipProto); - -private: - -// static SocketLayerOverride *slo; -}; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/StatisticsHistory.h b/vendors/mafianet/Source/include/mafianet/StatisticsHistory.h deleted file mode 100644 index 179a5f449..000000000 --- a/vendors/mafianet/Source/include/mafianet/StatisticsHistory.h +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file StatisticsHistory.h -/// \brief Input numerical values over time. Get sum, average, highest, lowest, standard deviation on recent or all-time values - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_StatisticsHistory==1 - -#ifndef __STATISTICS_HISTORY_H -#define __STATISTICS_HISTORY_H - -#include "PluginInterface2.h" -#include "memoryoverride.h" -#include "NativeTypes.h" -#include "DS_List.h" -#include "types.h" -#include "DS_OrderedList.h" -#include "string.h" -#include "DS_Queue.h" -#include "DS_Hash.h" -#include - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; - -// Type used to track values. If needed, change to double and recompile -typedef double SHValueType; -#define SH_TYPE_MAX DBL_MAX - -/// \brief Input numerical values over time. Get sum, average, highest, lowest, standard deviation on recent or all-time values -class RAK_DLL_EXPORT StatisticsHistory -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(StatisticsHistory) - - enum SHErrorCode - { - SH_OK, - SH_UKNOWN_OBJECT, - SH_UKNOWN_KEY, - SH_INVALID_PARAMETER, - }; - - enum SHSortOperation - { - SH_DO_NOT_SORT, - - SH_SORT_BY_RECENT_SUM_ASCENDING, - SH_SORT_BY_RECENT_SUM_DESCENDING, - SH_SORT_BY_LONG_TERM_SUM_ASCENDING, - SH_SORT_BY_LONG_TERM_SUM_DESCENDING, - SH_SORT_BY_RECENT_SUM_OF_SQUARES_ASCENDING, - SH_SORT_BY_RECENT_SUM_OF_SQUARES_DESCENDING, - SH_SORT_BY_RECENT_AVERAGE_ASCENDING, - SH_SORT_BY_RECENT_AVERAGE_DESCENDING, - SH_SORT_BY_LONG_TERM_AVERAGE_ASCENDING, - SH_SORT_BY_LONG_TERM_AVERAGE_DESCENDING, - SH_SORT_BY_RECENT_HIGHEST_ASCENDING, - SH_SORT_BY_RECENT_HIGHEST_DESCENDING, - SH_SORT_BY_RECENT_LOWEST_ASCENDING, - SH_SORT_BY_RECENT_LOWEST_DESCENDING, - SH_SORT_BY_LONG_TERM_HIGHEST_ASCENDING, - SH_SORT_BY_LONG_TERM_HIGHEST_DESCENDING, - SH_SORT_BY_LONG_TERM_LOWEST_ASCENDING, - SH_SORT_BY_LONG_TERM_LOWEST_DESCENDING, - }; - - enum SHDataCategory - { - /// Insert values from one set into the other set, in time order - /// Values at the same time end up in the final set twice - /// Use when you have additional data points to add to a graph - DC_DISCRETE, - - /// Add values from one set to values from the other set, at corresponding times - /// If value at time t does not exist in the other set, linearly extrapolate value for other set based on nearest two data points - /// longTerm* values are unknown using this method - /// Use to add two graphs together - DC_CONTINUOUS - }; - - struct TimeAndValue; - struct TimeAndValueQueue; - - struct TrackedObjectData - { - TrackedObjectData(); - TrackedObjectData(uint64_t _objectId, int _objectType, void *_userData); - uint64_t objectId; - int objectType; - void *userData; - }; - - StatisticsHistory(); - virtual ~StatisticsHistory(); - void SetDefaultTimeToTrack(Time defaultTimeToTrack); - Time GetDefaultTimeToTrack(void) const; - bool AddObject(TrackedObjectData tod); - bool RemoveObject(uint64_t objectId, void **userData); - void RemoveObjectAtIndex(unsigned int index); - void Clear(void); - unsigned int GetObjectCount(void) const; - StatisticsHistory::TrackedObjectData * GetObjectAtIndex(unsigned int index) const; - unsigned int GetObjectIndex(uint64_t objectId) const; - bool AddValueByObjectID(uint64_t objectId, RakString key, SHValueType val, Time curTime, bool combineEqualTimes); - void AddValueByIndex(unsigned int index, RakString key, SHValueType val, Time curTime, bool combineEqualTimes); - SHErrorCode GetHistoryForKey(uint64_t objectId, RakString key, TimeAndValueQueue **values, Time curTime) const; - bool GetHistorySorted(uint64_t objectId, SHSortOperation sortType, DataStructures::List &values) const; - void MergeAllObjectsOnKey(RakString key, TimeAndValueQueue *tavqOutput, SHDataCategory dataCategory) const; - void GetUniqueKeyList(DataStructures::List &keys); - - struct TimeAndValue - { - Time time; - SHValueType val; - }; - - struct TimeAndValueQueue - { - TimeAndValueQueue(); - ~TimeAndValueQueue(); - - DataStructures::Queue values; - - Time timeToTrackValues; - RakString key; - - SHValueType recentSum; - SHValueType recentSumOfSquares; - SHValueType longTermSum; - SHValueType longTermCount; - SHValueType longTermLowest; - SHValueType longTermHighest; - - void SetTimeToTrackValues(Time t); - Time GetTimeToTrackValues(void) const; - SHValueType GetRecentSum(void) const; - SHValueType GetRecentSumOfSquares(void) const; - SHValueType GetLongTermSum(void) const; - SHValueType GetRecentAverage(void) const; - SHValueType GetRecentLowest(void) const; - SHValueType GetRecentHighest(void) const; - SHValueType GetRecentStandardDeviation(void) const; - SHValueType GetLongTermAverage(void) const; - SHValueType GetLongTermLowest(void) const; - SHValueType GetLongTermHighest(void) const; - SHValueType GetSumSinceTime(Time t) const; - Time GetTimeRange(void) const; - - // Merge two sets to output - static void MergeSets( const TimeAndValueQueue *lhs, SHDataCategory lhsDataCategory, const TimeAndValueQueue *rhs, SHDataCategory rhsDataCategory, TimeAndValueQueue *output ); - - // Shrink or expand a sample set to the approximate number given - // DC_DISCRETE will produce a histogram (sum) while DC_CONTINUOUS will produce an average - void ResizeSampleSet( int approximateSamples, DataStructures::Queue &blendedSamples, SHDataCategory dataCategory, Time timeClipStart=0, Time timeClipEnd=0 ); - - // Clear out all values - void Clear(void); - - TimeAndValueQueue& operator = ( const TimeAndValueQueue& input ); - - /// \internal - void CullExpiredValues(Time curTime); - /// \internal - static SHValueType Interpolate(TimeAndValue t1, TimeAndValue t2, Time time); - /// \internal - SHValueType sortValue; - }; - -protected: - struct TrackedObject; -public: - static int TrackedObjectComp( const uint64_t &key, TrackedObject* const &data ); -protected: - - struct TrackedObject - { - TrackedObject(); - ~TrackedObject(); - TrackedObjectData trackedObjectData; - DataStructures::Hash dataQueues; - }; - - DataStructures::OrderedList objects; - - Time timeToTrack; -}; - -/// \brief Input numerical values over time. Get sum, average, highest, lowest, standard deviation on recent or all-time values -/// \ingroup PLUGINS_GROUP -class RAK_DLL_EXPORT StatisticsHistoryPlugin : public PluginInterface2 -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(StatisticsHistoryPlugin) - - StatisticsHistory statistics; - - StatisticsHistoryPlugin(); - virtual ~StatisticsHistoryPlugin(); - void SetTrackConnections(bool _addNewConnections, int newConnectionsObjectType, bool _removeLostConnections); - -protected: - virtual void Update(void); - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); - - // Too slow -// virtual bool UsesReliabilityLayer(void) const {return true;} -// virtual void OnDirectSocketSend(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress); -// virtual void OnDirectSocketReceive(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress); - - - bool addNewConnections; - bool removeLostConnections; - int newConnectionsObjectType; -}; - -} // namespace MafiaNet - -#endif // __STATISTICS_HISTORY_H - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/StringCompressor.h b/vendors/mafianet/Source/include/mafianet/StringCompressor.h deleted file mode 100644 index b9ecc80dc..000000000 --- a/vendors/mafianet/Source/include/mafianet/StringCompressor.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017-2019, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief \b Compresses/Decompresses ASCII strings and writes/reads them to BitStream class instances. You can use this to easily serialize and deserialize your own strings. -/// - - - -#ifndef __STRING_COMPRESSOR_H -#define __STRING_COMPRESSOR_H - -#include "Export.h" -#include "DS_Map.h" -#include "memoryoverride.h" -#include "NativeTypes.h" - -#ifdef _STD_STRING_COMPRESSOR -#include -#endif - -/// Forward declaration -namespace MafiaNet -{ - class BitStream; - class RakString; -}; - - -namespace MafiaNet -{ -/// Forward declarations -class HuffmanEncodingTree; - -/// \brief Writes and reads strings to and from bitstreams. -/// -/// Only works with ASCII strings. The default compression is for English. -/// You can call GenerateTreeFromStrings to compress and decompress other languages efficiently as well. -class RAK_DLL_EXPORT StringCompressor -{ -public: - - // Destructor - ~StringCompressor(); - - /// static function because only static functions can access static members - /// The RakPeer constructor adds a reference to this class, so don't call this until an instance of RakPeer exists, or unless you call AddReference yourself. - /// \return the unique instance of the StringCompressor - static StringCompressor* Instance(void); - - /// Given an array of strings, such as a chat log, generate the optimal encoding tree for it. - /// This function is optional and if it is not called a default tree will be used instead. - /// \param[in] input An array of bytes which should point to text. - /// \param[in] inputLength Length of \a input - /// \param[in] languageID An identifier for the language / string table to generate the tree for. English is automatically created with ID 0 in the constructor. - void GenerateTreeFromStrings( unsigned char *input, unsigned inputLength, uint8_t languageId ); - - /// Writes input to output, compressed. Takes care of the null-terminator for you. - /// \param[in] input Pointer to an ASCII string - /// \param[in] maxCharsToWrite The max number of bytes to write of \a input. Use 0 to mean no limit. - /// \param[out] output The bitstream to write the compressed string to - /// \param[in] languageID Which language to use - void EncodeString( const char *input, int maxCharsToWrite, MafiaNet::BitStream *output, uint8_t languageId=0 ); - - /// Writes input to output, uncompressed. Takes care of the null-terminator for you. - /// \param[out] output A block of bytes to receive the output - /// \param[in] maxCharsToWrite Size, in bytes, of \a output . A null-terminator will always be appended to the output string. If the maxCharsToWrite is not large enough, the string will be truncated. - /// \param[in] input The bitstream containing the compressed string - /// \param[in] languageID Which language to use - bool DecodeString( char *output, int maxCharsToWrite, MafiaNet::BitStream *input, uint8_t languageId=0 ); - -#ifdef _CSTRING_COMPRESSOR - void EncodeString( const CString &input, int maxCharsToWrite, MafiaNet::BitStream *output, uint8_t languageId=0 ); - bool DecodeString( CString &output, int maxCharsToWrite, MafiaNet::BitStream *input, uint8_t languageId=0 ); -#endif - -#ifdef _STD_STRING_COMPRESSOR - void EncodeString( const std::string &input, int maxCharsToWrite, MafiaNet::BitStream *output, uint8_t languageId=0 ); - bool DecodeString( std::string *output, int maxCharsToWrite, MafiaNet::BitStream *input, uint8_t languageId=0 ); -#endif - - void EncodeString( const MafiaNet::RakString *input, int maxCharsToWrite, MafiaNet::BitStream *output, uint8_t languageId=0 ); - bool DecodeString(MafiaNet::RakString *output, int maxCharsToWrite, MafiaNet::BitStream *input, uint8_t languageId=0 ); - - /// Used so I can allocate and deallocate this singleton at runtime - static void AddReference(void); - - /// Used so I can allocate and deallocate this singleton at runtime - static void RemoveReference(void); - - StringCompressor(); - -private: - - /// Singleton instance - static StringCompressor *instance; - - /// Pointer to the huffman encoding trees. - DataStructures::Map huffmanEncodingTrees; - - static int referenceCount; -}; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/StringTable.h b/vendors/mafianet/Source/include/mafianet/StringTable.h deleted file mode 100644 index 91a33fe9f..000000000 --- a/vendors/mafianet/Source/include/mafianet/StringTable.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017-2019, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief A simple class to encode and decode known strings based on a lookup table. Similar to the StringCompressor class. -/// - - - -#ifndef __STRING_TABLE_H -#define __STRING_TABLE_H - -#include "DS_OrderedList.h" -#include "Export.h" -#include "memoryoverride.h" - -/// Forward declaration -namespace MafiaNet -{ - class BitStream; -}; - -/// StringTableType should be the smallest type possible, or else it defeats the purpose of the StringTable class, which is to save bandwidth. -typedef unsigned char StringTableType; - -/// The string plus a bool telling us if this string was copied or not. -struct StrAndBool -{ - char *str; - bool b; -}; - -namespace MafiaNet -{ - int RAK_DLL_EXPORT StrAndBoolComp( char *const &key, const StrAndBool &data ); - - /// \details This is an even more efficient alternative to StringCompressor in that it writes a single byte from a lookup table and only does compression.
    - /// if the string does not already exist in the table.
    - /// All string tables must match on all systems - hence you must add all the strings in the same order on all systems.
    - /// Furthermore, this must be done before sending packets that use this class, since the strings are ordered for fast lookup. Adding after that time would mess up all the indices so don't do it.
    - /// Don't use this class to write strings which were not previously registered with AddString, since you just waste bandwidth then. Use StringCompressor instead. - /// \brief Writes a string index, instead of the whole string - class RAK_DLL_EXPORT StringTable - { - public: - - // Destructor - ~StringTable(); - - /// static function because only static functions can access static members - /// The RakPeer constructor adds a reference to this class, so don't call this until an instance of RakPeer exists, or unless you call AddReference yourself. - /// \return the unique instance of the StringTable - static StringTable* Instance(void); - - /// Add a string to the string table. - /// \param[in] str The string to add to the string table - /// \param[in] copyString true to make a copy of the passed string (takes more memory), false to not do so (if your string is in static memory). - void AddString(const char *str, bool copyString); - - /// Writes input to output, compressed. Takes care of the null-terminator for you. - /// Relies on the StringCompressor class, which is automatically reference counted in the constructor and destructor in RakPeer. You can call the reference counting functions yourself if you wish too. - /// \param[in] input Pointer to an ASCII string - /// \param[in] maxCharsToWrite The size of \a input - /// \param[out] output The bitstream to write the compressed string to - void EncodeString( const char *input, int maxCharsToWrite, MafiaNet::BitStream *output ); - - /// Writes input to output, uncompressed. Takes care of the null-terminator for you. - /// Relies on the StringCompressor class, which is automatically reference counted in the constructor and destructor in RakPeer. You can call the reference counting functions yourself if you wish too. - /// \param[out] output A block of bytes to receive the output - /// \param[in] maxCharsToWrite Size, in bytes, of \a output . A null-terminator will always be appended to the output string. If the maxCharsToWrite is not large enough, the string will be truncated. - /// \param[in] input The bitstream containing the compressed string - bool DecodeString( char *output, int maxCharsToWrite, MafiaNet::BitStream *input ); - - /// Used so I can allocate and deallocate this singleton at runtime - static void AddReference(void); - - /// Used so I can allocate and deallocate this singleton at runtime - static void RemoveReference(void); - - /// Private Constructor - StringTable(); - - protected: - /// Called when you mess up and send a string using this class that was not registered with AddString - /// \param[in] maxCharsToWrite Size, in bytes, of \a output . A null-terminator will always be appended to the output string. If the maxCharsToWrite is not large enough, the string will be truncated. - void LogStringNotFound(const char *strName); - - /// Singleton instance - static StringTable *instance; - static int referenceCount; - - DataStructures::OrderedList orderedStringList; - }; -} - - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/SuperFastHash.h b/vendors/mafianet/Source/include/mafianet/SuperFastHash.h deleted file mode 100644 index 2b9690fed..000000000 --- a/vendors/mafianet/Source/include/mafianet/SuperFastHash.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -#ifndef __SUPER_FAST_HASH_H -#define __SUPER_FAST_HASH_H - -#include -#include "NativeTypes.h" - -// From http://www.azillionmonkeys.com/qed/hash.html -// Author of main code is Paul Hsieh -// I just added some convenience functions -// Also note http://burtleburtle.net/bob/hash/doobs.html, which shows that this is 20% faster than the one on that page but has more collisions - -uint32_t SuperFastHash (const char * data, int length); -uint32_t SuperFastHashIncremental (const char * data, int len, unsigned int lastHash ); -uint32_t SuperFastHashFile (const char * filename); -uint32_t SuperFastHashFilePtr (FILE *fp); - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/TCPInterface.h b/vendors/mafianet/Source/include/mafianet/TCPInterface.h deleted file mode 100644 index 3281358c1..000000000 --- a/vendors/mafianet/Source/include/mafianet/TCPInterface.h +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief A simple TCP based server allowing sends and receives. Can be connected by any TCP client, including telnet. -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_TCPInterface==1 - -#ifndef __SIMPLE_TCP_SERVER -#define __SIMPLE_TCP_SERVER - -#include "memoryoverride.h" -#include "DS_List.h" -#include "types.h" -#include "Export.h" -#include "thread.h" -#include "DS_Queue.h" -#include "SimpleMutex.h" -#include "defines.h" -#include "SocketIncludes.h" -#include "DS_ByteQueue.h" -#include "DS_ThreadsafeAllocatingQueue.h" -#include "LocklessTypes.h" -#include "PluginInterface2.h" - -#if OPEN_SSL_CLIENT_SUPPORT==1 -#include -#include -#include -#include -#include -#endif - -namespace MafiaNet -{ -/// Forward declarations -struct RemoteClient; - -/// \internal -/// \brief As the name says, a simple multithreaded TCP server. Used by TelnetTransport -class RAK_DLL_EXPORT TCPInterface -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(TCPInterface) - - TCPInterface(); - virtual ~TCPInterface(); - - // TODO - add socketdescriptor - /// Starts the TCP server on the indicated port - /// \param[in] port Which port to listen on. - /// \param[in] maxIncomingConnections Max incoming connections we will accept - /// \param[in] maxConnections Max total connections, which should be >= maxIncomingConnections - /// \param[in] threadPriority Passed to the thread creation routine. Use THREAD_PRIORITY_NORMAL for Windows. For Linux based systems, you MUST pass something reasonable based on the thread priorities for your application. - /// \param[in] socketFamily IP version: For IPV4, use AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC. - bool Start(unsigned short port, unsigned short maxIncomingConnections, unsigned short maxConnections=0, int _threadPriority=-99999, unsigned short socketFamily=AF_INET, const char *bindAddress=0); - - /// Stops the TCP server - void Stop(void); - - /// Connect to the specified host on the specified port - SystemAddress Connect(const char* host, unsigned short remotePort, bool block=true, unsigned short socketFamily=AF_INET, const char *bindAddress=0); - -#if OPEN_SSL_CLIENT_SUPPORT==1 - /// Start SSL on an existing connection, notified with HasCompletedConnectionAttempt - void StartSSLClient(SystemAddress systemAddress); - - /// Was SSL started on this socket? - bool IsSSLActive(SystemAddress systemAddress); -#endif - - /// Sends a byte stream - virtual void Send( const char *data, unsigned int length, const SystemAddress &systemAddress, bool broadcast ); - - // Sends a concatenated list of byte streams - virtual bool SendList( const char **data, const unsigned int *lengths, const int numParameters, const SystemAddress &systemAddress, bool broadcast ); - - // Get how many bytes are waiting to be sent. If too many, you may want to skip sending - unsigned int GetOutgoingDataBufferSize(SystemAddress systemAddress) const; - - /// Returns if Receive() will return data - /// Do not use on PacketizedTCP - virtual bool ReceiveHasPackets( void ); - - /// Returns data received - virtual Packet* Receive( void ); - - /// Disconnects a player/address - void CloseConnection( SystemAddress systemAddress ); - - /// Deallocates a packet returned by Receive - void DeallocatePacket( Packet *packet ); - - /// Fills the array remoteSystems with the SystemAddress of all the systems we are connected to - /// \param[out] remoteSystems An array of SystemAddress structures to be filled with the SystemAddresss of the systems we are connected to. Pass 0 to remoteSystems to only get the number of systems we are connected to - /// \param[in, out] numberOfSystems As input, the size of remoteSystems array. As output, the number of elements put into the array - void GetConnectionList( SystemAddress *remoteSystems, unsigned short *numberOfSystems ) const; - - /// Returns just the number of connections we have - unsigned short GetConnectionCount(void) const; - - /// Has a previous call to connect succeeded? - /// \return UNASSIGNED_SYSTEM_ADDRESS = no. Anything else means yes. - SystemAddress HasCompletedConnectionAttempt(void); - - /// Has a previous call to connect failed? - /// \return UNASSIGNED_SYSTEM_ADDRESS = no. Anything else means yes. - SystemAddress HasFailedConnectionAttempt(void); - - /// Queued events of new incoming connections - SystemAddress HasNewIncomingConnection(void); - - /// Queued events of lost connections - SystemAddress HasLostConnection(void); - - /// Return an allocated but empty packet, for custom use - Packet* AllocatePacket(unsigned dataSize); - - // Push a packet back to the queue - virtual void PushBackPacket( Packet *packet, bool pushAtHead ); - - /// Returns if Start() was called successfully - bool WasStarted(void) const; - - void AttachPlugin( PluginInterface2 *plugin ); - void DetachPlugin( PluginInterface2 *plugin ); -protected: - - Packet* ReceiveInt( void ); - - bool CreateListenSocket(unsigned short port, unsigned short maxIncomingConnections, unsigned short socketFamily, const char *hostAddress); - - // Plugins - DataStructures::List messageHandlerList; - - MafiaNet::LocklessUint32_t isStarted, threadRunning; - __TCPSOCKET__ listenSocket; - - DataStructures::Queue headPush, tailPush; - RemoteClient* remoteClients; - unsigned short remoteClientsLength; - - // Assuming remoteClients is only used by one thread! - // DataStructures::List remoteClients; - // Use this thread-safe queue to add to remoteClients - // DataStructures::Queue remoteClientsInsertionQueue; - // SimpleMutex remoteClientsInsertionQueueMutex; - - /* - struct OutgoingMessage - { - unsigned char* data; - SystemAddress systemAddress; - bool broadcast; - unsigned int length; - }; - */ -// DataStructures::SingleProducerConsumer outgoingMessages; -// DataStructures::SingleProducerConsumer incomingMessages; -// DataStructures::SingleProducerConsumer newIncomingConnections, lostConnections, requestedCloseConnections; -// DataStructures::SingleProducerConsumer newRemoteClients; -// DataStructures::ThreadsafeAllocatingQueue outgoingMessages; - DataStructures::ThreadsafeAllocatingQueue incomingMessages; - DataStructures::ThreadsafeAllocatingQueue newIncomingConnections, lostConnections, requestedCloseConnections; - DataStructures::ThreadsafeAllocatingQueue newRemoteClients; - SimpleMutex completedConnectionAttemptMutex, failedConnectionAttemptMutex; - DataStructures::Queue completedConnectionAttempts, failedConnectionAttempts; - - int threadPriority; - - DataStructures::List<__TCPSOCKET__> blockingSocketList; - SimpleMutex blockingSocketListMutex; - - - - - - friend RAK_THREAD_DECLARATION(UpdateTCPInterfaceLoop); - friend RAK_THREAD_DECLARATION(ConnectionAttemptLoop); - -// void DeleteRemoteClient(RemoteClient *remoteClient, fd_set *exceptionFD); -// void InsertRemoteClient(RemoteClient* remoteClient); - __TCPSOCKET__ SocketConnect(const char* host, unsigned short remotePort, unsigned short socketFamily, const char *bindAddress); - - struct ThisPtrPlusSysAddr - { - TCPInterface *tcpInterface; - SystemAddress systemAddress; - bool useSSL; - char bindAddress[64]; - unsigned short socketFamily; - }; - -#if OPEN_SSL_CLIENT_SUPPORT==1 - SSL_CTX* ctx; - SSL_METHOD *meth; - DataStructures::ThreadsafeAllocatingQueue startSSL; - DataStructures::List activeSSLConnections; - SimpleMutex sharedSslMutex; -#endif -}; - -/// Stores information about a remote client. -struct RemoteClient -{ - RemoteClient() { -#if OPEN_SSL_CLIENT_SUPPORT==1 - ssl=0; -#endif - isActive=false; - socket=0; - } - __TCPSOCKET__ socket; - SystemAddress systemAddress; - DataStructures::ByteQueue outgoingData; - bool isActive; - SimpleMutex outgoingDataMutex; - SimpleMutex isActiveMutex; - -#if OPEN_SSL_CLIENT_SUPPORT==1 - SSL* ssl; - bool InitSSL(SSL_CTX* ctx, SSL_METHOD *meth); - void DisconnectSSL(void); - void FreeSSL(void); - int Send(const char *data, unsigned int length); - int Recv(char *data, const int dataSize); -#else - int Send(const char *data, unsigned int length); - int Recv(char *data, const int dataSize); -#endif - void Reset(void) - { - outgoingDataMutex.Lock(); - outgoingData.Clear(_FILE_AND_LINE_); - outgoingDataMutex.Unlock(); - } - void SetActive(bool a); - void SendOrBuffer(const char **data, const unsigned int *lengths, const int numParameters); -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* - diff --git a/vendors/mafianet/Source/include/mafianet/TableSerializer.h b/vendors/mafianet/Source/include/mafianet/TableSerializer.h deleted file mode 100644 index 2989f4b1c..000000000 --- a/vendors/mafianet/Source/include/mafianet/TableSerializer.h +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __TABLE_SERIALIZER_H -#define __TABLE_SERIALIZER_H - -#include "memoryoverride.h" -#include "DS_Table.h" -#include "Export.h" - -namespace MafiaNet -{ - class BitStream; -} - -namespace MafiaNet -{ - -class RAK_DLL_EXPORT TableSerializer -{ -public: - static void SerializeTable(DataStructures::Table *in, MafiaNet::BitStream *out); - static bool DeserializeTable(unsigned char *serializedTable, unsigned int dataLength, DataStructures::Table *out); - static bool DeserializeTable(MafiaNet::BitStream *in, DataStructures::Table *out); - static void SerializeColumns(DataStructures::Table *in, MafiaNet::BitStream *out); - static void SerializeColumns(DataStructures::Table *in, MafiaNet::BitStream *out, DataStructures::List &skipColumnIndices); - static bool DeserializeColumns(MafiaNet::BitStream *in, DataStructures::Table *out); - static void SerializeRow(DataStructures::Table::Row *in, unsigned keyIn, const DataStructures::List &columns, MafiaNet::BitStream *out); - static void SerializeRow(DataStructures::Table::Row *in, unsigned keyIn, const DataStructures::List &columns, MafiaNet::BitStream *out, DataStructures::List &skipColumnIndices); - static bool DeserializeRow(MafiaNet::BitStream *in, DataStructures::Table *out); - static void SerializeCell(MafiaNet::BitStream *out, DataStructures::Table::Cell *cell, DataStructures::Table::ColumnType columnType); - static bool DeserializeCell(MafiaNet::BitStream *in, DataStructures::Table::Cell *cell, DataStructures::Table::ColumnType columnType); - static void SerializeFilterQuery(MafiaNet::BitStream *in, DataStructures::Table::FilterQuery *query); - // Note that this allocates query->cell->c! - static bool DeserializeFilterQuery(MafiaNet::BitStream *out, DataStructures::Table::FilterQuery *query); - static void SerializeFilterQueryList(MafiaNet::BitStream *in, DataStructures::Table::FilterQuery *query, unsigned int numQueries, unsigned int maxQueries); - // Note that this allocates queries, cells, and query->cell->c!. Use DeallocateQueryList to free. - static bool DeserializeFilterQueryList(MafiaNet::BitStream *out, DataStructures::Table::FilterQuery **query, unsigned int *numQueries, unsigned int maxQueries, int allocateExtraQueries=0); - static void DeallocateQueryList(DataStructures::Table::FilterQuery *query, unsigned int numQueries); -}; - -} // namespace MafiaNet - -#endif - -// Test code for the table -/* -#include "LightweightDatabaseServer.h" -#include "LightweightDatabaseClient.h" -#include "TableSerializer.h" -#include "BitStream.h" -#include "StringCompressor.h" -#include "DS_Table.h" -void main(void) -{ - DataStructures::Table table; - DataStructures::Table::Row *row; - unsigned int dummydata=12345; - - // Add columns Name (string), IP (binary), score (int), and players (int). - table.AddColumn("Name", DataStructures::Table::STRING); - table.AddColumn("IP", DataStructures::Table::BINARY); - table.AddColumn("Score", DataStructures::Table::NUMERIC); - table.AddColumn("Players", DataStructures::Table::NUMERIC); - table.AddColumn("Empty Test Column", DataStructures::Table::STRING); - RakAssert(table.GetColumnCount()==5); - row=table.AddRow(0); - RakAssert(row); - row->UpdateCell(0,"Kevin Jenkins"); - row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); - row->UpdateCell(2,5); - row->UpdateCell(3,10); - //row->UpdateCell(4,"should be unique"); - - row=table.AddRow(1); - row->UpdateCell(0,"Kevin Jenkins"); - row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); - row->UpdateCell(2,5); - row->UpdateCell(3,15); - - row=table.AddRow(2); - row->UpdateCell(0,"Kevin Jenkins"); - row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); - row->UpdateCell(2,5); - row->UpdateCell(3,20); - - row=table.AddRow(3); - RakAssert(row); - row->UpdateCell(0,"Kevin Jenkins"); - row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); - row->UpdateCell(2,15); - row->UpdateCell(3,5); - row->UpdateCell(4,"col index 4"); - - row=table.AddRow(4); - RakAssert(row); - row->UpdateCell(0,"Kevin Jenkins"); - row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); - //row->UpdateCell(2,25); - row->UpdateCell(3,30); - //row->UpdateCell(4,"should be unique"); - - row=table.AddRow(5); - RakAssert(row); - row->UpdateCell(0,"Kevin Jenkins"); - row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); - //row->UpdateCell(2,25); - row->UpdateCell(3,5); - //row->UpdateCell(4,"should be unique"); - - row=table.AddRow(6); - RakAssert(row); - row->UpdateCell(0,"Kevin Jenkins"); - row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); - row->UpdateCell(2,35); - //row->UpdateCell(3,40); - //row->UpdateCell(4,"should be unique"); - - row=table.AddRow(7); - RakAssert(row); - row->UpdateCell(0,"Bob Jenkins"); - - row=table.AddRow(8); - RakAssert(row); - row->UpdateCell(0,"Zack Jenkins"); - - // Test multi-column sorting - DataStructures::Table::Row *rows[30]; - DataStructures::Table::SortQuery queries[4]; - queries[0].columnIndex=0; - queries[0].operation=DataStructures::Table::QS_INCREASING_ORDER; - queries[1].columnIndex=1; - queries[1].operation=DataStructures::Table::QS_INCREASING_ORDER; - queries[2].columnIndex=2; - queries[2].operation=DataStructures::Table::QS_INCREASING_ORDER; - queries[3].columnIndex=3; - queries[3].operation=DataStructures::Table::QS_DECREASING_ORDER; - table.SortTable(queries, 4, rows); - unsigned i; - char out[256]; - RAKNET_DEBUG_PRINTF("Sort: Ascending except for column index 3\n"); - for (i=0; i < table.GetRowCount(); i++) - { - table.PrintRow(out,256,',',true, rows[i]); - RAKNET_DEBUG_PRINTF("%s\n", out); - } - - // Test query: - // Don't return column 3, and swap columns 0 and 2 - unsigned columnsToReturn[4]; - columnsToReturn[0]=2; - columnsToReturn[1]=1; - columnsToReturn[2]=0; - columnsToReturn[3]=4; - DataStructures::Table resultsTable; - table.QueryTable(columnsToReturn,4,0,0,&resultsTable); - RAKNET_DEBUG_PRINTF("Query: Don't return column 3, and swap columns 0 and 2:\n"); - for (i=0; i < resultsTable.GetRowCount(); i++) - { - resultsTable.PrintRow(out,256,',',true, resultsTable.GetRowByIndex(i)); - RAKNET_DEBUG_PRINTF("%s\n", out); - } - - // Test filter: - // Only return rows with column index 4 empty - DataStructures::Table::FilterQuery inclusionFilters[3]; - inclusionFilters[0].columnIndex=4; - inclusionFilters[0].operation=DataStructures::Table::QF_IS_EMPTY; - // inclusionFilters[0].cellValue; // Unused for IS_EMPTY - table.QueryTable(0,0,inclusionFilters,1,&resultsTable); - RAKNET_DEBUG_PRINTF("Filter: Only return rows with column index 4 empty:\n"); - for (i=0; i < resultsTable.GetRowCount(); i++) - { - resultsTable.PrintRow(out,256,',',true, resultsTable.GetRowByIndex(i)); - RAKNET_DEBUG_PRINTF("%s\n", out); - } - - // Column 5 empty and column 0 == Kevin Jenkins - inclusionFilters[0].columnIndex=4; - inclusionFilters[0].operation=DataStructures::Table::QF_IS_EMPTY; - inclusionFilters[1].columnIndex=0; - inclusionFilters[1].operation=DataStructures::Table::QF_EQUAL; - inclusionFilters[1].cellValue.Set("Kevin Jenkins"); - table.QueryTable(0,0,inclusionFilters,2,&resultsTable); - RAKNET_DEBUG_PRINTF("Filter: Column 5 empty and column 0 == Kevin Jenkins:\n"); - for (i=0; i < resultsTable.GetRowCount(); i++) - { - resultsTable.PrintRow(out,256,',',true, resultsTable.GetRowByIndex(i)); - RAKNET_DEBUG_PRINTF("%s\n", out); - } - - MafiaNet::BitStream bs; - RAKNET_DEBUG_PRINTF("PreSerialize:\n"); - for (i=0; i < table.GetRowCount(); i++) - { - table.PrintRow(out,256,',',true, table.GetRowByIndex(i)); - RAKNET_DEBUG_PRINTF("%s\n", out); - } - StringCompressor::AddReference(); - TableSerializer::Serialize(&table, &bs); - TableSerializer::Deserialize(&bs, &table); - StringCompressor::RemoveReference(); - RAKNET_DEBUG_PRINTF("PostDeserialize:\n"); - for (i=0; i < table.GetRowCount(); i++) - { - table.PrintRow(out,256,',',true, table.GetRowByIndex(i)); - RAKNET_DEBUG_PRINTF("%s\n", out); - } - int a=5; -} -*/ diff --git a/vendors/mafianet/Source/include/mafianet/TeamBalancer.h b/vendors/mafianet/Source/include/mafianet/TeamBalancer.h deleted file mode 100644 index 0cd337f20..000000000 --- a/vendors/mafianet/Source/include/mafianet/TeamBalancer.h +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file TeamBalancer.h -/// \brief Set and network team selection (supports peer to peer or client/server) -/// \details Automatically handles transmission and resolution of team selection, including team switching and balancing -/// \deprecated Use TeamManager intead -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_TeamBalancer==1 - -#ifndef __TEAM_BALANCER_H -#define __TEAM_BALANCER_H - -#include "PluginInterface2.h" -#include "memoryoverride.h" -#include "NativeTypes.h" -#include "DS_List.h" -#include "string.h" - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; - -/// \defgroup TEAM_BALANCER_GROUP TeamBalancer -/// \brief Set and network team selection (supports peer to peer or client/server) -/// \details Automatically handles transmission and resolution of team selection, including team switching and balancing -/// \deprecated Use TeamManager intead -/// \ingroup PLUGINS_GROUP - -/// 0...254 for your team number identifiers. 255 is reserved as undefined. -/// \deprecated Use TeamManager intead -/// \ingroup TEAM_BALANCER_GROUP -typedef unsigned char TeamId; - -#define UNASSIGNED_TEAM_ID 255 - -/// \brief Set and network team selection (supports peer to peer or client/server) -/// \details Automatically handles transmission and resolution of team selection, including team switching and balancing.
    -/// Usage: TODO -/// \deprecated Use TeamManager intead -/// \ingroup TEAM_BALANCER_GROUP -class RAK_DLL_EXPORT TeamBalancer : public PluginInterface2 -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(TeamBalancer) - - TeamBalancer(); - virtual ~TeamBalancer(); - - /// \brief Set the limit to the number of players on the specified team - /// \details SetTeamSizeLimit() must be called on the host, so the host can enforce the maximum number of players on each team. - /// SetTeamSizeLimit() can be called on all systems if desired - for example, in a P2P environment you may wish to call it on all systems in advanced in case you become host. - /// \param[in] team Which team to set the limit for - /// \param[in] limit The maximum number of people on this team - void SetTeamSizeLimit(TeamId team, unsigned short limit); - - enum DefaultAssigmentAlgorithm - { - /// Among all the teams, join the team with the smallest number of players - SMALLEST_TEAM, - /// Join the team with the lowest index that has open slots. - FILL_IN_ORDER - }; - /// \brief Determine how players' teams will be set when they call RequestAnyTeam() - /// \details Based on the specified enumeration, a player will join a team automatically - /// Defaults to SMALLEST_TEAM - /// This function is only used by the host - /// \param[in] daa Enumeration describing the algorithm to use - void SetDefaultAssignmentAlgorithm(DefaultAssigmentAlgorithm daa); - - /// \brief By default, teams can be unbalanced up to the team size limit defined by SetTeamSizeLimits() - /// \details If SetForceEvenTeams(true) is called on the host, then teams cannot be unbalanced by more than 1 player - /// If teams are uneven at the time that SetForceEvenTeams(true) is called, players at randomly will be switched, and will be notified of ID_TEAM_BALANCER_TEAM_ASSIGNED - /// If players disconnect from the host such that teams would not be even, and teams are not locked, then a player from the largest team is randomly moved to even the teams. - /// Defaults to false - /// \note SetLockTeams(true) takes priority over SetForceEvenTeams(), so if teams are currently locked, this function will have no effect until teams become unlocked. - /// \param[in] force True to force even teams. False to allow teams to not be evenly matched - void SetForceEvenTeams(bool force); - - /// \brief If set, calls to RequestSpecificTeam() and RequestAnyTeam() will return the team you are currently on. - /// \details However, if those functions are called and you do not have a team, then you will be assigned to a default team according to SetDefaultAssignmentAlgorithm() and possibly SetForceEvenTeams(true) - /// If \a lock is false, and SetForceEvenTeams() was called with \a force as true, and teams are currently uneven, they will be made even, and those players randomly moved will get ID_TEAM_BALANCER_TEAM_ASSIGNED - /// Defaults to false - /// \param[in] lock True to lock teams, false to unlock - void SetLockTeams(bool lock); - - /// Set your requested team. UNASSIGNED_TEAM_ID means no team. - /// After enough time for network communication, ID_TEAM_BALANCER_SET_TEAM will be returned with your current team, or - /// If team switch is not possible, ID_TEAM_BALANCER_REQUESTED_TEAM_CHANGE_PENDING or ID_TEAM_BALANCER_TEAMS_LOCKED will be returned. - /// In the case of ID_TEAM_BALANCER_REQUESTED_TEAM_CHANGE_PENDING the request will stay in memory. ID_TEAM_BALANCER_SET_TEAM will be returned when someone on the desired team leaves or wants to switch to your team. - /// If SetLockTeams(true) is called while you have a request pending, you will get ID_TEAM_BALANCER_TEAMS_LOCKED - /// \pre Call SetTeamSizeLimits() on the host and call SetHostGuid() on this system. If the host is not running the TeamBalancer plugin or did not have SetTeamSizeLimits() called, then you will not get any response. - /// \param[in] memberId If there is more than one player per computer, this number identifies that player. Use any consistent value, such as UNASSIGNED_NETWORK_ID if there is only one player. - /// \param[in] desiredTeam An index representing your team number. The index should range from 0 to one less than the size of the list passed to SetTeamSizeLimits() on the host. You can also pass UNASSIGNED_TEAM_ID to not be on any team (such as if spectating) - void RequestSpecificTeam(NetworkID memberId, TeamId desiredTeam); - - /// If ID_TEAM_BALANCER_REQUESTED_TEAM_CHANGE_PENDING is returned after a call to RequestSpecificTeam(), the request will stay in memory on the host and execute when available, or until the teams become locked. - /// You can cancel the request by calling CancelRequestSpecificTeam(), in which case you will stay on your existing team. - /// \note Due to latency, even after calling CancelRequestSpecificTeam() you may still get ID_TEAM_BALANCER_SET_TEAM if the packet was already in transmission. - /// \param[in] memberId If there is more than one player per computer, this number identifies that player. Use any consistent value, such as UNASSIGNED_NETWORK_ID if there is only one player. - void CancelRequestSpecificTeam(NetworkID memberId); - - /// Allow host to pick your team, based on whatever algorithm it uses for default team assignments. - /// This only has an effect if you are not currently on a team (GetMyTeam() returns UNASSIGNED_TEAM_ID) - /// \pre Call SetTeamSizeLimits() on the host and call SetHostGuid() on this system - /// \param[in] memberId If there is more than one player per computer, this number identifies that player. Use any consistent value, such as UNASSIGNED_NETWORK_ID if there is only one player. - void RequestAnyTeam(NetworkID memberId); - - /// Returns your team. - /// As your team changes, you are notified through the ID_TEAM_BALANCER_TEAM_ASSIGNED packet in byte 1. - /// Returns UNASSIGNED_TEAM_ID initially - /// \pre For this to return anything other than UNASSIGNED_TEAM_ID, connect to a properly initialized host and RequestSpecificTeam() or RequestAnyTeam() first - /// \param[in] memberId If there is more than one player per computer, this number identifies that player. Use any consistent value, such as UNASSIGNED_NETWORK_ID if there is only one player. - /// \return UNASSIGNED_TEAM_ID for no team. Otherwise, the index should range from 0 to one less than the size of the list passed to SetTeamSizeLimits() on the host - TeamId GetMyTeam(NetworkID memberId) const; - - /// If you called RequestSpecificTeam() or RequestAnyTeam() with a value for \a memberId that - /// Has since been deleted, call DeleteMember(). to notify this plugin of that event. - /// Not necessary with only one team member per system - /// \param[in] memberId If there is more than one player per computer, this number identifies that player. Use any consistent value, such as UNASSIGNED_NETWORK_ID if there is only one player. - void DeleteMember(NetworkID memberId); - - struct TeamMember - { - RakNetGUID memberGuid; - NetworkID memberId; - TeamId currentTeam; - TeamId requestedTeam; - }; - struct MyTeamMembers - { - NetworkID memberId; - TeamId currentTeam; - TeamId requestedTeam; - }; - -protected: - - /// \internal - virtual PluginReceiveResult OnReceive(Packet *packet); - /// \internal - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - /// \internal - void OnAttach(void); - - void OnStatusUpdateToNewHost(Packet *packet); - void OnCancelTeamRequest(Packet *packet); - void OnRequestAnyTeam(Packet *packet); - void OnRequestSpecificTeam(Packet *packet); - - RakNetGUID hostGuid; - DefaultAssigmentAlgorithm defaultAssigmentAlgorithm; - bool forceTeamsToBeEven; - bool lockTeams; - // So if we lose the connection while processing, we request the same info of the new host - DataStructures::List myTeamMembers; - - DataStructures::List teamLimits; - DataStructures::List teamMemberCounts; - DataStructures::List teamMembers; - unsigned int GetMemberIndex(NetworkID memberId, RakNetGUID guid) const; - unsigned int AddTeamMember(const TeamMember &tm); // Returns index of new member - void RemoveTeamMember(unsigned int index); - void EvenTeams(void); - unsigned int GetMemberIndexToSwitchTeams(const DataStructures::List &sourceTeamNumbers, TeamId targetTeamNumber); - void GetOverpopulatedTeams(DataStructures::List &overpopulatedTeams, int maxTeamSize); - void SwitchMemberTeam(unsigned int teamMemberIndex, TeamId destinationTeam); - void NotifyTeamAssigment(unsigned int teamMemberIndex); - bool WeAreHost(void) const; - PluginReceiveResult OnTeamAssigned(Packet *packet); - PluginReceiveResult OnRequestedTeamChangePending(Packet *packet); - PluginReceiveResult OnTeamsLocked(Packet *packet); - void GetMinMaxTeamMembers(int &minMembersOnASingleTeam, int &maxMembersOnASingleTeam); - TeamId GetNextDefaultTeam(void); // Accounting for team balancing and team limits, get the team a player should be placed on - bool TeamWouldBeOverpopulatedOnAddition(TeamId teamId, unsigned int teamMemberSize); // Accounting for team balancing and team limits, would this team be overpopulated if a member was added to it? - bool TeamWouldBeUnderpopulatedOnLeave(TeamId teamId, unsigned int teamMemberSize); - TeamId GetSmallestNonFullTeam(void) const; - TeamId GetFirstNonFullTeam(void) const; - void MoveMemberThatWantsToJoinTeam(TeamId teamId); - TeamId MoveMemberThatWantsToJoinTeamInternal(TeamId teamId); - void NotifyTeamsLocked(RakNetGUID target, TeamId requestedTeam); - void NotifyTeamSwitchPending(RakNetGUID target, TeamId requestedTeam, NetworkID memberId); - void NotifyNoTeam(NetworkID memberId, RakNetGUID target); - void SwapTeamMembersByRequest(unsigned int memberIndex1, unsigned int memberIndex2); - void RemoveByGuid(RakNetGUID rakNetGUID); - bool TeamsWouldBeEvenOnSwitch(TeamId t1, TeamId t2); - -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/TeamManager.h b/vendors/mafianet/Source/include/mafianet/TeamManager.h deleted file mode 100644 index 5867a116e..000000000 --- a/vendors/mafianet/Source/include/mafianet/TeamManager.h +++ /dev/null @@ -1,762 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -// TODO: optimize the list of teams and team members to be O(1). Store in hashes, use linked lists to get ordered traversal - -/// \file TeamManager.h -/// \brief Automates networking and list management for teams -/// \details TeamManager provides support for teams. A team is a list of team members. -/// Teams contain properties including the number of team members per team, whether or not tagged teams must have equal numbers of members, and if a team is locked or not to certain entry conditions -/// Team members contain properties including which teams they are on and which teams they want to join if a team is not immediately joinable -/// Advanced functionality includes the ability for a team member to be on multiple teams simultaneously, the ability to swap teams with other members, and the ability to resize the number of members supported per team -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_TeamManager==1 - -#ifndef __TEAM_MANAGER_H -#define __TEAM_MANAGER_H - -#include "PluginInterface2.h" -#include "memoryoverride.h" -#include "NativeTypes.h" -#include "DS_List.h" -#include "types.h" -#include "DS_Hash.h" -#include "DS_OrderedList.h" - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; - -/// \defgroup TEAM_MANAGER_GROUP TeamManager -/// \brief Automates networking and list management for teams -/// \details When used with ReplicaManager3 and FullyConnectedMesh2, provides a complete solution to managing a distributed list of teams and team member objects with support for host migration. -/// \ingroup PLUGINS_GROUP - -/// \ingroup TEAM_MANAGER_GROUP -/// \brief A subcategory of not being on a team. For example, 0 may mean no team for a player, while 1 may mean no team for a spectator. Defined by the user. -typedef unsigned char NoTeamId; - -/// \ingroup TEAM_MANAGER_GROUP -/// Used for multiple worlds. -typedef uint8_t WorldId; - -/// \ingroup TEAM_MANAGER_GROUP -/// Maximum number of members on one team. Use 65535 for unlimited. -typedef uint16_t TeamMemberLimit; - -/// Allow members to join this team when they specify TeamSelection::JOIN_ANY_AVAILABLE_TEAM -#define ALLOW_JOIN_ANY_AVAILABLE_TEAM (1<<0) -/// Allow members to join this team when they specify TeamSelection::JOIN_SPECIFIC_TEAM -#define ALLOW_JOIN_SPECIFIC_TEAM (1<<1) -/// Allow the host to put members on this team when rebalancing with TM_World::SetBalanceTeams() -#define ALLOW_JOIN_REBALANCING (1<<2) - -// Bitwise combination of ALLOW_JOIN_ANY_AVAILABLE_TEAM, ALLOW_JOIN_SPECIFIC_TEAM, ALLOW_JOIN_REBALANCING -typedef uint8_t JoinPermissions; - -// Forward declarations -class TM_Team; -class TM_TeamMember; -class TM_World; -class TeamManager; - -/// \ingroup TEAM_MANAGER_GROUP -enum JoinTeamType -{ - /// Attempt to join the first available team. - JOIN_ANY_AVAILABLE_TEAM, - /// Attempt to join a specific team, previously added with TM_World::ReferenceTeam() - JOIN_SPECIFIC_TEAM, - /// No team. Always succeeds. - JOIN_NO_TEAM -}; - -/// \ingroup TEAM_MANAGER_GROUP -enum TMTopology -{ - // Each system will send all messages to all participants - TM_PEER_TO_PEER, - - // The host will relay incoming messages to all participants - TM_CLIENT_SERVER, -}; - -/// \brief Parameter to TM_World::ReferenceTeamMember() -/// \details Use TeamSelection::AnyAvailable(), TeamSelection::SpecificTeam(), or TeamSelection::NoTeam() -/// \ingroup TEAM_MANAGER_GROUP -struct TeamSelection -{ - TeamSelection(); - TeamSelection(JoinTeamType itt); - TeamSelection(JoinTeamType itt, TM_Team *param); - TeamSelection(JoinTeamType itt, NoTeamId param); - JoinTeamType joinTeamType; - - union - { - TM_Team *specificTeamToJoin; - NoTeamId noTeamSubcategory; - } teamParameter; - - /// \brief Join any team that has available slots and is tagged with ALLOW_JOIN_ANY_AVAILABLE_TEAM - /// \details ID_TEAM_BALANCER_TEAM_ASSIGNED, ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, or ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED will be returned to all systems. - static TeamSelection AnyAvailable(void); - /// \brief Join a specific team if it has available slots, and is tagged with JOIN_SPECIFIC_TEAMS - /// \details ID_TEAM_BALANCER_TEAM_ASSIGNED, ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, or ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED will be returned to all systems. - /// \param[in] specificTeamToJoin Which team to attempt to join. - static TeamSelection SpecificTeam(TM_Team *specificTeamToJoin); - /// \brief Do not join a team, or leave all current teams. - /// \details This always succeeds. ID_TEAM_BALANCER_TEAM_ASSIGNED will be returned to all systems. - /// \param[in] noTeamSubcategory Even when not on a team, you can internally identify a subcategory of not being on a team, such as AI or spectator. - static TeamSelection NoTeam(NoTeamId noTeamSubcategory); -}; - -/// \brief A member of one or more teams. -/// \details Contains data and operations on data to manage which team your game's team members are on. -/// Best used as a composite member of your "User" or "Player" class(es). -/// When using with ReplicaManager3, call TM_TeamMember::ReferenceTeamMember() in Replica3::DeserializeConstruction() and TM_TeamMember::DeserializeConstruction() in Replica3::PostDeserializeConstruction() -/// There is otherwise no need to manually serialize the class, as operations are networked internally. -/// \ingroup TEAM_MANAGER_GROUP -class RAK_DLL_EXPORT TM_TeamMember -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(TM_TeamMember) - - TM_TeamMember(); - virtual ~TM_TeamMember(); - - /// \brief Request to join any team, a specific team, or to leave all teams - /// \details Function will return false on invalid operations, such as joining a team you are already on. - /// Will also fail with TeamSelection::JOIN_ANY_AVAILABLE_TEAM if you are currently on a team. - /// On success, every system will get ID_TEAM_BALANCER_TEAM_ASSIGNED. Use TeamManager::DecomposeTeamAssigned() to get details of which team member the message refers to. - /// On failure, all systems will get ID_TEAM_BALANCER_REQUESTED_TEAM_FULL or ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED. Use TeamManager::DecomposeTeamFull() and TeamManager::DecomposeTeamLocked() to get details of which team member the message refers to. - /// \note Joining a specific team with this function may result in being on more than one team at once, even if you call the function while locally only on one team. If your game depends on only being on one team at a team, use RequestTeamSwitch() instead with the parameter teamToLeave set to 0 - /// \param[in] TeamSelection::AnyAvailable(), TeamSelection::SpecificTeam(), or TeamSelection::NoTeam() - /// \return false On invalid or unnecessary operation. Otherwise returns true - bool RequestTeam(TeamSelection teamSelection); - - /// \brief Similar to RequestTeam with TeamSelection::SpecificTeam(), but leave a team simultaneously when the desired team is joinable - /// \param[in] teamToJoin Which team to join - /// \param[in] teamToLeave If 0, means leave all current teams. Otherwise, leave the specified team. - /// \return false On invalid or unnecessary operation. Otherwise returns true - bool RequestTeamSwitch(TM_Team *teamToJoin, TM_Team *teamToLeave); - - /// \brief Returns the first requested team in the list of requested teams, if you have a requested team at all. - /// \return TeamSelection::SpecificTeam(), TeamSelection::NoTeam(), or TeamSelection::AnyAvailable() - TeamSelection GetRequestedTeam(void) const; - - /// \brief Returns pending calls to RequestTeam() when using TeamSelection::JOIN_SPECIFIC_TEAM - /// \param[out] All pending requested teams - void GetRequestedSpecificTeams(DataStructures::List &requestedTeams) const; - - /// \brief Returns if the specified team is in the list of pending requested teams - /// \param[in] The team we are checking - /// \return Did we request to join this specific team? - bool HasRequestedTeam(TM_Team *team) const; - - /// \brief Returns the index of \a team in the requested teams list - /// \param[in] The team we are checking - /// \return -1 if we did not requested to join this team. Otherwise the index. - unsigned int GetRequestedTeamIndex(TM_Team *team) const; - - /// \return The number of teams that would be returned by a call to GetRequestedSpecificTeams() - unsigned int GetRequestedTeamCount(void) const; - - /// \brief Cancels a request to join a specific team. - /// \details Useful if you got ID_TEAM_BALANCER_REQUESTED_TEAM_FULL or ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED and changed your mind about joining the team. - /// \note This is not guaranteed to work due to latency. To clarify, If the host switches your team at the same time you call CancelRequestTeam() you may still get ID_TEAM_BALANCER_TEAM_ASSIGNED for the team you tried to cancel. - /// \param[in] specificTeamToCancel Which team to no longer join. Use 0 for all. - /// \return false On invalid or unnecessary operation. Otherwise returns true - bool CancelTeamRequest(TM_Team *specificTeamToCancel); - - /// \brief Leave a team - /// \details Leaves a team that you are on. Always succeeds provided you are on that team - /// Generates ID_TEAM_BALANCER_TEAM_ASSIGNED on all systems on success. - /// If you leave the last team you are on, \a noTeamSubcategory is set as well. - /// \param[in] team Which team to leave - /// \param[in] _noTeamSubcategory If the team member has been removed from all teams, which subcategory of NoTeamId to set them to - /// \return false On invalid or unnecessary operation. Otherwise returns true - bool LeaveTeam(TM_Team* team, NoTeamId _noTeamSubcategory); - - /// \brief Leave all teams - /// \Details Leaves all teams you are on, and sets \a noTeamSubcategory - /// \note This is the same as and just calls RequestTeam(TeamSelection::NoTeam(noTeamSubcategory)); - /// \return false On invalid or unnecessary operation. Otherwise returns true - bool LeaveAllTeams(NoTeamId inNoTeamSubcategory); - - /// \return Get the first team we are on, or 0 if we are not on a team. - TM_Team* GetCurrentTeam(void) const; - - /// \return How many teams we are on - unsigned int GetCurrentTeamCount(void) const; - - /// \return Returns one of the teams in the current team list, up to GetCurrentTeamCount() - TM_Team* GetCurrentTeamByIndex(unsigned int index); - - /// \param[out] Get all teams we are on, as a list - void GetCurrentTeams(DataStructures::List &_teams) const; - - /// For each team member, when you get ID_TEAM_BALANCER_TEAM_ASSIGNED for that member, the team list is saved. - /// Use this function to get that list, for example to determine which teams we just left or joined - /// \param[out] _teams The previous list of teams we were on - void GetLastTeams(DataStructures::List &_teams) const; - - /// \param[in] The team we are checking - /// \return Are we on this team? - bool IsOnTeam(TM_Team *team) const; - - /// \return The teamMemberID parameter passed to TM_World::ReferenceTeamMember() - NetworkID GetNetworkID(void) const; - - /// \return The TM_World instance that was used when calling TM_World::ReferenceTeamMember() - TM_World* GetTM_World(void) const; - - /// \brief Serializes the current state of this object - /// \details To replicate a TM_TeamMember on another system, first instantiate the object using your own code, or a system such as ReplicaManager3. - /// Next, call SerializeConstruction() from whichever system owns the team member - /// Last, call DeserializeConstruction() on the newly created TM_TeamMember - /// \note You must instantiate and deserialize all TM_Team instances that the team member refers to before calling DesrializeConstruction(). ReplicaManager3::PostSerializeConstruction() and ReplicaManager3::PostDeserializeConstruction() will ensure this. - /// \param[out] constructionBitstream This object serialized to a BitStream - void SerializeConstruction(BitStream *constructionBitstream); - - /// \brief Deserializes the current state of this object - /// \details See SerializeConstruction for more details() - /// \note DeserializeConstruction also calls ReferenceTeamMember on the passed \a teamManager instance, there is no need to do so yourself - /// \param[in] teamManager TeamManager instance - /// \param[in] constructionBitstream This object serialized to a BitStream - bool DeserializeConstruction(TeamManager *teamManager, BitStream *constructionBitstream); - - /// \param[in] o Stores a void* for your own use. If using composition, this is useful to store a pointer to the containing object. - void SetOwner(void *o); - - /// \return Whatever was passed to SetOwner() - void *GetOwner(void) const; - - /// \return If not on a team, returns the current NoTeamId value - NoTeamId GetNoTeamId(void) const; - - /// Return world->GetTeamMemberIndex(this) - unsigned int GetWorldIndex(void) const; - - /// \internal - static unsigned long ToUint32( const NetworkID &g ); - - /// \internal - struct RequestedTeam - { - MafiaNet::Time whenRequested; - unsigned int requestIndex; - TM_Team *requested; - bool isTeamSwitch; - TM_Team *teamToLeave; - }; - -protected: - NetworkID networkId; - TM_World* world; - // Teams we are a member of. We can be on more than one team, but not on the same team more than once - DataStructures::List teams; - // If teams is empty, which subcategory of noTeam we are on - NoTeamId noTeamSubcategory; - // Teams we have requested to join. Mutually exclusive with teams we are already on. Cannot request the same team more than once. - DataStructures::List teamsRequested; - // If teamsRequested is not empty, we want to join a specific team - // If teamsRequested is empty, then joinTeamType is either JOIN_NO_TEAM or JOIN_ANY_AVAILABLE_TEAM - JoinTeamType joinTeamType; - // Set by StoreLastTeams() - DataStructures::List lastTeams; - MafiaNet::Time whenJoinAnyRequested; - unsigned int joinAnyRequestIndex; - void *owner; - - // Remove from all requested and current teams. - void UpdateListsToNoTeam(NoTeamId nti); - bool JoinAnyTeamCheck(void) const; - bool JoinSpecificTeamCheck(TM_Team *specificTeamToJoin, bool ignoreRequested) const; - bool SwitchSpecificTeamCheck(TM_Team *teamToJoin, TM_Team *teamToLeave, bool ignoreRequested) const; - bool LeaveTeamCheck(TM_Team *team) const; - void UpdateTeamsRequestedToAny(void); - void UpdateTeamsRequestedToNone(void); - void AddToRequestedTeams(TM_Team *teamToJoin); - void AddToRequestedTeams(TM_Team *teamToJoin, TM_Team *teamToLeave); - bool RemoveFromRequestedTeams(TM_Team *team); - void AddToTeamList(TM_Team *team); - void RemoveFromSpecificTeamInternal(TM_Team *team); - void RemoveFromAllTeamsInternal(void); - void StoreLastTeams(void); - - friend class TM_World; - friend class TM_Team; - friend class TeamManager; -}; - -/// \brief A team, containing a list of TM_TeamMember instances -/// \details Contains lists of TM_TeamMember instances -/// Best used as a composite member of your "Team" or "PlayerList" class(es). -/// When using with ReplicaManager3, call TM_Team::ReferenceTeam() in Replica3::DeserializeConstruction() and TM_Team::DeserializeConstruction() in Replica3::PostDeserializeConstruction() -/// There is otherwise no need to manually serialize the class, as operations are networked internally. -/// \ingroup TEAM_MANAGER_GROUP -class RAK_DLL_EXPORT TM_Team -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(TM_Team) - - TM_Team(); - virtual ~TM_Team(); - - /// \brief Set the maximum number of members that can join this team. - /// Defaults to 65535 - /// Setting the limit lower than the existing number of members kicks members out, and assigns noTeamSubcategory to them if they have no other team to go to - /// Setting the limit higher allows members to join in. If a member has a pending request to join this team, they join automatically and ID_TEAM_BALANCER_TEAM_ASSIGNED will be returned for those members. - /// \param[in] _teamMemberLimit The new limit - /// \param[in] noTeamSubcategory Which noTeamSubcategory to assign to members that now have no team. - /// \return false On invalid or unnecessary operation. Otherwise returns true - bool SetMemberLimit(TeamMemberLimit _teamMemberLimit, NoTeamId noTeamSubcategory); - - /// \return If team balancing is on, the most members that can be on this team that would not either unbalance it or exceed the value passed to SetMemberLimit(). If team balancing is off, the same as GetMemberLimitSetting() - TeamMemberLimit GetMemberLimit(void) const; - - /// \return What was passed to SetMemberLimit() or the default - TeamMemberLimit GetMemberLimitSetting(void) const; - - /// \brief Who can join this team under what conditions, while the team is not full - /// To not allow new joins, pass 0 - /// To allow all new joins under any circumstances, bitwise-OR all permission defines. - /// For an invite-only team, use ALLOW_JOIN_SPECIFIC_TEAM only and only allow the requester to call TM_TeamMember::RequestTeam() upon invitiation through your game code. - /// Defaults to allow all - /// \param[in] _joinPermissions Bitwise combination of ALLOW_JOIN_ANY_AVAILABLE_TEAM, ALLOW_JOIN_SPECIFIC_TEAM, ALLOW_JOIN_REBALANCING - /// \return false On invalid or unnecessary operation. Otherwise returns true - bool SetJoinPermissions(JoinPermissions _joinPermissions); - - /// \return Whatever was passed to SetJoinPermissions(), or the default. - JoinPermissions GetJoinPermissions(void) const; - - /// \brief Removes a member from a team he or she is on - /// \details Identical to teamMember->LeaveTeam(this, noTeamSubcategory); See TeamMember::LeaveTeam() for details. - /// \param[in] teamMember Which team member to remove - /// \param[in] noTeamSubcategory If the team member has been removed from all teams, which subcategory of NoTeamId to set them to - void LeaveTeam(TM_TeamMember* teamMember, NoTeamId noTeamSubcategory); - - /// \return What was passed as the \a applyBalancing parameter TM_World::ReferenceTeam() when this team was added. - bool GetBalancingApplies(void) const; - - /// \param[out] All team members of this team - void GetTeamMembers(DataStructures::List &_teamMembers) const; - - /// \return The number of team members on this team - unsigned int GetTeamMembersCount(void) const; - - /// \return A team member on this team. Members are stored in the order they are added - /// \param[in] index A value between 0 and GetTeamMembersCount() - TM_TeamMember *GetTeamMemberByIndex(unsigned int index) const; - - /// \return The teamID parameter passed to TM_World::ReferenceTeam() - NetworkID GetNetworkID(void) const; - - /// \return The TM_World instance that was used when calling TM_World::ReferenceTeamMember() - TM_World* GetTM_World(void) const; - - /// \brief Used by the host to serialize the initial state of this object to a new system - /// \details On the host, when sending existing objects to a new system, call SerializeConstruction() on each of those objects to serialize creation state. - /// Creating the actual Team and TeamMember objects should be handled by your game code, or a system such as ReplicaManager3 - void SerializeConstruction(BitStream *constructionBitstream); - - /// \brief Used by non-host systems to read the bitStream written by SerializeConstruction() - /// \details On non-host systems, after creating existing objects, call DeserializeConstruction() to read and setup that object - /// Creating the actual Team and TeamMember objects should be handled by your game code, or a system such as ReplicaManager3 - bool DeserializeConstruction(TeamManager *teamManager, BitStream *constructionBitstream); - - /// \param[in] o Stores a void* for your own use. If using composition, this is useful to store a pointer to the containing object. - void SetOwner(void *o); - - /// \return Whatever was passed to SetOwner() - void *GetOwner(void) const; - - /// Return world->GetTeamIndex(this) - unsigned int GetWorldIndex(void) const; - - /// \internal - static unsigned long ToUint32( const NetworkID &g ); - -protected: - NetworkID ID; - TM_World* world; - // Which members are on this team. The same member cannot be on the same team more than once - DataStructures::List teamMembers; - // Permissions on who can join this team - JoinPermissions joinPermissions; - // Whether or not to consider this team when balancing teams - bool balancingApplies; - TeamMemberLimit teamMemberLimit; - void *owner; - - // Remove input from list teamMembers - void RemoveFromTeamMemberList(TM_TeamMember *teamMember); - - // Find the member index that wants to join the indicated team, is only on one team, and wants to leave that team - unsigned int GetMemberWithRequestedSingleTeamSwitch(TM_Team *team); - - - friend class TM_World; - friend class TM_TeamMember; - friend class TeamManager; -}; - -/// \brief Stores a list of teams which may be enforcing a balanced number of members -/// \details Each TM_World instance is independent of other TM_World world instances. This enables you to host multiple games on a single computer. -/// Not currently supported to have the same TM_Team or TM_TeamMember in more than one world at a time, but easily added on request. -/// \ingroup TEAM_MANAGER_GROUP -class TM_World -{ -public: - TM_World(); - virtual ~TM_World(); - - /// \return Returns the plugin that created this TM_World instance - TeamManager *GetTeamManager(void) const; - - /// \brief Add a new system to send team and team member updates to. - /// \param[in] rakNetGUID GUID of the system you are adding. See Packet::rakNetGUID or RakPeerInterface::GetGUIDFromSystemAddress() - void AddParticipant(RakNetGUID rakNetGUID); - - /// \brief Remove a system that was previously added with AddParticipant() - /// \details Systems that disconnect are removed automatically - /// \param[in] rakNetGUID GUID of the system you are removing. See Packet::rakNetGUID or RakPeerInterface::GetGUIDFromSystemAddress() - void RemoveParticipant(RakNetGUID rakNetGUID); - - /// \brief If true, all new connections are added to this world using AddParticipant() - /// \details Defaults to true - /// \param[in] autoAdd Setting to set - void SetAutoManageConnections(bool autoAdd); - - /// Get the participants added with AddParticipant() - /// \param[out] participantList Participants added with AddParticipant(); - void GetParticipantList(DataStructures::List &participantList); - - /// \brief Register a TM_Team object with this system. - /// \details Your game should contain instances of TM_Team, for example by using composition with your game's Team or PlayerList class - /// Tell TeamManager about these instances using ReferenceTeam(). - /// \note The destrutor of TM_Team calls DereferenceTeam() automatically. - /// \param[in] team The instance you are registering - /// \param[in] networkId Identifies this instance. This value is independent of values used by NetworkIDManager. You can use the same value as the object that contains this instance. - /// \param[in] applyBalancing Whether or not to include this team for balancing when calling SetBalanceTeams(). - void ReferenceTeam(TM_Team *team, NetworkID networkId, bool applyBalancing); - - /// \brief Unregisters the associated TM_Team object with this system. - /// Call when a TM_Team instance is no longer needed - /// \param[in] team Which team instance to unregister - /// \param[in] noTeamSubcategory All players on this team are kicked off. If these players then have no team, they are set to this no team category. - void DereferenceTeam(TM_Team *team, NoTeamId noTeamSubcategory); - - /// \return Number of teams uniquely added with ReferenceTeam() - unsigned int GetTeamCount(void) const; - - /// \param[in] index A value between 0 and GetTeamCount() - /// \return Returns whatever was passed to \a team in the function ReferenceTeam() in the order it was called. - TM_Team *GetTeamByIndex(unsigned int index) const; - - /// \param[in] teamId Value passed to ReferenceTeam() - /// \return Returns whatever was passed to \a team in the function ReferenceTeam() with this NetworkID. - TM_Team *GetTeamByNetworkID(NetworkID teamId); - - /// \brief Inverse of GetTeamByIndex() - /// \param[in] team Which taem - /// \return The index of the specified team, or -1 if not found - unsigned int GetTeamIndex(const TM_Team *team) const; - - /// \brief Register a TM_TeamMember object with this system. - /// \details Your game should contain instances of TM_TeamMember, for example by using composition with your game's User or Player classes - /// Tell TeamManager about these instances using ReferenceTeamMember(). - /// \note The destrutor of TM_TeamMember calls DereferenceTeamMember() automatically. - /// \param[in] teamMember The instance you are registering - /// \param[in] networkId Identifies this instance. This value is independent of values used by NetworkIDManager. You can use the same value as the object that contains this instance - void ReferenceTeamMember(TM_TeamMember *teamMember, NetworkID networkId); - - /// \brief Unregisters the associated TM_TeamMember object with this system. - /// Call when a TM_TeamMember instance is no longer needed - /// \note This is called by the destructor of TM_TeamMember automatically, so you do not normally need to call this function - void DereferenceTeamMember(TM_TeamMember *teamMember); - - /// \return Number of team members uniquely added with ReferenceTeamMember() - unsigned int GetTeamMemberCount(void) const; - - /// \param[in] index A value between 0 and GetTeamMemberCount() - /// \return Returns whatever was passed to \a team in the function ReferenceTeamMember() in the order it was called. - TM_TeamMember *GetTeamMemberByIndex(unsigned int index) const; - - /// \param[in] index A value between 0 and GetTeamMemberCount() - /// \return Returns whatever was passed to \a teamMemberID in the function ReferenceTeamMember() in the order it was called. - NetworkID GetTeamMemberIDByIndex(unsigned int index) const; - - /// \param[in] teamId Value passed to ReferenceTeamMember() - /// \return Returns Returns whatever was passed to \a team in the function ReferenceTeamMember() with this NetworkID - TM_TeamMember *GetTeamMemberByNetworkID(NetworkID teamMemberId); - - /// \brief Inverse of GetTeamMemberByIndex() - /// \param[in] team Which team member - /// \return The index of the specified team member, or -1 if not found - unsigned int GetTeamMemberIndex(const TM_TeamMember *teamMember) const; - - /// \brief Force or stop forcing teams to be balanced. - /// \details For each team added with ReferenceTeam() and \a applyBalancing set to true, players on unbalanced teams will be redistributed - /// While active, players can only join balanced teams if doing so would not cause that team to become unbalanced. - /// If a player on the desired team also wants to switch, then both players will switch simultaneously. Otherwise, ID_TEAM_BALANCER_REQUESTED_TEAM_FULL will be returned to the requester and switching will occur when possible. - /// If balanceTeams is true and later set to false, players waiting on ID_TEAM_BALANCER_REQUESTED_TEAM_FULL will be able to join the desired team immediately provided it is not full. - /// \param[in] balanceTeams Whether to activate or deactivate team balancing. - /// \param[in] noTeamSubcategory If a player is kicked off a team and is no longer on any team, his or her noTeamSubcategory is set to this value - bool SetBalanceTeams(bool balanceTeams, NoTeamId noTeamSubcategory); - - /// \return \a balanceTeams parameter of SetBalanceTeams(), or the default - bool GetBalanceTeams(void) const; - - /// \brief Set the host that will perform balancing calculations and send notifications - /// \details Operations that can cause conflicts due to latency, such as joining teams, are operated on by the host. The result is sent to all systems added with AddParticipant() - /// For a client/server game, call SetHost() with the server's RakNetGUID value on all systems (including the server itself). If you call TeamManager::SetTopology(TM_CLIENT_SERVER), the server will also relay messages between participants. - /// For a peer to peer game, call SetHost() on the same peer when host migration occurs. Use TeamManager::SetTopology(TM_PEER_TO_PEER) in this case. - /// \note If using FullyConnectedMesh2, SetHost() is called automatically when ID_FCM2_NEW_HOST is returned. - /// \param[in] _hostGuid The host, which is the system that will serialize and resolve team disputes and calculate team balancing. - void SetHost(RakNetGUID _hostGuid); - - /// \return Returns the current host, or UNASSIGNED_RAKNET_GUID if unknown - RakNetGUID GetHost(void) const; - - /// \return The \a worldId passed to TeamManagr::AddWorld() - WorldId GetWorldId(void) const; - - /// \brief Clear all memory and reset everything. - /// \details It is up to the user to deallocate pointers passed to ReferenceTeamMember() or ReferenceTeam(), if so desired. - void Clear(void); - - /// \internal - struct JoinRequestHelper - { - MafiaNet::Time whenRequestMade; - unsigned int teamMemberIndex; - unsigned int indexIntoTeamsRequested; - unsigned int requestIndex; - }; - /// \internal - static int JoinRequestHelperComp(const TM_World::JoinRequestHelper &key, const TM_World::JoinRequestHelper &data); - -protected: - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); - - // Teams with too many members have those members go to other teams. - void EnforceTeamBalance(NoTeamId noTeamSubcategory); - void KickExcessMembers(NoTeamId noTeamSubcategory); - void FillRequestedSlots(void); - unsigned int GetAvailableTeamIndexWithFewestMembers(TeamMemberLimit secondaryLimit, JoinPermissions joinPermissions); - - void GetSortedJoinRequests(DataStructures::OrderedList &joinRequests); - - - // Send a message to all participants - void BroadcastToParticipants(MafiaNet::BitStream *bsOut, RakNetGUID exclusionGuid); - void BroadcastToParticipants(unsigned char *data, const int length, RakNetGUID exclusionGuid); - - // 1. If can join a team: - // A. teamMember->UpdateTeamsRequestedToNone(); - // B. teamMember->AddToTeamList() - // C. Return new team - // 2. Else return 0 - TM_Team* JoinAnyTeam(TM_TeamMember *teamMember, int *resultCode); - - int JoinSpecificTeam(TM_TeamMember *teamMember, TM_Team *team, bool isTeamSwitch, TM_Team *teamToLeave, DataStructures::List &teamsWeAreLeaving); - - TeamMemberLimit GetBalancedTeamLimit(void) const; - - // For fast lookup. Shares pointers with list teams - DataStructures::Hash teamsHash; - // For fast lookup. Shares pointers with list teamMembers - DataStructures::Hash teamMembersHash; - - TeamManager *teamManager; - DataStructures::List participants; - DataStructures::List teams; - DataStructures::List teamMembers; - bool balanceTeamsIsActive; - RakNetGUID hostGuid; - WorldId worldId; - bool autoAddParticipants; - int teamRequestIndex; - - friend class TeamManager; - friend class TM_TeamMember; - friend class TM_Team; -}; - -/// \brief Automates networking and list management for teams -/// \details TeamManager provides support for teams. A team is a list of team members. -/// Teams contain properties including the number of team members per team, whether or not tagged teams must have equal numbers of members, and if a team is locked or not to certain entry conditions -/// Team members contain properties including which teams they are on and which teams they want to join if a team is not immediately joinable -/// Advanced functionality includes the ability for a team member to be on multiple teams simultaneously, the ability to swap teams with other members, and the ability to resize the number of members supported per team -/// The architecture is designed for easy integration with ReplicaManager3 -/// -/// Usage:
    -/// 1. Define your game classes to represent teams and team members. Your game classes should hold game-specific information such as team name and color.
    -/// 2. Have those game classes contain a corresponding TM_Team or TM_TeamMember instance. Operations on teams will be performed by those instances. Use SetOwner() to refer to the parent object when using composition.
    -/// 3. Call TeamManager::SetTopology() for client/server or peer to peer.
    -/// 4. Call AddWorld() to instantiate a TM_World object which will contain references to your TM_TeamMember and TM_Team instances.
    -/// 5. When you instantiate a TM_TeamMember or TM_Team object, call ReferenceTeam() and ReferenceTeamMember() for each corresponding object
    -/// 6. When sending world state to a new connection, for example in ReplicaManager3::SerializeConstruction(), call TM_SerializeConstruction() on the corresponding TM_TeamMember and TM_Team objects. TM_Team instances on the new connection must be created before TM_TeamMember instances.
    -/// 7. Call TM_DeserializeConstruction() on your new corresponding TM_TeamMember and TM_Team instances.
    -/// 8. Execute team operations. ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED, ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED, and ID_TEAM_BALANCER_TEAM_ASSIGNED are returned to all systems when the corresponding event occurs for a team member.
    -/// 9. As the peer to peer session host changes, call SetHost() (Not necessary if using FullyConnectedMesh2). If using client/server, you must set the host
    -/// \note This replaces TeamBalancer. You cannot use TeamBalancer and TeamManager at the same time. -/// \ingroup TEAM_MANAGER_GROUP -class RAK_DLL_EXPORT TeamManager : public PluginInterface2 -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(TeamManager) - - TeamManager(); - virtual ~TeamManager(); - - /// \brief Allocate a world to hold a list of teams and players for that team. - /// Use the returned TM_World object for actual team functionality. - /// \note The world is tracked by TeamManager and deallocated by calling Clear() - /// \param[in] worldId Arbitrary user-defined id of the world to create. Each world instance must have a unique id. - TM_World* AddWorld(WorldId worldId); - - /// \brief Deallocate a world created with AddWorld() - /// \param[in] worldId The world to deallocate - void RemoveWorld(WorldId worldId); - - /// \return Returns the number of worlds created with AddWorld() - unsigned int GetWorldCount(void) const; - - /// \param[in] index A value beteween 0 and GetWorldCount()-1 inclusive. - /// \return Returns a world created with AddWorld() - TM_World* GetWorldAtIndex(unsigned int index) const; - - /// \param[in] worldId \a worldId value passed to AddWorld() - /// \return Returns a world created with AddWorld(), or 0 if no such \a worldId - TM_World* GetWorldWithId(WorldId worldId) const; - - /// \brief When auto managing connections, call TM_World::AddParticipant() on all worlds for all new connections automatically - /// Defaults to true - /// \note You probably want this set to false if using multiple worlds - /// \param[in] autoAdd Automatically call TM_World::AddParticipant() all worlds each new connection. Defaults to true. - void SetAutoManageConnections(bool autoAdd); - - /// \brief If \a _topology is set to TM_CLIENT_SERVER, the host will relay messages to participants. - /// \details If topology is set to TM_PEER_TO_PEER, the host assumes the original message source was connected to all other participants and does not relay messages. - /// \note If TM_PEER_TO_PEER, this plugin will listen for ID_FCM2_NEW_HOST and call SetHost() on all worlds automatically - /// \note Defaults to TM_PEER_TO_PEER - /// \param[in] _topology Topology to use - void SetTopology(TMTopology _topology); - - /// \brief When you get ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, pass the packet to this function to read out parameters - /// \param[in] A packet where packet->data[0]==ID_TEAM_BALANCER_REQUESTED_TEAM_FULL - /// \return true on success, false on read error - void DecomposeTeamFull(Packet *packet, - TM_World **world, TM_TeamMember **teamMember, TM_Team **team, - uint16_t ¤tMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions); - - /// \brief When you get ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED, pass the packet to this function to read out parameters - /// \param[in] A packet where packet->data[0]==ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED - /// \return true on success, false on read error - void DecomposeTeamLocked(Packet *packet, - TM_World **world, TM_TeamMember **teamMember, TM_Team **team, - uint16_t ¤tMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions); - - /// \brief Clear all memory and reset everything. - /// \details Deallocates TM_World instances. It is up to the user to deallocate pointers passed to ReferenceTeamMember() or ReferenceTeam(), if so desired. - void Clear(void); - - /// \brief Reads out the world and teamMember from ID_TEAM_BALANCER_TEAM_ASSIGNED - /// \note You can get the current and prior team list from the teamMember itself - /// \param[in] A packet where packet->data[0]==ID_TEAM_BALANCER_TEAM_ASSIGNED - /// \param[out] world Set to the world this \a teamMember is on. 0 on bad lookup. - /// \param[out] teamMember Set to the teamMember affected. 0 on bad lookup. - void DecodeTeamAssigned(Packet *packet, TM_World **world, TM_TeamMember **teamMember); - - // \brief Reads out the world and teamMember from ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED - /// \note You can get the requested team list from the teamMember itself - /// \param[in] A packet where packet->data[0]==ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED - /// \param[out] world Set to the world this \a teamMember is on. 0 on bad lookup. - /// \param[out] teamMember Set to the teamMember affected. 0 on bad lookup. - /// \param[out] teamCancelled Set to the team that was cancelled. 0 for all teams. - void DecodeTeamCancelled(Packet *packet, TM_World **world, TM_TeamMember **teamMember, TM_Team **teamCancelled); - -protected: - - virtual void Update(void); - virtual PluginReceiveResult OnReceive(Packet *packet); - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); - void Send( const MafiaNet::BitStream * bitStream, const AddressOrGUID systemIdentifier, bool broadcast ); - - void EncodeTeamFullOrLocked(MafiaNet::BitStream *bitStream, TM_TeamMember *teamMember, TM_Team *team); - void DecomposeTeamFullOrLocked(MafiaNet::BitStream *bsIn, TM_World **world, TM_TeamMember **teamMember, TM_Team **team, - uint16_t ¤tMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions); - void ProcessTeamAssigned(MafiaNet::BitStream *bsIn); - - void EncodeTeamAssigned(MafiaNet::BitStream *bitStream, TM_TeamMember *teamMember); - void RemoveFromTeamsRequestedAndAddTeam(TM_TeamMember *teamMember, TM_Team *team, bool isTeamSwitch, TM_Team *teamToLeave); - - void PushTeamAssigned(TM_TeamMember *teamMember); - void PushBitStream(MafiaNet::BitStream *bitStream); - void OnUpdateListsToNoTeam(Packet *packet, TM_World *world); - void OnUpdateTeamsRequestedToAny(Packet *packet, TM_World *world); - void OnJoinAnyTeam(Packet *packet, TM_World *world); - void OnJoinRequestedTeam(Packet *packet, TM_World *world); - void OnUpdateTeamsRequestedToNoneAndAddTeam(Packet *packet, TM_World *world); - void OnRemoveFromTeamsRequestedAndAddTeam(Packet *packet, TM_World *world); - void OnAddToRequestedTeams(Packet *packet, TM_World *world); - bool OnRemoveFromRequestedTeams(Packet *packet, TM_World *world); - void OnLeaveTeam(Packet *packet, TM_World *world); - void OnSetMemberLimit(Packet *packet, TM_World *world); - void OnSetJoinPermissions(Packet *packet, TM_World *world); - void OnSetBalanceTeams(Packet *packet, TM_World *world); - void OnSetBalanceTeamsInitial(Packet *packet, TM_World *world); - - - void EncodeTeamFull(MafiaNet::BitStream *bitStream, TM_TeamMember *teamMember, TM_Team *team); - void EncodeTeamLocked(MafiaNet::BitStream *bitStream, TM_TeamMember *teamMember, TM_Team *team); - - /// \brief When you get ID_TEAM_BALANCER_TEAM_ASSIGNED, pass the packet to this function to read out parameters - /// \param[in] A packet where packet->data[0]==ID_TEAM_BALANCER_TEAM_ASSIGNED - /// \return true on success, false on read error - void DecodeTeamAssigned(MafiaNet::BitStream *bsIn, TM_World **world, TM_TeamMember **teamMember, NoTeamId &noTeamSubcategory, - JoinTeamType &joinTeamType, DataStructures::List &newTeam, - DataStructures::List &teamsLeft, DataStructures::List &teamsJoined); - - // O(1) lookup for a given world. If I need more worlds, change this to a hash or ordered list - TM_World *worldsArray[255]; - // All allocated worlds for linear traversal - DataStructures::List worldsList; - bool autoAddParticipants; - TMTopology topology; - - friend class TM_TeamMember; - friend class TM_World; - friend class TM_Team; -}; - -} // namespace MafiaNet - -#endif // __TEAM_MANAGER_H - -#endif // _RAKNET_SUPPORT_* - diff --git a/vendors/mafianet/Source/include/mafianet/TelnetTransport.h b/vendors/mafianet/Source/include/mafianet/TelnetTransport.h deleted file mode 100644 index 24510fed4..000000000 --- a/vendors/mafianet/Source/include/mafianet/TelnetTransport.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Contains TelnetTransport , used to supports the telnet transport protocol. Insecure -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_TelnetTransport==1 && _RAKNET_SUPPORT_TCPInterface==1 - -#ifndef __TELNET_TRANSPORT -#define __TELNET_TRANSPORT - -#include "TransportInterface.h" -#include "DS_List.h" -#include "Export.h" - -namespace MafiaNet -{ -/// Forward declarations -class TCPInterface; -struct TelnetClient; - -/// \brief Use TelnetTransport to easily allow windows telnet to connect to your ConsoleServer -/// \details To run Windows telnet, go to your start menu, click run, and in the edit box type "telnet " where is the ip address.
    -/// of your ConsoleServer (most likely the same IP as your game).
    -/// This implementation always echos commands. -class RAK_DLL_EXPORT TelnetTransport : public TransportInterface -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(TelnetTransport) - - TelnetTransport(); - virtual ~TelnetTransport(); - bool Start(unsigned short port, bool serverMode); - void Stop(void); - void Send( SystemAddress systemAddress, const char *data, ... ); - void CloseConnection( SystemAddress systemAddress ); - Packet* Receive( void ); - void DeallocatePacket( Packet *packet ); - SystemAddress HasNewIncomingConnection(void); - SystemAddress HasLostConnection(void); - CommandParserInterface* GetCommandParser(void); - void SetSendSuffix(const char *suffix); - void SetSendPrefix(const char *prefix); -protected: - - struct TelnetClient - { - SystemAddress systemAddress; - char textInput[REMOTE_MAX_TEXT_INPUT]; - char lastSentTextInput[REMOTE_MAX_TEXT_INPUT]; - unsigned cursorPosition; - }; - - TCPInterface *tcpInterface; - void AutoAllocate(void); - bool ReassembleLine(TelnetTransport::TelnetClient* telnetClient, unsigned char c); - - // Crap this sucks but because windows telnet won't send line at a time, I have to reconstruct the lines at the server per player - DataStructures::List remoteClients; - - char *sendSuffix, *sendPrefix; - -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/ThreadPool.h b/vendors/mafianet/Source/include/mafianet/ThreadPool.h deleted file mode 100644 index e2f387b3f..000000000 --- a/vendors/mafianet/Source/include/mafianet/ThreadPool.h +++ /dev/null @@ -1,636 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __THREAD_POOL_H -#define __THREAD_POOL_H - -#include "memoryoverride.h" -#include "DS_Queue.h" -#include "SimpleMutex.h" -#include "Export.h" -#include "thread.h" -#include "SignaledEvent.h" - -class ThreadDataInterface -{ -public: - ThreadDataInterface() {} - virtual ~ThreadDataInterface() {} - - virtual void* PerThreadFactory(void *context)=0; - virtual void PerThreadDestructor(void* factoryResult, void *context)=0; -}; -/// A simple class to create worker threads that processes a queue of functions with data. -/// This class does not allocate or deallocate memory. It is up to the user to handle memory management. -/// InputType and OutputType are stored directly in a queue. For large structures, if you plan to delete from the middle of the queue, -/// you might wish to store pointers rather than the structures themselves so the array can shift efficiently. -template -struct RAK_DLL_EXPORT ThreadPool -{ - ThreadPool(); - ~ThreadPool(); - - /// Start the specified number of threads. - /// \param[in] numThreads The number of threads to start - /// \param[in] stackSize 0 for default (except on consoles). - /// \param[in] _perThreadInit User callback to return data stored per thread. Pass 0 if not needed. - /// \param[in] _perThreadDeinit User callback to destroy data stored per thread, created by _perThreadInit. Pass 0 if not needed. - /// \return True on success, false on failure. - bool StartThreads(int numThreads, int stackSize, void* (*_perThreadInit)()=0, void (*_perThreadDeinit)(void*)=0); - - // Alternate form of _perThreadDataFactory, _perThreadDataDestructor - void SetThreadDataInterface(ThreadDataInterface *tdi, void *context); - - /// Stops all threads - void StopThreads(void); - - /// Adds a function to a queue with data to pass to that function. This function will be called from the thread - /// Memory management is your responsibility! This class does not allocate or deallocate memory. - /// The best way to deallocate \a inputData is in userCallback. If you call EndThreads such that callbacks were not called, you - /// can iterate through the inputQueue and deallocate all pending input data there - /// The best way to deallocate output is as it is returned to you from GetOutput. Similarly, if you end the threads such that - /// not all output was returned, you can iterate through outputQueue and deallocate it there. - /// \param[in] workerThreadCallback The function to call from the thread - /// \param[in] inputData The parameter to pass to \a userCallback - void AddInput(OutputType (*workerThreadCallback)(InputType, bool *returnOutput, void* perThreadData), InputType inputData); - - /// Adds to the output queue - /// Use it if you want to inject output into the same queue that the system uses. Normally you would not use this. Consider it a convenience function. - /// \param[in] outputData The output to inject - void AddOutput(OutputType outputData); - - /// Returns true if output from GetOutput is waiting. - /// \return true if output is waiting, false otherwise - bool HasOutput(void); - - /// Inaccurate but fast version of HasOutput. If this returns true, you should still check HasOutput for the real value. - /// \return true if output is probably waiting, false otherwise - bool HasOutputFast(void); - - /// Returns true if input from GetInput is waiting. - /// \return true if input is waiting, false otherwise - bool HasInput(void); - - /// Inaccurate but fast version of HasInput. If this returns true, you should still check HasInput for the real value. - /// \return true if input is probably waiting, false otherwise - bool HasInputFast(void); - - /// Gets the output of a call to \a userCallback - /// HasOutput must return true before you call this function. Otherwise it will assert. - /// \return The output of \a userCallback. If you have different output signatures, it is up to you to encode the data to indicate this - OutputType GetOutput(void); - - /// Clears internal buffers - void Clear(void); - - /// Lock the input buffer before calling the functions InputSize, InputAtIndex, and RemoveInputAtIndex - /// It is only necessary to lock the input or output while the threads are running - void LockInput(void); - - /// Unlock the input buffer after you are done with the functions InputSize, GetInputAtIndex, and RemoveInputAtIndex - void UnlockInput(void); - - /// Length of the input queue - unsigned InputSize(void); - - /// Get the input at a specified index - InputType GetInputAtIndex(unsigned index); - - /// Remove input from a specific index. This does NOT do memory deallocation - it only removes the item from the queue - void RemoveInputAtIndex(unsigned index); - - /// Lock the output buffer before calling the functions OutputSize, OutputAtIndex, and RemoveOutputAtIndex - /// It is only necessary to lock the input or output while the threads are running - void LockOutput(void); - - /// Unlock the output buffer after you are done with the functions OutputSize, GetOutputAtIndex, and RemoveOutputAtIndex - void UnlockOutput(void); - - /// Length of the output queue - unsigned OutputSize(void); - - /// Get the output at a specified index - OutputType GetOutputAtIndex(unsigned index); - - /// Remove output from a specific index. This does NOT do memory deallocation - it only removes the item from the queue - void RemoveOutputAtIndex(unsigned index); - - /// Removes all items from the input queue - void ClearInput(void); - - /// Removes all items from the output queue - void ClearOutput(void); - - /// Are any of the threads working, or is input or output available? - bool IsWorking(void); - - /// The number of currently active threads. - int NumThreadsWorking(void); - - /// Did we call Start? - bool WasStarted(void); - - // Block until all threads are stopped. - bool Pause(void); - - // Continue running - void Resume(void); - -protected: - // It is valid to cancel input before it is processed. To do so, lock the inputQueue with inputQueueMutex, - // Scan the list, and remove the item you don't want. - MafiaNet::SimpleMutex inputQueueMutex, outputQueueMutex, workingThreadCountMutex, runThreadsMutex; - - void* (*perThreadDataFactory)(); - void (*perThreadDataDestructor)(void*); - - // inputFunctionQueue & inputQueue are paired arrays so if you delete from one at a particular index you must delete from the other - // at the same index - DataStructures::Queue inputFunctionQueue; - DataStructures::Queue inputQueue; - DataStructures::Queue outputQueue; - - ThreadDataInterface *threadDataInterface; - void *tdiContext; - - - template - friend RAK_THREAD_DECLARATION(WorkerThread); - - /* -#ifdef _WIN32 - friend unsigned __stdcall WorkerThread( LPVOID arguments ); -#else - friend void* WorkerThread( void* arguments ); -#endif - */ - - /// \internal - bool runThreads; - /// \internal - int numThreadsRunning; - /// \internal - int numThreadsWorking; - /// \internal - MafiaNet::SimpleMutex numThreadsRunningMutex; - - MafiaNet::SignaledEvent quitAndIncomingDataEvents; - -// #if defined(SN_TARGET_PSP2) -// MafiaNet::RakThread::UltUlThreadRuntime *runtime; -// #endif -}; - -#include "ThreadPool.h" -#include "sleep.h" -#ifdef _WIN32 - -#else -#include -#endif - -// #med - consider simplifying this and use a simple macro? -// disable false-positive warnings 4701/4703 about inputData not being initialized (which it isn't in the case it's used) -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4701) // potentially uninitialized local variable -#pragma warning(disable:4703) // potentially uninitialized local pointer -#endif -template -RAK_THREAD_DECLARATION(WorkerThread) -/* -#ifdef _WIN32 -unsigned __stdcall WorkerThread( LPVOID arguments ) -#else -void* WorkerThread( void* arguments ) -#endif -*/ -{ - - - - ThreadPool *threadPool = (ThreadPool*) arguments; - - - bool returnOutput; - ThreadOutputType (*userCallback)(ThreadInputType, bool *, void*); - ThreadInputType inputData; - ThreadOutputType callbackOutput; - - userCallback=0; - - void *perThreadData; - if (threadPool->perThreadDataFactory) - perThreadData=threadPool->perThreadDataFactory(); - else if (threadPool->threadDataInterface) - perThreadData=threadPool->threadDataInterface->PerThreadFactory(threadPool->tdiContext); - else - perThreadData=0; - - // Increase numThreadsRunning - threadPool->numThreadsRunningMutex.Lock(); - ++threadPool->numThreadsRunning; - threadPool->numThreadsRunningMutex.Unlock(); - - for(;;) - { -//#ifdef _WIN32 - if (userCallback==0) - { - threadPool->quitAndIncomingDataEvents.WaitOnEvent(1000); - } -// #else -// if (userCallback==0) -// RakSleep(30); -// #endif - - threadPool->runThreadsMutex.Lock(); - if (threadPool->runThreads==false) - { - threadPool->runThreadsMutex.Unlock(); - break; - } - threadPool->runThreadsMutex.Unlock(); - - threadPool->workingThreadCountMutex.Lock(); - ++threadPool->numThreadsWorking; - threadPool->workingThreadCountMutex.Unlock(); - - // Read input data - userCallback=0; - threadPool->inputQueueMutex.Lock(); - if (threadPool->inputFunctionQueue.Size()) - { - userCallback=threadPool->inputFunctionQueue.Pop(); - inputData=threadPool->inputQueue.Pop(); - } - threadPool->inputQueueMutex.Unlock(); - - if (userCallback) - { - callbackOutput=userCallback(inputData, &returnOutput,perThreadData); - if (returnOutput) - { - threadPool->outputQueueMutex.Lock(); - threadPool->outputQueue.Push(callbackOutput, _FILE_AND_LINE_ ); - threadPool->outputQueueMutex.Unlock(); - } - } - - threadPool->workingThreadCountMutex.Lock(); - --threadPool->numThreadsWorking; - threadPool->workingThreadCountMutex.Unlock(); - } - - // Decrease numThreadsRunning - threadPool->numThreadsRunningMutex.Lock(); - --threadPool->numThreadsRunning; - threadPool->numThreadsRunningMutex.Unlock(); - - if (threadPool->perThreadDataDestructor) - threadPool->perThreadDataDestructor(perThreadData); - else if (threadPool->threadDataInterface) - threadPool->threadDataInterface->PerThreadDestructor(perThreadData, threadPool->tdiContext); - - - - - return 0; - -} -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -template -ThreadPool::ThreadPool() -{ - runThreads=false; - numThreadsRunning=0; - threadDataInterface=0; - tdiContext=0; - numThreadsWorking=0; - -} -template -ThreadPool::~ThreadPool() -{ - StopThreads(); - Clear(); -} -template -bool ThreadPool::StartThreads(int numThreads, int stackSize, void* (*_perThreadDataFactory)(), void (*_perThreadDataDestructor)(void *)) -{ - (void) stackSize; - -// #if defined(SN_TARGET_PSP2) -// runtime = MafiaNet::RakThread::AllocRuntime(numThreads); -// #endif - - runThreadsMutex.Lock(); - if (runThreads==true) - { - // Already running - runThreadsMutex.Unlock(); - return false; - } - runThreadsMutex.Unlock(); - - quitAndIncomingDataEvents.InitEvent(); - - perThreadDataFactory=_perThreadDataFactory; - perThreadDataDestructor=_perThreadDataDestructor; - - runThreadsMutex.Lock(); - runThreads=true; - runThreadsMutex.Unlock(); - - numThreadsWorking=0; - unsigned threadId = 0; - (void) threadId; - int i; - for (i=0; i < numThreads; i++) - { - int errorCode; - - - - - errorCode = MafiaNet::RakThread::Create(WorkerThread, this); - - if (errorCode!=0) - { - StopThreads(); - return false; - } - } - // Wait for number of threads running to increase to numThreads - bool done=false; - while (done==false) - { - RakSleep(50); - numThreadsRunningMutex.Lock(); - if (numThreadsRunning==numThreads) - done=true; - numThreadsRunningMutex.Unlock(); - } - - return true; -} -template -void ThreadPool::SetThreadDataInterface(ThreadDataInterface *tdi, void *context) -{ - threadDataInterface=tdi; - tdiContext=context; -} -template -void ThreadPool::StopThreads(void) -{ - runThreadsMutex.Lock(); - if (runThreads==false) - { - runThreadsMutex.Unlock(); - return; - } - - runThreads=false; - runThreadsMutex.Unlock(); - - // Wait for number of threads running to decrease to 0 - bool done=false; - while (done==false) - { - quitAndIncomingDataEvents.SetEvent(); - - RakSleep(50); - numThreadsRunningMutex.Lock(); - if (numThreadsRunning==0) - done=true; - numThreadsRunningMutex.Unlock(); - } - - quitAndIncomingDataEvents.CloseEvent(); - -// #if defined(SN_TARGET_PSP2) -// MafiaNet::RakThread::DeallocRuntime(runtime); -// runtime=0; -// #endif - -} -template -void ThreadPool::AddInput(OutputType (*workerThreadCallback)(InputType, bool *returnOutput, void* perThreadData), InputType inputData) -{ - inputQueueMutex.Lock(); - inputQueue.Push(inputData, _FILE_AND_LINE_ ); - inputFunctionQueue.Push(workerThreadCallback, _FILE_AND_LINE_ ); - inputQueueMutex.Unlock(); - - quitAndIncomingDataEvents.SetEvent(); -} -template -void ThreadPool::AddOutput(OutputType outputData) -{ - outputQueueMutex.Lock(); - outputQueue.Push(outputData, _FILE_AND_LINE_ ); - outputQueueMutex.Unlock(); -} -template -bool ThreadPool::HasOutputFast(void) -{ - return outputQueue.IsEmpty()==false; -} -template -bool ThreadPool::HasOutput(void) -{ - bool res; - outputQueueMutex.Lock(); - res=outputQueue.IsEmpty()==false; - outputQueueMutex.Unlock(); - return res; -} -template -bool ThreadPool::HasInputFast(void) -{ - return inputQueue.IsEmpty()==false; -} -template -bool ThreadPool::HasInput(void) -{ - bool res; - inputQueueMutex.Lock(); - res=inputQueue.IsEmpty()==false; - inputQueueMutex.Unlock(); - return res; -} -template -OutputType ThreadPool::GetOutput(void) -{ - // Real output check - OutputType output; - outputQueueMutex.Lock(); - output=outputQueue.Pop(); - outputQueueMutex.Unlock(); - return output; -} -template -void ThreadPool::Clear(void) -{ - runThreadsMutex.Lock(); - if (runThreads) - { - runThreadsMutex.Unlock(); - inputQueueMutex.Lock(); - inputFunctionQueue.Clear(_FILE_AND_LINE_); - inputQueue.Clear(_FILE_AND_LINE_); - inputQueueMutex.Unlock(); - - outputQueueMutex.Lock(); - outputQueue.Clear(_FILE_AND_LINE_); - outputQueueMutex.Unlock(); - } - else - { - inputFunctionQueue.Clear(_FILE_AND_LINE_); - inputQueue.Clear(_FILE_AND_LINE_); - outputQueue.Clear(_FILE_AND_LINE_); - } -} -template -void ThreadPool::LockInput(void) -{ - inputQueueMutex.Lock(); -} -template -void ThreadPool::UnlockInput(void) -{ - inputQueueMutex.Unlock(); -} -template -unsigned ThreadPool::InputSize(void) -{ - return inputQueue.Size(); -} -template -InputType ThreadPool::GetInputAtIndex(unsigned index) -{ - return inputQueue[index]; -} -template -void ThreadPool::RemoveInputAtIndex(unsigned index) -{ - inputQueue.RemoveAtIndex(index); - inputFunctionQueue.RemoveAtIndex(index); -} -template -void ThreadPool::LockOutput(void) -{ - outputQueueMutex.Lock(); -} -template -void ThreadPool::UnlockOutput(void) -{ - outputQueueMutex.Unlock(); -} -template -unsigned ThreadPool::OutputSize(void) -{ - return outputQueue.Size(); -} -template -OutputType ThreadPool::GetOutputAtIndex(unsigned index) -{ - return outputQueue[index]; -} -template -void ThreadPool::RemoveOutputAtIndex(unsigned index) -{ - outputQueue.RemoveAtIndex(index); -} -template -void ThreadPool::ClearInput(void) -{ - inputQueue.Clear(_FILE_AND_LINE_); - inputFunctionQueue.Clear(_FILE_AND_LINE_); -} - -template -void ThreadPool::ClearOutput(void) -{ - outputQueue.Clear(_FILE_AND_LINE_); -} -template -bool ThreadPool::IsWorking(void) -{ - bool isWorking; -// workingThreadCountMutex.Lock(); -// isWorking=numThreadsWorking!=0; -// workingThreadCountMutex.Unlock(); - -// if (isWorking) -// return true; - - // Bug fix: Originally the order of these two was reversed. - // It's possible with the thread timing that working could have been false, then it picks up the data in the other thread, then it checks - // here and sees there is no data. So it thinks the thread is not working when it was. - if (HasOutputFast() && HasOutput()) - return true; - - if (HasInputFast() && HasInput()) - return true; - - // Need to check is working again, in case the thread was between the first and second checks - workingThreadCountMutex.Lock(); - isWorking=numThreadsWorking!=0; - workingThreadCountMutex.Unlock(); - - return isWorking; -} - -template -int ThreadPool::NumThreadsWorking(void) -{ - return numThreadsWorking; -} - -template -bool ThreadPool::WasStarted(void) -{ - bool b; - runThreadsMutex.Lock(); - b = runThreads; - runThreadsMutex.Unlock(); - return b; -} -template -bool ThreadPool::Pause(void) -{ - if (WasStarted()==false) - return false; - - workingThreadCountMutex.Lock(); - while (numThreadsWorking>0) - { - RakSleep(30); - } - return true; -} -template -void ThreadPool::Resume(void) -{ - workingThreadCountMutex.Unlock(); -} - -#endif - diff --git a/vendors/mafianet/Source/include/mafianet/ThreadsafePacketLogger.h b/vendors/mafianet/Source/include/mafianet/ThreadsafePacketLogger.h deleted file mode 100644 index a191579dd..000000000 --- a/vendors/mafianet/Source/include/mafianet/ThreadsafePacketLogger.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Derivation of the packet logger to defer the call to WriteLog until the user thread. -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_PacketLogger==1 - -#ifndef __THREADSAFE_PACKET_LOGGER_H -#define __THREADSAFE_PACKET_LOGGER_H - -#include "PacketLogger.h" -#include "SingleProducerConsumer.h" - -namespace MafiaNet -{ - -/// \ingroup PACKETLOGGER_GROUP -/// \brief Same as PacketLogger, but writes output in the user thread. -class RAK_DLL_EXPORT ThreadsafePacketLogger : public PacketLogger -{ -public: - ThreadsafePacketLogger(); - virtual ~ThreadsafePacketLogger(); - - virtual void Update(void); - -protected: - virtual void AddToLog(const char *str); - - DataStructures::SingleProducerConsumer logMessages; -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/TransportInterface.h b/vendors/mafianet/Source/include/mafianet/TransportInterface.h deleted file mode 100644 index af48fd0a6..000000000 --- a/vendors/mafianet/Source/include/mafianet/TransportInterface.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Contains TransportInterface from which you can derive custom transport providers for ConsoleServer. -/// - - - -#ifndef __TRANSPORT_INTERFACE_H -#define __TRANSPORT_INTERFACE_H - -#include "types.h" -#include "Export.h" -#include "memoryoverride.h" - -#define REMOTE_MAX_TEXT_INPUT 2048 - -namespace MafiaNet -{ - -class CommandParserInterface; - - -/// \brief Defines an interface that is used to send and receive null-terminated strings. -/// \details In practice this is only used by the CommandParser system for for servers. -class RAK_DLL_EXPORT TransportInterface -{ -public: - TransportInterface() {} - virtual ~TransportInterface() {} - - /// Start the transport provider on the indicated port. - /// \param[in] port The port to start the transport provider on - /// \param[in] serverMode If true, you should allow incoming connections (I don't actually use this anywhere) - /// \return Return true on success, false on failure. - virtual bool Start(unsigned short port, bool serverMode)=0; - - /// Stop the transport provider. You can clear memory and shutdown threads here. - virtual void Stop(void)=0; - - /// Send a null-terminated string to \a systemAddress - /// If your transport method requires particular formatting of the outgoing data (e.g. you don't just send strings) you can do it here - /// and parse it out in Receive(). - /// \param[in] systemAddress The player to send the string to - /// \param[in] data format specifier - same as RAKNET_DEBUG_PRINTF - /// \param[in] ... format specification arguments - same as RAKNET_DEBUG_PRINTF - virtual void Send( SystemAddress systemAddress, const char *data, ... )=0; - - /// Disconnect \a systemAddress . The binary address and port defines the SystemAddress structure. - /// \param[in] systemAddress The player/address to disconnect - virtual void CloseConnection( SystemAddress systemAddress )=0; - - /// Return a string. The string should be allocated and written to Packet::data . - /// The byte length should be written to Packet::length . The player/address should be written to Packet::systemAddress - /// If your transport protocol adds special formatting to the data stream you should parse it out before returning it in the packet - /// and thus only return a string in Packet::data - /// \return The packet structure containing the result of Receive, or 0 if no data is available - virtual Packet* Receive( void )=0; - - /// Deallocate the Packet structure returned by Receive - /// \param[in] The packet to deallocate - virtual void DeallocatePacket( Packet *packet )=0; - - /// If a new system connects to you, you should queue that event and return the systemAddress/address of that player in this function. - /// \return The SystemAddress/address of the system - virtual SystemAddress HasNewIncomingConnection(void)=0; - - /// If a system loses the connection, you should queue that event and return the systemAddress/address of that player in this function. - /// \return The SystemAddress/address of the system - virtual SystemAddress HasLostConnection(void)=0; - - /// Your transport provider can itself have command parsers if the transport layer has user-modifiable features - /// For example, your transport layer may have a password which you want remote users to be able to set or you may want - /// to allow remote users to turn on or off command echo - /// \return 0 if you do not need a command parser - otherwise the desired derivation of CommandParserInterface - virtual CommandParserInterface* GetCommandParser(void)=0; -protected: -}; - -} // namespace MafiaNet - -#endif - diff --git a/vendors/mafianet/Source/include/mafianet/TwoWayAuthentication.h b/vendors/mafianet/Source/include/mafianet/TwoWayAuthentication.h deleted file mode 100644 index 95f2df267..000000000 --- a/vendors/mafianet/Source/include/mafianet/TwoWayAuthentication.h +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file TwoWayAuthentication.h -/// \brief Implements two way authentication -/// \details Given two systems, each of whom known a common password, verify the password without transmitting it -/// This can be used to determine what permissions are should be allowed to the other system -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_TwoWayAuthentication==1 - -#ifndef __TWO_WAY_AUTHENTICATION_H -#define __TWO_WAY_AUTHENTICATION_H - -// How often to change the nonce. -#define NONCE_TIMEOUT_MS 10000 -// How often to check for ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT, and the minimum timeout time. Maximum is double this value. -#define CHALLENGE_MINIMUM_TIMEOUT 3000 - -#if LIBCAT_SECURITY==1 -// From CPP FILE: -// static const int HASH_BITS = 256; -// static const int HASH_BYTES = HASH_BITS / 8; -// static const int STRENGTHENING_FACTOR = 1000; -#define TWO_WAY_AUTHENTICATION_NONCE_LENGTH 32 -#define HASHED_NONCE_AND_PW_LENGTH 32 -#else -#include "DR_SHA1.h" -#define TWO_WAY_AUTHENTICATION_NONCE_LENGTH 20 -#define HASHED_NONCE_AND_PW_LENGTH SHA1_LENGTH -#endif - -#include "PluginInterface2.h" -#include "memoryoverride.h" -#include "NativeTypes.h" -#include "string.h" -#include "DS_Hash.h" -#include "DS_Queue.h" - -typedef int64_t FCM2Guid; - -namespace MafiaNet -{ -/// Forward declarations -class RakPeerInterface; - -/// \brief Implements two way authentication -/// \details Given two systems, each of whom known a common password / identifier pair, verify the password without transmitting it -/// This can be used to determine what permissions are should be allowed to the other system -/// If the other system should not send any data until authentication passes, you can use the MessageFilter plugin for this. Call MessageFilter::SetAllowMessageID() including ID_TWO_WAY_AUTHENTICATION_NEGOTIATION when doing so. Also attach MessageFilter first in the list of plugins -/// \note If other systems challenges us, and fails, you will get ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_FAILED. -/// \ingroup PLUGINS_GROUP -class RAK_DLL_EXPORT TwoWayAuthentication : public PluginInterface2 -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(TwoWayAuthentication) - - TwoWayAuthentication(); - virtual ~TwoWayAuthentication(); - - /// \brief Adds a password to the list of passwords the system will accept - /// \details Each password, which is secret and not transmitted, is identified by \a identifier. - /// \a identifier is transmitted in plaintext with the request. It is only needed because the system supports multiple password. - /// It is used to only hash against once password on the remote system, rather than having to hash against every known password. - /// \param[in] identifier A unique identifier representing this password. This is transmitted in plaintext and should be considered insecure - /// \param[in] password The password to add - /// \return True on success, false on identifier==password, either identifier or password is blank, or identifier is already in use - bool AddPassword(MafiaNet::RakString identifier, MafiaNet::RakString password); - - /// \brief Challenge another system for the specified identifier - /// \details After calling Challenge, you will get back ID_TWO_WAY_AUTHENTICATION_SUCCESS, ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT, or ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_FAILED - /// ID_TWO_WAY_AUTHENTICATION_SUCCESS will be returned if and only if the other system has called AddPassword() with the same identifier\password pair as this system. - /// \param[in] identifier A unique identifier representing this password. This is transmitted in plaintext and should be considered insecure - /// \return True on success, false on remote system not connected, or identifier not previously added with AddPassword() - bool Challenge(MafiaNet::RakString identifier, AddressOrGUID remoteSystem); - - /// \brief Free all memory - void Clear(void); - - /// \internal - virtual void Update(void); - /// \internal - virtual PluginReceiveResult OnReceive(Packet *packet); - /// \internal - virtual void OnRakPeerShutdown(void); - /// \internal - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - - /// \internal - struct PendingChallenge - { - MafiaNet::RakString identifier; - AddressOrGUID remoteSystem; - MafiaNet::Time time; - bool sentHash; - }; - - DataStructures::Queue outgoingChallenges; - - /// \internal - struct NonceAndRemoteSystemRequest - { - char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH]; - MafiaNet::AddressOrGUID remoteSystem; - unsigned short requestId; - MafiaNet::Time whenGenerated; - }; - /// \internal - struct RAK_DLL_EXPORT NonceGenerator - { - NonceGenerator(); - ~NonceGenerator(); - void GetNonce(char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH], unsigned short *requestId, MafiaNet::AddressOrGUID remoteSystem); - void GenerateNonce(char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH]); - bool GetNonceById(char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH], unsigned short requestId, MafiaNet::AddressOrGUID remoteSystem, bool popIfFound); - void Clear(void); - void ClearByAddress(MafiaNet::AddressOrGUID remoteSystem); - void Update(MafiaNet::Time curTime); - - DataStructures::List generatedNonces; - unsigned short nextRequestId; - }; - -protected: - void PushToUser(MessageID messageId, MafiaNet::RakString password, MafiaNet::AddressOrGUID remoteSystem); - // Key is identifier, data is password - DataStructures::Hash passwords; - - MafiaNet::Time whenLastTimeoutCheck; - - NonceGenerator nonceGenerator; - - void OnNonceRequest(Packet *packet); - void OnNonceReply(Packet *packet); - PluginReceiveResult OnHashedNonceAndPassword(Packet *packet); - void OnPasswordResult(Packet *packet); - void Hash(char thierNonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH], MafiaNet::RakString password, char out[HASHED_NONCE_AND_PW_LENGTH]); -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/UDPForwarder.h b/vendors/mafianet/Source/include/mafianet/UDPForwarder.h deleted file mode 100644 index 6e0914764..000000000 --- a/vendors/mafianet/Source/include/mafianet/UDPForwarder.h +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Forwards UDP datagrams. Independent of RakNet's protocol. -/// - - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_UDPForwarder==1 - -#ifndef __UDP_FORWARDER_H -#define __UDP_FORWARDER_H - -#include "Export.h" -#include "types.h" -#include "SocketIncludes.h" -#include "UDPProxyCommon.h" -#include "SimpleMutex.h" -#include "string.h" -#include "thread.h" -#include "DS_Queue.h" -#include "DS_OrderedList.h" -#include "LocklessTypes.h" -#include "DS_ThreadsafeAllocatingQueue.h" - -namespace MafiaNet -{ - -enum UDPForwarderResult -{ - UDPFORWARDER_FORWARDING_ALREADY_EXISTS, - UDPFORWARDER_NO_SOCKETS, - UDPFORWARDER_BIND_FAILED, - UDPFORWARDER_INVALID_PARAMETERS, - UDPFORWARDER_NOT_RUNNING, - UDPFORWARDER_SUCCESS, - UDPFORWARDER_RESULT_COUNT -}; - -/// \brief Forwards UDP datagrams. Independent of RakNet's protocol. -/// \ingroup NAT_PUNCHTHROUGH_GROUP -class RAK_DLL_EXPORT UDPForwarder -{ -public: - UDPForwarder(); - virtual ~UDPForwarder(); - - /// Starts the system. - /// Required to call before StartForwarding - void Startup(void); - - /// Stops the system, and frees all sockets - void Shutdown(void); - - /// Sets the maximum number of forwarding entries allowed - /// Set according to your available bandwidth and the estimated average bandwidth per forwarded address. - /// \param[in] maxEntries The maximum number of simultaneous forwarding entries. Defaults to 64 (32 connections) - void SetMaxForwardEntries(unsigned short maxEntries); - - /// \return The \a maxEntries parameter passed to SetMaxForwardEntries(), or the default if it was never called - int GetMaxForwardEntries(void) const; - - /// \return How many entries have been used - int GetUsedForwardEntries(void) const; - - /// Forwards datagrams from source to destination, and vice-versa - /// Does nothing if this forward entry already exists via a previous call - /// \pre Call Startup() - /// \note RakNet's protocol will ensure a message is sent at least every 15 seconds, so if routing RakNet messages, it is a reasonable value for timeoutOnNoDataMS, plus an some extra seconds for latency - /// \param[in] source The source IP and port - /// \param[in] destination Where to forward to (and vice-versa) - /// \param[in] timeoutOnNoDataMS If no messages are forwarded for this many MS, then automatically remove this entry. - /// \param[in] forceHostAddress Force binding on a particular address. 0 to use any. - /// \param[in] socketFamily IP version: For IPV4, use AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC. - /// \param[out] forwardingPort New opened port for forwarding - /// \param[out] forwardingSocket New opened socket for forwarding - /// \return UDPForwarderResult - UDPForwarderResult StartForwarding( - SystemAddress source, SystemAddress destination, MafiaNet::TimeMS timeoutOnNoDataMS, - const char *forceHostAddress, unsigned short socketFamily, - unsigned short *forwardingPort, __UDPSOCKET__ *forwardingSocket); - - /// No longer forward datagrams from source to destination - /// \param[in] source The source IP and port - /// \param[in] destination Where to forward to - void StopForwarding(SystemAddress source, SystemAddress destination); - - - struct ForwardEntry - { - ForwardEntry(); - ~ForwardEntry(); - SystemAddress addr1Unconfirmed, addr2Unconfirmed, addr1Confirmed, addr2Confirmed; - MafiaNet::TimeMS timeLastDatagramForwarded; - __UDPSOCKET__ socket; - MafiaNet::TimeMS timeoutOnNoDataMS; - short socketFamily; - }; - - -protected: - friend RAK_THREAD_DECLARATION(UpdateUDPForwarderGlobal); - - void UpdateUDPForwarder(void); - void RecvFrom(MafiaNet::TimeMS curTime, ForwardEntry *forwardEntry); - - struct StartForwardingInputStruct - { - SystemAddress source; - SystemAddress destination; - MafiaNet::TimeMS timeoutOnNoDataMS; - RakString forceHostAddress; - unsigned short socketFamily; - unsigned int inputId; - }; - - DataStructures::ThreadsafeAllocatingQueue startForwardingInput; - - struct StartForwardingOutputStruct - { - unsigned short forwardingPort; - __UDPSOCKET__ forwardingSocket; - UDPForwarderResult result; - unsigned int inputId; - }; - DataStructures::Queue startForwardingOutput; - SimpleMutex startForwardingOutputMutex; - - struct StopForwardingStruct - { - SystemAddress source; - SystemAddress destination; - }; - DataStructures::ThreadsafeAllocatingQueue stopForwardingCommands; - unsigned int nextInputId; - - // New entries are added to forwardListNotUpdated - DataStructures::List forwardListNotUpdated; -// SimpleMutex forwardListNotUpdatedMutex; - - unsigned short maxForwardEntries; - MafiaNet::LocklessUint32_t isRunning, threadRunning; - -}; - -} // End namespace - -#endif - -#endif // #if _RAKNET_SUPPORT_UDPForwarder==1 diff --git a/vendors/mafianet/Source/include/mafianet/UDPProxyClient.h b/vendors/mafianet/Source/include/mafianet/UDPProxyClient.h deleted file mode 100644 index 7bd5b2cfc..000000000 --- a/vendors/mafianet/Source/include/mafianet/UDPProxyClient.h +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief A RakNet plugin performing networking to communicate with UDPProxyCoordinator. Ultimately used to tell UDPProxyServer to forward UDP packets. - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_UDPProxyClient==1 - -#ifndef __UDP_PROXY_CLIENT_H -#define __UDP_PROXY_CLIENT_H - -#include "Export.h" -#include "types.h" -#include "PluginInterface2.h" -#include "DS_List.h" - -/// \defgroup UDP_PROXY_GROUP UDPProxy -/// \brief Forwards UDP datagrams from one system to another. Protocol independent -/// \details Used when NatPunchthroughClient fails -/// \ingroup PLUGINS_GROUP - -namespace MafiaNet -{ -class UDPProxyClient; - -/// Callback to handle results of calling UDPProxyClient::RequestForwarding() -/// \ingroup UDP_PROXY_GROUP -struct UDPProxyClientResultHandler -{ - UDPProxyClientResultHandler() {} - virtual ~UDPProxyClientResultHandler() {} - - /// Called when our forwarding request was completed. We can now connect to \a targetAddress by using \a proxyAddress instead - /// \param[out] proxyIPAddress IP Address of the proxy server, which will forward messages to targetAddress - /// \param[out] proxyPort Remote port to use on the proxy server, which will forward messages to targetAddress - /// \param[out] proxyCoordinator \a proxyCoordinator parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] sourceAddress \a sourceAddress parameter passed to UDPProxyClient::RequestForwarding. If it was UNASSIGNED_SYSTEM_ADDRESS, it is now our external IP address. - /// \param[out] targetAddress \a targetAddress parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] targetGuid \a targetGuid parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] proxyClient The plugin that is calling this callback - virtual void OnForwardingSuccess(const char *proxyIPAddress, unsigned short proxyPort, - SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, MafiaNet::UDPProxyClient *proxyClientPlugin)=0; - - /// Called when another system has setup forwarding, with our system as the target address. - /// Plugin automatically sends a datagram to proxyIPAddress before this callback, to open our router if necessary. - /// \param[out] proxyIPAddress IP Address of the proxy server, which will forward messages to targetAddress - /// \param[out] proxyPort Remote port to use on the proxy server, which will forward messages to targetAddress - /// \param[out] proxyCoordinator \a proxyCoordinator parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] sourceAddress \a sourceAddress parameter passed to UDPProxyClient::RequestForwarding. This is originating source IP address of the remote system that will be sending to us. - /// \param[out] targetAddress \a targetAddress parameter originally passed to UDPProxyClient::RequestForwarding. This is our external IP address. - /// \param[out] targetGuid \a targetGuid parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] proxyClient The plugin that is calling this callback - virtual void OnForwardingNotification(const char *proxyIPAddress, unsigned short proxyPort, - SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, MafiaNet::UDPProxyClient *proxyClientPlugin)=0; - - /// Called when our forwarding request failed, because no UDPProxyServers are connected to UDPProxyCoordinator - /// \param[out] proxyCoordinator \a proxyCoordinator parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] sourceAddress \a sourceAddress parameter passed to UDPProxyClient::RequestForwarding. If it was UNASSIGNED_SYSTEM_ADDRESS, it is now our external IP address. - /// \param[out] targetAddress \a targetAddress parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] targetGuid \a targetGuid parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] proxyClient The plugin that is calling this callback - virtual void OnNoServersOnline(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, MafiaNet::UDPProxyClient *proxyClientPlugin)=0; - - /// Called when our forwarding request failed, because no UDPProxyServers are connected to UDPProxyCoordinator - /// \param[out] proxyCoordinator \a proxyCoordinator parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] sourceAddress \a sourceAddress parameter passed to UDPProxyClient::RequestForwarding. If it was UNASSIGNED_SYSTEM_ADDRESS, it is now our external IP address. - /// \param[out] targetAddress \a targetAddress parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] targetGuid \a targetGuid parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] proxyClient The plugin that is calling this callback - virtual void OnRecipientNotConnected(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, MafiaNet::UDPProxyClient *proxyClientPlugin)=0; - - /// Called when our forwarding request failed, because all UDPProxyServers that are connected to UDPProxyCoordinator are at their capacity - /// Either add more servers, or increase capacity via UDPForwarder::SetMaxForwardEntries() - /// \param[out] proxyCoordinator \a proxyCoordinator parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] sourceAddress \a sourceAddress parameter passed to UDPProxyClient::RequestForwarding. If it was UNASSIGNED_SYSTEM_ADDRESS, it is now our external IP address. - /// \param[out] targetAddress \a targetAddress parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] targetGuid \a targetGuid parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] proxyClient The plugin that is calling this callback - virtual void OnAllServersBusy(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, MafiaNet::UDPProxyClient *proxyClientPlugin)=0; - - /// Called when our forwarding request is already in progress on the \a proxyCoordinator. - /// This can be ignored, but indicates an unneeded second request - /// \param[out] proxyIPAddress IP Address of the proxy server, which is forwarding messages to targetAddress - /// \param[out] proxyPort Remote port to use on the proxy server, which is forwarding messages to targetAddress - /// \param[out] proxyCoordinator \a proxyCoordinator parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] sourceAddress \a sourceAddress parameter passed to UDPProxyClient::RequestForwarding. If it was UNASSIGNED_SYSTEM_ADDRESS, it is now our external IP address. - /// \param[out] targetAddress \a targetAddress parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] targetGuid \a targetGuid parameter originally passed to UDPProxyClient::RequestForwarding - /// \param[out] proxyClient The plugin that is calling this callback - virtual void OnForwardingInProgress(const char *proxyIPAddress, unsigned short proxyPort, SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, MafiaNet::UDPProxyClient *proxyClientPlugin)=0; -}; - - -/// \brief Communicates with UDPProxyCoordinator, in order to find a UDPProxyServer to forward our datagrams. -/// \details When NAT Punchthrough fails, it is possible to use a non-NAT system to forward messages from us to the recipient, and vice-versa.
    -/// The class to forward messages is UDPForwarder, and it is triggered over the network via the UDPProxyServer plugin.
    -/// The UDPProxyClient connects to UDPProxyCoordinator to get a list of servers running UDPProxyServer, and the coordinator will relay our forwarding request -/// \sa NatPunchthroughServer -/// \sa NatPunchthroughClient -/// \ingroup UDP_PROXY_GROUP -class RAK_DLL_EXPORT UDPProxyClient : public PluginInterface2 -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(UDPProxyClient) - - UDPProxyClient(); - ~UDPProxyClient(); - - /// Receives the results of calling RequestForwarding() - /// Set before calling RequestForwarding or you won't know what happened - /// \param[in] resultHandler - void SetResultHandler(UDPProxyClientResultHandler *rh); - - /// Sends a request to proxyCoordinator to find a server and have that server setup UDPForwarder::StartForwarding() on our address to \a targetAddressAsSeenFromCoordinator - /// The forwarded datagrams can be from any UDP source, not just RakNet - /// \pre Must be connected to \a proxyCoordinator - /// \pre Systems running UDPProxyServer must be connected to \a proxyCoordinator and logged in via UDPProxyCoordinator::LoginServer() or UDPProxyServer::LoginToCoordinator() - /// \note May still fail, if all proxy servers have no open connections. - /// \note RakNet's protocol will ensure a message is sent at least every 5 seconds, so if routing RakNet messages, it is a reasonable value for timeoutOnNoDataMS, plus an extra few seconds for latency. - /// \param[in] proxyCoordinator System we are connected to that is running the UDPProxyCoordinator plugin - /// \param[in] sourceAddress External IP address of the system we want to forward messages from. This does not have to be our own system. To specify our own system, you can pass UNASSIGNED_SYSTEM_ADDRESS which the coordinator will treat as our external IP address. - /// \param[in] targetAddressAsSeenFromCoordinator External IP address of the system we want to forward messages to. If this system is connected to UDPProxyCoordinator at this address using RakNet, that system will ping the server and thus open the router for incoming communication. In any other case, you are responsible for doing your own network communication to have that system ping the server. See also targetGuid in the other version of RequestForwarding(), to avoid the need to know the IP address to the coordinator of the destination. - /// \param[in] timeoutOnNoData If no data is sent by the forwarded systems, how long before removing the forward entry from UDPForwarder? UDP_FORWARDER_MAXIMUM_TIMEOUT is the maximum value. Recommended 10 seconds. - /// \param[in] serverSelectionBitstream If you want to send data to UDPProxyCoordinator::GetBestServer(), write it here - /// \return true if the request was sent, false if we are not connected to proxyCoordinator - bool RequestForwarding(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddressAsSeenFromCoordinator, MafiaNet::TimeMS timeoutOnNoDataMS, MafiaNet::BitStream *serverSelectionBitstream=0); - - /// Same as above, but specify the target with a GUID, in case you don't know what its address is to the coordinator - /// If requesting forwarding to a RakNet enabled system, then it is easier to use targetGuid instead of targetAddressAsSeenFromCoordinator - bool RequestForwarding(SystemAddress proxyCoordinator, SystemAddress sourceAddress, RakNetGUID targetGuid, MafiaNet::TimeMS timeoutOnNoDataMS, MafiaNet::BitStream *serverSelectionBitstream=0); - - /// \internal - virtual void Update(void); - virtual PluginReceiveResult OnReceive(Packet *packet); - virtual void OnRakPeerShutdown(void); - - struct ServerWithPing - { - unsigned short ping; - SystemAddress serverAddress; - }; - struct SenderAndTargetAddress - { - SystemAddress senderClientAddress; - SystemAddress targetClientAddress; - }; - struct PingServerGroup - { - SenderAndTargetAddress sata; - MafiaNet::TimeMS startPingTime; - SystemAddress coordinatorAddressForPings; - //DataStructures::Multilist serversToPing; - DataStructures::List serversToPing; - bool AreAllServersPinged(void) const; - void SendPingedServersToCoordinator(RakPeerInterface *rakPeer); - }; - //DataStructures::Multilist pingServerGroups; - DataStructures::List pingServerGroups; -protected: - - void OnPingServers(Packet *packet); - void Clear(void); - UDPProxyClientResultHandler *resultHandler; - -}; - -} // End namespace - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/UDPProxyCommon.h b/vendors/mafianet/Source/include/mafianet/UDPProxyCommon.h deleted file mode 100644 index d1f7f1016..000000000 --- a/vendors/mafianet/Source/include/mafianet/UDPProxyCommon.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -#ifndef __UDP_PROXY_COMMON_H -#define __UDP_PROXY_COMMON_H - -// System flow: -/* -UDPProxyClient: End user -UDPProxyServer: open server, to route messages from end users that can't connect to each other using UDPForwarder class. -UDPProxyCoordinator: Server somewhere, connected to by RakNet, to maintain a list of UDPProxyServer - -UDPProxyServer - On startup, log into UDPProxyCoordinator and register self - -UDPProxyClient - Wish to open route to X - Send message to UDPProxyCoordinator containing X, desired timeout - Wait for success or failure - -UDPProxyCoordinator: -* Get openRouteRequest - If no servers registered, return failure - Add entry to memory - chooseBestUDPProxyServer() (overridable, chooses at random by default) - Query this server to StartForwarding(). Return success or failure - If failure, choose another server from the remaining list. If none remaining, return failure. Else return success. -* Disconnect: - If disconnected system is pending client on openRouteRequest, delete that request - If disconnected system is UDPProxyServer, remove from list. For each pending client for this server, choose from remaining servers. -* Login: - Add to UDPProxyServer list, validating password if set -*/ - -// Stored in the second byte after ID_UDP_PROXY_GENERAL -// Otherwise MessageIdentifiers.h is too cluttered and will hit the limit on enumerations in a single byte -enum UDPProxyMessages -{ - ID_UDP_PROXY_FORWARDING_SUCCEEDED, - ID_UDP_PROXY_FORWARDING_NOTIFICATION, - ID_UDP_PROXY_NO_SERVERS_ONLINE, - ID_UDP_PROXY_RECIPIENT_GUID_NOT_CONNECTED_TO_COORDINATOR, - ID_UDP_PROXY_ALL_SERVERS_BUSY, - ID_UDP_PROXY_IN_PROGRESS, - ID_UDP_PROXY_FORWARDING_REQUEST_FROM_CLIENT_TO_COORDINATOR, - ID_UDP_PROXY_PING_SERVERS_FROM_COORDINATOR_TO_CLIENT, - ID_UDP_PROXY_PING_SERVERS_REPLY_FROM_CLIENT_TO_COORDINATOR, - ID_UDP_PROXY_FORWARDING_REQUEST_FROM_COORDINATOR_TO_SERVER, - ID_UDP_PROXY_FORWARDING_REPLY_FROM_SERVER_TO_COORDINATOR, - ID_UDP_PROXY_LOGIN_REQUEST_FROM_SERVER_TO_COORDINATOR, - ID_UDP_PROXY_LOGIN_SUCCESS_FROM_COORDINATOR_TO_SERVER, - ID_UDP_PROXY_ALREADY_LOGGED_IN_FROM_COORDINATOR_TO_SERVER, - ID_UDP_PROXY_NO_PASSWORD_SET_FROM_COORDINATOR_TO_SERVER, - ID_UDP_PROXY_WRONG_PASSWORD_FROM_COORDINATOR_TO_SERVER -}; - - -#define UDP_FORWARDER_MAXIMUM_TIMEOUT (60000 * 10) - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/UDPProxyCoordinator.h b/vendors/mafianet/Source/include/mafianet/UDPProxyCoordinator.h deleted file mode 100644 index 12148e710..000000000 --- a/vendors/mafianet/Source/include/mafianet/UDPProxyCoordinator.h +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Essentially maintains a list of servers running UDPProxyServer, and some state management for UDPProxyClient to find a free server to forward datagrams -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_UDPProxyCoordinator==1 && _RAKNET_SUPPORT_UDPForwarder==1 - -#ifndef __UDP_PROXY_COORDINATOR_H -#define __UDP_PROXY_COORDINATOR_H - -#include "Export.h" -#include "types.h" -#include "PluginInterface2.h" -#include "string.h" -#include "BitStream.h" -#include "DS_Queue.h" -#include "DS_OrderedList.h" - -namespace MafiaNet -{ - /// When NAT Punchthrough fails, it is possible to use a non-NAT system to forward messages from us to the recipient, and vice-versa - /// The class to forward messages is UDPForwarder, and it is triggered over the network via the UDPProxyServer plugin. - /// The UDPProxyClient connects to UDPProxyCoordinator to get a list of servers running UDPProxyServer, and the coordinator will relay our forwarding request - /// \brief Middleman between UDPProxyServer and UDPProxyClient, maintaining a list of UDPProxyServer, and managing state for clients to find an available forwarding server. - /// \ingroup NAT_PUNCHTHROUGH_GROUP - class RAK_DLL_EXPORT UDPProxyCoordinator : public PluginInterface2 - { - public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(UDPProxyCoordinator) - - UDPProxyCoordinator(); - virtual ~UDPProxyCoordinator(); - - /// For UDPProxyServers logging in remotely, they must pass a password to UDPProxyServer::LoginToCoordinator(). It must match the password set here. - /// If no password is set, they cannot login remotely. - /// By default, no password is set - void SetRemoteLoginPassword(MafiaNet::RakString password); - - /// \internal - virtual void Update(void); - virtual PluginReceiveResult OnReceive(Packet *packet); - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - - struct SenderAndTargetAddress - { - SystemAddress senderClientAddress; - RakNetGUID senderClientGuid; - SystemAddress targetClientAddress; - RakNetGUID targetClientGuid; - }; - - struct ServerWithPing - { - unsigned short ping; - SystemAddress serverAddress; - }; - - struct ForwardingRequest - { - MafiaNet::TimeMS timeoutOnNoDataMS; - MafiaNet::TimeMS timeoutAfterSuccess; - SenderAndTargetAddress sata; - SystemAddress requestingAddress; // Which system originally sent the network message to start forwarding - SystemAddress currentlyAttemptedServerAddress; - DataStructures::Queue remainingServersToTry; - MafiaNet::BitStream serverSelectionBitstream; - - DataStructures::List sourceServerPings, targetServerPings; - MafiaNet::TimeMS timeRequestedPings; - // Order based on sourceServerPings and targetServerPings - void OrderRemainingServersToTry(void); - - }; - protected: - - static int ServerWithPingComp( const unsigned short &key, const UDPProxyCoordinator::ServerWithPing &data ); - static int ForwardingRequestComp( const SenderAndTargetAddress &key, ForwardingRequest* const &data); - - void OnForwardingRequestFromClientToCoordinator(Packet *packet); - void OnLoginRequestFromServerToCoordinator(Packet *packet); - void OnForwardingReplyFromServerToCoordinator(Packet *packet); - void OnPingServersReplyFromClientToCoordinator(Packet *packet); - void TryNextServer(SenderAndTargetAddress sata, ForwardingRequest *fw); - void SendAllBusy(SystemAddress senderClientAddress, SystemAddress targetClientAddress, RakNetGUID targetClientGuid, SystemAddress requestingAddress); - void Clear(void); - - void SendForwardingRequest(SystemAddress sourceAddress, SystemAddress targetAddress, SystemAddress serverAddress, MafiaNet::TimeMS timeoutOnNoDataMS); - - // Logged in servers - //DataStructures::Multilist serverList; - DataStructures::List serverList; - - // Forwarding requests in progress - //DataStructures::Multilist forwardingRequestList; - DataStructures::OrderedList forwardingRequestList; - - MafiaNet::RakString remoteLoginPassword; - - }; - -} // End namespace - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/UDPProxyServer.h b/vendors/mafianet/Source/include/mafianet/UDPProxyServer.h deleted file mode 100644 index fbb70af87..000000000 --- a/vendors/mafianet/Source/include/mafianet/UDPProxyServer.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief A RakNet plugin performing networking to communicate with UDPProxyServer. It allows UDPProxyServer to control our instance of UDPForwarder. -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_UDPProxyServer==1 && _RAKNET_SUPPORT_UDPForwarder==1 - -#ifndef __UDP_PROXY_SERVER_H -#define __UDP_PROXY_SERVER_H - -#include "Export.h" -#include "types.h" -#include "PluginInterface2.h" -#include "UDPForwarder.h" -#include "string.h" - -namespace MafiaNet -{ -class UDPProxyServer; - -/// Callback to handle results of calling UDPProxyServer::LoginToCoordinator() -/// \ingroup UDP_PROXY_GROUP -struct UDPProxyServerResultHandler -{ - UDPProxyServerResultHandler() {} - virtual ~UDPProxyServerResultHandler() {} - - /// Called when our login succeeds - /// \param[out] usedPassword The password we passed to UDPProxyServer::LoginToCoordinator() - /// \param[out] proxyServer The plugin calling this callback - virtual void OnLoginSuccess(MafiaNet::RakString usedPassword, MafiaNet::UDPProxyServer *proxyServerPlugin)=0; - - /// We are already logged in. - /// This login failed, but the system is operational as if it succeeded - /// \param[out] usedPassword The password we passed to UDPProxyServer::LoginToCoordinator() - /// \param[out] proxyServer The plugin calling this callback - virtual void OnAlreadyLoggedIn(MafiaNet::RakString usedPassword, MafiaNet::UDPProxyServer *proxyServerPlugin)=0; - - /// The coordinator operator forgot to call UDPProxyCoordinator::SetRemoteLoginPassword() - /// \param[out] usedPassword The password we passed to UDPProxyServer::LoginToCoordinator() - /// \param[out] proxyServer The plugin calling this callback - virtual void OnNoPasswordSet(MafiaNet::RakString usedPassword, MafiaNet::UDPProxyServer *proxyServerPlugin)=0; - - /// The coordinator operator set a different password in UDPProxyCoordinator::SetRemoteLoginPassword() than what we passed - /// \param[out] usedPassword The password we passed to UDPProxyServer::LoginToCoordinator() - /// \param[out] proxyServer The plugin calling this callback - virtual void OnWrongPassword(MafiaNet::RakString usedPassword, MafiaNet::UDPProxyServer *proxyServerPlugin)=0; -}; - -/// \brief UDPProxyServer to control our instance of UDPForwarder -/// \details When NAT Punchthrough fails, it is possible to use a non-NAT system to forward messages from us to the recipient, and vice-versa.
    -/// The class to forward messages is UDPForwarder, and it is triggered over the network via the UDPProxyServer plugin.
    -/// The UDPProxyServer connects to UDPProxyServer to get a list of servers running UDPProxyServer, and the coordinator will relay our forwarding request. -/// \ingroup UDP_PROXY_GROUP -class RAK_DLL_EXPORT UDPProxyServer : public PluginInterface2 -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(UDPProxyServer) - - UDPProxyServer(); - ~UDPProxyServer(); - - /// Sets the socket family to use, either IPV4 or IPV6 - /// \param[in] socketFamily For IPV4, use AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC. - void SetSocketFamily(unsigned short _socketFamily); - - /// Receives the results of calling LoginToCoordinator() - /// Set before calling LoginToCoordinator or you won't know what happened - /// \param[in] resultHandler - void SetResultHandler(UDPProxyServerResultHandler *rh); - - /// Before the coordinator will register the UDPProxyServer, you must login - /// \pre Must be connected to the coordinator - /// \pre Coordinator must have set a password with UDPProxyCoordinator::SetRemoteLoginPassword() - /// \returns false if already logged in, or logging in. Returns true otherwise - bool LoginToCoordinator(MafiaNet::RakString password, SystemAddress coordinatorAddress); - - /// \brief The server IP reported to the client is the IP address from the server to the coordinator. - /// If the server and coordinator are on the same LAN, you need to call SetServerPublicIP() to tell the client what address to connect to - /// \param[in] ip IP address to report in UDPProxyClientResultHandler::OnForwardingSuccess() and UDPProxyClientResultHandler::OnForwardingNotification() as proxyIPAddress - void SetServerPublicIP(RakString ip); - - /// Operative class that performs the forwarding - /// Exposed so you can call UDPForwarder::SetMaxForwardEntries() if you want to change away from the default - /// UDPForwarder::Startup(), UDPForwarder::Shutdown(), and UDPForwarder::Update() are called automatically by the plugin - UDPForwarder udpForwarder; - - virtual void OnAttach(void); - virtual void OnDetach(void); - - /// \internal - virtual void Update(void); - virtual PluginReceiveResult OnReceive(Packet *packet); - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - virtual void OnRakPeerStartup(void); - virtual void OnRakPeerShutdown(void); - -protected: - void OnForwardingRequestFromCoordinatorToServer(Packet *packet); - - DataStructures::OrderedList loggingInCoordinators; - DataStructures::OrderedList loggedInCoordinators; - - UDPProxyServerResultHandler *resultHandler; - unsigned short socketFamily; - RakString serverPublicIp; - -}; - -} // End namespace - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/VariableDeltaSerializer.h b/vendors/mafianet/Source/include/mafianet/VariableDeltaSerializer.h deleted file mode 100644 index d1823783d..000000000 --- a/vendors/mafianet/Source/include/mafianet/VariableDeltaSerializer.h +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __VARIABLE_DELTA_SERIALIZER_H -#define __VARIABLE_DELTA_SERIALIZER_H - -#include "VariableListDeltaTracker.h" -#include "DS_MemoryPool.h" -#include "NativeTypes.h" -#include "BitStream.h" -#include "PacketPriority.h" -#include "DS_OrderedList.h" - -namespace MafiaNet -{ - -/// \brief Class to compare memory values of variables in a current state to a prior state -/// Results of the comparisons will be written to a bitStream, such that only changed variables get written
    -/// Can be used with ReplicaManager3 to Serialize a Replica3 per-variable, rather than comparing the entire object against itself
    -/// Usage:
    -///
    -/// 1. Call BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize(). In the case of Replica3, this would be in the Serialize() call
    -/// 2. For each variable of the type in step 1, call Serialize(). The same variables must be serialized every tick()
    -/// 3. Call EndSerialize()
    -/// 4. Repeat step 1 for each of the other categories of how to send varaibles
    -///
    -/// On the receiver:
    -///
    -/// 1. Call BeginDeserialize(). In the case of Replica3, this would be in the Deserialize() call
    -/// 2. Call DeserializeVariable() for each variable, in the same order as was Serialized()
    -/// 3. Call EndSerialize()
    -/// \sa The ReplicaManager3 sample -class RAK_DLL_EXPORT VariableDeltaSerializer -{ -protected: - struct RemoteSystemVariableHistory; - struct ChangedVariablesList; - -public: - VariableDeltaSerializer(); - ~VariableDeltaSerializer(); - - struct SerializationContext - { - SerializationContext(); - ~SerializationContext(); - - RakNetGUID guid; - BitStream *bitStream; - uint32_t rakPeerSendReceipt; - RemoteSystemVariableHistory *variableHistory; - RemoteSystemVariableHistory *variableHistoryIdentical; - RemoteSystemVariableHistory *variableHistoryUnique; - ChangedVariablesList *changedVariables; - uint32_t sendReceipt; - MafiaNet::Reliability serializationMode; - bool anyVariablesWritten; - bool newSystemSend; // Force send all, do not record - }; - - struct DeserializationContext - { - BitStream *bitStream; - }; - - /// \brief Call before doing one or more SerializeVariable calls when the data will be sent MafiaNet::Reliability::UnreliableWithAckReceipt - /// The last value of each variable will be saved per remote system. Additionally, a history of \a _sendReceipts is stored to determine what to resend on packetloss. - /// When variables are lost, they will be flagged dirty and always resent to the system that lost it - /// Disadvantages: Every variable for every remote system is copied internally, in addition to a history list of what variables changed for which \a _sendReceipt. Very memory and CPU intensive for multiple connections. - /// Advantages: When data needs to be resent by RakNet, RakNet can only resend the value it currently has. This allows the application to control the resend, sending the most recent value of the variable. The end result is that bandwidth is used more efficiently because old data is never sent. - /// \pre Upon getting ID_SND_RECEIPT_LOSS or ID_SND_RECEIPT_ACKED call OnMessageReceipt() - /// \pre AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() must be called for new and lost connections - /// \param[in] context Holds the context of this group of serialize calls. This can be a stack object just passed to the function. - /// \param[in] _guid Which system we are sending to - /// \param[in] _bitSteam Which bitStream to write to - /// \param[in] _sendReceipt Returned from RakPeer::IncrementNextSendReceipt() and passed to the Send() or SendLists() function. Identifies this update for ID_SND_RECEIPT_LOSS and ID_SND_RECEIPT_ACKED - void BeginUnreliableAckedSerialize(SerializationContext *context, RakNetGUID _guid, BitStream *_bitStream, uint32_t _sendReceipt); - - /// \brief Call before doing one or more SerializeVariable calls for data that may be sent differently to every remote system (such as an invisibility flag that only teammates can see) - /// The last value of each variable will be saved per remote system. - /// Unlike BeginUnreliableAckedSerialize(), send receipts are not necessary - /// Disadvantages: Every variable for every remote system is copied internally. Very memory and CPU intensive for multiple connections. - /// Advantages: When data is sent differently depending on the recipient, this system can make things easier to use and is as efficient as it can be. - /// \pre AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() must be called for new and lost connections - /// \param[in] context Holds the context of this group of serialize calls. This can be a stack object just passed to the function. - /// \param[in] _guid Which system we are sending to - /// \param[in] _bitSteam Which bitStream to write to - void BeginUniqueSerialize(SerializationContext *context, RakNetGUID _guid, BitStream *_bitStream); - - /// \brief Call before doing one or more SerializeVariable calls for data that is sent with the same value to every remote system (such as health, position, etc.) - /// This is the most common type of serialization, and also the most efficient - /// Disadvantages: A copy of every variable still needs to be held, although only once - /// Advantages: After the first serialization, the last serialized bitStream will be used for subsequent sends - /// \pre Call OnPreSerializeTick() before doing any calls to BeginIdenticalSerialize() for each of your objects, once per game tick - /// \param[in] context Holds the context of this group of serialize calls. This can be a stack object just passed to the function. - /// \param[in] _isFirstSerializeToThisSystem Pass true if this is the first time ever serializing to this system (the initial download). This way all variables will be written, rather than checking against prior sent values. - /// \param[in] _bitSteam Which bitStream to write to - void BeginIdenticalSerialize(SerializationContext *context, bool _isFirstSerializeToThisSystem, BitStream *_bitStream); - - /// \brief Call after BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize(), then after calling SerializeVariable() one or more times - /// \param[in] context Same context pointer passed to BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize() - void EndSerialize(SerializationContext *context); - - /// \brief Call when you receive the BitStream written by SerializeVariable(), before calling DeserializeVariable() - /// \param[in] context Holds the context of this group of deserialize calls. This can be a stack object just passed to the function. - /// \param[in] _bitStream Pass the bitStream originally passed to and written to by serialize calls - void BeginDeserialize(DeserializationContext *context, BitStream *_bitStream); - - /// \param[in] context Same context pointer passed to BeginDeserialize() - void EndDeserialize(DeserializationContext *context); - - /// BeginUnreliableAckedSerialize() and BeginUniqueSerialize() require knowledge of when connections are added and dropped - /// Call AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() to notify the system of these events - /// \param[in] _guid Which system we are sending to - void AddRemoteSystemVariableHistory(RakNetGUID guid); - - /// BeginUnreliableAckedSerialize() and BeginUniqueSerialize() require knowledge of when connections are added and dropped - /// Call AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() to notify the system of these events - /// \param[in] _guid Which system we are sending to - void RemoveRemoteSystemVariableHistory(RakNetGUID guid); - - /// BeginIdenticalSerialize() requires knowledge of when serialization has started for an object across multiple systems - /// This way it can setup the flag to do new comparisons against the last sent values, rather than just resending the last sent bitStream - /// For Replica3, overload and call this from Replica3::OnUserReplicaPreSerializeTick() - void OnPreSerializeTick(void); - - /// Call when getting ID_SND_RECEIPT_LOSS or ID_SND_RECEIPT_ACKED for a particular system - /// Example: - /// - /// uint32_t msgNumber; - /// memcpy(&msgNumber, packet->data+1, 4); - /// DataStructures::List replicaListOut; - /// replicaManager.GetReplicasCreatedByMe(replicaListOut); - /// unsigned int idx; - /// for (idx=0; idx < replicaListOut.GetSize(); idx++) - /// { - /// ((SampleReplica*)replicaListOut[idx])->NotifyReplicaOfMessageDeliveryStatus(packet->guid,msgNumber, packet->data[0]==ID_SND_RECEIPT_ACKED); - /// } - /// - /// \param[in] guid Which system we are sending to - /// \param[in] receiptId Encoded in bytes 1-4 inclusive of ID_SND_RECEIPT_LOSS and ID_SND_RECEIPT_ACKED - /// \param[in] messageArrived True for ID_SND_RECEIPT_ACKED, false otherwise - void OnMessageReceipt(RakNetGUID guid, uint32_t receiptId, bool messageArrived); - - /// Call to Serialize a variable - /// Will write to the bitSteam passed to \a context true, variableValue if the variable has changed or has never been written. Otherwise will write false. - /// \pre You have called BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize() - /// \pre Will also require calling OnPreSerializeTick() if using BeginIdenticalSerialize() - /// \note Be sure to call EndSerialize() after finishing all serializations - /// \param[in] context Same context pointer passed to BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize() - /// \param[in] variable A variable to write to the bitStream passed to \a context - template - void SerializeVariable(SerializationContext *context, const VarType &variable) - { - if (context->newSystemSend) - { - if (context->variableHistory->variableListDeltaTracker.IsPastEndOfList()==false) - { - // previously sent data to another system - context->bitStream->Write(true); - context->bitStream->Write(variable); - context->anyVariablesWritten=true; - } - else - { - // never sent data to another system - context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream); - context->anyVariablesWritten=true; - } - } - else if (context->serializationMode==MafiaNet::Reliability::UnreliableWithAckReceipt) - { - context->anyVariablesWritten|= - context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream, context->changedVariables->bitField, context->changedVariables->bitWriteIndex++); - } - else - { - if (context->variableHistoryIdentical) - { - // Identical serialization to a number of systems - if (didComparisonThisTick==false) - context->anyVariablesWritten|= - context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream); - // Else bitstream is written to at the end - } - else - { - // Per-system serialization - context->anyVariablesWritten|= - context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream); - } - } - } - - /// Call to deserialize into a variable - /// \pre You have called BeginDeserialize() - /// \note Be sure to call EndDeserialize() after finishing all deserializations - /// \param[in] context Same context pointer passed to BeginDeserialize() - /// \param[in] variable A variable to write to the bitStream passed to \a context - template - bool DeserializeVariable(DeserializationContext *context, VarType &variable) - { - return VariableListDeltaTracker::ReadVarFromBitstream(variable, context->bitStream); - } - - - -protected: - - // For a given send receipt from RakPeer::Send() track which variables we updated - // That way if that send does not arrive (ID_SND_RECEIPT_LOSS) we can mark those variables as dirty to resend them with current values - struct ChangedVariablesList - { - uint32_t sendReceipt; - unsigned short bitWriteIndex; - unsigned char bitField[56]; - }; - - // static int Replica2ObjectComp( const uint32_t &key, ChangedVariablesList* const &data ); - - static int UpdatedVariablesListPtrComp( const uint32_t &key, ChangedVariablesList* const &data ); - - // For each remote system, track the last values of variables we sent to them, and the history of what values changed per call to Send() - // Every serialize if a variable changes from its last value, send it out again - // Also if a send does not arrive (ID_SND_RECEIPT_LOSS) we use updatedVariablesHistory to mark those variables as dirty, to resend them unreliably with the current values - struct RemoteSystemVariableHistory - { - RakNetGUID guid; - VariableListDeltaTracker variableListDeltaTracker; - DataStructures::OrderedList updatedVariablesHistory; - }; - /// A list of RemoteSystemVariableHistory indexed by guid, one per connection that we serialize to - /// List is added to when SerializeConstruction is called, and removed from when SerializeDestruction is called, or when a given connection is dropped - DataStructures::List remoteSystemVariableHistoryList; - - // Because the ChangedVariablesList is created every serialize and destroyed every receipt I use a pool to avoid fragmentation - DataStructures::MemoryPool updatedVariablesMemoryPool; - - bool didComparisonThisTick; - MafiaNet::BitStream identicalSerializationBs; - - void FreeVarsAssociatedWithReceipt(RakNetGUID guid, uint32_t receiptId); - void DirtyAndFreeVarsAssociatedWithReceipt(RakNetGUID guid, uint32_t receiptId); - unsigned int GetVarsWrittenPerRemoteSystemListIndex(RakNetGUID guid); - void RemoveRemoteSystemVariableHistory(void); - - RemoteSystemVariableHistory* GetRemoteSystemVariableHistory(RakNetGUID guid); - - ChangedVariablesList *AllocChangedVariablesList(void); - void FreeChangedVariablesList(ChangedVariablesList *changedVariables); - void StoreChangedVariablesList(RemoteSystemVariableHistory *variableHistory, ChangedVariablesList *changedVariables, uint32_t sendReceipt); - - RemoteSystemVariableHistory *StartVariableHistoryWrite(RakNetGUID guid); - unsigned int GetRemoteSystemHistoryListIndex(RakNetGUID guid); - -}; - -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/VariableListDeltaTracker.h b/vendors/mafianet/Source/include/mafianet/VariableListDeltaTracker.h deleted file mode 100644 index 0f466ee14..000000000 --- a/vendors/mafianet/Source/include/mafianet/VariableListDeltaTracker.h +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "NativeTypes.h" -#include "DS_List.h" -#include "memoryoverride.h" -#include "BitStream.h" - -#ifndef __VARIABLE_LIST_DELTA_TRACKER -#define __VARIABLE_LIST_DELTA_TRACKER - -namespace MafiaNet -{ -/// Class to write a series of variables, copy the contents to memory, and return if the newly written value is different than what was last written -/// Can also encode the reads, writes, and results directly to/from a bitstream -class VariableListDeltaTracker -{ -public: - VariableListDeltaTracker(); - ~VariableListDeltaTracker(); - - // Call before using a series of WriteVar - void StartWrite(void); - - bool IsPastEndOfList(void) const {return nextWriteIndex>=variableList.Size();} - - /// Records the passed value of the variable to memory, and returns true if the value is different from the write before that (or if it is the first write) - /// \pre Call StartWrite() before doing the first of a series of calls to WriteVar or other functions that call WriteVar - /// \note Variables must be of the same type, written in the same order, each time - template - bool WriteVar(const VarType &varData) - { - MafiaNet::BitStream temp; - temp.Write(varData); - if (nextWriteIndex>=variableList.Size()) - { - variableList.Push(VariableLastValueNode(temp.GetData(),temp.GetNumberOfBytesUsed()),_FILE_AND_LINE_); - nextWriteIndex++; - return true; // Different because it's new - } - - if (temp.GetNumberOfBytesUsed()!=variableList[nextWriteIndex].byteLength) - { - variableList[nextWriteIndex].lastData=(char*) rakRealloc_Ex(variableList[nextWriteIndex].lastData, temp.GetNumberOfBytesUsed(),_FILE_AND_LINE_); - variableList[nextWriteIndex].byteLength=temp.GetNumberOfBytesUsed(); - memcpy(variableList[nextWriteIndex].lastData,temp.GetData(),temp.GetNumberOfBytesUsed()); - nextWriteIndex++; - variableList[nextWriteIndex].isDirty=false; - return true; // Different because the serialized size is different - } - if (variableList[nextWriteIndex].isDirty==false && memcmp(temp.GetData(),variableList[nextWriteIndex].lastData, variableList[nextWriteIndex].byteLength)==0) - { - nextWriteIndex++; - return false; // Same because not dirty and memcmp is the same - } - - variableList[nextWriteIndex].isDirty=false; - memcpy(variableList[nextWriteIndex].lastData,temp.GetData(),temp.GetNumberOfBytesUsed()); - nextWriteIndex++; - return true; // Different because dirty or memcmp was different - } - /// Calls WriteVar. If the variable has changed, writes true, and writes the variable. Otherwise writes false. - template - bool WriteVarToBitstream(const VarType &varData, MafiaNet::BitStream *bitStream) - { - bool wasDifferent = WriteVar(varData); - bitStream->Write(wasDifferent); - if (wasDifferent) - { - bitStream->Write(varData); - return true; - } - return false; - } - /// Calls WriteVarToBitstream(). Additionally, adds the boolean result of WriteVar() to boolean bit array - template - bool WriteVarToBitstream(const VarType &varData, MafiaNet::BitStream *bitStream, unsigned char *bArray, unsigned short writeOffset) - { - if (WriteVarToBitstream(varData,bitStream)==true) - { - BitSize_t numberOfBitsMod8 = writeOffset & 7; - - if ( numberOfBitsMod8 == 0 ) - bArray[ writeOffset >> 3 ] = 0x80; - else - bArray[ writeOffset >> 3 ] |= 0x80 >> ( numberOfBitsMod8 ); // Set the bit to 1 - - return true; - } - else - { - if ( ( writeOffset & 7 ) == 0 ) - bArray[ writeOffset >> 3 ] = 0; - - return false; - } - } - - /// Paired with a call to WriteVarToBitstream(), will read a variable if it had changed. Otherwise the values remains the same. - template - static bool ReadVarFromBitstream(VarType &varData, MafiaNet::BitStream *bitStream) - { - bool wasWritten; - if (bitStream->Read(wasWritten)==false) - return false; - if (wasWritten) - { - if (bitStream->Read(varData)==false) - return false; - } - return wasWritten; - } - - /// Variables flagged dirty will cause WriteVar() to return true, even if the variable had not otherwise changed - /// This updates all the variables in the list, where in each index \a varsWritten is true, so will the variable at the corresponding index be flagged dirty - void FlagDirtyFromBitArray(unsigned char *bArray); - - /// \internal - struct VariableLastValueNode - { - VariableLastValueNode(); - VariableLastValueNode(const unsigned char *data, int _byteLength); - ~VariableLastValueNode(); - char *lastData; - unsigned int byteLength; - bool isDirty; - }; - -protected: - /// \internal - DataStructures::List variableList; - /// \internal - unsigned int nextWriteIndex; -}; - - -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/VariadicSQLParser.h b/vendors/mafianet/Source/include/mafianet/VariadicSQLParser.h deleted file mode 100644 index 9118af5d6..000000000 --- a/vendors/mafianet/Source/include/mafianet/VariadicSQLParser.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -#ifndef __VARIADIC_SQL_PARSER_H -#define __VARIADIC_SQL_PARSER_H - -#include "DS_List.h" - -#include - -namespace VariadicSQLParser -{ - struct IndexAndType - { - unsigned int strIndex; - unsigned int typeMappingIndex; - }; - const char* GetTypeMappingAtIndex(int i); - void GetTypeMappingIndices( const char *format, DataStructures::List &indices ); - // Given an SQL string with variadic arguments, allocate argumentBinary and argumentLengths, and hold the parameters in binary format - // Last 2 parameters are out parameters - void ExtractArguments( va_list argptr, const DataStructures::List &indices, char ***argumentBinary, int **argumentLengths ); - void FreeArguments(const DataStructures::List &indices, char **argumentBinary, int *argumentLengths); -} - - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/VirtualWorld.h b/vendors/mafianet/Source/include/mafianet/VirtualWorld.h deleted file mode 100644 index 4302c48d9..000000000 --- a/vendors/mafianet/Source/include/mafianet/VirtualWorld.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2024, MafiaHub - * - * This source code is licensed under the MIT-style license found in the - * license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Lightweight per-entity / per-observer "virtual world" (dimension) tag. -/// -/// A virtual world is a runtime visibility scope layered on top of -/// ReplicaManager3. Unlike an RM3 WorldId (a heavyweight, separate instance -/// with its own NetworkIDManager and connection/replica lists), a virtual world -/// is just an id carried by an entity (Replica3) and by an observer -/// (Connection_RM3) while both remain on the same connection and same RM3 world. -/// -/// Two subjects can see each other when they share the same virtual world id, -/// or when either side is the reserved \a global value (visible everywhere). -/// This is the SA-MP `SetPlayerVirtualWorld` / routing-bucket model: drop a -/// player into a dimension at runtime so they only see players, vehicles, and -/// objects in that dimension, and vanish for the rest. - -#ifndef __VIRTUAL_WORLD_H -#define __VIRTUAL_WORLD_H - -#include - -namespace MafiaNet -{ - -/// \brief Identifier for a virtual world (dimension). -/// \details A 32-bit id, so the number of simultaneous dimensions is effectively -/// unbounded (unlike RM3's 8-bit WorldId). \a VIRTUAL_WORLD_DEFAULT is the main -/// world; \a VIRTUAL_WORLD_GLOBAL means "visible in every virtual world". -/// \ingroup REPLICA_MANAGER_GROUP3 -typedef uint32_t VirtualWorldId; - -/// The default virtual world every entity and observer starts in (the overworld). -static const VirtualWorldId VIRTUAL_WORLD_DEFAULT = 0; - -/// Reserved sentinel: an entity in this world is visible to every observer, and -/// an observer in this world sees entities in every world. Useful for shared -/// world geometry, global NPCs, or admins/spectators. -static const VirtualWorldId VIRTUAL_WORLD_GLOBAL = 0xFFFFFFFF; - -/// \brief Returns whether two subjects in the given virtual worlds can see each other. -/// \details Visibility is symmetric: equal ids, or either side being -/// \a VIRTUAL_WORLD_GLOBAL. -/// \param[in] a First subject's virtual world -/// \param[in] b Second subject's virtual world -/// \return True if visible to one another, false otherwise -inline bool VirtualWorldsCanSee(VirtualWorldId a, VirtualWorldId b) -{ - return a == b || a == VIRTUAL_WORLD_GLOBAL || b == VIRTUAL_WORLD_GLOBAL; -} - -} // namespace MafiaNet - -#endif // __VIRTUAL_WORLD_H diff --git a/vendors/mafianet/Source/include/mafianet/VirtualWorldReplica3.h b/vendors/mafianet/Source/include/mafianet/VirtualWorldReplica3.h deleted file mode 100644 index 5b3431d1c..000000000 --- a/vendors/mafianet/Source/include/mafianet/VirtualWorldReplica3.h +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2024, MafiaHub - * - * This source code is licensed under the MIT-style license found in the - * license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Replica3 base class that scopes visibility by virtual world. - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_ReplicaManager3==1 - -#ifndef __VIRTUAL_WORLD_REPLICA_3_H -#define __VIRTUAL_WORLD_REPLICA_3_H - -#include "ReplicaManager3.h" -#include "VirtualWorld.h" - -namespace MafiaNet -{ - -/// \brief A Replica3 that is only visible to observers sharing its virtual world. -/// \details Derive your networked entities (players, vehicles, objects) from this -/// instead of Replica3 to get runtime dimension scoping for free. The virtual -/// world filter is applied in QueryConstruction / QueryDestruction / -/// QuerySerialization; when the observer can see this entity -/// (\ref VirtualWorldsCanSee), the call delegates to the *WithinWorld() hooks, -/// which you implement with the usual topology defaults (server, client, or -/// peer-to-peer). -/// -/// Runtime switching just works in the default construction mode -/// (QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION): when an entity's or an -/// observer's virtual world changes, RM3's next Update() re-queries and spawns -/// the newly-visible entities in and the no-longer-visible ones out -/// automatically — no Pop/Push of connections, no manual destruction broadcast. -/// -/// \note If you override QueryConstructionMode() to return -/// QUERY_CONNECTION_FOR_REPLICA_LIST, these hooks are not called and you are -/// responsible for applying VirtualWorldsCanSee() in QueryReplicaList() yourself. -/// \ingroup REPLICA_MANAGER_GROUP3 -class RAK_DLL_EXPORT VirtualWorldReplica3 : public Replica3 -{ -public: - VirtualWorldReplica3() : virtualWorld(VIRTUAL_WORLD_DEFAULT) {} - virtual ~VirtualWorldReplica3() {} - - /// \brief Set the virtual world this entity exists in. - void SetVirtualWorld(VirtualWorldId vw) { virtualWorld = vw; } - - /// \return The virtual world this entity exists in. - VirtualWorldId GetVirtualWorld(void) const { return virtualWorld; } - - // --- Replica3 visibility hooks: filter by virtual world, then delegate. --- - // - // The virtual world filter is only applied by the AUTHORITY for a given - // (entity, connection) pair -- i.e. the system that would actually construct - // this entity toward that connection. A downloaded copy on a non-authority - // (e.g. a server-owned object on a client) must defer entirely to the - // topology default; otherwise its own connection (whose virtual world is not - // meaningfully set on that side) would look "different" and the copy would - // send a spurious destruction upstream, deleting the entity at its owner. - // - // Authority is detected as QueryConstructionWithinWorld() == RM3CS_SEND_CONSTRUCTION - // ONLY. RM3CS_ALREADY_EXISTS_REMOTELY is deliberately NOT treated as - // authoritative: the same state is returned both by a currently-authoritative - // static owner AND by genuinely non-authoritative peers - // (R3P2PM_MULTI_OWNER_NOT_CURRENTLY_AUTHORITATIVE, - // R3P2PM_STATIC_OBJECT_NOT_CURRENTLY_AUTHORITATIVE), and the two cannot be - // distinguished from the construction state alone -- treating it as authority - // would re-introduce the spurious-upstream-destruction bug. Consequently - // "already exists remotely" static objects are not virtual-world filtered; - // such objects (typically global level geometry) should be scoped by other - // means if needed. - - virtual RM3ConstructionState QueryConstruction(Connection_RM3 *destinationConnection, ReplicaManager3 *replicaManager3) - { - RM3ConstructionState within = QueryConstructionWithinWorld(destinationConnection, replicaManager3); - if (within == RM3CS_SEND_CONSTRUCTION && !VirtualWorldsCanSee(virtualWorld, destinationConnection->GetVirtualWorld())) - return RM3CS_NO_ACTION; // authority, but not in this observer's world (re-queried next tick) - return within; - } - - virtual RM3DestructionState QueryDestruction(Connection_RM3 *destinationConnection, ReplicaManager3 *replicaManager3) - { - bool authoritative = QueryConstructionWithinWorld(destinationConnection, replicaManager3) == RM3CS_SEND_CONSTRUCTION; - if (authoritative && !VirtualWorldsCanSee(virtualWorld, destinationConnection->GetVirtualWorld())) - return RM3DS_SEND_DESTRUCTION; // left this observer's world -> despawn it for them - return QueryDestructionWithinWorld(destinationConnection, replicaManager3); - } - - virtual RM3QuerySerializationResult QuerySerialization(Connection_RM3 *destinationConnection) - { - bool authoritative = QueryConstructionWithinWorld(destinationConnection, replicaManager) == RM3CS_SEND_CONSTRUCTION; - if (authoritative && !VirtualWorldsCanSee(virtualWorld, destinationConnection->GetVirtualWorld())) - return RM3QSR_DO_NOT_CALL_SERIALIZE; // skipped while out of world (re-queried next tick) - return QuerySerializationWithinWorld(destinationConnection); - } - -protected: - /// \brief Construction decision once the observer is known to be in this entity's world. - /// \details Implement with one of QueryConstruction_ServerConstruction(), - /// QueryConstruction_ClientConstruction(), or QueryConstruction_PeerToPeer(). - virtual RM3ConstructionState QueryConstructionWithinWorld(Connection_RM3 *destinationConnection, ReplicaManager3 *replicaManager3) = 0; - - /// \brief Destruction decision once the observer is known to be in this entity's world. - /// \details Defaults to RM3DS_NO_ACTION (do nothing, keep querying) so that a - /// later virtual world change is still able to despawn the entity. Override - /// only if you also drive per-connection destruction from within a world. - virtual RM3DestructionState QueryDestructionWithinWorld(Connection_RM3 *destinationConnection, ReplicaManager3 *replicaManager3) - { - (void)destinationConnection; - (void)replicaManager3; - return RM3DS_NO_ACTION; - } - - /// \brief Serialization decision once the observer is known to be in this entity's world. - /// \details Implement with one of QuerySerialization_ServerSerializable(), - /// QuerySerialization_ClientSerializable(), or QuerySerialization_PeerToPeer(). - virtual RM3QuerySerializationResult QuerySerializationWithinWorld(Connection_RM3 *destinationConnection) = 0; - - VirtualWorldId virtualWorld; -}; - -} // namespace MafiaNet - -#endif // __VIRTUAL_WORLD_REPLICA_3_H - -#endif // _RAKNET_SUPPORT_ReplicaManager3 diff --git a/vendors/mafianet/Source/include/mafianet/VitaIncludes.h b/vendors/mafianet/Source/include/mafianet/VitaIncludes.h deleted file mode 100644 index 60124ffcc..000000000 --- a/vendors/mafianet/Source/include/mafianet/VitaIncludes.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * This file was taken from RakNet 4.082 without any modifications. - * Please see licenses/RakNet license.txt for the underlying license and related copyright. - */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/vendors/mafianet/Source/include/mafianet/WSAStartupSingleton.h b/vendors/mafianet/Source/include/mafianet/WSAStartupSingleton.h deleted file mode 100644 index 3c03b2d5f..000000000 --- a/vendors/mafianet/Source/include/mafianet/WSAStartupSingleton.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -#ifndef __WSA_STARTUP_SINGLETON_H -#define __WSA_STARTUP_SINGLETON_H - -class WSAStartupSingleton -{ -public: - WSAStartupSingleton(); - ~WSAStartupSingleton(); - static void AddRef(void); - static void Deref(void); - -protected: - static int refCount; -}; - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/WindowsIncludes.h b/vendors/mafianet/Source/include/mafianet/WindowsIncludes.h deleted file mode 100644 index 4aac6e74d..000000000 --- a/vendors/mafianet/Source/include/mafianet/WindowsIncludes.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2019, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef NOMINMAX - #define NOMINMAX -#endif - -#if defined (_WIN32) -#include -#include -#include -#include // used for GetAdaptersAddresses() -#pragma comment(lib, "IPHLPAPI.lib") // used for GetAdaptersAddresses() -#endif diff --git a/vendors/mafianet/Source/include/mafianet/XBox360Includes.h b/vendors/mafianet/Source/include/mafianet/XBox360Includes.h deleted file mode 100644 index fbe8cce8f..000000000 --- a/vendors/mafianet/Source/include/mafianet/XBox360Includes.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * This file was taken from RakNet 4.082 without any modifications. - * Please see licenses/RakNet license.txt for the underlying license and related copyright. - */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/vendors/mafianet/Source/include/mafianet/_FindFirst.h b/vendors/mafianet/Source/include/mafianet/_FindFirst.h deleted file mode 100644 index b0dc9c88e..000000000 --- a/vendors/mafianet/Source/include/mafianet/_FindFirst.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * This file was taken from RakNet 4.082. - * Please see licenses/RakNet license.txt for the underlying license and related copyright. - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// -/// Original file by the_viking, fixed by Rômulo Fernandes -/// Should emulate windows finddata structure -/// - -#ifndef GCC_FINDFIRST_H -#define GCC_FINDFIRST_H - -#if (defined(__GNUC__) || defined(__ARMCC_VERSION) || defined(__GCCXML__) || defined(__S3E__) ) && !defined(__WIN32) - -#include - -#include "string.h" - -#define _A_NORMAL 0x00 // Normal file -#define _A_RDONLY 0x01 // Read-only file -#define _A_HIDDEN 0x02 // Hidden file -#define _A_SYSTEM 0x04 // System file -#define _A_VOLID 0x08 // Volume ID -#define _A_SUBDIR 0x10 // Subdirectory -#define _A_ARCH 0x20 // File changed since last archive -#define FA_NORMAL 0x00 // Synonym of _A_NORMAL -#define FA_RDONLY 0x01 // Synonym of _A_RDONLY -#define FA_HIDDEN 0x02 // Synonym of _A_HIDDEN -#define FA_SYSTEM 0x04 // Synonym of _A_SYSTEM -#define FA_LABEL 0x08 // Synonym of _A_VOLID -#define FA_DIREC 0x10 // Synonym of _A_SUBDIR -#define FA_ARCH 0x20 // Synonym of _A_ARCH - - -const unsigned STRING_BUFFER_SIZE = 512; - -typedef struct _finddata_t -{ - char name[STRING_BUFFER_SIZE]; - int attrib; - unsigned long size; -} _finddata; - -/** - * Hold information about the current search - */ -typedef struct _findinfo_t -{ - DIR* openedDir; - MafiaNet::RakString filter; - MafiaNet::RakString dirName; -} _findinfo; - -long _findfirst(const char *name, _finddata_t *f); -int _findnext(long h, _finddata_t *f); -int _findclose(long h); - -#endif -#endif - diff --git a/vendors/mafianet/Source/include/mafianet/aliases.h b/vendors/mafianet/Source/include/mafianet/aliases.h deleted file mode 100644 index af8a5322a..000000000 --- a/vendors/mafianet/Source/include/mafianet/aliases.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2019, SLikeSoft UG (haftungsbeschraenkt) - * - * This source code is licensed under the MIT-style license found in the license.txt - * file in the root directory of this source tree. - */ - -/// \file aliases.h -/// \brief Canonical MafiaNet type aliases over the legacy RakNet names. -/// -/// The library lives in the `MafiaNet` namespace, but many public types still -/// carry their historical RakNet names. This header introduces clean, canonical -/// aliases so callers can write idiomatic MafiaNet code: -/// \code -/// MafiaNet::PeerInterface* peer = MafiaNet::PeerInterface::GetInstance(); -/// \endcode -/// -/// These are `using` aliases (not subclasses): each canonical name denotes the -/// exact same type as its legacy counterpart, so the two interoperate freely. -/// -/// \note Aliases only — the legacy declarations are intentionally left untouched -/// and un-deprecated. A `[[deprecated]]` pass is a separate, later task. - -#pragma once - -#include "mafianet/peerinterface.h" // RakPeerInterface -#include "mafianet/types.h" // RakNetGUID, UNASSIGNED_RAKNET_GUID -#include "mafianet/statistics.h" // RakNetStatistics - -namespace MafiaNet { - -/// Canonical name for the main entry point, RakPeerInterface. -using PeerInterface = RakPeerInterface; - -/// Canonical name for a peer's globally unique identifier, RakNetGUID. -using Guid = RakNetGUID; - -/// Canonical name for the connection statistics struct, RakNetStatistics. -using Statistics = RakNetStatistics; - -/// Canonical name for the unassigned-GUID sentinel, UNASSIGNED_RAKNET_GUID. -/// Bound by reference so it remains the same object as the legacy sentinel. -inline const Guid& UnassignedGuid = UNASSIGNED_RAKNET_GUID; - -} // namespace MafiaNet diff --git a/vendors/mafianet/Source/include/mafianet/alloca.h b/vendors/mafianet/Source/include/mafianet/alloca.h deleted file mode 100644 index 7767c5f96..000000000 --- a/vendors/mafianet/Source/include/mafianet/alloca.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -#if defined(__FreeBSD__) -#include - - - - -#elif defined ( __APPLE__ ) || defined ( __APPLE_CC__ ) -#include -#include -#elif defined(_WIN32) -#include -#else -#include -// Alloca needed on Ubuntu apparently -#include -#endif diff --git a/vendors/mafianet/Source/include/mafianet/assert.h b/vendors/mafianet/Source/include/mafianet/assert.h deleted file mode 100644 index c495a013a..000000000 --- a/vendors/mafianet/Source/include/mafianet/assert.h +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include -#include "defines.h" diff --git a/vendors/mafianet/Source/include/mafianet/commandparser.h b/vendors/mafianet/Source/include/mafianet/commandparser.h deleted file mode 100644 index d54ba8ef0..000000000 --- a/vendors/mafianet/Source/include/mafianet/commandparser.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Contains RakNetCommandParser , used to send commands to an instance of RakPeer -/// - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_RakNetCommandParser==1 - -#ifndef __RAKNET_COMMAND_PARSER -#define __RAKNET_COMMAND_PARSER - -#include "CommandParserInterface.h" -#include "Export.h" - -namespace MafiaNet -{ -class RakPeerInterface; - -/// \brief This allows a console client to call most of the functions in RakPeer -class RAK_DLL_EXPORT RakNetCommandParser : public CommandParserInterface -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(RakNetCommandParser) - - RakNetCommandParser(); - ~RakNetCommandParser(); - - /// Given \a command with parameters \a parameterList , do whatever processing you wish. - /// \param[in] command The command to process - /// \param[in] numParameters How many parameters were passed along with the command - /// \param[in] parameterList The list of parameters. parameterList[0] is the first parameter and so on. - /// \param[in] transport The transport interface we can use to write to - /// \param[in] systemAddress The player that sent this command. - /// \param[in] originalString The string that was actually sent over the network, in case you want to do your own parsing - bool OnCommand(const char *command, unsigned numParameters, char **parameterList, TransportInterface *transport, const SystemAddress &systemAddress, const char *originalString); - - /// You are responsible for overriding this function and returning a static string, which will identifier your parser. - /// This should return a static string - /// \return The name that you return. - const char *GetName(void) const; - - /// A callback for when you are expected to send a brief description of your parser to \a systemAddress - /// \param[in] transport The transport interface we can use to write to - /// \param[in] systemAddress The player that requested help. - void SendHelp(TransportInterface *transport, const SystemAddress &systemAddress); - - /// Records the instance of RakPeer to perform the desired commands on - /// \param[in] rakPeer The RakPeer instance, or a derived class (e.g. RakPeer or RakPeer) - void SetRakPeerInterface(MafiaNet::RakPeerInterface *rakPeer); -protected: - - /// Which instance of RakPeer we are working on. Set from SetRakPeerInterface() - RakPeerInterface *peer; -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/crypto/cryptomanager.h b/vendors/mafianet/Source/include/mafianet/crypto/cryptomanager.h deleted file mode 100644 index 36b358044..000000000 --- a/vendors/mafianet/Source/include/mafianet/crypto/cryptomanager.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2019, SLikeSoft UG (haftungsbeschr�nkt) - * - * This source code is licensed under the MIT-style license found in the license.txt - * file in the root directory of this source tree. - */ -#pragma once - -#include // used for EVP_xxxx - -namespace MafiaNet -{ - namespace Experimental - { - namespace Crypto - { - class CCryptoManager - { - private: - // class members - // note: using distinct contexts for encryption/decryption to prevent potential for race conditions - // #med - consider moving to SessionEncrypter class - static EVP_CIPHER_CTX* m_decryptionContext; - static EVP_CIPHER_CTX* m_encryptionContext; - static unsigned char m_initializationVector[EVP_MAX_IV_LENGTH]; - static unsigned char m_sessionKey[EVP_MAX_KEY_LENGTH]; - static bool m_Initialized; - - public: - // initialization - static bool Initialize(); - static void Shutdown(); - - public: - // session encryption - static bool EncryptSessionData(const unsigned char* plaintext, size_t dataLength, unsigned char* outBuffer, size_t& inOutBufferSize); - static bool DecryptSessionData(const unsigned char* encryptedtext, size_t dataLength, unsigned char* outBuffer, size_t& inOutBufferSize); - static bool GetRequiredEncryptionBufferSize(size_t& encryptionDataByteLength); - - public: - // secure memory management methods - // #med - consider moving to separate class (SecureMemory/MemoryManager) - static void* AllocateSecureMemory(size_t size); - static void FreeSecureMemory(void* pointer, size_t size); - static void SecureClearMemory(void* pointer, size_t dataSize); - }; - } - } -} \ No newline at end of file diff --git a/vendors/mafianet/Source/include/mafianet/crypto/factory.h b/vendors/mafianet/Source/include/mafianet/crypto/factory.h deleted file mode 100644 index a708c58a5..000000000 --- a/vendors/mafianet/Source/include/mafianet/crypto/factory.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2018-2019, SLikeSoft UG (haftungsbeschraenkt) - * - * This source code is licensed under the MIT-style license found in the license.txt - * file in the root directory of this source tree. - */ -#pragma once - -#include "securestring.h" // used for MafiaNet::Crypto::CSecureString -#include "ifileencrypter.h" // used for MafiaNet::Crypto::IFileEncrypter - -namespace MafiaNet -{ - namespace Experimental - { - namespace Crypto - { - class Factory - { - public: - static IFileEncrypter* ConstructFileEncrypter(const char *publicKey, size_t publicKeyLength); - static IFileEncrypter* ConstructFileEncrypter(const char *publicKey, size_t publicKeyLength, const char *privateKey, size_t privateKeyLength, CSecureString& privateKeyPassword); - }; - } - } -} \ No newline at end of file diff --git a/vendors/mafianet/Source/include/mafianet/crypto/fileencrypter.h b/vendors/mafianet/Source/include/mafianet/crypto/fileencrypter.h deleted file mode 100644 index f61ce1dfe..000000000 --- a/vendors/mafianet/Source/include/mafianet/crypto/fileencrypter.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2018-2019, SLikeSoft UG (haftungsbeschr�nkt) - * - * This source code is licensed under the MIT-style license found in the license.txt - * file in the root directory of this source tree. - */ -#pragma once - -#include "ifileencrypter.h" // used for Crypto::IFileEncrypter -#include "securestring.h" // used for Crypto::CSecureString - #include // used for RSA - -namespace MafiaNet -{ - namespace Experimental - { - namespace Crypto - { - class CFileEncrypter : public IFileEncrypter - { - // member variables - EVP_PKEY *m_privatePKey; - EVP_PKEY *m_publicPKey; - unsigned char m_sigBuffer[1024]; - char m_sigBufferBase64[1369]; // 1369 = 1368 (size of base64-encoded 1k signature which is 1024 / 3 * 4 (representing 1023 bytes) + 4 bytes for the last byte) + 1 byte for trailing \0-terminator - - // constructor - public: - // #high - drop the default ctor again (provide load from file instead incl. routing through customized file open handlers) - CFileEncrypter(); - CFileEncrypter(const char *publicKey, size_t publicKeyLength); - CFileEncrypter(const char *publicKey, size_t publicKeyLength, const char *privateKey, size_t privateKeyLength, CSecureString &password); - ~CFileEncrypter(); - - // signing methods - public: - const unsigned char* SignData(const unsigned char *data, const size_t dataLength) override; - const char* SignDataBase64(const unsigned char *data, const size_t dataLength) override; - // #med reconsider/review interface here (char / unsigned char) - bool VerifyData(const unsigned char *data, const size_t dataLength, const unsigned char *signature, const size_t signatureLength) override; - bool VerifyDataBase64(const unsigned char *data, const size_t dataLength, const char *signature, const size_t signatureLength) override; - - // internal helpers - private: - static int PasswordCallback(char *buffer, int bufferSize, int, void *password); - const char* SetPrivateKey(const char *privateKey, size_t privateKeyLength, CSecureString &password); - const char* SetPublicKey(const char *publicKey, size_t publicKeyLength); - }; - } - } -} \ No newline at end of file diff --git a/vendors/mafianet/Source/include/mafianet/crypto/ifileencrypter.h b/vendors/mafianet/Source/include/mafianet/crypto/ifileencrypter.h deleted file mode 100644 index 8ca245ce0..000000000 --- a/vendors/mafianet/Source/include/mafianet/crypto/ifileencrypter.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2018-2019, SLikeSoft UG (haftungsbeschraenkt) - * - * This source code is licensed under the MIT-style license found in the license.txt - * file in the root directory of this source tree. - */ -#pragma once - -#include // required for size_t - -namespace MafiaNet -{ - namespace Experimental - { - namespace Crypto - { - class IFileEncrypter - { - // constructor / destructor - protected: - IFileEncrypter() = default; - public: - virtual ~IFileEncrypter() = default; - - // signing methods - public: - virtual const unsigned char* SignData(const unsigned char* data, const size_t dataLength) = 0; - virtual const char* SignDataBase64(const unsigned char* data, const size_t dataLength) = 0; - virtual bool VerifyData(const unsigned char *data, const size_t dataLength, const unsigned char *signature, const size_t signatureLength) = 0; - virtual bool VerifyDataBase64(const unsigned char *data, const size_t dataLength, const char *signature, const size_t signatureLength) = 0; - }; - } - } -} \ No newline at end of file diff --git a/vendors/mafianet/Source/include/mafianet/crypto/securestring.h b/vendors/mafianet/Source/include/mafianet/crypto/securestring.h deleted file mode 100644 index 3acca152f..000000000 --- a/vendors/mafianet/Source/include/mafianet/crypto/securestring.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -* Copyright (c) 2018-2019, SLikeSoft UG (haftungsbeschraenkt) -* -* This source code is licensed under the MIT-style license found in the license.txt -* file in the root directory of this source tree. -*/ - -#pragma once -#include // required for size_t - -namespace MafiaNet -{ - namespace Experimental - { - namespace Crypto - { - // #med - consider CSecureMemoryBuffer and derive CSecureString from that class - // difference would be implicit null-terminated buffer in string buffer (upon Decrypt calls) - // document: document Decrypt/FlushUnencryptedData() requirements for most secure handling - // i.e. emphasize that FlushUnencryptedData() must be called after having called Decrypt() ASAP once access to the unencrypted data - // data is no longer required - class CSecureString - { - // member variables - private: - bool m_UTF8Mode; - bool m_wasFlushed; - size_t m_EncryptedBufferSize; // size of the buffer for the encrypted string - size_t m_numBufferSize; // size of the actual supported string buffer (excluding the trailing \0-terminator) - size_t m_numBufferUsed; // size of the available buffer currently used - size_t m_numEncryptedBufferUsed; // size of the encrypted buffer which is used and contains the encrypted data - size_t m_UnencryptedBufferSize; // size of the buffer allocated to retrieve the decrypted string - unsigned char* m_EncryptedMemory; - char* m_UnencryptedBuffer; - - // constructor / destructor - public: - CSecureString(const size_t maxBufferSize, const bool utf8Mode = false); - ~CSecureString(); - - // container methods - public: - size_t AddChar(char* character); - bool RemoveLastChar(); - void Reset(); - - // decryption methods - public: - const char* Decrypt(); - void FlushUnencryptedData(); - }; - } - } -} \ No newline at end of file diff --git a/vendors/mafianet/Source/include/mafianet/defineoverrides.h b/vendors/mafianet/Source/include/mafianet/defineoverrides.h deleted file mode 100644 index f3e874fe4..000000000 --- a/vendors/mafianet/Source/include/mafianet/defineoverrides.h +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -// USER EDITABLE FILE - diff --git a/vendors/mafianet/Source/include/mafianet/defines.h b/vendors/mafianet/Source/include/mafianet/defines.h deleted file mode 100644 index e733cbad7..000000000 --- a/vendors/mafianet/Source/include/mafianet/defines.h +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __RAKNET_DEFINES_H -#define __RAKNET_DEFINES_H - -#ifdef _RETAIL -// retail builds imply release configurations -#define _RELEASE -#endif - -// If you want to change these defines, put them in RakNetDefinesOverrides so your changes are not lost when updating RakNet -// The user should not edit this file -#include "defineoverrides.h" - -/// Define __GET_TIME_64BIT to have MafiaNet::TimeMS use a 64, rather than 32 bit value. A 32 bit value will overflow after about 5 weeks. -/// However, this doubles the bandwidth use for sending times, so don't do it unless you have a reason to. -/// Comment out if you are using the iPod Touch TG. See http://www.jenkinssoftware.com/forum/index.php?topic=2717.0 -/// This must be the same on all systems, or they won't connect -#ifndef __GET_TIME_64BIT -#define __GET_TIME_64BIT 1 -#endif - -// Define _FILE_AND_LINE_ to "",0 if you want to strip out file and line info for memory tracking from the EXE -// SWIG: This macro must be excluded from generating C# wrappers/interfaces since SWIG would try to handle the -// macro as a constant definition and fail to convert it, issuing the following warning: -// "warning 305: Bad constant value (ignored)." - see SLNET-227 for details -// Since this is not a constant definition at all, the correct solution is to exclude this macro therefore. -#ifndef _FILE_AND_LINE_ -#ifndef SWIG -#ifdef _RETAIL -// retail builds do not contain source-code related information in order to reduce the overall EXE size -#define _FILE_AND_LINE_ "",0 -#else -#define _FILE_AND_LINE_ __FILE__,__LINE__ -#endif // _RETAIL -#endif // SWIG -#endif // _FILE_AND_LINE_ - -/// Define RAKNET_COMPATIBILITY to enable API compatibility with RakNet. -/// This allows you to keep existing code which was compatible with RakNet 4.082 unmodified and -/// use MafiaNet as an in-place replacement for the RakNet library without having to modify any -/// of your code. -// #define RAKNET_COMPATIBILITY - -/// Define __BITSTREAM_NATIVE_END to NOT support endian swapping in the BitStream class. This is faster and is what you should use -/// unless you actually plan to have different endianness systems connect to each other -/// Enabled by default. -// #define __BITSTREAM_NATIVE_END - -/// Maximum (stack) size to use with _alloca before using new and delete instead. -#ifndef MAX_ALLOCA_STACK_ALLOCATION -#define MAX_ALLOCA_STACK_ALLOCATION 1048576 -#endif - -// Use WaitForSingleObject instead of sleep. -// Defining it plays nicer with other systems, and uses less CPU, but gives worse RakNet performance -// Undefining it uses more CPU time, but is more responsive and faster. -#define USE_WAIT_FOR_MULTIPLE_EVENTS - -/// Uncomment to use RakMemoryOverride for custom memory tracking -/// See memoryoverride.h. -#ifndef _USE_RAK_MEMORY_OVERRIDE -#define _USE_RAK_MEMORY_OVERRIDE 0 -#endif - -/// If defined, OpenSSL is enabled for the class TCPInterface -/// This is necessary to use the SendEmail class with Google POP servers -/// Note that OpenSSL carries its own license restrictions that you should be aware of. If you don't agree, don't enable this define -/// This also requires that you enable header search paths to DependentExtensions/openssl/include/[platform] -#ifndef OPEN_SSL_CLIENT_SUPPORT -#define OPEN_SSL_CLIENT_SUPPORT 0 -#endif - -/// Threshold at which to do a malloc / free rather than pushing data onto a fixed stack for the bitstream class -/// Arbitrary size, just picking something likely to be larger than most packets -#ifndef BITSTREAM_STACK_ALLOCATION_SIZE -#define BITSTREAM_STACK_ALLOCATION_SIZE 256 -#endif - -// Redefine if you want to disable or change the target for debug RAKNET_DEBUG_PRINTF -#ifndef RAKNET_DEBUG_PRINTF -#define RAKNET_DEBUG_PRINTF printf -#endif - -#ifndef RAKNET_DEBUG_TPRINTF -#define RAKNET_DEBUG_TPRINTF _tprintf -#endif - -// Maximum number of local IP addresses supported -#ifndef MAXIMUM_NUMBER_OF_INTERNAL_IDS -#define MAXIMUM_NUMBER_OF_INTERNAL_IDS 10 -#endif - -#ifndef RakAssert -#if defined(__native_client__) -#define RakAssert(x) -#else -#if defined(_DEBUG) -#define RakAssert(x) assert(x); -#else -#define RakAssert(x) -#endif -#endif -#endif - -#if !defined(_DEBUG) || defined(__native_client__) -#define SLNET_VERIFY(x) ((void)(x)) -#else -#define SLNET_VERIFY(x) RakAssert(x) -#endif - -/// This controls the amount of memory used per connection. -/// This many datagrams are tracked by datagramNumber. If more than this many datagrams are sent, then an ack for an older datagram would be ignored -/// This results in an unnecessary resend in that case -#ifndef DATAGRAM_MESSAGE_ID_ARRAY_LENGTH -#define DATAGRAM_MESSAGE_ID_ARRAY_LENGTH 512 -#endif - -/// This is the maximum number of reliable user messages that can be on the wire at a time -/// If this is too low, then high ping connections with a large throughput will be underutilized -/// This will be evident because RakNetStatistics::messagesInSend buffer will increase over time, yet at the same time the outgoing bandwidth per second is less than your connection supports -#ifndef RESEND_BUFFER_ARRAY_LENGTH -#define RESEND_BUFFER_ARRAY_LENGTH 512 -#define RESEND_BUFFER_ARRAY_MASK 511 -#endif - -/// Uncomment if you want to link in the DLMalloc library to use with RakMemoryOverride -// #define _LINK_DL_MALLOC - -#ifndef GET_TIME_SPIKE_LIMIT -/// Workaround for http://support.microsoft.com/kb/274323 -/// If two calls between MafiaNet::GetTime() happen farther apart than this time in microseconds, this delta will be returned instead -/// Note: This will cause ID_TIMESTAMP to be temporarily inaccurate if you set a breakpoint that pauses the UpdateNetworkLoop() thread in RakPeer -/// Define in definesoverrides.h to enable (non-zero) or disable (0) -#define GET_TIME_SPIKE_LIMIT 0 -#endif - -// Use sliding window congestion control instead of ping based congestion control -#ifndef USE_SLIDING_WINDOW_CONGESTION_CONTROL -#define USE_SLIDING_WINDOW_CONGESTION_CONTROL 1 -#endif - -// When a large message is arriving, preallocate the memory for the entire block -// This results in large messages not taking up time to reassembly with memcpy, but is vulnerable to attackers causing the host to run out of memory -#ifndef PREALLOCATE_LARGE_MESSAGES -#define PREALLOCATE_LARGE_MESSAGES 0 -#endif - -#ifndef RAKNET_SUPPORT_IPV6 -#define RAKNET_SUPPORT_IPV6 0 -#endif - -#ifndef RAKSTRING_TYPE -#if defined(_UNICODE) -#define RAKSTRING_TYPE RakWString -#define RAKSTRING_TYPE_IS_UNICODE 1 -#else -#define RAKSTRING_TYPE RakString -#define RAKSTRING_TYPE_IS_UNICODE 0 -#endif -#endif - -#ifndef RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS -#define RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS 48 -#endif - -#ifndef RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH -#define RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH 48 -#endif - -#ifndef XBOX_BYPASS_SECURITY -#define XBOX_BYPASS_SECURITY 1 -#endif - -// Controls how many allocations occur at once for the memory pool of incoming datagrams waiting to be transferred between the recvfrom thread and the main update thread -// Has large effect on memory usage, per instance of RakPeer. Approximately MAXIMUM_MTU_SIZE*BUFFERED_PACKETS_PAGE_SIZE bytes, once after calling RakPeer::Startup() -#ifndef BUFFERED_PACKETS_PAGE_SIZE -#define BUFFERED_PACKETS_PAGE_SIZE 8 -#endif - -// Controls how many allocations occur at once for the memory pool of incoming or outgoing datagrams. -// Has small effect on memory usage per connection. Uses about 256 bytes*INTERNAL_PACKET_PAGE_SIZE per connection -#ifndef INTERNAL_PACKET_PAGE_SIZE -#define INTERNAL_PACKET_PAGE_SIZE 8 -#endif - -// If defined to 1, the user is responsible for calling RakPeer::RunUpdateCycle and RakPeer::RunRecvfrom -#ifndef RAKPEER_USER_THREADED -#define RAKPEER_USER_THREADED 0 -#endif - -#ifndef USE_ALLOCA -#define USE_ALLOCA 1 -#endif - -//#define USE_THREADED_SEND - -// @since 0.1.1: added -// Controls the maximum retrievable filesize for incoming files using FileListTransfer. -// The configured limit only applies for files which are transferred incrementally (which basically applies to any larger file). -// Note that this also impacts the upper limit for memory allocations. It's suggested to redefine the value to a reasonable smaller size in the defineoverrides.h header file. -// For backwards compatibility with RakNet, the default is set to 4 GiB-1. -// #low - consider introducing GiB/MiB/KiB-functions and then define as GiB(4)? -#ifndef SLNET_MAX_RETRIEVABLE_FILESIZE -#define SLNET_MAX_RETRIEVABLE_FILESIZE (0xFFFFFFFF) -#endif - -// Short-hand alias for the MafiaNet namespace. -// note: we use a preprocessor macro rather than a namespace alias to ensure ABI compatibility with shared -// libraries/DLLs. With a namespace alias the names in the DLLs would still point to the actual namespace -// (MafiaNet) rather than the alias namespace, so the macro simply rewrites MNet to the real MafiaNet namespace. -#define MNet MafiaNet - -#endif // __RAKNET_DEFINES_H diff --git a/vendors/mafianet/Source/include/mafianet/gettimeofday.h b/vendors/mafianet/Source/include/mafianet/gettimeofday.h deleted file mode 100644 index 845389cc3..000000000 --- a/vendors/mafianet/Source/include/mafianet/gettimeofday.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * Modified work: Copyright (c) 2019, SLikeSoft UG (haftungsbeschr�nkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __GET_TIME_OF_DAY_H -#define __GET_TIME_OF_DAY_H - -#if defined(_WIN32) && !defined(__GNUC__) &&!defined(__GCCXML__) -#include -struct timezone -{ - int tz_minuteswest; /* minutes W of Greenwich */ - int tz_dsttime; /* type of dst correction */ -}; - -int gettimeofday(struct timeval *tv, struct timezone *tz); - - -#else - - - - -#include - -#include - -// Uncomment this if you need to -/* -// http://www.halcode.com/archives/2008/08/26/retrieving-system-time-gettimeofday/ -struct timezone -{ - int tz_minuteswest; - int tz_dsttime; -}; - -#ifdef __cplusplus - -void GetSystemTimeAsFileTime(FILETIME*); - -inline int gettimeofday(struct timeval* p, void* tz ) -{ - union { - long long ns100; // time since 1 Jan 1601 in 100ns units - FILETIME ft; - } now; - - GetSystemTimeAsFileTime( &(now.ft) ); - p->tv_usec=(long)((now.ns100 / 10LL) % 1000000LL ); - p->tv_sec= (long)((now.ns100-(116444736000000000LL))/10000000LL); - return 0; -} - -#else - int gettimeofday(struct timeval* p, void* tz ); -#endif -*/ - -#endif - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/guid_util.h b/vendors/mafianet/Source/include/mafianet/guid_util.h deleted file mode 100644 index c1d47cd34..000000000 --- a/vendors/mafianet/Source/include/mafianet/guid_util.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2024, MafiaHub - * - * This source code is licensed under the MIT-style license found in the - * license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Modern, additive value-type accessors layered over the legacy -/// RakNet/SLikeNet value types (\a RakNetGUID, \a SystemAddress). -/// -/// These free functions live alongside the legacy struct methods rather than -/// inside them, so they don't touch the wire-transmitted ABI of \a RakNetGUID. -/// They favour ownership over shared static buffers and \a std::optional over -/// sentinel return values, giving callers thread-safe, leak-free primitives to -/// build cleaner APIs on top of. - -#ifndef __MAFIANET_GUID_UTIL_H -#define __MAFIANET_GUID_UTIL_H - -#include -#include - -#include "types.h" -#include "peerinterface.h" - -namespace MafiaNet { - -/// Return the GUID as an owned \a std::string. -/// -/// Unlike the legacy \a RakNetGUID::ToString() member (which returned a pointer -/// into a rotating, process-wide static buffer and was explicitly NOT thread -/// safe), this allocates a fresh string on every call and shares no state, so -/// it is safe to call concurrently from multiple threads. It is implemented on -/// top of the thread-safe \a RakNetGUID::ToString(char*, size_t) member. -RAK_DLL_EXPORT std::string to_string(const RakNetGUID& g); - -/// Look up the SystemAddress currently connected to \a g. -/// -/// A thin facade over \a RakPeerInterface::GetSystemAddressFromGuid that maps -/// the legacy \a UNASSIGNED_SYSTEM_ADDRESS "none" sentinel to \a std::nullopt, -/// so callers can use ordinary optional handling instead of comparing against a -/// magic value. -RAK_DLL_EXPORT std::optional connected_address(RakPeerInterface& peer, const RakNetGUID& g); - -} // namespace MafiaNet - -#endif // __MAFIANET_GUID_UTIL_H diff --git a/vendors/mafianet/Source/include/mafianet/linux_adapter.h b/vendors/mafianet/Source/include/mafianet/linux_adapter.h deleted file mode 100644 index ee83d384f..000000000 --- a/vendors/mafianet/Source/include/mafianet/linux_adapter.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2016-2019, SLikeSoft UG (haftungsbeschränkt) - * - * This source code is licensed under the MIT-style license found in the - * license.txt file in the root directory of this source tree. - * - * - * This file declares adapters for all MS-specific functions used throughout MafiaNet. - */ -#pragma once - -#ifdef __linux__ -#define _TRUNCATE ((size_t)-1) -typedef int errno_t; - -#include // for va_start, va_end, va_list -#include // for FILE -#include // for time_t - -// MS specific security enhanced functions -errno_t fopen_s(FILE **pfile, const char *filename, const char *mode); -errno_t localtime_s(struct tm* _tm, const time_t *time); -errno_t mbstowcs_s(size_t *pReturnValue, wchar_t *wcstr, size_t sizeInWords, const char *mbstr, size_t count); -int sprintf_s(char *buffer, size_t sizeOfBuffer, const char *format, ...); -errno_t strcat_s(char *strDestination, size_t numberOfElements, const char *strSource); -errno_t strcpy_s(char* strDestination, size_t numberOfElements, const char *strSource); -errno_t strerror_s(char* buffer, size_t numberOfElements, int errnum); -errno_t strncat_s(char *strDest, size_t numberOfElements, const char *strSource, size_t count); -errno_t strncpy_s(char *strDest, size_t numberOfElements, const char *strSource, size_t count); -int vsnprintf_s(char *buffer, size_t sizeOfBuffer, size_t count, const char *format, va_list argptr); -errno_t wcscat_s(wchar_t *strDestination, size_t numberOfElements, const wchar_t *strSource); -errno_t wcscpy_s(wchar_t* strDestination, size_t numberOfElements, const wchar_t *strSource); - -// corresponding template overloads -template errno_t mbstowcs_s(size_t *pReturnValue, wchar_t(&wcstr)[BufferSize], const char *mbstr, size_t count) -{ - return mbstowcs_s(pReturnValue, wcstr, BufferSize, mbstr, count); -} - -template int sprintf_s(char (&buffer)[BufferSize], const char* format, ...) -{ - va_list arglist; - va_start(arglist, format); - int numCharsWritten = vsnprintf_s(buffer, BufferSize, BufferSize - 1, format, arglist); - va_end(arglist); - - return numCharsWritten; -} - -template errno_t strcat_s(char (&strDestination)[BufferSize], const char* strSource) -{ - return strcat_s(strDestination, BufferSize, strSource); -} - -template errno_t strcpy_s(char (&strDestination)[BufferSize], const char* strSource) -{ - return strcpy_s(strDestination, BufferSize, strSource); -} - -template errno_t strerror_s(char(&buffer)[BufferSize], int errnum) -{ - return strerror_s(buffer, BufferSize, errnum); -} - -template errno_t strncat_s(char(&strDest)[BufferSize], const char *strSource, size_t count) -{ - return strncat_s(strDest, BufferSize, strSource, count); -} - -template errno_t strncpy_s(char(&strDest)[BufferSize], const char *strSource, size_t count) -{ - return strncpy_s(strDest, BufferSize, strSource, count); -} - -template int vsnprintf_s(char (&buffer)[BufferSize], size_t count, const char *format, va_list argptr) -{ - return vsnprintf_s(buffer, BufferSize, count, format, argptr); -} - -// MS gets_s function adapter - wraps MafiaNet's Gets function -// Note: Samples should include this header for gets_s support on Linux -#include "Gets.h" -template char* gets_s(char (&buffer)[BufferSize]) -{ - return Gets(buffer, static_cast(BufferSize)); -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/mafianet.h b/vendors/mafianet/Source/include/mafianet/mafianet.h deleted file mode 100644 index ce0cad77a..000000000 --- a/vendors/mafianet/Source/include/mafianet/mafianet.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2019, SLikeSoft UG (haftungsbeschraenkt) - * - * This source code is licensed under the MIT-style license found in the license.txt - * file in the root directory of this source tree. - */ - -/// \file mafianet.h -/// \brief Umbrella header aggregating the core public MafiaNet API. -/// -/// Include this single header to pull in the common client/server path: -/// \code -/// #include "mafianet/mafianet.h" -/// \endcode -/// -/// This is purely additive — the granular headers under "mafianet/" remain -/// available for advanced users who want fine-grained control over includes. -/// -/// \note Encryption headers are intentionally omitted. Connection security is -/// opt-in via RakPeerInterface::InitializeSecurity() (gated behind the -/// LIBCAT_SECURITY build define) and is not part of the common path. - -#pragma once - -#include "mafianet/peerinterface.h" // RakPeerInterface — main entry point -#include "mafianet/types.h" // Packet, SystemAddress, RakNetGUID, enums -#include "mafianet/MessageIdentifiers.h" // ID_* message IDs + ID_USER_PACKET_ENUM -#include "mafianet/PacketPriority.h" // MafiaNet::Priority / MafiaNet::Reliability -#include "mafianet/statistics.h" // RakNetStatistics — return type of GetStatistics() -#include "mafianet/BitStream.h" // binary serialization -#include "mafianet/GetTime.h" // MafiaNet::GetTime / TimeMS -#include "mafianet/guid_util.h" // MafiaNet::to_string / connected_address -#include "mafianet/aliases.h" // canonical aliases: PeerInterface, Guid, Statistics -#include "mafianet/PeerHandle.h" // RAII handles: Peer, PacketPtr diff --git a/vendors/mafianet/Source/include/mafianet/memoryoverride.h b/vendors/mafianet/Source/include/mafianet/memoryoverride.h deleted file mode 100644 index e8fb0dbd1..000000000 --- a/vendors/mafianet/Source/include/mafianet/memoryoverride.h +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief If _USE_RAK_MEMORY_OVERRIDE is defined, memory allocations go through rakMalloc, rakRealloc, and rakFree -/// - - - -#ifndef __RAK_MEMORY_H -#define __RAK_MEMORY_H - -#include "Export.h" -#include "defines.h" -#include - - - - - - - -#include "alloca.h" - -// #if _USE_RAK_MEMORY_OVERRIDE==1 -// #if defined(new) -// #pragma push_macro("new") -// #undef new -// #define RMO_NEW_UNDEF -// #endif -// #endif - - -// These pointers are statically and globally defined in RakMemoryOverride.cpp -// Change them to point to your own allocators if you want. -// Use the functions for a DLL, or just reassign the variable if using source -extern RAK_DLL_EXPORT void * (*rakMalloc) (size_t size); -extern RAK_DLL_EXPORT void * (*rakRealloc) (void *p, size_t size); -extern RAK_DLL_EXPORT void (*rakFree) (void *p); -extern RAK_DLL_EXPORT void * (*rakMalloc_Ex) (size_t size, const char *file, unsigned int line); -extern RAK_DLL_EXPORT void * (*rakRealloc_Ex) (void *p, size_t size, const char *file, unsigned int line); -extern RAK_DLL_EXPORT void (*rakFree_Ex) (void *p, const char *file, unsigned int line); -extern RAK_DLL_EXPORT void (*notifyOutOfMemory) (const char *file, const long line); -extern RAK_DLL_EXPORT void * (*dlMallocMMap) (size_t size); -extern RAK_DLL_EXPORT void * (*dlMallocDirectMMap) (size_t size); -extern RAK_DLL_EXPORT int (*dlMallocMUnmap) (void* ptr, size_t size); - -// Change to a user defined allocation function -void RAK_DLL_EXPORT SetMalloc( void* (*userFunction)(size_t size) ); -void RAK_DLL_EXPORT SetRealloc( void* (*userFunction)(void *p, size_t size) ); -void RAK_DLL_EXPORT SetFree( void (*userFunction)(void *p) ); -void RAK_DLL_EXPORT SetMalloc_Ex( void* (*userFunction)(size_t size, const char *file, unsigned int line) ); -void RAK_DLL_EXPORT SetRealloc_Ex( void* (*userFunction)(void *p, size_t size, const char *file, unsigned int line) ); -void RAK_DLL_EXPORT SetFree_Ex( void (*userFunction)(void *p, const char *file, unsigned int line) ); -// Change to a user defined out of memory function -void RAK_DLL_EXPORT SetNotifyOutOfMemory( void (*userFunction)(const char *file, const long line) ); -void RAK_DLL_EXPORT SetDLMallocMMap( void* (*userFunction)(size_t size) ); -void RAK_DLL_EXPORT SetDLMallocDirectMMap( void* (*userFunction)(size_t size) ); -void RAK_DLL_EXPORT SetDLMallocMUnmap( int (*userFunction)(void* ptr, size_t size) ); - -extern RAK_DLL_EXPORT void * (*GetMalloc()) (size_t size); -extern RAK_DLL_EXPORT void * (*GetRealloc()) (void *p, size_t size); -extern RAK_DLL_EXPORT void (*GetFree()) (void *p); -extern RAK_DLL_EXPORT void * (*GetMalloc_Ex()) (size_t size, const char *file, unsigned int line); -extern RAK_DLL_EXPORT void * (*GetRealloc_Ex()) (void *p, size_t size, const char *file, unsigned int line); -extern RAK_DLL_EXPORT void (*GetFree_Ex()) (void *p, const char *file, unsigned int line); -extern RAK_DLL_EXPORT void *(*GetDLMallocMMap())(size_t size); -extern RAK_DLL_EXPORT void *(*GetDLMallocDirectMMap())(size_t size); -extern RAK_DLL_EXPORT int (*GetDLMallocMUnmap())(void* ptr, size_t size); - -namespace MafiaNet -{ - - template - RAK_DLL_EXPORT Type* OP_NEW(const char *file, unsigned int line) - { -#if _USE_RAK_MEMORY_OVERRIDE==1 - char *buffer = (char *) (GetMalloc_Ex())(sizeof(Type), file, line); - Type *t = new (buffer) Type; - return t; -#else - (void) file; - (void) line; - return new Type; -#endif - } - - template - RAK_DLL_EXPORT Type* OP_NEW_1(const char *file, unsigned int line, const P1 &p1) - { -#if _USE_RAK_MEMORY_OVERRIDE==1 - char *buffer = (char *) (GetMalloc_Ex())(sizeof(Type), file, line); - Type *t = new (buffer) Type(p1); - return t; -#else - (void) file; - (void) line; - return new Type(p1); -#endif - } - - template - RAK_DLL_EXPORT Type* OP_NEW_2(const char *file, unsigned int line, const P1 &p1, const P2 &p2) - { -#if _USE_RAK_MEMORY_OVERRIDE==1 - char *buffer = (char *) (GetMalloc_Ex())(sizeof(Type), file, line); - Type *t = new (buffer) Type(p1, p2); - return t; -#else - (void) file; - (void) line; - return new Type(p1, p2); -#endif - } - - template - RAK_DLL_EXPORT Type* OP_NEW_3(const char *file, unsigned int line, const P1 &p1, const P2 &p2, const P3 &p3) - { -#if _USE_RAK_MEMORY_OVERRIDE==1 - char *buffer = (char *) (GetMalloc_Ex())(sizeof(Type), file, line); - Type *t = new (buffer) Type(p1, p2, p3); - return t; -#else - (void) file; - (void) line; - return new Type(p1, p2, p3); -#endif - } - - template - RAK_DLL_EXPORT Type* OP_NEW_4(const char *file, unsigned int line, const P1 &p1, const P2 &p2, const P3 &p3, const P4 &p4) - { -#if _USE_RAK_MEMORY_OVERRIDE==1 - char *buffer = (char *) (GetMalloc_Ex())(sizeof(Type), file, line); - Type *t = new (buffer) Type(p1, p2, p3, p4); - return t; -#else - (void) file; - (void) line; - return new Type(p1, p2, p3, p4); -#endif - } - - - template - RAK_DLL_EXPORT Type* OP_NEW_ARRAY(const int count, const char *file, unsigned int line) - { - if (count==0) - return 0; - -#if _USE_RAK_MEMORY_OVERRIDE==1 -// Type *t; - char *buffer = (char *) (GetMalloc_Ex())(sizeof(int)+sizeof(Type)*count, file, line); - ((int*)buffer)[0]=count; - for (int i=0; i - RAK_DLL_EXPORT void OP_DELETE(Type *buff, const char *file, unsigned int line) - { -#if _USE_RAK_MEMORY_OVERRIDE==1 - if (buff==0) return; - buff->~Type(); - (GetFree_Ex())((char*)buff, file, line ); -#else - (void) file; - (void) line; - delete buff; -#endif - - } - - template - RAK_DLL_EXPORT void OP_DELETE_ARRAY(Type *buff, const char *file, unsigned int line) - { -#if _USE_RAK_MEMORY_OVERRIDE==1 - if (buff==0) - return; - - int count = ((int*)((char*)buff-sizeof(int)))[0]; - Type *t; - for (int i=0; i~Type(); - } - (GetFree_Ex())((char*)buff-sizeof(int), file, line ); -#else - (void) file; - (void) line; - delete [] buff; -#endif - - } - - void RAK_DLL_EXPORT * _RakMalloc (size_t size); - void RAK_DLL_EXPORT * _RakRealloc (void *p, size_t size); - void RAK_DLL_EXPORT _RakFree (void *p); - void RAK_DLL_EXPORT * _RakMalloc_Ex (size_t size, const char *file, unsigned int line); - void RAK_DLL_EXPORT * _RakRealloc_Ex (void *p, size_t size, const char *file, unsigned int line); - void RAK_DLL_EXPORT _RakFree_Ex (void *p, const char *file, unsigned int line); - void RAK_DLL_EXPORT * _DLMallocMMap (size_t size); - void RAK_DLL_EXPORT * _DLMallocDirectMMap (size_t size); - int RAK_DLL_EXPORT _DLMallocMUnmap (void *p, size_t size); - -} - -// Call to make RakNet allocate a large block of memory, and do all subsequent allocations in that memory block -// Initial and reallocations will be done through whatever function is pointed to by yourMMapFunction, and yourDirectMMapFunction (default is malloc) -// Allocations will be freed through whatever function is pointed to by yourMUnmapFunction (default free) -void UseRaknetFixedHeap(size_t initialCapacity, - void * (*yourMMapFunction) (size_t size) = MafiaNet::_DLMallocMMap, - void * (*yourDirectMMapFunction) (size_t size) = MafiaNet::_DLMallocDirectMMap, - int (*yourMUnmapFunction) (void *p, size_t size) = MafiaNet::_DLMallocMUnmap); - -// Free memory allocated from UseRaknetFixedHeap -void FreeRakNetFixedHeap(void); - -// #if _USE_RAK_MEMORY_OVERRIDE==1 -// #if defined(RMO_NEW_UNDEF) -// #pragma pop_macro("new") -// #undef RMO_NEW_UNDEF -// #endif -// #endif - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/osx_adapter.h b/vendors/mafianet/Source/include/mafianet/osx_adapter.h deleted file mode 100644 index 1b0273b57..000000000 --- a/vendors/mafianet/Source/include/mafianet/osx_adapter.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2016-2019, SLikeSoft UG (haftungsbeschränkt) - * - * This source code is licensed under the MIT-style license found in the - * license.txt file in the root directory of this source tree. - * - * - * This file declares adapters for all MS-specific functions used throughout MafiaNet. - */ -#pragma once - -#ifdef __APPLE__ -#define _TRUNCATE ((size_t)-1) -typedef int errno_t; - -#include // for va_start, va_end, va_list -#include // for FILE -#include // for time_t - -// MS specific string functions -char *_strlwr(char *str); - -// MS specific security enhanced functions -errno_t fopen_s(FILE **pfile, const char *filename, const char *mode); -errno_t localtime_s(struct tm* _tm, const time_t *time); -errno_t mbstowcs_s(size_t *pReturnValue, wchar_t *wcstr, size_t sizeInWords, const char *mbstr, size_t count); -int sprintf_s(char *buffer, size_t sizeOfBuffer, const char *format, ...); -errno_t strcat_s(char *strDestination, size_t numberOfElements, const char *strSource); -errno_t strcpy_s(char* strDestination, size_t numberOfElements, const char *strSource); -errno_t strerror_s(char* buffer, size_t numberOfElements, int errnum); -errno_t strncat_s(char *strDest, size_t numberOfElements, const char *strSource, size_t count); -errno_t strncpy_s(char *strDest, size_t numberOfElements, const char *strSource, size_t count); -int vsnprintf_s(char *buffer, size_t sizeOfBuffer, size_t count, const char *format, va_list argptr); -errno_t wcscat_s(wchar_t *strDestination, size_t numberOfElements, const wchar_t *strSource); -errno_t wcscpy_s(wchar_t* strDestination, size_t numberOfElements, const wchar_t *strSource); - -// corresponding template overloads -template errno_t mbstowcs_s(size_t *pReturnValue, wchar_t(&wcstr)[BufferSize], const char *mbstr, size_t count) -{ - return mbstowcs_s(pReturnValue, wcstr, BufferSize, mbstr, count); -} - -template int sprintf_s(char (&buffer)[BufferSize], const char* format, ...) -{ - va_list arglist; - va_start(arglist, format); - int numCharsWritten = vsnprintf_s(buffer, BufferSize, BufferSize - 1, format, arglist); - va_end(arglist); - - return numCharsWritten; -} - -template errno_t strcat_s(char (&strDestination)[BufferSize], const char* strSource) -{ - return strcat_s(strDestination, BufferSize, strSource); -} - -template errno_t strcpy_s(char (&strDestination)[BufferSize], const char* strSource) -{ - return strcpy_s(strDestination, BufferSize, strSource); -} - -template errno_t strerror_s(char(&buffer)[BufferSize], int errnum) -{ - return strerror_s(buffer, BufferSize, errnum); -} - -template errno_t strncat_s(char (&strDest)[BufferSize], const char *strSource, size_t count) -{ - return strncat_s(strDest, BufferSize, strSource, count); -} - -template errno_t strncpy_s(char (&strDest)[BufferSize], const char *strSource, size_t count) -{ - return strncpy_s(strDest, BufferSize, strSource, count); -} - -template int vsnprintf_s(char (&buffer)[BufferSize], size_t count, const char *format, va_list argptr) -{ - return vsnprintf_s(buffer, BufferSize, count, format, argptr); -} - -// MS gets_s function adapter - wraps MafiaNet's Gets function -// Note: Samples should include this header for gets_s support on macOS -#include "Gets.h" -template char* gets_s(char (&buffer)[BufferSize]) -{ - return Gets(buffer, static_cast(BufferSize)); -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/peer.h b/vendors/mafianet/Source/include/mafianet/peer.h deleted file mode 100644 index fbc41666f..000000000 --- a/vendors/mafianet/Source/include/mafianet/peer.h +++ /dev/null @@ -1,1053 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Declares RakPeer class. -/// - - -// TODO - RakNet 4 - Add network simulator -// TODO - RakNet 4 - Enable disabling flow control per connections - -#ifndef __RAK_PEER_H -#define __RAK_PEER_H - -#include "ReliabilityLayer.h" -#include "peerinterface.h" -#include "BitStream.h" -#include "SingleProducerConsumer.h" -#include "SimpleMutex.h" -#include "DS_OrderedList.h" -#include "Export.h" -#include "string.h" -#include "thread.h" -//#include "socket.h" -#include "smartptr.h" -#include "DS_ThreadsafeAllocatingQueue.h" -#include "SignaledEvent.h" -#include "NativeFeatureIncludes.h" -#include "SecureHandshake.h" -#include "LocklessTypes.h" -#include "DS_Queue.h" - -namespace MafiaNet { -/// Forward declarations -class HuffmanEncodingTree; -class PluginInterface2; - -// Sucks but this struct has to be outside the class. Inside and DevCPP won't let you refer to the struct as RakPeer::RemoteSystemIndex while GCC -// forces you to do RakPeer::RemoteSystemIndex -struct RemoteSystemIndex{unsigned index; RemoteSystemIndex *next;}; -//int RAK_DLL_EXPORT SystemAddressAndIndexComp( const SystemAddress &key, const RemoteSystemIndex &data ); // GCC requires RakPeer::RemoteSystemIndex or it won't compile - -///\brief Main interface for network communications. -/// \details It implements most of RakNet's functionality and is the primary interface for RakNet. -/// -/// Inherits RakPeerInterface. -/// -/// See the individual functions for what the class can do. -/// -class RAK_DLL_EXPORT RakPeer : public RakPeerInterface, public RNS2EventHandler -{ -public: - ///Constructor - RakPeer(); - - ///Destructor - virtual ~RakPeer(); - - // --------------------------------------------------------------------------------------------Major Low Level Functions - Functions needed by most users-------------------------------------------------------------------------------------------- - /// \brief Starts the network threads and opens the listen port. - /// \details You must call this before calling Connect(). - /// \pre On the PS3, call Startup() after Client_Login() - /// \note Multiple calls while already active are ignored. To call this function again with different settings, you must first call Shutdown(). - /// \note Call SetMaximumIncomingConnections if you want to accept incoming connections. - /// \param[in] maxConnections Maximum number of connections between this instance of RakPeer and another instance of RakPeer. Required so that the network can preallocate and for thread safety. A pure client would set this to 1. A pure server would set it to the number of allowed clients.A hybrid would set it to the sum of both types of connections. - /// \param[in] localPort The port to listen for connections on. On linux the system may be set up so thast ports under 1024 are restricted for everything but the root user. Use a higher port for maximum compatibility. - /// \param[in] socketDescriptors An array of SocketDescriptor structures to force RakNet to listen on a particular IP address or port (or both). Each SocketDescriptor will represent one unique socket. Do not pass redundant structures. To listen on a specific port, you can pass SocketDescriptor(myPort,0); such as for a server. For a client, it is usually OK to just pass SocketDescriptor(); However, on the XBOX be sure to use IPPROTO_VDP - /// \param[in] socketDescriptorCount The size of the \a socketDescriptors array. Pass 1 if you are not sure what to pass. - /// \param[in] threadPriority Passed to the thread creation routine. Use THREAD_PRIORITY_NORMAL for Windows. For Linux based systems, you MUST pass something reasonable based on the thread priorities for your application. - /// \return RAKNET_STARTED on success, otherwise appropriate failure enumeration. - StartupResult Startup( unsigned int maxConnections, SocketDescriptor *socketDescriptors, unsigned socketDescriptorCount, int threadPriority=-99999 ); - - /// If you accept connections, you must call this or else security will not be enabled for incoming connections. - /// This feature requires more round trips, bandwidth, and CPU time for the connection handshake - /// x64 builds require under 25% of the CPU time of other builds - /// See the Encryption sample for example usage - /// \pre Must be called while offline - /// \pre LIBCAT_SECURITY must be defined to 1 in NativeFeatureIncludes.h for this function to have any effect - /// \param[in] publicKey A pointer to the public key for accepting new connections - /// \param[in] privateKey A pointer to the private key for accepting new connections - /// \param[in] bRequireClientKey: Should be set to false for most servers. Allows the server to accept a public key from connecting clients as a proof of identity but eats twice as much CPU time as a normal connection - bool InitializeSecurity( const char *publicKey, const char *privateKey, bool bRequireClientKey = false ); - - /// Disables security for incoming connections. - /// \note Must be called while offline - void DisableSecurity( void ); - - /// \brief This is useful if you have a fixed-address internal server behind a LAN. - /// - /// Secure connections are determined by the recipient of an incoming connection. This has no effect if called on the system attempting to connect. - /// \note If secure connections are on, do not use secure connections for a specific IP address. - /// \param[in] ip IP address to add. * wildcards are supported. - void AddToSecurityExceptionList(const char *ip); - - /// \brief Remove a specific connection previously added via AddToSecurityExceptionList. - /// \param[in] ip IP address to remove. Pass 0 to remove all IP addresses. * wildcards are supported. - void RemoveFromSecurityExceptionList(const char *ip); - - /// \brief Checks to see if a given IP is in the security exception list. - /// \param[in] IP address to check. - /// \return True if the IP address is found in security exception list, else returns false. - bool IsInSecurityExceptionList(const char *ip); - - /// \brief Sets the maximum number of incoming connections allowed. - /// \details If the number of incoming connections is less than the number of players currently connected, - /// no more players will be allowed to connect. If this is greater than the maximum number of peers allowed, - /// it will be reduced to the maximum number of peers allowed. - /// - /// Defaults to 0, meaning by default, nobody can connect to you - /// \param[in] numberAllowed Maximum number of incoming connections allowed. - void SetMaximumIncomingConnections( unsigned short numberAllowed ); - - /// \brief Returns the value passed to SetMaximumIncomingConnections(). - /// \return Maximum number of incoming connections, which is always <= maxConnections - unsigned int GetMaximumIncomingConnections( void ) const; - - /// \brief Returns how many open connections exist at this time. - /// \return Number of open connections. - unsigned short NumberOfConnections(void) const; - - /// \brief Sets the password for the incoming connections. - /// \details The password must match in the call to Connect (defaults to none). - /// Pass 0 to passwordData to specify no password. - /// This is a way to set a low level password for all incoming connections. To selectively reject connections, implement your own scheme using CloseConnection() to remove unwanted connections. - /// \param[in] passwordData A data block that incoming connections must match. This can be just a password, or can be a stream of data. Specify 0 for no password data - /// \param[in] passwordDataLength The length in bytes of passwordData - void SetIncomingPassword( const char* passwordData, int passwordDataLength ); - - /// \brief Gets the password passed to SetIncomingPassword - /// \param[out] passwordData Should point to a block large enough to hold the password data you passed to SetIncomingPassword() - /// \param[in,out] passwordDataLength Maximum size of the passwordData array. Modified to hold the number of bytes actually written. - void GetIncomingPassword( char* passwordData, int *passwordDataLength ); - - /// \brief Connect to the specified host (ip or domain name) and server port. - /// \details Calling Connect and not calling SetMaximumIncomingConnections acts as a dedicated client. - /// Calling both acts as a true peer. - /// - /// This is a non-blocking connection. - /// - /// The connection is successful when GetConnectionState() returns IS_CONNECTED or Receive() gets a message with the type identifier ID_CONNECTION_REQUEST_ACCEPTED. - /// If the connection is not successful, such as a rejected connection or no response then neither of these things will happen. - /// \pre Requires that you first call Startup(). - /// \param[in] host Either a dotted IP address or a domain name. - /// \param[in] remotePort Port to connect to on the remote machine. - /// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword(). This can be a string or can be a stream of data. Use 0 for no password. - /// \param[in] passwordDataLength The length in bytes of passwordData. - /// \param[in] publicKey The public key the server is using. If 0, the server is not using security. If non-zero, the publicKeyMode member determines how to connect - /// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to determine the one to send on. - /// \param[in] sendConnectionAttemptCount Number of datagrams to send to the other system to try to connect. - /// \param[in] timeBetweenSendConnectionAttemptsMS Time to elapse before a datagram is sent to the other system to try to connect. After sendConnectionAttemptCount number of attempts, ID_CONNECTION_ATTEMPT_FAILED is returned. Under low bandwidth conditions with multiple simultaneous outgoing connections, this value should be raised to 1000 or higher, or else the MTU detection can overrun the available bandwidth. - /// \param[in] timeoutTime Time to elapse before dropping the connection if a reliable message could not be sent. 0 to use the default value from SetTimeoutTime(UNASSIGNED_SYSTEM_ADDRESS); - /// \return CONNECTION_ATTEMPT_STARTED on successful initiation. Otherwise, an appropriate enumeration indicating failure. - /// \note CONNECTION_ATTEMPT_STARTED does not mean you are already connected! - /// \note It is possible to immediately get back ID_CONNECTION_ATTEMPT_FAILED if you exceed the maxConnections parameter passed to Startup(). This could happen if you call CloseConnection() with sendDisconnectionNotificaiton true, then immediately call Connect() before the connection has closed. - ConnectionAttemptResult Connect( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, PublicKey *publicKey=0, unsigned connectionSocketIndex=0, unsigned sendConnectionAttemptCount=6, unsigned timeBetweenSendConnectionAttemptsMS=1000, MafiaNet::TimeMS timeoutTime=0 ); - - /// \brief Connect to the specified host (ip or domain name) and server port. - /// \param[in] host Either a dotted IP address or a domain name. - /// \param[in] remotePort Which port to connect to on the remote machine. - /// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword(). This can be a string or can be a stream of data. Use 0 for no password. - /// \param[in] passwordDataLength The length in bytes of passwordData. - /// \param[in] socket A bound socket returned by another instance of RakPeerInterface. - /// \param[in] sendConnectionAttemptCount Number of datagrams to send to the other system to try to connect. - /// \param[in] timeBetweenSendConnectionAttemptsMS Time to elapse before a datagram is sent to the other system to try to connect. After sendConnectionAttemptCount number of attempts, ID_CONNECTION_ATTEMPT_FAILED is returned.. Under low bandwidth conditions with multiple simultaneous outgoing connections, this value should be raised to 1000 or higher, or else the MTU detection can overrun the available bandwidth. - /// \param[in] timeoutTime Time to elapse before dropping the connection if a reliable message could not be sent. 0 to use the default from SetTimeoutTime(UNASSIGNED_SYSTEM_ADDRESS); - /// \return CONNECTION_ATTEMPT_STARTED on successful initiation. Otherwise, an appropriate enumeration indicating failure. - /// \note CONNECTION_ATTEMPT_STARTED does not mean you are already connected! - virtual ConnectionAttemptResult ConnectWithSocket(const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, RakNetSocket2* socket, PublicKey *publicKey=0, unsigned sendConnectionAttemptCount=6, unsigned timeBetweenSendConnectionAttemptsMS=1000, MafiaNet::TimeMS timeoutTime=0); - - /* /// \brief Connect to the specified network ID (Platform specific console function) - /// \details Does built-in NAT traversal - /// \param[in] networkServiceId Network ID structure for the online service - /// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword(). This can be a string or can be a stream of data. Use 0 for no password. - /// \param[in] passwordDataLength The length in bytes of passwordData. - //bool Console2LobbyConnect( void *networkServiceId, const char *passwordData, int passwordDataLength );*/ - - /// \brief Stops the network threads and closes all connections. - /// \param[in] blockDuration Wait time(milli seconds) for all remaining messages to go out, including ID_DISCONNECTION_NOTIFICATION. If 0, it doesn't wait at all. - /// \param[in] orderingChannel Channel on which ID_DISCONNECTION_NOTIFICATION will be sent, if blockDuration > 0. - /// \param[in] disconnectionNotificationPriority Priority at which ID_DISCONNECTION_NOTIFICATION is sent. Note that a blockDuration of 0 means the threads stop without waiting for it to flush. - void Shutdown( unsigned int blockDuration, unsigned char orderingChannel=0, MafiaNet::Priority disconnectionNotificationPriority=MafiaNet::Priority::Low ); - - /// \brief Returns true if the network thread is running. - /// \return True if the network thread is running, False otherwise - bool IsActive( void ) const; - - /// \brief Fills the array remoteSystems with the SystemAddress of all the systems we are connected to. - /// \param[out] remoteSystems An array of SystemAddress structures, to be filled with the SystemAddresss of the systems we are connected to. Pass 0 to remoteSystems to get the number of systems we are connected to. - /// \param[in, out] numberOfSystems As input, the size of remoteSystems array. As output, the number of elements put into the array. - bool GetConnectionList( SystemAddress *remoteSystems, unsigned short *numberOfSystems ) const; - - /// Returns the next uint32_t that Send() will return - /// \note If using RakPeer from multiple threads, this may not be accurate for your thread. Use IncrementNextSendReceipt() in that case. - /// \return The next uint32_t that Send() or SendList will return - virtual uint32_t GetNextSendReceipt(void); - - /// Returns the next uint32_t that Send() will return, and increments the value by one - /// \note If using RakPeer from multiple threads, pass this to forceReceipt in the send function - /// \return The next uint32_t that Send() or SendList will return - virtual uint32_t IncrementNextSendReceipt(void); - - /// \brief Sends a block of data to the specified system that you are connected to. - /// \note This function only works while connected. - /// \note The first byte should be a message identifier starting at ID_USER_PACKET_ENUM. - /// \param[in] data Block of data to send. - /// \param[in] length Size in bytes of the data to send. - /// \param[in] priority Priority level to send on. See PacketPriority.h - /// \param[in] reliability How reliably to send this data. See PacketPriority.h - /// \param[in] orderingChannel When using ordered or sequenced messages, the channel to order these on. Messages are only ordered relative to other messages on the same stream. - /// \param[in] systemIdentifier Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none - /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. - /// \param[in] forceReceipt If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it. - /// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number - uint32_t Send( const char *data, const int length, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber=0 ); - - /// \brief "Send" to yourself rather than a remote system. - /// \details The message will be processed through the plugins and returned to the game as usual. - /// This function works anytime - /// \note The first byte should be a message identifier starting at ID_USER_PACKET_ENUM - /// \param[in] data Block of data to send. - /// \param[in] length Size in bytes of the data to send. - void SendLoopback( const char *data, const int length ); - - /// \brief Sends a block of data to the specified system that you are connected to. - /// - /// Same as the above version, but takes a BitStream as input. - /// \param[in] bitStream Bitstream to send - /// \param[in] priority Priority level to send on. See PacketPriority.h - /// \param[in] reliability How reliably to send this data. See PacketPriority.h - /// \param[in] orderingChannel Channel to order the messages on, when using ordered or sequenced messages. Messages are only ordered relative to other messages on the same stream. - /// \param[in] systemIdentifier System Address or RakNetGUID to send this packet to, or in the case of broadcasting, the address not to send it to. Use UNASSIGNED_SYSTEM_ADDRESS to specify none. - /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. - /// \param[in] forceReceipt If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it. - /// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number - /// \note COMMON MISTAKE: When writing the first byte, bitStream->Write((unsigned char) ID_MY_TYPE) be sure it is casted to a byte, and you are not writing a 4 byte enumeration. - uint32_t Send( const MafiaNet::BitStream * bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber=0 ); - - /// \brief Sends multiple blocks of data, concatenating them automatically. - /// - /// This is equivalent to: - /// MafiaNet::BitStream bs; - /// bs.WriteAlignedBytes(block1, blockLength1); - /// bs.WriteAlignedBytes(block2, blockLength2); - /// bs.WriteAlignedBytes(block3, blockLength3); - /// Send(&bs, ...) - /// - /// This function only works when connected. - /// \param[in] data An array of pointers to blocks of data - /// \param[in] lengths An array of integers indicating the length of each block of data - /// \param[in] numParameters Length of the arrays data and lengths - /// \param[in] priority Priority level to send on. See PacketPriority.h - /// \param[in] reliability How reliably to send this data. See PacketPriority.h - /// \param[in] orderingChannel Channel to order the messages on, when using ordered or sequenced messages. Messages are only ordered relative to other messages on the same stream. - /// \param[in] systemIdentifier System Address or RakNetGUID to send this packet to, or in the case of broadcasting, the address not to send it to. Use UNASSIGNED_SYSTEM_ADDRESS to specify none. - /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. - /// \param[in] forceReceipt If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it. - /// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number - uint32_t SendList( const char **data, const int *lengths, const int numParameters, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber=0 ); - - /// \brief Gets a message from the incoming message queue. - /// \details Use DeallocatePacket() to deallocate the message after you are done with it. - /// User-thread functions, such as RPC calls and the plugin function PluginInterface::Update occur here. - /// \return 0 if no packets are waiting to be handled, otherwise a pointer to a packet. - /// \note COMMON MISTAKE: Be sure to call this in a loop, once per game tick, until it returns 0. If you only process one packet per game tick they will buffer up. - /// \sa types.h contains struct Packet. - Packet* Receive( void ); - - /// \brief Call this to deallocate a message returned by Receive() when you are done handling it. - /// \param[in] packet Message to deallocate. - void DeallocatePacket( Packet *packet ); - - /// \brief Return the total number of connections we are allowed. - /// \return Total number of connections allowed. - unsigned int GetMaximumNumberOfPeers( void ) const; - - // -------------------------------------------------------------------------------------------- Connection Management Functions-------------------------------------------------------------------------------------------- - /// \brief Close the connection to another host (if we initiated the connection it will disconnect, if they did it will kick them out). - /// \details This method closes the connection irrespective of who initiated the connection. - /// \param[in] target Which system to close the connection to. - /// \param[in] sendDisconnectionNotification True to send ID_DISCONNECTION_NOTIFICATION to the recipient. False to close it silently. - /// \param[in] channel Which ordering channel to send the disconnection notification on, if any - /// \param[in] disconnectionNotificationPriority Priority to send ID_DISCONNECTION_NOTIFICATION on. - void CloseConnection( const AddressOrGUID target, bool sendDisconnectionNotification, unsigned char orderingChannel=0, MafiaNet::Priority disconnectionNotificationPriority=MafiaNet::Priority::Low, const MafiaNet::BitStream *reasonData=nullptr ); - - /// \brief Cancel a pending connection attempt. - /// \details If we are already connected, the connection stays open - /// \param[in] target Target system to cancel. - void CancelConnectionAttempt( const SystemAddress target ); - /// Returns if a system is connected, disconnected, connecting in progress, or various other states - /// \param[in] systemIdentifier The system we are referring to - /// \note This locks a mutex, do not call too frequently during connection attempts or the attempt will take longer and possibly even timeout - /// \return What state the remote system is in - ConnectionState GetConnectionState(const AddressOrGUID systemIdentifier); - - /// \brief Given \a systemAddress, returns its index into remoteSystemList. - /// \details Values range from 0 to the maximum number of players allowed - 1. - /// This includes systems which were formerly connected, but are now not connected. - /// \param[in] systemAddress The SystemAddress we are referring to - /// \return The index of this SystemAddress or -1 on system not found. - int GetIndexFromSystemAddress( const SystemAddress systemAddress ) const; - - /// \brief Given \a index into remoteSystemList, will return a SystemAddress. - /// This function is only useful for looping through all systems. - /// - /// \param[in] index Index should range between 0 and the maximum number of players allowed - 1. - /// \return The SystemAddress structure corresponding to \a index in remoteSystemList. - SystemAddress GetSystemAddressFromIndex( unsigned int index ); - - /// \brief Same as GetSystemAddressFromIndex but returns RakNetGUID - /// \param[in] index Index should range between 0 and the maximum number of players allowed - 1. - /// \return The RakNetGUID - RakNetGUID GetGUIDFromIndex( unsigned int index ); - - /// \brief Same as calling GetSystemAddressFromIndex and GetGUIDFromIndex for all systems, but more efficient - /// Indices match each other, so \a addresses[0] and \a guids[0] refer to the same system - /// \param[out] addresses All system addresses. Size of the list is the number of connections. Size of the \a addresses list will match the size of the \a guids list. - /// \param[out] guids All guids. Size of the list is the number of connections. Size of the list will match the size of the \a addresses list. - void GetSystemList(DataStructures::List &addresses, DataStructures::List &guids) const; - - /// \brief Bans an IP from connecting. - /// \details Banned IPs persist between connections but are not saved on shutdown nor loaded on startup. - /// \param[in] IP Dotted IP address. You can use * for a wildcard address, such as 128.0.0. * will ban all IP addresses starting with 128.0.0. - /// \param[in] milliseconds Gives time in milli seconds for a temporary ban of the IP address. Use 0 for a permanent ban. - void AddToBanList( const char *IP, MafiaNet::TimeMS milliseconds=0 ); - - /// \brief Allows a previously banned IP to connect. - /// param[in] Dotted IP address. You can use * as a wildcard. An IP such as 128.0.0.* will ban all IP addresses starting with 128.0.0. - void RemoveFromBanList( const char *IP ); - - /// \brief Allows all previously banned IPs to connect. - void ClearBanList( void ); - - /// \brief Returns true or false indicating if a particular IP is banned. - /// \param[in] IP Dotted IP address. - /// \return True if IP matches any IPs in the ban list, accounting for any wildcards. False otherwise. - bool IsBanned( const char *IP ); - - /// \brief Enable or disable allowing frequent connections from the same IP adderss - /// \details This is a security measure which is disabled by default, but can be set to true to prevent attackers from using up all connection slots. - /// \param[in] b True to limit connections from the same ip to at most 1 per 100 milliseconds. - void SetLimitIPConnectionFrequency(bool b); - - // --------------------------------------------------------------------------------------------Pinging Functions - Functions dealing with the automatic ping mechanism-------------------------------------------------------------------------------------------- - /// Send a ping to the specified connected system. - /// \pre The sender and recipient must already be started via a successful call to Startup() - /// \param[in] target Which system to ping - void Ping( const SystemAddress target ); - - /// \brief Send a ping to the specified unconnected system. - /// \details The remote system, if it is Initialized, will respond with ID_PONG followed by sizeof(MafiaNet::TimeMS) containing the system time the ping was sent. Default is 4 bytes - See __GET_TIME_64BIT in types.h - /// System should reply with ID_PONG if it is active - /// \param[in] host Either a dotted IP address or a domain name. Can be 255.255.255.255 for LAN broadcast. - /// \param[in] remotePort Which port to connect to on the remote machine. - /// \param[in] onlyReplyOnAcceptingConnections Only request a reply if the remote system is accepting connections - /// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on. - /// \return true on success, false on failure (unknown hostname) - bool Ping( const char* host, unsigned short remotePort, bool onlyReplyOnAcceptingConnections, unsigned connectionSocketIndex=0 ); - - /// \brief Returns the average of all ping times read for the specific system or -1 if none read yet - /// \param[in] systemAddress Which system we are referring to - /// \return The ping time for this system, or -1 - int GetAveragePing( const AddressOrGUID systemIdentifier ); - - /// \brief Returns the last ping time read for the specific system or -1 if none read yet. - /// \param[in] systemAddress Which system we are referring to - /// \return The last ping time for this system, or -1. - int GetLastPing( const AddressOrGUID systemIdentifier ) const; - - /// \brief Returns the lowest ping time read or -1 if none read yet. - /// \param[in] systemIdentifier Which system we are referring to - /// \return The lowest ping time for this system, or -1. - int GetLowestPing( const AddressOrGUID systemIdentifier ) const; - - /// Ping the remote systems every so often, or not. Can be called anytime. - /// By default this is true. Recommended to leave on, because congestion control uses it to determine how often to resend lost packets. - /// It would be true by default to prevent timestamp drift, since in the event of a clock spike, the timestamp deltas would no longer be accurate - /// \param[in] doPing True to start occasional pings. False to stop them. - void SetOccasionalPing( bool doPing ); - - /// Return the clock difference between your system and the specified system - /// Subtract GetClockDifferential() from a time returned by the remote system to get that time relative to your own system - /// Returns 0 if the system is unknown - /// \param[in] systemIdentifier Which system we are referring to - MafiaNet::Time GetClockDifferential( const AddressOrGUID systemIdentifier ); - - // --------------------------------------------------------------------------------------------Static Data Functions - Functions dealing with API defined synchronized memory-------------------------------------------------------------------------------------------- - /// \brief Sets the data to send along with a LAN server discovery or offline ping reply. - /// \param[in] data Block of data to send, or 0 for none - /// \param[in] length Length of the data in bytes, or 0 for none - /// \note \a length should be under 400 bytes, as a security measure against flood attacks - /// \sa Ping.cpp - void SetOfflinePingResponse( const char *data, const unsigned int length ); - - /// \brief Returns pointers to a copy of the \a data passed to SetOfflinePingResponse. - /// \param[out] data A pointer to a copy of the data passed to SetOfflinePingResponse() - /// \param[out] length A pointer filled in with the length parameter passed to SetOfflinePingResponse() - /// \sa SetOfflinePingResponse - void GetOfflinePingResponse( char **data, unsigned int *length ); - - //--------------------------------------------------------------------------------------------Network Functions - Functions dealing with the network in general-------------------------------------------------------------------------------------------- - /// \brief Returns the unique address identifier that represents you or another system on the the network - /// \note Not supported by the XBOX - /// \param[in] systemAddress Use UNASSIGNED_SYSTEM_ADDRESS to get your behind-LAN address. Use a connected system to get their behind-LAN address. This does not return the port. - /// \param[in] index When you have multiple internal IDs, which index to return? Currently limited to MAXIMUM_NUMBER_OF_INTERNAL_IDS (so the maximum value of this variable is MAXIMUM_NUMBER_OF_INTERNAL_IDS-1) - /// \return Identifier of your system internally, which may not be how other systems see if you if you are behind a NAT or proxy. - SystemAddress GetInternalID( const SystemAddress systemAddress=UNASSIGNED_SYSTEM_ADDRESS, const int index=0 ) const; - - /// \brief Sets your internal IP address, for platforms that do not support reading it, or to override a value - /// \param[in] systemAddress. The address to set. Use SystemAddress::FromString() if you want to use a dotted string - /// \param[in] index When you have multiple internal IDs, which index to set? - void SetInternalID(SystemAddress systemAddress, int index=0); - - /// \brief Returns the unique address identifier that represents the target on the the network and is based on the target's external IP / port. - /// \param[in] target The SystemAddress of the remote system. Usually the same for all systems, unless you have two or more network cards. - SystemAddress GetExternalID( const SystemAddress target ) const; - - /// Return my own GUID - const RakNetGUID GetMyGUID(void) const; - - /// Return the address bound to a socket at the specified index - SystemAddress GetMyBoundAddress(const int socketIndex=0); - - /// \brief Given a connected system address, this method gives the unique GUID representing that instance of RakPeer. - /// This will be the same on all systems connected to that instance of RakPeer, even if the external system addresses are different. - /// Complexity is O(log2(n)). - /// If \a input is UNASSIGNED_SYSTEM_ADDRESS, will return your own GUID - /// \pre Call Startup() first, or the function will return UNASSIGNED_RAKNET_GUID - /// \param[in] input The system address of the target system we are connected to. - const RakNetGUID& GetGuidFromSystemAddress( const SystemAddress input ) const; - - /// \brief Gives the system address of a connected system, given its GUID. - /// The GUID will be the same on all systems connected to that instance of RakPeer, even if the external system addresses are different. - /// Currently O(log(n)), but this may be improved in the future - /// If \a input is UNASSIGNED_RAKNET_GUID, UNASSIGNED_SYSTEM_ADDRESS is returned. - /// \param[in] input The RakNetGUID of the target system. - SystemAddress GetSystemAddressFromGuid( const RakNetGUID input ) const; - - /// Given the SystemAddress of a connected system, get the public key they provided as an identity - /// Returns false if system address was not found or client public key is not known - /// \param[in] input The RakNetGUID of the system - /// \param[in] client_public_key The connected client's public key is copied to this address. Buffer must be cat::EasyHandshake::PUBLIC_KEY_BYTES bytes in length. - bool GetClientPublicKeyFromSystemAddress( const SystemAddress input, char *client_public_key ) const; - - /// \brief Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable message. - - /// Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable message. - /// Default time is 10,000 or 10 seconds in release and 30,000 or 30 seconds in debug. - /// Do not set different values for different computers that are connected to each other, or you won't be able to reconnect after ID_CONNECTION_LOST - /// \param[in] timeMS Time, in MS - /// \param[in] target SystemAddress structure of the target system. Pass UNASSIGNED_SYSTEM_ADDRESS for all systems. - void SetTimeoutTime(MafiaNet::TimeMS timeMS, const SystemAddress target ); - - /// \brief Returns the Timeout time for the given system. - /// \param[in] target Target system to get the TimeoutTime for. Pass UNASSIGNED_SYSTEM_ADDRESS to get the default value. - /// \return Timeout time for a given system. - MafiaNet::TimeMS GetTimeoutTime( const SystemAddress target ); - - /// \brief Returns the current MTU size - /// \param[in] target Which system to get MTU for. UNASSIGNED_SYSTEM_ADDRESS to get the default - /// \return The current MTU size of the target system. - int GetMTUSize( const SystemAddress target ) const; - - /// \brief Returns the number of IP addresses this system has internally. - /// \details Get the actual addresses from GetLocalIP() - unsigned GetNumberOfAddresses( void ); - - /// Returns an IP address at index 0 to GetNumberOfAddresses-1 in ipList array. - /// \param[in] index index into the list of IP addresses - /// \return The local IP address at this index - const char* GetLocalIP( unsigned int index ); - - /// Is this a local IP? - /// Checks if this ip is in the ipList array. - /// \param[in] An IP address to check, excluding the port. - /// \return True if this is one of the IP addresses returned by GetLocalIP - bool IsLocalIP( const char *ip ); - - /// \brief Allow or disallow connection responses from any IP. - /// \details Normally this should be false, but may be necessary when connecting to servers with multiple IP addresses. - /// \param[in] allow - True to allow this behavior, false to not allow. Defaults to false. Value persists between connections. - void AllowConnectionResponseIPMigration( bool allow ); - - /// \brief Sends a one byte message ID_ADVERTISE_SYSTEM to the remote unconnected system. - /// This will send our external IP outside the LAN along with some user data to the remote system. - /// \pre The sender and recipient must already be started via a successful call to Initialize - /// \param[in] host Either a dotted IP address or a domain name - /// \param[in] remotePort Which port to connect to on the remote machine. - /// \param[in] data Optional data to append to the packet. - /// \param[in] dataLength Length of data in bytes. Use 0 if no data. - /// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on. - /// \return False if IsActive()==false or the host is unresolvable. True otherwise. - bool AdvertiseSystem( const char *host, unsigned short remotePort, const char *data, int dataLength, unsigned connectionSocketIndex=0 ); - - /// \brief Controls how often to return ID_DOWNLOAD_PROGRESS for large message downloads. - /// \details ID_DOWNLOAD_PROGRESS is returned to indicate a new partial message chunk, roughly the MTU size, has arrived. - /// As it can be slow or cumbersome to get this notification for every chunk, you can set the interval at which it is returned. - /// Defaults to 0 (never return this notification). - /// \param[in] interval How many messages to use as an interval before a download progress notification is returned. - void SetSplitMessageProgressInterval(int interval); - - /// \brief Returns what was passed to SetSplitMessageProgressInterval(). - /// \return Number of messages to be recieved before a download progress notification is returned. Default to 0. - int GetSplitMessageProgressInterval(void) const; - - /// \brief Set how long to wait before giving up on sending an unreliable message. - /// Useful if the network is clogged up. - /// Set to 0 or less to never timeout. Defaults to 0. - /// \param[in] timeoutMS How many ms to wait before simply not sending an unreliable message. - void SetUnreliableTimeout(MafiaNet::TimeMS timeoutMS); - - /// \brief Send a message to a host, with the IP socket option TTL set to 3. - /// \details This message will not reach the host, but will open the router. - /// \param[in] host The address of the remote host in dotted notation. - /// \param[in] remotePort The port number to send to. - /// \param[in] ttl Max hops of datagram, set to 3 - /// \param[in] connectionSocketIndex userConnectionSocketIndex. - /// \remarks Used for NAT-Punchthrough - void SendTTL( const char* host, unsigned short remotePort, int ttl, unsigned connectionSocketIndex=0 ); - - // -------------------------------------------------------------------------------------------- Plugin Functions-------------------------------------------------------------------------------------------- - /// \brief Attaches a Plugin interface to an instance of the base class (RakPeer or PacketizedTCP) to run code automatically on message receipt in the Receive call. - /// If the plugin returns false from PluginInterface::UsesReliabilityLayer(), which is the case for all plugins except PacketLogger, you can call AttachPlugin() and DetachPlugin() for this plugin while RakPeer is active. - /// \param[in] messageHandler Pointer to the plugin to attach. - void AttachPlugin( PluginInterface2 *plugin ); - - /// \brief Detaches a Plugin interface from the instance of the base class (RakPeer or PacketizedTCP) it is attached to. - /// \details This method disables the plugin code from running automatically on base class's updates or message receipt. - /// If the plugin returns false from PluginInterface::UsesReliabilityLayer(), which is the case for all plugins except PacketLogger, you can call AttachPlugin() and DetachPlugin() for this plugin while RakPeer is active. - /// \param[in] messageHandler Pointer to a plugin to detach. - void DetachPlugin( PluginInterface2 *messageHandler ); - - // --------------------------------------------------------------------------------------------Miscellaneous Functions-------------------------------------------------------------------------------------------- - /// \brief Puts a message back in the receive queue in case you don't want to deal with it immediately. - /// \param[in] packet The pointer to the packet you want to push back. - /// \param[in] pushAtHead True to push the packet at the start of the queue so that the next receive call returns it. False to push it at the end of the queue. - /// \note Setting pushAtHead to false end makes the packets out of order. - void PushBackPacket( Packet *packet, bool pushAtHead ); - - /// \internal - /// \brief For a given system identified by \a guid, change the SystemAddress to send to. - /// \param[in] guid The connection we are referring to - /// \param[in] systemAddress The new address to send to - void ChangeSystemAddress(RakNetGUID guid, const SystemAddress &systemAddress); - - /// \brief Returns a packet for you to write to if you want to create a Packet for some reason. - /// You can add it to the receive buffer with PushBackPacket - /// \param[in] dataSize How many bytes to allocate for the buffer - /// \return A packet. - Packet* AllocatePacket(unsigned dataSize); - - /// \brief Get the socket used with a particular active connection. - /// The smart pointer reference counts the RakNetSocket object, so the socket will remain active as long as the smart pointer does, even if RakNet were to shutdown or close the connection. - /// \note This sends a query to the thread and blocks on the return value for up to one second. In practice it should only take a millisecond or so. - /// \param[in] target Which system. - /// \return A smart pointer object containing the socket information about the target. Be sure to check IsNull() which is returned if the update thread is unresponsive, shutting down, or if this system is not connected. - virtual RakNetSocket2* GetSocket( const SystemAddress target ); - - /// \brief Gets all sockets in use. - /// \note This sends a query to the thread and blocks on the return value for up to one second. In practice it should only take a millisecond or so. - /// \param[out] sockets List of RakNetSocket structures in use. - virtual void GetSockets( DataStructures::List &sockets ); - virtual void ReleaseSockets( DataStructures::List &sockets ); - - /// \internal - virtual void WriteOutOfBandHeader(MafiaNet::BitStream *bitStream); - - /// If you need code to run in the same thread as RakNet's update thread, this function can be used for that - /// \param[in] _userUpdateThreadPtr C callback function - /// \param[in] _userUpdateThreadData Passed to C callback function - virtual void SetUserUpdateThread(void (*_userUpdateThreadPtr)(RakPeerInterface *, void *), void *_userUpdateThreadData); - - /// Set a C callback to be called whenever a datagram arrives - /// Return true from the callback to have RakPeer handle the datagram. Return false and RakPeer will ignore the datagram. - /// This can be used to filter incoming datagrams by system, or to share a recvfrom socket with RakPeer - /// RNS2RecvStruct will only remain valid for the duration of the call - virtual void SetIncomingDatagramEventHandler( bool (*_incomingDatagramEventHandler)(RNS2RecvStruct *) ); - - // --------------------------------------------------------------------------------------------Network Simulator Functions-------------------------------------------------------------------------------------------- - /// Adds simulated ping and packet loss to the outgoing data flow. - /// To simulate bi-directional ping and packet loss, you should call this on both the sender and the recipient, with half the total ping and packetloss value on each. - /// You can exclude network simulator code with the _RELEASE #define to decrease code size - /// \deprecated Use http://www.jenkinssoftware.com/forum/index.php?topic=1671.0 instead. - /// \note Doesn't work past version 3.6201 - /// \param[in] packetloss Chance to lose a packet. Ranges from 0 to 1. - /// \param[in] minExtraPing The minimum time to delay sends. - /// \param[in] extraPingVariance The additional random time to delay sends. - virtual void ApplyNetworkSimulator( float packetloss, unsigned short minExtraPing, unsigned short extraPingVariance); - - /// Limits how much outgoing bandwidth can be sent per-connection. - /// This limit does not apply to the sum of all connections! - /// Exceeding the limit queues up outgoing traffic - /// \param[in] maxBitsPerSecond Maximum bits per second to send. Use 0 for unlimited (default). Once set, it takes effect immedately and persists until called again. - virtual void SetPerConnectionOutgoingBandwidthLimit( unsigned maxBitsPerSecond ); - - /// Returns if you previously called ApplyNetworkSimulator - /// \return If you previously called ApplyNetworkSimulator - virtual bool IsNetworkSimulatorActive( void ); - - // --------------------------------------------------------------------------------------------Statistical Functions - Functions dealing with API performance-------------------------------------------------------------------------------------------- - - /// \brief Returns a structure containing a large set of network statistics for the specified system. - /// You can map this data to a string using the C style StatisticsToString() function - /// \param[in] systemAddress Which connected system to get statistics for. - /// \param[in] rns If you supply this structure,the network statistics will be written to it. Otherwise the method uses a static struct to write the data, which is not threadsafe. - /// \return 0 if the specified system can't be found. Otherwise a pointer to the struct containing the specified system's network statistics. - /// \sa statistics.h - RakNetStatistics * GetStatistics( const SystemAddress systemAddress, RakNetStatistics *rns=0 ); - /// \brief Returns the network statistics of the system at the given index in the remoteSystemList. - /// \return True if the index is less than the maximum number of peers allowed and the system is active. False otherwise. - bool GetStatistics( const unsigned int index, RakNetStatistics *rns ); - /// \brief Returns the list of systems, and statistics for each of those systems - /// Each system has one entry in each of the lists, in the same order - /// \param[out] addresses SystemAddress for each connected system - /// \param[out] guids RakNetGUID for each connected system - /// \param[out] statistics Calculated RakNetStatistics for each connected system - virtual void GetStatisticsList(DataStructures::List &addresses, DataStructures::List &guids, DataStructures::List &statistics); - - /// \Returns how many messages are waiting when you call Receive() - virtual unsigned int GetReceiveBufferSize(void); - - // --------------------------------------------------------------------------------------------EVERYTHING AFTER THIS COMMENT IS FOR INTERNAL USE ONLY-------------------------------------------------------------------------------------------- - - - /// \internal - // Call manually if RAKPEER_USER_THREADED==1 at least every 30 milliseconds. - // updateBitStream should be: - // BitStream updateBitStream( MAXIMUM_MTU_SIZE - // #if LIBCAT_SECURITY==1 - // + cat::AuthenticatedEncryption::OVERHEAD_BYTES - // #endif - // ); - bool RunUpdateCycle( BitStream &updateBitStream ); - - /// \internal - // Call manually if RAKPEER_USER_THREADED==1 at least every 30 milliseconds. - // Call in a loop until returns false if the socket is non-blocking - // remotePortRakNetWasStartedOn_PS3 and extraSocketOptions are from SocketDescriptor when the socket was created - // bool RunRecvFromOnce( RakNetSocket *s ); - - /// \internal - bool SendOutOfBand(const char *host, unsigned short remotePort, const char *data, BitSize_t dataLength, unsigned connectionSocketIndex=0 ); - - // static Packet *AllocPacket(unsigned dataSize, const char *file, unsigned int line); - - /// \internal - /// \brief Holds the clock differences between systems, along with the ping - struct PingAndClockDifferential - { - unsigned short pingTime; - MafiaNet::Time clockDifferential; - }; - - /// \internal - /// \brief All the information representing a connected system - struct RemoteSystemStruct - { - bool isActive; // Is this structure in use? - SystemAddress systemAddress; /// Their external IP on the internet - SystemAddress myExternalSystemAddress; /// Your external IP on the internet, from their perspective - SystemAddress theirInternalSystemAddress[MAXIMUM_NUMBER_OF_INTERNAL_IDS]; /// Their internal IP, behind the LAN - ReliabilityLayer reliabilityLayer; /// The reliability layer associated with this player - bool weInitiatedTheConnection; /// True if we started this connection via Connect. False if someone else connected to us. - PingAndClockDifferential pingAndClockDifferential[ PING_TIMES_ARRAY_SIZE ]; /// last x ping times and calculated clock differentials with it - MafiaNet::Time pingAndClockDifferentialWriteIndex; /// The index we are writing into the pingAndClockDifferential circular buffer - unsigned short lowestPing; ///The lowest ping value encountered - MafiaNet::Time nextPingTime; /// When to next ping this player - MafiaNet::Time lastReliableSend; /// When did the last reliable send occur. Reliable sends must occur at least once every timeoutTime/2 units to notice disconnects - MafiaNet::Time connectionTime; /// connection time, if active. -// int connectionSocketIndex; // index into connectionSockets to send back on. - RakNetGUID guid; - int MTUSize; - // Reference counted socket to send back on - RakNetSocket2* rakNetSocket; - SystemIndex remoteSystemIndex; - - // Optional disconnect-reason payload received with an incoming ID_DISCONNECTION_NOTIFICATION. The payload is - // stashed here when the notification arrives and copied into the user-facing notification packet that is - // synthesized after outstanding ACKs are flushed (the raw reliability-layer buffer is freed in between, so it - // cannot be delivered directly). null/0 when the remote sent no reason. Owned by this struct; copied out at - // delivery and freed via ClearDisconnectReason() on every slot teardown (including the immediate close that - // directly follows delivery) and on slot reuse. - unsigned char* disconnectReasonData; - unsigned int disconnectReasonLength; - -#if LIBCAT_SECURITY==1 - // Cached answer used internally by RakPeer to prevent DoS attacks based on the connexion handshake - char answer[cat::EasyHandshake::ANSWER_BYTES]; - - // If the server has bRequireClientKey = true, then this is set to the validated public key of the connected client - // Valid after connectMode reaches HANDLING_CONNECTION_REQUEST - char client_public_key[cat::EasyHandshake::PUBLIC_KEY_BYTES]; -#endif - - enum ConnectMode {NO_ACTION, DISCONNECT_ASAP, DISCONNECT_ASAP_SILENTLY, DISCONNECT_ON_NO_ACK, REQUESTED_CONNECTION, HANDLING_CONNECTION_REQUEST, UNVERIFIED_SENDER, CONNECTED} connectMode; - }; - - // DS_APR - //void ProcessChromePacket(RakNetSocket2 *s, const char *buffer, int dataSize, const SystemAddress& recvFromAddress, MafiaNet::TimeUS timeRead); - // /DS_APR -protected: - - friend RAK_THREAD_DECLARATION(UpdateNetworkLoop); - //friend RAK_THREAD_DECLARATION(RecvFromLoop); - friend RAK_THREAD_DECLARATION(UDTConnect); - - friend bool ProcessOfflineNetworkPacket( SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNetSocket2* rakNetSocket, bool *isOfflineMessage, MafiaNet::TimeUS timeRead ); - friend void ProcessNetworkPacket( const SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, MafiaNet::TimeUS timeRead, BitStream &updateBitStream ); - friend void ProcessNetworkPacket( const SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNetSocket2* rakNetSocket, MafiaNet::TimeUS timeRead, BitStream &updateBitStream ); - - int GetIndexFromSystemAddress( const SystemAddress systemAddress, bool calledFromNetworkThread ) const; - int GetIndexFromGuid( const RakNetGUID guid ); - - //void RemoveFromRequestedConnectionsList( const SystemAddress systemAddress ); - // Two versions needed because some buggy compilers strip the last parameter if unused, and crashes - ConnectionAttemptResult SendConnectionRequest( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, PublicKey *publicKey, unsigned connectionSocketIndex, unsigned int extraData, unsigned sendConnectionAttemptCount, unsigned timeBetweenSendConnectionAttemptsMS, MafiaNet::TimeMS timeoutTime, RakNetSocket2* socket ); - ConnectionAttemptResult SendConnectionRequest( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, PublicKey *publicKey, unsigned connectionSocketIndex, unsigned int extraData, unsigned sendConnectionAttemptCount, unsigned timeBetweenSendConnectionAttemptsMS, MafiaNet::TimeMS timeoutTime ); - ///Get the reliability layer associated with a systemAddress. - /// \param[in] systemAddress The player identifier - /// \return 0 if none - RemoteSystemStruct *GetRemoteSystemFromSystemAddress( const SystemAddress systemAddress, bool calledFromNetworkThread, bool onlyActive ) const; - RakPeer::RemoteSystemStruct *GetRemoteSystem( const AddressOrGUID systemIdentifier, bool calledFromNetworkThread, bool onlyActive ) const; - void ValidateRemoteSystemLookup(void) const; - RemoteSystemStruct *GetRemoteSystemFromGUID( const RakNetGUID guid, bool onlyActive ) const; - ///Parse out a connection request packet - void ParseConnectionRequestPacket( RakPeer::RemoteSystemStruct *remoteSystem, const SystemAddress &systemAddress, const char *data, int byteSize); - void OnConnectionRequest( RakPeer::RemoteSystemStruct *remoteSystem, MafiaNet::Time incomingTimestamp ); - ///Send a reliable disconnect packet to this player and disconnect them when it is delivered - void NotifyAndFlagForShutdown( const SystemAddress systemAddress, bool performImmediate, unsigned char orderingChannel, MafiaNet::Priority disconnectionNotificationPriority, const MafiaNet::BitStream *reasonData=nullptr ); - ///Returns how many remote systems initiated a connection to us - unsigned int GetNumberOfRemoteInitiatedConnections( void ) const; - /// \brief Get a free remote system from the list and assign our systemAddress to it. - /// \note Should only be called from the update thread - not the user thread. - /// \param[in] systemAddress systemAddress to be assigned - /// \param[in] connectionMode connection mode of the RemoteSystem. - /// \param[in] rakNetSocket - /// \param[in] thisIPConnectedRecently Is this IP connected recently? set to False; - /// \param[in] bindingAddress Address to be binded with the remote system - /// \param[in] incomingMTU MTU for the remote system - RemoteSystemStruct * AssignSystemAddressToRemoteSystemList( const SystemAddress systemAddress, RemoteSystemStruct::ConnectMode connectionMode, RakNetSocket2* incomingRakNetSocket, bool *thisIPConnectedRecently, SystemAddress bindingAddress, int incomingMTU, RakNetGUID guid, bool useSecurity ); - /// \brief Adjust the timestamp of the incoming packet to be relative to this system. - /// \param[in] data Data in the incoming packet. - /// \param[in] systemAddress Sender of the incoming packet. - void ShiftIncomingTimestamp( unsigned char *data, const SystemAddress &systemAddress ) const; - /// Get the most accurate clock differential for a certain player. - /// \param[in] systemAddress The player with whose clock the time difference is calculated. - /// \returns The clock differential for a certain player. - MafiaNet::Time GetBestClockDifferential( const SystemAddress systemAddress ) const; - - bool IsLoopbackAddress(const AddressOrGUID &systemIdentifier, bool matchPort) const; - SystemAddress GetLoopbackAddress(void) const; - - ///Set this to true to terminate the Peer thread execution - volatile bool endThreads; - ///true if the peer thread is active. - volatile bool isMainLoopThreadActive; - - // MafiaNet::LocklessUint32_t isRecvFromLoopThreadActive; - - - bool occasionalPing; /// Do we occasionally ping the other systems?*/ - ///Store the maximum number of peers allowed to connect - unsigned int maximumNumberOfPeers; - //05/02/06 Just using maximumNumberOfPeers instead - ///Store the maximum number of peers able to connect, including reserved connection slots for pings, etc. - //unsigned short remoteSystemListSize; - ///Store the maximum incoming connection allowed - unsigned int maximumIncomingConnections; - MafiaNet::BitStream offlinePingResponse; - ///Local Player ID - // SystemAddress mySystemAddress[MAXIMUM_NUMBER_OF_INTERNAL_IDS]; - char incomingPassword[256]; - unsigned char incomingPasswordLength; - - /// This is an array of pointers to RemoteSystemStruct - /// This allows us to preallocate the list when starting, so we don't have to allocate or delete at runtime. - /// Another benefit is that is lets us add and remove active players simply by setting systemAddress - /// and moving elements in the list by copying pointers variables without affecting running threads, even if they are in the reliability layer - RemoteSystemStruct* remoteSystemList; - /// activeSystemList holds a list of pointers and is preallocated to be the same size as remoteSystemList. It is updated only by the network thread, but read by both threads - /// When the isActive member of RemoteSystemStruct is set to true or false, that system is added to this list of pointers - /// Threadsafe because RemoteSystemStruct is preallocated, and the list is only added to, not removed from - RemoteSystemStruct** activeSystemList; - unsigned int activeSystemListSize; - - // Use a hash, with binaryAddress plus port mod length as the index - RemoteSystemIndex **remoteSystemLookup; - unsigned int RemoteSystemLookupHashIndex(const SystemAddress &sa) const; - void ReferenceRemoteSystem(const SystemAddress &sa, unsigned int remoteSystemListIndex); - void DereferenceRemoteSystem(const SystemAddress &sa); - RemoteSystemStruct* GetRemoteSystem(const SystemAddress &sa) const; - unsigned int GetRemoteSystemIndex(const SystemAddress &sa) const; - void ClearRemoteSystemLookup(void); - DataStructures::MemoryPool remoteSystemIndexPool; - - void AddToActiveSystemList(unsigned int remoteSystemListIndex); - void RemoveFromActiveSystemList(const SystemAddress &sa); - -// unsigned int LookupIndexUsingHashIndex(const SystemAddress &sa) const; -// unsigned int RemoteSystemListIndexUsingHashIndex(const SystemAddress &sa) const; -// unsigned int FirstFreeRemoteSystemLookupIndex(const SystemAddress &sa) const; - - enum - { - // Only put these mutexes in user thread functions! - requestedConnectionList_Mutex, - offlinePingResponse_Mutex, - NUMBER_OF_RAKPEER_MUTEXES - }; - SimpleMutex rakPeerMutexes[ NUMBER_OF_RAKPEER_MUTEXES ]; - ///RunUpdateCycle is not thread safe but we don't need to mutex calls. Just skip calls if it is running already - - bool updateCycleIsRunning; - ///The list of people we have tried to connect to recently - - //DataStructures::Queue requestedConnectionsList; - ///Data that both the client and the server needs - - unsigned int bytesSentPerSecond, bytesReceivedPerSecond; - // bool isSocketLayerBlocking; - // bool continualPing,isRecvfromThreadActive,isMainLoopThreadActive, endThreads, isSocketLayerBlocking; - unsigned int validationInteger; - SimpleMutex incomingQueueMutex, banListMutex; //,synchronizedMemoryQueueMutex, automaticVariableSynchronizationMutex; - //DataStructures::Queue incomingpacketSingleProducerConsumer; //, synchronizedMemorypacketSingleProducerConsumer; - // BitStream enumerationData; - - struct BanStruct - { - char *IP; - MafiaNet::TimeMS timeout; // 0 for none - }; - - struct RequestedConnectionStruct - { - SystemAddress systemAddress; - MafiaNet::Time nextRequestTime; - unsigned char requestsMade; - char *data; - unsigned short dataLength; - char outgoingPassword[256]; - unsigned char outgoingPasswordLength; - unsigned socketIndex; - unsigned int extraData; - unsigned sendConnectionAttemptCount; - unsigned timeBetweenSendConnectionAttemptsMS; - MafiaNet::TimeMS timeoutTime; - PublicKeyMode publicKeyMode; - RakNetSocket2* socket; - enum {CONNECT=1, /*PING=2, PING_OPEN_CONNECTIONS=4,*/ /*ADVERTISE_SYSTEM=2*/} actionToTake; - -#if LIBCAT_SECURITY==1 - char handshakeChallenge[cat::EasyHandshake::CHALLENGE_BYTES]; - cat::ClientEasyHandshake *client_handshake; - char remote_public_key[cat::EasyHandshake::PUBLIC_KEY_BYTES]; -// char remote_challenge[cat::EasyHandshake::CHALLENGE_BYTES]; - // char random[16]; -#endif - }; -#if LIBCAT_SECURITY==1 - bool GenerateConnectionRequestChallenge(RequestedConnectionStruct *rcs,PublicKey *publicKey); -#endif - - //DataStructures::List* > automaticVariableSynchronizationList; - DataStructures::List banList; - // Threadsafe, and not thread safe - DataStructures::List pluginListTS, pluginListNTS; - - DataStructures::Queue requestedConnectionQueue; - SimpleMutex requestedConnectionQueueMutex; - - // void RunMutexedUpdateCycle(void); - - struct BufferedCommandStruct - { - BitSize_t numberOfBitsToSend; - MafiaNet::Priority priority; - MafiaNet::Reliability reliability; - char orderingChannel; - AddressOrGUID systemIdentifier; - bool broadcast; - RemoteSystemStruct::ConnectMode connectionMode; - NetworkID networkID; - bool blockingCommand; // Only used for RPC - char *data; - bool haveRakNetCloseSocket; - unsigned connectionSocketIndex; - unsigned short remotePortRakNetWasStartedOn_PS3; - unsigned int extraSocketOptions; - RakNetSocket2* socket; - unsigned short port; - uint32_t receipt; - enum {BCS_SEND, BCS_CLOSE_CONNECTION, BCS_GET_SOCKET, BCS_CHANGE_SYSTEM_ADDRESS,/* BCS_USE_USER_SOCKET, BCS_REBIND_SOCKET_ADDRESS, BCS_RPC, BCS_RPC_SHIFT,*/ BCS_DO_NOTHING} command; - }; - - // Single producer single consumer queue using a linked list - //BufferedCommandStruct* bufferedCommandReadIndex, bufferedCommandWriteIndex; - - DataStructures::ThreadsafeAllocatingQueue bufferedCommands; - - - // DataStructures::ThreadsafeAllocatingQueue bufferedPackets; - - DataStructures::Queue bufferedPacketsFreePool; - MafiaNet::SimpleMutex bufferedPacketsFreePoolMutex; - DataStructures::Queue bufferedPacketsQueue; - MafiaNet::SimpleMutex bufferedPacketsQueueMutex; - - virtual void DeallocRNS2RecvStruct(RNS2RecvStruct *s, const char *file, unsigned int line); - virtual RNS2RecvStruct *AllocRNS2RecvStruct(const char *file, unsigned int line); - void SetupBufferedPackets(void); - void PushBufferedPacket(RNS2RecvStruct * p); - RNS2RecvStruct *PopBufferedPacket(void); - - struct SocketQueryOutput - { - SocketQueryOutput() {} - ~SocketQueryOutput() {} - DataStructures::List sockets; - }; - - DataStructures::ThreadsafeAllocatingQueue socketQueryOutput; - - - bool AllowIncomingConnections(void) const; - - void PingInternal( const SystemAddress target, bool performImmediate, MafiaNet::Reliability reliability ); - // This stores the user send calls to be handled by the update thread. This way we don't have thread contention over systemAddresss - void CloseConnectionInternal( const AddressOrGUID& systemIdentifier, bool sendDisconnectionNotification, bool performImmediate, unsigned char orderingChannel, MafiaNet::Priority disconnectionNotificationPriority ); - void SendBuffered( const char *data, BitSize_t numberOfBitsToSend, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, RemoteSystemStruct::ConnectMode connectionMode, uint32_t receipt ); - void SendBufferedList( const char **data, const int *lengths, const int numParameters, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, RemoteSystemStruct::ConnectMode connectionMode, uint32_t receipt ); - bool SendImmediate( char *data, BitSize_t numberOfBitsToSend, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, bool useCallerDataAllocation, MafiaNet::TimeUS currentTime, uint32_t receipt ); - //bool HandleBufferedRPC(BufferedCommandStruct *bcs, MafiaNet::TimeMS time); - void ClearBufferedCommands(void); - void ClearBufferedPackets(void); - void ClearSocketQueryOutput(void); - void ClearRequestedConnectionList(void); - void AddPacketToProducer(MafiaNet::Packet *p); - unsigned int GenerateSeedFromGuid(void); - MafiaNet::Time GetClockDifferentialInt(RemoteSystemStruct *remoteSystem) const; - SimpleMutex securityExceptionMutex; - - //DataStructures::AVLBalancedBinarySearchTree rpcTree; - int defaultMTUSize; - bool trackFrequencyTable; - - // Smart pointer so I can return the object to the user - DataStructures::List socketList; - void DerefAllSockets(void); - unsigned int GetRakNetSocketFromUserConnectionSocketIndex(unsigned int userIndex) const; - // Used for RPC replies - MafiaNet::BitStream *replyFromTargetBS; - SystemAddress replyFromTargetPlayer; - bool replyFromTargetBroadcast; - - MafiaNet::TimeMS defaultTimeoutTime; - - // Generate and store a unique GUID - void GenerateGUID(void); - unsigned int GetSystemIndexFromGuid( const RakNetGUID input ) const; - RakNetGUID myGuid; - - unsigned maxOutgoingBPS; - - // Nobody would use the internet simulator in a final build. -#ifdef _DEBUG - double _packetloss; - unsigned short _minExtraPing, _extraPingVariance; -#endif - - ///How long it has been since things were updated by a call to receiveUpdate thread uses this to determine how long to sleep for - //unsigned int lastUserUpdateCycle; - /// True to allow connection accepted packets from anyone. False to only allow these packets from servers we requested a connection to. - bool allowConnectionResponseIPMigration; - - SystemAddress firstExternalID; - int splitMessageProgressInterval; - MafiaNet::TimeMS unreliableTimeout; - - bool (*incomingDatagramEventHandler)(RNS2RecvStruct *); - - // Systems in this list will not go through the secure connection process, even when secure connections are turned on. Wildcards are accepted. - DataStructures::List securityExceptionList; - - SystemAddress ipList[ MAXIMUM_NUMBER_OF_INTERNAL_IDS ]; - - bool allowInternalRouting; - - void (*userUpdateThreadPtr)(RakPeerInterface *, void *); - void *userUpdateThreadData; - - - SignaledEvent quitAndDataEvents; - bool limitConnectionFrequencyFromTheSameIP; - - SimpleMutex packetAllocationPoolMutex; - DataStructures::MemoryPool packetAllocationPool; - - SimpleMutex packetReturnMutex; - DataStructures::Queue packetReturnQueue; - Packet *AllocPacket(unsigned dataSize, const char *file, unsigned int line); - Packet *AllocPacket(unsigned dataSize, unsigned char *data, const char *file, unsigned int line); - - /// This is used to return a number to the user when they call Send identifying the message - /// This number will be returned back with ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS and is only returned - /// with the reliability types that contain RECEIPT in the name - SimpleMutex sendReceiptSerialMutex; - uint32_t sendReceiptSerial; - void ResetSendReceipt(void); - void OnConnectedPong(MafiaNet::Time sendPingTime, MafiaNet::Time sendPongTime, RemoteSystemStruct *remoteSystem); - void CallPluginCallbacks(DataStructures::List &pluginList, Packet *packet); - -#if LIBCAT_SECURITY==1 - // Encryption and security - bool _using_security, _require_client_public_key; - char my_public_key[cat::EasyHandshake::PUBLIC_KEY_BYTES]; - cat::ServerEasyHandshake *_server_handshake; - cat::CookieJar *_cookie_jar; - bool InitializeClientSecurity(RequestedConnectionStruct *rcs, const char *public_key); -#endif - - - - - - - virtual void OnRNS2Recv(RNS2RecvStruct *recvStruct); - void FillIPList(void); - - private: - // internal helpers - void CloseConnectionInternal2(const AddressOrGUID& systemIdentifier, bool sendDisconnectionNotification, bool performImmediate, unsigned char orderingChannel, MafiaNet::Priority disconnectionNotificationPriority, RakNetSocket2& socket, const MafiaNet::BitStream *reasonData=nullptr); - // Free and null any stashed disconnect-reason payload for the given remote system (safe on null). - void ClearDisconnectReason(RemoteSystemStruct *remoteSystem); -} -// #if defined(SN_TARGET_PSP2) -// __attribute__((aligned(8))) -// #endif -; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/peerinterface.h b/vendors/mafianet/Source/include/mafianet/peerinterface.h deleted file mode 100644 index e759bd8b0..000000000 --- a/vendors/mafianet/Source/include/mafianet/peerinterface.h +++ /dev/null @@ -1,627 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief An interface for RakPeer. Simply contains all user functions as pure virtuals. -/// - - - -#ifndef __RAK_PEER_INTERFACE_H -#define __RAK_PEER_INTERFACE_H - -#include "PacketPriority.h" -#include "types.h" -#include "memoryoverride.h" -#include "Export.h" -#include "DS_List.h" -#include "smartptr.h" -#include "socket2.h" - -namespace MafiaNet -{ -// Forward declarations -class BitStream; -class PluginInterface2; -struct RPCMap; -struct RakNetStatistics; -struct RakNetBandwidth; -class RouterInterface; -class NetworkIDManager; - -/// The primary interface for RakNet, RakPeer contains all major functions for the library. -/// See the individual functions for what the class can do. -/// \brief The main interface for network communications -class RAK_DLL_EXPORT RakPeerInterface -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(RakPeerInterface) - - ///Destructor - virtual ~RakPeerInterface() {} - - // --------------------------------------------------------------------------------------------Major Low Level Functions - Functions needed by most users-------------------------------------------------------------------------------------------- - /// \brief Starts the network threads, opens the listen port. - /// \details You must call this before calling Connect(). - /// \pre On the PS3, call Startup() after Client_Login() - /// \pre On Android, add the necessary permission to your application's androidmanifest.xml: - /// Multiple calls while already active are ignored. To call this function again with different settings, you must first call Shutdown(). - /// \note Call SetMaximumIncomingConnections if you want to accept incoming connections - /// \param[in] maxConnections The maximum number of connections between this instance of RakPeer and another instance of RakPeer. Required so the network can preallocate and for thread safety. A pure client would set this to 1. A pure server would set it to the number of allowed clients.- A hybrid would set it to the sum of both types of connections - /// \param[in] localPort The port to listen for connections on. On linux the system may be set up so thast ports under 1024 are restricted for everything but the root user. Use a higher port for maximum compatibility. - /// \param[in] socketDescriptors An array of SocketDescriptor structures to force RakNet to listen on a particular IP address or port (or both). Each SocketDescriptor will represent one unique socket. Do not pass redundant structures. To listen on a specific port, you can pass SocketDescriptor(myPort,0); such as for a server. For a client, it is usually OK to just pass SocketDescriptor(); However, on the XBOX be sure to use IPPROTO_VDP - /// \param[in] socketDescriptorCount The size of the \a socketDescriptors array. Pass 1 if you are not sure what to pass. - /// \param[in] threadPriority Passed to the thread creation routine. Use THREAD_PRIORITY_NORMAL for Windows. For Linux based systems, you MUST pass something reasonable based on the thread priorities for your application. - /// \return RAKNET_STARTED on success, otherwise appropriate failure enumeration. - virtual StartupResult Startup( unsigned int maxConnections, SocketDescriptor *socketDescriptors, unsigned socketDescriptorCount, int threadPriority=-99999 )=0; - - /// If you accept connections, you must call this or else security will not be enabled for incoming connections. - /// This feature requires more round trips, bandwidth, and CPU time for the connection handshake - /// x64 builds require under 25% of the CPU time of other builds - /// See the Encryption sample for example usage - /// \pre Must be called while offline - /// \pre LIBCAT_SECURITY must be defined to 1 in NativeFeatureIncludes.h for this function to have any effect - /// \param[in] publicKey A pointer to the public key for accepting new connections - /// \param[in] privateKey A pointer to the private key for accepting new connections - /// \param[in] bRequireClientKey: Should be set to false for most servers. Allows the server to accept a public key from connecting clients as a proof of identity but eats twice as much CPU time as a normal connection - virtual bool InitializeSecurity( const char *publicKey, const char *privateKey, bool bRequireClientKey = false )=0; - - /// Disables security for incoming connections. - /// \note Must be called while offline - virtual void DisableSecurity( void )=0; - - /// If secure connections are on, do not use secure connections for a specific IP address. - /// This is useful if you have a fixed-address internal server behind a LAN. - /// \note Secure connections are determined by the recipient of an incoming connection. This has no effect if called on the system attempting to connect. - /// \param[in] ip IP address to add. * wildcards are supported. - virtual void AddToSecurityExceptionList(const char *ip)=0; - - /// Remove a specific connection previously added via AddToSecurityExceptionList - /// \param[in] ip IP address to remove. Pass 0 to remove all IP addresses. * wildcards are supported. - virtual void RemoveFromSecurityExceptionList(const char *ip)=0; - - /// Checks to see if a given IP is in the security exception list - /// \param[in] IP address to check. - virtual bool IsInSecurityExceptionList(const char *ip)=0; - - /// Sets how many incoming connections are allowed. If this is less than the number of players currently connected, - /// no more players will be allowed to connect. If this is greater than the maximum number of peers allowed, - /// it will be reduced to the maximum number of peers allowed. - /// Defaults to 0, meaning by default, nobody can connect to you - /// \param[in] numberAllowed Maximum number of incoming connections allowed. - virtual void SetMaximumIncomingConnections( unsigned short numberAllowed )=0; - - /// Returns the value passed to SetMaximumIncomingConnections() - /// \return the maximum number of incoming connections, which is always <= maxConnections - virtual unsigned int GetMaximumIncomingConnections( void ) const=0; - - /// Returns how many open connections there are at this time - /// \return the number of open connections - virtual unsigned short NumberOfConnections(void) const=0; - - /// Sets the password incoming connections must match in the call to Connect (defaults to none). Pass 0 to passwordData to specify no password - /// This is a way to set a low level password for all incoming connections. To selectively reject connections, implement your own scheme using CloseConnection() to remove unwanted connections - /// \param[in] passwordData A data block that incoming connections must match. This can be just a password, or can be a stream of data. Specify 0 for no password data - /// \param[in] passwordDataLength The length in bytes of passwordData - virtual void SetIncomingPassword( const char* passwordData, int passwordDataLength )=0; - - /// Gets the password passed to SetIncomingPassword - /// \param[out] passwordData Should point to a block large enough to hold the password data you passed to SetIncomingPassword() - /// \param[in,out] passwordDataLength Maximum size of the array passwordData. Modified to hold the number of bytes actually written - virtual void GetIncomingPassword( char* passwordData, int *passwordDataLength )=0; - - /// \brief Connect to the specified host (ip or domain name) and server port. - /// Calling Connect and not calling SetMaximumIncomingConnections acts as a dedicated client. - /// Calling both acts as a true peer. This is a non-blocking connection. - /// You know the connection is successful when GetConnectionState() returns IS_CONNECTED or Receive() gets a message with the type identifier ID_CONNECTION_REQUEST_ACCEPTED. - /// If the connection is not successful, such as a rejected connection or no response then neither of these things will happen. - /// \pre Requires that you first call Startup() - /// \param[in] host Either a dotted IP address or a domain name - /// \param[in] remotePort Which port to connect to on the remote machine. - /// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password. - /// \param[in] passwordDataLength The length in bytes of passwordData - /// \param[in] publicKey The public key the server is using. If 0, the server is not using security. If non-zero, the publicKeyMode member determines how to connect - /// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on. - /// \param[in] sendConnectionAttemptCount How many datagrams to send to the other system to try to connect. - /// \param[in] timeBetweenSendConnectionAttemptsMS Time to elapse before a datagram is sent to the other system to try to connect. After sendConnectionAttemptCount number of attempts, ID_CONNECTION_ATTEMPT_FAILED is returned. Under low bandwidth conditions with multiple simultaneous outgoing connections, this value should be raised to 1000 or higher, or else the MTU detection can overrun the available bandwidth. - /// \param[in] timeoutTime How long to keep the connection alive before dropping it on unable to send a reliable message. 0 to use the default from SetTimeoutTime(UNASSIGNED_SYSTEM_ADDRESS); - /// \return CONNECTION_ATTEMPT_STARTED on successful initiation. Otherwise, an appropriate enumeration indicating failure. - /// \note CONNECTION_ATTEMPT_STARTED does not mean you are already connected! - /// \note It is possible to immediately get back ID_CONNECTION_ATTEMPT_FAILED if you exceed the maxConnections parameter passed to Startup(). This could happen if you call CloseConnection() with sendDisconnectionNotificaiton true, then immediately call Connect() before the connection has closed. - virtual ConnectionAttemptResult Connect( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, PublicKey *publicKey=0, unsigned connectionSocketIndex=0, unsigned sendConnectionAttemptCount=12, unsigned timeBetweenSendConnectionAttemptsMS=500, MafiaNet::TimeMS timeoutTime=0 )=0; - - /// \brief Connect to the specified host (ip or domain name) and server port, using a shared socket from another instance of RakNet - /// \param[in] host Either a dotted IP address or a domain name - /// \param[in] remotePort Which port to connect to on the remote machine. - /// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password. - /// \param[in] passwordDataLength The length in bytes of passwordData - /// \param[in] socket A bound socket returned by another instance of RakPeerInterface - /// \param[in] sendConnectionAttemptCount How many datagrams to send to the other system to try to connect. - /// \param[in] timeBetweenSendConnectionAttemptsMS Time to elapse before a datagram is sent to the other system to try to connect. After sendConnectionAttemptCount number of attempts, ID_CONNECTION_ATTEMPT_FAILED is returned. Under low bandwidth conditions with multiple simultaneous outgoing connections, this value should be raised to 1000 or higher, or else the MTU detection can overrun the available bandwidth. - /// \param[in] timeoutTime How long to keep the connection alive before dropping it on unable to send a reliable message. 0 to use the default from SetTimeoutTime(UNASSIGNED_SYSTEM_ADDRESS); - /// \return CONNECTION_ATTEMPT_STARTED on successful initiation. Otherwise, an appropriate enumeration indicating failure. - /// \note CONNECTION_ATTEMPT_STARTED does not mean you are already connected! - virtual ConnectionAttemptResult ConnectWithSocket(const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, RakNetSocket2* socket, PublicKey *publicKey=0, unsigned sendConnectionAttemptCount=12, unsigned timeBetweenSendConnectionAttemptsMS=500, MafiaNet::TimeMS timeoutTime=0)=0; - - /// \brief Connect to the specified network ID (Platform specific console function) - /// \details Does built-in NAt traversal - /// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password. - /// \param[in] passwordDataLength The length in bytes of passwordData - //virtual bool Console2LobbyConnect( void *networkServiceId, const char *passwordData, int passwordDataLength )=0; - - /// \brief Stops the network threads and closes all connections. - /// \param[in] blockDuration How long, in milliseconds, you should wait for all remaining messages to go out, including ID_DISCONNECTION_NOTIFICATION. If 0, it doesn't wait at all. - /// \param[in] orderingChannel If blockDuration > 0, ID_DISCONNECTION_NOTIFICATION will be sent on this channel - /// \param[in] disconnectionNotificationPriority Priority at which ID_DISCONNECTION_NOTIFICATION is sent. Note that a blockDuration of 0 means the threads stop without waiting for it to flush. - virtual void Shutdown( unsigned int blockDuration, unsigned char orderingChannel=0, MafiaNet::Priority disconnectionNotificationPriority=MafiaNet::Priority::Low )=0; - - /// Returns if the network thread is running - /// \return true if the network thread is running, false otherwise - virtual bool IsActive( void ) const=0; - - /// Fills the array remoteSystems with the SystemAddress of all the systems we are connected to - /// \param[out] remoteSystems An array of SystemAddress structures to be filled with the SystemAddresss of the systems we are connected to. Pass 0 to remoteSystems to only get the number of systems we are connected to - /// \param[in, out] numberOfSystems As input, the size of remoteSystems array. As output, the number of elements put into the array - virtual bool GetConnectionList( SystemAddress *remoteSystems, unsigned short *numberOfSystems ) const=0; - - /// Returns the next uint32_t that Send() will return - /// \note If using RakPeer from multiple threads, this may not be accurate for your thread. Use IncrementNextSendReceipt() in that case. - /// \return The next uint32_t that Send() or SendList will return - virtual uint32_t GetNextSendReceipt(void)=0; - - /// Returns the next uint32_t that Send() will return, and increments the value by one - /// \note If using RakPeer from multiple threads, pass this to forceReceipt in the send function - /// \return The next uint32_t that Send() or SendList will return - virtual uint32_t IncrementNextSendReceipt(void)=0; - - /// Sends a block of data to the specified system that you are connected to. - /// This function only works while connected - /// The first byte should be a message identifier starting at ID_USER_PACKET_ENUM - /// \param[in] data The block of data to send - /// \param[in] length The size in bytes of the data to send - /// \param[in] priority What priority level to send on. See PacketPriority.h - /// \param[in] reliability How reliability to send this data. See PacketPriority.h - /// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream - /// \param[in] systemIdentifier Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none - /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. - /// \param[in] forceReceipt If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it. - /// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number - virtual uint32_t Send( const char *data, const int length, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber=0 )=0; - - /// "Send" to yourself rather than a remote system. The message will be processed through the plugins and returned to the game as usual - /// This function works anytime - /// The first byte should be a message identifier starting at ID_USER_PACKET_ENUM - /// \param[in] data The block of data to send - /// \param[in] length The size in bytes of the data to send - virtual void SendLoopback( const char *data, const int length )=0; - - /// Sends a block of data to the specified system that you are connected to. Same as the above version, but takes a BitStream as input. - /// \param[in] bitStream The bitstream to send - /// \param[in] priority What priority level to send on. See PacketPriority.h - /// \param[in] reliability How reliability to send this data. See PacketPriority.h - /// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream - /// \param[in] systemIdentifier Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none - /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. - /// \param[in] forceReceipt If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it. - /// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number - /// \note COMMON MISTAKE: When writing the first byte, bitStream->Write((unsigned char) ID_MY_TYPE) be sure it is casted to a byte, and you are not writing a 4 byte enumeration. - virtual uint32_t Send( const MafiaNet::BitStream * bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber=0 )=0; - - /// Sends multiple blocks of data, concatenating them automatically. - /// - /// This is equivalent to: - /// MafiaNet::BitStream bs; - /// bs.WriteAlignedBytes(block1, blockLength1); - /// bs.WriteAlignedBytes(block2, blockLength2); - /// bs.WriteAlignedBytes(block3, blockLength3); - /// Send(&bs, ...) - /// - /// This function only works while connected - /// \param[in] data An array of pointers to blocks of data - /// \param[in] lengths An array of integers indicating the length of each block of data - /// \param[in] numParameters Length of the arrays data and lengths - /// \param[in] priority What priority level to send on. See PacketPriority.h - /// \param[in] reliability How reliability to send this data. See PacketPriority.h - /// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream - /// \param[in] systemIdentifier Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none - /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. - /// \param[in] forceReceipt If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it. - /// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number - virtual uint32_t SendList( const char **data, const int *lengths, const int numParameters, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber=0 )=0; - - /// Gets a message from the incoming message queue. - /// Use DeallocatePacket() to deallocate the message after you are done with it. - /// User-thread functions, such as RPC calls and the plugin function PluginInterface::Update occur here. - /// \return 0 if no packets are waiting to be handled, otherwise a pointer to a packet. - /// \note COMMON MISTAKE: Be sure to call this in a loop, once per game tick, until it returns 0. If you only process one packet per game tick they will buffer up. - /// sa types.h contains struct Packet - virtual Packet* Receive( void )=0; - - /// Call this to deallocate a message returned by Receive() when you are done handling it. - /// \param[in] packet The message to deallocate. - virtual void DeallocatePacket( Packet *packet )=0; - - /// Return the total number of connections we are allowed - virtual unsigned int GetMaximumNumberOfPeers( void ) const=0; - - // -------------------------------------------------------------------------------------------- Connection Management Functions-------------------------------------------------------------------------------------------- - /// Close the connection to another host (if we initiated the connection it will disconnect, if they did it will kick them out). - /// \param[in] target Which system to close the connection to. - /// \param[in] sendDisconnectionNotification True to send ID_DISCONNECTION_NOTIFICATION to the recipient. False to close it silently. - /// \param[in] channel Which ordering channel to send the disconnection notification on, if any - /// \param[in] disconnectionNotificationPriority Priority to send ID_DISCONNECTION_NOTIFICATION on. - /// \param[in] reasonData Optional payload appended after the ID_DISCONNECTION_NOTIFICATION message ID so the - /// remote peer can learn *why* it was dropped (e.g. an enum + custom string). The receiver reads it - /// from packet->data+1 (length packet->length-1), exactly like any other message body. Only graceful - /// disconnects (sendDisconnectionNotification==true) carry a reason; locally-synthesized notifications - /// (ID_CONNECTION_LOST and timeout/dead-connection paths) stay payload-less, so consumers must tolerate - /// a zero-length body. Pass nullptr (the default) for no reason. Appending bytes after the 1-byte ID is - /// wire-backward-compatible: peers that only read data[0] are unaffected. - virtual void CloseConnection( const AddressOrGUID target, bool sendDisconnectionNotification, unsigned char orderingChannel=0, MafiaNet::Priority disconnectionNotificationPriority=MafiaNet::Priority::Low, const MafiaNet::BitStream *reasonData=nullptr )=0; - - /// Returns if a system is connected, disconnected, connecting in progress, or various other states - /// \param[in] systemIdentifier The system we are referring to - /// \note This locks a mutex, do not call too frequently during connection attempts or the attempt will take longer and possibly even timeout - /// \return What state the remote system is in - virtual ConnectionState GetConnectionState(const AddressOrGUID systemIdentifier)=0; - - /// Cancel a pending connection attempt - /// If we are already connected, the connection stays open - /// \param[in] target Which system to cancel - virtual void CancelConnectionAttempt( const SystemAddress target )=0; - - /// Given a systemAddress, returns an index from 0 to the maximum number of players allowed - 1. - /// \param[in] systemAddress The SystemAddress we are referring to - /// \return The index of this SystemAddress or -1 on system not found. - virtual int GetIndexFromSystemAddress( const SystemAddress systemAddress ) const=0; - - /// This function is only useful for looping through all systems - /// Given an index, will return a SystemAddress. - /// \param[in] index Index should range between 0 and the maximum number of players allowed - 1. - /// \return The SystemAddress - virtual SystemAddress GetSystemAddressFromIndex( unsigned int index )=0; - - /// Same as GetSystemAddressFromIndex but returns RakNetGUID - /// \param[in] index Index should range between 0 and the maximum number of players allowed - 1. - /// \return The RakNetGUID - virtual RakNetGUID GetGUIDFromIndex( unsigned int index )=0; - - /// Same as calling GetSystemAddressFromIndex and GetGUIDFromIndex for all systems, but more efficient - /// Indices match each other, so \a addresses[0] and \a guids[0] refer to the same system - /// \param[out] addresses All system addresses. Size of the list is the number of connections. Size of the list will match the size of the \a guids list. - /// \param[out] guids All guids. Size of the list is the number of connections. Size of the list will match the size of the \a addresses list. - virtual void GetSystemList(DataStructures::List &addresses, DataStructures::List &guids) const=0; - - /// Bans an IP from connecting. Banned IPs persist between connections but are not saved on shutdown nor loaded on startup. - /// param[in] IP Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will ban all IP addresses starting with 128.0.0 - /// \param[in] milliseconds how many ms for a temporary ban. Use 0 for a permanent ban - virtual void AddToBanList( const char *IP, MafiaNet::TimeMS milliseconds=0 )=0; - - /// Allows a previously banned IP to connect. - /// param[in] Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will banAll IP addresses starting with 128.0.0 - virtual void RemoveFromBanList( const char *IP )=0; - - /// Allows all previously banned IPs to connect. - virtual void ClearBanList( void )=0; - - /// Returns true or false indicating if a particular IP is banned. - /// \param[in] IP - Dotted IP address. - /// \return true if IP matches any IPs in the ban list, accounting for any wildcards. False otherwise. - virtual bool IsBanned( const char *IP )=0; - - /// Enable or disable allowing frequent connections from the same IP adderss - /// This is a security measure which is disabled by default, but can be set to true to prevent attackers from using up all connection slots - /// \param[in] b True to limit connections from the same ip to at most 1 per 100 milliseconds. - virtual void SetLimitIPConnectionFrequency(bool b)=0; - - // --------------------------------------------------------------------------------------------Pinging Functions - Functions dealing with the automatic ping mechanism-------------------------------------------------------------------------------------------- - /// Send a ping to the specified connected system. - /// \pre The sender and recipient must already be started via a successful call to Startup() - /// \param[in] target Which system to ping - virtual void Ping( const SystemAddress target )=0; - - /// Send a ping to the specified unconnected system. The remote system, if it is Initialized, will respond with ID_PONG followed by sizeof(MafiaNet::TimeMS) containing the system time the ping was sent.(Default is 4 bytes - See __GET_TIME_64BIT in types.h - /// System should reply with ID_PONG if it is active - /// \param[in] host Either a dotted IP address or a domain name. Can be 255.255.255.255 for LAN broadcast. - /// \param[in] remotePort Which port to connect to on the remote machine. - /// \param[in] onlyReplyOnAcceptingConnections Only request a reply if the remote system is accepting connections - /// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on. - /// \return true on success, false on failure (unknown hostname) - virtual bool Ping( const char* host, unsigned short remotePort, bool onlyReplyOnAcceptingConnections, unsigned connectionSocketIndex=0 )=0; - - /// Returns the average of all ping times read for the specific system or -1 if none read yet - /// \param[in] systemAddress Which system we are referring to - /// \return The ping time for this system, or -1 - virtual int GetAveragePing( const AddressOrGUID systemIdentifier )=0; - - /// Returns the last ping time read for the specific system or -1 if none read yet - /// \param[in] systemAddress Which system we are referring to - /// \return The last ping time for this system, or -1 - virtual int GetLastPing( const AddressOrGUID systemIdentifier ) const=0; - - /// Returns the lowest ping time read or -1 if none read yet - /// \param[in] systemAddress Which system we are referring to - /// \return The lowest ping time for this system, or -1 - virtual int GetLowestPing( const AddressOrGUID systemIdentifier ) const=0; - - /// Ping the remote systems every so often, or not. Can be called anytime. - /// By default this is true. Recommended to leave on, because congestion control uses it to determine how often to resend lost packets. - /// It would be true by default to prevent timestamp drift, since in the event of a clock spike, the timestamp deltas would no longer be accurate - /// \param[in] doPing True to start occasional pings. False to stop them. - virtual void SetOccasionalPing( bool doPing )=0; - - /// Return the clock difference between your system and the specified system - /// Subtract GetClockDifferential() from a time returned by the remote system to get that time relative to your own system - /// Returns 0 if the system is unknown - /// \param[in] systemIdentifier Which system we are referring to - virtual MafiaNet::Time GetClockDifferential( const AddressOrGUID systemIdentifier )=0; - - // --------------------------------------------------------------------------------------------Static Data Functions - Functions dealing with API defined synchronized memory-------------------------------------------------------------------------------------------- - /// Sets the data to send along with a LAN server discovery or offline ping reply. - /// \a length should be under 400 bytes, as a security measure against flood attacks - /// \param[in] data a block of data to store, or 0 for none - /// \param[in] length The length of data in bytes, or 0 for none - /// \sa Ping.cpp - virtual void SetOfflinePingResponse( const char *data, const unsigned int length )=0; - - /// Returns pointers to a copy of the data passed to SetOfflinePingResponse - /// \param[out] data A pointer to a copy of the data passed to \a SetOfflinePingResponse() - /// \param[out] length A pointer filled in with the length parameter passed to SetOfflinePingResponse() - /// \sa SetOfflinePingResponse - virtual void GetOfflinePingResponse( char **data, unsigned int *length )=0; - - //--------------------------------------------------------------------------------------------Network Functions - Functions dealing with the network in general-------------------------------------------------------------------------------------------- - /// Return the unique address identifier that represents you or another system on the the network and is based on your local IP / port. - /// \note Not supported by the XBOX - /// \param[in] systemAddress Use UNASSIGNED_SYSTEM_ADDRESS to get your behind-LAN address. Use a connected system to get their behind-LAN address - /// \param[in] index When you have multiple internal IDs, which index to return? Currently limited to MAXIMUM_NUMBER_OF_INTERNAL_IDS (so the maximum value of this variable is MAXIMUM_NUMBER_OF_INTERNAL_IDS-1) - /// \return the identifier of your system internally, which may not be how other systems see if you if you are behind a NAT or proxy - virtual SystemAddress GetInternalID( const SystemAddress systemAddress=UNASSIGNED_SYSTEM_ADDRESS, const int index=0 ) const=0; - - /// \brief Sets your internal IP address, for platforms that do not support reading it, or to override a value - /// \param[in] systemAddress. The address to set. Use SystemAddress::FromString() if you want to use a dotted string - /// \param[in] index When you have multiple internal IDs, which index to set? - virtual void SetInternalID(SystemAddress systemAddress, int index=0)=0; - - /// Return the unique address identifier that represents you on the the network and is based on your externalIP / port - /// (the IP / port the specified player uses to communicate with you) - /// \param[in] target Which remote system you are referring to for your external ID. Usually the same for all systems, unless you have two or more network cards. - virtual SystemAddress GetExternalID( const SystemAddress target ) const=0; - - /// Return my own GUID - virtual const RakNetGUID GetMyGUID(void) const=0; - - /// Return the address bound to a socket at the specified index - virtual SystemAddress GetMyBoundAddress(const int socketIndex=0)=0; - - /// Get a random number (to generate a GUID) - static uint64_t Get64BitUniqueRandomNumber(void); - - /// Given a connected system, give us the unique GUID representing that instance of RakPeer. - /// This will be the same on all systems connected to that instance of RakPeer, even if the external system addresses are different - /// Currently O(log(n)), but this may be improved in the future. If you use this frequently, you may want to cache the value as it won't change. - /// Returns UNASSIGNED_RAKNET_GUID if system address can't be found. - /// If \a input is UNASSIGNED_SYSTEM_ADDRESS, will return your own GUID - /// \pre Call Startup() first, or the function will return UNASSIGNED_RAKNET_GUID - /// \param[in] input The system address of the system we are connected to - virtual const RakNetGUID& GetGuidFromSystemAddress( const SystemAddress input ) const=0; - - /// Given the GUID of a connected system, give us the system address of that system. - /// The GUID will be the same on all systems connected to that instance of RakPeer, even if the external system addresses are different - /// Currently O(log(n)), but this may be improved in the future. If you use this frequently, you may want to cache the value as it won't change. - /// If \a input is UNASSIGNED_RAKNET_GUID, will return UNASSIGNED_SYSTEM_ADDRESS - /// \param[in] input The RakNetGUID of the system we are checking to see if we are connected to - virtual SystemAddress GetSystemAddressFromGuid( const RakNetGUID input ) const=0; - - /// Given the SystemAddress of a connected system, get the public key they provided as an identity - /// Returns false if system address was not found or client public key is not known - /// \param[in] input The RakNetGUID of the system - /// \param[in] client_public_key The connected client's public key is copied to this address. Buffer must be cat::EasyHandshake::PUBLIC_KEY_BYTES bytes in length. - virtual bool GetClientPublicKeyFromSystemAddress( const SystemAddress input, char *client_public_key ) const=0; - - /// Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable message. - /// Default time is 10,000 or 10 seconds in release and 30,000 or 30 seconds in debug. - /// Do not set different values for different computers that are connected to each other, or you won't be able to reconnect after ID_CONNECTION_LOST - /// \param[in] timeMS Time, in MS - /// \param[in] target Which system to do this for. Pass UNASSIGNED_SYSTEM_ADDRESS for all systems. - virtual void SetTimeoutTime(MafiaNet::TimeMS timeMS, const SystemAddress target )=0; - - /// \param[in] target Which system to do this for. Pass UNASSIGNED_SYSTEM_ADDRESS to get the default value - /// \return timeoutTime for a given system. - virtual MafiaNet::TimeMS GetTimeoutTime( const SystemAddress target )=0; - - /// Returns the current MTU size - /// \param[in] target Which system to get this for. UNASSIGNED_SYSTEM_ADDRESS to get the default - /// \return The current MTU size - virtual int GetMTUSize( const SystemAddress target ) const=0; - - /// Returns the number of IP addresses this system has internally. Get the actual addresses from GetLocalIP() - virtual unsigned GetNumberOfAddresses( void )=0; - - /// Returns an IP address at index 0 to GetNumberOfAddresses-1 - /// \param[in] index index into the list of IP addresses - /// \return The local IP address at this index - virtual const char* GetLocalIP( unsigned int index )=0; - - /// Is this a local IP? - /// \param[in] An IP address to check, excluding the port - /// \return True if this is one of the IP addresses returned by GetLocalIP - virtual bool IsLocalIP( const char *ip )=0; - - /// Allow or disallow connection responses from any IP. Normally this should be false, but may be necessary - /// when connecting to servers with multiple IP addresses. - /// \param[in] allow - True to allow this behavior, false to not allow. Defaults to false. Value persists between connections - virtual void AllowConnectionResponseIPMigration( bool allow )=0; - - /// Sends a one byte message ID_ADVERTISE_SYSTEM to the remote unconnected system. - /// This will tell the remote system our external IP outside the LAN along with some user data. - /// \pre The sender and recipient must already be started via a successful call to Initialize - /// \param[in] host Either a dotted IP address or a domain name - /// \param[in] remotePort Which port to connect to on the remote machine. - /// \param[in] data Optional data to append to the packet. - /// \param[in] dataLength length of data in bytes. Use 0 if no data. - /// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on. - /// \return false if IsActive()==false or the host is unresolvable. True otherwise - virtual bool AdvertiseSystem( const char *host, unsigned short remotePort, const char *data, int dataLength, unsigned connectionSocketIndex=0 )=0; - - /// Controls how often to return ID_DOWNLOAD_PROGRESS for large message downloads. - /// ID_DOWNLOAD_PROGRESS is returned to indicate a new partial message chunk, roughly the MTU size, has arrived - /// As it can be slow or cumbersome to get this notification for every chunk, you can set the interval at which it is returned. - /// Defaults to 0 (never return this notification) - /// \param[in] interval How many messages to use as an interval - virtual void SetSplitMessageProgressInterval(int interval)=0; - - /// Returns what was passed to SetSplitMessageProgressInterval() - /// \return What was passed to SetSplitMessageProgressInterval(). Default to 0. - virtual int GetSplitMessageProgressInterval(void) const=0; - - /// Set how long to wait before giving up on sending an unreliable message - /// Useful if the network is clogged up. - /// Set to 0 or less to never timeout. Defaults to 0. - /// \param[in] timeoutMS How many ms to wait before simply not sending an unreliable message. - virtual void SetUnreliableTimeout(MafiaNet::TimeMS timeoutMS)=0; - - /// Send a message to host, with the IP socket option TTL set to 3 - /// This message will not reach the host, but will open the router. - /// Used for NAT-Punchthrough - virtual void SendTTL( const char* host, unsigned short remotePort, int ttl, unsigned connectionSocketIndex=0 )=0; - - // -------------------------------------------------------------------------------------------- Plugin Functions-------------------------------------------------------------------------------------------- - /// \brief Attaches a Plugin interface to an instance of the base class (RakPeer or PacketizedTCP) to run code automatically on message receipt in the Receive call. - /// If the plugin returns false from PluginInterface::UsesReliabilityLayer(), which is the case for all plugins except PacketLogger, you can call AttachPlugin() and DetachPlugin() for this plugin while RakPeer is active. - /// \param[in] messageHandler Pointer to the plugin to attach. - virtual void AttachPlugin( PluginInterface2 *plugin )=0; - - /// \brief Detaches a Plugin interface from the instance of the base class (RakPeer or PacketizedTCP) it is attached to. - /// \details This method disables the plugin code from running automatically on base class's updates or message receipt. - /// If the plugin returns false from PluginInterface::UsesReliabilityLayer(), which is the case for all plugins except PacketLogger, you can call AttachPlugin() and DetachPlugin() for this plugin while RakPeer is active. - /// \param[in] messageHandler Pointer to a plugin to detach. - virtual void DetachPlugin( PluginInterface2 *messageHandler )=0; - - // --------------------------------------------------------------------------------------------Miscellaneous Functions-------------------------------------------------------------------------------------------- - /// Put a message back at the end of the receive queue in case you don't want to deal with it immediately - /// \param[in] packet The packet you want to push back. - /// \param[in] pushAtHead True to push the packet so that the next receive call returns it. False to push it at the end of the queue (obviously pushing it at the end makes the packets out of order) - virtual void PushBackPacket( Packet *packet, bool pushAtHead )=0; - - /// \internal - /// \brief For a given system identified by \a guid, change the SystemAddress to send to. - /// \param[in] guid The connection we are referring to - /// \param[in] systemAddress The new address to send to - virtual void ChangeSystemAddress(RakNetGUID guid, const SystemAddress &systemAddress)=0; - - /// \returns a packet for you to write to if you want to create a Packet for some reason. - /// You can add it to the receive buffer with PushBackPacket - /// \param[in] dataSize How many bytes to allocate for the buffer - /// \return A packet you can write to - virtual Packet* AllocatePacket(unsigned dataSize)=0; - - /// Get the socket used with a particular active connection - /// The smart pointer reference counts the RakNetSocket2 object, so the socket will remain active as long as the smart pointer does, even if RakNet were to shutdown or close the connection. - /// \note This sends a query to the thread and blocks on the return value for up to one second. In practice it should only take a millisecond or so. - /// \param[in] target Which system - /// \return A smart pointer object containing the socket information about the socket. Be sure to check IsNull() which is returned if the update thread is unresponsive, shutting down, or if this system is not connected - virtual RakNetSocket2* GetSocket( const SystemAddress target )=0; - - /// Get all sockets in use - /// \note This sends a query to the thread and blocks on the return value for up to one second. In practice it should only take a millisecond or so. - /// \param[out] sockets List of RakNetSocket2 structures in use. Sockets will not be closed until \a sockets goes out of scope - virtual void GetSockets( DataStructures::List &sockets )=0; - virtual void ReleaseSockets( DataStructures::List &sockets )=0; - - virtual void WriteOutOfBandHeader(MafiaNet::BitStream *bitStream)=0; - - /// If you need code to run in the same thread as RakNet's update thread, this function can be used for that - /// \param[in] _userUpdateThreadPtr C callback function - /// \param[in] _userUpdateThreadData Passed to C callback function - virtual void SetUserUpdateThread(void (*_userUpdateThreadPtr)(RakPeerInterface *, void *), void *_userUpdateThreadData)=0; - - /// Set a C callback to be called whenever a datagram arrives - /// Return true from the callback to have RakPeer handle the datagram. Return false and RakPeer will ignore the datagram. - /// This can be used to filter incoming datagrams by system, or to share a recvfrom socket with RakPeer - /// RNS2RecvStruct will only remain valid for the duration of the call - /// If the incoming datagram is not from your game at all, it is a RakNet packet. - /// If the incoming datagram has an IP address that matches a known address from your game, then check the first byte of data. - /// For RakNet connected systems, the first bit is always 1. So for your own game packets, make sure the first bit is always 0. - virtual void SetIncomingDatagramEventHandler( bool (*_incomingDatagramEventHandler)(RNS2RecvStruct *) )=0; - - // --------------------------------------------------------------------------------------------Network Simulator Functions-------------------------------------------------------------------------------------------- - /// Adds simulated ping and packet loss to the outgoing data flow. - /// To simulate bi-directional ping and packet loss, you should call this on both the sender and the recipient, with half the total ping and packetloss value on each. - /// You can exclude network simulator code with the _RELEASE #define to decrease code size - /// \deprecated Use http://www.jenkinssoftware.com/forum/index.php?topic=1671.0 instead. - /// \note Doesn't work past version 3.6201 - /// \param[in] packetloss Chance to lose a packet. Ranges from 0 to 1. - /// \param[in] minExtraPing The minimum time to delay sends. - /// \param[in] extraPingVariance The additional random time to delay sends. - virtual void ApplyNetworkSimulator( float packetloss, unsigned short minExtraPing, unsigned short extraPingVariance)=0; - - /// Limits how much outgoing bandwidth can be sent per-connection. - /// This limit does not apply to the sum of all connections! - /// Exceeding the limit queues up outgoing traffic - /// \param[in] maxBitsPerSecond Maximum bits per second to send. Use 0 for unlimited (default). Once set, it takes effect immedately and persists until called again. - virtual void SetPerConnectionOutgoingBandwidthLimit( unsigned maxBitsPerSecond )=0; - - /// Returns if you previously called ApplyNetworkSimulator - /// \return If you previously called ApplyNetworkSimulator - virtual bool IsNetworkSimulatorActive( void )=0; - - // --------------------------------------------------------------------------------------------Statistical Functions - Functions dealing with API performance-------------------------------------------------------------------------------------------- - - /// Returns a structure containing a large set of network statistics for the specified system. - /// You can map this data to a string using the C style StatisticsToString() function - /// \param[in] systemAddress: Which connected system to get statistics for - /// \param[in] rns If you supply this structure, it will be written to it. Otherwise it will use a static struct, which is not threadsafe - /// \return 0 on can't find the specified system. A pointer to a set of data otherwise. - /// \sa statistics.h - virtual RakNetStatistics * GetStatistics( const SystemAddress systemAddress, RakNetStatistics *rns=0 )=0; - /// \brief Returns the network statistics of the system at the given index in the remoteSystemList. - /// \return True if the index is less than the maximum number of peers allowed and the system is active. False otherwise. - virtual bool GetStatistics( const unsigned int index, RakNetStatistics *rns )=0; - /// \brief Returns the list of systems, and statistics for each of those systems - /// Each system has one entry in each of the lists, in the same order - /// \param[out] addresses SystemAddress for each connected system - /// \param[out] guids RakNetGUID for each connected system - /// \param[out] statistics Calculated RakNetStatistics for each connected system - virtual void GetStatisticsList(DataStructures::List &addresses, DataStructures::List &guids, DataStructures::List &statistics)=0; - - /// \Returns how many messages are waiting when you call Receive() - virtual unsigned int GetReceiveBufferSize(void)=0; - - // --------------------------------------------------------------------------------------------EVERYTHING AFTER THIS COMMENT IS FOR INTERNAL USE ONLY-------------------------------------------------------------------------------------------- - - /// \internal - // Call manually if RAKPEER_USER_THREADED==1 at least every 30 milliseconds. - // updateBitStream should be: - // BitStream updateBitStream( MAXIMUM_MTU_SIZE - // #if LIBCAT_SECURITY==1 - // + cat::AuthenticatedEncryption::OVERHEAD_BYTES - // #endif - // ); - virtual bool RunUpdateCycle( BitStream &updateBitStream )=0; - - /// \internal - virtual bool SendOutOfBand(const char *host, unsigned short remotePort, const char *data, BitSize_t dataLength, unsigned connectionSocketIndex=0 )=0; - -} -// #if defined(SN_TARGET_PSP2) -// __attribute__((aligned(8))) -// #endif -; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/sleep.h b/vendors/mafianet/Source/include/mafianet/sleep.h deleted file mode 100644 index 83f825787..000000000 --- a/vendors/mafianet/Source/include/mafianet/sleep.h +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -#ifndef __RAK_SLEEP_H -#define __RAK_SLEEP_H - -#include "Export.h" - -void RAK_DLL_EXPORT RakSleep(unsigned int ms); - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/smartptr.h b/vendors/mafianet/Source/include/mafianet/smartptr.h deleted file mode 100644 index fd4e0f966..000000000 --- a/vendors/mafianet/Source/include/mafianet/smartptr.h +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __RAKNET_SMART_PTR_H -#define __RAKNET_SMART_PTR_H - -// From http://www.codeproject.com/KB/cpp/SmartPointers.aspx -// with bugs fixed - -#include "memoryoverride.h" -#include "Export.h" - -//static int allocCount=0; -//static int deallocCount=0; - -namespace MafiaNet -{ - -class RAK_DLL_EXPORT ReferenceCounter -{ -private: - int refCount; - -public: - ReferenceCounter() {refCount=0;} - ~ReferenceCounter() {} - void AddRef() {refCount++;} - int Release() {return --refCount;} - int GetRefCount(void) const {return refCount;} -}; - -template < typename T > class RAK_DLL_EXPORT RakNetSmartPtr -{ -private: - T* ptr; // pointer - ReferenceCounter* reference; // Reference refCount - -public: - RakNetSmartPtr() : ptr(0), reference(0) - { - // Do not allocate by default, wasteful if we just have a list of preallocated and unassigend smart pointers - } - - RakNetSmartPtr(T* pValue) : ptr(pValue) - { - reference = MafiaNet::OP_NEW(_FILE_AND_LINE_); - reference->AddRef(); - -// allocCount+=2; -// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); - } - - RakNetSmartPtr(const RakNetSmartPtr& sp) : ptr(sp.ptr), reference(sp.reference) - { - if (reference) - reference->AddRef(); - } - - ~RakNetSmartPtr() - { - if(reference && reference->Release() == 0) - { - MafiaNet::OP_DELETE(ptr, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(reference, _FILE_AND_LINE_); - -// deallocCount+=2; -// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); - } - } - - bool IsNull(void) const - { - return ptr==0; - } - - void SetNull(void) - { - if(reference && reference->Release() == 0) - { - MafiaNet::OP_DELETE(ptr, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(reference, _FILE_AND_LINE_); - -// deallocCount+=2; -// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); - } - ptr=0; - reference=0; - } - - bool IsUnique(void) const - { - return reference->GetRefCount()==1; - } - - // Allow you to change the values of the internal contents of the pointer, without changing what is pointed to by other instances of the smart pointer - void Clone(bool copyContents) - { - if (IsUnique()==false) - { - reference->Release(); - - reference = MafiaNet::OP_NEW(_FILE_AND_LINE_); - reference->AddRef(); - T* oldPtr=ptr; - ptr= MafiaNet::OP_NEW(_FILE_AND_LINE_); - if (copyContents) - *ptr=*oldPtr; - } - } - - int GetRefCount(void) const - { - return reference->GetRefCount(); - } - - T& operator* () - { - return *ptr; - } - - const T& operator* () const - { - return *ptr; - } - - T* operator-> () - { - return ptr; - } - - const T* operator-> () const - { - return ptr; - } - - bool operator == (const RakNetSmartPtr& sp) - { - return ptr == sp.ptr; - } - bool operator<( const RakNetSmartPtr &right ) {return ptr < right.ptr;} - bool operator>( const RakNetSmartPtr &right ) {return ptr > right.ptr;} - - bool operator != (const RakNetSmartPtr& sp) - { - return ptr != sp.ptr; - } - - RakNetSmartPtr& operator = (const RakNetSmartPtr& sp) - { - // Assignment operator - - if (this != &sp) // Avoid self assignment - { - if(reference && reference->Release() == 0) - { - MafiaNet::OP_DELETE(ptr, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(reference, _FILE_AND_LINE_); - -// deallocCount+=2; -// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); - } - - ptr = sp.ptr; - reference = sp.reference; - if (reference) - reference->AddRef(); - } - return *this; - } - - -}; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/socket.h b/vendors/mafianet/Source/include/mafianet/socket.h deleted file mode 100644 index f78b3b4dd..000000000 --- a/vendors/mafianet/Source/include/mafianet/socket.h +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/* -#ifndef __RAKNET_SOCKET_H -#define __RAKNET_SOCKET_H - -#include "types.h" -#include "defines.h" -#include "Export.h" -#include "SocketIncludes.h" -#include "assert.h" -#include "SocketDefines.h" -#include "MTUSize.h" - -namespace MafiaNet -{ - -struct RAK_DLL_EXPORT RakNetSocket -{ -public: - RakNetSocket(); - ~RakNetSocket(); - -// void Accept( -// struct sockaddr *addr, -// int *addrlen); - - inline int Connect( - const struct sockaddr *name, - int namelen) {return connect__(s,name,namelen);} - - static RakNetSocket* Create -#ifdef __native_client__ - (_PP_Instance_ _chromeInstance); -#else - (int af, - int type, - int protocol); -#endif - - int Bind( - const struct sockaddr *addr, - int namelen); - - inline int GetSockName( - struct sockaddr *name, - socklen_t * namelen) {return getsockname__(s,name,namelen);} - - inline int GetSockOpt ( - int level, - int optname, - char * optval, - socklen_t *optlen) {return getsockopt__(s,level,optname,optval,optlen);} - - - int IOCTLSocket( - long cmd, - unsigned long *argp); - - int Listen ( - int backlog); - - inline int Recv( - char * buf, - int len, - int flags) {return recv__(s,buf,len,flags);} - - inline int RecvFrom( - char * buf, - int len, - int flags, - struct sockaddr * from, - socklen_t * fromlen) {return recvfrom__(s,buf,len,flags,from,fromlen);} - -// inline int Select( -// int nfds, -// fd_set *readfds, -// fd_set *writefds, -// fd_set *exceptfds, -// struct timeval *timeout) {return select__(nfds,readfds,writefds,exceptfds,timeout);} - - inline int Send( - const char * buf, - int len, - int flags) {return send__(s,buf,len,flags);} - - inline int SendTo( - const char * buf, - int len, - int flags, - const struct sockaddr *to, - int tolen) {return sendto__(s,buf,len,flags,to,tolen);} - - #ifdef _WIN32 - #elif defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3) || defined(_PS4) || defined(SN_TARGET_PSP2) - #else - inline int Fcntl(int cmd, int arg) {return fcntl(s,cmd,arg);} - #endif - - -#if defined(_WIN32) - inline int _WSASendTo( - LPWSABUF lpBuffers, - DWORD dwBufferCount, - LPDWORD lpNumberOfBytesSent, - DWORD dwFlags, - const struct sockaddr FAR * lpTo, - int iTolen, - LPWSAOVERLAPPED lpOverlapped, - LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine - ) - { return WSASendTo(s,lpBuffers,dwBufferCount,lpNumberOfBytesSent,dwFlags,lpTo,iTolen,lpOverlapped,lpCompletionRoutine);} - -#endif - - int SetSockOpt( - int level, - int optname, - const char * optval, - int optlen); - - int Shutdown( - int how); - - - inline void SetRemotePortRakNetWasStartedOn(unsigned short i) {remotePortRakNetWasStartedOn_PS3_PSP2=i;} - inline void SetUserConnectionSocketIndex(unsigned int i) {userConnectionSocketIndex=i;} - inline void SetBoundAddress(SystemAddress i) {boundAddress=i;} - inline void SetSocketFamily(unsigned short i) {socketFamily=i;} - inline void SetBlockingSocket(bool i) {blockingSocket=i;} - inline void SetExtraSocketOptions(unsigned int i) {extraSocketOptions=i;} - inline void SetChromeInstance(_PP_Instance_ i) {chromeInstance=i;} - inline void SetBoundAddressToLoopback(unsigned char ipVersion) {boundAddress.SetToLoopback(ipVersion);} - - inline SystemAddress GetBoundAddress(void) const {return boundAddress;} - inline unsigned short GetRemotePortRakNetWasStartedOn(void) const {return remotePortRakNetWasStartedOn_PS3_PSP2;} - inline bool GetBlockingSocket(void) {return blockingSocket;} - inline unsigned int GetExtraSocketOptions(void) const {return extraSocketOptions;} - inline unsigned short GetSocketFamily(void) const {return socketFamily;} - inline _PP_Instance_ GetChromeInstance(void) const {return chromeInstance;} - inline unsigned int GetUserConnectionSocketIndex(void) const { - RakAssert(userConnectionSocketIndex!=(unsigned int)-1); - return userConnectionSocketIndex;} - - -#ifdef __native_client__ - // Flag indicating if a SendTo is currently in progress - bool sendInProgress; - - // Data for next queued packet to send, if nextSendSize > 0 - char nextSendBuffer[MAXIMUM_MTU_SIZE]; - - // Size of next queued packet to send, or 0 if no queued packet - int nextSendSize; - - // Destination address of queued packet - PP_NetAddress_Private nextSendAddr; -#endif - - __UDPSOCKET__ s; - -protected: - -#if defined (_WIN32) && defined(USE_WAIT_FOR_MULTIPLE_EVENTS) - void* recvEvent; -#endif - - #if defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3) || defined(_PS4) || defined(SN_TARGET_PSP2) - /// PS3: Set for the PS3, when using signaling. - /// PS3: Connect with the port returned by signaling. Set this to whatever port RakNet was actually started on - /// PSP2: Set non-zero to use SCE_NET_SOCK_DGRAM_P2P. This should be done for ad-hoc or with - #endif - - unsigned short remotePortRakNetWasStartedOn_PS3_PSP2; - unsigned int userConnectionSocketIndex; - SystemAddress boundAddress; - unsigned short socketFamily; - bool blockingSocket; - unsigned int extraSocketOptions; - _PP_Instance_ chromeInstance; -}; - -} // namespace MafiaNet - -#endif -*/ diff --git a/vendors/mafianet/Source/include/mafianet/socket2.h b/vendors/mafianet/Source/include/mafianet/socket2.h deleted file mode 100644 index 592afef50..000000000 --- a/vendors/mafianet/Source/include/mafianet/socket2.h +++ /dev/null @@ -1,271 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __RAKNET_SOCKET_2_H -#define __RAKNET_SOCKET_2_H - -#include "types.h" -#include "MTUSize.h" -#include "LocklessTypes.h" -#include "thread.h" -#include "DS_ThreadsafeAllocatingQueue.h" -#include "Export.h" - -// For CFSocket -// https://developer.apple.com/library/mac/#documentation/CoreFOundation/Reference/CFSocketRef/Reference/reference.html -// Reason: http://sourceforge.net/p/open-dis/discussion/683284/thread/0929d6a0 -#if defined(__APPLE__) -#import -#include -#include -#endif - -namespace MafiaNet -{ - -class RakNetSocket2; -struct RNS2_BerkleyBindParameters; -struct RNS2_SendParameters; -#ifdef WIN32 -typedef SOCKET RNS2Socket; -#else -// #low determine whether we cannot use SOCKET on all platforms... -typedef int RNS2Socket; -#endif - -enum RNS2BindResult -{ - BR_SUCCESS, - BR_REQUIRES_RAKNET_SUPPORT_IPV6_DEFINE, - BR_FAILED_TO_BIND_SOCKET, - BR_FAILED_SEND_TEST, -}; - -typedef int RNS2SendResult; - -enum RNS2Type -{ - RNS2T_WINDOWS, - RNS2T_LINUX -}; - -struct RNS2_SendParameters -{ - RNS2_SendParameters() {ttl=0;} - char *data; - int length; - SystemAddress systemAddress; - int ttl; -}; - -struct RNS2RecvStruct -{ - - char data[MAXIMUM_MTU_SIZE]; - - int bytesRead; - SystemAddress systemAddress; - MafiaNet::TimeUS timeRead; - RakNetSocket2 *socket; -}; - -class RakNetSocket2Allocator -{ -public: - static RakNetSocket2* AllocRNS2(void); - static void DeallocRNS2(RakNetSocket2 *s); -}; - -class RAK_DLL_EXPORT RNS2EventHandler -{ -public: - RNS2EventHandler() {} - virtual ~RNS2EventHandler() {} - - // bufferedPackets.Push(recvFromStruct); - // quitAndDataEvents.SetEvent(); - virtual void OnRNS2Recv(RNS2RecvStruct *recvStruct)=0; - virtual void DeallocRNS2RecvStruct(RNS2RecvStruct *s, const char *file, unsigned int line)=0; - virtual RNS2RecvStruct *AllocRNS2RecvStruct(const char *file, unsigned int line)=0; - - // recvFromStruct=bufferedPackets.Allocate( _FILE_AND_LINE_ ); - // DataStructures::ThreadsafeAllocatingQueue bufferedPackets; -}; - -class RakNetSocket2 -{ -public: - RakNetSocket2(); - virtual ~RakNetSocket2(); - - // In order for the handler to trigger, some platforms must call PollRecvFrom, some platforms this create an internal thread. - void SetRecvEventHandler(RNS2EventHandler *_eventHandler); - virtual RNS2SendResult Send( RNS2_SendParameters *sendParameters, const char *file, unsigned int line )=0; - RNS2Type GetSocketType(void) const; - void SetSocketType(RNS2Type t); - bool IsBerkleySocket(void) const; - SystemAddress GetBoundAddress(void) const; - unsigned int GetUserConnectionSocketIndex(void) const; - void SetUserConnectionSocketIndex(unsigned int i); - RNS2EventHandler * GetEventHandler(void) const; - - // ----------- STATICS ------------ - static void GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); - static void DomainNameToIP( const char *domainName, char ip[65] ); - -protected: - RNS2EventHandler *eventHandler; - RNS2Type socketType; - SystemAddress boundAddress; - unsigned int userConnectionSocketIndex; -}; - -struct RNS2_BerkleyBindParameters -{ - // Input parameters - unsigned short port; - char *hostAddress; - unsigned short addressFamily; // AF_INET or AF_INET6 - int type; // SOCK_DGRAM - int protocol; // 0 - bool nonBlockingSocket; - int setBroadcast; - int setIPHdrIncl; - int doNotFragment; - int pollingThreadPriority; - RNS2EventHandler *eventHandler; - unsigned short remotePortRakNetWasStartedOn_PS3_PS4_PSP2; -}; - -// Berkeley sockets interface - base class for all platforms -class IRNS2_Berkley : public RakNetSocket2 -{ -public: - // ----------- STATICS ------------ - // For addressFamily, use AF_INET - // For type, use SOCK_DGRAM - static bool IsPortInUse(unsigned short port, const char *hostAddress, unsigned short addressFamily, int type ); - - // ----------- MEMBERS ------------ - virtual RNS2BindResult Bind( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line )=0; -}; -// Common Berkeley socket implementation for Windows and Linux -class RNS2_Berkley : public IRNS2_Berkley -{ -public: - RNS2_Berkley(); - virtual ~RNS2_Berkley(); - int CreateRecvPollingThread(int threadPriority); - void SignalStopRecvPollingThread(void); - void BlockOnStopRecvPollingThread(void); - const RNS2_BerkleyBindParameters *GetBindings(void) const; - RNS2Socket GetSocket(void) const; - void SetDoNotFragment( int opt ); - -protected: - // Used by other classes - RNS2BindResult BindShared( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ); - RNS2BindResult BindSharedIPV4( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ); - RNS2BindResult BindSharedIPV4And6( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ); - - static void GetSystemAddressIPV4 ( RNS2Socket rns2Socket, SystemAddress *systemAddressOut ); - static void GetSystemAddressIPV4And6 ( RNS2Socket rns2Socket, SystemAddress *systemAddressOut ); - - // Internal - void SetNonBlockingSocket(unsigned long nonblocking); - void SetSocketOptions(void); - void SetBroadcastSocket(int broadcast); - void SetIPHdrIncl(int ipHdrIncl); - void RecvFromBlocking(RNS2RecvStruct *recvFromStruct); - void RecvFromBlockingIPV4(RNS2RecvStruct *recvFromStruct); - void RecvFromBlockingIPV4And6(RNS2RecvStruct *recvFromStruct); - - RNS2Socket rns2Socket; - RNS2_BerkleyBindParameters binding; - - unsigned RecvFromLoopInt(void); - MafiaNet::LocklessUint32_t isRecvFromLoopThreadActive; - volatile bool endThreads; - // Constructor not called! - -#if defined(__APPLE__) - // http://sourceforge.net/p/open-dis/discussion/683284/thread/0929d6a0 - CFSocketRef _cfSocket; -#endif - - static RAK_THREAD_DECLARATION(RecvFromLoop); -}; - -#if defined(_WIN32) || defined(__GNUC__) || defined(__GCCXML__) || defined(__S3E__) -class RNS2_Windows_Linux_360 -{ -public: -protected: - static RNS2SendResult Send_Windows_Linux_360NoVDP( RNS2Socket rns2Socket, RNS2_SendParameters *sendParameters, const char *file, unsigned int line ); -}; -#endif - -#if defined(_WIN32) - -class RAK_DLL_EXPORT SocketLayerOverride -{ -public: - SocketLayerOverride() {} - virtual ~SocketLayerOverride() {} - - /// Called when SendTo would otherwise occur. - virtual int RakNetSendTo( const char *data, int length, const SystemAddress &systemAddress )=0; - - /// Called when RecvFrom would otherwise occur. Return number of bytes read. Write data into dataOut - // Return -1 to use RakNet's normal recvfrom, 0 to abort RakNet's normal recvfrom, and positive to return data - virtual int RakNetRecvFrom( char dataOut[ MAXIMUM_MTU_SIZE ], SystemAddress *senderOut, bool calledFromMainThread )=0; -}; - -class RNS2_Windows : public RNS2_Berkley, public RNS2_Windows_Linux_360 -{ -public: - RNS2_Windows(); - virtual ~RNS2_Windows(); - RNS2BindResult Bind( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ); - RNS2SendResult Send( RNS2_SendParameters *sendParameters, const char *file, unsigned int line ); - void SetSocketLayerOverride(SocketLayerOverride *_slo); - SocketLayerOverride* GetSocketLayerOverride(void); - // ----------- STATICS ------------ - static void GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); -protected: - static void GetMyIPIPV4( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); - static void GetMyIPIPV4And6( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); - SocketLayerOverride *slo; -}; - -#else -class RNS2_Linux : public RNS2_Berkley, public RNS2_Windows_Linux_360 -{ -public: - RNS2BindResult Bind( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ); - RNS2SendResult Send( RNS2_SendParameters *sendParameters, const char *file, unsigned int line ); - - // ----------- STATICS ------------ - static void GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); -protected: - static void GetMyIPIPV4( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); - static void GetMyIPIPV4And6( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); -}; - -#endif // Linux - -} // namespace MafiaNet - -#endif // __RAKNET_SOCKET_2_H diff --git a/vendors/mafianet/Source/include/mafianet/statistics.h b/vendors/mafianet/Source/include/mafianet/statistics.h deleted file mode 100644 index d66fc930d..000000000 --- a/vendors/mafianet/Source/include/mafianet/statistics.h +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief A structure that holds all statistical data returned by RakNet. -/// - - - -#ifndef __RAK_NET_STATISTICS_H -#define __RAK_NET_STATISTICS_H - -#include "PacketPriority.h" -#include "Export.h" -#include "types.h" - -namespace MafiaNet -{ - -enum RNSPerSecondMetrics -{ - /// How many bytes per pushed via a call to RakPeerInterface::Send() - USER_MESSAGE_BYTES_PUSHED, - - /// How many user message bytes were sent via a call to RakPeerInterface::Send(). This is less than or equal to USER_MESSAGE_BYTES_PUSHED. - /// A message would be pushed, but not yet sent, due to congestion control - USER_MESSAGE_BYTES_SENT, - - /// How many user message bytes were resent. A message is resent if it is marked as reliable, and either the message didn't arrive or the message ack didn't arrive. - USER_MESSAGE_BYTES_RESENT, - - /// How many user message bytes were received, and returned to the user successfully. - USER_MESSAGE_BYTES_RECEIVED_PROCESSED, - - /// How many user message bytes were received, but ignored due to data format errors. This will usually be 0. - USER_MESSAGE_BYTES_RECEIVED_IGNORED, - - /// How many actual bytes were sent, including per-message and per-datagram overhead, and reliable message acks - ACTUAL_BYTES_SENT, - - /// How many actual bytes were received, including overead and acks. - ACTUAL_BYTES_RECEIVED, - - /// \internal - RNS_PER_SECOND_METRICS_COUNT -}; - -/// \brief Network Statisics Usage -/// -/// Store Statistics information related to network usage -struct RAK_DLL_EXPORT RakNetStatistics -{ - /// For each type in RNSPerSecondMetrics, what is the value over the last 1 second? - uint64_t valueOverLastSecond[RNS_PER_SECOND_METRICS_COUNT]; - - /// For each type in RNSPerSecondMetrics, what is the total value over the lifetime of the connection? - uint64_t runningTotal[RNS_PER_SECOND_METRICS_COUNT]; - - /// When did the connection start? - /// \sa MafiaNet::GetTimeUS() - MafiaNet::TimeUS connectionStartTime; - - /// Is our current send rate throttled by congestion control? - /// This value should be true if you send more data per second than your bandwidth capacity - bool isLimitedByCongestionControl; - - /// If \a isLimitedByCongestionControl is true, what is the limit, in bytes per second? - uint64_t BPSLimitByCongestionControl; - - /// Is our current send rate throttled by a call to RakPeer::SetPerConnectionOutgoingBandwidthLimit()? - bool isLimitedByOutgoingBandwidthLimit; - - /// If \a isLimitedByOutgoingBandwidthLimit is true, what is the limit, in bytes per second? - uint64_t BPSLimitByOutgoingBandwidthLimit; - - /// For each priority level, how many messages are waiting to be sent out? - unsigned int messageInSendBuffer[MafiaNet::NUMBER_OF_PRIORITIES]; - - /// For each priority level, how many bytes are waiting to be sent out? - double bytesInSendBuffer[MafiaNet::NUMBER_OF_PRIORITIES]; - - /// How many messages are waiting in the resend buffer? This includes messages waiting for an ack, so should normally be a small value - /// If the value is rising over time, you are exceeding the bandwidth capacity. See BPSLimitByCongestionControl - unsigned int messagesInResendBuffer; - - /// How many bytes are waiting in the resend buffer. See also messagesInResendBuffer - uint64_t bytesInResendBuffer; - - /// Over the last second, what was our packetloss? This number will range from 0.0 (for none) to 1.0 (for 100%) - float packetlossLastSecond; - - /// What is the average total packetloss over the lifetime of the connection? - float packetlossTotal; - - RakNetStatistics& operator +=(const RakNetStatistics& other) - { - unsigned i; - for (i=0; i < MafiaNet::NUMBER_OF_PRIORITIES; i++) - { - messageInSendBuffer[i]+=other.messageInSendBuffer[i]; - bytesInSendBuffer[i]+=other.bytesInSendBuffer[i]; - } - - for (i=0; i < RNS_PER_SECOND_METRICS_COUNT; i++) - { - valueOverLastSecond[i]+=other.valueOverLastSecond[i]; - runningTotal[i]+=other.runningTotal[i]; - } - - return *this; - } -}; - -/// Verbosity level currently supports 0 (low), 1 (medium), 2 (high) -/// \param[in] s The Statistical information to format out -/// \param[in] buffer The buffer containing a formated report -/// \param[in] bufferLength The size (in characters) of the buffer -/// \param[in] verbosityLevel -/// 0 low -/// 1 medium -/// 2 high -/// 3 debugging congestion control -void RAK_DLL_EXPORT StatisticsToString(RakNetStatistics *s, char *buffer, int verbosityLevel); -void RAK_DLL_EXPORT StatisticsToString( RakNetStatistics *s, char *buffer, size_t bufferLength, int verbosityLevel ); - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/string.h b/vendors/mafianet/Source/include/mafianet/string.h deleted file mode 100644 index e2325deec..000000000 --- a/vendors/mafianet/Source/include/mafianet/string.h +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2019, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __RAK_STRING_H -#define __RAK_STRING_H - -#include "Export.h" -#include "DS_List.h" -#include "types.h" // int64_t -#include -#include "stdarg.h" - -#ifdef _WIN32 -#include "WindowsIncludes.h" -#endif - -namespace MafiaNet -{ -/// Forward declarations -class SimpleMutex; -class BitStream; - -/// \brief String class -/// \details Has the following improvements over std::string -/// -Reference counting: Suitable to store in lists -/// -Variadic assignment operator -/// -Doesn't cause linker errors -class RAK_DLL_EXPORT RakString -{ -public: - // Constructors - RakString(); - RakString(char input); - RakString(unsigned char input); - RakString(const unsigned char *format, ...); - RakString(const char *format, ...); - ~RakString(); - RakString( const RakString & rhs); - - /// Implicit return of const char* - operator const char* () const {return sharedString->c_str;} - - /// Same as std::string::c_str - const char *C_String(void) const {return sharedString->c_str;} - - // Lets you modify the string. Do not make the string longer - however, you can make it shorter, or change the contents. - // Pointer is only valid in the scope of RakString itself - char *C_StringUnsafe(void) {Clone(); return sharedString->c_str;} - - /// Assigment operators - RakString& operator = ( const RakString& rhs ); - RakString& operator = ( const char *str ); - RakString& operator = ( char *str ); - RakString& operator = ( const unsigned char *str ); - RakString& operator = ( char unsigned *str ); - RakString& operator = ( const char c ); - - /// Concatenation - RakString& operator +=( const RakString& rhs); - RakString& operator += ( const char *str ); - RakString& operator += ( char *str ); - RakString& operator += ( const unsigned char *str ); - RakString& operator += ( char unsigned *str ); - RakString& operator += ( const char c ); - - /// Character index. Do not use to change the string however. - unsigned char operator[] ( const unsigned int position ) const; - -#ifdef _WIN32 - // Return as Wide char - // Deallocate with DeallocWideChar - WCHAR * ToWideChar(void); - void DeallocWideChar(WCHAR * w); - - void FromWideChar(const wchar_t *source); - static MafiaNet::RakString FromWideChar_S(const wchar_t *source); -#endif - - /// String class find replacement - /// Searches the string for the content specified in stringToFind and returns the position of the first occurrence in the string. - /// Search only includes characters on or after position pos, ignoring any possible occurrences in previous locations. - /// \param[in] stringToFind The string to find inside of this object's string - /// \param[in] pos The position in the string to start the search - /// \return Returns the position of the first occurrence in the string. - size_t Find(const char *stringToFind,size_t pos = 0 ); - - /// Equality - bool operator==(const RakString &rhs) const; - bool operator==(const char *str) const; - bool operator==(char *str) const; - - // Comparison - bool operator < ( const RakString& right ) const; - bool operator <= ( const RakString& right ) const; - bool operator > ( const RakString& right ) const; - bool operator >= ( const RakString& right ) const; - - /// Inequality - bool operator!=(const RakString &rhs) const; - bool operator!=(const char *str) const; - bool operator!=(char *str) const; - - /// Change all characters to lowercase - const char * ToLower(void); - - /// Change all characters to uppercase - const char * ToUpper(void); - - /// Set the value of the string - void Set(const char *format, ...); - - /// Sets a copy of a substring of str as the new content. The substring is the portion of str - /// that begins at the character position pos and takes up to n characters - /// (it takes less than n if the end of str is reached before). - /// \param[in] str The string to copy in - /// \param[in] pos The position on str to start the copy - /// \param[in] n How many chars to copy - /// \return Returns the string, note that the current string is set to that value as well - RakString Assign(const char *str,size_t pos, size_t n ); - - /// Returns if the string is empty. Also, C_String() would return "" - bool IsEmpty(void) const; - - /// Returns the length of the string - size_t GetLength(void) const; - size_t GetLengthUTF8(void) const; - - /// Replace character(s) in starting at index, for count, with c - void Replace(unsigned index, unsigned count, unsigned char c); - - /// Replace character at index with c - void SetChar( unsigned index, unsigned char c ); - - /// Replace character at index with string s - void SetChar( unsigned index, MafiaNet::RakString s ); - - /// Make sure string is no longer than \a length - void Truncate(unsigned int length); - void TruncateUTF8(unsigned int length); - - // Gets the substring starting at index for count characters - RakString SubStr(unsigned int index, size_t count) const; - - /// Erase characters out of the string at index for count - void Erase(unsigned int index, unsigned int count); - - /// Set the first instance of c with a null-terminator - void TerminateAtFirstCharacter(char c); - /// Set the last instance of c with a null-terminator - void TerminateAtLastCharacter(char c); - - void StartAfterFirstCharacter(char c); - void StartAfterLastCharacter(char c); - - /// Returns how many occurances there are of \a c in the string - int GetCharacterCount(char c); - - /// Remove all instances of c - void RemoveCharacter(char c); - - /// Create a RakString with a value, without doing printf style parsing - /// Equivalent to assignment operator - static MafiaNet::RakString NonVariadic(const char *str); - - /// Hash the string into an unsigned int - static unsigned long ToInteger(const char *str); - static unsigned long ToInteger(const RakString &rs); - - /// \brief Read an integer out of a substring - /// \param[in] str The string - /// \param[in] pos The position on str where the integer starts - /// \param[in] n How many chars to copy - static int ReadIntFromSubstring(const char *str, size_t pos, size_t n); - - // Like strncat, but for a fixed length - void AppendBytes(const char *bytes, size_t count); - - /// Compare strings (case sensitive) - int StrCmp(const RakString &rhs) const; - - /// Compare strings (case sensitive), up to num characters - int StrNCmp(const RakString &rhs, size_t num) const; - - /// Compare strings (not case sensitive) - int StrICmp(const RakString &rhs) const; - - /// Clear the string - void Clear(void); - - /// Print the string to the screen - void Printf(void); - - /// Print the string to a file - void FPrintf(FILE *fp); - - /// Does the given IP address match the IP address encoded into this string, accounting for wildcards? - bool IPAddressMatch(const char *IP); - - /// Does the string contain non-printable characters other than spaces? - bool ContainsNonprintableExceptSpaces(void) const; - - /// Is this a valid email address? - bool IsEmailAddress(void) const; - - /// URL Encode the string. See http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4029/ - MafiaNet::RakString& URLEncode(void); - - /// URL decode the string - MafiaNet::RakString& URLDecode(void); - - /// https://servers.api.rackspacecloud.com/v1.0 to https://, servers.api.rackspacecloud.com, /v1.0 - void SplitURI(MafiaNet::RakString &header, MafiaNet::RakString &domain, MafiaNet::RakString &path); - - /// Scan for quote, double quote, and backslash and prepend with backslash - MafiaNet::RakString& SQLEscape(void); - - /// Format as a POST command that can be sent to a webserver - /// \param[in] uri For example, masterserver2.raknet.com/testServer - /// \param[in] contentType For example, text/plain; charset=UTF-8 - /// \param[in] body Body of the post - /// \return Formatted string - static MafiaNet::RakString FormatForPOST(const char* uri, const char* contentType, const char* body, const char* extraHeaders=""); - static MafiaNet::RakString FormatForPUT(const char* uri, const char* contentType, const char* body, const char* extraHeaders=""); - - /// Format as a GET command that can be sent to a webserver - /// \param[in] uri For example, masterserver2.raknet.com/testServer?__gameId=comprehensivePCGame - /// \return Formatted string - static MafiaNet::RakString FormatForGET(const char* uri, const char* extraHeaders=""); - - /// Format as a DELETE command that can be sent to a webserver - /// \param[in] uri For example, masterserver2.raknet.com/testServer?__gameId=comprehensivePCGame&__rowId=1 - /// \return Formatted string - static MafiaNet::RakString FormatForDELETE(const char* uri, const char* extraHeaders=""); - - /// Fix to be a file path, ending with / - MafiaNet::RakString& MakeFilePath(void); - - /// RakString uses a freeList of old no-longer used strings - /// Call this function to clear this memory on shutdown - static void FreeMemory(void); - /// \internal - static void FreeMemoryNoMutex(void); - - /// Serialize to a bitstream, uncompressed (slightly faster) - /// \param[out] bs Bitstream to serialize to - void Serialize(BitStream *bs) const; - - /// Static version of the Serialize function - static void Serialize(const char *str, BitStream *bs); - - /// Serialize to a bitstream, compressed (better bandwidth usage) - /// \param[out] bs Bitstream to serialize to - /// \param[in] languageId languageId to pass to the StringCompressor class - /// \param[in] writeLanguageId encode the languageId variable in the stream. If false, 0 is assumed, and DeserializeCompressed will not look for this variable in the stream (saves bandwidth) - /// \pre StringCompressor::AddReference must have been called to instantiate the class (Happens automatically from RakPeer::Startup()) - void SerializeCompressed(BitStream *bs, uint8_t languageId=0, bool writeLanguageId=false) const; - - /// Static version of the SerializeCompressed function - static void SerializeCompressed(const char *str, BitStream *bs, uint8_t languageId=0, bool writeLanguageId=false); - - /// Deserialize what was written by Serialize - /// \param[in] bs Bitstream to serialize from - /// \return true if the deserialization was successful - bool Deserialize(BitStream *bs); - - /// Static version of the Deserialize() function - static bool Deserialize(char *str, BitStream *bs); - - /// Deserialize compressed string, written by SerializeCompressed - /// \param[in] bs Bitstream to serialize from - /// \param[in] readLanguageId If true, looks for the variable langaugeId in the data stream. Must match what was passed to SerializeCompressed - /// \return true if the deserialization was successful - /// \pre StringCompressor::AddReference must have been called to instantiate the class (Happens automatically from RakPeer::Startup()) - bool DeserializeCompressed(BitStream *bs, bool readLanguageId=false); - - /// Static version of the DeserializeCompressed() function - static bool DeserializeCompressed(char *str, BitStream *bs, bool readLanguageId=false); - - static const char *ToString(int64_t i); - static const char *ToString(uint64_t i); - - /// \internal - static size_t GetSizeToAllocate(size_t bytes) - { - const size_t smallStringSize = 128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2; - if (bytes<=smallStringSize) - return smallStringSize; - else - return bytes*2; - } - - /// \internal - struct SharedString - { - SimpleMutex *refCountMutex; - unsigned int refCount; - size_t bytesUsed; - char *bigString; - char *c_str; - char smallString[128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2]; - }; - - /// \internal - RakString( SharedString *_sharedString ); - - /// \internal - SharedString *sharedString; - -// static SimpleMutex poolMutex; -// static DataStructures::MemoryPool pool; - /// \internal - static SharedString emptyString; - - //static SharedString *sharedStringFreeList; - //static unsigned int sharedStringFreeListAllocationCount; - /// \internal - /// List of free objects to reduce memory reallocations - static DataStructures::List freeList; - - static int RakStringComp( RakString const &key, RakString const &data ); - - static void LockMutex(void); - static void UnlockMutex(void); - -protected: - static MafiaNet::RakString FormatForPUTOrPost(const char* type, const char* uri, const char* contentType, const char* body, const char* extraHeaders); - void Allocate(size_t len); - void Assign(const char *str); - void Assign(const char *str, va_list ap); - - void Clone(void); - void Free(void); - unsigned char ToLower(unsigned char c); - unsigned char ToUpper(unsigned char c); - void Realloc(SharedString *inSharedString, size_t bytes); -}; - -} - -const MafiaNet::RakString RAK_DLL_EXPORT operator+(const MafiaNet::RakString &lhs, const MafiaNet::RakString &rhs); - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/thread.h b/vendors/mafianet/Source/include/mafianet/thread.h deleted file mode 100644 index af0a3423f..000000000 --- a/vendors/mafianet/Source/include/mafianet/thread.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __RAK_THREAD_H -#define __RAK_THREAD_H - -#include "Export.h" - -namespace MafiaNet -{ -/// To define a thread, use RAK_THREAD_DECLARATION(functionName); -#if defined(_WIN32) -#define RAK_THREAD_DECLARATION(functionName) unsigned __stdcall functionName( void* arguments ) - -#else -#define RAK_THREAD_DECLARATION(functionName) void* functionName( void* arguments ) -#endif - -class RAK_DLL_EXPORT RakThread -{ -public: - /// Create a thread, simplified to be cross platform without all the extra junk - /// To then start that thread, call RakCreateThread(functionName, arguments); - /// \param[in] start_address Function you want to call - /// \param[in] arglist Arguments to pass to the function - /// \return 0=success. >0 = error code - - /* - nice value Win32 Priority - -20 to -16 THREAD_PRIORITY_HIGHEST - -15 to -6 THREAD_PRIORITY_ABOVE_NORMAL - -5 to +4 THREAD_PRIORITY_NORMAL - +5 to +14 THREAD_PRIORITY_BELOW_NORMAL - +15 to +19 THREAD_PRIORITY_LOWEST - */ -#if defined(_WIN32) - static int Create( unsigned __stdcall start_address( void* ), void *arglist, int priority=0); -#else - static int Create( void* start_address( void* ), void *arglist, int priority=0); -#endif -}; - -} - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/time.h b/vendors/mafianet/Source/include/mafianet/time.h deleted file mode 100644 index 7b9ecb919..000000000 --- a/vendors/mafianet/Source/include/mafianet/time.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __RAKNET_TIME_H -#define __RAKNET_TIME_H - -#include "NativeTypes.h" -#include "defines.h" - -namespace MafiaNet { - -// Define __GET_TIME_64BIT if you want to use large types for GetTime (takes more bandwidth when you transmit time though!) -// You would want to do this if your system is going to run long enough to overflow the millisecond counter (over a month) -#if __GET_TIME_64BIT==1 -typedef uint64_t Time; -#define RAK_TIME_FORMAT_STRING "%llu" -typedef uint32_t TimeMS; -typedef uint64_t TimeUS; -#else -typedef uint32_t Time; -#define RAK_TIME_FORMAT_STRING "%u" -typedef uint32_t TimeMS; -typedef uint64_t TimeUS; -#endif - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/transport2.h b/vendors/mafianet/Source/include/mafianet/transport2.h deleted file mode 100644 index ea88bba9a..000000000 --- a/vendors/mafianet/Source/include/mafianet/transport2.h +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Contains RakNetTransportCommandParser and RakNetTransport used to provide a secure console connection. -/// - - -#include "NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_TelnetTransport==1 - -#ifndef __RAKNET_TRANSPORT_2 -#define __RAKNET_TRANSPORT_2 - -#include "TransportInterface.h" -#include "DS_Queue.h" -#include "CommandParserInterface.h" -#include "PluginInterface2.h" -#include "Export.h" - -namespace MafiaNet -{ -/// Forward declarations -class BitStream; -class RakPeerInterface; -class RakNetTransport; - -/// \defgroup RAKNET_TRANSPORT_GROUP RakNetTransport -/// \brief UDP based transport implementation for the ConsoleServer -/// \details -/// \ingroup PLUGINS_GROUP - -/// \brief Use RakNetTransport if you need a secure connection between the client and the console server. -/// \details RakNetTransport automatically initializes security for the system. Use the project CommandConsoleClient to connect -/// To the ConsoleServer if you use RakNetTransport -/// \ingroup RAKNET_TRANSPORT_GROUP -class RAK_DLL_EXPORT RakNetTransport2 : public TransportInterface, public PluginInterface2 -{ -public: - // GetInstance() and DestroyInstance(instance*) - STATIC_FACTORY_DECLARATIONS(RakNetTransport2) - - RakNetTransport2(); - virtual ~RakNetTransport2(); - - /// Start the transport provider on the indicated port. - /// \param[in] port The port to start the transport provider on - /// \param[in] serverMode If true, you should allow incoming connections (I don't actually use this anywhere) - /// \return Return true on success, false on failure. - bool Start(unsigned short port, bool serverMode); - - /// Stop the transport provider. You can clear memory and shutdown threads here. - void Stop(void); - - /// Send a null-terminated string to \a systemAddress - /// If your transport method requires particular formatting of the outgoing data (e.g. you don't just send strings) you can do it here - /// and parse it out in Receive(). - /// \param[in] systemAddress The player to send the string to - /// \param[in] data format specifier - same as RAKNET_DEBUG_PRINTF - /// \param[in] ... format specification arguments - same as RAKNET_DEBUG_PRINTF - void Send( SystemAddress systemAddress, const char *data, ... ); - - /// Disconnect \a systemAddress . The binary address and port defines the SystemAddress structure. - /// \param[in] systemAddress The player/address to disconnect - void CloseConnection( SystemAddress systemAddress ); - - /// Return a string. The string should be allocated and written to Packet::data . - /// The byte length should be written to Packet::length . The player/address should be written to Packet::systemAddress - /// If your transport protocol adds special formatting to the data stream you should parse it out before returning it in the packet - /// and thus only return a string in Packet::data - /// \return The packet structure containing the result of Receive, or 0 if no data is available - Packet* Receive( void ); - - /// Deallocate the Packet structure returned by Receive - /// \param[in] The packet to deallocate - void DeallocatePacket( Packet *packet ); - - /// If a new system connects to you, you should queue that event and return the systemAddress/address of that player in this function. - /// \return The SystemAddress/address of the system - SystemAddress HasNewIncomingConnection(void); - - /// If a system loses the connection, you should queue that event and return the systemAddress/address of that player in this function. - /// \return The SystemAddress/address of the system - SystemAddress HasLostConnection(void); - - virtual CommandParserInterface* GetCommandParser(void) {return 0;} - - /// \internal - virtual PluginReceiveResult OnReceive(Packet *packet); - /// \internal - virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); - /// \internal - virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); -protected: - DataStructures::Queue newConnections, lostConnections; - DataStructures::Queue packetQueue; -}; - -} // namespace MafiaNet - -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/include/mafianet/types.h b/vendors/mafianet/Source/include/mafianet/types.h deleted file mode 100644 index 05f3a31ac..000000000 --- a/vendors/mafianet/Source/include/mafianet/types.h +++ /dev/null @@ -1,493 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2019, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief Types used by RakNet, most of which involve user code. -/// -#ifndef __NETWORK_TYPES_H -#define __NETWORK_TYPES_H - -#include "defines.h" -#include "NativeTypes.h" -#include "time.h" -#include "Export.h" -#include "WindowsIncludes.h" -#include "XBox360Includes.h" -#include "SocketIncludes.h" - -namespace MafiaNet { -/// Forward declarations -class RakPeerInterface; -class BitStream; -struct Packet; - -enum StartupResult -{ - RAKNET_STARTED, - RAKNET_ALREADY_STARTED, - INVALID_SOCKET_DESCRIPTORS, - INVALID_MAX_CONNECTIONS, - SOCKET_FAMILY_NOT_SUPPORTED, - SOCKET_PORT_ALREADY_IN_USE, - SOCKET_FAILED_TO_BIND, - SOCKET_FAILED_TEST_SEND, - PORT_CANNOT_BE_ZERO, - FAILED_TO_CREATE_NETWORK_THREAD, - COULD_NOT_GENERATE_GUID, - STARTUP_OTHER_FAILURE -}; - - -enum ConnectionAttemptResult -{ - CONNECTION_ATTEMPT_STARTED, - INVALID_PARAMETER, - CANNOT_RESOLVE_DOMAIN_NAME, - ALREADY_CONNECTED_TO_ENDPOINT, - CONNECTION_ATTEMPT_ALREADY_IN_PROGRESS, - SECURITY_INITIALIZATION_FAILED -}; - -/// Returned from RakPeerInterface::GetConnectionState() -enum ConnectionState -{ - /// Connect() was called, but the process hasn't started yet - IS_PENDING, - /// Processing the connection attempt - IS_CONNECTING, - /// Is connected and able to communicate - IS_CONNECTED, - /// Was connected, but will disconnect as soon as the remaining messages are delivered - IS_DISCONNECTING, - /// A connection attempt failed and will be aborted - IS_SILENTLY_DISCONNECTING, - /// No longer connected - IS_DISCONNECTED, - /// Was never connected, or else was disconnected long enough ago that the entry has been discarded - IS_NOT_CONNECTED -}; - -/// Given a number of bits, return how many bytes are needed to represent that. -#define BITS_TO_BYTES(x) (((x)+7)>>3) -#define BYTES_TO_BITS(x) ((x)<<3) - -/// \sa NetworkIDObject.h -typedef unsigned char UniqueIDType; -typedef unsigned short SystemIndex; -typedef unsigned char RPCIndex; -const int MAX_RPC_MAP_SIZE=((RPCIndex)-1)-1; -const int UNDEFINED_RPC_INDEX=((RPCIndex)-1); - -/// First byte of a network message -typedef unsigned char MessageID; - -typedef uint32_t BitSize_t; - -#define PRINTF_64_BIT_MODIFIER "ll" - -/// Used with the PublicKey structure -enum PublicKeyMode -{ - /// The connection is insecure. You can also just pass 0 for the pointer to PublicKey in RakPeerInterface::Connect() - PKM_INSECURE_CONNECTION, - - /// Accept whatever public key the server gives us. This is vulnerable to man in the middle, but does not require - /// distribution of the public key in advance of connecting. - PKM_ACCEPT_ANY_PUBLIC_KEY, - - /// Use a known remote server public key. PublicKey::remoteServerPublicKey must be non-zero. - /// This is the recommended mode for secure connections. - PKM_USE_KNOWN_PUBLIC_KEY, - - /// Use a known remote server public key AND provide a public key for the connecting client. - /// PublicKey::remoteServerPublicKey, myPublicKey and myPrivateKey must be all be non-zero. - /// The server must cooperate for this mode to work. - /// I recommend not using this mode except for server-to-server communication as it significantly increases the CPU requirements during connections for both sides. - /// Furthermore, when it is used, a connection password should be used as well to avoid DoS attacks. - PKM_USE_TWO_WAY_AUTHENTICATION -}; - -/// Passed to RakPeerInterface::Connect() -struct RAK_DLL_EXPORT PublicKey -{ - /// How to interpret the public key, see above - PublicKeyMode publicKeyMode; - - /// Pointer to a public key of length cat::EasyHandshake::PUBLIC_KEY_BYTES. See the Encryption sample. - char *remoteServerPublicKey; - - /// (Optional) Pointer to a public key of length cat::EasyHandshake::PUBLIC_KEY_BYTES - char *myPublicKey; - - /// (Optional) Pointer to a private key of length cat::EasyHandshake::PRIVATE_KEY_BYTES - char *myPrivateKey; -}; - -/// Describes the local socket to use for RakPeer::Startup -struct RAK_DLL_EXPORT SocketDescriptor -{ - SocketDescriptor(); - SocketDescriptor(unsigned short _port, const char *_hostAddress); - - /// The local port to bind to. Pass 0 to have the OS autoassign a port. - unsigned short port; - - /// The local network card address to bind to, such as "127.0.0.1". Pass an empty string to use INADDR_ANY. - char hostAddress[32]; - - /// IP version: For IPV4, use AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC. - /// IPV6 is the newer internet protocol. Instead of addresses such as natpunch.slikesoft.com, you may have an address such as fe80::7c:31f7:fec4:27de%14. - /// Encoding takes 16 bytes instead of 4, so IPV6 is less efficient for bandwidth. - /// On the positive side, NAT Punchthrough is not needed and should not be used with IPV6 because there are enough addresses that routers do not need to create address mappings. - /// RakPeer::Startup() will fail if this IP version is not supported. - /// \pre RAKNET_SUPPORT_IPV6 must be set to 1 in RakNetDefines.h for AF_INET6 - short socketFamily; - - unsigned short remotePortRakNetWasStartedOn_PS3_PSP2; - - // Required for Google chrome - _PP_Instance_ chromeInstance; - - // Set to true to use a blocking socket (default, do not change unless you have a reason to) - bool blockingSocket; - - /// XBOX only: set IPPROTO_VDP if you want to use VDP. If enabled, this socket does not support broadcast to 255.255.255.255 - unsigned int extraSocketOptions; -}; - -extern bool NonNumericHostString( const char *host ); - -/// \brief Network address for a system -/// \details Corresponds to a network address
    -/// This is not necessarily a unique identifier. For example, if a system has both LAN and internet connections, the system may be identified by either one, depending on who is communicating
    -/// Therefore, you should not transmit the SystemAddress over the network and expect it to identify a system, or use it to connect to that system, except in the case where that system is not behind a NAT (such as with a dedciated server) -/// Use RakNetGUID for a unique per-instance of RakPeer to identify systems -struct RAK_DLL_EXPORT SystemAddress -{ - /// Constructors - SystemAddress(); - SystemAddress(const char *str); - SystemAddress(const char *str, unsigned short port); - - /// SystemAddress, with RAKNET_SUPPORT_IPV6 defined, holds both an sockaddr_in6 and a sockaddr_in - union// In6OrIn4 - { -#if RAKNET_SUPPORT_IPV6==1 - struct sockaddr_storage sa_stor; - sockaddr_in6 addr6; -#endif - - sockaddr_in addr4; - } address; - - /// This is not used internally, but holds a copy of the port held in the address union, so for debugging it's easier to check what port is being held - unsigned short debugPort; - - /// \internal Return the size to write to a bitStream - static int size(void); - - /// Hash the system address - static unsigned long ToInteger(const SystemAddress &sa); - - /// Return the IP version, either IPV4 or IPV6 - /// \return Either 4 or 6 - unsigned char GetIPVersion(void) const; - - /// \internal Returns either IPPROTO_IP or IPPROTO_IPV6 - /// \sa GetIPVersion - unsigned int GetIPPROTO(void) const; - - /// Call SetToLoopback(), with whatever IP version is currently held. Defaults to IPV4 - void SetToLoopback(void); - - /// Call SetToLoopback() with a specific IP version - /// \param[in] ipVersion Either 4 for IPV4 or 6 for IPV6 - void SetToLoopback(unsigned char ipVersion); - - /// \return If was set to 127.0.0.1 or ::1 - bool IsLoopback(void) const; - - // Return the systemAddress as a string in the format | - // Returns a static string - // NOT THREADSAFE - // portDelineator should not be '.', ':', '%', '-', '/', a number, or a-f - const char *ToString(bool writePort=true, char portDelineator='|') const; - - // Return the systemAddress as a string in the format | - // dest must be large enough to hold the output - // portDelineator should not be '.', ':', '%', '-', '/', a number, or a-f - // THREADSAFE - void ToString(bool writePort, char *dest, char portDelineator = '|') const; - void ToString(bool writePort, char *dest, size_t destLength, char portDelineator='|') const; - - /// Set the system address from a printable IP string, for example "192.0.2.1" or "2001:db8:63b3:1::3490" - /// You can write the port as well, using the portDelineator, for example "192.0.2.1|1234" - /// \param[in] str A printable IP string, for example "192.0.2.1" or "2001:db8:63b3:1::3490". Pass 0 for \a str to set to UNASSIGNED_SYSTEM_ADDRESS - /// \param[in] portDelineator if \a str contains a port, delineate the port with this character. portDelineator should not be '.', ':', '%', '-', '/', a number, or a-f - /// \param[in] ipVersion Only used if str is a pre-defined address in the wrong format, such as 127.0.0.1 but you want ip version 6, so you can pass 6 here to do the conversion - /// \note The current port is unchanged if a port is not specified in \a str - /// \return True on success, false on ipVersion does not match type of passed string - bool FromString(const char *str, char portDelineator='|', int ipVersion=0); - - /// Same as FromString(), but you explicitly set a port at the same time - bool FromStringExplicitPort(const char *str, unsigned short port, int ipVersion=0); - - /// Copy the port from another SystemAddress structure - void CopyPort( const SystemAddress& right ); - - /// Returns if two system addresses have the same IP (port is not checked) - bool EqualsExcludingPort( const SystemAddress& right ) const; - - /// Returns the port in host order (this is what you normally use) - unsigned short GetPort(void) const; - - /// \internal Returns the port in network order - unsigned short GetPortNetworkOrder(void) const; - - /// Sets the port. The port value should be in host order (this is what you normally use) - /// Renamed from SetPort because of winspool.h http://edn.embarcadero.com/article/21494 - void SetPortHostOrder(unsigned short s); - - /// \internal Sets the port. The port value should already be in network order. - void SetPortNetworkOrder(unsigned short s); - - /// Old version, for crap platforms that don't support newer socket functions - bool SetBinaryAddress(const char *str, char portDelineator=':'); - /// Old version, for crap platforms that don't support newer socket functions - void ToString_Old(bool writePort, char *dest, char portDelineator = ':') const; - void ToString_Old(bool writePort, char *dest, size_t destLength, char portDelineator = ':') const; - - /// \internal sockaddr_in6 requires extra data beyond just the IP and port. Copy that extra data from an existing SystemAddress that already has it - void FixForIPVersion(const SystemAddress &boundAddressToSocket); - - bool IsLANAddress(void); - - SystemAddress& operator = ( const SystemAddress& input ); - bool operator==( const SystemAddress& right ) const; - bool operator!=( const SystemAddress& right ) const; - bool operator > ( const SystemAddress& right ) const; - bool operator < ( const SystemAddress& right ) const; - - /// \internal Used internally for fast lookup. Optional (use -1 to do regular lookup). Don't transmit this. - SystemIndex systemIndex; - - private: - -#if RAKNET_SUPPORT_IPV6==1 - void ToString_New(bool writePort, char *dest, char portDelineator) const; - void ToString_New(bool writePort, char *dest, size_t destLength, char portDelineator) const; -#endif -}; - -/// Uniquely identifies an instance of RakPeer. Use RakPeer::GetGuidFromSystemAddress() and RakPeer::GetSystemAddressFromGuid() to go between SystemAddress and RakNetGUID -/// Use RakPeer::GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS) to get your own GUID -struct RAK_DLL_EXPORT RakNetGUID -{ - RakNetGUID(); - explicit RakNetGUID(uint64_t _g) {g=_g; systemIndex=(SystemIndex)-1;} -// uint32_t g[6]; - uint64_t g; - - // Return the GUID as a string. - // For an owning, thread-safe std::string use MafiaNet::to_string(guid) - // from "mafianet/guid_util.h". - // dest must be large enough to hold the output - // THREADSAFE - void ToString(char *dest) const; - void ToString(char *dest, size_t destSize) const; - - bool FromString(const char *source); - - static unsigned long ToUint32( const RakNetGUID &g ); - - RakNetGUID& operator = ( const RakNetGUID& input ) - { - g=input.g; - systemIndex=input.systemIndex; - return *this; - } - - // Used internally for fast lookup. Optional (use -1 to do regular lookup). Don't transmit this. - SystemIndex systemIndex; - static int size() {return (int) sizeof(uint64_t);} - - bool operator==( const RakNetGUID& right ) const; - bool operator!=( const RakNetGUID& right ) const; - bool operator > ( const RakNetGUID& right ) const; - bool operator < ( const RakNetGUID& right ) const; -}; - -/// Strong type for a peer's RakNetGUID value, distinct from NetworkID so the two -/// can't be passed interchangeably. Trivially copyable and 8 bytes, so it is -/// wire-compatible with the raw uint64_t it replaces. Convert with ToPeerGuid()/ToGuid(). -enum class PeerGuid : uint64_t {}; - -inline PeerGuid ToPeerGuid( const RakNetGUID& guid ) { return static_cast(guid.g); } -inline RakNetGUID ToGuid( PeerGuid guid ) { return RakNetGUID(static_cast(guid)); } - -constexpr PeerGuid UNASSIGNED_PEER_GUID = static_cast((uint64_t)-1); - -/// Index of an invalid SystemAddress -//const SystemAddress UNASSIGNED_SYSTEM_ADDRESS = -//{ -// 0xFFFFFFFF, 0xFFFF -//}; -#ifndef SWIG -extern const SystemAddress UNASSIGNED_SYSTEM_ADDRESS; -extern const RakNetGUID UNASSIGNED_RAKNET_GUID; -#endif -//{ -// {0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF} -// 0xFFFFFFFFFFFFFFFF -//}; - - -struct RAK_DLL_EXPORT AddressOrGUID -{ - RakNetGUID rakNetGuid; - SystemAddress systemAddress; - - SystemIndex GetSystemIndex(void) const {if (rakNetGuid!=UNASSIGNED_RAKNET_GUID) return rakNetGuid.systemIndex; else return systemAddress.systemIndex;} - bool IsUndefined(void) const {return rakNetGuid==UNASSIGNED_RAKNET_GUID && systemAddress==UNASSIGNED_SYSTEM_ADDRESS;} - void SetUndefined(void) {rakNetGuid=UNASSIGNED_RAKNET_GUID; systemAddress=UNASSIGNED_SYSTEM_ADDRESS;} - static unsigned long ToInteger( const AddressOrGUID &aog ); - const char *ToString(bool writePort=true) const; - void ToString(bool writePort, char *dest) const; - void ToString(bool writePort, char *dest, size_t destLength) const; - - AddressOrGUID() {} - AddressOrGUID( const AddressOrGUID& input ) - { - rakNetGuid=input.rakNetGuid; - systemAddress=input.systemAddress; - } - AddressOrGUID( const SystemAddress& input ) - { - rakNetGuid=UNASSIGNED_RAKNET_GUID; - systemAddress=input; - } - AddressOrGUID( Packet *packet ); - AddressOrGUID( const RakNetGUID& input ) - { - rakNetGuid=input; - systemAddress=UNASSIGNED_SYSTEM_ADDRESS; - } - AddressOrGUID& operator = ( const AddressOrGUID& input ) - { - rakNetGuid=input.rakNetGuid; - systemAddress=input.systemAddress; - return *this; - } - - AddressOrGUID& operator = ( const SystemAddress& input ) - { - rakNetGuid=UNASSIGNED_RAKNET_GUID; - systemAddress=input; - return *this; - } - - AddressOrGUID& operator = ( const RakNetGUID& input ) - { - rakNetGuid=input; - systemAddress=UNASSIGNED_SYSTEM_ADDRESS; - return *this; - } - - inline bool operator==( const AddressOrGUID& right ) const {return (rakNetGuid!=UNASSIGNED_RAKNET_GUID && rakNetGuid==right.rakNetGuid) || (systemAddress!=UNASSIGNED_SYSTEM_ADDRESS && systemAddress==right.systemAddress);} -}; - -typedef uint64_t NetworkID; - -/// This represents a user message from another system. -struct Packet -{ - /// The system that send this packet. - SystemAddress systemAddress; - - /// A unique identifier for the system that sent this packet, regardless of IP address (internal / external / remote system) - /// Only valid once a connection has been established (ID_CONNECTION_REQUEST_ACCEPTED, or ID_NEW_INCOMING_CONNECTION) - /// Until that time, will be UNASSIGNED_RAKNET_GUID - RakNetGUID guid; - - /// The length of the data in bytes - unsigned int length; - - /// The length of the data in bits - BitSize_t bitSize; - - /// The data from the sender - unsigned char* data; - - /// @internal - /// Indicates whether to delete the data, or to simply delete the packet. - bool deleteData; - - /// @internal - /// If true, this message is meant for the user, not for the plugins, so do not process it through plugins - bool wasGeneratedLocally; -}; - -/// Index of an unassigned player -const SystemIndex UNASSIGNED_PLAYER_INDEX = 65535; - -/// Unassigned object ID -const NetworkID UNASSIGNED_NETWORK_ID = (uint64_t) -1; - -const int PING_TIMES_ARRAY_SIZE = 5; - -struct RAK_DLL_EXPORT uint24_t -{ - uint32_t val; - - uint24_t() {} - inline operator uint32_t() { return val; } - inline operator uint32_t() const { return val; } - - inline uint24_t(const uint24_t& a) {val=a.val;} - inline uint24_t operator++() {++val; val&=0x00FFFFFF; return *this;} - inline uint24_t operator--() {--val; val&=0x00FFFFFF; return *this;} - inline uint24_t operator++(int) {uint24_t temp(val); ++val; val&=0x00FFFFFF; return temp;} - inline uint24_t operator--(int) {uint24_t temp(val); --val; val&=0x00FFFFFF; return temp;} - inline uint24_t operator&(const uint24_t& a) {return uint24_t(val&a.val);} - inline uint24_t& operator=(const uint24_t& a) { val=a.val; return *this; } - inline uint24_t& operator+=(const uint24_t& a) { val+=a.val; val&=0x00FFFFFF; return *this; } - inline uint24_t& operator-=(const uint24_t& a) { val-=a.val; val&=0x00FFFFFF; return *this; } - inline bool operator==( const uint24_t& right ) const {return val==right.val;} - inline bool operator!=( const uint24_t& right ) const {return val!=right.val;} - inline bool operator > ( const uint24_t& right ) const {return val>right.val;} - inline bool operator < ( const uint24_t& right ) const {return val ( const uint32_t& right ) const {return val>(right&0x00FFFFFF);} - inline bool operator < ( const uint32_t& right ) const {return val<(right&0x00FFFFFF);} - inline const uint24_t operator+( const uint32_t &other ) const { return uint24_t(val+other); } - inline const uint24_t operator-( const uint32_t &other ) const { return uint24_t(val-other); } - inline const uint24_t operator/( const uint32_t &other ) const { return uint24_t(val/other); } - inline const uint24_t operator*( const uint32_t &other ) const { return uint24_t(val*other); } -}; - -} // namespace MafiaNet - -#endif diff --git a/vendors/mafianet/Source/include/mafianet/version.h b/vendors/mafianet/Source/include/mafianet/version.h deleted file mode 100644 index c33536903..000000000 --- a/vendors/mafianet/Source/include/mafianet/version.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017-2019, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -// MafiaNet version. This is the current, authoritative version of the library. -// Keep in sync with the project() VERSION in the root CMakeLists.txt. -#define MAFIANET_VERSION "0.10.0" -#define MAFIANET_VERSION_NUMBER_INT 1000 -#define MAFIANET_VERSION_MAJOR 0 -#define MAFIANET_VERSION_MINOR 10 -#define MAFIANET_VERSION_PATCH 0 - -// Defines kept here for backwards compatibility with RAKNET 4.081/4.082. -// Usage of these defines is deprecated. Please switch to using MAFIANET version defines. -#define RAKNET_VERSION "4.082" -#define RAKNET_VERSION_NUMBER 4.082 -#define RAKNET_VERSION_NUMBER_INT 4082 -#define RAKNET_DATE "7/26/2017" - -#define SLIKENET_VERSION "0.1.3" -#define SLIKENET_VERSION_NUMBER 0.1.3 -#define SLIKENET_VERSION_NUMBER_INT 000103 -#define SLIKENET_DATE "23/08/2019" - -// What compatible protocol version RakNet is using. When this value changes, it indicates this version of RakNet cannot connection to an older version. -// ID_INCOMPATIBLE_PROTOCOL_VERSION will be returned on connection attempt in this case -#define RAKNET_PROTOCOL_VERSION 6 diff --git a/vendors/mafianet/Source/include/mafianet/wstring.h b/vendors/mafianet/Source/include/mafianet/wstring.h deleted file mode 100644 index bb5c9199d..000000000 --- a/vendors/mafianet/Source/include/mafianet/wstring.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#ifndef __RAK_W_STRING_H -#define __RAK_W_STRING_H - -#include "Export.h" -#include "types.h" // int64_t -#include "string.h" - -#ifdef _WIN32 -#include "WindowsIncludes.h" -#endif - -namespace MafiaNet -{ - /// \brief String class for Unicode - class RAK_DLL_EXPORT RakWString - { - public: - // Constructors - RakWString(); - RakWString( const RakString &right ); - RakWString( const wchar_t *input ); - RakWString( const RakWString & right); - RakWString( const char *input ); - ~RakWString(); - - /// Implicit return of wchar_t* - operator wchar_t* () const {if (c_str) return c_str; return (wchar_t*) L"";} - - /// Same as std::string::c_str - const wchar_t* C_String(void) const {if (c_str) return c_str; return (const wchar_t*) L"";} - - /// Assignment operators - RakWString& operator = ( const RakWString& right ); - RakWString& operator = ( const RakString& right ); - RakWString& operator = ( const wchar_t * const str ); - RakWString& operator = ( wchar_t *str ); - RakWString& operator = ( const char * const str ); - RakWString& operator = ( char *str ); - - /// Concatenation - RakWString& operator +=( const RakWString& right); - RakWString& operator += ( const wchar_t * const right ); - RakWString& operator += ( wchar_t *right ); - - /// Equality - bool operator==(const RakWString &right) const; - - // Comparison - bool operator < ( const RakWString& right ) const; - bool operator <= ( const RakWString& right ) const; - bool operator > ( const RakWString& right ) const; - bool operator >= ( const RakWString& right ) const; - - /// Inequality - bool operator!=(const RakWString &right) const; - - /// Set the value of the string - void Set( wchar_t *str ); - - /// Returns if the string is empty. Also, C_String() would return "" - bool IsEmpty(void) const; - - /// Returns the length of the string - size_t GetLength(void) const; - - /// Has the string into an unsigned int - static unsigned long ToInteger(const RakWString &rs); - - /// Compare strings (case sensitive) - int StrCmp(const RakWString &right) const; - - /// Compare strings (not case sensitive) - int StrICmp(const RakWString &right) const; - - /// Clear the string - void Clear(void); - - /// Print the string to the screen - void Printf(void); - - /// Print the string to a file - void FPrintf(FILE *fp); - - /// Serialize to a bitstream, uncompressed (slightly faster) - /// \param[out] bs Bitstream to serialize to - void Serialize(BitStream *bs) const; - - /// Static version of the Serialize function - static void Serialize(const wchar_t * const str, BitStream *bs); - - /// Deserialize what was written by Serialize - /// \param[in] bs Bitstream to serialize from - /// \return true if the deserialization was successful - bool Deserialize(BitStream *bs); - - /// Static version of the Deserialize() function - static bool Deserialize(wchar_t *str, BitStream *bs); - static bool Deserialize(wchar_t *str, size_t strLength, BitStream *bs); - - - protected: - wchar_t* c_str; - size_t c_strCharLength; - }; -} - -const MafiaNet::RakWString RAK_DLL_EXPORT operator+(const MafiaNet::RakWString &lhs, const MafiaNet::RakWString &rhs); - -#endif diff --git a/vendors/mafianet/Source/src/Base64Encoder.cpp b/vendors/mafianet/Source/src/Base64Encoder.cpp deleted file mode 100644 index 7808ffcdc..000000000 --- a/vendors/mafianet/Source/src/Base64Encoder.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/Base64Encoder.h" -#include "mafianet/memoryoverride.h" - -const char *Base64Map(void) {return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";} -const char *base64Map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -// 3/17/2013 must be unsigned char or else it will use negative indices -int Base64Encoding(const unsigned char *inputData, int dataLength, char *outputData) -{ - // http://en.wikipedia.org/wiki/Base64 - - int outputOffset, charCount; - int write3Count; - outputOffset=0; - charCount=0; - int j; - - write3Count=dataLength/3; - for (j=0; j < write3Count; j++) - { - // 6 leftmost bits from first byte, shifted to bits 7,8 are 0 - outputData[outputOffset++]=base64Map[inputData[j*3+0] >> 2]; - if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} - - // Remaining 2 bits from first byte, placed in position, and 4 high bits from the second byte, masked to ignore bits 7,8 - outputData[outputOffset++]=base64Map[((inputData[j*3+0] << 4) | (inputData[j*3+1] >> 4)) & 63]; - if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} - - // 4 low bits from the second byte and the two high bits from the third byte, masked to ignore bits 7,8 - outputData[outputOffset++]=base64Map[((inputData[j*3+1] << 2) | (inputData[j*3+2] >> 6)) & 63]; // Third 6 bits - if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} - - // Last 6 bits from the third byte, masked to ignore bits 7,8 - outputData[outputOffset++]=base64Map[inputData[j*3+2] & 63]; - if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} - } - - if (dataLength % 3==1) - { - // One input byte remaining - outputData[outputOffset++]=base64Map[inputData[j*3+0] >> 2]; - if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} - - // Remaining 2 bits from first byte, placed in position, and 4 high bits from the second byte, masked to ignore bits 7,8 - outputData[outputOffset++]=base64Map[((inputData[j*3+0] << 4) | (inputData[j*3+1] >> 4)) & 63]; - if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} - - // Pad with two equals - outputData[outputOffset++]='='; - outputData[outputOffset++]='='; - } - else if (dataLength % 3==2) - { - // Two input bytes remaining - - // 6 leftmost bits from first byte, shifted to bits 7,8 are 0 - outputData[outputOffset++]=base64Map[inputData[j*3+0] >> 2]; - if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} - - // Remaining 2 bits from first byte, placed in position, and 4 high bits from the second byte, masked to ignore bits 7,8 - outputData[outputOffset++]=base64Map[((inputData[j*3+0] << 4) | (inputData[j*3+1] >> 4)) & 63]; - if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} - - // 4 low bits from the second byte, followed by 00 - outputData[outputOffset++]=base64Map[(inputData[j*3+1] << 2) & 63]; // Third 6 bits - if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} - - // Pad with one equal - outputData[outputOffset++]='='; - //outputData[outputOffset++]='='; - } - - // Append \r\n - outputData[outputOffset++]='\r'; - outputData[outputOffset++]='\n'; - outputData[outputOffset]=0; - - return outputOffset; -} - -int Base64Encoding(const unsigned char *inputData, int dataLength, char **outputData) -{ - *outputData = (char*) rakMalloc_Ex(dataLength * 2 + 6, _FILE_AND_LINE_); - return Base64Encoding(inputData, dataLength, *outputData); -} diff --git a/vendors/mafianet/Source/src/BitStream.cpp b/vendors/mafianet/Source/src/BitStream.cpp deleted file mode 100644 index bfb9c6fa0..000000000 --- a/vendors/mafianet/Source/src/BitStream.cpp +++ /dev/null @@ -1,1235 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2019, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// -#include "mafianet/BitStream.h" - -#include -#include -#include -#include -#include - -#include "mafianet/SocketIncludes.h" -#include "mafianet/defines.h" - -#if defined(_WIN32) -#include "mafianet/WindowsIncludes.h" -#include -#else -#include -#if defined(ANDROID) -#include -#else -#include -#endif -#endif -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -// MSWin uses _copysign, others use copysign... -#ifndef _WIN32 -#define _copysign copysign -#endif - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(BitStream,BitStream) - -BitStream::BitStream() -{ - numberOfBitsUsed = 0; - //numberOfBitsAllocated = 32 * 8; - numberOfBitsAllocated = BITSTREAM_STACK_ALLOCATION_SIZE * 8; - readOffset = 0; - //data = ( unsigned char* ) rakMalloc_Ex( 32, _FILE_AND_LINE_ ); - data = ( unsigned char* ) stackData; - -#ifdef _DEBUG - // RakAssert( data ); -#endif - //memset(data, 0, 32); - copyData = true; -} - -BitStream::BitStream( const unsigned int initialBytesToAllocate ) -{ - numberOfBitsUsed = 0; - readOffset = 0; - if (initialBytesToAllocate <= BITSTREAM_STACK_ALLOCATION_SIZE) - { - data = ( unsigned char* ) stackData; - numberOfBitsAllocated = BITSTREAM_STACK_ALLOCATION_SIZE * 8; - } - else - { - data = ( unsigned char* ) rakMalloc_Ex( (size_t) initialBytesToAllocate, _FILE_AND_LINE_ ); - numberOfBitsAllocated = initialBytesToAllocate << 3; - } -#ifdef _DEBUG - RakAssert( data ); -#endif - // memset(data, 0, initialBytesToAllocate); - copyData = true; -} - -BitStream::BitStream( unsigned char* _data, const unsigned int lengthInBytes, bool _copyData ) -{ - numberOfBitsUsed = lengthInBytes << 3; - readOffset = 0; - copyData = _copyData; - numberOfBitsAllocated = lengthInBytes << 3; - - if ( copyData ) - { - if ( lengthInBytes > 0 ) - { - if (lengthInBytes < BITSTREAM_STACK_ALLOCATION_SIZE) - { - data = ( unsigned char* ) stackData; - numberOfBitsAllocated = BITSTREAM_STACK_ALLOCATION_SIZE << 3; - } - else - { - data = ( unsigned char* ) rakMalloc_Ex( (size_t) lengthInBytes, _FILE_AND_LINE_ ); - } -#ifdef _DEBUG - RakAssert( data ); -#endif - memcpy( data, _data, (size_t) lengthInBytes ); - } - else - data = 0; - } - else - data = ( unsigned char* ) _data; -} - -// Use this if you pass a pointer copy to the constructor (_copyData==false) and want to overallocate to prevent reallocation -void BitStream::SetNumberOfBitsAllocated( const BitSize_t lengthInBits ) -{ -#ifdef _DEBUG - RakAssert( lengthInBits >= ( BitSize_t ) numberOfBitsAllocated ); -#endif - numberOfBitsAllocated = lengthInBits; -} - -BitStream::~BitStream() -{ - if ( copyData && numberOfBitsAllocated > (BITSTREAM_STACK_ALLOCATION_SIZE << 3)) - rakFree_Ex( data , _FILE_AND_LINE_ ); // Use realloc and free so we are more efficient than delete and new for resizing -} - -void BitStream::Reset( void ) -{ - // Note: Do NOT reallocate memory because BitStream is used - // in places to serialize/deserialize a buffer. Reallocation - // is a dangerous operation (may result in leaks). - - if ( numberOfBitsUsed > 0 ) - { - // memset(data, 0, BITS_TO_BYTES(numberOfBitsUsed)); - } - - // Don't free memory here for speed efficiency - //free(data); // Use realloc and free so we are more efficient than delete and new for resizing - numberOfBitsUsed = 0; - - //numberOfBitsAllocated=8; - readOffset = 0; - - //data=(unsigned char*)rakMalloc_Ex(1, _FILE_AND_LINE_); - // if (numberOfBitsAllocated>0) - // memset(data, 0, BITS_TO_BYTES(numberOfBitsAllocated)); -} - -// Write an array or casted stream -void BitStream::Write( const char* inputByteArray, const unsigned int numberOfBytes ) -{ - if (numberOfBytes==0) - return; - - // Optimization: - if ((numberOfBitsUsed & 7) == 0) - { - AddBitsAndReallocate( BYTES_TO_BITS(numberOfBytes) ); - memcpy(data+BITS_TO_BYTES(numberOfBitsUsed), inputByteArray, (size_t) numberOfBytes); - numberOfBitsUsed+=BYTES_TO_BITS(numberOfBytes); - } - else - { - WriteBits( ( unsigned char* ) inputByteArray, numberOfBytes * 8, true ); - } - -} -void BitStream::Write( BitStream *bitStream) -{ - Write(bitStream, bitStream->GetNumberOfBitsUsed()-bitStream->GetReadOffset()); -} -void BitStream::Write( BitStream *bitStream, BitSize_t numberOfBits ) -{ - if (numberOfBits > bitStream->GetNumberOfUnreadBits()) - return; - - AddBitsAndReallocate( numberOfBits ); - BitSize_t numberOfBitsMod8; - - if ((bitStream->GetReadOffset()&7)==0 && (numberOfBitsUsed&7)==0) - { - int readOffsetBytes=bitStream->GetReadOffset()/8; - int numBytes=numberOfBits/8; - memcpy(data + (numberOfBitsUsed >> 3), bitStream->GetData()+readOffsetBytes, numBytes); - numberOfBits-=BYTES_TO_BITS(numBytes); - bitStream->SetReadOffset(BYTES_TO_BITS(numBytes+readOffsetBytes)); - numberOfBitsUsed+=BYTES_TO_BITS(numBytes); - } - - while (numberOfBits-->0) - { - numberOfBitsMod8 = numberOfBitsUsed & 7; - if ( numberOfBitsMod8 == 0 ) - { - // New byte - if (bitStream->data[ bitStream->readOffset >> 3 ] & ( 0x80 >> ( bitStream->readOffset & 7 ) ) ) - { - // Write 1 - data[ numberOfBitsUsed >> 3 ] = 0x80; - } - else - { - // Write 0 - data[ numberOfBitsUsed >> 3 ] = 0; - } - - } - else - { - // Existing byte - if (bitStream->data[ bitStream->readOffset >> 3 ] & ( 0x80 >> ( bitStream->readOffset & 7 ) ) ) - data[ numberOfBitsUsed >> 3 ] |= 0x80 >> ( numberOfBitsMod8 ); // Set the bit to 1 - // else 0, do nothing - } - - bitStream->readOffset++; - numberOfBitsUsed++; - } -} -void BitStream::Write( BitStream &bitStream, BitSize_t numberOfBits ) -{ - Write(&bitStream, numberOfBits); -} -void BitStream::Write( BitStream &bitStream ) -{ - Write(&bitStream); -} -bool BitStream::Read( BitStream *bitStream, BitSize_t numberOfBits ) -{ - if (GetNumberOfUnreadBits() < numberOfBits) - return false; - bitStream->Write(this, numberOfBits); - return true; -} -bool BitStream::Read( BitStream *bitStream ) -{ - bitStream->Write(this); - return true; -} -bool BitStream::Read( BitStream &bitStream, BitSize_t numberOfBits ) -{ - if (GetNumberOfUnreadBits() < numberOfBits) - return false; - bitStream.Write(this, numberOfBits); - return true; -} -bool BitStream::Read( BitStream &bitStream ) -{ - bitStream.Write(this); - return true; -} - -// Read an array or casted stream -bool BitStream::Read( char* outByteArray, const unsigned int numberOfBytes ) -{ - // Optimization: - if ((readOffset & 7) == 0) - { - if (GetNumberOfUnreadBits() < (numberOfBytes << 3)) - return false; - - // Write the data - memcpy( outByteArray, data + ( readOffset >> 3 ), (size_t) numberOfBytes ); - - readOffset += numberOfBytes << 3; - return true; - } - - return ReadBits( ( unsigned char* ) outByteArray, numberOfBytes * 8 ); -} - -// Sets the read pointer back to the beginning of your data. -void BitStream::ResetReadPointer( void ) -{ - readOffset = 0; -} - -// Sets the write pointer back to the beginning of your data. -void BitStream::ResetWritePointer( void ) -{ - numberOfBitsUsed = 0; -} - -// Write a 0 -void BitStream::Write0( void ) -{ - AddBitsAndReallocate( 1 ); - - // New bytes need to be zeroed - if ( ( numberOfBitsUsed & 7 ) == 0 ) - data[ numberOfBitsUsed >> 3 ] = 0; - - numberOfBitsUsed++; -} - -// Write a 1 -void BitStream::Write1( void ) -{ - AddBitsAndReallocate( 1 ); - - BitSize_t numberOfBitsMod8 = numberOfBitsUsed & 7; - - if ( numberOfBitsMod8 == 0 ) - data[ numberOfBitsUsed >> 3 ] = 0x80; - else - data[ numberOfBitsUsed >> 3 ] |= 0x80 >> ( numberOfBitsMod8 ); // Set the bit to 1 - - numberOfBitsUsed++; -} - -// Returns true if the next data read is a 1, false if it is a 0 -bool BitStream::ReadBit( void ) -{ - if (GetNumberOfUnreadBits() == 0) { - return false; - } - - bool result = ( data[ readOffset >> 3 ] & ( 0x80 >> ( readOffset & 7 ) ) ) !=0; - readOffset++; - return result; -} - -// Align the bitstream to the byte boundary and then write the specified number of bits. -// This is faster than WriteBits but wastes the bits to do the alignment and requires you to call -// SetReadToByteAlignment at the corresponding read position -void BitStream::WriteAlignedBytes( const unsigned char* inByteArray, const unsigned int numberOfBytesToWrite ) -{ - AlignWriteToByteBoundary(); - Write((const char*) inByteArray, numberOfBytesToWrite); -} -void BitStream::EndianSwapBytes( int byteOffset, int length ) -{ - if (DoEndianSwap()) - { - ReverseBytesInPlace(data+byteOffset, length); - } -} -/// Aligns the bitstream, writes inputLength, and writes input. Won't write beyond maxBytesToWrite -void BitStream::WriteAlignedBytesSafe( const char *inByteArray, const unsigned int inputLength, const unsigned int maxBytesToWrite ) -{ - if (inByteArray==0 || inputLength==0) - { - WriteCompressed((unsigned int)0); - return; - } - WriteCompressed(inputLength); - WriteAlignedBytes((const unsigned char*) inByteArray, inputLength < maxBytesToWrite ? inputLength : maxBytesToWrite); -} - -// Read bits, starting at the next aligned bits. Note that the modulus 8 starting offset of the -// sequence must be the same as was used with WriteBits. This will be a problem with packet coalescence -// unless you byte align the coalesced packets. -bool BitStream::ReadAlignedBytes( unsigned char* inOutByteArray, const unsigned int numberOfBytesToRead ) -{ -#ifdef _DEBUG - RakAssert( numberOfBytesToRead > 0 ); -#endif - - if ( numberOfBytesToRead <= 0 ) - return false; - - // Byte align - AlignReadToByteBoundary(); - - if (GetNumberOfUnreadBits() < (numberOfBytesToRead << 3)) - return false; - - // Write the data - memcpy( inOutByteArray, data + ( readOffset >> 3 ), (size_t) numberOfBytesToRead ); - - readOffset += numberOfBytesToRead << 3; - - return true; -} -bool BitStream::ReadAlignedBytesSafe( char *inOutByteArray, int &inputLength, const int maxBytesToRead ) -{ - return ReadAlignedBytesSafe(inOutByteArray,(unsigned int&) inputLength,(unsigned int)maxBytesToRead); -} -bool BitStream::ReadAlignedBytesSafe( char *inOutByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead ) -{ - if (ReadCompressed(inputLength)==false) - return false; - if (inputLength > maxBytesToRead) - inputLength=maxBytesToRead; - if (inputLength==0) - return true; - return ReadAlignedBytes((unsigned char*) inOutByteArray, inputLength); -} -bool BitStream::ReadAlignedBytesSafeAlloc( char **outByteArray, int &inputLength, const unsigned int maxBytesToRead ) -{ - return ReadAlignedBytesSafeAlloc(outByteArray,(unsigned int&) inputLength, maxBytesToRead); -} -bool BitStream::ReadAlignedBytesSafeAlloc( char ** outByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead ) -{ - rakFree_Ex(*outByteArray, _FILE_AND_LINE_ ); - *outByteArray=0; - if (ReadCompressed(inputLength)==false) - return false; - if (inputLength > maxBytesToRead) - inputLength=maxBytesToRead; - if (inputLength==0) - return true; - *outByteArray = (char*) rakMalloc_Ex( (size_t) inputLength, _FILE_AND_LINE_ ); - return ReadAlignedBytes((unsigned char*) *outByteArray, inputLength); -} - -// Write numberToWrite bits from the input source -void BitStream::WriteBits( const unsigned char* inByteArray, BitSize_t numberOfBitsToWrite, const bool rightAlignedBits ) -{ -// if (numberOfBitsToWrite<=0) -// return; - - AddBitsAndReallocate( numberOfBitsToWrite ); - - const BitSize_t numberOfBitsUsedMod8 = numberOfBitsUsed & 7; - - // If currently aligned and numberOfBits is a multiple of 8, just memcpy for speed - if (numberOfBitsUsedMod8==0 && (numberOfBitsToWrite&7)==0) - { - memcpy( data + ( numberOfBitsUsed >> 3 ), inByteArray, numberOfBitsToWrite>>3); - numberOfBitsUsed+=numberOfBitsToWrite; - return; - } - - unsigned char dataByte; - const unsigned char* inputPtr=inByteArray; - - // Faster to put the while at the top surprisingly enough - while ( numberOfBitsToWrite > 0 ) - //do - { - dataByte = *( inputPtr++ ); - - if ( numberOfBitsToWrite < 8 && rightAlignedBits ) // rightAlignedBits means in the case of a partial byte, the bits are aligned from the right (bit 0) rather than the left (as in the normal internal representation) - dataByte <<= 8 - numberOfBitsToWrite; // shift left to get the bits on the left, as in our internal representation - - // Writing to a new byte each time - if ( numberOfBitsUsedMod8 == 0 ) - * ( data + ( numberOfBitsUsed >> 3 ) ) = dataByte; - else - { - // Copy over the new data. - *( data + ( numberOfBitsUsed >> 3 ) ) |= dataByte >> ( numberOfBitsUsedMod8 ); // First half - - if ( 8 - ( numberOfBitsUsedMod8 ) < 8 && 8 - ( numberOfBitsUsedMod8 ) < numberOfBitsToWrite ) // If we didn't write it all out in the first half (8 - (numberOfBitsUsed%8) is the number we wrote in the first half) - { - *( data + ( numberOfBitsUsed >> 3 ) + 1 ) = (unsigned char) ( dataByte << ( 8 - ( numberOfBitsUsedMod8 ) ) ); // Second half (overlaps byte boundary) - } - } - - if ( numberOfBitsToWrite >= 8 ) - { - numberOfBitsUsed += 8; - numberOfBitsToWrite -= 8; - } - else - { - numberOfBitsUsed += numberOfBitsToWrite; - numberOfBitsToWrite=0; - } - } - // } while(numberOfBitsToWrite>0); -} - -// Set the stream to some initial data. For internal use -void BitStream::SetData( unsigned char *inByteArray ) -{ - data=inByteArray; - copyData=false; -} - -// Assume the input source points to a native type, compress and write it -void BitStream::WriteCompressed( const unsigned char* inByteArray, - const unsigned int size, const bool unsignedData ) -{ - BitSize_t currentByte = ( size >> 3 ) - 1; // PCs - - unsigned char byteMatch; - - if ( unsignedData ) - { - byteMatch = 0; - } - - else - { - byteMatch = 0xFF; - } - - // Write upper bytes with a single 1 - // From high byte to low byte, if high byte is a byteMatch then write a 1 bit. Otherwise write a 0 bit and then write the remaining bytes - while ( currentByte > 0 ) - { - if ( inByteArray[ currentByte ] == byteMatch ) // If high byte is byteMatch (0 of 0xff) then it would have the same value shifted - { - bool b = true; - Write( b ); - } - else - { - // Write the remainder of the data after writing 0 - bool b = false; - Write( b ); - - WriteBits( inByteArray, ( currentByte + 1 ) << 3, true ); - // currentByte--; - - - return ; - } - - currentByte--; - } - - // If the upper half of the last byte is a 0 (positive) or 16 (negative) then write a 1 and the remaining 4 bits. Otherwise write a 0 and the 8 bites. - if ( ( unsignedData && ( ( *( inByteArray + currentByte ) ) & 0xF0 ) == 0x00 ) || - ( unsignedData == false && ( ( *( inByteArray + currentByte ) ) & 0xF0 ) == 0xF0 ) ) - { - bool b = true; - Write( b ); - WriteBits( inByteArray + currentByte, 4, true ); - } - - else - { - bool b = false; - Write( b ); - WriteBits( inByteArray + currentByte, 8, true ); - } -} - -void BitStream::AlignReadToByteBoundary() -{ - readOffset += 8 - ( (( readOffset - 1 ) & 7 ) + 1 ); -} - -// Read numberOfBitsToRead bits to the output source -// alignBitsToRight should be set to true to convert internal bitstream data to userdata -// It should be false if you used WriteBits with rightAlignedBits false -bool BitStream::ReadBits( unsigned char *inOutByteArray, BitSize_t numberOfBitsToRead, const bool alignBitsToRight ) -{ -#ifdef _DEBUG - // RakAssert( numberOfBitsToRead > 0 ); -#endif - if (numberOfBitsToRead<=0) - return false; - - if (GetNumberOfUnreadBits() < numberOfBitsToRead) - return false; - - - const BitSize_t readOffsetMod8 = readOffset & 7; - - // If currently aligned and numberOfBits is a multiple of 8, just memcpy for speed - if (readOffsetMod8==0 && (numberOfBitsToRead&7)==0) - { - memcpy( inOutByteArray, data + ( readOffset >> 3 ), numberOfBitsToRead>>3); - readOffset+=numberOfBitsToRead; - return true; - } - - - - BitSize_t offset = 0; - - memset( inOutByteArray, 0, (size_t) BITS_TO_BYTES( numberOfBitsToRead ) ); - - while ( numberOfBitsToRead > 0 ) - { - *( inOutByteArray + offset ) |= *( data + ( readOffset >> 3 ) ) << ( readOffsetMod8 ); // First half - - if ( readOffsetMod8 > 0 && numberOfBitsToRead > 8 - ( readOffsetMod8 ) ) // If we have a second half, we didn't read enough bytes in the first half - *( inOutByteArray + offset ) |= *( data + ( readOffset >> 3 ) + 1 ) >> ( 8 - ( readOffsetMod8 ) ); // Second half (overlaps byte boundary) - - if (numberOfBitsToRead>=8) - { - numberOfBitsToRead -= 8; - readOffset += 8; - offset++; - } - else - { - int neg = (int) numberOfBitsToRead - 8; - - if ( neg < 0 ) // Reading a partial byte for the last byte, shift right so the data is aligned on the right - { - - if ( alignBitsToRight ) - * ( inOutByteArray + offset ) >>= -neg; - - readOffset += 8 + neg; - } - else - readOffset += 8; - - offset++; - - numberOfBitsToRead=0; - } - } - - return true; -} - -// Assume the input source points to a compressed native type. Decompress and read it -bool BitStream::ReadCompressed( unsigned char* inOutByteArray, - const unsigned int size, const bool unsignedData ) -{ - unsigned int currentByte = ( size >> 3 ) - 1; - - - unsigned char byteMatch, halfByteMatch; - - if ( unsignedData ) - { - byteMatch = 0; - halfByteMatch = 0; - } - - else - { - byteMatch = 0xFF; - halfByteMatch = 0xF0; - } - - // Upper bytes are specified with a single 1 if they match byteMatch - // From high byte to low byte, if high byte is a byteMatch then write a 1 bit. Otherwise write a 0 bit and then write the remaining bytes - while ( currentByte > 0 ) - { - // If we read a 1 then the data is byteMatch. - - bool b; - - if ( Read( b ) == false ) - return false; - - if ( b ) // Check that bit - { - inOutByteArray[ currentByte ] = byteMatch; - currentByte--; - } - else - { - // Read the rest of the bytes - - if ( ReadBits( inOutByteArray, ( currentByte + 1 ) << 3 ) == false ) - return false; - - return true; - } - } - - // All but the first bytes are byteMatch. If the upper half of the last byte is a 0 (positive) or 16 (negative) then what we read will be a 1 and the remaining 4 bits. - // Otherwise we read a 0 and the 8 bytes - //RakAssert(readOffset+1 <=numberOfBitsUsed); // If this assert is hit the stream wasn't long enough to read from - if ( readOffset + 1 > numberOfBitsUsed ) - return false; - - bool b=false; - - if ( Read( b ) == false ) - return false; - - if ( b ) // Check that bit - { - - if ( ReadBits( inOutByteArray + currentByte, 4 ) == false ) - return false; - - inOutByteArray[ currentByte ] |= halfByteMatch; // We have to set the high 4 bits since these are set to 0 by ReadBits - } - else - { - if ( ReadBits( inOutByteArray + currentByte, 8 ) == false ) - return false; - } - - return true; -} - -// Reallocates (if necessary) in preparation of writing numberOfBitsToWrite -void BitStream::AddBitsAndReallocate( const BitSize_t numberOfBitsToWrite ) -{ - BitSize_t newNumberOfBitsAllocated = numberOfBitsToWrite + numberOfBitsUsed; - - if ( numberOfBitsToWrite + numberOfBitsUsed > 0 && ( ( numberOfBitsAllocated - 1 ) >> 3 ) < ( ( newNumberOfBitsAllocated - 1 ) >> 3 ) ) // If we need to allocate 1 or more new bytes - { -#ifdef _DEBUG - // If this assert hits then we need to specify true for the third parameter in the constructor - // It needs to reallocate to hold all the data and can't do it unless we allocated to begin with - // Often hits if you call Write or Serialize on a read-only bitstream - RakAssert( copyData == true ); -#endif - - // Less memory efficient but saves on news and deletes - /// Cap to 1 meg buffer to save on huge allocations - newNumberOfBitsAllocated = ( numberOfBitsToWrite + numberOfBitsUsed ) * 2; - if (newNumberOfBitsAllocated - ( numberOfBitsToWrite + numberOfBitsUsed ) > 1048576 ) - newNumberOfBitsAllocated = numberOfBitsToWrite + numberOfBitsUsed + 1048576; - - // BitSize_t newByteOffset = BITS_TO_BYTES( numberOfBitsAllocated ); - // Use realloc and free so we are more efficient than delete and new for resizing - BitSize_t amountToAllocate = BITS_TO_BYTES( newNumberOfBitsAllocated ); - if (data==(unsigned char*)stackData) - { - if (amountToAllocate > BITSTREAM_STACK_ALLOCATION_SIZE) - { - data = ( unsigned char* ) rakMalloc_Ex( (size_t) amountToAllocate, _FILE_AND_LINE_ ); - RakAssert(data); - - // need to copy the stack data over to our new memory area too - memcpy ((void *)data, (void *)stackData, (size_t) BITS_TO_BYTES( numberOfBitsAllocated )); - } - } - else - { - data = ( unsigned char* ) rakRealloc_Ex( data, (size_t) amountToAllocate, _FILE_AND_LINE_ ); - } - -#ifdef _DEBUG - RakAssert( data ); // Make sure realloc succeeded -#endif - // memset(data+newByteOffset, 0, ((newNumberOfBitsAllocated-1)>>3) - ((numberOfBitsAllocated-1)>>3)); // Set the new data block to 0 - } - - if ( newNumberOfBitsAllocated > numberOfBitsAllocated ) - numberOfBitsAllocated = newNumberOfBitsAllocated; -} -BitSize_t BitStream::GetNumberOfBitsAllocated(void) const -{ - return numberOfBitsAllocated; -} -void BitStream::PadWithZeroToByteLength( unsigned int bytes ) -{ - if (GetNumberOfBytesUsed() < bytes) - { - AlignWriteToByteBoundary(); - unsigned int numToWrite = bytes - GetNumberOfBytesUsed(); - AddBitsAndReallocate( BYTES_TO_BITS(numToWrite) ); - memset(data+BITS_TO_BYTES(numberOfBitsUsed), 0, (size_t) numToWrite); - numberOfBitsUsed+=BYTES_TO_BITS(numToWrite); - } -} - -/* -// Julius Goryavsky's version of Harley's algorithm. -// 17 elementary ops plus an indexed load, if the machine -// has "and not." - -int nlz10b(unsigned x) { - - static char table[64] = - {32,20,19, u, u,18, u, 7, 10,17, u, u,14, u, 6, u, - u, 9, u,16, u, u, 1,26, u,13, u, u,24, 5, u, u, - u,21, u, 8,11, u,15, u, u, u, u, 2,27, 0,25, u, - 22, u,12, u, u, 3,28, u, 23, u, 4,29, u, u,30,31}; - - x = x | (x >> 1); // Propagate leftmost - x = x | (x >> 2); // 1-bit to the right. - x = x | (x >> 4); - x = x | (x >> 8); - x = x & ~(x >> 16); - x = x*0xFD7049FF; // Activate this line or the following 3. -// x = (x << 9) - x; // Multiply by 511. -// x = (x << 11) - x; // Multiply by 2047. -// x = (x << 14) - x; // Multiply by 16383. - return table[x >> 26]; -} -*/ -int BitStream::NumberOfLeadingZeroes( int8_t x ) {return NumberOfLeadingZeroes((uint8_t)x);} -int BitStream::NumberOfLeadingZeroes( uint8_t x ) -{ - uint8_t y; - int n; - - n = 8; - y = x >> 4; if (y != 0) {n = n - 4; x = y;} - y = x >> 2; if (y != 0) {n = n - 2; x = y;} - y = x >> 1; if (y != 0) return n - 2; - return (int)(n - x); -} -int BitStream::NumberOfLeadingZeroes( int16_t x ) {return NumberOfLeadingZeroes((uint16_t)x);} -int BitStream::NumberOfLeadingZeroes( uint16_t x ) -{ - uint16_t y; - int n; - - n = 16; - y = x >> 8; if (y != 0) {n = n - 8; x = y;} - y = x >> 4; if (y != 0) {n = n - 4; x = y;} - y = x >> 2; if (y != 0) {n = n - 2; x = y;} - y = x >> 1; if (y != 0) return n - 2; - return (int)(n - x); -} -int BitStream::NumberOfLeadingZeroes( int32_t x ) {return NumberOfLeadingZeroes((uint32_t)x);} -int BitStream::NumberOfLeadingZeroes( uint32_t x ) -{ - uint32_t y; - int n; - - n = 32; - y = x >>16; if (y != 0) {n = n -16; x = y;} - y = x >> 8; if (y != 0) {n = n - 8; x = y;} - y = x >> 4; if (y != 0) {n = n - 4; x = y;} - y = x >> 2; if (y != 0) {n = n - 2; x = y;} - y = x >> 1; if (y != 0) return n - 2; - return (int)(n - x); -} -int BitStream::NumberOfLeadingZeroes( int64_t x ) {return NumberOfLeadingZeroes((uint64_t)x);} -int BitStream::NumberOfLeadingZeroes( uint64_t x ) -{ - uint64_t y; - int n; - - n = 64; - y = x >>32; if (y != 0) {n = n -32; x = y;} - y = x >>16; if (y != 0) {n = n -16; x = y;} - y = x >> 8; if (y != 0) {n = n - 8; x = y;} - y = x >> 4; if (y != 0) {n = n - 4; x = y;} - y = x >> 2; if (y != 0) {n = n - 2; x = y;} - y = x >> 1; if (y != 0) return n - 2; - return (int)(n - x); -} - -// Should hit if reads didn't match writes -void BitStream::AssertStreamEmpty( void ) -{ - RakAssert( readOffset == numberOfBitsUsed ); -} - -void BitStream::PrintBits( char *out ) const -{ - if (numberOfBitsUsed <= 0) - { -#pragma warning(push) -#pragma warning(disable:4996) - strcpy(out, "No bits\n"); -#pragma warning(pop) - return; - } - - unsigned int strIndex = 0; - for (BitSize_t counter = 0; counter < BITS_TO_BYTES(numberOfBitsUsed) && strIndex < 2000; counter++) - { - BitSize_t stop; - - if (counter == (numberOfBitsUsed - 1) >> 3) - stop = 8 - (((numberOfBitsUsed - 1) & 7) + 1); - else - stop = 0; - - for (BitSize_t counter2 = 7; counter2 >= stop; counter2--) - { - if ((data[counter] >> counter2) & 1) - out[strIndex++] = '1'; - else - out[strIndex++] = '0'; - - if (counter2 == 0) - break; - } - - out[strIndex++] = ' '; - } - - out[strIndex++] = '\n'; - - out[strIndex++] = 0; -} - -void BitStream::PrintBits( char *out, size_t outLength ) const -{ - if ( numberOfBitsUsed <= 0 ) - { - strcpy_s(out, outLength, "No bits\n" ); - return; - } - - unsigned int strIndex=0; - for ( BitSize_t counter = 0; counter < BITS_TO_BYTES( numberOfBitsUsed ) && strIndex < 2000 ; counter++ ) - { - BitSize_t stop; - - if ( counter == ( numberOfBitsUsed - 1 ) >> 3 ) - stop = 8 - ( ( ( numberOfBitsUsed - 1 ) & 7 ) + 1 ); - else - stop = 0; - - for ( BitSize_t counter2 = 7; counter2 >= stop; counter2-- ) - { - if ( ( data[ counter ] >> counter2 ) & 1 ) - out[strIndex++]='1'; - else - out[strIndex++]='0'; - - if (counter2==0) - break; - } - - out[strIndex++]=' '; - } - - out[strIndex++]='\n'; - - out[strIndex++]=0; -} -void BitStream::PrintBits( void ) const -{ - char out[2048]; - PrintBits(out, 2048); - RAKNET_DEBUG_PRINTF("%s", out); -} - -void BitStream::PrintHex( char *out, size_t outLength ) const -{ - BitSize_t i; - for ( i=0; i < GetNumberOfBytesUsed(); i++) - { - sprintf_s(out+i*3, outLength-i*3, "%02x ", data[i]); - } -} - -void BitStream::PrintHex( char *out ) const -{ - BitSize_t i; - for (i = 0; i < GetNumberOfBytesUsed(); i++) - { -#pragma warning(push) -#pragma warning(disable:4996) - sprintf(out + i * 3, "%02x ", data[i]); -#pragma warning(pop) - } -} - -void BitStream::PrintHex( void ) const -{ - char out[2048]; - PrintHex(out, 2048); - RAKNET_DEBUG_PRINTF("%s", out); -} - -void BitStream::SetReadOffset(const BitSize_t newReadOffset) -{ - readOffset = newReadOffset; -} - -// Exposes the data for you to look at, like PrintBits does. -// Data will point to the stream. Returns the length in bits of the stream. -BitSize_t BitStream::CopyData( unsigned char** _data ) const -{ -#ifdef _DEBUG - RakAssert( numberOfBitsUsed > 0 ); -#endif - - *_data = (unsigned char*) rakMalloc_Ex( (size_t) BITS_TO_BYTES( numberOfBitsUsed ), _FILE_AND_LINE_ ); - memcpy( *_data, data, sizeof(unsigned char) * (size_t) ( BITS_TO_BYTES( numberOfBitsUsed ) ) ); - return numberOfBitsUsed; -} - -// Ignore data we don't intend to read -void BitStream::IgnoreBits( const BitSize_t numberOfBits ) -{ - readOffset += numberOfBits; -} - -void BitStream::IgnoreBytes( const unsigned int numberOfBytes ) -{ - IgnoreBits(BYTES_TO_BITS(numberOfBytes)); -} - -// Move the write pointer to a position on the array. Dangerous if you don't know what you are doing! -// Doesn't work with non-aligned data! -void BitStream::SetWriteOffset( const BitSize_t offset ) -{ - numberOfBitsUsed = offset; -} - -/* -BitSize_t BitStream::GetWriteOffset( void ) const -{ -return numberOfBitsUsed; -} - -// Returns the length in bits of the stream -BitSize_t BitStream::GetNumberOfBitsUsed( void ) const -{ -return GetWriteOffset(); -} - -// Returns the length in bytes of the stream -BitSize_t BitStream::GetNumberOfBytesUsed( void ) const -{ -return BITS_TO_BYTES( numberOfBitsUsed ); -} - -// Returns the number of bits into the stream that we have read -BitSize_t BitStream::GetReadOffset( void ) const -{ -return readOffset; -} - - -// Sets the read bit index -void BitStream::SetReadOffset( const BitSize_t newReadOffset ) -{ -readOffset=newReadOffset; -} - -// Returns the number of bits left in the stream that haven't been read -BitSize_t BitStream::GetNumberOfUnreadBits( void ) const -{ -return numberOfBitsUsed - readOffset; -} -// Exposes the internal data -unsigned char* BitStream::GetData( void ) const -{ -return data; -} - -*/ -// If we used the constructor version with copy data off, this makes sure it is set to on and the data pointed to is copied. -void BitStream::AssertCopyData( void ) -{ - if ( copyData == false ) - { - copyData = true; - - if ( numberOfBitsAllocated > 0 ) - { - unsigned char * newdata = ( unsigned char* ) rakMalloc_Ex( (size_t) BITS_TO_BYTES( numberOfBitsAllocated ), _FILE_AND_LINE_ ); -#ifdef _DEBUG - - RakAssert( data ); -#endif - - memcpy( newdata, data, (size_t) BITS_TO_BYTES( numberOfBitsAllocated ) ); - data = newdata; - } - - else - data = 0; - } -} -bool BitStream::IsNetworkOrderInternal(void) -{ - - - - - - static unsigned long htonlValue = htonl(12345); - return htonlValue == 12345; - -} -void BitStream::ReverseBytes(unsigned char *inByteArray, unsigned char *inOutByteArray, const unsigned int length) -{ - for (BitSize_t i=0; i < length; i++) - inOutByteArray[i]=inByteArray[length-i-1]; -} -void BitStream::ReverseBytesInPlace(unsigned char *inOutData,const unsigned int length) -{ - unsigned char temp; - BitSize_t i; - for (i=0; i < (length>>1); i++) - { - temp = inOutData[i]; - inOutData[i]=inOutData[length-i-1]; - inOutData[length-i-1]=temp; - } -} - -bool BitStream::Read(char *varString) -{ - return RakString::Deserialize(varString,this); -} -bool BitStream::Read(unsigned char *varString) -{ - return RakString::Deserialize((char*) varString,this); -} -void BitStream::WriteAlignedVar8(const char *inByteArray) -{ - RakAssert((numberOfBitsUsed&7)==0); - AddBitsAndReallocate(1*8); - data[( numberOfBitsUsed >> 3 ) + 0] = inByteArray[0]; - numberOfBitsUsed+=1*8; -} -bool BitStream::ReadAlignedVar8(char *inOutByteArray) -{ - RakAssert((readOffset&7)==0); - if (GetNumberOfUnreadBits() < 1 * 8) - return false; - - inOutByteArray[0] = data[( readOffset >> 3 ) + 0]; - readOffset+=1*8; - return true; -} -void BitStream::WriteAlignedVar16(const char *inByteArray) -{ - RakAssert((numberOfBitsUsed&7)==0); - AddBitsAndReallocate(2*8); -#ifndef __BITSTREAM_NATIVE_END - if (DoEndianSwap()) - { - data[( numberOfBitsUsed >> 3 ) + 0] = inByteArray[1]; - data[( numberOfBitsUsed >> 3 ) + 1] = inByteArray[0]; - } - else -#endif - { - data[( numberOfBitsUsed >> 3 ) + 0] = inByteArray[0]; - data[( numberOfBitsUsed >> 3 ) + 1] = inByteArray[1]; - } - - numberOfBitsUsed+=2*8; -} -bool BitStream::ReadAlignedVar16(char *inOutByteArray) -{ - RakAssert((readOffset&7)==0); - if (GetNumberOfUnreadBits() < 2 * 8) - return false; -#ifndef __BITSTREAM_NATIVE_END - if (DoEndianSwap()) - { - inOutByteArray[0] = data[( readOffset >> 3 ) + 1]; - inOutByteArray[1] = data[( readOffset >> 3 ) + 0]; - } - else -#endif - { - inOutByteArray[0] = data[( readOffset >> 3 ) + 0]; - inOutByteArray[1] = data[( readOffset >> 3 ) + 1]; - } - - readOffset+=2*8; - return true; -} -void BitStream::WriteAlignedVar32(const char *inByteArray) -{ - RakAssert((numberOfBitsUsed&7)==0); - AddBitsAndReallocate(4*8); -#ifndef __BITSTREAM_NATIVE_END - if (DoEndianSwap()) - { - data[( numberOfBitsUsed >> 3 ) + 0] = inByteArray[3]; - data[( numberOfBitsUsed >> 3 ) + 1] = inByteArray[2]; - data[( numberOfBitsUsed >> 3 ) + 2] = inByteArray[1]; - data[( numberOfBitsUsed >> 3 ) + 3] = inByteArray[0]; - } - else -#endif - { - data[( numberOfBitsUsed >> 3 ) + 0] = inByteArray[0]; - data[( numberOfBitsUsed >> 3 ) + 1] = inByteArray[1]; - data[( numberOfBitsUsed >> 3 ) + 2] = inByteArray[2]; - data[( numberOfBitsUsed >> 3 ) + 3] = inByteArray[3]; - } - - numberOfBitsUsed+=4*8; -} -bool BitStream::ReadAlignedVar32(char *inOutByteArray) -{ - RakAssert((readOffset&7)==0); - if (GetNumberOfUnreadBits() < 4*8) - return false; -#ifndef __BITSTREAM_NATIVE_END - if (DoEndianSwap()) - { - inOutByteArray[0] = data[( readOffset >> 3 ) + 3]; - inOutByteArray[1] = data[( readOffset >> 3 ) + 2]; - inOutByteArray[2] = data[( readOffset >> 3 ) + 1]; - inOutByteArray[3] = data[( readOffset >> 3 ) + 0]; - } - else -#endif - { - inOutByteArray[0] = data[( readOffset >> 3 ) + 0]; - inOutByteArray[1] = data[( readOffset >> 3 ) + 1]; - inOutByteArray[2] = data[( readOffset >> 3 ) + 2]; - inOutByteArray[3] = data[( readOffset >> 3 ) + 3]; - } - - readOffset+=4*8; - return true; -} -bool BitStream::ReadFloat16( float &outFloat, float floatMin, float floatMax ) -{ - unsigned short percentile; - if (Read(percentile)) - { - RakAssert(floatMax>floatMin); - outFloat = floatMin + ((float) percentile / 65535.0f) * (floatMax-floatMin); - if (outFloatfloatMax) - outFloat=floatMax; - return true; - } - return false; -} -bool BitStream::SerializeFloat16(bool writeToBitstream, float &inOutFloat, float floatMin, float floatMax) -{ - if (writeToBitstream) - WriteFloat16(inOutFloat, floatMin, floatMax); - else - return ReadFloat16(inOutFloat, floatMin, floatMax); - return true; -} -void BitStream::WriteFloat16( float inOutFloat, float floatMin, float floatMax ) -{ - RakAssert(floatMax>floatMin); - if (inOutFloat>floatMax+.001) - { - RakAssert(inOutFloat<=floatMax+.001); - } - if (inOutFloat=floatMin-.001); - } - float percentile=65535.0f * (inOutFloat-floatMin)/(floatMax-floatMin); - if (percentile<0.0) - percentile=0.0; - if (percentile>65535.0f) - percentile=65535.0f; - Write((unsigned short)percentile); -} diff --git a/vendors/mafianet/Source/src/CCRakNetSlidingWindow.cpp b/vendors/mafianet/Source/src/CCRakNetSlidingWindow.cpp deleted file mode 100644 index 6919254a4..000000000 --- a/vendors/mafianet/Source/src/CCRakNetSlidingWindow.cpp +++ /dev/null @@ -1,380 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/CCRakNetSlidingWindow.h" - -#if USE_SLIDING_WINDOW_CONGESTION_CONTROL==1 - -static const double UNSET_TIME_US=-1; - -#if CC_TIME_TYPE_BYTES==4 -static const CCTimeType SYN=10; -#else -static const CCTimeType SYN=10000; -#endif - -#include "mafianet/MTUSize.h" -#include -#include -#include -#include "mafianet/assert.h" -#include "mafianet/alloca.h" - -using namespace MafiaNet; - -// ****************************************************** PUBLIC METHODS ****************************************************** - -CCRakNetSlidingWindow::CCRakNetSlidingWindow() -{ -} -// ---------------------------------------------------------------------------------------------------------------------------- -CCRakNetSlidingWindow::~CCRakNetSlidingWindow() -{ - -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetSlidingWindow::Init(CCTimeType curTime, uint32_t maxDatagramPayload) -{ - (void) curTime; - - lastRtt=estimatedRTT=deviationRtt=UNSET_TIME_US; - RakAssert(maxDatagramPayload <= MAXIMUM_MTU_SIZE); - MAXIMUM_MTU_INCLUDING_UDP_HEADER=maxDatagramPayload; - cwnd=maxDatagramPayload; - ssThresh=0.0; - oldestUnsentAck=0; - nextDatagramSequenceNumber=0; - nextCongestionControlBlock=0; - backoffThisBlock=speedUpThisBlock=false; - expectedNextSequenceNumber=0; - _isContinuousSend=false; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetSlidingWindow::Update(CCTimeType curTime, bool hasDataToSendOrResend) -{ - (void) curTime; - (void) hasDataToSendOrResend; -} -// ---------------------------------------------------------------------------------------------------------------------------- -int CCRakNetSlidingWindow::GetRetransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend) -{ - (void) curTime; - (void) isContinuousSend; - (void) timeSinceLastTick; - - return unacknowledgedBytes; -} -// ---------------------------------------------------------------------------------------------------------------------------- -int CCRakNetSlidingWindow::GetTransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend) -{ - (void) curTime; - (void) timeSinceLastTick; - - _isContinuousSend=isContinuousSend; - - if (unacknowledgedBytes<=cwnd) - return (int) (cwnd-unacknowledgedBytes); - else - return 0; -} -// ---------------------------------------------------------------------------------------------------------------------------- -bool CCRakNetSlidingWindow::ShouldSendACKs(CCTimeType curTime, CCTimeType estimatedTimeToNextTick) -{ - CCTimeType rto = GetSenderRTOForACK(); - (void) estimatedTimeToNextTick; - - // UNSET_TIME_US is a negative double (-1); converting it straight to the unsigned - // CCTimeType is undefined behavior, which Apple clang at -O2 turns into a trap - // (brk #1). Cast through int64_t so the negative->unsigned conversion is defined - // and yields the same sentinel as GetSenderRTOForACK() on every platform. - if (rto==(CCTimeType)(int64_t) UNSET_TIME_US) - { - // Unknown how long until the remote system will retransmit, so better send right away - return true; - } - - return curTime >= oldestUnsentAck + SYN; -} -// ---------------------------------------------------------------------------------------------------------------------------- -DatagramSequenceNumberType CCRakNetSlidingWindow::GetNextDatagramSequenceNumber(void) -{ - return nextDatagramSequenceNumber; -} -// ---------------------------------------------------------------------------------------------------------------------------- -DatagramSequenceNumberType CCRakNetSlidingWindow::GetAndIncrementNextDatagramSequenceNumber(void) -{ - DatagramSequenceNumberType dsnt=nextDatagramSequenceNumber; - nextDatagramSequenceNumber++; - return dsnt; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetSlidingWindow::OnSendBytes(CCTimeType curTime, uint32_t numBytes) -{ - (void) curTime; - (void) numBytes; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetSlidingWindow::OnGotPacketPair(DatagramSequenceNumberType datagramSequenceNumber, uint32_t sizeInBytes, CCTimeType curTime) -{ - (void) curTime; - (void) sizeInBytes; - (void) datagramSequenceNumber; -} -// ---------------------------------------------------------------------------------------------------------------------------- -bool CCRakNetSlidingWindow::OnGotPacket(DatagramSequenceNumberType datagramSequenceNumber, bool isContinuousSend, CCTimeType curTime, uint32_t sizeInBytes, uint32_t *skippedMessageCount) -{ - (void) curTime; - (void) sizeInBytes; - (void) isContinuousSend; - - if (oldestUnsentAck==0) - oldestUnsentAck=curTime; - - if (datagramSequenceNumber==expectedNextSequenceNumber) - { - *skippedMessageCount=0; - expectedNextSequenceNumber=datagramSequenceNumber+(DatagramSequenceNumberType)1; - } - else if (GreaterThan(datagramSequenceNumber, expectedNextSequenceNumber)) - { - *skippedMessageCount=datagramSequenceNumber-expectedNextSequenceNumber; - // Sanity check, just use timeout resend if this was really valid - if (*skippedMessageCount>1000) - { - // During testing, the nat punchthrough server got 51200 on the first packet. I have no idea where this comes from, but has happened twice - if (*skippedMessageCount>(uint32_t)50000) - return false; - *skippedMessageCount=1000; - } - expectedNextSequenceNumber=datagramSequenceNumber+(DatagramSequenceNumberType)1; - } - else - { - *skippedMessageCount=0; - } - - return true; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetSlidingWindow::OnResend(CCTimeType curTime, MafiaNet::TimeUS nextActionTime) -{ - (void) curTime; - (void) nextActionTime; - - if (_isContinuousSend && backoffThisBlock==false && cwnd>MAXIMUM_MTU_INCLUDING_UDP_HEADER*2) - { - // Spec says 1/2 cwnd, but it never recovers because cwnd increases too slowly - //ssThresh=cwnd-8.0 * (MAXIMUM_MTU_INCLUDING_UDP_HEADER*MAXIMUM_MTU_INCLUDING_UDP_HEADER/cwnd); - ssThresh=cwnd/2; - if (ssThresh ssThresh && ssThresh!=0) - cwnd = ssThresh + MAXIMUM_MTU_INCLUDING_UDP_HEADER*MAXIMUM_MTU_INCLUDING_UDP_HEADER/cwnd; - - // CC PRINTF - // printf("++ %.0f Slow start increase.\n", cwnd); - - } - else if (isNewCongestionControlPeriod) - { - cwnd+=MAXIMUM_MTU_INCLUDING_UDP_HEADER*MAXIMUM_MTU_INCLUDING_UDP_HEADER/cwnd; - - // CC PRINTF - // printf("+ %.0f Congestion avoidance increase.\n", cwnd); - } -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetSlidingWindow::OnDuplicateAck( CCTimeType curTime, DatagramSequenceNumberType sequenceNumber ) -{ - (void) curTime; - (void) sequenceNumber; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetSlidingWindow::OnSendAckGetBAndAS(CCTimeType curTime, bool *hasBAndAS, BytesPerMicrosecond *_B, BytesPerMicrosecond *_AS) -{ - (void) curTime; - (void) _B; - (void) _AS; - - *hasBAndAS=false; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetSlidingWindow::OnSendAck(CCTimeType curTime, uint32_t numBytes) -{ - (void) curTime; - (void) numBytes; - - oldestUnsentAck=0; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetSlidingWindow::OnSendNACK(CCTimeType curTime, uint32_t numBytes) -{ - (void) curTime; - (void) numBytes; - -} -// ---------------------------------------------------------------------------------------------------------------------------- -CCTimeType CCRakNetSlidingWindow::GetRTOForRetransmission(unsigned char timesSent) const -{ - (void) timesSent; - -#if CC_TIME_TYPE_BYTES==4 - const CCTimeType maxThreshold=2000; - //const CCTimeType minThreshold=100; - const CCTimeType additionalVariance=30; -#else - const CCTimeType maxThreshold=2000000; - //const CCTimeType minThreshold=100000; - const CCTimeType additionalVariance=30000; -#endif - - - if (estimatedRTT==UNSET_TIME_US) - return maxThreshold; - - //double u=1.0f; - double u=2.0f; - double q=4.0f; - - CCTimeType threshhold = (CCTimeType) (u * estimatedRTT + q * deviationRtt) + additionalVariance; - if (threshhold > maxThreshold) - return maxThreshold; - return threshhold; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetSlidingWindow::SetMTU(uint32_t bytes) -{ - RakAssert(bytes < MAXIMUM_MTU_SIZE); - MAXIMUM_MTU_INCLUDING_UDP_HEADER=bytes; -} -// ---------------------------------------------------------------------------------------------------------------------------- -uint32_t CCRakNetSlidingWindow::GetMTU(void) const -{ - return MAXIMUM_MTU_INCLUDING_UDP_HEADER; -} -// ---------------------------------------------------------------------------------------------------------------------------- -BytesPerMicrosecond CCRakNetSlidingWindow::GetLocalReceiveRate(CCTimeType currentTime) const -{ - (void) currentTime; - - return 0; // TODO -} -// ---------------------------------------------------------------------------------------------------------------------------- -double CCRakNetSlidingWindow::GetRTT(void) const -{ - if (lastRtt==UNSET_TIME_US) - return 0.0; - return lastRtt; -} -// ---------------------------------------------------------------------------------------------------------------------------- -bool CCRakNetSlidingWindow::GreaterThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b) -{ - // a > b? - const DatagramSequenceNumberType halfSpan =(DatagramSequenceNumberType) (((DatagramSequenceNumberType)(const uint32_t)-1)/(DatagramSequenceNumberType)2); - return b!=a && b-a>halfSpan; -} -// ---------------------------------------------------------------------------------------------------------------------------- -bool CCRakNetSlidingWindow::LessThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b) -{ - // a < b? - const DatagramSequenceNumberType halfSpan = ((DatagramSequenceNumberType)(const uint32_t)-1)/(DatagramSequenceNumberType)2; - return b!=a && b-aunsigned cast - return (CCTimeType)(lastRtt + SYN); -} -// ---------------------------------------------------------------------------------------------------------------------------- -bool CCRakNetSlidingWindow::IsInSlowStart(void) const -{ - return cwnd <= ssThresh || ssThresh==0; -} -// ---------------------------------------------------------------------------------------------------------------------------- -#endif diff --git a/vendors/mafianet/Source/src/CCRakNetUDT.cpp b/vendors/mafianet/Source/src/CCRakNetUDT.cpp deleted file mode 100644 index a4c2181dd..000000000 --- a/vendors/mafianet/Source/src/CCRakNetUDT.cpp +++ /dev/null @@ -1,813 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/CCRakNetUDT.h" - -#if USE_SLIDING_WINDOW_CONGESTION_CONTROL!=1 - -#include "mafianet/Rand.h" -#include "mafianet/MTUSize.h" -#include -#include -#include -//#include -#include "mafianet/assert.h" -#include "mafianet/alloca.h" - -using namespace MafiaNet; - -static const double UNSET_TIME_US=-1; -static const double CWND_MIN_THRESHOLD=2.0; -static const double UNDEFINED_TRANSFER_RATE=0.0; -/// Interval at which to update aspects of the system -/// 1. send acks -/// 2. update time interval between outgoing packets -/// 3, Yodate retransmit timeout -#if CC_TIME_TYPE_BYTES==4 -static const CCTimeType SYN=10; -#else -static const CCTimeType SYN=10000; -#endif - -#if CC_TIME_TYPE_BYTES==4 -#define MAX_RTT 1000 -#define RTT_TOLERANCE 30 -#else -#define MAX_RTT 1000000 -#define RTT_TOLERANCE 30000 -#endif - - -double RTTVarMultiple=4.0; - - -// ****************************************************** PUBLIC METHODS ****************************************************** - -CCRakNetUDT::CCRakNetUDT() -{ -} - -// ---------------------------------------------------------------------------------------------------------------------------- - -CCRakNetUDT::~CCRakNetUDT() -{ -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetUDT::Init(CCTimeType curTime, uint32_t maxDatagramPayload) -{ - (void) curTime; - - nextSYNUpdate=0; - packetPairRecieptHistoryWriteIndex=0; - packetArrivalHistoryWriteIndex=0; - packetArrivalHistoryWriteCount=0; - RTT=UNSET_TIME_US; - // RTTVar=UNSET_TIME_US; - isInSlowStart=true; - NAKCount=1000; - AvgNAKNum=1; - DecInterval=1; - DecCount=0; - nextDatagramSequenceNumber=0; - lastPacketPairPacketArrivalTime=0; - lastPacketPairSequenceNumber=(DatagramSequenceNumberType)(const uint32_t)-1; - lastPacketArrivalTime=0; - CWND=CWND_MIN_THRESHOLD; - lastUpdateWindowSizeAndAck=0; - lastTransmitOfBAndAS=0; - ExpCount=1.0; - totalUserDataBytesSent=0; - oldestUnsentAck=0; - MAXIMUM_MTU_INCLUDING_UDP_HEADER=maxDatagramPayload; - CWND_MAX_THRESHOLD=RESEND_BUFFER_ARRAY_LENGTH; -#if CC_TIME_TYPE_BYTES==4 - const BytesPerMicrosecond DEFAULT_TRANSFER_RATE=(BytesPerMicrosecond) 3.6; -#else - const BytesPerMicrosecond DEFAULT_TRANSFER_RATE=(BytesPerMicrosecond) .0036; -#endif - -#if CC_TIME_TYPE_BYTES==4 - lastRttOnIncreaseSendRate=1000; -#else - lastRttOnIncreaseSendRate=1000000; -#endif - nextCongestionControlBlock=0; - lastRtt=0; - - // B=DEFAULT_TRANSFER_RATE; - AS=UNDEFINED_TRANSFER_RATE; - const MicrosecondsPerByte DEFAULT_BYTE_INTERVAL=(MicrosecondsPerByte) (1.0/DEFAULT_TRANSFER_RATE); - SND=DEFAULT_BYTE_INTERVAL; - expectedNextSequenceNumber=0; - sendBAndASCount=0; - packetArrivalHistoryContinuousGapsIndex=0; - //packetPairRecipetHistoryGapsIndex=0; - hasWrittenToPacketPairReceiptHistory=false; - InitPacketArrivalHistory(); - - estimatedLinkCapacityBytesPerSecond=0; - bytesCanSendThisTick=0; - hadPacketlossThisBlock=false; - pingsLastInterval.Clear(__FILE__,__LINE__); -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetUDT::SetMTU(uint32_t bytes) -{ - MAXIMUM_MTU_INCLUDING_UDP_HEADER=bytes; -} -// ---------------------------------------------------------------------------------------------------------------------------- -uint32_t CCRakNetUDT::GetMTU(void) const -{ - return MAXIMUM_MTU_INCLUDING_UDP_HEADER; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetUDT::Update(CCTimeType curTime, bool hasDataToSendOrResend) -{ - (void) hasDataToSendOrResend; - (void) curTime; - - return; - - // I suspect this is causing major lag - - /* - if (hasDataToSendOrResend==false) - halveSNDOnNoDataTime=0; - else if (halveSNDOnNoDataTime==0) - { - UpdateHalveSNDOnNoDataTime(curTime); - ExpCount=1.0; - } - - // If you send, and get no data at all from that time to RTO, then halve send rate7 - if (HasHalveSNDOnNoDataTimeElapsed(curTime)) - { - /// 2000 bytes per second - /// 0.0005 seconds per byte - /// 0.5 milliseconds per byte - /// 500 microseconds per byte - // printf("No incoming data, halving send rate\n"); - SND*=2.0; - CapMinSnd(_FILE_AND_LINE_); - ExpCount+=1.0; - if (ExpCount>8.0) - ExpCount=8.0; - - UpdateHalveSNDOnNoDataTime(curTime); - } - */ -} -// ---------------------------------------------------------------------------------------------------------------------------- -int CCRakNetUDT::GetRetransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend) -{ - (void) curTime; - - if (isInSlowStart) - { - uint32_t CWNDLimit = (uint32_t) (CWND*MAXIMUM_MTU_INCLUDING_UDP_HEADER); - return CWNDLimit; - } - return GetTransmissionBandwidth(curTime,timeSinceLastTick,unacknowledgedBytes,isContinuousSend); -} -// ---------------------------------------------------------------------------------------------------------------------------- -int CCRakNetUDT::GetTransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend) -{ - (void) curTime; - - if (isInSlowStart) - { - uint32_t CWNDLimit = (uint32_t) (CWND*MAXIMUM_MTU_INCLUDING_UDP_HEADER-unacknowledgedBytes); - return CWNDLimit; - } - if (bytesCanSendThisTick>0) - bytesCanSendThisTick=0; - -#if CC_TIME_TYPE_BYTES==4 - if (isContinuousSend==false && timeSinceLastTick>100) - timeSinceLastTick=100; -#else - if (isContinuousSend==false && timeSinceLastTick>100000) - timeSinceLastTick=100000; -#endif - - bytesCanSendThisTick=(int)((double)timeSinceLastTick*((double)1.0/SND)+(double)bytesCanSendThisTick); - if (bytesCanSendThisTick>0) - return bytesCanSendThisTick; - return 0; -} -uint64_t CCRakNetUDT::GetBytesPerSecondLimitByCongestionControl(void) const -{ - if (isInSlowStart) - return 0; -#if CC_TIME_TYPE_BYTES==4 - return (uint64_t) ((double)1.0/(SND*1000.0)); -#else - return (uint64_t) ((double)1.0/(SND*1000000.0)); -#endif -} -// ---------------------------------------------------------------------------------------------------------------------------- -bool CCRakNetUDT::ShouldSendACKs(CCTimeType curTime, CCTimeType estimatedTimeToNextTick) -{ - CCTimeType rto = GetSenderRTOForACK(); - - // iphone crashes on comparison between double and int64 http://www.jenkinssoftware.com/forum/index.php?topic=2717.0 - if (rto==(CCTimeType) UNSET_TIME_US) - { - // Unknown how long until the remote system will retransmit, so better send right away - return true; - } - - - // CCTimeType remoteRetransmitTime=oldestUnsentAck+rto-RTT*.5; - // CCTimeType ackArrivalTimeIfWeDelay=RTT*.5+estimatedTimeToNextTick+curTime; - // return ackArrivalTimeIfWeDelay= oldestUnsentAck + SYN || - estimatedTimeToNextTick+curTime < oldestUnsentAck+rto-RTT; -} -// ---------------------------------------------------------------------------------------------------------------------------- -DatagramSequenceNumberType CCRakNetUDT::GetNextDatagramSequenceNumber(void) -{ - return nextDatagramSequenceNumber; -} -// ---------------------------------------------------------------------------------------------------------------------------- -DatagramSequenceNumberType CCRakNetUDT::GetAndIncrementNextDatagramSequenceNumber(void) -{ - DatagramSequenceNumberType dsnt=nextDatagramSequenceNumber; - nextDatagramSequenceNumber++; - return dsnt; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetUDT::OnSendBytes(CCTimeType curTime, uint32_t numBytes) -{ - (void) curTime; - - totalUserDataBytesSent+=numBytes; - if (isInSlowStart==false) - bytesCanSendThisTick-=numBytes; -} - -// ****************************************************** PROTECTED METHODS ****************************************************** - -void CCRakNetUDT::SetNextSYNUpdate(CCTimeType currentTime) -{ - nextSYNUpdate+=SYN; - if (nextSYNUpdate < currentTime) - nextSYNUpdate=currentTime+SYN; -} -// ---------------------------------------------------------------------------------------------------------------------------- -BytesPerMicrosecond CCRakNetUDT::ReceiverCalculateDataArrivalRate(CCTimeType curTime) const -{ - (void) curTime; - // Not an instantaneous measurement - /* - if (continuousBytesReceivedStartTime!=0 && curTime>continuousBytesReceivedStartTime) - { - #if CC_TIME_TYPE_BYTES==4 - const CCTimeType threshold=100; - #else - const CCTimeType threshold=100000; - #endif - if (curTime-continuousBytesReceivedStartTime>threshold) - return (BytesPerMicrosecond) continuousBytesReceived/(BytesPerMicrosecond) (curTime-continuousBytesReceivedStartTime); - } - - return UNDEFINED_TRANSFER_RATE; - */ - - - if (packetArrivalHistoryWriteCount=oneEighthMedian && - packetArrivalHistory[i] b? - const DatagramSequenceNumberType halfSpan =(DatagramSequenceNumberType) (((DatagramSequenceNumberType)(const uint32_t)-1)/(DatagramSequenceNumberType)2); - return b!=a && b-a>halfSpan; -} -// ---------------------------------------------------------------------------------------------------------------------------- -bool CCRakNetUDT::LessThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b) -{ - // a < b? - const DatagramSequenceNumberType halfSpan = ((DatagramSequenceNumberType)(const uint32_t)-1)/(DatagramSequenceNumberType)2; - return b!=a && b-amaxThreshold) - return maxThreshold; - return ret; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetUDT::OnResend(CCTimeType curTime, MafiaNet::TimeUS nextActionTime) -{ - (void) curTime; - - if (isInSlowStart) - { - if (AS!=UNDEFINED_TRANSFER_RATE) - EndSlowStart(); - return; - } - - if (hadPacketlossThisBlock==false) - { - // Logging - // printf("Sending SLOWER due to Resend, Rate=%f MBPS. Rtt=%i\n", GetLocalSendRate(), lastRtt ); - - IncreaseTimeBetweenSends(); - hadPacketlossThisBlock=true; - } -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetUDT::OnNAK(CCTimeType curTime, DatagramSequenceNumberType nakSequenceNumber) -{ - (void) nakSequenceNumber; - (void) curTime; - - if (isInSlowStart) - { - if (AS!=UNDEFINED_TRANSFER_RATE) - EndSlowStart(); - return; - } - - if (hadPacketlossThisBlock==false) - { - // Logging - //printf("Sending SLOWER due to NAK, Rate=%f MBPS. Rtt=%i\n", GetLocalSendRate(), lastRtt ); - if (pingsLastInterval.Size()>10) - { - for (int i=0; i < 10; i++) - printf("%i, ", pingsLastInterval[pingsLastInterval.Size()-1-i]/1000); - } - printf("\n"); - IncreaseTimeBetweenSends(); - - hadPacketlossThisBlock=true; - } -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetUDT::EndSlowStart(void) -{ - RakAssert(isInSlowStart==true); - RakAssert(AS!=UNDEFINED_TRANSFER_RATE); - - // This overestimates - estimatedLinkCapacityBytesPerSecond=AS * 1000000.0; - - isInSlowStart=false; - SND=1.0/AS; - CapMinSnd(_FILE_AND_LINE_); - - // printf("ENDING SLOW START\n"); -#if CC_TIME_TYPE_BYTES==4 - // printf("Initial SND=%f Kilobytes per second\n", 1.0/SND); -#else - // printf("Initial SND=%f Megabytes per second\n", 1.0/SND); -#endif - if (SND > .1) - PrintLowBandwidthWarning(); -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetUDT::OnGotPacketPair(DatagramSequenceNumberType datagramSequenceNumber, uint32_t sizeInBytes, CCTimeType curTime) -{ - (void) datagramSequenceNumber; - (void) sizeInBytes; - (void) curTime; - -} -// ---------------------------------------------------------------------------------------------------------------------------- -bool CCRakNetUDT::OnGotPacket(DatagramSequenceNumberType datagramSequenceNumber, bool isContinuousSend, CCTimeType curTime, uint32_t sizeInBytes, uint32_t *skippedMessageCount) -{ - CC_DEBUG_PRINTF_2("R%i ",datagramSequenceNumber.val); - - if (datagramSequenceNumber==expectedNextSequenceNumber) - { - *skippedMessageCount=0; - expectedNextSequenceNumber=datagramSequenceNumber+(DatagramSequenceNumberType)1; - } - else if (GreaterThan(datagramSequenceNumber, expectedNextSequenceNumber)) - { - *skippedMessageCount=datagramSequenceNumber-expectedNextSequenceNumber; - // Sanity check, just use timeout resend if this was really valid - if (*skippedMessageCount>1000) - { - // During testing, the nat punchthrough server got 51200 on the first packet. I have no idea where this comes from, but has happened twice - if (*skippedMessageCount>(uint32_t)50000) - return false; - *skippedMessageCount=1000; - } - expectedNextSequenceNumber=datagramSequenceNumber+(DatagramSequenceNumberType)1; - } - else - { - *skippedMessageCount=0; - } - - if (curTime>lastPacketArrivalTime) - { - CCTimeType interval = curTime-lastPacketArrivalTime; - - // printf("Packet arrival gap is %I64u\n", (interval)); - - if (isContinuousSend) - { - continuousBytesReceived+=sizeInBytes; - if (continuousBytesReceivedStartTime==0) - continuousBytesReceivedStartTime=lastPacketArrivalTime; - - - mostRecentPacketArrivalHistory=(BytesPerMicrosecond)sizeInBytes/(BytesPerMicrosecond)interval; - - // if (mostRecentPacketArrivalHistory < (BytesPerMicrosecond)0.0035) - // { - // printf("%s:%i LIKELY BUG: Calculated packetArrivalHistory is below 28.8 Kbps modem\nReport to rakkar@jenkinssoftware.com with file and line number\n", _FILE_AND_LINE_); - // } - - packetArrivalHistoryContinuousGaps[packetArrivalHistoryContinuousGapsIndex++]=(int) interval; - packetArrivalHistoryContinuousGapsIndex&=(CC_RAKNET_UDT_PACKET_HISTORY_LENGTH-1); - - packetArrivalHistoryWriteCount++; - packetArrivalHistory[packetArrivalHistoryWriteIndex++]=mostRecentPacketArrivalHistory; - // Wrap to 0 at the end of the range - // Assumes power of 2 for CC_RAKNET_UDT_PACKET_HISTORY_LENGTH - packetArrivalHistoryWriteIndex&=(CC_RAKNET_UDT_PACKET_HISTORY_LENGTH-1); - } - else - { - continuousBytesReceivedStartTime=0; - continuousBytesReceived=0; - } - - lastPacketArrivalTime=curTime; - } - return true; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetUDT::OnAck(CCTimeType curTime, CCTimeType rtt, bool hasBAndAS, BytesPerMicrosecond _B, BytesPerMicrosecond _AS, double totalUserDataBytesAcked, bool isContinuousSend, DatagramSequenceNumberType sequenceNumber ) -{ -#if CC_TIME_TYPE_BYTES==4 - RakAssert(rtt < 10000); -#else - RakAssert(rtt < 10000000); -#endif - (void) _B; - - if (hasBAndAS) - { - /// RakAssert(_B!=UNDEFINED_TRANSFER_RATE && _AS!=UNDEFINED_TRANSFER_RATE); - // B=B * .875 + _B * .125; - // AS is packet arrival rate - RakAssert(_AS!=UNDEFINED_TRANSFER_RATE); - AS=_AS; - CC_DEBUG_PRINTF_4("ArrivalRate=%f linkCap=%f incomingLinkCap=%f\n", _AS,B,_B); - } - - if (oldestUnsentAck==0) - oldestUnsentAck=curTime; - - if (isInSlowStart==true) - { - nextCongestionControlBlock=nextDatagramSequenceNumber; - lastRttOnIncreaseSendRate=rtt; - UpdateWindowSizeAndAckOnAckPreSlowStart(totalUserDataBytesAcked); - } - else - { - UpdateWindowSizeAndAckOnAckPerSyn(curTime, rtt, isContinuousSend, sequenceNumber); - } - - lastUpdateWindowSizeAndAck=curTime; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetUDT::OnSendAckGetBAndAS(CCTimeType curTime, bool *hasBAndAS, BytesPerMicrosecond *_B, BytesPerMicrosecond *_AS) -{ - if (curTime>lastTransmitOfBAndAS+SYN) - { - *_B=0; - *_AS=ReceiverCalculateDataArrivalRate(curTime); - - if (*_AS==UNDEFINED_TRANSFER_RATE) - { - *hasBAndAS=false; - } - else - { - *hasBAndAS=true; - } - } - else - { - *hasBAndAS=false; - } -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetUDT::OnSendAck(CCTimeType curTime, uint32_t numBytes) -{ - (void) numBytes; - (void) curTime; - - // This is not accounted for on the remote system, and thus causes bandwidth to be underutilized - //UpdateNextAllowedSend(curTime, numBytes+UDP_HEADER_SIZE); - - oldestUnsentAck=0; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetUDT::OnSendNACK(CCTimeType curTime, uint32_t numBytes) -{ - (void) numBytes; - (void) curTime; - - // This is not accounted for on the remote system, and thus causes bandwidth to be underutilized - // UpdateNextAllowedSend(curTime, numBytes+UDP_HEADER_SIZE); -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetUDT::UpdateWindowSizeAndAckOnAckPreSlowStart(double totalUserDataBytesAcked) -{ - // During slow start, max window size is the number of full packets that have been sent out - // CWND=(double) ((double)totalUserDataBytesSent/(double)MAXIMUM_MTU_INCLUDING_UDP_HEADER); - CC_DEBUG_PRINTF_3("CWND increasing from %f to %f\n", CWND, (double) ((double)totalUserDataBytesAcked/(double)MAXIMUM_MTU_INCLUDING_UDP_HEADER)); - CWND=(double) ((double)totalUserDataBytesAcked/(double)MAXIMUM_MTU_INCLUDING_UDP_HEADER); - if (CWND>=CWND_MAX_THRESHOLD) - { - CWND=CWND_MAX_THRESHOLD; - - if (AS!=UNDEFINED_TRANSFER_RATE) - EndSlowStart(); - } - if (CWNDintervalSize) - pingsLastInterval.Pop(); - if (GreaterThan(sequenceNumber, nextCongestionControlBlock) && - sequenceNumber-nextCongestionControlBlock>=intervalSize && - pingsLastInterval.Size()==intervalSize) - { - double slopeSum=0.0; - double average=(double) pingsLastInterval[0]; - int sampleSize=pingsLastInterval.Size(); - for (int i=1; i < sampleSize; i++) - { - slopeSum+=(double)pingsLastInterval[i]-(double)pingsLastInterval[i-1]; - average+=pingsLastInterval[i]; - } - average/=sampleSize; - - if (hadPacketlossThisBlock==true) - { - } - else if (slopeSum < -.10*average) - { - // Logging - //printf("Ping dropping. slope=%f%%. Rate=%f MBPS. Rtt=%i\n", 100.0*slopeSum/average, GetLocalSendRate(), rtt ); - } - else if (slopeSum > .10*average) - { - // Logging - //printf("Ping rising. slope=%f%%. Rate=%f MBPS. Rtt=%i\n", 100.0*slopeSum/average, GetLocalSendRate(), rtt ); - IncreaseTimeBetweenSends(); - } - else - { - // Logging - //printf("Ping stable. slope=%f%%. Rate=%f MBPS. Rtt=%i\n", 100.0*slopeSum/average, GetLocalSendRate(), rtt ); - - // No packetloss over time threshhold, and rtt decreased, so send faster - lastRttOnIncreaseSendRate=rtt; - DecreaseTimeBetweenSends(); - } - - pingsLastInterval.Clear(__FILE__,__LINE__); - hadPacketlossThisBlock=false; - nextCongestionControlBlock=nextDatagramSequenceNumber; - } - - lastRtt=rtt; -} - -// ---------------------------------------------------------------------------------------------------------------------------- -double CCRakNetUDT::BytesPerMicrosecondToPacketsPerMillisecond(BytesPerMicrosecond in) -{ -#if CC_TIME_TYPE_BYTES==4 - const BytesPerMicrosecond factor = 1.0 / (BytesPerMicrosecond) MAXIMUM_MTU_INCLUDING_UDP_HEADER; -#else - const BytesPerMicrosecond factor = 1000.0 / (BytesPerMicrosecond) MAXIMUM_MTU_INCLUDING_UDP_HEADER; -#endif - return in * factor; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetUDT::InitPacketArrivalHistory(void) -{ - unsigned int i; - for (i=0; i < CC_RAKNET_UDT_PACKET_HISTORY_LENGTH; i++) - { - packetArrivalHistory[i]=UNDEFINED_TRANSFER_RATE; - packetArrivalHistoryContinuousGaps[i]=0; - } - - packetArrivalHistoryWriteCount=0; - continuousBytesReceived=0; - continuousBytesReceivedStartTime=0; -} -// ---------------------------------------------------------------------------------------------------------------------------- -void CCRakNetUDT::PrintLowBandwidthWarning(void) -{ - - /* - printf("\n-------LOW BANDWIDTH -----\n"); - if (isInSlowStart==false) - printf("SND=%f Megabytes per second\n", 1.0/SND); - printf("Window size=%f\n", CWND); - printf("Pipe from packet pair = %f megabytes per second\n", B); - printf("RTT=%f milliseconds\n", RTT/1000.0); - printf("RTT Variance=%f milliseconds\n", RTTVar/1000.0); - printf("Retransmission=%i milliseconds\n", GetRTOForRetransmission(1)/1000); - printf("Packet arrival rate on the remote system=%f megabytes per second\n", AS); - printf("Packet arrival rate on our system=%f megabytes per second\n", ReceiverCalculateDataArrivalRate()); - printf("isInSlowStart=%i\n", isInSlowStart); - printf("---------------\n"); - */ -} -BytesPerMicrosecond CCRakNetUDT::GetLocalReceiveRate(CCTimeType currentTime) const -{ - return ReceiverCalculateDataArrivalRate(currentTime); -} -double CCRakNetUDT::GetRTT(void) const -{ - if (RTT==UNSET_TIME_US) - return 0.0; - return RTT; -} -void CCRakNetUDT::CapMinSnd(const char *file, int line) -{ - (void) file; - (void) line; - - if (SND > 500) - { - SND=500; - CC_DEBUG_PRINTF_3("%s:%i LIKELY BUG: SND has gotten above 500 microseconds between messages (28.8 modem)\nReport to rakkar@jenkinssoftware.com with file and line number\n", file, line); - } -} -void CCRakNetUDT::IncreaseTimeBetweenSends(void) -{ - // In order to converge, bigger numbers have to increase slower and decrease faster - // SND==500 then increment is .02 - // SND==0 then increment is near 0 - // (SND+1.0) brings it to the range of 1 to 501 - // Square the number, which is the range of 1 to 251001 - // Divide by 251001, which is the range of 1/251001 to 1 - - double increment; - increment = .02 * ((SND+1.0) * (SND+1.0)) / (501.0*501.0) ; - // SND=500 then increment=.02 - // SND=0 then increment=near 0 - SND*=(1.02 - increment); - - // SND=0 then fast increase, slow decrease - // SND=500 then slow increase, fast decrease - CapMinSnd(__FILE__,__LINE__); -} -void CCRakNetUDT::DecreaseTimeBetweenSends(void) -{ - double increment; - increment = .01 * ((SND+1.0) * (SND+1.0)) / (501.0*501.0) ; - // SND=500 then increment=.01 - // SND=0 then increment=near 0 - SND*=(.99 - increment); -} -/* -void CCRakNetUDT::SetTimeBetweenSendsLimit(unsigned int bitsPerSecond) -{ -// bitsPerSecond / 1000000 = bitsPerMicrosecond -// bitsPerMicrosecond / 8 = BytesPerMicrosecond -// 1 / BytesPerMicrosecond = MicrosecondsPerByte -// 1 / ( (bitsPerSecond / 1000000) / 8 ) = -// 1 / (bitsPerSecond / 8000000) = -// 8000000 / bitsPerSecond - -#if CC_TIME_TYPE_BYTES==4 - MicrosecondsPerByte limit = (MicrosecondsPerByte) 8000 / (MicrosecondsPerByte)bitsPerSecond; -#else - MicrosecondsPerByte limit = (MicrosecondsPerByte) 8000000 / (MicrosecondsPerByte)bitsPerSecond; -#endif - if (limit > SND) - SND=limit; -} -*/ - -#endif diff --git a/vendors/mafianet/Source/src/CheckSum.cpp b/vendors/mafianet/Source/src/CheckSum.cpp deleted file mode 100644 index 0a96355f9..000000000 --- a/vendors/mafianet/Source/src/CheckSum.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/** -* @file -* @brief CheckSum implementation from http://www.flounder.com/checksum.htm -* -*/ -#include "mafianet/CheckSum.h" - -/**************************************************************************** -* CheckSum::add -* Inputs: -* unsigned int d: word to add -* Result: void -* -* Effect: -* Adds the bytes of the unsigned int to the CheckSum -****************************************************************************/ - -void CheckSum::Add ( unsigned int value ) -{ - union - { - unsigned int value; - unsigned char bytes[ 4 ]; - } - - data; - data.value = value; - - for ( unsigned int i = 0; i < sizeof( data.bytes ); i++ ) - Add ( data.bytes[ i ] ) - - ; -} // CheckSum::add(unsigned int) - -/**************************************************************************** -* CheckSum::add -* Inputs: -* unsigned short value: -* Result: void -* -* Effect: -* Adds the bytes of the unsigned short value to the CheckSum -****************************************************************************/ - -void CheckSum::Add ( unsigned short value ) -{ - union - { - unsigned short value; - unsigned char bytes[ 2 ]; - } - - data; - data.value = value; - - for ( unsigned int i = 0; i < sizeof( data.bytes ); i++ ) - Add ( data.bytes[ i ] ) - - ; -} // CheckSum::add(unsigned short) - -/**************************************************************************** -* CheckSum::add -* Inputs: -* unsigned char value: -* Result: void -* -* Effect: -* Adds the byte to the CheckSum -****************************************************************************/ - -void CheckSum::Add ( unsigned char value ) -{ - unsigned char cipher = (unsigned char)( value ^ ( r >> 8 ) ); - r = ( cipher + r ) * c1 + c2; - sum += cipher; -} // CheckSum::add(unsigned char) - - -/**************************************************************************** -* CheckSum::add -* Inputs: -* LPunsigned char b: pointer to byte array -* unsigned int length: count -* Result: void -* -* Effect: -* Adds the bytes to the CheckSum -****************************************************************************/ - -void CheckSum::Add ( unsigned char *b, unsigned int length ) -{ - for ( unsigned int i = 0; i < length; i++ ) - Add ( b[ i ] ) - - ; -} // CheckSum::add(LPunsigned char, unsigned int) diff --git a/vendors/mafianet/Source/src/CloudClient.cpp b/vendors/mafianet/Source/src/CloudClient.cpp deleted file mode 100644 index df7e36ad1..000000000 --- a/vendors/mafianet/Source/src/CloudClient.cpp +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_CloudClient==1 - -#include "mafianet/CloudClient.h" -#include "mafianet/GetTime.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/BitStream.h" -#include "mafianet/peerinterface.h" - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(CloudClient,CloudClient); - -CloudClient::CloudClient() -{ - callback=0; - allocator=&unsetDefaultAllocator; -} -CloudClient::~CloudClient() -{ -} -void CloudClient::SetDefaultCallbacks(CloudAllocator *_allocator, CloudClientCallback *_callback) -{ - callback=_callback; - allocator=_allocator; -} -void CloudClient::Post(CloudKey *cloudKey, const unsigned char *data, uint32_t dataLengthBytes, RakNetGUID systemIdentifier) -{ - RakAssert(cloudKey); - - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_POST_REQUEST); - cloudKey->Serialize(true,&bsOut); - if (data==0) - dataLengthBytes=0; - bsOut.Write(dataLengthBytes); - if (dataLengthBytes>0) - bsOut.WriteAlignedBytes((const unsigned char*) data, dataLengthBytes); - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, systemIdentifier, false); -} -void CloudClient::Release(DataStructures::List &keys, RakNetGUID systemIdentifier) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_RELEASE_REQUEST); - RakAssert(keys.Size() < (uint16_t)-1 ); - bsOut.WriteCasted(keys.Size()); - for (uint16_t i=0; i < keys.Size(); i++) - { - keys[i].Serialize(true,&bsOut); - } - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, systemIdentifier, false); -} -bool CloudClient::Get(CloudQuery *keyQuery, RakNetGUID systemIdentifier) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_GET_REQUEST); - keyQuery->Serialize(true, &bsOut); - bsOut.WriteCasted(0); // Specific systems - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, systemIdentifier, false); - return true; -} -bool CloudClient::Get(CloudQuery *keyQuery, DataStructures::List &specificSystems, RakNetGUID systemIdentifier) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_GET_REQUEST); - keyQuery->Serialize(true, &bsOut); - bsOut.WriteCasted(specificSystems.Size()); - RakAssert(specificSystems.Size() < (uint16_t)-1 ); - for (uint16_t i=0; i < specificSystems.Size(); i++) - { - bsOut.Write(specificSystems[i]); - } - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, systemIdentifier, false); - return true; -} -bool CloudClient::Get(CloudQuery *keyQuery, DataStructures::List &specificSystems, RakNetGUID systemIdentifier) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_GET_REQUEST); - keyQuery->Serialize(true, &bsOut); - bsOut.WriteCasted(specificSystems.Size()); - RakAssert(specificSystems.Size() < (uint16_t)-1 ); - for (uint16_t i=0; i < specificSystems.Size(); i++) - { - if (specificSystems[i]->clientGUID!=UNASSIGNED_RAKNET_GUID) - { - bsOut.Write(true); - bsOut.Write(specificSystems[i]->clientGUID); - } - else - { - bsOut.Write(false); - bsOut.Write(specificSystems[i]->clientSystemAddress); - } - } - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, systemIdentifier, false); - return true; -} -void CloudClient::Unsubscribe(DataStructures::List &keys, RakNetGUID systemIdentifier) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_UNSUBSCRIBE_REQUEST); - RakAssert(keys.Size() < (uint16_t)-1 ); - bsOut.WriteCasted(keys.Size()); - for (uint16_t i=0; i < keys.Size(); i++) - { - keys[i].Serialize(true,&bsOut); - } - bsOut.WriteCasted(0); - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, systemIdentifier, false); -} -void CloudClient::Unsubscribe(DataStructures::List &keys, DataStructures::List &specificSystems, RakNetGUID systemIdentifier) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_UNSUBSCRIBE_REQUEST); - RakAssert(keys.Size() < (uint16_t)-1 ); - bsOut.WriteCasted(keys.Size()); - for (uint16_t i=0; i < keys.Size(); i++) - { - keys[i].Serialize(true,&bsOut); - } - bsOut.WriteCasted(specificSystems.Size()); - RakAssert(specificSystems.Size() < (uint16_t)-1 ); - for (uint16_t i=0; i < specificSystems.Size(); i++) - { - bsOut.Write(specificSystems[i]); - } - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, systemIdentifier, false); -} -void CloudClient::Unsubscribe(DataStructures::List &keys, DataStructures::List &specificSystems, RakNetGUID systemIdentifier) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_UNSUBSCRIBE_REQUEST); - RakAssert(keys.Size() < (uint16_t)-1 ); - bsOut.WriteCasted(keys.Size()); - for (uint16_t i=0; i < keys.Size(); i++) - { - keys[i].Serialize(true,&bsOut); - } - bsOut.WriteCasted(specificSystems.Size()); - RakAssert(specificSystems.Size() < (uint16_t)-1 ); - for (uint16_t i=0; i < specificSystems.Size(); i++) - { - if (specificSystems[i]->clientGUID!=UNASSIGNED_RAKNET_GUID) - { - bsOut.Write(true); - bsOut.Write(specificSystems[i]->clientGUID); - } - else - { - bsOut.Write(false); - bsOut.Write(specificSystems[i]->clientSystemAddress); - } - } - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, systemIdentifier, false); -} -PluginReceiveResult CloudClient::OnReceive(Packet *packet) -{ - (void) packet; - - return RR_CONTINUE_PROCESSING; -} -void CloudClient::OnGetReponse(Packet *packet, CloudClientCallback *_callback, CloudAllocator *_allocator) -{ - if (_callback==0) - _callback=callback; - if (_allocator==0) - _allocator=allocator; - - CloudQueryResult cloudQueryResult; - - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)); - cloudQueryResult.Serialize(false,&bsIn,_allocator); - bool deallocateRowsAfterReturn=true; - _callback->OnGet(&cloudQueryResult, &deallocateRowsAfterReturn); - if (deallocateRowsAfterReturn) - { - unsigned int i; - for (i=0; i < cloudQueryResult.rowsReturned.Size(); i++) - { - _allocator->DeallocateRowData(cloudQueryResult.rowsReturned[i]->data); - _allocator->DeallocateCloudQueryRow(cloudQueryResult.rowsReturned[i]); - } - } -} -void CloudClient::OnGetReponse(CloudQueryResult *cloudQueryResult, Packet *packet, CloudAllocator *_allocator) -{ - if (_allocator==0) - _allocator=allocator; - - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)); - cloudQueryResult->Serialize(false,&bsIn,_allocator); -} -void CloudClient::OnSubscriptionNotification(Packet *packet, CloudClientCallback *_callback, CloudAllocator *_allocator) -{ - if (_callback==0) - _callback=callback; - if (_allocator==0) - _allocator=allocator; - - bool wasUpdated=false; - CloudQueryRow row; - - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)); - bsIn.Read(wasUpdated); - row.Serialize(false,&bsIn,_allocator); - bool deallocateRowAfterReturn=true; - _callback->OnSubscriptionNotification(&row, wasUpdated, &deallocateRowAfterReturn); - if (deallocateRowAfterReturn) - { - _allocator->DeallocateRowData(row.data); - } -} -void CloudClient::OnSubscriptionNotification(bool *wasUpdated, CloudQueryRow *row, Packet *packet, CloudAllocator *_allocator) -{ - if (_allocator==0) - _allocator=allocator; - - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)); - bool b=false; - bsIn.Read(b); - *wasUpdated=b; - row->Serialize(false,&bsIn,_allocator); -} -void CloudClient::DeallocateWithDefaultAllocator(CloudQueryResult *cloudQueryResult) -{ - unsigned int i; - for (i=0; i < cloudQueryResult->rowsReturned.Size(); i++) - { - allocator->DeallocateRowData(cloudQueryResult->rowsReturned[i]->data); - allocator->DeallocateCloudQueryRow(cloudQueryResult->rowsReturned[i]); - } - - cloudQueryResult->rowsReturned.Clear(false, _FILE_AND_LINE_); - cloudQueryResult->resultKeyIndices.Clear(false, _FILE_AND_LINE_); - cloudQueryResult->cloudQuery.keys.Clear(false, _FILE_AND_LINE_); -} -void CloudClient::DeallocateWithDefaultAllocator(CloudQueryRow *row) -{ - allocator->DeallocateRowData(row->data); -} -#endif diff --git a/vendors/mafianet/Source/src/CloudCommon.cpp b/vendors/mafianet/Source/src/CloudCommon.cpp deleted file mode 100644 index a7935c879..000000000 --- a/vendors/mafianet/Source/src/CloudCommon.cpp +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_CloudClient==1 || _RAKNET_SUPPORT_CloudServer==1 - -#include "mafianet/CloudCommon.h" -#include "mafianet/BitStream.h" - -using namespace MafiaNet; - -int MafiaNet::CloudKeyComp(const CloudKey &key, const CloudKey &data) -{ - if (key.primaryKey < data.primaryKey) - return -1; - if (key.primaryKey > data.primaryKey) - return 1; - if (key.secondaryKey < data.secondaryKey) - return -1; - if (key.secondaryKey > data.secondaryKey) - return 1; - return 0; -} - -CloudQueryRow* CloudAllocator::AllocateCloudQueryRow(void) -{ - return MafiaNet::OP_NEW(_FILE_AND_LINE_); -} -void CloudAllocator::DeallocateCloudQueryRow(CloudQueryRow *row) -{ - MafiaNet::OP_DELETE(row,_FILE_AND_LINE_); -} -unsigned char *CloudAllocator::AllocateRowData(uint32_t bytesNeededForData) -{ - return (unsigned char*) rakMalloc_Ex(bytesNeededForData,_FILE_AND_LINE_); -} -void CloudAllocator::DeallocateRowData(void *data) -{ - rakFree_Ex(data, _FILE_AND_LINE_); -} -void CloudKey::Serialize(bool writeToBitstream, BitStream *bitStream) -{ - bitStream->Serialize(writeToBitstream, primaryKey); - bitStream->Serialize(writeToBitstream, secondaryKey); -} -void CloudQuery::Serialize(bool writeToBitstream, BitStream *bitStream) -{ - bool startingRowIndexIsZero=0; - bool maxRowsToReturnIsZero=0; - startingRowIndexIsZero=startingRowIndex==0; - maxRowsToReturnIsZero=maxRowsToReturn==0; - bitStream->Serialize(writeToBitstream,startingRowIndexIsZero); - bitStream->Serialize(writeToBitstream,maxRowsToReturnIsZero); - bitStream->Serialize(writeToBitstream,subscribeToResults); - if (startingRowIndexIsZero==false) - bitStream->Serialize(writeToBitstream,startingRowIndex); - if (maxRowsToReturnIsZero==false) - bitStream->Serialize(writeToBitstream,maxRowsToReturn); - RakAssert(keys.Size()<(uint16_t)-1); - uint16_t numKeys = (uint16_t) keys.Size(); - bitStream->Serialize(writeToBitstream,numKeys); - if (writeToBitstream) - { - for (uint16_t i=0; i < numKeys; i++) - { - keys[i].Serialize(true,bitStream); - } - } - else - { - CloudKey cmdk; - for (uint16_t i=0; i < numKeys; i++) - { - cmdk.Serialize(false,bitStream); - keys.Push(cmdk, _FILE_AND_LINE_); - } - } -} -void CloudQueryRow::Serialize(bool writeToBitstream, BitStream *bitStream, CloudAllocator *allocator) -{ - key.Serialize(writeToBitstream,bitStream); - bitStream->Serialize(writeToBitstream,serverSystemAddress); - bitStream->Serialize(writeToBitstream,clientSystemAddress); - bitStream->Serialize(writeToBitstream,serverGUID); - bitStream->Serialize(writeToBitstream,clientGUID); - bitStream->Serialize(writeToBitstream,length); - if (writeToBitstream) - { - bitStream->WriteAlignedBytes((const unsigned char*) data,length); - } - else - { - if (length>0) - { - data = allocator->AllocateRowData(length); - if (data) - { - bitStream->ReadAlignedBytes((unsigned char *) data,length); - } - else - { - notifyOutOfMemory(_FILE_AND_LINE_); - } - } - else - data=0; - } -} -void CloudQueryResult::SerializeHeader(bool writeToBitstream, BitStream *bitStream) -{ - cloudQuery.Serialize(writeToBitstream,bitStream); - bitStream->Serialize(writeToBitstream,subscribeToResults); -} -void CloudQueryResult::SerializeNumRows(bool writeToBitstream, uint32_t &numRows, BitStream *bitStream) -{ - bitStream->Serialize(writeToBitstream,numRows); -} -void CloudQueryResult::SerializeCloudQueryRows(bool writeToBitstream, uint32_t &numRows, BitStream *bitStream, CloudAllocator *allocator) -{ - if (writeToBitstream) - { - for (uint16_t i=0; i < numRows; i++) - { - rowsReturned[i]->Serialize(true,bitStream, allocator); - } - } - else - { - CloudQueryRow* cmdr; - for (uint16_t i=0; i < numRows; i++) - { - cmdr = allocator->AllocateCloudQueryRow(); - if (cmdr) - { - cmdr->Serialize(false,bitStream,allocator); - if (cmdr->data==0 && cmdr->length>0) - { - allocator->DeallocateCloudQueryRow(cmdr); - notifyOutOfMemory(_FILE_AND_LINE_); - numRows=i; - return; - } - rowsReturned.Push(cmdr, _FILE_AND_LINE_); - } - else - { - notifyOutOfMemory(_FILE_AND_LINE_); - numRows=i; - return; - } - } - } -} -void CloudQueryResult::Serialize(bool writeToBitstream, BitStream *bitStream, CloudAllocator *allocator) -{ - SerializeHeader(writeToBitstream, bitStream); - uint32_t numRows = (uint32_t) rowsReturned.Size(); - SerializeNumRows(writeToBitstream, numRows, bitStream); - SerializeCloudQueryRows(writeToBitstream, numRows, bitStream, allocator); -} - -#endif // #if _RAKNET_SUPPORT_CloudMemoryClient==1 || _RAKNET_SUPPORT_CloudMemoryServer==1 diff --git a/vendors/mafianet/Source/src/CloudServer.cpp b/vendors/mafianet/Source/src/CloudServer.cpp deleted file mode 100644 index a19954fed..000000000 --- a/vendors/mafianet/Source/src/CloudServer.cpp +++ /dev/null @@ -1,1687 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_CloudServer==1 - -#include "mafianet/CloudServer.h" -#include "mafianet/GetTime.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/BitStream.h" -#include "mafianet/peerinterface.h" - -enum ServerToServerCommands -{ - STSC_PROCESS_GET_REQUEST, - STSC_PROCESS_GET_RESPONSE, - STSC_ADD_UPLOADED_AND_SUBSCRIBED_KEYS, - STSC_ADD_UPLOADED_KEY, - STSC_ADD_SUBSCRIBED_KEY, - STSC_REMOVE_UPLOADED_KEY, - STSC_REMOVE_SUBSCRIBED_KEY, - STSC_DATA_CHANGED, -}; - -using namespace MafiaNet; - -int CloudServer::RemoteServerComp(const RakNetGUID &key, RemoteServer* const &data ) -{ - if (key < data->serverAddress) - return -1; - if (key > data->serverAddress) - return 1; - return 0; -} -int CloudServer::KeySubscriberIDComp(const CloudKey &key, KeySubscriberID * const &data ) -{ - if (key.primaryKey < data->key.primaryKey) - return -1; - if (key.primaryKey > data->key.primaryKey) - return 1; - if (key.secondaryKey < data->key.secondaryKey) - return -1; - if (key.secondaryKey > data->key.secondaryKey) - return 1; - return 0; -} -int CloudServer::KeyDataPtrComp( const RakNetGUID &key, CloudData* const &data ) -{ - if (key < data->clientGUID) - return -1; - if (key > data->clientGUID) - return 1; - return 0; -} -int CloudServer::KeyDataListComp( const CloudKey &key, CloudDataList * const &data ) -{ - if (key.primaryKey < data->key.primaryKey) - return -1; - if (key.primaryKey > data->key.primaryKey) - return 1; - if (key.secondaryKey < data->key.secondaryKey) - return -1; - if (key.secondaryKey > data->key.secondaryKey) - return 1; - return 0; -} -int CloudServer::BufferedGetResponseFromServerComp(const RakNetGUID &key, CloudServer::BufferedGetResponseFromServer* const &data ) -{ - if (key < data->serverAddress) - return -1; - if (key > data->serverAddress) - return 1; - return 0; -} -int CloudServer::GetRequestComp(const uint32_t &key, CloudServer::GetRequest* const &data ) -{ - if (key < data->requestId) - return -1; - if (key > data->requestId) - return -1; - return 0; -} -void CloudServer::CloudQueryWithAddresses::Serialize(bool writeToBitstream, BitStream *bitStream) -{ - cloudQuery.Serialize(writeToBitstream, bitStream); - - if (writeToBitstream) - { - bitStream->WriteCasted(specificSystems.Size()); - RakAssert(specificSystems.Size() < (uint16_t)-1 ); - for (uint16_t i=0; i < specificSystems.Size(); i++) - { - bitStream->Write(specificSystems[i]); - } - } - else - { - uint16_t specificSystemsCount; - RakNetGUID addressOrGuid; - bitStream->Read(specificSystemsCount); - for (uint16_t i=0; i < specificSystemsCount; i++) - { - bitStream->Read(addressOrGuid); - specificSystems.Push(addressOrGuid, _FILE_AND_LINE_); - } - } -} -bool CloudServer::GetRequest::AllRemoteServersHaveResponded(void) const -{ - unsigned int i; - for (i=0; i < remoteServerResponses.Size(); i++) - if (remoteServerResponses[i]->gotResult==false) - return false; - return true; -} -void CloudServer::GetRequest::Clear(CloudAllocator *allocator) -{ - unsigned int i; - for (i=0; i < remoteServerResponses.Size(); i++) - { - remoteServerResponses[i]->Clear(allocator); - MafiaNet::OP_DELETE(remoteServerResponses[i], _FILE_AND_LINE_); - } - remoteServerResponses.Clear(false, _FILE_AND_LINE_); -} -void CloudServer::BufferedGetResponseFromServer::Clear(CloudAllocator *allocator) -{ - unsigned int i; - for (i=0; i < queryResult.rowsReturned.Size(); i++) - { - allocator->DeallocateRowData(queryResult.rowsReturned[i]->data); - allocator->DeallocateCloudQueryRow(queryResult.rowsReturned[i]); - } - queryResult.rowsReturned.Clear(false, _FILE_AND_LINE_); -} -CloudServer::CloudServer() -{ - maxUploadBytesPerClient=0; - maxBytesPerDowload=0; - nextGetRequestId=0; - nextGetRequestsCheck=0; -} -CloudServer::~CloudServer() -{ - Clear(); -} -void CloudServer::SetMaxUploadBytesPerClient(uint64_t bytes) -{ - maxUploadBytesPerClient=bytes; -} -void CloudServer::SetMaxBytesPerDownload(uint64_t bytes) -{ - maxBytesPerDowload=bytes; -} -void CloudServer::Update(void) -{ - // Timeout getRequests - MafiaNet::Time time = MafiaNet::Time(); - if (time > nextGetRequestsCheck) - { - nextGetRequestsCheck=time+1000; - - unsigned int i=0; - while (i < getRequests.Size()) - { - if (time - getRequests[i]->requestStartTime > 3000) - { - // Remote server is not responding, just send back data with whoever did respond - ProcessAndTransmitGetRequest(getRequests[i]); - getRequests[i]->Clear(this); - MafiaNet::OP_DELETE(getRequests[i],_FILE_AND_LINE_); - getRequests.RemoveAtIndex(i); - } - else - { - i++; - } - } - } -} -PluginReceiveResult CloudServer::OnReceive(Packet *packet) -{ - switch (packet->data[0]) - { - case ID_CLOUD_POST_REQUEST: - OnPostRequest(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_CLOUD_RELEASE_REQUEST: - OnReleaseRequest(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_CLOUD_GET_REQUEST: - OnGetRequest(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_CLOUD_UNSUBSCRIBE_REQUEST: - OnUnsubscribeRequest(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_CLOUD_SERVER_TO_SERVER_COMMAND: - if (packet->length>1) - { - switch (packet->data[1]) - { - case STSC_PROCESS_GET_REQUEST: - OnServerToServerGetRequest(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case STSC_PROCESS_GET_RESPONSE: - OnServerToServerGetResponse(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case STSC_ADD_UPLOADED_AND_SUBSCRIBED_KEYS: - OnSendUploadedAndSubscribedKeysToServer(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case STSC_ADD_UPLOADED_KEY: - OnSendUploadedKeyToServers(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case STSC_ADD_SUBSCRIBED_KEY: - OnSendSubscribedKeyToServers(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case STSC_REMOVE_UPLOADED_KEY: - OnRemoveUploadedKeyFromServers(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case STSC_REMOVE_SUBSCRIBED_KEY: - OnRemoveSubscribedKeyFromServers(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case STSC_DATA_CHANGED: - OnServerDataChanged(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - } - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - return RR_CONTINUE_PROCESSING; -} -void CloudServer::OnPostRequest(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)); - CloudKey key; - key.Serialize(false,&bsIn); - uint32_t dataLengthBytes; - bsIn.Read(dataLengthBytes); - if (maxUploadBytesPerClient>0 && dataLengthBytes>maxUploadBytesPerClient) - return; // Exceeded max upload bytes - - bsIn.AlignReadToByteBoundary(); - for (unsigned int filterIndex=0; filterIndex < queryFilters.Size(); filterIndex++) - { - if (queryFilters[filterIndex]->OnPostRequest(packet->guid, packet->systemAddress, key, dataLengthBytes, (const char*) bsIn.GetData()+BITS_TO_BYTES(bsIn.GetReadOffset()))==false) - return; - } - - unsigned char *data; - if (dataLengthBytes>CLOUD_SERVER_DATA_STACK_SIZE) - { - data = (unsigned char *) rakMalloc_Ex(dataLengthBytes,_FILE_AND_LINE_); - if (data==0) - { - notifyOutOfMemory(_FILE_AND_LINE_); - return; - } - bsIn.ReadAlignedBytes(data,dataLengthBytes); - } - else - data=0; - - // Add this system to remoteSystems if they aren't there already - DataStructures::HashIndex remoteSystemsHashIndex = remoteSystems.GetIndexOf(packet->guid); - RemoteCloudClient *remoteCloudClient; - if (remoteSystemsHashIndex.IsInvalid()) - { - remoteCloudClient = MafiaNet::OP_NEW(_FILE_AND_LINE_); - remoteCloudClient->uploadedKeys.Insert(key,key,true,_FILE_AND_LINE_); - remoteCloudClient->uploadedBytes=0; - remoteSystems.Push(packet->guid, remoteCloudClient, _FILE_AND_LINE_); - } - else - { - remoteCloudClient = remoteSystems.ItemAtIndex(remoteSystemsHashIndex); - bool objectExists; - // Add to RemoteCloudClient::uploadedKeys if it isn't there already - unsigned int uploadedKeysIndex = remoteCloudClient->uploadedKeys.GetIndexFromKey(key,&objectExists); - if (objectExists==false) - { - remoteCloudClient->uploadedKeys.InsertAtIndex(key, uploadedKeysIndex, _FILE_AND_LINE_); - } - } - - bool cloudDataAlreadyUploaded; - unsigned int dataRepositoryIndex; - bool dataRepositoryExists; - CloudDataList* cloudDataList = GetOrAllocateCloudDataList(key, &dataRepositoryExists, dataRepositoryIndex); - if (dataRepositoryExists==false) - { - cloudDataList->uploaderCount=1; - cloudDataAlreadyUploaded=false; - } - else - { - cloudDataAlreadyUploaded=cloudDataList->uploaderCount>0; - cloudDataList->uploaderCount++; - } - - CloudData *cloudData; - bool keyDataListExists; - unsigned int keyDataListIndex = cloudDataList->keyData.GetIndexFromKey(packet->guid, &keyDataListExists); - if (keyDataListExists==false) - { - if (maxUploadBytesPerClient>0 && remoteCloudClient->uploadedBytes+dataLengthBytes>maxUploadBytesPerClient) - { - // Undo prior insertion of cloudDataList into cloudData if needed - if (keyDataListExists==false) - { - MafiaNet::OP_DELETE(cloudDataList,_FILE_AND_LINE_); - dataRepository.RemoveAtIndex(dataRepositoryIndex); - } - - if (remoteCloudClient->IsUnused()) - { - MafiaNet::OP_DELETE(remoteCloudClient, _FILE_AND_LINE_); - remoteSystems.Remove(packet->guid, _FILE_AND_LINE_); - } - - if (dataLengthBytes>CLOUD_SERVER_DATA_STACK_SIZE) - rakFree_Ex(data, _FILE_AND_LINE_); - - return; - } - - cloudData = MafiaNet::OP_NEW(_FILE_AND_LINE_); - cloudData->dataLengthBytes=dataLengthBytes; - cloudData->isUploaded=true; - if (forceAddress!=UNASSIGNED_SYSTEM_ADDRESS) - { - cloudData->serverSystemAddress=forceAddress; - cloudData->serverSystemAddress.SetPortHostOrder(rakPeerInterface->GetExternalID(packet->systemAddress).GetPort()); - } - else - { - cloudData->serverSystemAddress=rakPeerInterface->GetExternalID(packet->systemAddress); - if (cloudData->serverSystemAddress.IsLoopback()) - cloudData->serverSystemAddress.FromString(rakPeerInterface->GetLocalIP(0)); - } - if (cloudData->serverSystemAddress.GetPort()==0) - { - // Fix localhost port - cloudData->serverSystemAddress.SetPortHostOrder(rakPeerInterface->GetSocket(UNASSIGNED_SYSTEM_ADDRESS)->GetBoundAddress().GetPort()); - } - cloudData->clientSystemAddress=packet->systemAddress; - cloudData->serverGUID=rakPeerInterface->GetMyGUID(); - cloudData->clientGUID=packet->guid; - cloudDataList->keyData.Insert(packet->guid,cloudData,true,_FILE_AND_LINE_); - } - else - { - cloudData = cloudDataList->keyData[keyDataListIndex]; - - if (cloudDataAlreadyUploaded==false) - { - if (forceAddress!=UNASSIGNED_SYSTEM_ADDRESS) - { - cloudData->serverSystemAddress=forceAddress; - cloudData->serverSystemAddress.SetPortHostOrder(rakPeerInterface->GetExternalID(packet->systemAddress).GetPort()); - } - else - { - cloudData->serverSystemAddress=rakPeerInterface->GetExternalID(packet->systemAddress); - } - if (cloudData->serverSystemAddress.GetPort()==0) - { - // Fix localhost port - cloudData->serverSystemAddress.SetPortHostOrder(rakPeerInterface->GetSocket(UNASSIGNED_SYSTEM_ADDRESS)->GetBoundAddress().GetPort()); - } - - cloudData->clientSystemAddress=packet->systemAddress; - } - - if (maxUploadBytesPerClient>0 && remoteCloudClient->uploadedBytes-cloudData->dataLengthBytes+dataLengthBytes>maxUploadBytesPerClient) - { - // Undo prior insertion of cloudDataList into cloudData if needed - if (dataRepositoryExists==false) - { - MafiaNet::OP_DELETE(cloudDataList,_FILE_AND_LINE_); - dataRepository.RemoveAtIndex(dataRepositoryIndex); - } - return; - } - else - { - // Subtract already used bytes we are overwriting - remoteCloudClient->uploadedBytes-=cloudData->dataLengthBytes; - } - - if (cloudData->allocatedData!=0) - rakFree_Ex(cloudData->allocatedData,_FILE_AND_LINE_); - } - - if (dataLengthBytes>CLOUD_SERVER_DATA_STACK_SIZE) - { - // Data already allocated - cloudData->allocatedData=data; - cloudData->dataPtr=data; - } - else - { - // Read to stack - if (dataLengthBytes>0) - bsIn.ReadAlignedBytes(cloudData->stackData,dataLengthBytes); - cloudData->allocatedData=0; - cloudData->dataPtr=cloudData->stackData; - } - // Update how many bytes were written for this data - cloudData->dataLengthBytes=dataLengthBytes; - remoteCloudClient->uploadedBytes+=dataLengthBytes; - - if (cloudDataAlreadyUploaded==false) - { - // New data field - SendUploadedKeyToServers(cloudDataList->key); - } - - // Existing data field changed - NotifyClientSubscribersOfDataChange(cloudData, cloudDataList->key, cloudData->specificSubscribers, true ); - NotifyClientSubscribersOfDataChange(cloudData, cloudDataList->key, cloudDataList->nonSpecificSubscribers, true ); - - // Send update to all remote servers that subscribed to this key - NotifyServerSubscribersOfDataChange(cloudData, cloudDataList->key, true); - - // I could have also subscribed to a key not yet updated locally - // This means I have to go through every RemoteClient that wants this key - // Seems like cloudData->specificSubscribers is unnecessary in that case -} -void CloudServer::OnReleaseRequest(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)); - - uint16_t keyCount; - bsIn.Read(keyCount); - - if (keyCount==0) - return; - - DataStructures::HashIndex remoteSystemIndex = remoteSystems.GetIndexOf(packet->guid); - if (remoteSystemIndex.IsInvalid()==true) - return; - - RemoteCloudClient* remoteCloudClient = remoteSystems.ItemAtIndex(remoteSystemIndex); - - CloudKey key; - - // Read all in a list first so I can run filter on it - DataStructures::List cloudKeys; - for (uint16_t keyCountIndex=0; keyCountIndex < keyCount; keyCountIndex++) - { - key.Serialize(false, &bsIn); - cloudKeys.Push(key, _FILE_AND_LINE_); - } - - for (unsigned int filterIndex=0; filterIndex < queryFilters.Size(); filterIndex++) - { - if (queryFilters[filterIndex]->OnReleaseRequest(packet->guid, packet->systemAddress, cloudKeys)==false) - return; - } - - for (uint16_t keyCountIndex=0; keyCountIndex < keyCount; keyCountIndex++) - { - // Serialize in list above so I can run the filter on it - // key.Serialize(false, &bsIn); - key=cloudKeys[keyCountIndex]; - - // Remove remote systems uploaded keys - bool objectExists; - unsigned int uploadedKeysIndex = remoteCloudClient->uploadedKeys.GetIndexFromKey(key,&objectExists); - if (objectExists) - { - bool dataRepositoryExists; - unsigned int dataRepositoryIndex = dataRepository.GetIndexFromKey(key, &dataRepositoryExists); - CloudDataList* cloudDataList = dataRepository[dataRepositoryIndex]; - RakAssert(cloudDataList); - - CloudData *cloudData; - bool keyDataListExists; - unsigned int keyDataListIndex = cloudDataList->keyData.GetIndexFromKey(packet->guid, &keyDataListExists); - cloudData = cloudDataList->keyData[keyDataListIndex]; - - remoteCloudClient->uploadedKeys.RemoveAtIndex(uploadedKeysIndex); - remoteCloudClient->uploadedBytes-=cloudData->dataLengthBytes; - cloudDataList->uploaderCount--; - - // Broadcast destruction of this key to subscribers - NotifyClientSubscribersOfDataChange(cloudData, cloudDataList->key, cloudData->specificSubscribers, false ); - NotifyClientSubscribersOfDataChange(cloudData, cloudDataList->key, cloudDataList->nonSpecificSubscribers, false ); - NotifyServerSubscribersOfDataChange(cloudData, cloudDataList->key, false ); - - cloudData->Clear(); - - if (cloudData->IsUnused()) - { - MafiaNet::OP_DELETE(cloudData, _FILE_AND_LINE_); - cloudDataList->keyData.RemoveAtIndex(keyDataListIndex); - if (cloudDataList->IsNotUploaded()) - { - // Tell other servers that this key is no longer uploaded, so they do not request it from us - RemoveUploadedKeyFromServers(cloudDataList->key); - } - - if (cloudDataList->IsUnused()) - { - MafiaNet::OP_DELETE(cloudDataList, _FILE_AND_LINE_); - dataRepository.RemoveAtIndex(dataRepositoryIndex); - } - } - - if (remoteCloudClient->IsUnused()) - { - MafiaNet::OP_DELETE(remoteCloudClient, _FILE_AND_LINE_); - remoteSystems.RemoveAtIndex(remoteSystemIndex, _FILE_AND_LINE_); - break; - } - } - } -} -void CloudServer::OnGetRequest(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)); - uint16_t specificSystemsCount; - CloudKey cloudKey; - - // Create a new GetRequest - GetRequest *getRequest; - getRequest = MafiaNet::OP_NEW(_FILE_AND_LINE_); - getRequest->cloudQueryWithAddresses.cloudQuery.Serialize(false, &bsIn); - getRequest->requestingClient=packet->guid; - - RakNetGUID addressOrGuid; - bsIn.Read(specificSystemsCount); - for (uint16_t i=0; i < specificSystemsCount; i++) - { - bsIn.Read(addressOrGuid); - getRequest->cloudQueryWithAddresses.specificSystems.Push(addressOrGuid, _FILE_AND_LINE_); - } - - if (getRequest->cloudQueryWithAddresses.cloudQuery.keys.Size()==0) - { - MafiaNet::OP_DELETE(getRequest, _FILE_AND_LINE_); - return; - } - - for (unsigned int filterIndex=0; filterIndex < queryFilters.Size(); filterIndex++) - { - if (queryFilters[filterIndex]->OnGetRequest(packet->guid, packet->systemAddress, getRequest->cloudQueryWithAddresses.cloudQuery, getRequest->cloudQueryWithAddresses.specificSystems )==false) - return; - } - - getRequest->requestStartTime= MafiaNet::GetTime(); - getRequest->requestId=nextGetRequestId++; - - // Send request to servers that have this data - DataStructures::List remoteServersWithData; - GetServersWithUploadedKeys(getRequest->cloudQueryWithAddresses.cloudQuery.keys, remoteServersWithData); - - if (remoteServersWithData.Size()==0) - { - ProcessAndTransmitGetRequest(getRequest); - } - else - { - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); - bsOut.Write((MessageID)STSC_PROCESS_GET_REQUEST); - getRequest->cloudQueryWithAddresses.Serialize(true, &bsOut); - bsOut.Write(getRequest->requestId); - - for (unsigned int remoteServerIndex=0; remoteServerIndex < remoteServersWithData.Size(); remoteServerIndex++) - { - BufferedGetResponseFromServer* bufferedGetResponseFromServer = MafiaNet::OP_NEW(_FILE_AND_LINE_); - bufferedGetResponseFromServer->serverAddress=remoteServersWithData[remoteServerIndex]->serverAddress; - bufferedGetResponseFromServer->gotResult=false; - getRequest->remoteServerResponses.Insert(remoteServersWithData[remoteServerIndex]->serverAddress, bufferedGetResponseFromServer, true, _FILE_AND_LINE_); - - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, remoteServersWithData[remoteServerIndex]->serverAddress, false); - } - - // Record that this system made this request - getRequests.Insert(getRequest->requestId, getRequest, true, _FILE_AND_LINE_); - } - - if (getRequest->cloudQueryWithAddresses.cloudQuery.subscribeToResults) - { - // Add to key subscription list for the client, which contains a keyId / specificUploaderList pair - DataStructures::HashIndex remoteSystemsHashIndex = remoteSystems.GetIndexOf(packet->guid); - RemoteCloudClient *remoteCloudClient; - if (remoteSystemsHashIndex.IsInvalid()) - { - remoteCloudClient = MafiaNet::OP_NEW(_FILE_AND_LINE_); - remoteCloudClient->uploadedBytes=0; - remoteSystems.Push(packet->guid, remoteCloudClient, _FILE_AND_LINE_); - } - else - { - remoteCloudClient = remoteSystems.ItemAtIndex(remoteSystemsHashIndex); - } - - unsigned int keyIndex; - for (keyIndex=0; keyIndex < getRequest->cloudQueryWithAddresses.cloudQuery.keys.Size(); keyIndex++) - { - cloudKey = getRequest->cloudQueryWithAddresses.cloudQuery.keys[keyIndex]; - - unsigned int keySubscriberIndex; - bool hasKeySubscriber; - keySubscriberIndex = remoteCloudClient->subscribedKeys.GetIndexFromKey(cloudKey, &hasKeySubscriber); - KeySubscriberID* keySubscriberId; - if (hasKeySubscriber) - { - DataStructures::List specificSystems; - UnsubscribeFromKey(remoteCloudClient, packet->guid, keySubscriberIndex, cloudKey, specificSystems); - } - - keySubscriberId = MafiaNet::OP_NEW(_FILE_AND_LINE_); - keySubscriberId->key=cloudKey; - - unsigned int specificSystemIndex; - for (specificSystemIndex=0; specificSystemIndex < getRequest->cloudQueryWithAddresses.specificSystems.Size(); specificSystemIndex++) - { - keySubscriberId->specificSystemsSubscribedTo.Insert(getRequest->cloudQueryWithAddresses.specificSystems[specificSystemIndex], getRequest->cloudQueryWithAddresses.specificSystems[specificSystemIndex], true, _FILE_AND_LINE_); - } - - remoteCloudClient->subscribedKeys.InsertAtIndex(keySubscriberId, keySubscriberIndex, _FILE_AND_LINE_); - - // Add CloudData in a similar way - unsigned int dataRepositoryIndex; - bool dataRepositoryExists; - CloudDataList* cloudDataList = GetOrAllocateCloudDataList(cloudKey, &dataRepositoryExists, dataRepositoryIndex); - - // If this is the first local client to subscribe to this key, call SendSubscribedKeyToServers - if (cloudDataList->subscriberCount==0) - SendSubscribedKeyToServers(cloudKey); - - // If the subscription is specific, may have to also allocate CloudData - if (getRequest->cloudQueryWithAddresses.specificSystems.Size()) - { - CloudData *cloudData; - bool keyDataListExists; - - for (specificSystemIndex=0; specificSystemIndex < getRequest->cloudQueryWithAddresses.specificSystems.Size(); specificSystemIndex++) - { - RakNetGUID specificSystem = getRequest->cloudQueryWithAddresses.specificSystems[specificSystemIndex]; - - unsigned int keyDataListIndex = cloudDataList->keyData.GetIndexFromKey(specificSystem, &keyDataListExists); - if (keyDataListExists==false) - { - cloudData = MafiaNet::OP_NEW(_FILE_AND_LINE_); - cloudData->dataLengthBytes=0; - cloudData->allocatedData=0; - cloudData->isUploaded=false; - cloudData->dataPtr=0; - cloudData->serverSystemAddress=UNASSIGNED_SYSTEM_ADDRESS; - cloudData->clientSystemAddress=UNASSIGNED_SYSTEM_ADDRESS; - cloudData->serverGUID=rakPeerInterface->GetMyGUID(); - cloudData->clientGUID=specificSystem; - cloudDataList->keyData.Insert(specificSystem,cloudData,true,_FILE_AND_LINE_); - } - else - { - cloudData = cloudDataList->keyData[keyDataListIndex]; - } - - ++cloudDataList->subscriberCount; - cloudData->specificSubscribers.Insert(packet->guid, packet->guid, true, _FILE_AND_LINE_); - } - } - else - { - ++cloudDataList->subscriberCount; - cloudDataList->nonSpecificSubscribers.Insert(packet->guid, packet->guid, true, _FILE_AND_LINE_); - - // Remove packet->guid from CloudData::specificSubscribers among all instances of cloudDataList->keyData - unsigned int subscribedKeysIndex; - bool subscribedKeysIndexExists; - subscribedKeysIndex = remoteCloudClient->subscribedKeys.GetIndexFromKey(cloudDataList->key, &subscribedKeysIndexExists); - if (subscribedKeysIndexExists) - { - keySubscriberId = remoteCloudClient->subscribedKeys[subscribedKeysIndex]; - for (specificSystemIndex=0; specificSystemIndex < keySubscriberId->specificSystemsSubscribedTo.Size(); specificSystemIndex++) - { - bool keyDataExists; - unsigned int keyDataIndex = cloudDataList->keyData.GetIndexFromKey(keySubscriberId->specificSystemsSubscribedTo[specificSystemIndex], &keyDataExists); - if (keyDataExists) - { - CloudData *keyData = cloudDataList->keyData[keyDataIndex]; - keyData->specificSubscribers.Remove(packet->guid); - --cloudDataList->subscriberCount; - } - } - } - } - } - - if (remoteCloudClient->subscribedKeys.Size()==0) - { - // Didn't do anything - remoteSystems.Remove(packet->guid, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(remoteCloudClient, _FILE_AND_LINE_); - } - } - - if (remoteServersWithData.Size()==0) - MafiaNet::OP_DELETE(getRequest, _FILE_AND_LINE_); -} -void CloudServer::OnUnsubscribeRequest(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)); - - DataStructures::HashIndex remoteSystemIndex = remoteSystems.GetIndexOf(packet->guid); - if (remoteSystemIndex.IsInvalid()==true) - return; - - RemoteCloudClient* remoteCloudClient = remoteSystems.ItemAtIndex(remoteSystemIndex); - - uint16_t keyCount, specificSystemCount; - DataStructures::List cloudKeys; - DataStructures::List specificSystems; - uint16_t index; - - CloudKey cloudKey; - bsIn.Read(keyCount); - for (index=0; index < keyCount; index++) - { - cloudKey.Serialize(false, &bsIn); - cloudKeys.Push(cloudKey, _FILE_AND_LINE_); - } - - RakNetGUID specificSystem; - bsIn.Read(specificSystemCount); - for (index=0; index < specificSystemCount; index++) - { - bsIn.Read(specificSystem); - specificSystems.Push(specificSystem, _FILE_AND_LINE_); - } - - for (unsigned int filterIndex=0; filterIndex < queryFilters.Size(); filterIndex++) - { - if (queryFilters[filterIndex]->OnUnsubscribeRequest(packet->guid, packet->systemAddress, cloudKeys, specificSystems )==false) - return; - } - -// CloudDataList *cloudDataList; - bool dataRepositoryExists; -// unsigned int dataRepositoryIndex; - - for (index=0; index < keyCount; index++) - { - cloudKey = cloudKeys[index]; - - // dataRepositoryIndex = - dataRepository.GetIndexFromKey(cloudKey, &dataRepositoryExists); - if (dataRepositoryExists==false) - continue; -// cloudDataList = dataRepository[dataRepositoryIndex]; - - unsigned int keySubscriberIndex; - bool hasKeySubscriber; - keySubscriberIndex = remoteCloudClient->subscribedKeys.GetIndexFromKey(cloudKey, &hasKeySubscriber); - - if (hasKeySubscriber==false) - continue; - - UnsubscribeFromKey(remoteCloudClient, packet->guid, keySubscriberIndex, cloudKey, specificSystems); - } - - if (remoteCloudClient->IsUnused()) - { - MafiaNet::OP_DELETE(remoteCloudClient, _FILE_AND_LINE_); - remoteSystems.RemoveAtIndex(remoteSystemIndex, _FILE_AND_LINE_); - } -} -void CloudServer::OnServerToServerGetRequest(Packet *packet) -{ -// unsigned int remoteServerIndex; - bool objectExists; - //remoteServerIndex = - remoteServers.GetIndexFromKey(packet->guid, &objectExists); - if (objectExists==false) - return; - - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - - CloudQueryWithAddresses cloudQueryWithAddresses; - uint32_t requestId; - cloudQueryWithAddresses.Serialize(false, &bsIn); - bsIn.Read(requestId); - - DataStructures::List cloudDataResultList; - DataStructures::List cloudKeyResultList; - ProcessCloudQueryWithAddresses(cloudQueryWithAddresses, cloudDataResultList, cloudKeyResultList); - - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); - bsOut.Write((MessageID)STSC_PROCESS_GET_RESPONSE); - bsOut.Write(requestId); - WriteCloudQueryRowFromResultList(cloudDataResultList, cloudKeyResultList, &bsOut); - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, packet->guid, false); -} -void CloudServer::OnServerToServerGetResponse(Packet *packet) -{ - unsigned int remoteServerIndex; - bool objectExists; - remoteServerIndex = remoteServers.GetIndexFromKey(packet->guid, &objectExists); - if (objectExists==false) - return; - - RemoteServer *remoteServer = remoteServers[remoteServerIndex]; - if (remoteServer==0) - return; - - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - - uint32_t requestId; - bsIn.Read(requestId); - - // Lookup request id - bool hasGetRequest; - unsigned int getRequestIndex; - getRequestIndex = getRequests.GetIndexFromKey(requestId, &hasGetRequest); - if (hasGetRequest==false) - return; - GetRequest *getRequest = getRequests[getRequestIndex]; - bool hasRemoteServer; - unsigned int remoteServerResponsesIndex; - remoteServerResponsesIndex = getRequest->remoteServerResponses.GetIndexFromKey(packet->guid, &hasRemoteServer); - if (hasRemoteServer==false) - return; - BufferedGetResponseFromServer *bufferedGetResponseFromServer; - bufferedGetResponseFromServer = getRequest->remoteServerResponses[remoteServerResponsesIndex]; - if (bufferedGetResponseFromServer->gotResult==true) - return; - bufferedGetResponseFromServer->gotResult=true; - uint32_t numRows; - bufferedGetResponseFromServer->queryResult.SerializeNumRows(false, numRows, &bsIn); - bufferedGetResponseFromServer->queryResult.SerializeCloudQueryRows(false, numRows, &bsIn, this); - - // If all results returned, then also process locally, and return to user - if (getRequest->AllRemoteServersHaveResponded()) - { - ProcessAndTransmitGetRequest(getRequest); - - getRequest->Clear(this); - MafiaNet::OP_DELETE(getRequest, _FILE_AND_LINE_); - - getRequests.RemoveAtIndex(getRequestIndex); - } -} -void CloudServer::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) lostConnectionReason; - (void) systemAddress; - - unsigned int remoteServerIndex; - bool objectExists; - remoteServerIndex = remoteServers.GetIndexFromKey(rakNetGUID, &objectExists); - if (objectExists) - { - // Update remoteServerResponses by removing this server and sending the response if it is now complete - unsigned int getRequestIndex=0; - while (getRequestIndex < getRequests.Size()) - { - GetRequest *getRequest = getRequests[getRequestIndex]; - bool waitingForThisServer; - unsigned int remoteServerResponsesIndex = getRequest->remoteServerResponses.GetIndexFromKey(rakNetGUID, &waitingForThisServer); - if (waitingForThisServer) - { - getRequest->remoteServerResponses[remoteServerResponsesIndex]->Clear(this); - MafiaNet::OP_DELETE(getRequest->remoteServerResponses[remoteServerResponsesIndex], _FILE_AND_LINE_); - getRequest->remoteServerResponses.RemoveAtIndex(remoteServerResponsesIndex); - - if (getRequest->AllRemoteServersHaveResponded()) - { - ProcessAndTransmitGetRequest(getRequest); - getRequest->Clear(this); - MafiaNet::OP_DELETE(getRequest, _FILE_AND_LINE_); - - getRequests.RemoveAtIndex(getRequestIndex); - } - else - getRequestIndex++; - } - else - getRequestIndex++; - } - - MafiaNet::OP_DELETE(remoteServers[remoteServerIndex],_FILE_AND_LINE_); - remoteServers.RemoveAtIndex(remoteServerIndex); - } - - DataStructures::HashIndex remoteSystemIndex = remoteSystems.GetIndexOf(rakNetGUID); - if (remoteSystemIndex.IsInvalid()==false) - { - RemoteCloudClient* remoteCloudClient = remoteSystems.ItemAtIndex(remoteSystemIndex); - unsigned int uploadedKeysIndex; - for (uploadedKeysIndex=0; uploadedKeysIndex < remoteCloudClient->uploadedKeys.Size(); uploadedKeysIndex++) - { - // Delete keys this system has uploaded - bool keyDataRepositoryExists; - unsigned int dataRepositoryIndex = dataRepository.GetIndexFromKey(remoteCloudClient->uploadedKeys[uploadedKeysIndex], &keyDataRepositoryExists); - if (keyDataRepositoryExists) - { - CloudDataList* cloudDataList = dataRepository[dataRepositoryIndex]; - bool keyDataExists; - unsigned int keyDataIndex = cloudDataList->keyData.GetIndexFromKey(rakNetGUID, &keyDataExists); - if (keyDataExists) - { - CloudData *cloudData = cloudDataList->keyData[keyDataIndex]; - cloudDataList->uploaderCount--; - - NotifyClientSubscribersOfDataChange(cloudData, cloudDataList->key, cloudData->specificSubscribers, false ); - NotifyClientSubscribersOfDataChange(cloudData, cloudDataList->key, cloudDataList->nonSpecificSubscribers, false ); - NotifyServerSubscribersOfDataChange(cloudData, cloudDataList->key, false ); - - cloudData->Clear(); - - if (cloudData->IsUnused()) - { - MafiaNet::OP_DELETE(cloudData,_FILE_AND_LINE_); - cloudDataList->keyData.RemoveAtIndex(keyDataIndex); - - if (cloudDataList->IsNotUploaded()) - { - // Tell other servers that this key is no longer uploaded, so they do not request it from us - RemoveUploadedKeyFromServers(cloudDataList->key); - } - - if (cloudDataList->IsUnused()) - { - // Tell other servers that this key is no longer uploaded, so they do not request it from us - RemoveUploadedKeyFromServers(cloudDataList->key); - - MafiaNet::OP_DELETE(cloudDataList, _FILE_AND_LINE_); - dataRepository.RemoveAtIndex(dataRepositoryIndex); - } - } - } - } - } - - unsigned int subscribedKeysIndex; - for (subscribedKeysIndex=0; subscribedKeysIndex < remoteCloudClient->subscribedKeys.Size(); subscribedKeysIndex++) - { - KeySubscriberID* keySubscriberId; - keySubscriberId = remoteCloudClient->subscribedKeys[subscribedKeysIndex]; - - bool keyDataRepositoryExists; - unsigned int keyDataRepositoryIndex = dataRepository.GetIndexFromKey(remoteCloudClient->subscribedKeys[subscribedKeysIndex]->key, &keyDataRepositoryExists); - if (keyDataRepositoryExists) - { - CloudDataList* cloudDataList = dataRepository[keyDataRepositoryIndex]; - if (keySubscriberId->specificSystemsSubscribedTo.Size()==0) - { - cloudDataList->nonSpecificSubscribers.Remove(rakNetGUID); - --cloudDataList->subscriberCount; - } - else - { - unsigned int specificSystemIndex; - for (specificSystemIndex=0; specificSystemIndex < keySubscriberId->specificSystemsSubscribedTo.Size(); specificSystemIndex++) - { - bool keyDataExists; - unsigned int keyDataIndex = cloudDataList->keyData.GetIndexFromKey(keySubscriberId->specificSystemsSubscribedTo[specificSystemIndex], &keyDataExists); - if (keyDataExists) - { - CloudData *keyData = cloudDataList->keyData[keyDataIndex]; - keyData->specificSubscribers.Remove(rakNetGUID); - --cloudDataList->subscriberCount; - } - } - } - } - - MafiaNet::OP_DELETE(keySubscriberId, _FILE_AND_LINE_); - } - - // Delete and remove from remoteSystems - MafiaNet::OP_DELETE(remoteCloudClient, _FILE_AND_LINE_); - remoteSystems.RemoveAtIndex(remoteSystemIndex, _FILE_AND_LINE_); - } -} -void CloudServer::OnRakPeerShutdown(void) -{ - Clear(); -} -void CloudServer::Clear(void) -{ - unsigned int i,j; - for (i=0; i < dataRepository.Size(); i++) - { - CloudDataList *cloudDataList = dataRepository[i]; - for (j=0; j < cloudDataList->keyData.Size(); j++) - { - cloudDataList->keyData[j]->Clear(); - MafiaNet::OP_DELETE(cloudDataList->keyData[j], _FILE_AND_LINE_); - } - MafiaNet::OP_DELETE(cloudDataList, _FILE_AND_LINE_); - } - dataRepository.Clear(false, _FILE_AND_LINE_); - - for (i=0; i < remoteServers.Size(); i++) - { - MafiaNet::OP_DELETE(remoteServers[i], _FILE_AND_LINE_); - } - remoteServers.Clear(false, _FILE_AND_LINE_); - - for (i=0; i < getRequests.Size(); i++) - { - GetRequest *getRequest = getRequests[i]; - getRequest->Clear(this); - MafiaNet::OP_DELETE(getRequests[i], _FILE_AND_LINE_); - } - getRequests.Clear(false, _FILE_AND_LINE_); - - DataStructures::List keyList; - DataStructures::List itemList; - remoteSystems.GetAsList(itemList, keyList, _FILE_AND_LINE_); - for (i=0; i < itemList.Size(); i++) - { - RemoteCloudClient* remoteCloudClient = itemList[i]; - for (j=0; j < remoteCloudClient->subscribedKeys.Size(); j++) - { - MafiaNet::OP_DELETE(remoteCloudClient->subscribedKeys[j], _FILE_AND_LINE_); - } - MafiaNet::OP_DELETE(remoteCloudClient, _FILE_AND_LINE_); - } - remoteSystems.Clear(_FILE_AND_LINE_); -} -void CloudServer::WriteCloudQueryRowFromResultList(DataStructures::List &cloudDataResultList, DataStructures::List &cloudKeyResultList, BitStream *bsOut) -{ - bsOut->WriteCasted(cloudKeyResultList.Size()); - unsigned int i; - for (i=0; i < cloudKeyResultList.Size(); i++) - { - WriteCloudQueryRowFromResultList(i, cloudDataResultList, cloudKeyResultList, bsOut); - } -} -void CloudServer::WriteCloudQueryRowFromResultList(unsigned int i, DataStructures::List &cloudDataResultList, DataStructures::List &cloudKeyResultList, BitStream *bsOut) -{ - CloudQueryRow cloudQueryRow; - CloudData *cloudData = cloudDataResultList[i]; - cloudQueryRow.key=cloudKeyResultList[i]; - cloudQueryRow.data=cloudData->dataPtr; - cloudQueryRow.length=cloudData->dataLengthBytes; - cloudQueryRow.serverSystemAddress=cloudData->serverSystemAddress; - cloudQueryRow.clientSystemAddress=cloudData->clientSystemAddress; - cloudQueryRow.serverGUID=cloudData->serverGUID; - cloudQueryRow.clientGUID=cloudData->clientGUID; - cloudQueryRow.Serialize(true, bsOut, 0); -} -void CloudServer::NotifyClientSubscribersOfDataChange( CloudData *cloudData, CloudKey &key, DataStructures::OrderedList &subscribers, bool wasUpdated ) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID) ID_CLOUD_SUBSCRIPTION_NOTIFICATION); - bsOut.Write(wasUpdated); - CloudQueryRow row; - row.key=key; - row.data=cloudData->dataPtr; - row.length=cloudData->dataLengthBytes; - row.serverSystemAddress=cloudData->serverSystemAddress; - row.clientSystemAddress=cloudData->clientSystemAddress; - row.serverGUID=cloudData->serverGUID; - row.clientGUID=cloudData->clientGUID; - row.Serialize(true,&bsOut,0); - - unsigned int i; - for (i=0; i < subscribers.Size(); i++) - { - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, subscribers[i], false); - } -} -void CloudServer::NotifyClientSubscribersOfDataChange( CloudQueryRow *row, DataStructures::OrderedList &subscribers, bool wasUpdated ) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID) ID_CLOUD_SUBSCRIPTION_NOTIFICATION); - bsOut.Write(wasUpdated); - row->Serialize(true,&bsOut,0); - - unsigned int i; - for (i=0; i < subscribers.Size(); i++) - { - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, subscribers[i], false); - } -} -void CloudServer::NotifyServerSubscribersOfDataChange( CloudData *cloudData, CloudKey &key, bool wasUpdated ) -{ - // Find every server that has subscribed - // Send them change notifications - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); - bsOut.Write((MessageID)STSC_DATA_CHANGED); - bsOut.Write(wasUpdated); - CloudQueryRow row; - row.key=key; - row.data=cloudData->dataPtr; - row.length=cloudData->dataLengthBytes; - row.serverSystemAddress=cloudData->serverSystemAddress; - row.clientSystemAddress=cloudData->clientSystemAddress; - row.serverGUID=cloudData->serverGUID; - row.clientGUID=cloudData->clientGUID; - row.Serialize(true,&bsOut,0); - - unsigned int i; - for (i=0; i < remoteServers.Size(); i++) - { - if (remoteServers[i]->gotSubscribedAndUploadedKeys==false || remoteServers[i]->subscribedKeys.HasData(key)) - { - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, remoteServers[i]->serverAddress, false); - } - } -} -void CloudServer::AddServer(RakNetGUID systemIdentifier) -{ - ConnectionState cs = rakPeerInterface->GetConnectionState(systemIdentifier); - if (cs==IS_DISCONNECTED || cs==IS_NOT_CONNECTED) - return; - bool objectExists; - unsigned int index = remoteServers.GetIndexFromKey(systemIdentifier,&objectExists); - if (objectExists==false) - { - RemoteServer *remoteServer = MafiaNet::OP_NEW(_FILE_AND_LINE_); - remoteServer->gotSubscribedAndUploadedKeys=false; - remoteServer->serverAddress=systemIdentifier; - remoteServers.InsertAtIndex(remoteServer, index, _FILE_AND_LINE_); - - SendUploadedAndSubscribedKeysToServer(systemIdentifier); - } -} -void CloudServer::RemoveServer(RakNetGUID systemAddress) -{ - bool objectExists; - unsigned int index = remoteServers.GetIndexFromKey(systemAddress,&objectExists); - if (objectExists==true) - { - MafiaNet::OP_DELETE(remoteServers[index],_FILE_AND_LINE_); - remoteServers.RemoveAtIndex(index); - } -} -void CloudServer::GetRemoteServers(DataStructures::List &remoteServersOut) -{ - remoteServersOut.Clear(true, _FILE_AND_LINE_); - - unsigned int i; - for (i=0; i < remoteServers.Size(); i++) - { - remoteServersOut.Push(remoteServers[i]->serverAddress, _FILE_AND_LINE_); - } -} -void CloudServer::ProcessAndTransmitGetRequest(GetRequest *getRequest) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID) ID_CLOUD_GET_RESPONSE); - - // BufferedGetResponseFromServer getResponse; - CloudQueryResult cloudQueryResult; - cloudQueryResult.cloudQuery=getRequest->cloudQueryWithAddresses.cloudQuery; - cloudQueryResult.subscribeToResults=getRequest->cloudQueryWithAddresses.cloudQuery.subscribeToResults; - cloudQueryResult.SerializeHeader(true, &bsOut); - - DataStructures::List cloudDataResultList; - DataStructures::List cloudKeyResultList; - ProcessCloudQueryWithAddresses(getRequest->cloudQueryWithAddresses, cloudDataResultList, cloudKeyResultList); - bool unlimitedRows=getRequest->cloudQueryWithAddresses.cloudQuery.maxRowsToReturn==0; - - uint32_t localNumRows = (uint32_t) cloudDataResultList.Size(); - if (unlimitedRows==false && - localNumRows > getRequest->cloudQueryWithAddresses.cloudQuery.startingRowIndex && - localNumRows - getRequest->cloudQueryWithAddresses.cloudQuery.startingRowIndex > getRequest->cloudQueryWithAddresses.cloudQuery.maxRowsToReturn ) - localNumRows=getRequest->cloudQueryWithAddresses.cloudQuery.startingRowIndex + getRequest->cloudQueryWithAddresses.cloudQuery.maxRowsToReturn; - - BitSize_t bitStreamOffset = bsOut.GetWriteOffset(); - uint32_t localRowsToWrite; - unsigned int skipRows; - if (localNumRows>getRequest->cloudQueryWithAddresses.cloudQuery.startingRowIndex) - { - localRowsToWrite=localNumRows-getRequest->cloudQueryWithAddresses.cloudQuery.startingRowIndex; - skipRows=0; - } - else - { - localRowsToWrite=0; - skipRows=getRequest->cloudQueryWithAddresses.cloudQuery.startingRowIndex-localNumRows; - } - cloudQueryResult.SerializeNumRows(true, localRowsToWrite, &bsOut); - for (unsigned int i=getRequest->cloudQueryWithAddresses.cloudQuery.startingRowIndex; i < localNumRows; i++) - { - WriteCloudQueryRowFromResultList(i, cloudDataResultList, cloudKeyResultList, &bsOut); - } - - // Append remote systems for remaining rows - if (unlimitedRows==true || getRequest->cloudQueryWithAddresses.cloudQuery.maxRowsToReturn>localRowsToWrite) - { - uint32_t remainingRows=0; - uint32_t additionalRowsWritten=0; - if (unlimitedRows==false) - remainingRows=getRequest->cloudQueryWithAddresses.cloudQuery.maxRowsToReturn-localRowsToWrite; - - unsigned int remoteServerResponseIndex; - for (remoteServerResponseIndex=0; remoteServerResponseIndex < getRequest->remoteServerResponses.Size(); remoteServerResponseIndex++) - { - BufferedGetResponseFromServer *bufferedGetResponseFromServer = getRequest->remoteServerResponses[remoteServerResponseIndex]; - unsigned int cloudQueryRowIndex; - for (cloudQueryRowIndex=0; cloudQueryRowIndex < bufferedGetResponseFromServer->queryResult.rowsReturned.Size(); cloudQueryRowIndex++) - { - if (skipRows>0) - { - --skipRows; - continue; - } - bufferedGetResponseFromServer->queryResult.rowsReturned[cloudQueryRowIndex]->Serialize(true, &bsOut, this); - - ++additionalRowsWritten; - if (unlimitedRows==false && --remainingRows==0) - break; - } - - if (unlimitedRows==false && remainingRows==0) - break; - } - - if (additionalRowsWritten>0) - { - BitSize_t curOffset = bsOut.GetWriteOffset(); - bsOut.SetWriteOffset(bitStreamOffset); - localRowsToWrite+=additionalRowsWritten; - cloudQueryResult.SerializeNumRows(true, localRowsToWrite, &bsOut); - bsOut.SetWriteOffset(curOffset); - } - } - - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, getRequest->requestingClient, false); -} -void CloudServer::ProcessCloudQueryWithAddresses( CloudServer::CloudQueryWithAddresses &cloudQueryWithAddresses, DataStructures::List &cloudDataResultList, DataStructures::List &cloudKeyResultList ) -{ - CloudQueryResult cloudQueryResult; - CloudQueryRow cloudQueryRow; - unsigned int queryIndex; - bool dataRepositoryExists; - CloudDataList* cloudDataList; - unsigned int keyDataIndex; - - // If specificSystems list empty, applies to all systems - // For each of keys in cloudQueryWithAddresses, return that data, limited by maxRowsToReturn - for (queryIndex=0; queryIndex < cloudQueryWithAddresses.cloudQuery.keys.Size(); queryIndex++) - { - const CloudKey &key = cloudQueryWithAddresses.cloudQuery.keys[queryIndex]; - - unsigned int dataRepositoryIndex = dataRepository.GetIndexFromKey(key, &dataRepositoryExists); - if (dataRepositoryExists) - { - cloudDataList=dataRepository[dataRepositoryIndex]; - - if (cloudDataList->uploaderCount>0) - { - // Return all keyData that was uploaded by specificSystems, or all if not specified - if (cloudQueryWithAddresses.specificSystems.Size()>0) - { - // Return data for matching systems - unsigned int specificSystemIndex; - for (specificSystemIndex=0; specificSystemIndex < cloudQueryWithAddresses.specificSystems.Size(); specificSystemIndex++) - { - bool uploaderExists; - keyDataIndex = cloudDataList->keyData.GetIndexFromKey(cloudQueryWithAddresses.specificSystems[specificSystemIndex], &uploaderExists); - if (uploaderExists) - { - cloudDataResultList.Push(cloudDataList->keyData[keyDataIndex], _FILE_AND_LINE_); - cloudKeyResultList.Push(key, _FILE_AND_LINE_); - } - } - } - else - { - // Return data for all systems - for (keyDataIndex=0; keyDataIndex < cloudDataList->keyData.Size(); keyDataIndex++) - { - cloudDataResultList.Push(cloudDataList->keyData[keyDataIndex], _FILE_AND_LINE_); - cloudKeyResultList.Push(key, _FILE_AND_LINE_); - } - } - } - } - } -} -void CloudServer::SendUploadedAndSubscribedKeysToServer( RakNetGUID systemAddress ) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); - bsOut.Write((MessageID)STSC_ADD_UPLOADED_AND_SUBSCRIBED_KEYS); - bsOut.WriteCasted(dataRepository.Size()); - for (unsigned int i=0; i < dataRepository.Size(); i++) - dataRepository[i]->key.Serialize(true, &bsOut); - - BitSize_t startOffset, endOffset; - uint16_t subscribedKeyCount=0; - startOffset=bsOut.GetWriteOffset(); - bsOut.WriteCasted(subscribedKeyCount); - for (unsigned int i=0; i < dataRepository.Size(); i++) - { - if (dataRepository[i]->subscriberCount>0) - { - dataRepository[i]->key.Serialize(true, &bsOut); - subscribedKeyCount++; - } - } - endOffset=bsOut.GetWriteOffset(); - bsOut.SetWriteOffset(startOffset); - bsOut.WriteCasted(subscribedKeyCount); - bsOut.SetWriteOffset(endOffset); - - if (dataRepository.Size()>0 || subscribedKeyCount>0) - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, systemAddress, false); -} -void CloudServer::SendUploadedKeyToServers( CloudKey &cloudKey ) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); - bsOut.Write((MessageID)STSC_ADD_UPLOADED_KEY); - cloudKey.Serialize(true, &bsOut); - for (unsigned int i=0; i < remoteServers.Size(); i++) - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, remoteServers[i]->serverAddress, false); -} -void CloudServer::SendSubscribedKeyToServers( CloudKey &cloudKey ) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); - bsOut.Write((MessageID)STSC_ADD_SUBSCRIBED_KEY); - cloudKey.Serialize(true, &bsOut); - for (unsigned int i=0; i < remoteServers.Size(); i++) - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, remoteServers[i]->serverAddress, false); -} -void CloudServer::RemoveUploadedKeyFromServers( CloudKey &cloudKey ) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); - bsOut.Write((MessageID)STSC_REMOVE_UPLOADED_KEY); - cloudKey.Serialize(true, &bsOut); - for (unsigned int i=0; i < remoteServers.Size(); i++) - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, remoteServers[i]->serverAddress, false); -} -void CloudServer::RemoveSubscribedKeyFromServers( CloudKey &cloudKey ) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); - bsOut.Write((MessageID)STSC_REMOVE_SUBSCRIBED_KEY); - cloudKey.Serialize(true, &bsOut); - for (unsigned int i=0; i < remoteServers.Size(); i++) - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, remoteServers[i]->serverAddress, false); -} -void CloudServer::OnSendUploadedAndSubscribedKeysToServer( Packet *packet ) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - - bool objectExists; - unsigned int index = remoteServers.GetIndexFromKey(packet->guid,&objectExists); - if (objectExists==false) - return; - RemoteServer *remoteServer = remoteServers[index]; - remoteServer->gotSubscribedAndUploadedKeys=true; - -// unsigned int insertionIndex; - bool alreadyHasKey; - uint16_t numUploadedKeys, numSubscribedKeys; - bsIn.Read(numUploadedKeys); - for (uint16_t i=0; i < numUploadedKeys; i++) - { - CloudKey cloudKey; - cloudKey.Serialize(false, &bsIn); - - // insertionIndex = - remoteServer->uploadedKeys.GetIndexFromKey(cloudKey, &alreadyHasKey); - if (alreadyHasKey==false) - remoteServer->uploadedKeys.Insert(cloudKey,cloudKey,true,_FILE_AND_LINE_); - } - - bsIn.Read(numSubscribedKeys); - for (uint16_t i=0; i < numSubscribedKeys; i++) - { - CloudKey cloudKey; - cloudKey.Serialize(false, &bsIn); - - //insertionIndex = - remoteServer->subscribedKeys.GetIndexFromKey(cloudKey, &alreadyHasKey); - if (alreadyHasKey==false) - remoteServer->subscribedKeys.Insert(cloudKey,cloudKey,true,_FILE_AND_LINE_); - } - - // Potential todo - join servers - // For each uploaded key that we subscribe to, query it - // For each subscribed key that we have, send it -} -void CloudServer::OnSendUploadedKeyToServers( Packet *packet ) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - - bool objectExists; - unsigned int index = remoteServers.GetIndexFromKey(packet->guid,&objectExists); - if (objectExists==false) - return; - RemoteServer *remoteServer = remoteServers[index]; - CloudKey cloudKey; - cloudKey.Serialize(false, &bsIn); -// unsigned int insertionIndex; - bool alreadyHasKey; -// insertionIndex = - remoteServer->uploadedKeys.GetIndexFromKey(cloudKey, &alreadyHasKey); - if (alreadyHasKey==false) - remoteServer->uploadedKeys.Insert(cloudKey,cloudKey,true,_FILE_AND_LINE_); -} -void CloudServer::OnSendSubscribedKeyToServers( Packet *packet ) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - - bool objectExists; - unsigned int index = remoteServers.GetIndexFromKey(packet->guid,&objectExists); - if (objectExists==false) - return; - RemoteServer *remoteServer = remoteServers[index]; - CloudKey cloudKey; - cloudKey.Serialize(false, &bsIn); -// unsigned int insertionIndex; - bool alreadyHasKey; -// insertionIndex = - remoteServer->subscribedKeys.GetIndexFromKey(cloudKey, &alreadyHasKey); - - // Do not need to send current values, the Get request will do that as the Get request is sent at the same time - if (alreadyHasKey==false) - remoteServer->subscribedKeys.Insert(cloudKey,cloudKey,true,_FILE_AND_LINE_); -} -void CloudServer::OnRemoveUploadedKeyFromServers( Packet *packet ) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - - bool objectExists; - unsigned int index = remoteServers.GetIndexFromKey(packet->guid,&objectExists); - if (objectExists==false) - return; - RemoteServer *remoteServer = remoteServers[index]; - CloudKey cloudKey; - cloudKey.Serialize(false, &bsIn); - unsigned int insertionIndex; - bool alreadyHasKey; - insertionIndex = remoteServer->uploadedKeys.GetIndexFromKey(cloudKey, &alreadyHasKey); - if (alreadyHasKey==true) - remoteServer->uploadedKeys.RemoveAtIndex(insertionIndex); -} -void CloudServer::OnRemoveSubscribedKeyFromServers( Packet *packet ) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - - bool objectExists; - unsigned int index = remoteServers.GetIndexFromKey(packet->guid,&objectExists); - if (objectExists==false) - return; - RemoteServer *remoteServer = remoteServers[index]; - CloudKey cloudKey; - cloudKey.Serialize(false, &bsIn); - unsigned int insertionIndex; - bool alreadyHasKey; - insertionIndex = remoteServer->subscribedKeys.GetIndexFromKey(cloudKey, &alreadyHasKey); - if (alreadyHasKey==true) - remoteServer->subscribedKeys.RemoveAtIndex(insertionIndex); -} -void CloudServer::OnServerDataChanged( Packet *packet ) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - - bool objectExists; - remoteServers.GetIndexFromKey(packet->guid,&objectExists); - if (objectExists==false) - return; - - // Find everyone that cares about this change and relay - bool wasUpdated=false; - bsIn.Read(wasUpdated); - CloudQueryRow row; - row.Serialize(false, &bsIn, this); - - CloudDataList *cloudDataList; - bool dataRepositoryExists; - unsigned int dataRepositoryIndex; - dataRepositoryIndex = dataRepository.GetIndexFromKey(row.key, &dataRepositoryExists); - if (dataRepositoryExists==false) - { - DeallocateRowData(row.data); - return; - } - cloudDataList = dataRepository[dataRepositoryIndex]; - CloudData *cloudData; - bool keyDataListExists; - unsigned int keyDataListIndex = cloudDataList->keyData.GetIndexFromKey(row.clientGUID, &keyDataListExists); - if (keyDataListExists==true) - { - cloudData = cloudDataList->keyData[keyDataListIndex]; - NotifyClientSubscribersOfDataChange(&row, cloudData->specificSubscribers, wasUpdated ); - } - - NotifyClientSubscribersOfDataChange(&row, cloudDataList->nonSpecificSubscribers, wasUpdated ); - DeallocateRowData(row.data); -} -void CloudServer::GetServersWithUploadedKeys( - DataStructures::List &keys, - DataStructures::List &remoteServersWithData - ) -{ - remoteServersWithData.Clear(true, _FILE_AND_LINE_); - - unsigned int i,j; - for (i=0; i < remoteServers.Size(); i++) - { - remoteServers[i]->workingFlag=false; - } - - for (i=0; i < remoteServers.Size(); i++) - { - if (remoteServers[i]->workingFlag==false) - { - if (remoteServers[i]->gotSubscribedAndUploadedKeys==false) - { - remoteServers[i]->workingFlag=true; - remoteServersWithData.Push(remoteServers[i], _FILE_AND_LINE_); - } - else - { - remoteServers[i]->workingFlag=false; - for (j=0; j < keys.Size(); j++) - { - if (remoteServers[i]->workingFlag==false && remoteServers[i]->uploadedKeys.HasData(keys[j])) - { - remoteServers[i]->workingFlag=true; - remoteServersWithData.Push(remoteServers[i], _FILE_AND_LINE_); - break; - } - } - } - } - } -} - -CloudServer::CloudDataList *CloudServer::GetOrAllocateCloudDataList(CloudKey key, bool *dataRepositoryExists, unsigned int &dataRepositoryIndex) -{ - CloudDataList *cloudDataList; - - dataRepositoryIndex = dataRepository.GetIndexFromKey(key, dataRepositoryExists); - if (*dataRepositoryExists==false) - { - cloudDataList = MafiaNet::OP_NEW(_FILE_AND_LINE_); - cloudDataList->key=key; - cloudDataList->uploaderCount=0; - cloudDataList->subscriberCount=0; - dataRepository.InsertAtIndex(cloudDataList,dataRepositoryIndex,_FILE_AND_LINE_); - } - else - { - cloudDataList = dataRepository[dataRepositoryIndex]; - } - - return cloudDataList; -} - -void CloudServer::UnsubscribeFromKey(RemoteCloudClient *remoteCloudClient, RakNetGUID remoteCloudClientGuid, unsigned int keySubscriberIndex, CloudKey &cloudKey, DataStructures::List &specificSystems) -{ - KeySubscriberID* keySubscriberId = remoteCloudClient->subscribedKeys[keySubscriberIndex]; - - // If removing specific systems, but global subscription, fail - if (keySubscriberId->specificSystemsSubscribedTo.Size()==0 && specificSystems.Size()>0) - return; - - bool dataRepositoryExists; - CloudDataList *cloudDataList; - unsigned int dataRepositoryIndex = dataRepository.GetIndexFromKey(cloudKey, &dataRepositoryExists); - if (dataRepositoryExists==false) - return; - - unsigned int i,j; - - cloudDataList = dataRepository[dataRepositoryIndex]; - if (specificSystems.Size()==0) - { - // Remove global subscriber. If returns false, have to remove specific subscribers - if (cloudDataList->RemoveSubscriber(remoteCloudClientGuid)==false) - { - for (i=0; i < keySubscriberId->specificSystemsSubscribedTo.Size(); i++) - { - RemoveSpecificSubscriber(keySubscriberId->specificSystemsSubscribedTo[i], cloudDataList, remoteCloudClientGuid); - } - } - keySubscriberId->specificSystemsSubscribedTo.Clear(true, _FILE_AND_LINE_); - } - else - { - for (j=0; j < specificSystems.Size(); j++) - { - unsigned int specificSystemsSubscribedToIndex; - bool hasSpecificSystemsSubscribedTo; - specificSystemsSubscribedToIndex=keySubscriberId->specificSystemsSubscribedTo.GetIndexFromKey(specificSystems[j], &hasSpecificSystemsSubscribedTo); - if (hasSpecificSystemsSubscribedTo) - { - RemoveSpecificSubscriber(specificSystems[j], cloudDataList, remoteCloudClientGuid); - keySubscriberId->specificSystemsSubscribedTo.RemoveAtIndex(specificSystemsSubscribedToIndex); - } - } - } - - if (keySubscriberId->specificSystemsSubscribedTo.Size()==0) - { - MafiaNet::OP_DELETE(keySubscriberId, _FILE_AND_LINE_); - remoteCloudClient->subscribedKeys.RemoveAtIndex(keySubscriberIndex); - } - - if (cloudDataList->subscriberCount==0) - RemoveSubscribedKeyFromServers(cloudKey); - - if (cloudDataList->IsUnused()) - { - MafiaNet::OP_DELETE(cloudDataList, _FILE_AND_LINE_); - dataRepository.RemoveAtIndex(dataRepositoryIndex); - } -} -void CloudServer::RemoveSpecificSubscriber(RakNetGUID specificSubscriber, CloudDataList *cloudDataList, RakNetGUID remoteCloudClientGuid) -{ - bool keyDataListExists; - unsigned int keyDataListIndex = cloudDataList->keyData.GetIndexFromKey(specificSubscriber, &keyDataListExists); - if (keyDataListExists==false) - return; - CloudData *cloudData = cloudDataList->keyData[keyDataListIndex]; - bool hasSpecificSubscriber; - unsigned int specificSubscriberIndex = cloudData->specificSubscribers.GetIndexFromKey(remoteCloudClientGuid, &hasSpecificSubscriber); - if (hasSpecificSubscriber) - { - cloudData->specificSubscribers.RemoveAtIndex(specificSubscriberIndex); - cloudDataList->subscriberCount--; - - if (cloudData->IsUnused()) - { - MafiaNet::OP_DELETE(cloudData, _FILE_AND_LINE_); - cloudDataList->keyData.RemoveAtIndex(keyDataListIndex); - } - } -} - -void CloudServer::ForceExternalSystemAddress(SystemAddress forcedAddress) -{ - forceAddress=forcedAddress; -} -void CloudServer::AddQueryFilter(CloudServerQueryFilter* filter) -{ - if (queryFilters.GetIndexOf(filter)!=(unsigned int) -1) - return; - queryFilters.Push(filter, _FILE_AND_LINE_); -} -void CloudServer::RemoveQueryFilter(CloudServerQueryFilter* filter) -{ - unsigned int index; - index = queryFilters.GetIndexOf(filter); - if (index != (unsigned int) -1) - queryFilters.RemoveAtIndex(index); -} -void CloudServer::RemoveAllQueryFilters(void) -{ - queryFilters.Clear(true, _FILE_AND_LINE_); -} - -#endif diff --git a/vendors/mafianet/Source/src/CommandParserInterface.cpp b/vendors/mafianet/Source/src/CommandParserInterface.cpp deleted file mode 100644 index 2076ff0b3..000000000 --- a/vendors/mafianet/Source/src/CommandParserInterface.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/CommandParserInterface.h" -#include "mafianet/TransportInterface.h" -#include -#include "mafianet/assert.h" -#include - - -#if defined(_WIN32) -// IP_DONTFRAGMENT is different between winsock 1 and winsock 2. Therefore, Winsock2.h must be linked againt Ws2_32.lib -// winsock.h must be linked against WSock32.lib. If these two are mixed up the flag won't work correctly -#include - -#else -#include -#include -#include -#endif - -#include "mafianet/LinuxStrings.h" - -using namespace MafiaNet; - -const unsigned char CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS=255; - -int MafiaNet::RegisteredCommandComp( const char* const & key, const RegisteredCommand &data ) -{ - return _stricmp(key,data.command); -} - -CommandParserInterface::CommandParserInterface() {} -CommandParserInterface::~CommandParserInterface() {} - -void CommandParserInterface::ParseConsoleString(char *str, const char delineator, unsigned char delineatorToggle, unsigned *numParameters, char **parameterList, unsigned parameterListLength) -{ - unsigned strIndex, parameterListIndex; - unsigned strLen; - bool replaceDelineator=true; - - strLen = (unsigned) strlen(str); - - // Replace every instance of delineator, \n, \r with 0 - for (strIndex=0; strIndex < strLen; strIndex++) - { - if (str[strIndex]==delineator && replaceDelineator) - str[strIndex]=0; - - if (str[strIndex]=='\n' || str[strIndex]=='\r') - str[strIndex]=0; - - if (str[strIndex]==delineatorToggle) - { - str[strIndex]=0; - replaceDelineator=!replaceDelineator; - } - } - - // Fill up parameterList starting at each non-0 - for (strIndex=0, parameterListIndex=0; strIndex < strLen; ) - { - if (str[strIndex]!=0) - { - parameterList[parameterListIndex]=str+strIndex; - parameterListIndex++; - RakAssert(parameterListIndex < parameterListLength); - if (parameterListIndex >= parameterListLength) - break; - - strIndex++; - while (str[strIndex]!=0 && strIndex < strLen) - strIndex++; - } - else - strIndex++; - } - - parameterList[parameterListIndex]=0; - *numParameters=parameterListIndex; -} -void CommandParserInterface::SendCommandList(TransportInterface *transport, const SystemAddress &systemAddress) -{ - unsigned i; - if (commandList.Size()) - { - for (i=0; i < commandList.Size(); i++) - { - transport->Send(systemAddress, "%s", commandList[i].command); - if (i < commandList.Size()-1) - transport->Send(systemAddress, ", "); - } - transport->Send(systemAddress, "\r\n"); - } - else - transport->Send(systemAddress, "No registered commands\r\n"); -} -void CommandParserInterface::RegisterCommand(unsigned char parameterCount, const char *command, const char *commandHelp) -{ - RegisteredCommand rc; - rc.command=command; - rc.commandHelp=commandHelp; - rc.parameterCount=parameterCount; - commandList.Insert( command, rc, true, _FILE_AND_LINE_); -} -bool CommandParserInterface::GetRegisteredCommand(const char *command, RegisteredCommand *rc) -{ - bool objectExists; - unsigned index; - index=commandList.GetIndexFromKey(command, &objectExists); - if (objectExists) - *rc=commandList[index]; - return objectExists; -} -void CommandParserInterface::OnTransportChange(TransportInterface *transport) -{ - (void) transport; -} -void CommandParserInterface::OnNewIncomingConnection(const SystemAddress &systemAddress, TransportInterface *transport) -{ - (void) systemAddress; - (void) transport; -} -void CommandParserInterface::OnConnectionLost(const SystemAddress &systemAddress, TransportInterface *transport) -{ - (void) systemAddress; - (void) transport; -} -void CommandParserInterface::ReturnResult(bool res, const char *command,TransportInterface *transport, const SystemAddress &systemAddress) -{ - if (res) - transport->Send(systemAddress, "%s returned true.\r\n", command); - else - transport->Send(systemAddress, "%s returned false.\r\n", command); -} -void CommandParserInterface::ReturnResult(int res, const char *command,TransportInterface *transport, const SystemAddress &systemAddress) -{ - transport->Send(systemAddress, "%s returned %i.\r\n", command, res); -} -void CommandParserInterface::ReturnResult(const char *command, TransportInterface *transport, const SystemAddress &systemAddress) -{ - transport->Send(systemAddress, "Successfully called %s.\r\n", command); -} -void CommandParserInterface::ReturnResult(char *res, const char *command, TransportInterface *transport, const SystemAddress &systemAddress) -{ - transport->Send(systemAddress, "%s returned %s.\r\n", command, res); -} -void CommandParserInterface::ReturnResult(SystemAddress res, const char *command, TransportInterface *transport, const SystemAddress &systemAddress) -{ - char addr[128]; - systemAddress.ToString(false,addr,static_cast(128)); - char addr2[128]; - res.ToString(false,addr2,static_cast(128)); - transport->Send(systemAddress, "%s returned %s %s:%i\r\n", command,addr,addr2,res.GetPort()); -} diff --git a/vendors/mafianet/Source/src/ConnectionGraph2.cpp b/vendors/mafianet/Source/src/ConnectionGraph2.cpp deleted file mode 100644 index a17bdbea4..000000000 --- a/vendors/mafianet/Source/src/ConnectionGraph2.cpp +++ /dev/null @@ -1,313 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_ConnectionGraph2==1 - -#include "mafianet/ConnectionGraph2.h" -#include "mafianet/peerinterface.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/BitStream.h" - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(ConnectionGraph2,ConnectionGraph2) - -int MafiaNet::ConnectionGraph2::RemoteSystemComp( const RakNetGUID &key, RemoteSystem * const &data ) -{ - if (key < data->guid) - return -1; - if (key > data->guid) - return 1; - return 0; -} - -int MafiaNet::ConnectionGraph2::SystemAddressAndGuidComp( const SystemAddressAndGuid &key, const SystemAddressAndGuid &data ) -{ - if (key.guiddata.guid) - return 1; - return 0; -} -ConnectionGraph2::ConnectionGraph2() -{ - autoProcessNewConnections=true; -} -ConnectionGraph2::~ConnectionGraph2() -{ - -} -bool ConnectionGraph2::GetConnectionListForRemoteSystem(RakNetGUID remoteSystemGuid, SystemAddress *saOut, RakNetGUID *guidOut, unsigned int *outLength) -{ - if ((saOut==0 && guidOut==0) || outLength==0 || *outLength==0 || remoteSystemGuid==UNASSIGNED_RAKNET_GUID) - { - *outLength=0; - return false; - } - - bool objectExists; - unsigned int idx = remoteSystems.GetIndexFromKey(remoteSystemGuid, &objectExists); - if (objectExists==false) - { - *outLength=0; - return false; - } - - unsigned int idx2; - if (remoteSystems[idx]->remoteConnections.Size() < *outLength) - *outLength=remoteSystems[idx]->remoteConnections.Size(); - for (idx2=0; idx2 < *outLength; idx2++) - { - if (guidOut) - guidOut[idx2]=remoteSystems[idx]->remoteConnections[idx2].guid; - if (saOut) - saOut[idx2]=remoteSystems[idx]->remoteConnections[idx2].systemAddress; - } - return true; -} -bool ConnectionGraph2::ConnectionExists(RakNetGUID g1, RakNetGUID g2) -{ - if (g1==g2) - return false; - - bool objectExists; - unsigned int idx = remoteSystems.GetIndexFromKey(g1, &objectExists); - if (objectExists==false) - { - return false; - } - SystemAddressAndGuid sag; - sag.guid=g2; - return remoteSystems[idx]->remoteConnections.HasData(sag); -} -uint16_t ConnectionGraph2::GetPingBetweenSystems(RakNetGUID g1, RakNetGUID g2) const -{ - if (g1==g2) - return 0; - - if (g1==rakPeerInterface->GetMyGUID()) - return (uint16_t) rakPeerInterface->GetAveragePing(g2); - if (g2==rakPeerInterface->GetMyGUID()) - return (uint16_t) rakPeerInterface->GetAveragePing(g1); - - bool objectExists; - unsigned int idx = remoteSystems.GetIndexFromKey(g1, &objectExists); - if (objectExists==false) - { - return (uint16_t) -1; - } - - SystemAddressAndGuid sag; - sag.guid=g2; - unsigned int idx2 = remoteSystems[idx]->remoteConnections.GetIndexFromKey(sag, &objectExists); - if (objectExists==false) - { - return (uint16_t) -1; - } - return remoteSystems[idx]->remoteConnections[idx2].sendersPingToThatSystem; -} - -/// Returns the system with the lowest total ping among all its connections. This can be used as the 'best host' for a peer to peer session -RakNetGUID ConnectionGraph2::GetLowestAveragePingSystem(void) const -{ - float lowestPing=-1.0; - unsigned int lowestPingIdx=(unsigned int) -1; - float thisAvePing=0.0f; - unsigned int idx, idx2; - int ap, count=0; - - for (idx=0; idxGetAveragePing(remoteSystems[idx]->guid); - if (ap!=-1) - { - thisAvePing+=(float) ap; - count++; - } - } - - if (count>0) - { - lowestPing=thisAvePing/count; - } - - for (idx=0; idxremoteConnections.Size(); idx2++) - { - ap=remoteSystem->remoteConnections[idx2].sendersPingToThatSystem; - if (ap!=-1) - { - thisAvePing+=(float) ap; - count++; - } - } - - if (count>0 && (lowestPing==-1.0f || thisAvePing/count < lowestPing)) - { - lowestPing=thisAvePing/count; - lowestPingIdx=idx; - } - } - - if (lowestPingIdx==(unsigned int) -1) - return rakPeerInterface->GetMyGUID(); - return remoteSystems[lowestPingIdx]->guid; -} - -void ConnectionGraph2::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - // Send notice to all existing connections - MafiaNet::BitStream bs; - if (lostConnectionReason==LCR_CONNECTION_LOST) - bs.Write((MessageID)ID_REMOTE_CONNECTION_LOST); - else - bs.Write((MessageID)ID_REMOTE_DISCONNECTION_NOTIFICATION); - bs.Write(systemAddress); - bs.Write(rakNetGUID); - SendUnified(&bs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,systemAddress,true); - - bool objectExists; - unsigned int idx = remoteSystems.GetIndexFromKey(rakNetGUID, &objectExists); - if (objectExists) - { - MafiaNet::OP_DELETE(remoteSystems[idx],_FILE_AND_LINE_); - remoteSystems.RemoveAtIndex(idx); - } -} -void ConnectionGraph2::SetAutoProcessNewConnections(bool b) -{ - autoProcessNewConnections=b; -} -bool ConnectionGraph2::GetAutoProcessNewConnections(void) const -{ - return autoProcessNewConnections; -} -void ConnectionGraph2::AddParticipant(const SystemAddress &systemAddress, RakNetGUID rakNetGUID) -{ - // Relay the new connection to other systems. - MafiaNet::BitStream bs; - bs.Write((MessageID)ID_REMOTE_NEW_INCOMING_CONNECTION); - bs.Write((uint32_t)1); - bs.Write(systemAddress); - bs.Write(rakNetGUID); - bs.WriteCasted(rakPeerInterface->GetAveragePing(rakNetGUID)); - SendUnified(&bs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,systemAddress,true); - - // Send everyone to the new guy - DataStructures::List addresses; - DataStructures::List guids; - rakPeerInterface->GetSystemList(addresses, guids); - bs.Reset(); - bs.Write((MessageID)ID_REMOTE_NEW_INCOMING_CONNECTION); - BitSize_t writeOffset = bs.GetWriteOffset(); - bs.Write((uint32_t) addresses.Size()); - - unsigned int i; - uint32_t count=0; - for (i=0; i < addresses.Size(); i++) - { - if (addresses[i]==systemAddress) - continue; - - bs.Write(addresses[i]); - bs.Write(guids[i]); - bs.WriteCasted(rakPeerInterface->GetAveragePing(guids[i])); - count++; - } - - if (count>0) - { - BitSize_t writeOffset2 = bs.GetWriteOffset(); - bs.SetWriteOffset(writeOffset); - bs.Write(count); - bs.SetWriteOffset(writeOffset2); - SendUnified(&bs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,systemAddress,false); - } - - bool objectExists; - unsigned int ii = remoteSystems.GetIndexFromKey(rakNetGUID, &objectExists); - if (objectExists==false) - { - RemoteSystem* remoteSystem = MafiaNet::OP_NEW(_FILE_AND_LINE_); - remoteSystem->guid=rakNetGUID; - remoteSystems.InsertAtIndex(remoteSystem,ii,_FILE_AND_LINE_); - } -} -void ConnectionGraph2::GetParticipantList(DataStructures::OrderedList &participantList) -{ - participantList.Clear(true, _FILE_AND_LINE_); - unsigned int i; - for (i=0; i < remoteSystems.Size(); i++) - participantList.InsertAtEnd(remoteSystems[i]->guid, _FILE_AND_LINE_); -} -void ConnectionGraph2::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) -{ - (void) isIncoming; - if (autoProcessNewConnections) - AddParticipant(systemAddress, rakNetGUID); -} -PluginReceiveResult ConnectionGraph2::OnReceive(Packet *packet) -{ - if (packet->data[0]==ID_REMOTE_CONNECTION_LOST || packet->data[0]==ID_REMOTE_DISCONNECTION_NOTIFICATION) - { - bool objectExists; - unsigned idx = remoteSystems.GetIndexFromKey(packet->guid, &objectExists); - if (objectExists) - { - MafiaNet::BitStream bs(packet->data,packet->length,false); - bs.IgnoreBytes(1); - SystemAddressAndGuid saag; - bs.Read(saag.systemAddress); - bs.Read(saag.guid); - unsigned long idx2 = remoteSystems[idx]->remoteConnections.GetIndexFromKey(saag, &objectExists); - if (objectExists) - remoteSystems[idx]->remoteConnections.RemoveAtIndex(idx2); - } - } - else if (packet->data[0]==ID_REMOTE_NEW_INCOMING_CONNECTION) - { - bool objectExists; - unsigned idx = remoteSystems.GetIndexFromKey(packet->guid, &objectExists); - if (objectExists) - { - uint32_t numAddresses; - MafiaNet::BitStream bs(packet->data,packet->length,false); - bs.IgnoreBytes(1); - bs.Read(numAddresses); - for (unsigned int idx2=0; idx2 < numAddresses; idx2++) - { - SystemAddressAndGuid saag; - bs.Read(saag.systemAddress); - bs.Read(saag.guid); - bs.Read(saag.sendersPingToThatSystem); - unsigned int ii = remoteSystems[idx]->remoteConnections.GetIndexFromKey(saag, &objectExists); - if (objectExists==false) - remoteSystems[idx]->remoteConnections.InsertAtIndex(saag,ii,_FILE_AND_LINE_); - } - } - } - - return RR_CONTINUE_PROCESSING; -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/ConsoleServer.cpp b/vendors/mafianet/Source/src/ConsoleServer.cpp deleted file mode 100644 index 41805b561..000000000 --- a/vendors/mafianet/Source/src/ConsoleServer.cpp +++ /dev/null @@ -1,328 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_ConsoleServer==1 - -#include "mafianet/ConsoleServer.h" -#include "mafianet/TransportInterface.h" -#include "mafianet/CommandParserInterface.h" -#include -#include - -#define COMMAND_DELINATOR ' ' -#define COMMAND_DELINATOR_TOGGLE '"' - -#include "mafianet/LinuxStrings.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(ConsoleServer,ConsoleServer); - -ConsoleServer::ConsoleServer() -{ - transport=0; - password[0]=0; - prompt=0; -} -ConsoleServer::~ConsoleServer() -{ - if (prompt) - rakFree_Ex(prompt, _FILE_AND_LINE_); -} -void ConsoleServer::SetTransportProvider(TransportInterface *transportInterface, unsigned short port) -{ - // Replace the current TransportInterface, stopping the old one, if present, and starting the new one. - if (transportInterface) - { - if (transport) - { - RemoveCommandParser(transport->GetCommandParser()); - transport->Stop(); - } - transport=transportInterface; - transport->Start(port, true); - - unsigned i; - for (i=0; i < commandParserList.Size(); i++) - commandParserList[i]->OnTransportChange(transport); - - // The transport itself might have a command parser - for example password for the RakNet transport - AddCommandParser(transport->GetCommandParser()); - } -} -void ConsoleServer::AddCommandParser(CommandParserInterface *commandParserInterface) -{ - if (commandParserInterface==0) - return; - - // Non-duplicate insertion - unsigned i; - for (i=0; i < commandParserList.Size(); i++) - { - if (commandParserList[i]==commandParserInterface) - return; - - if (_stricmp(commandParserList[i]->GetName(), commandParserInterface->GetName())==0) - { - // Naming conflict between two command parsers - RakAssert(0); - return; - } - } - - commandParserList.Insert(commandParserInterface, _FILE_AND_LINE_); - if (transport) - commandParserInterface->OnTransportChange(transport); -} -void ConsoleServer::RemoveCommandParser(CommandParserInterface *commandParserInterface) -{ - if (commandParserInterface==0) - return; - - // Overwrite the element we are removing from the back of the list and delete the back of the list - unsigned i; - for (i=0; i < commandParserList.Size(); i++) - { - if (commandParserList[i]==commandParserInterface) - { - commandParserList[i]=commandParserList[commandParserList.Size()-1]; - commandParserList.RemoveFromEnd(); - return; - } - } -} -void ConsoleServer::Update(void) -{ - unsigned i; - char *parameterList[20]; // Up to 20 parameters - unsigned numParameters; - MafiaNet::SystemAddress newOrLostConnectionId; - MafiaNet::Packet *p; - MafiaNet::RegisteredCommand rc; - - p = transport->Receive(); - newOrLostConnectionId=transport->HasNewIncomingConnection(); - - if (newOrLostConnectionId!=UNASSIGNED_SYSTEM_ADDRESS) - { - for (i=0; i < commandParserList.Size(); i++) - { - commandParserList[i]->OnNewIncomingConnection(newOrLostConnectionId, transport); - } - - transport->Send(newOrLostConnectionId, "Connected to remote command console.\r\nType 'help' for help.\r\n"); - ListParsers(newOrLostConnectionId); - ShowPrompt(newOrLostConnectionId); - } - - newOrLostConnectionId=transport->HasLostConnection(); - if (newOrLostConnectionId!=UNASSIGNED_SYSTEM_ADDRESS) - { - for (i=0; i < commandParserList.Size(); i++) - commandParserList[i]->OnConnectionLost(newOrLostConnectionId, transport); - } - - while (p) - { - bool commandParsed=false; - char copy[REMOTE_MAX_TEXT_INPUT]; - memcpy(copy, p->data, p->length); - copy[p->length]=0; - MafiaNet::CommandParserInterface::ParseConsoleString((char*)p->data, COMMAND_DELINATOR, COMMAND_DELINATOR_TOGGLE, &numParameters, parameterList, 20); // Up to 20 parameters - if (numParameters==0) - { - transport->DeallocatePacket(p); - p = transport->Receive(); - continue; - } - if (_stricmp(*parameterList, "help")==0 && numParameters<=2) - { - // Find the parser specified and display help for it - if (numParameters==1) - { - transport->Send(p->systemAddress, "\r\nINSTRUCTIONS:\r\n"); - transport->Send(p->systemAddress, "Enter commands on your keyboard, using spaces to delineate parameters.\r\n"); - transport->Send(p->systemAddress, "You can use quotation marks to toggle space delineation.\r\n"); - transport->Send(p->systemAddress, "You can connect multiple times from the same computer.\r\n"); - transport->Send(p->systemAddress, "You can direct commands to a parser by prefixing the parser name or number.\r\n"); - transport->Send(p->systemAddress, "COMMANDS:\r\n"); - transport->Send(p->systemAddress, "help Show this display.\r\n"); - transport->Send(p->systemAddress, "help Show help on a particular parser.\r\n"); - transport->Send(p->systemAddress, "help Show help on a particular command.\r\n"); - transport->Send(p->systemAddress, "quit Disconnects from the server.\r\n"); - transport->Send(p->systemAddress, "[] [] Execute a command\r\n"); - transport->Send(p->systemAddress, "[] [] Execute a command\r\n"); - ListParsers(p->systemAddress); - //ShowPrompt(p->systemAddress); - } - else // numParameters == 2, including the help tag - { - for (i=0; i < commandParserList.Size(); i++) - { - if (_stricmp(parameterList[1], commandParserList[i]->GetName())==0) - { - commandParsed=true; - commandParserList[i]->SendHelp(transport, p->systemAddress); - transport->Send(p->systemAddress, "COMMAND LIST:\r\n"); - commandParserList[i]->SendCommandList(transport, p->systemAddress); - transport->Send(p->systemAddress, "\r\n"); - break; - } - } - - if (commandParsed==false) - { - // Try again, for all commands for all parsers. - MafiaNet::RegisteredCommand rc2; - for (i=0; i < commandParserList.Size(); i++) - { - if (commandParserList[i]->GetRegisteredCommand(parameterList[1], &rc2)) - { - if (rc2.parameterCount== MafiaNet::CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS) - transport->Send(p->systemAddress, "(Variable parms): %s %s\r\n", rc2.command, rc2.commandHelp); - else - transport->Send(p->systemAddress, "(%i parms): %s %s\r\n", rc2.parameterCount, rc2.command, rc2.commandHelp); - commandParsed=true; - break; - } - } - } - - if (commandParsed==false) - { - // Don't know what to do - transport->Send(p->systemAddress, "Unknown help topic: %s.\r\n", parameterList[1]); - } - //ShowPrompt(p->systemAddress); - } - } - else if (_stricmp(*parameterList, "quit")==0 && numParameters==1) - { - transport->Send(p->systemAddress, "Goodbye!\r\n"); - transport->CloseConnection(p->systemAddress); - } - else - { - bool tryAllParsers=true; - bool failed=false; - - if (numParameters >=2) // At minimum - { - unsigned commandParserIndex=(unsigned)-1; - // Prefixing with numbers directs to a particular parser - if (**parameterList>='0' && **parameterList<='9') - { - commandParserIndex=atoi(*parameterList); // Use specified parser unless it's an invalid number - commandParserIndex--; // Subtract 1 since we displayed numbers starting at index+1 - if (commandParserIndex >= commandParserList.Size()) - { - transport->Send(p->systemAddress, "Invalid index.\r\n"); - failed=true; - } - } - else - { - // // Prefixing with the name of a command parser directs to that parser. See if the first word matches a parser - for (i=0; i < commandParserList.Size(); i++) - { - if (_stricmp(parameterList[0], commandParserList[i]->GetName())==0) - { - commandParserIndex=i; // Matches parser at index i - break; - } - } - } - - if (failed==false) - { - // -1 means undirected, so otherwise this is directed to a target - if (commandParserIndex!=(unsigned)-1) - { - // Only this parser should use this command - tryAllParsers=false; - if (commandParserList[commandParserIndex]->GetRegisteredCommand(parameterList[1], &rc)) - { - commandParsed=true; - if (rc.parameterCount==CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS || rc.parameterCount==numParameters-2) - commandParserList[commandParserIndex]->OnCommand(rc.command, numParameters-2, parameterList+2, transport, p->systemAddress, copy); - else - transport->Send(p->systemAddress, "Invalid parameter count.\r\n(%i parms): %s %s\r\n", rc.parameterCount, rc.command, rc.commandHelp); - } - } - } - } - - if (failed == false && tryAllParsers) - { - for (i=0; i < commandParserList.Size(); i++) - { - // Undirected command. Try all the parsers to see if they understand the command - // Pass the 1nd element as the command, and the remainder as the parameter list - if (commandParserList[i]->GetRegisteredCommand(parameterList[0], &rc)) - { - commandParsed=true; - - if (rc.parameterCount==CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS || rc.parameterCount==numParameters-1) - commandParserList[i]->OnCommand(rc.command, numParameters-1, parameterList+1, transport, p->systemAddress, copy); - else - transport->Send(p->systemAddress, "Invalid parameter count.\r\n(%i parms): %s %s\r\n", rc.parameterCount, rc.command, rc.commandHelp); - } - } - } - if (commandParsed==false && commandParserList.Size() > 0) - { - transport->Send(p->systemAddress, "Unknown command: Type 'help' for help.\r\n"); - } - - } - - ShowPrompt(p->systemAddress); - - transport->DeallocatePacket(p); - p = transport->Receive(); - } -} - -void ConsoleServer::ListParsers(SystemAddress systemAddress) -{ - transport->Send(systemAddress,"INSTALLED PARSERS:\r\n"); - unsigned i; - for (i=0; i < commandParserList.Size(); i++) - { - transport->Send(systemAddress, "%i. %s\r\n", i+1, commandParserList[i]->GetName()); - } -} -void ConsoleServer::ShowPrompt(SystemAddress systemAddress) -{ - transport->Send(systemAddress, prompt); -} -void ConsoleServer::SetPrompt(const char *_prompt) -{ - if (prompt) - rakFree_Ex(prompt,_FILE_AND_LINE_); - if (_prompt && _prompt[0]) - { - size_t len = strlen(_prompt); - prompt = (char*) rakMalloc_Ex(len+1,_FILE_AND_LINE_); - strcpy_s(prompt,len+1,_prompt); - } - else - prompt=0; -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/DR_SHA1.cpp b/vendors/mafianet/Source/src/DR_SHA1.cpp deleted file mode 100644 index 9454a9c5c..000000000 --- a/vendors/mafianet/Source/src/DR_SHA1.cpp +++ /dev/null @@ -1,314 +0,0 @@ -/* - 100% free public domain implementation of the SHA-1 algorithm - by Dominik Reichl - Web: http://www.dominik-reichl.de/ - - See header file for version history and test vectors. -*/ - -/* - * Modified work : Copyright(c) 2016-2020, SLikeSoft UG(haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications in this file are put under the public domain. - * Alternatively you are permitted to license the modifications under the MIT license, if you so desire. The - * license can be found in the license.txt file in the root directory of this source tree. - */ - -// If compiling with MFC, you might want to add #include "StdAfx.h" - -#define _CRT_SECURE_NO_WARNINGS -#include "mafianet/DR_SHA1.h" -#include - -#define SHA1_MAX_FILE_BUFFER (32 * 20 * 820) - -// Rotate p_val32 by p_nBits bits to the left -#ifndef ROL32 -#ifdef _MSC_VER -#define ROL32(p_val32,p_nBits) _rotl(p_val32,p_nBits) -#else -#define ROL32(p_val32,p_nBits) (((p_val32)<<(p_nBits))|((p_val32)>>(32-(p_nBits)))) -#endif -#endif - -#ifdef SHA1_LITTLE_ENDIAN -#define SHABLK0(i) (m_block->l[i] = \ - (ROL32(m_block->l[i],24) & 0xFF00FF00) | (ROL32(m_block->l[i],8) & 0x00FF00FF)) -#else -#define SHABLK0(i) (m_block->l[i]) -#endif - -#define SHABLK(i) (m_block->l[i&15] = ROL32(m_block->l[(i+13)&15] ^ \ - m_block->l[(i+8)&15] ^ m_block->l[(i+2)&15] ^ m_block->l[i&15],1)) - -// SHA-1 rounds -#define S_R0(v,w,x,y,z,i) {z+=((w&(x^y))^y)+SHABLK0(i)+0x5A827999+ROL32(v,5);w=ROL32(w,30);} -#define S_R1(v,w,x,y,z,i) {z+=((w&(x^y))^y)+SHABLK(i)+0x5A827999+ROL32(v,5);w=ROL32(w,30);} -#define S_R2(v,w,x,y,z,i) {z+=(w^x^y)+SHABLK(i)+0x6ED9EBA1+ROL32(v,5);w=ROL32(w,30);} -#define S_R3(v,w,x,y,z,i) {z+=(((w|x)&y)|(w&x))+SHABLK(i)+0x8F1BBCDC+ROL32(v,5);w=ROL32(w,30);} -#define S_R4(v,w,x,y,z,i) {z+=(w^x^y)+SHABLK(i)+0xCA62C1D6+ROL32(v,5);w=ROL32(w,30);} - -CSHA1::CSHA1() -{ - m_block = (SHA1_WORKSPACE_BLOCK*)m_workspace; - - Reset(); -} - -#ifdef SHA1_WIPE_VARIABLES -CSHA1::~CSHA1() -{ - Reset(); -} -#endif - -void CSHA1::Reset() -{ - // SHA1 initialization constants - m_state[0] = 0x67452301; - m_state[1] = 0xEFCDAB89; - m_state[2] = 0x98BADCFE; - m_state[3] = 0x10325476; - m_state[4] = 0xC3D2E1F0; - - m_count[0] = 0; - m_count[1] = 0; -} - -void CSHA1::Transform(UINT_32* pState, const UINT_8* pBuffer) -{ - UINT_32 a = pState[0], b = pState[1], c = pState[2], d = pState[3], e = pState[4]; - - memcpy(m_block, pBuffer, 64); - - // 4 rounds of 20 operations each, loop unrolled - S_R0(a,b,c,d,e, 0); S_R0(e,a,b,c,d, 1); S_R0(d,e,a,b,c, 2); S_R0(c,d,e,a,b, 3); - S_R0(b,c,d,e,a, 4); S_R0(a,b,c,d,e, 5); S_R0(e,a,b,c,d, 6); S_R0(d,e,a,b,c, 7); - S_R0(c,d,e,a,b, 8); S_R0(b,c,d,e,a, 9); S_R0(a,b,c,d,e,10); S_R0(e,a,b,c,d,11); - S_R0(d,e,a,b,c,12); S_R0(c,d,e,a,b,13); S_R0(b,c,d,e,a,14); S_R0(a,b,c,d,e,15); - S_R1(e,a,b,c,d,16); S_R1(d,e,a,b,c,17); S_R1(c,d,e,a,b,18); S_R1(b,c,d,e,a,19); - S_R2(a,b,c,d,e,20); S_R2(e,a,b,c,d,21); S_R2(d,e,a,b,c,22); S_R2(c,d,e,a,b,23); - S_R2(b,c,d,e,a,24); S_R2(a,b,c,d,e,25); S_R2(e,a,b,c,d,26); S_R2(d,e,a,b,c,27); - S_R2(c,d,e,a,b,28); S_R2(b,c,d,e,a,29); S_R2(a,b,c,d,e,30); S_R2(e,a,b,c,d,31); - S_R2(d,e,a,b,c,32); S_R2(c,d,e,a,b,33); S_R2(b,c,d,e,a,34); S_R2(a,b,c,d,e,35); - S_R2(e,a,b,c,d,36); S_R2(d,e,a,b,c,37); S_R2(c,d,e,a,b,38); S_R2(b,c,d,e,a,39); - S_R3(a,b,c,d,e,40); S_R3(e,a,b,c,d,41); S_R3(d,e,a,b,c,42); S_R3(c,d,e,a,b,43); - S_R3(b,c,d,e,a,44); S_R3(a,b,c,d,e,45); S_R3(e,a,b,c,d,46); S_R3(d,e,a,b,c,47); - S_R3(c,d,e,a,b,48); S_R3(b,c,d,e,a,49); S_R3(a,b,c,d,e,50); S_R3(e,a,b,c,d,51); - S_R3(d,e,a,b,c,52); S_R3(c,d,e,a,b,53); S_R3(b,c,d,e,a,54); S_R3(a,b,c,d,e,55); - S_R3(e,a,b,c,d,56); S_R3(d,e,a,b,c,57); S_R3(c,d,e,a,b,58); S_R3(b,c,d,e,a,59); - S_R4(a,b,c,d,e,60); S_R4(e,a,b,c,d,61); S_R4(d,e,a,b,c,62); S_R4(c,d,e,a,b,63); - S_R4(b,c,d,e,a,64); S_R4(a,b,c,d,e,65); S_R4(e,a,b,c,d,66); S_R4(d,e,a,b,c,67); - S_R4(c,d,e,a,b,68); S_R4(b,c,d,e,a,69); S_R4(a,b,c,d,e,70); S_R4(e,a,b,c,d,71); - S_R4(d,e,a,b,c,72); S_R4(c,d,e,a,b,73); S_R4(b,c,d,e,a,74); S_R4(a,b,c,d,e,75); - S_R4(e,a,b,c,d,76); S_R4(d,e,a,b,c,77); S_R4(c,d,e,a,b,78); S_R4(b,c,d,e,a,79); - - // Add the working vars back into state - pState[0] += a; - pState[1] += b; - pState[2] += c; - pState[3] += d; - pState[4] += e; - - // Wipe variables -#ifdef SHA1_WIPE_VARIABLES - a = b = c = d = e = 0; -#endif -} - -void CSHA1::Update(const UINT_8* pbData, UINT_32 uLen) -{ - UINT_32 j = ((m_count[0] >> 3) & 0x3F); - - if((m_count[0] += (uLen << 3)) < (uLen << 3)) - ++m_count[1]; // Overflow - - m_count[1] += (uLen >> 29); - - UINT_32 i; - if((j + uLen) > 63) - { - i = 64 - j; - memcpy(&m_buffer[j], pbData, i); - Transform(m_state, m_buffer); - - for( ; (i + 63) < uLen; i += 64) - Transform(m_state, &pbData[i]); - - j = 0; - } - else i = 0; - - if((uLen - i) != 0) - memcpy(&m_buffer[j], &pbData[i], uLen - i); -} - -#ifdef SHA1_UTILITY_FUNCTIONS -bool CSHA1::HashFile(const TCHAR* tszFileName) -{ - if(tszFileName == nullptr) return false; - - FILE* fpIn = _tfopen(tszFileName, _T("rb")); - if(fpIn == nullptr) return false; - - UINT_8* pbData = new UINT_8[SHA1_MAX_FILE_BUFFER]; - if(pbData == nullptr) { fclose(fpIn); return false; } - - bool bSuccess = true; - for(;;) - { - const size_t uRead = fread(pbData, 1, SHA1_MAX_FILE_BUFFER, fpIn); - - if(uRead > 0) - Update(pbData, static_cast(uRead)); - - if(uRead < SHA1_MAX_FILE_BUFFER) - { - if(feof(fpIn) == 0) bSuccess = false; - break; - } - } - - fclose(fpIn); - delete[] pbData; - return bSuccess; -} -#endif - -void CSHA1::Final() -{ - UINT_32 i; - - UINT_8 pbFinalCount[8]; - for(i = 0; i < 8; ++i) - pbFinalCount[i] = static_cast((m_count[((i >= 4) ? 0 : 1)] >> - ((3 - (i & 3)) * 8) ) & 0xFF); // Endian independent - - Update((UINT_8*)"\200", 1); - - while((m_count[0] & 504) != 448) - Update((UINT_8*)"\0", 1); - - Update(pbFinalCount, 8); // Cause a Transform() - - for(i = 0; i < 20; ++i) - m_digest[i] = static_cast((m_state[i >> 2] >> ((3 - - (i & 3)) * 8)) & 0xFF); - - // Wipe variables for security reasons -#ifdef SHA1_WIPE_VARIABLES - memset(m_buffer, 0, 64); - memset(m_state, 0, 20); - memset(m_count, 0, 8); - memset(pbFinalCount, 0, 8); - Transform(m_state, m_buffer); -#endif -} - -#ifdef SHA1_UTILITY_FUNCTIONS -bool CSHA1::ReportHash(TCHAR* tszReport, REPORT_TYPE rtReportType) const -{ - if(tszReport == nullptr) return false; - - TCHAR tszTemp[16]; - - if((rtReportType == REPORT_HEX) || (rtReportType == REPORT_HEX_SHORT)) - { - _sntprintf(tszTemp, 15, _T("%02X"), m_digest[0]); - _tcscpy(tszReport, tszTemp); - - const TCHAR* lpFmt = ((rtReportType == REPORT_HEX) ? _T(" %02X") : _T("%02X")); - for(size_t i = 1; i < 20; ++i) - { - _sntprintf(tszTemp, 15, lpFmt, m_digest[i]); - _tcscat(tszReport, tszTemp); - } - } - else if(rtReportType == REPORT_DIGIT) - { - _sntprintf(tszTemp, 15, _T("%u"), m_digest[0]); - _tcscpy(tszReport, tszTemp); - - for(size_t i = 1; i < 20; ++i) - { - _sntprintf(tszTemp, 15, _T(" %u"), m_digest[i]); - _tcscat(tszReport, tszTemp); - } - } - else return false; - - return true; -} -#endif - -#ifdef SHA1_STL_FUNCTIONS -bool CSHA1::ReportHashStl(std::basic_string& strOut, REPORT_TYPE rtReportType) const -{ - TCHAR tszOut[84]; - const bool bResult = ReportHash(tszOut, rtReportType); - if(bResult) strOut = tszOut; - return bResult; -} -#endif - -bool CSHA1::GetHash(UINT_8* pbDest20) const -{ - if(pbDest20 == nullptr) return false; - memcpy(pbDest20, m_digest, 20); - return true; -} - -// Get the raw message digest -// Added by Kevin to be quicker -unsigned char * CSHA1::GetHash( void ) const -{ - return ( unsigned char * ) m_digest; -} - -// http://cseweb.ucsd.edu/~mihir/papers/hmac-cb.pdf -// Sample code: http://www.opensource.apple.com/source/freeradius/freeradius-11/freeradius/src/lib/hmac.c -void CSHA1::HMAC(unsigned char *sharedKey, int sharedKeyLength, unsigned char *data, int dataLength, unsigned char output[SHA1_LENGTH]) -{ - // 1. Append zeros to the end of K to create a 64 byte string - static const int sha1BlockLength=64; - - if (sharedKeyLength > sha1BlockLength) - sharedKeyLength = sha1BlockLength; - - // ipad = the byte 0x36 repeated 64 times - // opad = the byte 0x5C repeated 64 times - unsigned char keyWithIpad[sha1BlockLength]; - unsigned char keyWithOpad[sha1BlockLength]; - - memset( keyWithIpad, 0, sizeof(keyWithIpad)); - memset( keyWithOpad, 0, sizeof(keyWithOpad)); - memcpy( keyWithIpad, sharedKey, sharedKeyLength); - memcpy( keyWithOpad, sharedKey, sharedKeyLength); - - for (int i = 0; i < sha1BlockLength; i++) { - keyWithIpad[i] ^= 0x36; - keyWithOpad[i] ^= 0x5c; - } - - // 3. Append the data stream Text to the 64 byte string resulting from step (2) - // 4. Apply H to the stream generated in step (3) - CSHA1 firstHash; - firstHash.Reset(); - firstHash.Update( keyWithIpad, sha1BlockLength ); - firstHash.Update( data, dataLength ); - firstHash.Final(); - - // 6. Append the H (hash) result from step (4) to the 64 byte string resulting from step (5) - // 7. Apply H to the stream generated in step (6) and output the result - CSHA1 secondHash; - secondHash.Reset(); - secondHash.Update( keyWithOpad, sha1BlockLength ); - secondHash.Update( firstHash.GetHash(), SHA1_LENGTH ); - secondHash.Final(); - - memcpy(output, secondHash.GetHash(), SHA1_LENGTH); - - // char report[128]; - // memset(report,0,128); - // secondHash.ReportHash( report, 0 ); -} diff --git a/vendors/mafianet/Source/src/DS_BytePool.cpp b/vendors/mafianet/Source/src/DS_BytePool.cpp deleted file mode 100644 index 2794fdc91..000000000 --- a/vendors/mafianet/Source/src/DS_BytePool.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/DS_BytePool.h" -#include "mafianet/assert.h" -#ifndef __APPLE__ -// Use stdlib and not malloc for compatibility -#include -#endif - -using namespace DataStructures; - -BytePool::BytePool() -{ - pool128.SetPageSize(8192*4); - pool512.SetPageSize(8192*4); - pool2048.SetPageSize(8192*4); - pool8192.SetPageSize(8192*4); -} -BytePool::~BytePool() -{ -} -void BytePool::SetPageSize(int size) -{ - pool128.SetPageSize(size); - pool512.SetPageSize(size); - pool2048.SetPageSize(size); - pool8192.SetPageSize(size); -} -unsigned char *BytePool::Allocate(int bytesWanted, const char *file, unsigned int line) -{ -#ifdef _DISABLE_BYTE_POOL - return rakMalloc_Ex(bytesWanted, _FILE_AND_LINE_); -#endif - unsigned char *out; - if (bytesWanted <= 127) - { - #ifdef _THREADSAFE_BYTE_POOL - mutex128.Lock(); - #endif - out = (unsigned char*) pool128.Allocate(file, line); - #ifdef _THREADSAFE_BYTE_POOL - mutex128.Unlock(); - #endif - out[0]=0; - return ((unsigned char*) out)+1; - } - if (bytesWanted <= 511) - { - #ifdef _THREADSAFE_BYTE_POOL - mutex512.Lock(); - #endif - out = (unsigned char*) pool512.Allocate(file, line); - #ifdef _THREADSAFE_BYTE_POOL - mutex512.Unlock(); - #endif - out[0]=1; - return ((unsigned char*) out)+1; - } - if (bytesWanted <= 2047) - { - #ifdef _THREADSAFE_BYTE_POOL - mutex2048.Lock(); - #endif - out = (unsigned char*) pool2048.Allocate(file, line); - #ifdef _THREADSAFE_BYTE_POOL - mutex2048.Unlock(); - #endif - out[0]=2; - return ((unsigned char*) out)+1; - } - if (bytesWanted <= 8191) - { - #ifdef _THREADSAFE_BYTE_POOL - mutex8192.Lock(); - #endif - out = (unsigned char*) pool8192.Allocate(file, line); - #ifdef _THREADSAFE_BYTE_POOL - mutex8192.Unlock(); - #endif - out[0]=3; - return ((unsigned char*) out)+1; - } - - out = (unsigned char*) rakMalloc_Ex(bytesWanted+1, _FILE_AND_LINE_); - out[0]=(unsigned char)255; - return out+1; -} -void BytePool::Release(unsigned char *data, const char *file, unsigned int line) -{ -#ifdef _DISABLE_BYTE_POOL - _rakFree_Ex(data, _FILE_AND_LINE_ ); -#endif - unsigned char *realData = data-1; - switch (realData[0]) - { - case 0: - #ifdef _THREADSAFE_BYTE_POOL - mutex128.Lock(); - #endif - pool128.Release((unsigned char(*)[128]) realData, file, line ); - #ifdef _THREADSAFE_BYTE_POOL - mutex128.Unlock(); - #endif - break; - case 1: - #ifdef _THREADSAFE_BYTE_POOL - mutex512.Lock(); - #endif - pool512.Release((unsigned char(*)[512]) realData, file, line ); - #ifdef _THREADSAFE_BYTE_POOL - mutex512.Unlock(); - #endif - break; - case 2: - #ifdef _THREADSAFE_BYTE_POOL - mutex2048.Lock(); - #endif - pool2048.Release((unsigned char(*)[2048]) realData, file, line ); - #ifdef _THREADSAFE_BYTE_POOL - mutex2048.Unlock(); - #endif - break; - case 3: - #ifdef _THREADSAFE_BYTE_POOL - mutex8192.Lock(); - #endif - pool8192.Release((unsigned char(*)[8192]) realData, file, line ); - #ifdef _THREADSAFE_BYTE_POOL - mutex8192.Unlock(); - #endif - break; - case 255: - rakFree_Ex(realData, file, line ); - break; - default: - RakAssert(0); - break; - } -} -void BytePool::Clear(const char *file, unsigned int line) -{ - (void) file; - (void) line; - -#ifdef _THREADSAFE_BYTE_POOL - pool128.Clear(file, line); - pool512.Clear(file, line); - pool2048.Clear(file, line); - pool8192.Clear(file, line); -#endif -} diff --git a/vendors/mafianet/Source/src/DS_ByteQueue.cpp b/vendors/mafianet/Source/src/DS_ByteQueue.cpp deleted file mode 100644 index 656803b61..000000000 --- a/vendors/mafianet/Source/src/DS_ByteQueue.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/DS_ByteQueue.h" -#include // Memmove -#include // realloc -#include - - -using namespace DataStructures; - -ByteQueue::ByteQueue() -{ - readOffset=writeOffset=lengthAllocated=0; - data=0; -} -ByteQueue::~ByteQueue() -{ - Clear(_FILE_AND_LINE_); - - -} -void ByteQueue::WriteBytes(const char *in, unsigned length, const char *file, unsigned int line) -{ - unsigned bytesWritten; - bytesWritten=GetBytesWritten(); - if (lengthAllocated==0 || length > lengthAllocated-bytesWritten-1) - { - unsigned oldLengthAllocated=lengthAllocated; - // Always need to waste 1 byte for the math to work, else writeoffset==readoffset - unsigned newAmountToAllocate=length+oldLengthAllocated+1; - if (newAmountToAllocate<256) - newAmountToAllocate=256; - lengthAllocated=lengthAllocated + newAmountToAllocate; - data=(char*)rakRealloc_Ex(data, lengthAllocated, file, line); - if (writeOffset < readOffset) - { - if (writeOffset <= newAmountToAllocate) - { - memcpy(data + oldLengthAllocated, data, writeOffset); - writeOffset=readOffset+bytesWritten; - } - else - { - memcpy(data + oldLengthAllocated, data, newAmountToAllocate); - memmove(data, data+newAmountToAllocate, writeOffset-newAmountToAllocate); - writeOffset-=newAmountToAllocate; - } - } - } - - if (length <= lengthAllocated-writeOffset) - memcpy(data+writeOffset, in, length); - else - { - // Wrap - memcpy(data+writeOffset, in, lengthAllocated-writeOffset); - memcpy(data, in+(lengthAllocated-writeOffset), length-(lengthAllocated-writeOffset)); - } - writeOffset=(writeOffset+length) % lengthAllocated; -} -bool ByteQueue::ReadBytes(char *out, unsigned maxLengthToRead, bool peek) -{ - unsigned bytesWritten = GetBytesWritten(); - unsigned bytesToRead = bytesWritten < maxLengthToRead ? bytesWritten : maxLengthToRead; - if (bytesToRead==0) - return false; - if (writeOffset>=readOffset) - { - memcpy(out, data+readOffset, bytesToRead); - } - else - { - unsigned availableUntilWrap = lengthAllocated-readOffset; - if (bytesToRead <= availableUntilWrap) - { - memcpy(out, data+readOffset, bytesToRead); - } - else - { - memcpy(out, data+readOffset, availableUntilWrap); - memcpy(out+availableUntilWrap, data, bytesToRead-availableUntilWrap); - } - } - - if (peek==false) - IncrementReadOffset(bytesToRead); - - return true; -} -char* ByteQueue::PeekContiguousBytes(unsigned int *outLength) const -{ - if (writeOffset>=readOffset) - *outLength=writeOffset-readOffset; - else - *outLength=lengthAllocated-readOffset; - return data+readOffset; -} -void ByteQueue::Clear(const char *file, unsigned int line) -{ - if (lengthAllocated) - rakFree_Ex(data, file, line ); - readOffset=writeOffset=lengthAllocated=0; - data=0; -} -unsigned ByteQueue::GetBytesWritten(void) const -{ - if (writeOffset>=readOffset) - return writeOffset-readOffset; - else - return writeOffset+(lengthAllocated-readOffset); -} -void ByteQueue::IncrementReadOffset(unsigned length) -{ - readOffset=(readOffset+length) % lengthAllocated; -} -void ByteQueue::DecrementReadOffset(unsigned length) -{ - if (length>readOffset) - readOffset=lengthAllocated-(length-readOffset); - else - readOffset-=length; -} -void ByteQueue::Print(void) -{ - unsigned i; - for (i=readOffset; i!=writeOffset; i++) - RAKNET_DEBUG_PRINTF("%i ", data[i]); - RAKNET_DEBUG_PRINTF("\n"); -} diff --git a/vendors/mafianet/Source/src/DS_HuffmanEncodingTree.cpp b/vendors/mafianet/Source/src/DS_HuffmanEncodingTree.cpp deleted file mode 100644 index 93a87b57a..000000000 --- a/vendors/mafianet/Source/src/DS_HuffmanEncodingTree.cpp +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/DS_HuffmanEncodingTree.h" -#include "mafianet/DS_Queue.h" -#include "mafianet/BitStream.h" -#include "mafianet/assert.h" - -using namespace MafiaNet; - -HuffmanEncodingTree::HuffmanEncodingTree() -{ - root = 0; -} - -HuffmanEncodingTree::~HuffmanEncodingTree() -{ - FreeMemory(); -} - -void HuffmanEncodingTree::FreeMemory( void ) -{ - if ( root == 0 ) - return ; - - // Use an in-order traversal to delete the tree - DataStructures::Queue nodeQueue; - - HuffmanEncodingTreeNode *node; - - nodeQueue.Push( root, _FILE_AND_LINE_ ); - - while ( nodeQueue.Size() > 0 ) - { - node = nodeQueue.Pop(); - - if ( node->left ) - nodeQueue.Push( node->left, _FILE_AND_LINE_ ); - - if ( node->right ) - nodeQueue.Push( node->right, _FILE_AND_LINE_ ); - - MafiaNet::OP_DELETE(node, _FILE_AND_LINE_); - } - - // Delete the encoding table - for ( int i = 0; i < 256; i++ ) - rakFree_Ex(encodingTable[ i ].encoding, _FILE_AND_LINE_ ); - - root = 0; -} - - -////#include - -// Given a frequency table of 256 elements, all with a frequency of 1 or more, generate the tree -void HuffmanEncodingTree::GenerateFromFrequencyTable( unsigned int frequencyTable[ 256 ] ) -{ - int counter; - HuffmanEncodingTreeNode * node; - HuffmanEncodingTreeNode *leafList[ 256 ]; // Keep a copy of the pointers to all the leaves so we can generate the encryption table bottom-up, which is easier - // 1. Make 256 trees each with a weight equal to the frequency of the corresponding character - DataStructures::LinkedList huffmanEncodingTreeNodeList; - - FreeMemory(); - - for ( counter = 0; counter < 256; counter++ ) - { - node = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - node->left = 0; - node->right = 0; - node->value = (unsigned char) counter; - node->weight = frequencyTable[ counter ]; - - if ( node->weight == 0 ) - node->weight = 1; // 0 weights are illegal - - leafList[ counter ] = node; // Used later to generate the encryption table - - InsertNodeIntoSortedList( node, &huffmanEncodingTreeNodeList ); // Insert and maintain sort order. - } - - - // 2. While there is more than one tree, take the two smallest trees and merge them so that the two trees are the left and right - // children of a new node, where the new node has the weight the sum of the weight of the left and right child nodes. - for(;;) - { - huffmanEncodingTreeNodeList.Beginning(); - HuffmanEncodingTreeNode *lesser, *greater; - lesser = huffmanEncodingTreeNodeList.Pop(); - greater = huffmanEncodingTreeNodeList.Pop(); - node = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - node->left = lesser; - node->right = greater; - node->weight = lesser->weight + greater->weight; - lesser->parent = node; // This is done to make generating the encryption table easier - greater->parent = node; // This is done to make generating the encryption table easier - - if ( huffmanEncodingTreeNodeList.Size() == 0 ) - { - // 3. Assign the one remaining node in the list to the root node. - root = node; - root->parent = 0; - break; - } - - // Put the new node back into the list at the correct spot to maintain the sort. Linear search time - InsertNodeIntoSortedList( node, &huffmanEncodingTreeNodeList ); - } - - bool tempPath[ 256 ]; // Maximum path length is 256 - unsigned short tempPathLength; - HuffmanEncodingTreeNode *currentNode; - MafiaNet::BitStream bitStream; - - // Generate the encryption table. From before, we have an array of pointers to all the leaves which contain pointers to their parents. - // This can be done more efficiently but this isn't bad and it's way easier to program and debug - - for ( counter = 0; counter < 256; counter++ ) - { - // Already done at the end of the loop and before it! - tempPathLength = 0; - - // Set the current node at the leaf - currentNode = leafList[ counter ]; - - do - { - if ( currentNode->parent->left == currentNode ) // We're storing the paths in reverse order.since we are going from the leaf to the root - tempPath[ tempPathLength++ ] = false; - else - tempPath[ tempPathLength++ ] = true; - - currentNode = currentNode->parent; - } - - while ( currentNode != root ); - - // Write to the bitstream in the reverse order that we stored the path, which gives us the correct order from the root to the leaf - while ( tempPathLength-- > 0 ) - { - if ( tempPath[ tempPathLength ] ) // Write 1's and 0's because writing a bool will write the BitStream TYPE_CHECKING validation bits if that is defined along with the actual data bit, which is not what we want - bitStream.Write1(); - else - bitStream.Write0(); - } - - // Read data from the bitstream, which is written to the encoding table in bits and bitlength. Note this function allocates the encodingTable[counter].encoding pointer - encodingTable[ counter ].bitLength = ( unsigned char ) bitStream.CopyData( &encodingTable[ counter ].encoding ); - - // Reset the bitstream for the next iteration - bitStream.Reset(); - } -} - -// Pass an array of bytes to array and a preallocated BitStream to receive the output -void HuffmanEncodingTree::EncodeArray( unsigned char *input, size_t sizeInBytes, MafiaNet::BitStream * output ) -{ - unsigned counter; - - // For each input byte, Write out the corresponding series of 1's and 0's that give the encoded representation - for ( counter = 0; counter < sizeInBytes; counter++ ) - { - output->WriteBits( encodingTable[ input[ counter ] ].encoding, encodingTable[ input[ counter ] ].bitLength, false ); // Data is left aligned - } - - // Byte align the output so the unassigned remaining bits don't equate to some actual value - if ( output->GetNumberOfBitsUsed() % 8 != 0 ) - { - // Find an input that is longer than the remaining bits. Write out part of it to pad the output to be byte aligned. - unsigned char remainingBits = (unsigned char) ( 8 - ( output->GetNumberOfBitsUsed() % 8 ) ); - - for ( counter = 0; counter < 256; counter++ ) - if ( encodingTable[ counter ].bitLength > remainingBits ) - { - output->WriteBits( encodingTable[ counter ].encoding, remainingBits, false ); // Data is left aligned - break; - } - -#ifdef _DEBUG - RakAssert( counter != 256 ); // Given 256 elements, we should always be able to find an input that would be >= 7 bits - -#endif - - } -} - -unsigned HuffmanEncodingTree::DecodeArray(MafiaNet::BitStream * input, BitSize_t sizeInBits, size_t maxCharsToWrite, unsigned char *output ) -{ - HuffmanEncodingTreeNode * currentNode; - - unsigned outputWriteIndex; - outputWriteIndex = 0; - currentNode = root; - - // For each bit, go left if it is a 0 and right if it is a 1. When we reach a leaf, that gives us the desired value and we restart from the root - - for ( unsigned counter = 0; counter < sizeInBits; counter++ ) - { - if ( input->ReadBit() == false ) // left! - currentNode = currentNode->left; - else - currentNode = currentNode->right; - - if ( currentNode->left == 0 && currentNode->right == 0 ) // Leaf - { - - if ( outputWriteIndex < maxCharsToWrite ) - output[ outputWriteIndex ] = currentNode->value; - - outputWriteIndex++; - - currentNode = root; - } - } - - return outputWriteIndex; -} - -// Pass an array of encoded bytes to array and a preallocated BitStream to receive the output -void HuffmanEncodingTree::DecodeArray( unsigned char *input, BitSize_t sizeInBits, MafiaNet::BitStream * output ) -{ - HuffmanEncodingTreeNode * currentNode; - - if ( sizeInBits <= 0 ) - return ; - - MafiaNet::BitStream bitStream( input, BITS_TO_BYTES(sizeInBits), false ); - - currentNode = root; - - // For each bit, go left if it is a 0 and right if it is a 1. When we reach a leaf, that gives us the desired value and we restart from the root - for ( unsigned counter = 0; counter < sizeInBits; counter++ ) - { - if ( bitStream.ReadBit() == false ) // left! - currentNode = currentNode->left; - else - currentNode = currentNode->right; - - if ( currentNode->left == 0 && currentNode->right == 0 ) // Leaf - { - output->WriteBits( &( currentNode->value ), sizeof( char ) * 8, true ); // Use WriteBits instead of Write(char) because we want to avoid TYPE_CHECKING - currentNode = root; - } - } -} - -// Insertion sort. Slow but easy to write in this case -void HuffmanEncodingTree::InsertNodeIntoSortedList( HuffmanEncodingTreeNode * node, DataStructures::LinkedList *huffmanEncodingTreeNodeList ) const -{ - if ( huffmanEncodingTreeNodeList->Size() == 0 ) - { - huffmanEncodingTreeNodeList->Insert( node ); - return ; - } - - huffmanEncodingTreeNodeList->Beginning(); - - unsigned counter = 0; - for(;;) - { - if ( huffmanEncodingTreeNodeList->Peek()->weight < node->weight ) - ++( *huffmanEncodingTreeNodeList ); - else - { - huffmanEncodingTreeNodeList->Insert( node ); - break; - } - - // Didn't find a spot in the middle - add to the end - if ( ++counter == huffmanEncodingTreeNodeList->Size() ) - { - huffmanEncodingTreeNodeList->End(); - - huffmanEncodingTreeNodeList->Add( node ) - - ; // Add to the end - break; - } - } -} diff --git a/vendors/mafianet/Source/src/DS_Table.cpp b/vendors/mafianet/Source/src/DS_Table.cpp deleted file mode 100644 index ff130ff95..000000000 --- a/vendors/mafianet/Source/src/DS_Table.cpp +++ /dev/null @@ -1,1148 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/DS_Table.h" -#include "mafianet/DS_OrderedList.h" -#include -#include "mafianet/assert.h" -#include "mafianet/assert.h" -#include "mafianet/Itoa.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace DataStructures; - -void ExtendRows(Table::Row* input, int index) -{ - (void) index; - input->cells.Insert(MafiaNet::OP_NEW(_FILE_AND_LINE_), _FILE_AND_LINE_ ); -} -void FreeRow(Table::Row* input, int index) -{ - (void) index; - - unsigned i; - for (i=0; i < input->cells.Size(); i++) - { - MafiaNet::OP_DELETE(input->cells[i], _FILE_AND_LINE_); - } - MafiaNet::OP_DELETE(input, _FILE_AND_LINE_); -} -Table::Cell::Cell() -{ - isEmpty=true; - c=0; - ptr=0; - i=0.0; -} -Table::Cell::~Cell() -{ - Clear(); -} -Table::Cell& Table::Cell::operator = ( const Table::Cell& input ) -{ - isEmpty=input.isEmpty; - i=input.i; - ptr=input.ptr; - if (c) - rakFree_Ex(c, _FILE_AND_LINE_); - if (input.c) - { - c = (char*) rakMalloc_Ex( (int) i, _FILE_AND_LINE_ ); - memcpy(c, input.c, (int) i); - } - else - c=0; - return *this; -} -Table::Cell::Cell( const Table::Cell & input) -{ - isEmpty=input.isEmpty; - i=input.i; - ptr=input.ptr; - if (input.c) - { - if (c) - rakFree_Ex(c, _FILE_AND_LINE_); - c = (char*) rakMalloc_Ex( (int) i, _FILE_AND_LINE_ ); - memcpy(c, input.c, (int) i); - } -} -void Table::Cell::Set(double input) -{ - Clear(); - i=input; - c=0; - ptr=0; - isEmpty=false; -} -void Table::Cell::Set(unsigned int input) -{ - Set((int) input); -} -void Table::Cell::Set(int input) -{ - Clear(); - i=(double) input; - c=0; - ptr=0; - isEmpty=false; -} - -void Table::Cell::Set(const char *input) -{ - Clear(); - - if (input) - { - i=(int)strlen(input)+1; - c = (char*) rakMalloc_Ex( (int) i, _FILE_AND_LINE_ ); - strcpy_s(c, (int) i, input); - } - else - { - c=0; - i=0; - } - ptr=0; - isEmpty=false; -} -void Table::Cell::Set(const char *input, int inputLength) -{ - Clear(); - if (input) - { - c = (char*) rakMalloc_Ex( inputLength, _FILE_AND_LINE_ ); - i=inputLength; - memcpy(c, input, inputLength); - } - else - { - c=0; - i=0; - } - ptr=0; - isEmpty=false; -} -void Table::Cell::SetPtr(void* p) -{ - Clear(); - c=0; - ptr=p; - isEmpty=false; -} -void Table::Cell::Get(int *output) -{ - RakAssert(isEmpty==false); - int o = (int) i; - *output=o; -} -void Table::Cell::Get(double *output) -{ - RakAssert(isEmpty==false); - *output=i; -} -void Table::Cell::Get(char *output) -{ - RakAssert(isEmpty == false); -#pragma warning(push) -#pragma warning(disable:4996) - strcpy(output, c); -#pragma warning(pop) -} -void Table::Cell::Get(char *output, size_t outputLength) -{ - RakAssert(isEmpty==false); - strcpy_s(output, outputLength, c); -} -void Table::Cell::Get(char *output, int *outputLength) -{ - RakAssert(isEmpty==false); - memcpy(output, c, (int) i); - if (outputLength) - *outputLength=(int) i; -} -MafiaNet::RakString Table::Cell::ToString(ColumnType columnType) -{ - if (isEmpty) - return MafiaNet::RakString(); - - if (columnType==NUMERIC) - { - return MafiaNet::RakString("%f", i); - } - else if (columnType==STRING) - { - return MafiaNet::RakString(c); - } - else if (columnType==BINARY) - { - return MafiaNet::RakString(""); - } - else if (columnType==POINTER) - { - return MafiaNet::RakString("%p", ptr); - } - - return MafiaNet::RakString(); -} -Table::Cell::Cell(double numericValue, char *charValue, void *ptr, ColumnType type) -{ - SetByType(numericValue,charValue,ptr,type); -} -void Table::Cell::SetByType(double numericValue, char *charValue, void *inPtr, ColumnType type) -{ - isEmpty=true; - if (type==NUMERIC) - { - Set(numericValue); - } - else if (type==STRING) - { - Set(charValue); - } - else if (type==BINARY) - { - Set(charValue, (int) numericValue); - } - else if (type==POINTER) - { - SetPtr(inPtr); - } - else - { - inPtr=(void*) charValue; - } -} -Table::ColumnType Table::Cell::EstimateColumnType(void) const -{ - if (c) - { - if (i!=0.0f) - return BINARY; - else - return STRING; - } - - if (ptr) - return POINTER; - return NUMERIC; -} -void Table::Cell::Clear(void) -{ - if (isEmpty==false && c) - { - rakFree_Ex(c, _FILE_AND_LINE_); - c=0; - } - isEmpty=true; -} -Table::ColumnDescriptor::ColumnDescriptor() -{ - -} -Table::ColumnDescriptor::~ColumnDescriptor() -{ - -} -Table::ColumnDescriptor::ColumnDescriptor(const char cn[_TABLE_MAX_COLUMN_NAME_LENGTH], ColumnType ct) -{ - columnType=ct; - strcpy_s(columnName, cn); -} -void Table::Row::UpdateCell(unsigned columnIndex, double value) -{ - cells[columnIndex]->Clear(); - cells[columnIndex]->Set(value); - -// cells[columnIndex]->i=value; -// cells[columnIndex]->c=0; -// cells[columnIndex]->isEmpty=false; -} -void Table::Row::UpdateCell(unsigned columnIndex, const char *str) -{ - cells[columnIndex]->Clear(); - cells[columnIndex]->Set(str); -} -void Table::Row::UpdateCell(unsigned columnIndex, int byteLength, const char *data) -{ - cells[columnIndex]->Clear(); - cells[columnIndex]->Set(data,byteLength); -} -Table::Table() -{ -} -Table::~Table() -{ - Clear(); -} -unsigned Table::AddColumn(const char columnName[_TABLE_MAX_COLUMN_NAME_LENGTH], ColumnType columnType) -{ - if (columnName[0]==0) - return (unsigned) -1; - - // Add this column. - columns.Insert(Table::ColumnDescriptor(columnName, columnType), _FILE_AND_LINE_); - - // Extend the rows by one - rows.ForEachData(ExtendRows); - - return columns.Size()-1; -} -void Table::RemoveColumn(unsigned columnIndex) -{ - if (columnIndex >= columns.Size()) - return; - - columns.RemoveAtIndex(columnIndex); - - // Remove this index from each row. - int i; - DataStructures::Page *cur = rows.GetListHead(); - while (cur) - { - for (i=0; i < cur->size; i++) - { - MafiaNet::OP_DELETE(cur->data[i]->cells[columnIndex], _FILE_AND_LINE_); - cur->data[i]->cells.RemoveAtIndex(columnIndex); - } - - cur=cur->next; - } -} -unsigned Table::ColumnIndex(const char *columnName) const -{ - unsigned columnIndex; - for (columnIndex=0; columnIndex= columns.Size()) - return 0; - else - return (char*)columns[index].columnName; -} -Table::ColumnType Table::GetColumnType(unsigned index) const -{ - if (index >= columns.Size()) - return (Table::ColumnType) 0; - else - return columns[index].columnType; -} -unsigned Table::GetColumnCount(void) const -{ - return columns.Size(); -} -unsigned Table::GetRowCount(void) const -{ - return rows.Size(); -} -Table::Row* Table::AddRow(unsigned rowId) -{ - Row *newRow; - newRow = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - if (rows.Insert(rowId, newRow)==false) - { - MafiaNet::OP_DELETE(newRow, _FILE_AND_LINE_); - return 0; // Already exists - } - unsigned rowIndex; - for (rowIndex=0; rowIndex < columns.Size(); rowIndex++) - newRow->cells.Insert(MafiaNet::OP_NEW(_FILE_AND_LINE_), _FILE_AND_LINE_ ); - return newRow; -} -Table::Row* Table::AddRow(unsigned rowId, DataStructures::List &initialCellValues) -{ - Row *newRow = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - unsigned rowIndex; - for (rowIndex=0; rowIndex < columns.Size(); rowIndex++) - { - if (rowIndex < initialCellValues.Size() && initialCellValues[rowIndex].isEmpty==false) - { - Table::Cell *c; - c = MafiaNet::OP_NEW(_FILE_AND_LINE_); - c->SetByType(initialCellValues[rowIndex].i,initialCellValues[rowIndex].c,initialCellValues[rowIndex].ptr,columns[rowIndex].columnType); - newRow->cells.Insert(c, _FILE_AND_LINE_ ); - } - else - newRow->cells.Insert(MafiaNet::OP_NEW(_FILE_AND_LINE_), _FILE_AND_LINE_ ); - } - rows.Insert(rowId, newRow); - return newRow; -} -Table::Row* Table::AddRow(unsigned rowId, DataStructures::List &initialCellValues, bool copyCells) -{ - Row *newRow = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - unsigned rowIndex; - for (rowIndex=0; rowIndex < columns.Size(); rowIndex++) - { - if (rowIndex < initialCellValues.Size() && initialCellValues[rowIndex] && initialCellValues[rowIndex]->isEmpty==false) - { - if (copyCells==false) - newRow->cells.Insert(MafiaNet::OP_NEW_4( _FILE_AND_LINE_, initialCellValues[rowIndex]->i, initialCellValues[rowIndex]->c, initialCellValues[rowIndex]->ptr, columns[rowIndex].columnType), _FILE_AND_LINE_); - else - { - Table::Cell *c = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - newRow->cells.Insert(c, _FILE_AND_LINE_); - *c=*(initialCellValues[rowIndex]); - } - } - else - newRow->cells.Insert(MafiaNet::OP_NEW(_FILE_AND_LINE_), _FILE_AND_LINE_); - } - rows.Insert(rowId, newRow); - return newRow; -} -Table::Row* Table::AddRowColumns(unsigned rowId, Row *row, DataStructures::List columnIndices) -{ - Row *newRow = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - unsigned columnIndex; - for (columnIndex=0; columnIndex < columnIndices.Size(); columnIndex++) - { - if (row->cells[columnIndices[columnIndex]]->isEmpty==false) - { - newRow->cells.Insert(MafiaNet::OP_NEW_4( _FILE_AND_LINE_, - row->cells[columnIndices[columnIndex]]->i, - row->cells[columnIndices[columnIndex]]->c, - row->cells[columnIndices[columnIndex]]->ptr, - columns[columnIndex].columnType - ), _FILE_AND_LINE_); - } - else - { - newRow->cells.Insert(MafiaNet::OP_NEW(_FILE_AND_LINE_), _FILE_AND_LINE_); - } - } - rows.Insert(rowId, newRow); - return newRow; -} -bool Table::RemoveRow(unsigned rowId) -{ - Row *out; - if (rows.Delete(rowId, out)) - { - DeleteRow(out); - return true; - } - return false; -} -void Table::RemoveRows(Table *tableContainingRowIDs) -{ - unsigned i; - DataStructures::Page *cur = tableContainingRowIDs->GetRows().GetListHead(); - while (cur) - { - for (i=0; i < (unsigned)cur->size; i++) - { - rows.Delete(cur->keys[i]); - } - cur=cur->next; - } - return; -} -bool Table::UpdateCell(unsigned rowId, unsigned columnIndex, int value) -{ - RakAssert(columns[columnIndex].columnType==NUMERIC); - - Row *row = GetRowByID(rowId); - if (row) - { - row->UpdateCell(columnIndex, value); - return true; - } - return false; -} -bool Table::UpdateCell(unsigned rowId, unsigned columnIndex, char *str) -{ - RakAssert(columns[columnIndex].columnType==STRING); - - Row *row = GetRowByID(rowId); - if (row) - { - row->UpdateCell(columnIndex, str); - return true; - } - return false; -} -bool Table::UpdateCell(unsigned rowId, unsigned columnIndex, int byteLength, char *data) -{ - RakAssert(columns[columnIndex].columnType==BINARY); - - Row *row = GetRowByID(rowId); - if (row) - { - row->UpdateCell(columnIndex, byteLength, data); - return true; - } - return false; -} -bool Table::UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, int value) -{ - RakAssert(columns[columnIndex].columnType==NUMERIC); - - Row *row = GetRowByIndex(rowIndex,0); - if (row) - { - row->UpdateCell(columnIndex, value); - return true; - } - return false; -} -bool Table::UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, char *str) -{ - RakAssert(columns[columnIndex].columnType==STRING); - - Row *row = GetRowByIndex(rowIndex,0); - if (row) - { - row->UpdateCell(columnIndex, str); - return true; - } - return false; -} -bool Table::UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, int byteLength, char *data) -{ - RakAssert(columns[columnIndex].columnType==BINARY); - - Row *row = GetRowByIndex(rowIndex,0); - if (row) - { - row->UpdateCell(columnIndex, byteLength, data); - return true; - } - return false; -} -void Table::GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, int *output) -{ - RakAssert(columns[columnIndex].columnType==NUMERIC); - - Row *row = GetRowByIndex(rowIndex,0); - if (row) - { - row->cells[columnIndex]->Get(output); - } -} -void Table::GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, char *output) -{ - RakAssert(columns[columnIndex].columnType == STRING); - - Row *row = GetRowByIndex(rowIndex, 0); - if (row) - { - row->cells[columnIndex]->Get(output); - } -} -void Table::GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, char *output, size_t outputLength) -{ - RakAssert(columns[columnIndex].columnType==STRING); - - Row *row = GetRowByIndex(rowIndex,0); - if (row) - { - row->cells[columnIndex]->Get(output, outputLength); - } -} -void Table::GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, char *output, int *outputLength) -{ - RakAssert(columns[columnIndex].columnType==BINARY); - - Row *row = GetRowByIndex(rowIndex,0); - if (row) - { - row->cells[columnIndex]->Get(output, outputLength); - } -} -Table::FilterQuery::FilterQuery() -{ - columnName[0]=0; -} -Table::FilterQuery::~FilterQuery() -{ - -} -Table::FilterQuery::FilterQuery(unsigned column, Cell *cell, FilterQueryType op) -{ - columnIndex=column; - cellValue=cell; - operation=op; -} -Table::Row* Table::GetRowByID(unsigned rowId) const -{ - Row *row; - if (rows.Get(rowId, row)) - return row; - return 0; -} - -Table::Row* Table::GetRowByIndex(unsigned rowIndex, unsigned *key) const -{ - DataStructures::Page *cur = rows.GetListHead(); - while (cur) - { - if (rowIndex < (unsigned)cur->size) - { - if (key) - *key=cur->keys[rowIndex]; - return cur->data[rowIndex]; - } - if (rowIndex <= (unsigned)cur->size) - rowIndex-=cur->size; - else - return 0; - cur=cur->next; - } - return 0; -} - -void Table::QueryTable(unsigned *columnIndicesSubset, unsigned numColumnSubset, FilterQuery *inclusionFilters, unsigned numInclusionFilters, unsigned *rowIds, unsigned numRowIDs, Table *result) -{ - unsigned i; - DataStructures::List columnIndicesToReturn; - - // Clear the result table. - result->Clear(); - - if (columnIndicesSubset && numColumnSubset>0) - { - for (i=0; i < numColumnSubset; i++) - { - if (columnIndicesSubset[i]AddColumn(columns[columnIndicesToReturn[i]].columnName,columns[columnIndicesToReturn[i]].columnType); - } - - // Get the column indices of the filter queries. - DataStructures::List inclusionFilterColumnIndices; - if (inclusionFilters && numInclusionFilters>0) - { - for (i=0; i < numInclusionFilters; i++) - { - if (inclusionFilters[i].columnName[0]) - inclusionFilters[i].columnIndex=ColumnIndex(inclusionFilters[i].columnName); - if (inclusionFilters[i].columnIndex *cur = rows.GetListHead(); - while (cur) - { - for (i=0; i < (unsigned)cur->size; i++) - { - QueryRow(inclusionFilterColumnIndices, columnIndicesToReturn, cur->keys[i], cur->data[i], inclusionFilters, result); - } - cur=cur->next; - } - } - else - { - // Specific rows - Row *row; - for (i=0; i < numRowIDs; i++) - { - if (rows.Get(rowIds[i], row)) - { - QueryRow(inclusionFilterColumnIndices, columnIndicesToReturn, rowIds[i], row, inclusionFilters, result); - } - } - } -} - -void Table::QueryRow(DataStructures::List &inclusionFilterColumnIndices, DataStructures::List &columnIndicesToReturn, unsigned key, Table::Row* row, FilterQuery *inclusionFilters, Table *result) -{ - bool pass=false; - unsigned columnIndex; - unsigned j; - - // If no inclusion filters, just add the row - if (inclusionFilterColumnIndices.Size()==0) - { - result->AddRowColumns(key, row, columnIndicesToReturn); - } - else - { - // Go through all inclusion filters. Only add this row if all filters pass. - for (j=0; jcells[columnIndex]->isEmpty==false ) - { - if (columns[inclusionFilterColumnIndices[j]].columnType==STRING && - (row->cells[columnIndex]->c==0 || - inclusionFilters[j].cellValue->c==0) ) - continue; - - switch (inclusionFilters[j].operation) - { - case QF_EQUAL: - switch(columns[inclusionFilterColumnIndices[j]].columnType) - { - case NUMERIC: - pass=row->cells[columnIndex]->i==inclusionFilters[j].cellValue->i; - break; - case STRING: - pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)==0; - break; - case BINARY: - pass=row->cells[columnIndex]->i==inclusionFilters[j].cellValue->i && - memcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c, (int) row->cells[columnIndex]->i)==0; - break; - case POINTER: - pass=row->cells[columnIndex]->ptr==inclusionFilters[j].cellValue->ptr; - break; - } - break; - case QF_NOT_EQUAL: - switch(columns[inclusionFilterColumnIndices[j]].columnType) - { - case NUMERIC: - pass=row->cells[columnIndex]->i!=inclusionFilters[j].cellValue->i; - break; - case STRING: - pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)!=0; - break; - case BINARY: - pass=row->cells[columnIndex]->i==inclusionFilters[j].cellValue->i && - memcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c, (int) row->cells[columnIndex]->i)==0; - break; - case POINTER: - pass=row->cells[columnIndex]->ptr!=inclusionFilters[j].cellValue->ptr; - break; - } - break; - case QF_GREATER_THAN: - switch(columns[inclusionFilterColumnIndices[j]].columnType) - { - case NUMERIC: - pass=row->cells[columnIndex]->i>inclusionFilters[j].cellValue->i; - break; - case STRING: - pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)>0; - break; - case BINARY: - break; - case POINTER: - pass=row->cells[columnIndex]->ptr>inclusionFilters[j].cellValue->ptr; - break; - } - break; - case QF_GREATER_THAN_EQ: - switch(columns[inclusionFilterColumnIndices[j]].columnType) - { - case NUMERIC: - pass=row->cells[columnIndex]->i>=inclusionFilters[j].cellValue->i; - break; - case STRING: - pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)>=0; - break; - case BINARY: - break; - case POINTER: - pass=row->cells[columnIndex]->ptr>=inclusionFilters[j].cellValue->ptr; - break; - } - break; - case QF_LESS_THAN: - switch(columns[inclusionFilterColumnIndices[j]].columnType) - { - case NUMERIC: - pass=row->cells[columnIndex]->ii; - break; - case STRING: - pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)<0; - break; - case BINARY: - break; - case POINTER: - pass=row->cells[columnIndex]->ptrptr; - break; - } - break; - case QF_LESS_THAN_EQ: - switch(columns[inclusionFilterColumnIndices[j]].columnType) - { - case NUMERIC: - pass=row->cells[columnIndex]->i<=inclusionFilters[j].cellValue->i; - break; - case STRING: - pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)<=0; - break; - case BINARY: - break; - case POINTER: - pass=row->cells[columnIndex]->ptr<=inclusionFilters[j].cellValue->ptr; - break; - } - break; - case QF_IS_EMPTY: - pass=false; - break; - case QF_NOT_EMPTY: - pass=true; - break; - default: - pass=false; - RakAssert(0); - break; - } - } - else - { - if (inclusionFilters[j].operation==QF_IS_EMPTY) - pass=true; - else - pass=false; // No value for this cell - } - - if (pass==false) - break; - } - - if (pass) - { - result->AddRowColumns(key, row, columnIndicesToReturn); - } - } -} - -static Table::SortQuery *_sortQueries; -static unsigned _numSortQueries; -static DataStructures::List *_columnIndices; -static DataStructures::List *_columns; -int RowSort(Table::Row* const &first, Table::Row* const &second) // first is the one inserting, second is the one already there. -{ - unsigned i, columnIndex; - for (i=0; i<_numSortQueries; i++) - { - columnIndex=(*_columnIndices)[i]; - if (columnIndex==(unsigned)-1) - continue; - - if (first->cells[columnIndex]->isEmpty==true && second->cells[columnIndex]->isEmpty==false) - return 1; // Empty cells always go at the end - - if (first->cells[columnIndex]->isEmpty==false && second->cells[columnIndex]->isEmpty==true) - return -1; // Empty cells always go at the end - - if (_sortQueries[i].operation==Table::QS_INCREASING_ORDER) - { - if ((*_columns)[columnIndex].columnType==Table::NUMERIC) - { - if (first->cells[columnIndex]->i>second->cells[columnIndex]->i) - return 1; - if (first->cells[columnIndex]->icells[columnIndex]->i) - return -1; - } - else - { - // String - if (strcmp(first->cells[columnIndex]->c,second->cells[columnIndex]->c)>0) - return 1; - if (strcmp(first->cells[columnIndex]->c,second->cells[columnIndex]->c)<0) - return -1; - } - } - else - { - if ((*_columns)[columnIndex].columnType==Table::NUMERIC) - { - if (first->cells[columnIndex]->icells[columnIndex]->i) - return 1; - if (first->cells[columnIndex]->i>second->cells[columnIndex]->i) - return -1; - } - else - { - // String - if (strcmp(first->cells[columnIndex]->c,second->cells[columnIndex]->c)<0) - return 1; - if (strcmp(first->cells[columnIndex]->c,second->cells[columnIndex]->c)>0) - return -1; - } - } - } - - return 0; -} -void Table::SortTable(Table::SortQuery *sortQueries, unsigned numSortQueries, Table::Row** out) -{ - unsigned i; - unsigned outLength; - DataStructures::List columnIndices; - _sortQueries=sortQueries; - _numSortQueries=numSortQueries; - _columnIndices=&columnIndices; - _columns=&columns; - bool anyValid=false; - - for (i=0; i < numSortQueries; i++) - { - if (sortQueries[i].columnIndex *cur; - cur = rows.GetListHead(); - if (anyValid==false) - { - outLength=0; - while (cur) - { - for (i=0; i < (unsigned)cur->size; i++) - { - out[(outLength)++]=cur->data[i]; - } - cur=cur->next; - } - return; - } - - // Start adding to ordered list. - DataStructures::OrderedList orderedList; - while (cur) - { - for (i=0; i < (unsigned)cur->size; i++) - { - RakAssert(cur->data[i]); - orderedList.Insert(cur->data[i],cur->data[i], true, _FILE_AND_LINE_); - } - cur=cur->next; - } - - outLength=0; - for (i=0; i < orderedList.Size(); i++) - out[(outLength)++]=orderedList[i]; -} -void Table::PrintColumnHeaders(char *out, int outLength, char columnDelineator) const -{ - if (outLength<=0) - return; - if (outLength==1) - { - *out=0; - return; - } - - unsigned i; - out[0]=0; - int len; - for (i=0; i < columns.Size(); i++) - { - if (i!=0) - { - len = (int) strlen(out); - if (len < outLength-1) - sprintf_s(out+len, outLength-len, "%c", columnDelineator); - else - return; - } - - len = (int) strlen(out); - if (len < outLength-(int) strlen(columns[i].columnName)) - sprintf_s(out+len, outLength-len, "%s", columns[i].columnName); - else - return; - } -} -void Table::PrintRow(char *out, int outLength, char columnDelineator, bool printDelineatorForBinary, Table::Row* inputRow) const -{ - if (outLength<=0) - return; - if (outLength==1) - { - *out=0; - return; - } - - if (inputRow->cells.Size()!=columns.Size()) - { - strncpy_s(out, outLength, "Cell width does not match column width.\n", outLength); - out[outLength-1]=0; - return; - } - - char buff[512]; - unsigned i; - int len; - out[0]=0; - for (i=0; i < columns.Size(); i++) - { - if (columns[i].columnType==NUMERIC) - { - if (inputRow->cells[i]->isEmpty==false) - { - sprintf_s(buff, "%f", inputRow->cells[i]->i); - len=(int)strlen(buff); - } - else - len=0; - if (i+1!=columns.Size()) - buff[len++]=columnDelineator; - buff[len]=0; - } - else if (columns[i].columnType==STRING) - { - if (inputRow->cells[i]->isEmpty==false && inputRow->cells[i]->c) - { - strncpy_s(buff, inputRow->cells[i]->c, 512-2); - buff[512-2]=0; - len=(int)strlen(buff); - } - else - len=0; - if (i+1!=columns.Size()) - buff[len++]=columnDelineator; - buff[len]=0; - } - else if (columns[i].columnType==POINTER) - { - if (inputRow->cells[i]->isEmpty==false && inputRow->cells[i]->ptr) - { - sprintf_s(buff, "%p", inputRow->cells[i]->ptr); - len=(int)strlen(buff); - } - else - len=0; - if (i+1!=columns.Size()) - buff[len++]=columnDelineator; - buff[len]=0; - } - else - { - if (printDelineatorForBinary) - { - if (i+1!=columns.Size()) - buff[0]=columnDelineator; - buff[1]=0; - } - else - buff[0]=0; - - } - - len=(int)strlen(out); - if (outLength==len+1) - break; - strncpy_s(out+len, outLength-len, buff, outLength-len); - out[outLength-1]=0; - } -} - -void Table::Clear(void) -{ - rows.ForEachData(FreeRow); - rows.Clear(); - columns.Clear(true, _FILE_AND_LINE_); -} -const List& Table::GetColumns(void) const -{ - return columns; -} -const DataStructures::BPlusTree& Table::GetRows(void) const -{ - return rows; -} -DataStructures::Page * Table::GetListHead(void) -{ - return rows.GetListHead(); -} -unsigned Table::GetAvailableRowId(void) const -{ - bool setKey=false; - unsigned key=0; - int i; - DataStructures::Page *cur = rows.GetListHead(); - - while (cur) - { - for (i=0; i < cur->size; i++) - { - if (setKey==false) - { - key=cur->keys[i]+1; - setKey=true; - } - else - { - if (key!=cur->keys[i]) - return key; - key++; - } - } - - cur=cur->next; - } - return key; -} -void Table::DeleteRow(Table::Row *row) -{ - unsigned rowIndex; - for (rowIndex=0; rowIndex < row->cells.Size(); rowIndex++) - { - MafiaNet::OP_DELETE(row->cells[rowIndex], _FILE_AND_LINE_); - } - MafiaNet::OP_DELETE(row, _FILE_AND_LINE_); -} -Table& Table::operator = ( const Table& input ) -{ - Clear(); - - unsigned int i; - for (i=0; i < input.GetColumnCount(); i++) - AddColumn(input.ColumnName(i), input.GetColumnType(i)); - - DataStructures::Page *cur = input.GetRows().GetListHead(); - while (cur) - { - for (i=0; i < (unsigned int) cur->size; i++) - { - AddRow(cur->keys[i], cur->data[i]->cells, false); - } - - cur=cur->next; - } - - return *this; -} diff --git a/vendors/mafianet/Source/src/DataCompressor.cpp b/vendors/mafianet/Source/src/DataCompressor.cpp deleted file mode 100644 index 913f5b20f..000000000 --- a/vendors/mafianet/Source/src/DataCompressor.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/DataCompressor.h" -#include "mafianet/DS_HuffmanEncodingTree.h" -#include "mafianet/assert.h" -#include // Use string.h rather than memory.h for a console - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(DataCompressor,DataCompressor) - -void DataCompressor::Compress( unsigned char *userData, unsigned sizeInBytes, MafiaNet::BitStream * output ) -{ - // Don't use this for small files as you will just make them bigger! - RakAssert(sizeInBytes > 2048); - - unsigned int frequencyTable[ 256 ]; - unsigned int i; - memset(frequencyTable,0,256*sizeof(unsigned int)); - for (i=0; i < sizeInBytes; i++) - ++frequencyTable[userData[i]]; - HuffmanEncodingTree tree; - BitSize_t writeOffset1, writeOffset2, bitsUsed1, bitsUsed2; - tree.GenerateFromFrequencyTable(frequencyTable); - output->WriteCompressed(sizeInBytes); - for (i=0; i < 256; i++) - output->WriteCompressed(frequencyTable[i]); - output->AlignWriteToByteBoundary(); - writeOffset1=output->GetWriteOffset(); - output->Write((unsigned int)0); // Dummy value - bitsUsed1=output->GetNumberOfBitsUsed(); - tree.EncodeArray(userData, sizeInBytes, output); - bitsUsed2=output->GetNumberOfBitsUsed(); - writeOffset2=output->GetWriteOffset(); - output->SetWriteOffset(writeOffset1); - output->Write(bitsUsed2-bitsUsed1); // Go back and write how many bits were used for the encoding - output->SetWriteOffset(writeOffset2); -} - -unsigned DataCompressor::DecompressAndAllocate(MafiaNet::BitStream * input, unsigned char **output ) -{ - HuffmanEncodingTree tree; - unsigned int bitsUsed, destinationSizeInBytes; - unsigned int decompressedBytes; - unsigned int frequencyTable[ 256 ]; - unsigned i; - - input->ReadCompressed(destinationSizeInBytes); - for (i=0; i < 256; i++) - input->ReadCompressed(frequencyTable[i]); - input->AlignReadToByteBoundary(); - if (input->Read(bitsUsed)==false) - { - // Read error -#ifdef _DEBUG - RakAssert(0); -#endif - return 0; - } - *output = (unsigned char*) rakMalloc_Ex(destinationSizeInBytes, _FILE_AND_LINE_); - tree.GenerateFromFrequencyTable(frequencyTable); - decompressedBytes=tree.DecodeArray(input, bitsUsed, destinationSizeInBytes, *output ); - RakAssert(decompressedBytes==destinationSizeInBytes); - return destinationSizeInBytes; -} diff --git a/vendors/mafianet/Source/src/DirectoryDeltaTransfer.cpp b/vendors/mafianet/Source/src/DirectoryDeltaTransfer.cpp deleted file mode 100644 index ab38fe921..000000000 --- a/vendors/mafianet/Source/src/DirectoryDeltaTransfer.cpp +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_DirectoryDeltaTransfer==1 && _RAKNET_SUPPORT_FileOperations==1 - -#include "mafianet/DirectoryDeltaTransfer.h" -#include "mafianet/FileList.h" -#include "mafianet/StringCompressor.h" -#include "mafianet/peerinterface.h" -#include "mafianet/FileListTransfer.h" -#include "mafianet/FileListTransferCBInterface.h" -#include "mafianet/BitStream.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/FileOperations.h" -#include "mafianet/IncrementalReadInterface.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace MafiaNet; - -class DDTCallback : public FileListTransferCBInterface -{ -public: - unsigned subdirLen; - char outputSubdir[512]; - FileListTransferCBInterface *onFileCallback; - - DDTCallback() {} - virtual ~DDTCallback() {} - - virtual bool OnFile(OnFileStruct *onFileStruct) - { - char fullPathToDir[1024]; - - if (onFileStruct->fileData && subdirLen < strlen(onFileStruct->fileName)) - { - strcpy_s(fullPathToDir, outputSubdir); - strcat_s(fullPathToDir, onFileStruct->fileName+subdirLen); - WriteFileWithDirectories(fullPathToDir, (char*)onFileStruct->fileData, (unsigned int ) onFileStruct->byteLengthOfThisFile); - } - else - fullPathToDir[0]=0; - - return onFileCallback->OnFile(onFileStruct); - } - - virtual void OnFileProgress(FileProgressStruct *fps) - { - char fullPathToDir[1024]; - - if (subdirLen < strlen(fps->onFileStruct->fileName)) - { - strcpy_s(fullPathToDir, outputSubdir); - strcat_s(fullPathToDir, fps->onFileStruct->fileName+subdirLen); - } - else - fullPathToDir[0]=0; - - onFileCallback->OnFileProgress(fps); - } - virtual bool OnDownloadComplete(DownloadCompleteStruct *dcs) - { - return onFileCallback->OnDownloadComplete(dcs); - } -}; - -STATIC_FACTORY_DEFINITIONS(DirectoryDeltaTransfer,DirectoryDeltaTransfer); - -DirectoryDeltaTransfer::DirectoryDeltaTransfer() -{ - applicationDirectory[0]=0; - fileListTransfer=0; - availableUploads = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - priority=MafiaNet::Priority::High; - orderingChannel=0; - incrementalReadInterface=0; -} -DirectoryDeltaTransfer::~DirectoryDeltaTransfer() -{ - MafiaNet::OP_DELETE(availableUploads, _FILE_AND_LINE_); -} -void DirectoryDeltaTransfer::SetFileListTransferPlugin(FileListTransfer *flt) -{ - if (fileListTransfer) - { - DataStructures::List fileListProgressList; - fileListTransfer->GetCallbacks(fileListProgressList); - unsigned int i; - for (i=0; i < fileListProgressList.Size(); i++) - availableUploads->RemoveCallback(fileListProgressList[i]); - } - - fileListTransfer=flt; - - if (flt) - { - DataStructures::List fileListProgressList; - flt->GetCallbacks(fileListProgressList); - unsigned int i; - for (i=0; i < fileListProgressList.Size(); i++) - availableUploads->AddCallback(fileListProgressList[i]); - } - else - { - availableUploads->ClearCallbacks(); - } -} -void DirectoryDeltaTransfer::SetApplicationDirectory(const char *pathToApplication) -{ - if (pathToApplication==0 || pathToApplication[0]==0) - applicationDirectory[0]=0; - else - { - strncpy_s(applicationDirectory, pathToApplication, 510); - if (applicationDirectory[strlen(applicationDirectory)-1]!='/' && applicationDirectory[strlen(applicationDirectory)-1]!='\\') - strcat_s(applicationDirectory, "/"); - applicationDirectory[511]=0; - } -} -void DirectoryDeltaTransfer::SetUploadSendParameters(MafiaNet::Priority _priority, char _orderingChannel) -{ - priority=_priority; - orderingChannel=_orderingChannel; -} -void DirectoryDeltaTransfer::AddFile(const char* filePath, const char* fileName) -{ - availableUploads->AddFile(filePath, fileName, FileListNodeContext(0, 0, 0, 0)); -} -void DirectoryDeltaTransfer::AddUploadsFromSubdirectory(const char *subdir) -{ - availableUploads->AddFilesFromDirectory(applicationDirectory, subdir, true, false, true, FileListNodeContext(0,0,0,0)); -} -unsigned short DirectoryDeltaTransfer::DownloadFromSubdirectory(FileList &localFiles, const char *subdir, const char *outputSubdir, bool prependAppDirToOutputSubdir, SystemAddress host, FileListTransferCBInterface *onFileCallback, MafiaNet::Priority _priority, char _orderingChannel, FileListProgress *cb) -{ - RakAssert(host!=UNASSIGNED_SYSTEM_ADDRESS); - - DDTCallback *transferCallback; - - localFiles.AddCallback(cb); - - // Prepare the callback data - transferCallback = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - if (subdir && subdir[0]) - { - transferCallback->subdirLen=(unsigned int)strlen(subdir); - if (subdir[transferCallback->subdirLen-1]!='/' && subdir[transferCallback->subdirLen-1]!='\\') - transferCallback->subdirLen++; - } - else - transferCallback->subdirLen=0; - if (prependAppDirToOutputSubdir) - strcpy_s(transferCallback->outputSubdir, applicationDirectory); - else - transferCallback->outputSubdir[0]=0; - if (outputSubdir) - strcat_s(transferCallback->outputSubdir, outputSubdir); - if (transferCallback->outputSubdir[strlen(transferCallback->outputSubdir)-1]!='/' && transferCallback->outputSubdir[strlen(transferCallback->outputSubdir)-1]!='\\') - strcat_s(transferCallback->outputSubdir, "/"); - transferCallback->onFileCallback=onFileCallback; - - // Setup the transfer plugin to get the response to this download request - unsigned short setId = fileListTransfer->SetupReceive(transferCallback, true, host); - - // Send to the host, telling it to process this request - MafiaNet::BitStream outBitstream; - outBitstream.Write((MessageID)ID_DDT_DOWNLOAD_REQUEST); - outBitstream.Write(setId); - StringCompressor::Instance()->EncodeString(subdir, 256, &outBitstream); - StringCompressor::Instance()->EncodeString(outputSubdir, 256, &outBitstream); - localFiles.Serialize(&outBitstream); - SendUnified(&outBitstream, _priority, MafiaNet::Reliability::ReliableOrdered, _orderingChannel, host, false); - - return setId; -} -unsigned short DirectoryDeltaTransfer::DownloadFromSubdirectory(const char *subdir, const char *outputSubdir, bool prependAppDirToOutputSubdir, SystemAddress host, FileListTransferCBInterface *onFileCallback, MafiaNet::Priority _priority, char _orderingChannel, FileListProgress *cb) -{ - FileList localFiles; - // Get a hash of all the files that we already have (if any) - localFiles.AddFilesFromDirectory(prependAppDirToOutputSubdir ? applicationDirectory : 0, outputSubdir, true, false, true, FileListNodeContext(0,0,0,0)); - return DownloadFromSubdirectory(localFiles, subdir, outputSubdir, prependAppDirToOutputSubdir, host, onFileCallback, _priority, _orderingChannel, cb); -} -void DirectoryDeltaTransfer::GenerateHashes(FileList &localFiles, const char *outputSubdir, bool prependAppDirToOutputSubdir) -{ - localFiles.AddFilesFromDirectory(prependAppDirToOutputSubdir ? applicationDirectory : 0, outputSubdir, true, false, true, FileListNodeContext(0,0,0,0)); -} -void DirectoryDeltaTransfer::ClearUploads(void) -{ - availableUploads->Clear(); -} -void DirectoryDeltaTransfer::OnDownloadRequest(Packet *packet) -{ - char subdir[256]; - char remoteSubdir[256]; - MafiaNet::BitStream inBitstream(packet->data, packet->length, false); - FileList remoteFileHash; - FileList delta; - unsigned short setId; - inBitstream.IgnoreBits(8); - inBitstream.Read(setId); - StringCompressor::Instance()->DecodeString(subdir, 256, &inBitstream); - StringCompressor::Instance()->DecodeString(remoteSubdir, 256, &inBitstream); - if (remoteFileHash.Deserialize(&inBitstream)==false) - { -#ifdef _DEBUG - RakAssert(0); -#endif - return; - } - - availableUploads->GetDeltaToCurrent(&remoteFileHash, &delta, subdir, remoteSubdir); - if (incrementalReadInterface==0) - delta.PopulateDataFromDisk(applicationDirectory, true, false, true); - else - delta.FlagFilesAsReferences(); - - // This will call the ddtCallback interface that was passed to FileListTransfer::SetupReceive on the remote system - fileListTransfer->Send(&delta, rakPeerInterface, packet->systemAddress, setId, priority, orderingChannel, incrementalReadInterface, chunkSize); -} -PluginReceiveResult DirectoryDeltaTransfer::OnReceive(Packet *packet) -{ - switch (packet->data[0]) - { - case ID_DDT_DOWNLOAD_REQUEST: - OnDownloadRequest(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - - return RR_CONTINUE_PROCESSING; -} - -unsigned DirectoryDeltaTransfer::GetNumberOfFilesForUpload(void) const -{ - return availableUploads->fileList.Size(); -} - -void DirectoryDeltaTransfer::SetDownloadRequestIncrementalReadInterface(IncrementalReadInterface *_incrementalReadInterface, unsigned int _chunkSize) -{ - incrementalReadInterface=_incrementalReadInterface; - chunkSize=_chunkSize; -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/DynDNS.cpp b/vendors/mafianet/Source/src/DynDNS.cpp deleted file mode 100644 index c5383eef1..000000000 --- a/vendors/mafianet/Source/src/DynDNS.cpp +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_DynDNS==1 && _RAKNET_SUPPORT_TCPInterface==1 - -#include "mafianet/TCPInterface.h" -#include "mafianet/socket2.h" -#include "mafianet/DynDNS.h" -#include "mafianet/GetTime.h" -#include "mafianet/Base64Encoder.h" - -using namespace MafiaNet; - -struct DynDnsResult -{ - const char *description; - const char *code; - DynDnsResultCode resultCode; -}; - -DynDnsResult resultTable[13] = -{ - // See http://www.dyndns.com/developers/specs/flow.pdf - {"DNS update success.\nPlease wait up to 60 seconds for the change to take effect.\n", "good", RC_SUCCESS}, // Even with success, it takes time for the cache to update! - {"No change", "nochg", RC_NO_CHANGE}, - {"Host has been blocked. You will need to contact DynDNS to reenable.", "abuse", RC_ABUSE}, - {"Useragent is blocked", "badagent", RC_BAD_AGENT}, - {"Username/password pair bad", "badauth", RC_BAD_AUTH}, - {"Bad system parameter", "badsys", RC_BAD_SYS}, - {"DNS inconsistency", "dnserr", RC_DNS_ERROR}, - {"Paid account feature", "!donator", RC_NOT_DONATOR}, - {"No such host in system", "nohost", RC_NO_HOST}, - {"Invalid hostname format", "notfqdn", RC_NOT_FQDN}, - {"Serious error", "numhost", RC_NUM_HOST}, - {"This host exists, but does not belong to you", "!yours", RC_NOT_YOURS}, - {"911", "911", RC_911} -}; -DynDNS::DynDNS() -{ - connectPhase=CP_IDLE; - tcp=0; -} -DynDNS::~DynDNS() -{ - if (tcp) - MafiaNet::OP_DELETE(tcp, _FILE_AND_LINE_); -} -void DynDNS::Stop(void) -{ - tcp->Stop(); - connectPhase = CP_IDLE; - MafiaNet::OP_DELETE(tcp, _FILE_AND_LINE_); - tcp=0; -} - - -// newIPAddress is optional - if left out, DynDNS will use whatever it receives -void DynDNS::UpdateHostIPAsynch(const char *dnsHost, const char *newIPAddress, const char *usernameAndPassword ) -{ - myIPStr[0]=0; - - if (tcp==0) - tcp = MafiaNet::OP_NEW(_FILE_AND_LINE_); - connectPhase = CP_IDLE; - host = dnsHost; - - if (tcp->Start(0, 1)==false) - { - SetCompleted(RC_TCP_FAILED_TO_START, "TCP failed to start"); - return; - } - - connectPhase = CP_CONNECTING_TO_CHECKIP; - tcp->Connect("checkip.dyndns.org", 80, false); - - // See https://www.dyndns.com/developers/specs/syntax.html - getString="GET /nic/update?hostname="; - getString+=dnsHost; - if (newIPAddress) - { - getString+="&myip="; - getString+=newIPAddress; - } - getString+="&wildcard=NOCHG&mx=NOCHG&backmx=NOCHG HTTP/1.0\n"; - getString+="Host: members.dyndns.org\n"; - getString+="Authorization: Basic "; - char outputData[512]; - Base64Encoding((const unsigned char*) usernameAndPassword, (int) strlen(usernameAndPassword), outputData); - getString+=outputData; - getString+="User-Agent: Jenkins Software LLC - PC - 1.0\n\n"; -} -void DynDNS::Update(void) -{ - if (connectPhase==CP_IDLE) - return; - - serverAddress=tcp->HasFailedConnectionAttempt(); - if (serverAddress!=UNASSIGNED_SYSTEM_ADDRESS) - { - SetCompleted(RC_TCP_DID_NOT_CONNECT, "Could not connect to DynDNS"); - return; - } - - serverAddress=tcp->HasCompletedConnectionAttempt(); - if (serverAddress!=UNASSIGNED_SYSTEM_ADDRESS) - { - if (connectPhase == CP_CONNECTING_TO_CHECKIP) - { - checkIpAddress=serverAddress; - connectPhase = CP_WAITING_FOR_CHECKIP_RESPONSE; - tcp->Send("GET\n\n", (unsigned int) strlen("GET\n\n"), serverAddress, false); // Needs 2 newlines! This is not documented and wasted a lot of my time - } - else - { - connectPhase = CP_WAITING_FOR_DYNDNS_RESPONSE; - tcp->Send(getString.C_String(), (unsigned int) getString.GetLength(), serverAddress, false); - } - phaseTimeout= MafiaNet::GetTime()+1000; - } - - if (connectPhase==CP_WAITING_FOR_CHECKIP_RESPONSE && MafiaNet::GetTime()>phaseTimeout) - { - connectPhase = CP_CONNECTING_TO_DYNDNS; - tcp->CloseConnection(checkIpAddress); - tcp->Connect("members.dyndns.org", 80, false); - } - else if (connectPhase==CP_WAITING_FOR_DYNDNS_RESPONSE && MafiaNet::GetTime()>phaseTimeout) - { - SetCompleted(RC_DYNDNS_TIMEOUT, "DynDNS did not respond"); - return; - } - - Packet *packet = tcp->Receive(); - if (packet) - { - if (connectPhase==CP_WAITING_FOR_DYNDNS_RESPONSE) - { - unsigned int i; - - char *curResult; - curResult=strstr((char*) packet->data, "Connection: close"); - if (curResult!=0) - { - curResult+=strlen("Connection: close"); - while (*curResult && ((*curResult=='\r') || (*curResult=='\n') || (*curResult==' ')) ) - curResult++; - for (i=0; i < 13; i++) - { - if (strncmp(resultTable[i].code, curResult, strlen(resultTable[i].code))==0) - { - if (resultTable[i].resultCode==RC_SUCCESS) - { - // Read my external IP into myIPStr - // Advance until we hit a number - while (*curResult && ((*curResult<'0') || (*curResult>'9')) ) - curResult++; - if (*curResult) - { - SystemAddress parser; - parser.FromString(curResult); - parser.ToString(false, myIPStr, static_cast(32)); - } - } - tcp->DeallocatePacket(packet); - SetCompleted(resultTable[i].resultCode, resultTable[i].description); - break; - } - } - if (i==13) - { - tcp->DeallocatePacket(packet); - SetCompleted(RC_UNKNOWN_RESULT, "DynDNS returned unknown result"); - } - } - else - { - tcp->DeallocatePacket(packet); - SetCompleted(RC_PARSING_FAILURE, "Parsing failure on returned string from DynDNS"); - } - - return; - } - else - { - /* - HTTP/1.1 200 OK - Content-Type: text/html - Server: DynDNS-CheckIP/1.0 - Connection: close - Cache-Control: no-cache - Pragma: no-cache - Content-Length: 105 - - Current IP CheckCurrent IP Address: 98.1 - 89.219.22 - - - Connection to host lost. - */ - - char *curResult; - curResult=strstr((char*) packet->data, "Current IP Address: "); - if (curResult!=0) - { - curResult+=strlen("Current IP Address: "); - SystemAddress myIp; - myIp.FromString(curResult); - myIp.ToString(false, myIPStr, static_cast(32)); - - char existingHost[65]; - existingHost[0]=0; - // Resolve DNS we are setting. If equal to current then abort - RakNetSocket2::DomainNameToIP(host.C_String(), existingHost); - if (strcmp(existingHost, myIPStr)==0) - { - // DynDNS considers setting the IP to what it is already set abuse - tcp->DeallocatePacket(packet); - SetCompleted(RC_DNS_ALREADY_SET, "No action needed"); - return; - } - } - - tcp->DeallocatePacket(packet); - tcp->CloseConnection(packet->systemAddress); - - connectPhase = CP_CONNECTING_TO_DYNDNS; - tcp->Connect("members.dyndns.org", 80, false); - } - } - - if (tcp->HasLostConnection()!=UNASSIGNED_SYSTEM_ADDRESS) - { - if (connectPhase==CP_WAITING_FOR_DYNDNS_RESPONSE) - { - SetCompleted(RC_CONNECTION_LOST_WITHOUT_RESPONSE, "Connection lost to DynDNS during GET operation"); - } - } -} - - -#endif // _RAKNET_SUPPORT_DynDNS diff --git a/vendors/mafianet/Source/src/EmailSender.cpp b/vendors/mafianet/Source/src/EmailSender.cpp deleted file mode 100644 index c4649157b..000000000 --- a/vendors/mafianet/Source/src/EmailSender.cpp +++ /dev/null @@ -1,378 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_EmailSender==1 && _RAKNET_SUPPORT_TCPInterface==1 && _RAKNET_SUPPORT_FileOperations==1 - -// Useful sites -// http://www.faqs.org\rfcs\rfc2821.html -// http://www2.rad.com\networks/1995/mime/examples.htm - -#include "mafianet/EmailSender.h" -#include "mafianet/TCPInterface.h" -#include "mafianet/GetTime.h" -#include "mafianet/Rand.h" -#include "mafianet/FileList.h" -#include "mafianet/BitStream.h" -#include "mafianet/Base64Encoder.h" -#include -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - - - - - -#include "mafianet/sleep.h" - -using namespace MafiaNet; - - -STATIC_FACTORY_DEFINITIONS(EmailSender,EmailSender); - -const char *EmailSender::Send(const char *hostAddress, unsigned short hostPort, const char *sender, const char *recipient, const char *senderName, const char *recipientName, const char *subject, const char *body, FileList *attachedFiles, bool doPrintf, const char *password) -{ - MafiaNet::Packet *packet; - char query[1024]; - TCPInterface tcpInterface; - SystemAddress emailServer; - if (tcpInterface.Start(0, 0)==false) - return "Unknown error starting TCP"; - emailServer=tcpInterface.Connect(hostAddress, hostPort,true); - if (emailServer==UNASSIGNED_SYSTEM_ADDRESS) - return "Failed to connect to host"; -#if OPEN_SSL_CLIENT_SUPPORT==1 - tcpInterface.StartSSLClient(emailServer); -#endif - MafiaNet::TimeMS timeoutTime = MafiaNet::GetTimeMS()+3000; - packet=0; - while (MafiaNet::GetTimeMS() < timeoutTime) - { - packet = tcpInterface.Receive(); - if (packet) - { - if (doPrintf) - { - RAKNET_DEBUG_PRINTF("%s", packet->data); - tcpInterface.DeallocatePacket(packet); - } - break; - } - RakSleep(250); - } - - if (packet==0) - return "Timeout while waiting for initial data from server."; - - tcpInterface.Send("EHLO\r\n", 6, emailServer,false); - const char *response; - bool authenticate=false; - for(;;) - { - response=GetResponse(&tcpInterface, emailServer, doPrintf); - - if (response!=0 && strcmp(response, "AUTHENTICATE")==0) - { - authenticate=true; - break; - } - - // Something other than continue? - if (response!=0 && strcmp(response, "CONTINUE")!=0) - return response; - - // Success? - if (response==0) - break; - } - - if (authenticate) - { - sprintf_s(query, "EHLO %s\r\n", sender); - tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); - response=GetResponse(&tcpInterface, emailServer, doPrintf); - if (response!=0) - return response; - if (password==0) - return "Password needed"; - char *outputData = MafiaNet::OP_NEW_ARRAY((const int) (strlen(sender)+strlen(password)+2)*3, _FILE_AND_LINE_ ); - MafiaNet::BitStream bs; - char zero=0; - bs.Write(&zero,1); - bs.Write(sender,(const unsigned int)strlen(sender)); - //bs.Write("jms1@jms1.net",(const unsigned int)strlen("jms1@jms1.net")); - bs.Write(&zero,1); - bs.Write(password,(const unsigned int)strlen(password)); - bs.Write(&zero,1); - //bs.Write("not.my.real.password",(const unsigned int)strlen("not.my.real.password")); - Base64Encoding((const unsigned char*)bs.GetData(), bs.GetNumberOfBytesUsed(), outputData); - sprintf_s(query, "AUTH PLAIN %s", outputData); - tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); - response=GetResponse(&tcpInterface, emailServer, doPrintf); - if (response!=0) - return response; - } - - - if (sender) - sprintf_s(query, "MAIL From: <%s>\r\n", sender); - else - sprintf_s(query, "MAIL From: <>\r\n"); - tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); - response=GetResponse(&tcpInterface, emailServer, doPrintf); - if (response!=0) - return response; - - if (recipient) - sprintf_s(query, "RCPT TO: <%s>\r\n", recipient); - else - sprintf_s(query, "RCPT TO: <>\r\n"); - tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); - response=GetResponse(&tcpInterface, emailServer, doPrintf); - if (response!=0) - return response; - - tcpInterface.Send("DATA\r\n", (unsigned int)strlen("DATA\r\n"), emailServer,false); - - // Wait for 354... - - response=GetResponse(&tcpInterface, emailServer, doPrintf); - if (response!=0) - return response; - - if (subject) - { - sprintf_s(query, "Subject: %s\r\n", subject); - tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); - } - if (senderName) - { - sprintf_s(query, "From: %s\r\n", senderName); - tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); - } - if (recipientName) - { - sprintf_s(query, "To: %s\r\n", recipientName); - tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); - } - - const int boundarySize=60; - char boundary[boundarySize+1]; - int i,j; - if (attachedFiles && attachedFiles->fileList.Size()) - { - rakNetRandom.SeedMT((unsigned int)MafiaNet::GetTimeMS()); - // Random multipart message boundary - for (i=0; i < boundarySize; i++) - boundary[i]=Base64Map()[rakNetRandom.RandomMT()%64]; - boundary[boundarySize]=0; - } - - sprintf_s(query, "MIME-version: 1.0\r\n"); - tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); - - if (attachedFiles && attachedFiles->fileList.Size()) - { - sprintf_s(query, "Content-type: multipart/mixed; BOUNDARY=\"%s\"\r\n\r\n", boundary); - tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); - - sprintf_s(query, "This is a multi-part message in MIME format.\r\n\r\n--%s\r\n", boundary); - tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); - } - - sprintf_s(query, "Content-Type: text/plain; charset=\"US-ASCII\"\r\n\r\n"); - tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); - - // Write the body of the email, doing some lame shitty shit where I have to make periods at the start of a newline have a second period. - char *newBody; - int bodyLength; - bodyLength=(int)strlen(body); - newBody = (char*) rakMalloc_Ex( bodyLength*3, _FILE_AND_LINE_ ); - if (bodyLength>=0) - newBody[0]=body[0]; - for (i=1, j=1; i < bodyLength; i++) - { - // Transform \n . \r \n into \n . . \r \n - if (i < bodyLength-2 && - body[i-1]=='\n' && - body[i+0]=='.' && - body[i+1]=='\r' && - body[i+2]=='\n') - { - newBody[j++]='.'; - newBody[j++]='.'; - newBody[j++]='\r'; - newBody[j++]='\n'; - i+=2; - } - // Transform \n . . \r \n into \n . . . \r \n - // Having to process .. is a bug in the mail server - the spec says ONLY \r\n.\r\n should be transformed - else if (i <= bodyLength-3 && - body[i-1]=='\n' && - body[i+0]=='.' && - body[i+1]=='.' && - body[i+2]=='\r' && - body[i+3]=='\n') - { - newBody[j++]='.'; - newBody[j++]='.'; - newBody[j++]='.'; - newBody[j++]='\r'; - newBody[j++]='\n'; - i+=3; - } - // Transform \n . \n into \n . . \r \n (this is a bug in the mail server - the spec says do not count \n alone but it does) - else if (i < bodyLength-1 && - body[i-1]=='\n' && - body[i+0]=='.' && - body[i+1]=='\n') - { - newBody[j++]='.'; - newBody[j++]='.'; - newBody[j++]='\r'; - newBody[j++]='\n'; - i+=1; - } - // Transform \n . . \n into \n . . . \r \n (this is a bug in the mail server - the spec says do not count \n alone but it does) - // In fact having to process .. is a bug too - because the spec says ONLY \r\n.\r\n should be transformed - else if (i <= bodyLength-2 && - body[i-1]=='\n' && - body[i+0]=='.' && - body[i+1]=='.' && - body[i+2]=='\n') - { - newBody[j++]='.'; - newBody[j++]='.'; - newBody[j++]='.'; - newBody[j++]='\r'; - newBody[j++]='\n'; - i+=2; - } - else - newBody[j++]=body[i]; - } - - newBody[j++]='\r'; - newBody[j++]='\n'; - tcpInterface.Send(newBody, j, emailServer,false); - - rakFree_Ex(newBody, _FILE_AND_LINE_ ); - int outputOffset; - - // What a pain in the rear. I have to map the binary to printable characters using 6 bits per character. - if (attachedFiles && attachedFiles->fileList.Size()) - { - for (i=0; i < (int) attachedFiles->fileList.Size(); i++) - { - // Write boundary - sprintf_s(query, "\r\n--%s\r\n", boundary); - tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); - - sprintf_s(query, "Content-Type: APPLICATION/Octet-Stream; SizeOnDisk=%i; name=\"%s\"\r\nContent-Transfer-Encoding: BASE64\r\nContent-Description: %s\r\n\r\n", attachedFiles->fileList[i].dataLengthBytes, attachedFiles->fileList[i].filename.C_String(), attachedFiles->fileList[i].filename.C_String()); - tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); - - newBody = (char*) rakMalloc_Ex( (size_t) (attachedFiles->fileList[i].dataLengthBytes*3)/2, _FILE_AND_LINE_ ); - - outputOffset=Base64Encoding((const unsigned char*) attachedFiles->fileList[i].data, (int) attachedFiles->fileList[i].dataLengthBytes, newBody); - - // Send the base64 mapped file. - tcpInterface.Send(newBody, outputOffset, emailServer,false); - rakFree_Ex(newBody, _FILE_AND_LINE_ ); - - } - - // Write last boundary - sprintf_s(query, "\r\n--%s--\r\n", boundary); - tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); - } - - - sprintf_s(query, "\r\n.\r\n"); - tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); - response=GetResponse(&tcpInterface, emailServer, doPrintf); - if (response!=0) - return response; - - tcpInterface.Send("QUIT\r\n", (unsigned int)strlen("QUIT\r\n"), emailServer,false); - - RakSleep(30); - if (doPrintf) - { - packet = tcpInterface.Receive(); - while (packet) - { - RAKNET_DEBUG_PRINTF("%s", packet->data); - tcpInterface.DeallocatePacket(packet); - packet = tcpInterface.Receive(); - } - } - tcpInterface.Stop(); - return 0; // Success -} - -const char *EmailSender::GetResponse(TCPInterface *tcpInterface, const SystemAddress &emailServer, bool doPrintf) -{ - MafiaNet::Packet *packet; - MafiaNet::TimeMS timeout; - timeout= MafiaNet::GetTimeMS()+5000; - for(;;) - { - if (tcpInterface->HasLostConnection()==emailServer) - return "Connection to server lost."; - packet = tcpInterface->Receive(); - if (packet) - { - if (doPrintf) - { - RAKNET_DEBUG_PRINTF("%s", packet->data); - } -#if OPEN_SSL_CLIENT_SUPPORT==1 - if (strstr((const char*)packet->data, "220")) - { - tcpInterface->StartSSLClient(packet->systemAddress); - return "AUTHENTICATE"; // OK - } -// if (strstr((const char*)packet->data, "250-AUTH LOGIN PLAIN")) -// { -// tcpInterface->StartSSLClient(packet->systemAddress); -// return "AUTHENTICATE"; // OK -// } -#endif - if (strstr((const char*)packet->data, "235")) - return 0; // Authentication accepted - if (strstr((const char*)packet->data, "354")) - return 0; // Go ahead -#if OPEN_SSL_CLIENT_SUPPORT==1 - if (strstr((const char*)packet->data, "250-STARTTLS")) - { - tcpInterface->Send("STARTTLS\r\n", (unsigned int) strlen("STARTTLS\r\n"), packet->systemAddress, false); - return "CONTINUE"; - } -#endif - if (strstr((const char*)packet->data, "250")) - return 0; // OK - if (strstr((const char*)packet->data, "550")) - return "Failed on error code 550"; - if (strstr((const char*)packet->data, "553")) - return "Failed on error code 553"; - } - if (MafiaNet::GetTimeMS() > timeout) - return "Timed out"; - RakSleep(100); - } -} - - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/EpochTimeToString.cpp b/vendors/mafianet/Source/src/EpochTimeToString.cpp deleted file mode 100644 index 3d02e4dc5..000000000 --- a/vendors/mafianet/Source/src/EpochTimeToString.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/FormatString.h" -#include "mafianet/EpochTimeToString.h" -#include -#include -#include -// localtime -#include -#include "mafianet/LinuxStrings.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -char * EpochTimeToString(long long time) -{ - static int textIndex=0; - static char text[4][64]; - - if (++textIndex==4) - textIndex=0; - - struct tm timeinfo; - time_t t = time; - localtime_s ( &timeinfo, &t ); - strftime (text[textIndex],64,"%c.",&timeinfo); - - /* - time_t - // Copied from the docs - struct tm *newtime; - newtime = _localtime64(& time); - asctime_s( text[textIndex], sizeof(text[textIndex]), newtime ); - - while (text[textIndex][0] && (text[textIndex][strlen(text[textIndex])-1]=='\n' || text[textIndex][strlen(text[textIndex])-1]=='\r')) - text[textIndex][strlen(text[textIndex])-1]=0; - */ - - return text[textIndex]; -} diff --git a/vendors/mafianet/Source/src/FileList.cpp b/vendors/mafianet/Source/src/FileList.cpp deleted file mode 100644 index 1ded75734..000000000 --- a/vendors/mafianet/Source/src/FileList.cpp +++ /dev/null @@ -1,834 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/FileList.h" - -#if _RAKNET_SUPPORT_FileOperations==1 - -#include // RAKNET_DEBUG_PRINTF -#include "mafianet/assert.h" -#if defined(ANDROID) -#include -#elif defined(_WIN32) || defined(__CYGWIN__) -#include - - -#elif !defined ( __APPLE__ ) && !defined ( __APPLE_CC__ ) && !defined ( __PPC__ ) && !defined ( __FreeBSD__ ) && !defined ( __S3E__ ) && ( defined(__i386__) || defined(__x86_64__) ) -// only exists for x86/x86_64 glibc (port I/O helpers). It is not -// referenced here, so on other Linux architectures (e.g. aarch64/arm) we omit it. -#include -#endif - - -#ifdef _WIN32 -// For mkdir -#include - - -#else -#include -#endif - -//#include "mafianet/DR_SHA1.h" -#include "mafianet/DS_Queue.h" -#include "mafianet/StringCompressor.h" -#include "mafianet/BitStream.h" -#include "mafianet/FileOperations.h" -#include "mafianet/SuperFastHash.h" -#include "mafianet/assert.h" -#include "mafianet/LinuxStrings.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -#define MAX_FILENAME_LENGTH 512 -static const unsigned HASH_LENGTH=4; - -using namespace MafiaNet; - -// alloca - -#if defined(_WIN32) -#include - - -#else - #if !defined ( __FreeBSD__ ) - #include - #endif -#include -#include -#include -#include "mafianet/_FindFirst.h" -#include //defines intptr_t -#endif - -#include "mafianet/alloca.h" - -//int RAK_DLL_EXPORT FileListNodeComp( char * const &key, const FileListNode &data ) -//{ -// return strcmp(key, data.filename); -//} - - -STATIC_FACTORY_DEFINITIONS(FileListProgress,FileListProgress) -STATIC_FACTORY_DEFINITIONS(FLP_Printf,FLP_Printf) -STATIC_FACTORY_DEFINITIONS(FileList,FileList) - -/// First callback called when FileList::AddFilesFromDirectory() starts -void FLP_Printf::OnAddFilesFromDirectoryStarted(FileList *fileList, char *dir) { - (void) fileList; - RAKNET_DEBUG_PRINTF("Adding files from directory %s\n",dir);} - -/// Called for each directory, when that directory begins processing -void FLP_Printf::OnDirectory(FileList *fileList, char *dir, unsigned int directoriesRemaining) { - (void) fileList; - RAKNET_DEBUG_PRINTF("Adding %s. %i remaining.\n", dir, directoriesRemaining);} -void FLP_Printf::OnFilePushesComplete( SystemAddress systemAddress, unsigned short setID ) -{ - (void) setID; - - char str[32]; - systemAddress.ToString(true, (char*) str, static_cast(32)); - RAKNET_DEBUG_PRINTF("File pushes complete to %s\n", str); -} -void FLP_Printf::OnSendAborted( SystemAddress systemAddress ) -{ - char str[32]; - systemAddress.ToString(true, (char*) str, static_cast(32)); - RAKNET_DEBUG_PRINTF("Send aborted to %s\n", str); -} -FileList::FileList() -{ -} -FileList::~FileList() -{ - Clear(); -} -void FileList::AddFile(const char *filepath, const char *filename, FileListNodeContext context) -{ - if (filepath==0 || filename==0) - return; - - char *data; - //std::fstream file; - //file.open(filename, std::ios::in | std::ios::binary); - - FILE *fp; - if (fopen_s(&fp, filepath, "rb") != 0) - return; - fseek(fp, 0, SEEK_END); - int length = ftell(fp); - fseek(fp, 0, SEEK_SET); - - if (length > (int) ((unsigned int)-1 / 8)) - { - // If this assert hits, split up your file. You could also change BitSize_t in types.h to unsigned long long but this is not recommended for performance reasons - RakAssert("Cannot add files over 536 MB" && 0); - fclose(fp); - return; - } - - -#if USE_ALLOCA==1 - bool usedAlloca=false; - if (length < MAX_ALLOCA_STACK_ALLOCATION) - { - data = ( char* ) alloca( length ); - usedAlloca=true; - } - else -#endif - { - data = (char*) rakMalloc_Ex( length, _FILE_AND_LINE_ ); - RakAssert(data); - } - - fread(data, 1, length, fp); - AddFile(filename, filepath, data, length, length, context); - fclose(fp); - -#if USE_ALLOCA==1 - if (usedAlloca==false) -#endif - rakFree_Ex(data, _FILE_AND_LINE_ ); - -} -void FileList::AddFile(const char *filename, const char *fullPathToFile, const char *data, const unsigned dataLength, const unsigned fileLength, FileListNodeContext context, bool isAReference, bool takeDataPointer) -{ - if (filename==0) - return; - if (strlen(filename)>MAX_FILENAME_LENGTH) - { - // Should be enough for anyone - RakAssert(0); - return; - } - // If adding a reference, do not send data - RakAssert(isAReference==false || data==0); - // Avoid duplicate insertions unless the data is different, in which case overwrite the old data - unsigned i; - for (i=0; i dirList; - char root[260]; - char fullPath[520]; - _finddata_t fileInfo; - intptr_t dir; - FILE *fp; - char *dirSoFar, *fileData; - dirSoFar=(char*) rakMalloc_Ex( 520, _FILE_AND_LINE_ ); - RakAssert(dirSoFar); - - if (applicationDirectory) - strcpy_s(root, applicationDirectory); - else - root[0]=0; - - int rootLen=(int)strlen(root); - if (rootLen) - { - strcpy_s(dirSoFar, 520, root); - if (FixEndingSlash(dirSoFar, 520)) - rootLen++; - } - else - dirSoFar[0]=0; - - if (subDirectory) - { - strcat_s(dirSoFar, 520, subDirectory); - FixEndingSlash(dirSoFar, 520); - } - for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++) - fileListProgressCallbacks[flpcIndex]->OnAddFilesFromDirectoryStarted(this, dirSoFar); - // RAKNET_DEBUG_PRINTF("Adding files from directory %s\n",dirSoFar); - dirList.Push(dirSoFar, _FILE_AND_LINE_ ); - while (dirList.Size()) - { - dirSoFar=dirList.Pop(); - strcpy_s(fullPath, dirSoFar); - // Changed from *.* to * for Linux compatibility - strcat_s(fullPath, "*"); - - - dir=_findfirst(fullPath, &fileInfo ); - if (dir==-1) - { - _findclose(dir); - rakFree_Ex(dirSoFar, _FILE_AND_LINE_ ); - unsigned i; - for (i=0; i < dirList.Size(); i++) - rakFree_Ex(dirList[i], _FILE_AND_LINE_ ); - return; - } - -// RAKNET_DEBUG_PRINTF("Adding %s. %i remaining.\n", fullPath, dirList.Size()); - for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++) - fileListProgressCallbacks[flpcIndex]->OnDirectory(this, fullPath, dirList.Size()); - - do - { - // no guarantee these entries are first... - if (strcmp("." , fileInfo.name) == 0 || - strcmp("..", fileInfo.name) == 0) - { - continue; - } - - if ((fileInfo.attrib & (_A_HIDDEN | _A_SUBDIR | _A_SYSTEM))==0) - { - strcpy_s(fullPath, dirSoFar); - strcat_s(fullPath, fileInfo.name); - fileData=0; - - for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++) - fileListProgressCallbacks[flpcIndex]->OnFile(this, dirSoFar, fileInfo.name, fileInfo.size); - - if (writeData && writeHash) - { - if (fopen_s(&fp, fullPath, "rb") == 0) - { - fileData= (char*) rakMalloc_Ex( fileInfo.size+HASH_LENGTH, _FILE_AND_LINE_ ); - RakAssert(fileData); - fread(fileData+HASH_LENGTH, fileInfo.size, 1, fp); - fclose(fp); - - unsigned int hash = SuperFastHash(fileData+HASH_LENGTH, fileInfo.size); - if (MafiaNet::BitStream::DoEndianSwap()) - MafiaNet::BitStream::ReverseBytesInPlace((unsigned char*) &hash, sizeof(hash)); - memcpy(fileData, &hash, HASH_LENGTH); - - // sha1.Reset(); - // sha1.Update( ( unsigned char* ) fileData+HASH_LENGTH, fileInfo.size ); - // sha1.Final(); - // memcpy(fileData, sha1.GetHash(), HASH_LENGTH); - // File data and hash - AddFile((const char*)fullPath+rootLen, fullPath, fileData, fileInfo.size+HASH_LENGTH, fileInfo.size, context); - } - } - else if (writeHash) - { -// sha1.Reset(); -// DR_SHA1.hashFile((char*)fullPath); -// sha1.Final(); - - unsigned int hash = SuperFastHashFile(fullPath); - if (MafiaNet::BitStream::DoEndianSwap()) - MafiaNet::BitStream::ReverseBytesInPlace((unsigned char*) &hash, sizeof(hash)); - - // Hash only - // AddFile((const char*)fullPath+rootLen, (const char*)sha1.GetHash(), HASH_LENGTH, fileInfo.size, context); - AddFile((const char*)fullPath+rootLen, fullPath, (const char*)&hash, HASH_LENGTH, fileInfo.size, context); - } - else if (writeData) - { - fileData= (char*) rakMalloc_Ex( fileInfo.size, _FILE_AND_LINE_ ); - RakAssert(fileData); - fopen_s(&fp, fullPath, "rb"); - fread(fileData, fileInfo.size, 1, fp); - fclose(fp); - - // File data only - AddFile(fullPath+rootLen, fullPath, fileData, fileInfo.size, fileInfo.size, context); - } - else - { - // Just the filename - AddFile(fullPath+rootLen, fullPath, 0, 0, fileInfo.size, context); - } - - if (fileData) - rakFree_Ex(fileData, _FILE_AND_LINE_ ); - } - else if ((fileInfo.attrib & _A_SUBDIR) && (fileInfo.attrib & (_A_HIDDEN | _A_SYSTEM))==0 && recursive) - { - char *newDir=(char*) rakMalloc_Ex( 520, _FILE_AND_LINE_ ); - RakAssert(newDir); - strcpy_s(newDir, 520, dirSoFar); - strcat_s(newDir, 520, fileInfo.name); - strcat_s(newDir, 520, "/"); - dirList.Push(newDir, _FILE_AND_LINE_ ); - } - - } while (_findnext(dir, &fileInfo ) != -1); - - _findclose(dir); - rakFree_Ex(dirSoFar, _FILE_AND_LINE_ ); - } - -} -void FileList::Clear(void) -{ - unsigned i; - for (i=0; iWriteCompressed(fileList.Size()); - unsigned i; - for (i=0; i < fileList.Size(); i++) - { - outBitStream->WriteCompressed(fileList[i].context.op); - outBitStream->WriteCompressed(fileList[i].context.flnc_extraData1); - outBitStream->WriteCompressed(fileList[i].context.flnc_extraData2); - StringCompressor::Instance()->EncodeString(fileList[i].filename.C_String(), MAX_FILENAME_LENGTH, outBitStream); - - bool writeFileData = (fileList[i].dataLengthBytes>0)==true; - outBitStream->Write(writeFileData); - if (writeFileData) - { - outBitStream->WriteCompressed(fileList[i].dataLengthBytes); - outBitStream->Write(fileList[i].data, fileList[i].dataLengthBytes); - } - - outBitStream->Write((bool)(fileList[i].fileLengthBytes==fileList[i].dataLengthBytes)); - if (fileList[i].fileLengthBytes!=fileList[i].dataLengthBytes) - outBitStream->WriteCompressed(fileList[i].fileLengthBytes); - } -} -bool FileList::Deserialize(MafiaNet::BitStream *inBitStream) -{ - bool b, dataLenNonZero=false, fileLenMatchesDataLen=false; - char filename[512]; - uint32_t fileListSize; - FileListNode n; - b=inBitStream->ReadCompressed(fileListSize); -#ifdef _DEBUG - RakAssert(b); - RakAssert(fileListSize < 10000); -#endif - if (b==false || fileListSize > 10000) - return false; // Sanity check - Clear(); - unsigned i; - for (i=0; i < fileListSize; i++) - { - inBitStream->ReadCompressed(n.context.op); - inBitStream->ReadCompressed(n.context.flnc_extraData1); - inBitStream->ReadCompressed(n.context.flnc_extraData2); - StringCompressor::Instance()->DecodeString((char*)filename, MAX_FILENAME_LENGTH, inBitStream); - inBitStream->Read(dataLenNonZero); - if (dataLenNonZero) - { - inBitStream->ReadCompressed(n.dataLengthBytes); - // sanity check - if (n.dataLengthBytes>2000000000) - { -#ifdef _DEBUG - RakAssert(n.dataLengthBytes<=2000000000); -#endif - return false; - } - n.data=(char*) rakMalloc_Ex( (size_t) n.dataLengthBytes, _FILE_AND_LINE_ ); - RakAssert(n.data); - inBitStream->Read(n.data, n.dataLengthBytes); - } - else - { - n.dataLengthBytes=0; - n.data=0; - } - - b=inBitStream->Read(fileLenMatchesDataLen); - if (fileLenMatchesDataLen) - n.fileLengthBytes=(unsigned) n.dataLengthBytes; - else - b=inBitStream->ReadCompressed(n.fileLengthBytes); -#ifdef _DEBUG - RakAssert(b); -#endif - if (b==0) - { - Clear(); - return false; - } - n.filename=filename; - n.fullPathToFile=filename; - fileList.Insert(n, _FILE_AND_LINE_); - } - - return true; -} -void FileList::GetDeltaToCurrent(FileList *input, FileList *output, const char *dirSubset, const char *remoteSubdir) -{ - // For all files in this list that do not match the input list, write them to the output list. - // dirSubset allows checking only a portion of the files in this list. - unsigned thisIndex, inputIndex; - unsigned dirSubsetLen, localPathLen, remoteSubdirLen; - bool match; - if (dirSubset) - dirSubsetLen = (unsigned int) strlen(dirSubset); - else - dirSubsetLen = 0; - if (remoteSubdir && remoteSubdir[0]) - { - remoteSubdirLen=(unsigned int) strlen(remoteSubdir); - if (IsSlash(remoteSubdir[remoteSubdirLen-1])) - remoteSubdirLen--; - } - else - remoteSubdirLen=0; - - for (thisIndex=0; thisIndex < fileList.Size(); thisIndex++) - { - localPathLen = (unsigned int) fileList[thisIndex].filename.GetLength(); - while (localPathLen>0) - { - if (IsSlash(fileList[thisIndex].filename[localPathLen-1])) - { - localPathLen--; - break; - } - localPathLen--; - } - - // fileList[thisIndex].filename has to match dirSubset and be shorter or equal to it in length. - if (dirSubsetLen>0 && - (localPathLendirSubsetLen && IsSlash(fileList[thisIndex].filename[dirSubsetLen])==false))) - continue; - - match=false; - for (inputIndex=0; inputIndex < input->fileList.Size(); inputIndex++) - { - // If the filenames, hashes, and lengths match then skip this element in fileList. Otherwise write it to output - if (_stricmp(input->fileList[inputIndex].filename.C_String()+remoteSubdirLen,fileList[thisIndex].filename.C_String()+dirSubsetLen)==0) - { - match=true; - if (input->fileList[inputIndex].fileLengthBytes==fileList[thisIndex].fileLengthBytes && - input->fileList[inputIndex].dataLengthBytes==fileList[thisIndex].dataLengthBytes && - memcmp(input->fileList[inputIndex].data,fileList[thisIndex].data,(size_t) fileList[thisIndex].dataLengthBytes)==0) - { - // File exists on both machines and is the same. - break; - } - else - { - // File exists on both machines and is not the same. - output->AddFile(fileList[thisIndex].filename, fileList[thisIndex].fullPathToFile, 0,0, fileList[thisIndex].fileLengthBytes, FileListNodeContext(0,0,0,0), false); - break; - } - } - } - if (match==false) - { - // Other system does not have the file at all - output->AddFile(fileList[thisIndex].filename, fileList[thisIndex].fullPathToFile, 0,0, fileList[thisIndex].fileLengthBytes, FileListNodeContext(0,0,0,0), false); - } - } -} -void FileList::ListMissingOrChangedFiles(const char *applicationDirectory, FileList *missingOrChangedFiles, bool alwaysWriteHash, bool neverWriteHash) -{ - unsigned fileLength; -// CSHA1 sha1; - FILE *fp; - char fullPath[512]; - unsigned i; -// char *fileData; - - for (i=0; i < fileList.Size(); i++) - { - strcpy_s(fullPath, applicationDirectory); - FixEndingSlash(fullPath, 512); - strcat_s(fullPath,fileList[i].filename); - if (fopen_s(&fp, fullPath, "rb") != 0) - { - missingOrChangedFiles->AddFile(fileList[i].filename, fileList[i].fullPathToFile, 0, 0, 0, FileListNodeContext(0,0,0,0), false); - } - else - { - fseek(fp, 0, SEEK_END); - fileLength = ftell(fp); - fseek(fp, 0, SEEK_SET); - - if (fileLength != fileList[i].fileLengthBytes && alwaysWriteHash==false) - { - missingOrChangedFiles->AddFile(fileList[i].filename, fileList[i].fullPathToFile, 0, 0, fileLength, FileListNodeContext(0,0,0,0), false); - } - else - { - -// fileData= (char*) rakMalloc_Ex( fileLength, _FILE_AND_LINE_ ); -// fread(fileData, fileLength, 1, fp); - -// sha1.Reset(); -// sha1.Update( ( unsigned char* ) fileData, fileLength ); -// sha1.Final(); - -// rakFree_Ex(fileData, _FILE_AND_LINE_ ); - - unsigned int hash = SuperFastHashFilePtr(fp); - if (MafiaNet::BitStream::DoEndianSwap()) - MafiaNet::BitStream::ReverseBytesInPlace((unsigned char*) &hash, sizeof(hash)); - - //if (fileLength != fileList[i].fileLength || memcmp( sha1.GetHash(), fileList[i].data, HASH_LENGTH)!=0) - if (fileLength != fileList[i].fileLengthBytes || memcmp( &hash, fileList[i].data, HASH_LENGTH)!=0) - { - if (neverWriteHash==false) - // missingOrChangedFiles->AddFile((const char*)fileList[i].filename, (const char*)sha1.GetHash(), HASH_LENGTH, fileLength, 0); - missingOrChangedFiles->AddFile((const char*)fileList[i].filename, (const char*)fileList[i].fullPathToFile, (const char *) &hash, HASH_LENGTH, fileLength, FileListNodeContext(0,0,0,0), false); - else - missingOrChangedFiles->AddFile((const char*)fileList[i].filename, (const char*)fileList[i].fullPathToFile, 0, 0, fileLength, FileListNodeContext(0,0,0,0), false); - } - } - fclose(fp); - } - } -} -void FileList::PopulateDataFromDisk(const char *applicationDirectory, bool writeFileData, bool writeFileHash, bool removeUnknownFiles) -{ - FILE *fp; - char fullPath[512]; - unsigned i; -// CSHA1 sha1; - - i=0; - while (i < fileList.Size()) - { - rakFree_Ex(fileList[i].data, _FILE_AND_LINE_ ); - strcpy_s(fullPath, applicationDirectory); - FixEndingSlash(fullPath, 512); - strcat_s(fullPath,fileList[i].filename.C_String()); - if (fopen_s(&fp, fullPath, "rb") == 0) - { - if (writeFileHash || writeFileData) - { - fseek(fp, 0, SEEK_END); - fileList[i].fileLengthBytes = ftell(fp); - fseek(fp, 0, SEEK_SET); - if (writeFileHash) - { - if (writeFileData) - { - // Hash + data so offset the data by HASH_LENGTH - fileList[i].data=(char*) rakMalloc_Ex( fileList[i].fileLengthBytes+HASH_LENGTH, _FILE_AND_LINE_ ); - RakAssert(fileList[i].data); - fread(fileList[i].data+HASH_LENGTH, fileList[i].fileLengthBytes, 1, fp); -// sha1.Reset(); -// sha1.Update((unsigned char*)fileList[i].data+HASH_LENGTH, fileList[i].fileLength); -// sha1.Final(); - unsigned int hash = SuperFastHash(fileList[i].data+HASH_LENGTH, fileList[i].fileLengthBytes); - if (MafiaNet::BitStream::DoEndianSwap()) - MafiaNet::BitStream::ReverseBytesInPlace((unsigned char*) &hash, sizeof(hash)); -// memcpy(fileList[i].data, sha1.GetHash(), HASH_LENGTH); - memcpy(fileList[i].data, &hash, HASH_LENGTH); - } - else - { - // Hash only - fileList[i].dataLengthBytes=HASH_LENGTH; - if (fileList[i].fileLengthBytes < HASH_LENGTH) - fileList[i].data=(char*) rakMalloc_Ex( HASH_LENGTH, _FILE_AND_LINE_ ); - else - fileList[i].data=(char*) rakMalloc_Ex( fileList[i].fileLengthBytes, _FILE_AND_LINE_ ); - RakAssert(fileList[i].data); - fread(fileList[i].data, fileList[i].fileLengthBytes, 1, fp); - // sha1.Reset(); - // sha1.Update((unsigned char*)fileList[i].data, fileList[i].fileLength); - // sha1.Final(); - unsigned int hash = SuperFastHash(fileList[i].data, fileList[i].fileLengthBytes); - if (MafiaNet::BitStream::DoEndianSwap()) - MafiaNet::BitStream::ReverseBytesInPlace((unsigned char*) &hash, sizeof(hash)); - // memcpy(fileList[i].data, sha1.GetHash(), HASH_LENGTH); - memcpy(fileList[i].data, &hash, HASH_LENGTH); - } - } - else - { - // Data only - fileList[i].dataLengthBytes=fileList[i].fileLengthBytes; - fileList[i].data=(char*) rakMalloc_Ex( fileList[i].fileLengthBytes, _FILE_AND_LINE_ ); - RakAssert(fileList[i].data); - fread(fileList[i].data, fileList[i].fileLengthBytes, 1, fp); - } - - fclose(fp); - i++; - } - else - { - fileList[i].data=0; - fileList[i].dataLengthBytes=0; - } - } - else - { - if (removeUnknownFiles) - { - fileList.RemoveAtIndex(i); - } - else - i++; - } - } -} -void FileList::FlagFilesAsReferences(void) -{ - for (unsigned int i=0; i < fileList.Size(); i++) - { - fileList[i].isAReference=true; - fileList[i].dataLengthBytes=fileList[i].fileLengthBytes; - } -} -void FileList::WriteDataToDisk(const char *applicationDirectory) -{ - char fullPath[512]; - unsigned i,j; - - for (i=0; i < fileList.Size(); i++) - { - strcpy_s(fullPath, applicationDirectory); - FixEndingSlash(fullPath, 512); - strcat_s(fullPath,fileList[i].filename.C_String()); - - // Security - Don't allow .. in the filename anywhere so you can't write outside of the root directory - for (j=1; j < fileList[i].filename.GetLength(); j++) - { - if (fileList[i].filename[j]=='.' && fileList[i].filename[j-1]=='.') - { -#ifdef _DEBUG - RakAssert(0); -#endif - // Just cancel the write entirely - return; - } - } - - WriteFileWithDirectories(fullPath, fileList[i].data, (unsigned int) fileList[i].dataLengthBytes); - } -} - -void FileList::DeleteFiles(const char *applicationDirectory) -{ - - - - char fullPath[512]; - unsigned i,j; - - for (i=0; i < fileList.Size(); i++) - { - // The filename should not have .. in the path - if it does ignore it - for (j=1; j < fileList[i].filename.GetLength(); j++) - { - if (fileList[i].filename[j]=='.' && fileList[i].filename[j-1]=='.') - { -#ifdef _DEBUG - RakAssert(0); -#endif - // Just cancel the deletion entirely - return; - } - } - - strcpy_s(fullPath, applicationDirectory); - FixEndingSlash(fullPath, 512); - strcat_s(fullPath, fileList[i].filename.C_String()); - - // Do not rename to _unlink as linux uses unlink -#if defined(_WIN32) - int result = _unlink(fullPath); -#else - int result = unlink(fullPath); -#endif - if (result!=0) - { - RAKNET_DEBUG_PRINTF("FileList::DeleteFiles: unlink (%s) failed.\n", fullPath); - } - } - -} - -void FileList::AddCallback(FileListProgress *cb) -{ - if (cb==0) - return; - - if ((unsigned int) fileListProgressCallbacks.GetIndexOf(cb)==(unsigned int)-1) - fileListProgressCallbacks.Push(cb, _FILE_AND_LINE_); -} -void FileList::RemoveCallback(FileListProgress *cb) -{ - unsigned int idx = fileListProgressCallbacks.GetIndexOf(cb); - if (idx!=(unsigned int) -1) - fileListProgressCallbacks.RemoveAtIndex(idx); -} -void FileList::ClearCallbacks(void) -{ - fileListProgressCallbacks.Clear(true, _FILE_AND_LINE_); -} -void FileList::GetCallbacks(DataStructures::List &callbacks) -{ - callbacks = fileListProgressCallbacks; -} - -bool FileList::FixEndingSlash(char *str) -{ -#ifdef _WIN32 - if (str[strlen(str) - 1] != '/' && str[strlen(str) - 1] != '\\') - { -#pragma warning(push) -#pragma warning(disable:4996) - strcat(str, "\\"); // Only \ works with system commands, used by AutopatcherClient -#pragma warning(pop) - return true; - } -#else - if (str[strlen(str) - 1] != '\\' && str[strlen(str) - 1] != '/') - { - strcat(str, "/"); // Only / works with Linux - return true; - } -#endif - - return false; -} - -bool FileList::FixEndingSlash(char *str, size_t strLength) -{ -#ifdef _WIN32 - if (str[strlen(str)-1]!='/' && str[strlen(str)-1]!='\\') - { - strcat_s(str, strLength, "\\"); // Only \ works with system commands, used by AutopatcherClient - return true; - } -#else - if (str[strlen(str)-1]!='\\' && str[strlen(str)-1]!='/') - { - strcat_s(str, strLength, "/"); // Only / works with Linux - return true; - } -#endif - - return false; -} - -#endif // _RAKNET_SUPPORT_FileOperations diff --git a/vendors/mafianet/Source/src/FileListTransfer.cpp b/vendors/mafianet/Source/src/FileListTransfer.cpp deleted file mode 100644 index ad05d5293..000000000 --- a/vendors/mafianet/Source/src/FileListTransfer.cpp +++ /dev/null @@ -1,1163 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_FileListTransfer==1 && _RAKNET_SUPPORT_FileOperations==1 - -#include "mafianet/FileListTransfer.h" -#include "mafianet/DS_HuffmanEncodingTree.h" -#include "mafianet/FileListTransferCBInterface.h" -#include "mafianet/StringCompressor.h" -#include "mafianet/FileList.h" -#include "mafianet/DS_Queue.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/types.h" -#include "mafianet/peerinterface.h" -#include "mafianet/statistics.h" -#include "mafianet/IncrementalReadInterface.h" -#include "mafianet/assert.h" -#include "mafianet/alloca.h" - -namespace MafiaNet -{ - -struct FLR_MemoryBlock -{ - char *flrMemoryBlock; -}; - -struct FileListReceiver -{ - FileListReceiver(); - ~FileListReceiver(); - FileListTransferCBInterface *downloadHandler; - SystemAddress allowedSender; - unsigned short setID; - unsigned setCount; - unsigned setTotalCompressedTransmissionLength; - unsigned setTotalFinalLength; - unsigned setTotalDownloadedLength; - bool gotSetHeader; - bool deleteDownloadHandler; - bool isCompressed; - int filesReceived; - DataStructures::Map pushedFiles; - - // Notifications - unsigned int partLength; - -}; - -} // namespace MafiaNet - -using namespace MafiaNet; - -FileListReceiver::FileListReceiver() {filesReceived=0; setTotalDownloadedLength=0; partLength=1; DataStructures::Map::IMPLEMENT_DEFAULT_COMPARISON();} -FileListReceiver::~FileListReceiver() { - unsigned int i=0; - for (i=0; i < pushedFiles.Size(); i++) - rakFree_Ex(pushedFiles[i].flrMemoryBlock, _FILE_AND_LINE_ ); -} - -STATIC_FACTORY_DEFINITIONS(FileListTransfer,FileListTransfer) - -void FileListTransfer::FileToPushRecipient::DeleteThis(void) -{ -//// filesToPushMutex.Lock(); - for (unsigned int j=0; j < filesToPush.Size(); j++) - MafiaNet::OP_DELETE(filesToPush[j],_FILE_AND_LINE_); -//// filesToPushMutex.Unlock(); - MafiaNet::OP_DELETE(this,_FILE_AND_LINE_); -} -void FileListTransfer::FileToPushRecipient::AddRef(void) -{ - refCountMutex.Lock(); - ++refCount; - refCountMutex.Unlock(); -} -void FileListTransfer::FileToPushRecipient::Deref(void) -{ - refCountMutex.Lock(); - --refCount; - if (refCount==0) - { - refCountMutex.Unlock(); - DeleteThis(); - return; - } - refCountMutex.Unlock(); -} -FileListTransfer::FileListTransfer() -{ - setId=0; - DataStructures::Map::IMPLEMENT_DEFAULT_COMPARISON(); -} -FileListTransfer::~FileListTransfer() -{ - threadPool.StopThreads(); - Clear(); -} -void FileListTransfer::StartIncrementalReadThreads(int numThreads, int threadPriority) -{ - (void) threadPriority; - - threadPool.StartThreads(numThreads, 0); -} -unsigned short FileListTransfer::SetupReceive(FileListTransferCBInterface *handler, bool deleteHandler, SystemAddress allowedSender) -{ - if (rakPeerInterface && rakPeerInterface->GetConnectionState(allowedSender)!=IS_CONNECTED) - return (unsigned short)-1; - FileListReceiver *receiver; - - if (fileListReceivers.Has(setId)) - { - receiver=fileListReceivers.Get(setId); - receiver->downloadHandler->OnDereference(); - if (receiver->deleteDownloadHandler) - MafiaNet::OP_DELETE(receiver->downloadHandler, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(receiver, _FILE_AND_LINE_); - fileListReceivers.Delete(setId); - } - - unsigned short oldId; - receiver = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - RakAssert(handler); - receiver->downloadHandler=handler; - receiver->allowedSender=allowedSender; - receiver->gotSetHeader=false; - receiver->deleteDownloadHandler=deleteHandler; - receiver->setID=setId; - fileListReceivers.Set(setId, receiver); - oldId=setId; - if (++setId==(unsigned short)-1) - setId=0; - return oldId; -} - -void FileListTransfer::Send(FileList *fileList, MafiaNet::RakPeerInterface *rakPeer, SystemAddress recipient, unsigned short setID, MafiaNet::Priority priority, char orderingChannel, IncrementalReadInterface *_incrementalReadInterface, unsigned int _chunkSize) -{ - for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++) - fileList->AddCallback(fileListProgressCallbacks[flpcIndex]); - - unsigned int i, totalLength; - MafiaNet::BitStream outBitstream; - bool sendReference; - const char *dataBlocks[2]; - int lengths[2]; - totalLength=0; - for (i=0; i < fileList->fileList.Size(); i++) - { - const FileListNode &fileListNode = fileList->fileList[i]; - totalLength+=fileListNode.dataLengthBytes; - } - - // Write the chunk header, which contains the frequency table, the total number of files, and the total number of bytes - bool anythingToWrite; - outBitstream.Write((MessageID)ID_FILE_LIST_TRANSFER_HEADER); - outBitstream.Write(setID); - anythingToWrite=fileList->fileList.Size()>0; - outBitstream.Write(anythingToWrite); - if (anythingToWrite) - { - outBitstream.WriteCompressed(fileList->fileList.Size()); - outBitstream.WriteCompressed(totalLength); - - if (rakPeer) - rakPeer->Send(&outBitstream, priority, MafiaNet::Reliability::ReliableOrdered, orderingChannel, recipient, false); - else - SendUnified(&outBitstream, priority, MafiaNet::Reliability::ReliableOrdered, orderingChannel, recipient, false); - - DataStructures::Queue filesToPush; - - for (i=0; i < fileList->fileList.Size(); i++) - { - sendReference = fileList->fileList[i].isAReference && _incrementalReadInterface!=0; - if (sendReference) - { - FileToPush *fileToPush = MafiaNet::OP_NEW(_FILE_AND_LINE_); - fileToPush->fileListNode.context=fileList->fileList[i].context; - fileToPush->setIndex=i; - fileToPush->fileListNode.filename=fileList->fileList[i].filename; - fileToPush->fileListNode.fullPathToFile=fileList->fileList[i].fullPathToFile; - fileToPush->fileListNode.fileLengthBytes=fileList->fileList[i].fileLengthBytes; - fileToPush->fileListNode.dataLengthBytes=fileList->fileList[i].dataLengthBytes; - // fileToPush->systemAddress=recipient; - //fileToPush->setID=setID; - fileToPush->packetPriority=priority; - fileToPush->orderingChannel=orderingChannel; - fileToPush->currentOffset=0; - fileToPush->incrementalReadInterface=_incrementalReadInterface; - fileToPush->chunkSize=_chunkSize; - filesToPush.Push(fileToPush,_FILE_AND_LINE_); - } - else - { - outBitstream.Reset(); - outBitstream.Write((MessageID)ID_FILE_LIST_TRANSFER_FILE); - outBitstream << fileList->fileList[i].context; - // outBitstream.Write(fileList->fileList[i].context); - outBitstream.Write(setID); - StringCompressor::Instance()->EncodeString(fileList->fileList[i].filename, 512, &outBitstream); - - outBitstream.WriteCompressed(i); - outBitstream.WriteCompressed(fileList->fileList[i].dataLengthBytes); // Original length in bytes - - outBitstream.AlignWriteToByteBoundary(); - - dataBlocks[0]=(char*) outBitstream.GetData(); - lengths[0]=outBitstream.GetNumberOfBytesUsed(); - dataBlocks[1]=fileList->fileList[i].data; - lengths[1]=fileList->fileList[i].dataLengthBytes; - SendListUnified(dataBlocks,lengths,2,priority, MafiaNet::Reliability::ReliableOrdered, orderingChannel, recipient, false); - } - } - - if (filesToPush.IsEmpty()==false) - { - FileToPushRecipient *ftpr; - - fileToPushRecipientListMutex.Lock(); - for (i=0; i < fileToPushRecipientList.Size(); i++) - { - if (fileToPushRecipientList[i]->systemAddress==recipient && fileToPushRecipientList[i]->setId==setId) - { -// ftpr=fileToPushRecipientList[i]; -// ftpr->AddRef(); -// break; - RakAssert("setId already in use for this recipient" && 0); - } - } - fileToPushRecipientListMutex.Unlock(); - - //if (ftpr==0) - //{ - ftpr = MafiaNet::OP_NEW(_FILE_AND_LINE_); - ftpr->systemAddress=recipient; - ftpr->setId=setID; - ftpr->refCount=2; // Allocated and in the list - fileToPushRecipientList.Push(ftpr, _FILE_AND_LINE_); - //} - while (filesToPush.IsEmpty()==false) - { - ////ftpr->filesToPushMutex.Lock(); - ftpr->filesToPush.Push(filesToPush.Pop(), _FILE_AND_LINE_); - ////ftpr->filesToPushMutex.Unlock(); - } - // ftpr out of scope - ftpr->Deref(); - SendIRIToAddress(recipient, setID); - return; - } - else - { - for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++) - fileListProgressCallbacks[flpcIndex]->OnFilePushesComplete(recipient, setID); - } - } - else - { - for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++) - fileListProgressCallbacks[flpcIndex]->OnFilePushesComplete(recipient, setID); - - if (rakPeer) - rakPeer->Send(&outBitstream, priority, MafiaNet::Reliability::ReliableOrdered, orderingChannel, recipient, false); - else - SendUnified(&outBitstream, priority, MafiaNet::Reliability::ReliableOrdered, orderingChannel, recipient, false); - } -} - -bool FileListTransfer::DecodeSetHeader(Packet *packet) -{ - bool anythingToWrite=false; - unsigned short setID; - MafiaNet::BitStream inBitStream(packet->data, packet->length, false); - inBitStream.IgnoreBits(8); - inBitStream.Read(setID); - FileListReceiver *fileListReceiver; - if (fileListReceivers.Has(setID)==false) - { - // If this assert hits you didn't call SetupReceive -#ifdef _DEBUG - RakAssert(0); -#endif - return false; - } - fileListReceiver=fileListReceivers.Get(setID); - if (fileListReceiver->allowedSender!=packet->systemAddress) - { -#ifdef _DEBUG - RakAssert(0); -#endif - return false; - } - -#ifdef _DEBUG - RakAssert(fileListReceiver->gotSetHeader==false); -#endif - - inBitStream.Read(anythingToWrite); - - if (anythingToWrite) - { - inBitStream.ReadCompressed(fileListReceiver->setCount); - if (inBitStream.ReadCompressed(fileListReceiver->setTotalFinalLength)) - { - fileListReceiver->setTotalCompressedTransmissionLength=fileListReceiver->setTotalFinalLength; - fileListReceiver->gotSetHeader=true; - return true; - } - - } - else - { - FileListTransferCBInterface::DownloadCompleteStruct dcs; - dcs.setID=fileListReceiver->setID; - dcs.numberOfFilesInThisSet=fileListReceiver->setCount; - dcs.byteLengthOfThisSet=fileListReceiver->setTotalFinalLength; - dcs.senderSystemAddress=packet->systemAddress; - dcs.senderGuid=packet->guid; - - if (fileListReceiver->downloadHandler->OnDownloadComplete(&dcs)==false) - { - fileListReceiver->downloadHandler->OnDereference(); - fileListReceivers.Delete(setID); - if (fileListReceiver->deleteDownloadHandler) - MafiaNet::OP_DELETE(fileListReceiver->downloadHandler, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(fileListReceiver, _FILE_AND_LINE_); - } - - return true; - } - - return false; -} - -bool FileListTransfer::DecodeFile(Packet *packet, bool isTheFullFile) -{ - FileListTransferCBInterface::OnFileStruct onFileStruct; - MafiaNet::BitStream inBitStream(packet->data, packet->length, false); - inBitStream.IgnoreBits(8); - - onFileStruct.senderSystemAddress=packet->systemAddress; - onFileStruct.senderGuid=packet->guid; - - unsigned int partCount=0; - unsigned int partTotal=0; - unsigned int partLength=0; - onFileStruct.fileData=0; - if (isTheFullFile==false) - { - // Disable endian swapping on reading this, as it's generated locally in ReliabilityLayer.cpp - inBitStream.ReadBits( (unsigned char* ) &partCount, BYTES_TO_BITS(sizeof(partCount)), true ); - inBitStream.ReadBits( (unsigned char* ) &partTotal, BYTES_TO_BITS(sizeof(partTotal)), true ); - inBitStream.ReadBits( (unsigned char* ) &partLength, BYTES_TO_BITS(sizeof(partLength)), true ); - inBitStream.IgnoreBits(8); - // The header is appended to every chunk, which we continue to read after this statement flrMemoryBlock - } - inBitStream >> onFileStruct.context; - // inBitStream.Read(onFileStruct.context); - inBitStream.Read(onFileStruct.setID); - FileListReceiver *fileListReceiver; - if (fileListReceivers.Has(onFileStruct.setID)==false) - { - return false; - } - fileListReceiver=fileListReceivers.Get(onFileStruct.setID); - if (fileListReceiver->allowedSender!=packet->systemAddress) - { -#ifdef _DEBUG - RakAssert(0); -#endif - return false; - } - -#ifdef _DEBUG - RakAssert(fileListReceiver->gotSetHeader==true); -#endif - - if (StringCompressor::Instance()->DecodeString(onFileStruct.fileName, 512, &inBitStream)==false) - { -#ifdef _DEBUG - RakAssert(0); -#endif - return false; - } - - inBitStream.ReadCompressed(onFileStruct.fileIndex); - inBitStream.ReadCompressed(onFileStruct.byteLengthOfThisFile); - - onFileStruct.numberOfFilesInThisSet=fileListReceiver->setCount; - onFileStruct.byteLengthOfThisSet=fileListReceiver->setTotalFinalLength; - - if (isTheFullFile) - { - onFileStruct.bytesDownloadedForThisFile=onFileStruct.byteLengthOfThisFile; - fileListReceiver->setTotalDownloadedLength+=onFileStruct.byteLengthOfThisFile; - onFileStruct.bytesDownloadedForThisSet=fileListReceiver->setTotalDownloadedLength; - } - else - { - onFileStruct.bytesDownloadedForThisFile=partLength*partCount; - onFileStruct.bytesDownloadedForThisSet=fileListReceiver->setTotalDownloadedLength+onFileStruct.bytesDownloadedForThisFile; - } - - // User callback for this file. - if (isTheFullFile) - { - inBitStream.AlignReadToByteBoundary(); - onFileStruct.fileData = (char*) rakMalloc_Ex( (size_t) onFileStruct.byteLengthOfThisFile, _FILE_AND_LINE_ ); - inBitStream.Read((char*)onFileStruct.fileData, onFileStruct.byteLengthOfThisFile); - - FileListTransferCBInterface::FileProgressStruct fps; - fps.onFileStruct=&onFileStruct; - fps.partCount=1; - fps.partTotal=1; - fps.dataChunkLength=onFileStruct.byteLengthOfThisFile; - fps.firstDataChunk=onFileStruct.fileData; - fps.iriDataChunk=onFileStruct.fileData; - fps.allocateIrIDataChunkAutomatically=true; - fps.iriWriteOffset=0; - fps.senderSystemAddress=packet->systemAddress; - fps.senderGuid=packet->guid; - fileListReceiver->downloadHandler->OnFileProgress(&fps); - - // Got a complete file - // Either we are using IncrementalReadInterface and it was a small file or - // We are not using IncrementalReadInterface - if (fileListReceiver->downloadHandler->OnFile(&onFileStruct)) - rakFree_Ex(onFileStruct.fileData, _FILE_AND_LINE_ ); - - fileListReceiver->filesReceived++; - - // If this set is done, free the memory for it. - if ((int) fileListReceiver->setCount==fileListReceiver->filesReceived) - { - FileListTransferCBInterface::DownloadCompleteStruct dcs; - dcs.setID=fileListReceiver->setID; - dcs.numberOfFilesInThisSet=fileListReceiver->setCount; - dcs.byteLengthOfThisSet=fileListReceiver->setTotalFinalLength; - dcs.senderSystemAddress=packet->systemAddress; - dcs.senderGuid=packet->guid; - - if (fileListReceiver->downloadHandler->OnDownloadComplete(&dcs)==false) - { - fileListReceiver->downloadHandler->OnDereference(); - if (fileListReceiver->deleteDownloadHandler) - MafiaNet::OP_DELETE(fileListReceiver->downloadHandler, _FILE_AND_LINE_); - fileListReceivers.Delete(onFileStruct.setID); - MafiaNet::OP_DELETE(fileListReceiver, _FILE_AND_LINE_); - } - } - - } - else - { - inBitStream.AlignReadToByteBoundary(); - - char *firstDataChunk; - unsigned int unreadBits = inBitStream.GetNumberOfUnreadBits(); - unsigned int unreadBytes = BITS_TO_BYTES(unreadBits); - firstDataChunk=(char*) inBitStream.GetData()+BITS_TO_BYTES(inBitStream.GetReadOffset()); - - FileListTransferCBInterface::FileProgressStruct fps; - fps.onFileStruct=&onFileStruct; - fps.partCount=partCount; - fps.partTotal=partTotal; - fps.dataChunkLength=unreadBytes; - fps.firstDataChunk=firstDataChunk; - fps.iriDataChunk=0; - fps.allocateIrIDataChunkAutomatically=true; - fps.iriWriteOffset=0; - fps.senderSystemAddress=packet->systemAddress; - fps.senderGuid=packet->guid; - - // Remote system is sending a complete file, but the file is large enough that we get ID_PROGRESS_NOTIFICATION from the transport layer - fileListReceiver->downloadHandler->OnFileProgress(&fps); - - } - - return true; -} -PluginReceiveResult FileListTransfer::OnReceive(Packet *packet) -{ - switch (packet->data[0]) - { - case ID_FILE_LIST_TRANSFER_HEADER: - DecodeSetHeader(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_FILE_LIST_TRANSFER_FILE: - DecodeFile(packet, true); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_FILE_LIST_REFERENCE_PUSH: - OnReferencePush(packet, true); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_FILE_LIST_REFERENCE_PUSH_ACK: - OnReferencePushAck(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_DOWNLOAD_PROGRESS: - if (packet->length>sizeof(MessageID)+sizeof(unsigned int)*3) - { - if (packet->data[sizeof(MessageID)+sizeof(unsigned int)*3]==ID_FILE_LIST_TRANSFER_FILE) - { - DecodeFile(packet, false); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - if (packet->data[sizeof(MessageID)+sizeof(unsigned int)*3]==ID_FILE_LIST_REFERENCE_PUSH) - { - OnReferencePush(packet, false); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - } - break; - } - - return RR_CONTINUE_PROCESSING; -} -void FileListTransfer::OnRakPeerShutdown(void) -{ - threadPool.StopThreads(); - threadPool.ClearInput(); - Clear(); -} -void FileListTransfer::Clear(void) -{ - unsigned i; - for (i=0; i < fileListReceivers.Size(); i++) - { - fileListReceivers[i]->downloadHandler->OnDereference(); - if (fileListReceivers[i]->deleteDownloadHandler) - MafiaNet::OP_DELETE(fileListReceivers[i]->downloadHandler, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(fileListReceivers[i], _FILE_AND_LINE_); - } - fileListReceivers.Clear(); - - fileToPushRecipientListMutex.Lock(); - for (i=0; i < fileToPushRecipientList.Size(); i++) - { - FileToPushRecipient *ftpr = fileToPushRecipientList[i]; - // Taken out of the list - ftpr->Deref(); - } - fileToPushRecipientList.Clear(false,_FILE_AND_LINE_); - fileToPushRecipientListMutex.Unlock(); - - //filesToPush.Clear(false, _FILE_AND_LINE_); -} -void FileListTransfer::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) lostConnectionReason; - (void) rakNetGUID; - - RemoveReceiver(systemAddress); -} -void FileListTransfer::CancelReceive(unsigned short inSetId) -{ - if (fileListReceivers.Has(inSetId)==false) - { -#ifdef _DEBUG - RakAssert(0); -#endif - return; - } - FileListReceiver *fileListReceiver=fileListReceivers.Get(inSetId); - fileListReceiver->downloadHandler->OnDereference(); - if (fileListReceiver->deleteDownloadHandler) - MafiaNet::OP_DELETE(fileListReceiver->downloadHandler, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(fileListReceiver, _FILE_AND_LINE_); - fileListReceivers.Delete(inSetId); -} -void FileListTransfer::RemoveReceiver(SystemAddress systemAddress) -{ - unsigned i; - i=0; - threadPool.LockInput(); - while (i < threadPool.InputSize()) - { - if (threadPool.GetInputAtIndex(i).systemAddress==systemAddress) - { - threadPool.RemoveInputAtIndex(i); - } - else - i++; - } - threadPool.UnlockInput(); - - i=0; - while (i < fileListReceivers.Size()) - { - if (fileListReceivers[i]->allowedSender==systemAddress) - { - fileListReceivers[i]->downloadHandler->OnDereference(); - if (fileListReceivers[i]->deleteDownloadHandler) - MafiaNet::OP_DELETE(fileListReceivers[i]->downloadHandler, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(fileListReceivers[i], _FILE_AND_LINE_); - fileListReceivers.RemoveAtIndex(i); - } - else - i++; - } - - fileToPushRecipientListMutex.Lock(); - i=0; - while (i < fileToPushRecipientList.Size()) - { - if (fileToPushRecipientList[i]->systemAddress==systemAddress) - { - FileToPushRecipient *ftpr = fileToPushRecipientList[i]; - - // Tell the user that this recipient was lost - for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++) - fileListProgressCallbacks[flpcIndex]->OnSendAborted(ftpr->systemAddress); - - fileToPushRecipientList.RemoveAtIndex(i); - // Taken out of the list - ftpr->Deref(); - } - else - { - i++; - } - } - fileToPushRecipientListMutex.Unlock(); -} -bool FileListTransfer::IsHandlerActive(unsigned short inSetId) -{ - return fileListReceivers.Has(inSetId); -} -void FileListTransfer::AddCallback(FileListProgress *cb) -{ - if (cb==0) - return; - - if (fileListProgressCallbacks.GetIndexOf(cb)==(unsigned int) -1) - fileListProgressCallbacks.Push(cb, _FILE_AND_LINE_); -} -void FileListTransfer::RemoveCallback(FileListProgress *cb) -{ - unsigned int idx = fileListProgressCallbacks.GetIndexOf(cb); - if (idx!=(unsigned int) -1) - fileListProgressCallbacks.RemoveAtIndex(idx); -} -void FileListTransfer::ClearCallbacks(void) -{ - fileListProgressCallbacks.Clear(true, _FILE_AND_LINE_); -} -void FileListTransfer::GetCallbacks(DataStructures::List &callbacks) -{ - callbacks = fileListProgressCallbacks; -} - -void FileListTransfer::Update(void) -{ - unsigned i; - i=0; - while (i < fileListReceivers.Size()) - { - if (fileListReceivers[i]->downloadHandler->Update()==false) - { - fileListReceivers[i]->downloadHandler->OnDereference(); - if (fileListReceivers[i]->deleteDownloadHandler) - MafiaNet::OP_DELETE(fileListReceivers[i]->downloadHandler, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(fileListReceivers[i], _FILE_AND_LINE_); - fileListReceivers.RemoveAtIndex(i); - } - else - i++; - } -} -void FileListTransfer::OnReferencePush(Packet *packet, bool isTheFullFile) -{ - MafiaNet::BitStream refPushAck; - if (isTheFullFile==false) - { - // 12/23/09 Why do I care about ID_DOWNLOAD_PROGRESS for reference pushes? - // 2/16/2012 I care because a reference push is 16 megabytes by default. Also, if it is the last file "if (ftpr->filesToPush.Size()<2)" or total file size exceeds smallFileTotalSize it always sends a reference push. -// return; - } - - FileListTransferCBInterface::OnFileStruct onFileStruct; - MafiaNet::BitStream inBitStream(packet->data, packet->length, false); - inBitStream.IgnoreBits(8); - - unsigned int partCount=0; - unsigned int partTotal=1; - unsigned int partLength=0; - onFileStruct.fileData=0; - if (isTheFullFile==false) - { - // Disable endian swapping on reading this, as it's generated locally in ReliabilityLayer.cpp - inBitStream.ReadBits( (unsigned char* ) &partCount, BYTES_TO_BITS(sizeof(partCount)), true ); - inBitStream.ReadBits( (unsigned char* ) &partTotal, BYTES_TO_BITS(sizeof(partTotal)), true ); - inBitStream.ReadBits( (unsigned char* ) &partLength, BYTES_TO_BITS(sizeof(partLength)), true ); - inBitStream.IgnoreBits(8); - // The header is appended to every chunk, which we continue to read after this statement flrMemoryBlock - } - - inBitStream >> onFileStruct.context; - inBitStream.Read(onFileStruct.setID); - - // This is not a progress notification, it is actually the entire packet - if (isTheFullFile==true) - { - refPushAck.Write((MessageID)ID_FILE_LIST_REFERENCE_PUSH_ACK); - refPushAck.Write(onFileStruct.setID); - SendUnified(&refPushAck,MafiaNet::Priority::High, MafiaNet::Reliability::Reliable, 0, packet->systemAddress, false); - } - - // inBitStream.Read(onFileStruct.context); - FileListReceiver *fileListReceiver; - if (fileListReceivers.Has(onFileStruct.setID)==false) - { - return; - } - fileListReceiver=fileListReceivers.Get(onFileStruct.setID); - if (fileListReceiver->allowedSender!=packet->systemAddress) - { -#ifdef _DEBUG - RakAssert(0); -#endif - return; - } - -#ifdef _DEBUG - RakAssert(fileListReceiver->gotSetHeader==true); -#endif - - if (StringCompressor::Instance()->DecodeString(onFileStruct.fileName, 512, &inBitStream)==false) - { -#ifdef _DEBUG - RakAssert(0); -#endif - return; - } - - inBitStream.ReadCompressed(onFileStruct.fileIndex); - inBitStream.ReadCompressed(onFileStruct.byteLengthOfThisFile); - unsigned int offset; - unsigned int chunkLength; - inBitStream.ReadCompressed(offset); - inBitStream.ReadCompressed(chunkLength); - - bool lastChunk=false; - inBitStream.Read(lastChunk); - bool finished = lastChunk && isTheFullFile; - - if (isTheFullFile==false) - fileListReceiver->partLength=partLength; - - FLR_MemoryBlock mb; - if (fileListReceiver->pushedFiles.Has(onFileStruct.fileIndex)==false) - { - if (onFileStruct.byteLengthOfThisFile <= SLNET_MAX_RETRIEVABLE_FILESIZE) - mb.flrMemoryBlock = (char*)rakMalloc_Ex(onFileStruct.byteLengthOfThisFile, _FILE_AND_LINE_); - else - mb.flrMemoryBlock = nullptr; - fileListReceiver->pushedFiles.SetNew(onFileStruct.fileIndex, mb); - } - else - { - mb=fileListReceiver->pushedFiles.Get(onFileStruct.fileIndex); - } - - unsigned int unreadBits = inBitStream.GetNumberOfUnreadBits(); - unsigned int unreadBytes = BITS_TO_BYTES(unreadBits); - unsigned int amountToRead; - if (isTheFullFile) - amountToRead=chunkLength; - else - amountToRead=unreadBytes; - - inBitStream.AlignReadToByteBoundary(); - - FileListTransferCBInterface::FileProgressStruct fps; - - if (isTheFullFile) - { - if (mb.flrMemoryBlock) - { - // Either the very first block, or a subsequent block and allocateIrIDataChunkAutomatically was true for the first block - memcpy(mb.flrMemoryBlock+offset, inBitStream.GetData()+BITS_TO_BYTES(inBitStream.GetReadOffset()), amountToRead); - fps.iriDataChunk=mb.flrMemoryBlock+offset; - } - else - { - // In here mb.flrMemoryBlock is null - // This means the first block explicitly deallocated the memory, and no blocks will be permanently held by RakNet - fps.iriDataChunk=(char*) inBitStream.GetData()+BITS_TO_BYTES(inBitStream.GetReadOffset()); - } - - onFileStruct.bytesDownloadedForThisFile=offset+chunkLength; - fileListReceiver->setTotalDownloadedLength+=chunkLength; - onFileStruct.bytesDownloadedForThisSet=fileListReceiver->setTotalDownloadedLength; - } - else - { - onFileStruct.bytesDownloadedForThisFile=offset+partLength*partCount; - onFileStruct.bytesDownloadedForThisSet=fileListReceiver->setTotalDownloadedLength+partCount*partLength; - fps.iriDataChunk=(char*) inBitStream.GetData()+BITS_TO_BYTES(inBitStream.GetReadOffset()); - } - - onFileStruct.numberOfFilesInThisSet=fileListReceiver->setCount; -// onFileStruct.setTotalCompressedTransmissionLength=fileListReceiver->setTotalCompressedTransmissionLength; - onFileStruct.byteLengthOfThisSet=fileListReceiver->setTotalFinalLength; - // Note: mb.flrMemoryBlock may be null here - onFileStruct.fileData=mb.flrMemoryBlock; - onFileStruct.senderSystemAddress=packet->systemAddress; - onFileStruct.senderGuid=packet->guid; - - unsigned int totalNotifications; - unsigned int currentNotificationIndex; - if (chunkLength==0 || chunkLength==onFileStruct.byteLengthOfThisFile) - totalNotifications=1; - else - totalNotifications = onFileStruct.byteLengthOfThisFile / chunkLength + 1; - - if (chunkLength==0) - currentNotificationIndex = 0; - else - currentNotificationIndex = offset / chunkLength; - - fps.onFileStruct=&onFileStruct; - fps.partCount=currentNotificationIndex; - fps.partTotal=totalNotifications; - fps.dataChunkLength=amountToRead; - fps.firstDataChunk=mb.flrMemoryBlock; - fps.allocateIrIDataChunkAutomatically=true; - fps.onFileStruct->fileData=mb.flrMemoryBlock; - fps.iriWriteOffset=offset; - fps.senderSystemAddress=packet->systemAddress; - fps.senderGuid=packet->guid; - - if (finished) - { - char *oldFileData=fps.onFileStruct->fileData; - if (fps.partCount==0) - fps.firstDataChunk=fps.iriDataChunk; - if (fps.partTotal==1) - fps.onFileStruct->fileData=fps.iriDataChunk; - fileListReceiver->downloadHandler->OnFileProgress(&fps); - - // Incremental read interface sent us a file chunk - // This is the last file chunk we were waiting for to consider the file done - if (fileListReceiver->downloadHandler->OnFile(&onFileStruct)) - rakFree_Ex(oldFileData, _FILE_AND_LINE_ ); - fileListReceiver->pushedFiles.Delete(onFileStruct.fileIndex); - - fileListReceiver->filesReceived++; - - // If this set is done, free the memory for it. - if ((int) fileListReceiver->setCount==fileListReceiver->filesReceived) - { - FileListTransferCBInterface::DownloadCompleteStruct dcs; - dcs.setID=fileListReceiver->setID; - dcs.numberOfFilesInThisSet=fileListReceiver->setCount; - dcs.byteLengthOfThisSet=fileListReceiver->setTotalFinalLength; - dcs.senderSystemAddress=packet->systemAddress; - dcs.senderGuid=packet->guid; - - if (fileListReceiver->downloadHandler->OnDownloadComplete(&dcs)==false) - { - fileListReceiver->downloadHandler->OnDereference(); - fileListReceivers.Delete(onFileStruct.setID); - if (fileListReceiver->deleteDownloadHandler) - MafiaNet::OP_DELETE(fileListReceiver->downloadHandler, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(fileListReceiver, _FILE_AND_LINE_); - } - } - } - else - { - if (isTheFullFile) - { - // 12/23/09 Don't use OnReferencePush anymore, just use OnFileProgress - fileListReceiver->downloadHandler->OnFileProgress(&fps); - - if (fps.allocateIrIDataChunkAutomatically==false) - { - rakFree_Ex(fileListReceiver->pushedFiles.Get(onFileStruct.fileIndex).flrMemoryBlock, _FILE_AND_LINE_ ); - fileListReceiver->pushedFiles.Get(onFileStruct.fileIndex).flrMemoryBlock=0; - } - } - else - { - // This is a download progress notification for a file chunk using incremental read interface - // We don't have all the data for this chunk yet - - totalNotifications = onFileStruct.byteLengthOfThisFile / fileListReceiver->partLength + 1; - if (isTheFullFile==false) - currentNotificationIndex = (offset+partCount*fileListReceiver->partLength) / fileListReceiver->partLength ; - else - currentNotificationIndex = (offset+chunkLength) / fileListReceiver->partLength ; - unreadBytes = onFileStruct.byteLengthOfThisFile - ((currentNotificationIndex+1) * fileListReceiver->partLength); - fps.partCount=currentNotificationIndex; - fps.partTotal=totalNotifications; - -// 2/19/2013 Why was this check here? It prevent smaller progress notifications -// if (rakPeerInterface) - { - // Thus chunk is incomplete - fps.iriDataChunk=0; - - fileListReceiver->downloadHandler->OnFileProgress(&fps); - } - } - } -} -namespace MafiaNet -{ - -/* -SendIRIToAddress - executes from Send(). = -1, Find the recipient to send for -2. Send ID_FILE_LIST_TRANSFER_FILE for each small file in the queue of ifles to be sent -3. If the file we are working on is done, remove it from the list -4. Send ID_FILE_LIST_REFERENCE_PUSH for the file we are working on - -File sender: -ID_FILE_LIST_REFERENCE_PUSH sent from end of SendIRIToAddressCB - -Recipient: -send ID_FILE_LIST_REFERENCE_PUSH_ACK sent from OnReferencePush() when 2nd parameter is true. - -File sender: -Got ID_FILE_LIST_REFERENCE_PUSH_ACK. Calls OnReferencePushAck, calls SendIRIToAddress, calls SendIRIToAddressCB -*/ - -int SendIRIToAddressCB(FileListTransfer::ThreadData threadData, bool *returnOutput, void* perThreadData) -{ - (void) perThreadData; - - FileListTransfer *fileListTransfer = threadData.fileListTransfer; - SystemAddress systemAddress = threadData.systemAddress; - unsigned short setId = threadData.setId; - *returnOutput=false; - - // Was previously using GetStatistics to get outgoing buffer size, but TCP with UnifiedSend doesn't have this - unsigned int bytesRead; - const char *dataBlocks[2]; - int lengths[2]; - unsigned int smallFileTotalSize=0; - MafiaNet::BitStream outBitstream; - unsigned int ftpIndex; - - fileListTransfer->fileToPushRecipientListMutex.Lock(); - for (ftpIndex=0; ftpIndex < fileListTransfer->fileToPushRecipientList.Size(); ftpIndex++) - { - FileListTransfer::FileToPushRecipient *ftpr = fileListTransfer->fileToPushRecipientList[ftpIndex]; - // Referenced by both ftpr and list - ftpr->AddRef(); - - fileListTransfer->fileToPushRecipientListMutex.Unlock(); - - if (ftpr->systemAddress==systemAddress && ftpr->setId==setId) - { - FileListTransfer::FileToPush *ftp; - ////ftpr->filesToPushMutex.Lock(); - ftp = ftpr->filesToPush.Pop(); - ////ftpr->filesToPushMutex.Unlock(); - - // Read and send chunk. If done, delete at this index - void *buff = rakMalloc_Ex(ftp->chunkSize, _FILE_AND_LINE_); - if (buff==0) - { - ////ftpr->filesToPushMutex.Lock(); - ftpr->filesToPush.PushAtHead(ftp,0,_FILE_AND_LINE_); - ////ftpr->filesToPushMutex.Unlock(); - - ftpr->Deref(); - notifyOutOfMemory(_FILE_AND_LINE_); - return 0; - } - - // Read the next file chunk - bytesRead=ftp->incrementalReadInterface->GetFilePart(ftp->fileListNode.fullPathToFile, ftp->currentOffset, ftp->chunkSize, buff, ftp->fileListNode.context); - - bool done = ftp->fileListNode.dataLengthBytes == ftp->currentOffset+bytesRead; - while (done && ftp->currentOffset==0 && smallFileTotalSizechunkSize) - { - ////ftpr->filesToPushMutex.Lock(); - // The reason for 2 is that ID_FILE_LIST_REFERENCE_PUSH gets ID_FILE_LIST_REFERENCE_PUSH_ACK. WIthout ID_FILE_LIST_REFERENCE_PUSH_ACK, SendIRIToAddressCB would not be called again - if (ftpr->filesToPush.Size()<2) - { - ////ftpr->filesToPushMutex.Unlock(); - break; - } - ////ftpr->filesToPushMutex.Unlock(); - - // Send all small files at once, rather than wait for ID_FILE_LIST_REFERENCE_PUSH. But at least one ID_FILE_LIST_REFERENCE_PUSH must be sent - outBitstream.Reset(); - outBitstream.Write((MessageID)ID_FILE_LIST_TRANSFER_FILE); - // outBitstream.Write(ftp->fileListNode.context); - outBitstream << ftp->fileListNode.context; - outBitstream.Write(setId); - StringCompressor::Instance()->EncodeString(ftp->fileListNode.filename, 512, &outBitstream); - outBitstream.WriteCompressed(ftp->setIndex); - outBitstream.WriteCompressed(ftp->fileListNode.dataLengthBytes); // Original length in bytes - outBitstream.AlignWriteToByteBoundary(); - dataBlocks[0]=(char*) outBitstream.GetData(); - lengths[0]=outBitstream.GetNumberOfBytesUsed(); - dataBlocks[1]=(const char*) buff; - lengths[1]=bytesRead; - - fileListTransfer->SendListUnified(dataBlocks,lengths,2,ftp->packetPriority, MafiaNet::Reliability::ReliableOrdered, ftp->orderingChannel, systemAddress, false); - - // LWS : fixed freed pointer reference -// unsigned int chunkSize = ftp->chunkSize; - MafiaNet::OP_DELETE(ftp,_FILE_AND_LINE_); - smallFileTotalSize+=bytesRead; - //done = bytesRead!=ftp->chunkSize; - ////ftpr->filesToPushMutex.Lock(); - ftp = ftpr->filesToPush.Pop(); - ////ftpr->filesToPushMutex.Unlock(); - - bytesRead=ftp->incrementalReadInterface->GetFilePart(ftp->fileListNode.fullPathToFile, ftp->currentOffset, ftp->chunkSize, buff, ftp->fileListNode.context); - done = ftp->fileListNode.dataLengthBytes == ftp->currentOffset+bytesRead; - } - - - outBitstream.Reset(); - outBitstream.Write((MessageID)ID_FILE_LIST_REFERENCE_PUSH); - // outBitstream.Write(ftp->fileListNode.context); - outBitstream << ftp->fileListNode.context; - outBitstream.Write(setId); - StringCompressor::Instance()->EncodeString(ftp->fileListNode.filename, 512, &outBitstream); - outBitstream.WriteCompressed(ftp->setIndex); - outBitstream.WriteCompressed(ftp->fileListNode.dataLengthBytes); // Original length in bytes - outBitstream.WriteCompressed(ftp->currentOffset); - ftp->currentOffset+=bytesRead; - outBitstream.WriteCompressed(bytesRead); - outBitstream.Write(done); - - for (unsigned int flpcIndex=0; flpcIndex < fileListTransfer->fileListProgressCallbacks.Size(); flpcIndex++) - fileListTransfer->fileListProgressCallbacks[flpcIndex]->OnFilePush(ftp->fileListNode.filename, ftp->fileListNode.fileLengthBytes, ftp->currentOffset-bytesRead, bytesRead, done, systemAddress, setId); - - dataBlocks[0]=(char*) outBitstream.GetData(); - lengths[0]=outBitstream.GetNumberOfBytesUsed(); - dataBlocks[1]=(char*) buff; - lengths[1]=bytesRead; - //rakPeerInterface->SendList(dataBlocks,lengths,2,ftp->packetPriority, MafiaNet::Reliability::ReliableOrdered, ftp->orderingChannel, ftp->systemAddress, false); - char orderingChannel = ftp->orderingChannel; - MafiaNet::Priority packetPriority = ftp->packetPriority; - - // Mutex state: FileToPushRecipient (ftpr) has AddRef. fileToPushRecipientListMutex not locked. - if (done) - { - // Done - //unsigned short setId = ftp->setID; - MafiaNet::OP_DELETE(ftp,_FILE_AND_LINE_); - - ////ftpr->filesToPushMutex.Lock(); - if (ftpr->filesToPush.Size()==0) - { - ////ftpr->filesToPushMutex.Unlock(); - - for (unsigned int flpcIndex=0; flpcIndex < fileListTransfer->fileListProgressCallbacks.Size(); flpcIndex++) - fileListTransfer->fileListProgressCallbacks[flpcIndex]->OnFilePushesComplete(systemAddress, setId); - - // Remove ftpr from fileToPushRecipientList - fileListTransfer->RemoveFromList(ftpr); - } - else - { - ////ftpr->filesToPushMutex.Unlock(); - } - } - else - { - ////ftpr->filesToPushMutex.Lock(); - ftpr->filesToPush.PushAtHead(ftp,0,_FILE_AND_LINE_); - ////ftpr->filesToPushMutex.Unlock(); - } - // ftpr out of scope - ftpr->Deref(); - - // 2/12/2012 Moved this line at after the if (done) block above. - // See http://www.jenkinssoftware.com/forum/index.php?topic=4768.msg19738#msg19738 - fileListTransfer->SendListUnified(dataBlocks,lengths,2, packetPriority, MafiaNet::Reliability::ReliableOrdered, orderingChannel, systemAddress, false); - - rakFree_Ex(buff, _FILE_AND_LINE_ ); - return 0; - } - else - { - ftpr->Deref(); - fileListTransfer->fileToPushRecipientListMutex.Lock(); - } - } - - fileListTransfer->fileToPushRecipientListMutex.Unlock(); - - return 0; -} -} -void FileListTransfer::SendIRIToAddress(SystemAddress systemAddress, unsigned short inSetId) -{ - ThreadData threadData; - threadData.fileListTransfer=this; - threadData.systemAddress=systemAddress; - threadData.setId= inSetId; - - if (threadPool.WasStarted()) - { - threadPool.AddInput(SendIRIToAddressCB, threadData); - } - else - { - bool doesNothing; - SendIRIToAddressCB(threadData, &doesNothing, 0); - } -} -void FileListTransfer::OnReferencePushAck(Packet *packet) -{ - MafiaNet::BitStream inBitStream(packet->data, packet->length, false); - inBitStream.IgnoreBits(8); - unsigned short curSetId; - inBitStream.Read(curSetId); - SendIRIToAddress(packet->systemAddress, curSetId); -} -void FileListTransfer::RemoveFromList(FileToPushRecipient *ftpr) -{ - fileToPushRecipientListMutex.Lock(); - for (unsigned int i=0; i < fileToPushRecipientList.Size(); i++) - { - if (fileToPushRecipientList[i]==ftpr) - { - fileToPushRecipientList.RemoveAtIndex(i); - // List no longer references - ftpr->Deref(); - fileToPushRecipientListMutex.Unlock(); - return; - } - } - fileToPushRecipientListMutex.Unlock(); -} -unsigned int FileListTransfer::GetPendingFilesToAddress(SystemAddress recipient) -{ - fileToPushRecipientListMutex.Lock(); - for (unsigned int i=0; i < fileToPushRecipientList.Size(); i++) - { - if (fileToPushRecipientList[i]->systemAddress==recipient) - { - unsigned int size = fileToPushRecipientList[i]->filesToPush.Size(); - fileToPushRecipientListMutex.Unlock(); - return size; - } - } - fileToPushRecipientListMutex.Unlock(); - - return 0; -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/FileOperations.cpp b/vendors/mafianet/Source/src/FileOperations.cpp deleted file mode 100644 index 4c826391b..000000000 --- a/vendors/mafianet/Source/src/FileOperations.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/FileOperations.h" -#if _RAKNET_SUPPORT_FileOperations==1 -#include "mafianet/memoryoverride.h" -#include "mafianet/_FindFirst.h" // For linux -#include -#include -#ifdef _WIN32 -// For mkdir -#include -#include -#else -#include -#include -#include "mafianet/_FindFirst.h" -#endif -#include "errno.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -#ifndef MAX_PATH -#define MAX_PATH 260 -#endif - -bool WriteFileWithDirectories( const char *path, char *data, unsigned dataLength ) -{ - int index; - FILE *fp; - char pathCopy[MAX_PATH]; - int res; - - if ( path == 0 || path[ 0 ] == 0 ) - return false; - - strcpy_s( pathCopy, path ); - - // Ignore first / if there is one - if (pathCopy[0]) - { - index = 1; - while ( pathCopy[ index ] ) - { - if ( pathCopy[ index ] == '/' || pathCopy[ index ] == '\\') - { - pathCopy[ index ] = 0; - - #ifdef _WIN32 - res = _mkdir( pathCopy ); - #else - - res = mkdir( pathCopy, 0744 ); - #endif - if (res<0 && errno!=EEXIST && errno!=EACCES) - { - return false; - } - - pathCopy[ index ] = '/'; - } - - index++; - } - } - - if (data) - { - if ( fopen_s( &fp, path, "wb" ) != 0 ) - { - return false; - } - - fwrite( data, 1, dataLength, fp ); - - fclose( fp ); - } - else - { -#ifdef _WIN32 - res = _mkdir( pathCopy ); -#else - res = mkdir( pathCopy, 0744 ); -#endif - - if (res<0 && errno!=EEXIST) - { - return false; - } - } - - return true; -} -bool IsSlash(unsigned char c) -{ - return c=='/' || c=='\\'; -} - -void AddSlash( char *input ) -{ - if (input==0 || input[0]==0) - return; - - int lastCharIndex=(int) strlen(input)-1; - if (input[lastCharIndex]=='\\') - input[lastCharIndex]='/'; - else if (input[lastCharIndex]!='/') - { - input[lastCharIndex+1]='/'; - input[lastCharIndex+2]=0; - } -} -bool DirectoryExists(const char *directory) -{ - _finddata_t fileInfo; - intptr_t dir; - char baseDirWithStars[560]; - strcpy_s(baseDirWithStars, directory); - AddSlash(baseDirWithStars); - strcat_s(baseDirWithStars, "*.*"); - dir=_findfirst(baseDirWithStars, &fileInfo ); - if (dir==-1) - return false; - _findclose(dir); - return true; -} -void QuoteIfSpaces(char *str) -{ - unsigned i; - bool hasSpace=false; - for (i=0; str[i]; i++) - { - if (str[i]==' ') - { - hasSpace=true; - break; - } - } - if (hasSpace) - { - int len=(int)strlen(str); - memmove(str+1, str, len); - str[0]='\"'; - str[len]='\"'; - str[len+1]=0; - } -} -unsigned int GetFileLength(const char *path) -{ - FILE *fp; - if (fopen_s(&fp, path, "rb")!=0) return 0; - fseek(fp, 0, SEEK_END); - unsigned int fileLength = ftell(fp); - fclose(fp); - return fileLength; - -} - -#endif // _RAKNET_SUPPORT_FileOperations diff --git a/vendors/mafianet/Source/src/FormatString.cpp b/vendors/mafianet/Source/src/FormatString.cpp deleted file mode 100644 index afc5d60d2..000000000 --- a/vendors/mafianet/Source/src/FormatString.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/FormatString.h" -#include -#include -#include -#include "mafianet/LinuxStrings.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -char * FormatString(const char *format, ...) -{ - static int textIndex=0; - static char text[4][8096]; - va_list ap; - va_start(ap, format); - - if (++textIndex==4) - textIndex=0; - vsnprintf_s(text[textIndex], 8096, _TRUNCATE, format, ap); - va_end(ap); - - return text[textIndex]; -} - -char * FormatStringTS(char *output, const char *format, ...) -{ - va_list ap; - va_start(ap, format); - vsnprintf_s(output, 512, _TRUNCATE, format, ap); - va_end(ap); - return output; -} diff --git a/vendors/mafianet/Source/src/FullyConnectedMesh2.cpp b/vendors/mafianet/Source/src/FullyConnectedMesh2.cpp deleted file mode 100644 index e22d1fe64..000000000 --- a/vendors/mafianet/Source/src/FullyConnectedMesh2.cpp +++ /dev/null @@ -1,1429 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// - - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_FullyConnectedMesh2==1 - -#include "mafianet/FullyConnectedMesh2.h" -#include "mafianet/peerinterface.h" -#include "mafianet/guid_util.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/assert.h" -#include "mafianet/GetTime.h" -#include "mafianet/Rand.h" -#include "mafianet/DS_OrderedList.h" - -using namespace MafiaNet; - -int FCM2ParticipantComp( FullyConnectedMesh2::FCM2Participant * const &key, FullyConnectedMesh2::FCM2Participant * const &data ) -{ - if (key->fcm2Guid < data->fcm2Guid) - return -1; - if (key->fcm2Guid > data->fcm2Guid) - return 1; - return 0; -} - -STATIC_FACTORY_DEFINITIONS(FullyConnectedMesh2,FullyConnectedMesh2); - -FullyConnectedMesh2::FullyConnectedMesh2() -{ - startupTime=0; - totalConnectionCount=0; - ourFCMGuid=0; - autoParticipateConnections=true; - - - - - connectOnNewRemoteConnections=true; - - hostRakNetGuid=UNASSIGNED_RAKNET_GUID; -} -FullyConnectedMesh2::~FullyConnectedMesh2() -{ - Clear(); -} -RakNetGUID FullyConnectedMesh2::GetConnectedHost(void) const -{ - if (ourFCMGuid==0) - return UNASSIGNED_RAKNET_GUID; - return hostRakNetGuid; -} -SystemAddress FullyConnectedMesh2::GetConnectedHostAddr(void) const -{ - if (ourFCMGuid==0) - return UNASSIGNED_SYSTEM_ADDRESS; - return rakPeerInterface->GetSystemAddressFromGuid(hostRakNetGuid); -} -RakNetGUID FullyConnectedMesh2::GetHostSystem(void) const -{ - if (ourFCMGuid==0) - return rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); - - return hostRakNetGuid; -} -bool FullyConnectedMesh2::IsHostSystem(void) const -{ - return GetHostSystem()==rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); -} -void FullyConnectedMesh2::GetHostOrder(DataStructures::List &hostList) -{ - hostList.Clear(true, _FILE_AND_LINE_); - - if (ourFCMGuid==0 || fcm2ParticipantList.Size()==0) - { - hostList.Push(rakPeerInterface->GetMyGUID(), _FILE_AND_LINE_); - return; - } - - FCM2Participant fcm2; - fcm2.fcm2Guid=ourFCMGuid; - fcm2.rakNetGuid=rakPeerInterface->GetMyGUID(); - - DataStructures::OrderedList olist; - olist.Insert(&fcm2, &fcm2, true, _FILE_AND_LINE_); - for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) - olist.Insert(fcm2ParticipantList[i], fcm2ParticipantList[i], true, _FILE_AND_LINE_); - - for (unsigned int i=0; i < olist.Size(); i++) - { - hostList.Push(olist[i]->rakNetGuid, _FILE_AND_LINE_); - } -} -bool FullyConnectedMesh2::IsConnectedHost(void) const -{ - return GetConnectedHost()==rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); -} -void FullyConnectedMesh2::SetAutoparticipateConnections(bool b) -{ - autoParticipateConnections=b; -} -void FullyConnectedMesh2::ResetHostCalculation(void) -{ - hostRakNetGuid=UNASSIGNED_RAKNET_GUID; - startupTime= MafiaNet::GetTimeUS(); - totalConnectionCount=0; - ourFCMGuid=0; - for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) - SendFCMGuidRequest(fcm2ParticipantList[i]->rakNetGuid); -} -// bool FullyConnectedMesh2::AddParticipantInternal( RakNetGUID rakNetGuid, FCM2Guid theirFCMGuid, BitStream *userContext ) -bool FullyConnectedMesh2::AddParticipantInternal( RakNetGUID rakNetGuid, FCM2Guid theirFCMGuid ) -{ - for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) - { - if (fcm2ParticipantList[i]->rakNetGuid==rakNetGuid) - { - if (theirFCMGuid!=0) - fcm2ParticipantList[i]->fcm2Guid=theirFCMGuid; - /* - fcm2ParticipantList[i]->userContext.Reset(); - if (userContext) - { - userContext->ResetReadPointer(); - fcm2ParticipantList[i]->userContext.Write(userContext); - } - */ - return false; - } - } - - FCM2Participant *participant = MafiaNet::OP_NEW(_FILE_AND_LINE_); - participant->rakNetGuid=rakNetGuid; - participant->fcm2Guid=theirFCMGuid; - /* - if (userContext) - { - userContext->ResetReadPointer(); - participant->userContext.Write(userContext); - } - */ - fcm2ParticipantList.Push(participant,_FILE_AND_LINE_); - - SendFCMGuidRequest(rakNetGuid); - - return true; -} -void FullyConnectedMesh2::AddParticipant( RakNetGUID rakNetGuid ) -{ - if (rakPeerInterface->GetConnectionState(rakPeerInterface->GetSystemAddressFromGuid(rakNetGuid))!=IS_CONNECTED) - { -#ifdef DEBUG_FCM2 - printf("AddParticipant to %s failed (not connected)\n", to_string(rakNetGuid).c_str()); -#endif - return; - } - - // Need to query other system for userdata before calling AddParticipantInternal - // But maybe I can call with no data, and piggyback on ID_FCM2_REQUEST_FCMGUID - //AddParticipantInternal(rakNetGuid,0,0); - AddParticipantInternal(rakNetGuid,0); -} -void FullyConnectedMesh2::GetParticipantList(DataStructures::List &participantList) -{ - participantList.Clear(true, _FILE_AND_LINE_); - unsigned int i; - for (i=0; i < fcm2ParticipantList.Size(); i++) - participantList.Push(fcm2ParticipantList[i]->rakNetGuid, _FILE_AND_LINE_); -} -bool FullyConnectedMesh2::HasParticipant(RakNetGUID participantGuid) -{ - unsigned int i; - for (i=0; i < fcm2ParticipantList.Size(); i++) - { - if (fcm2ParticipantList[i]->rakNetGuid==participantGuid) - return true; - } - return false; -} -/* -bool FullyConnectedMesh2::GetParticipantContext(RakNetGUID participantGuid, BitStream *userContext) -{ - unsigned int i; - for (i=0; i < fcm2ParticipantList.Size(); i++) - { - if (fcm2ParticipantList[i]->rakNetGuid==participantGuid) - { - if (fcm2ParticipantList[i]->userContext.GetNumberOfBitsUsed() > 0) - { - userContext->Write(fcm2ParticipantList[i]->userContext); - fcm2ParticipantList[i]->userContext.ResetReadPointer(); - return true; - } - return false; - } - } - return false; -} -void FullyConnectedMesh2::SetMyContext(BitStream *userContext) -{ - if (userContext==0) - { - if (myContext.GetNumberOfBitsUsed()==0) - return; - myContext.Reset(); - } - else - { - myContext.Write(userContext); - userContext->ResetReadPointer(); - } - - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_FCM2_UPDATE_USER_CONTEXT); - bsOut.Write(myContext); - myContext.ResetReadPointer(); - - unsigned int idx; - for (idx=0; idx < fcm2ParticipantList.Size(); idx++) - { - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,fcm2ParticipantList[idx]->rakNetGuid,false); - } -} -*/ -PluginReceiveResult FullyConnectedMesh2::OnReceive(Packet *packet) -{ - switch (packet->data[0]) - { - case ID_REMOTE_NEW_INCOMING_CONNECTION: - { - if (connectOnNewRemoteConnections) - ConnectToRemoteNewIncomingConnections(packet); - } - break; - case ID_FCM2_REQUEST_FCMGUID: - OnRequestFCMGuid(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - //case ID_FCM2_UPDATE_USER_CONTEXT: - // OnUpdateUserContext(packet); - // return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_FCM2_RESPOND_CONNECTION_COUNT: - OnRespondConnectionCount(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_FCM2_INFORM_FCMGUID: - OnInformFCMGuid(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_FCM2_UPDATE_MIN_TOTAL_CONNECTION_COUNT: - OnUpdateMinTotalConnectionCount(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_FCM2_NEW_HOST: - if (packet->wasGeneratedLocally==false) - return RR_STOP_PROCESSING_AND_DEALLOCATE; - break; - case ID_FCM2_VERIFIED_JOIN_START: - return OnVerifiedJoinStart(packet); - case ID_FCM2_VERIFIED_JOIN_CAPABLE: - return OnVerifiedJoinCapable(packet); - case ID_FCM2_VERIFIED_JOIN_FAILED: - OnVerifiedJoinFailed(packet->guid, true); - return RR_CONTINUE_PROCESSING; - case ID_FCM2_VERIFIED_JOIN_ACCEPTED: - if (packet->wasGeneratedLocally==false) - OnVerifiedJoinAccepted(packet); - return RR_CONTINUE_PROCESSING; - case ID_FCM2_VERIFIED_JOIN_REJECTED: - OnVerifiedJoinRejected(packet); - return RR_CONTINUE_PROCESSING; - - case ID_NAT_TARGET_UNRESPONSIVE: - case ID_NAT_TARGET_NOT_CONNECTED: - case ID_NAT_CONNECTION_TO_TARGET_LOST: - { - MafiaNet::RakNetGUID g; - MafiaNet::BitStream b(packet->data, packet->length, false); - b.IgnoreBits(8); // Ignore the ID_... - b.Read(g); - UpdateVerifiedJoinInProgressMember(g, UNASSIGNED_RAKNET_GUID, JIPS_FAILED); - return RR_CONTINUE_PROCESSING; - } - case ID_NAT_PUNCHTHROUGH_FAILED: - UpdateVerifiedJoinInProgressMember(packet->guid, UNASSIGNED_RAKNET_GUID, JIPS_FAILED); - return RR_CONTINUE_PROCESSING; - } - - return RR_CONTINUE_PROCESSING; -} -void FullyConnectedMesh2::OnRakPeerStartup(void) -{ - Clear(); - startupTime= MafiaNet::GetTimeUS(); -} -void FullyConnectedMesh2::OnAttach(void) -{ - Clear(); - // In case Startup() was called first - if (rakPeerInterface->IsActive()) - startupTime= MafiaNet::GetTimeUS(); -} -void FullyConnectedMesh2::OnRakPeerShutdown(void) -{ - Clear(); - startupTime=0; -} -void FullyConnectedMesh2::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) lostConnectionReason; - (void) systemAddress; - (void) rakNetGUID; - - unsigned int idx; - idx=0; - while (idx < joinsInProgress.Size()) - { - if (joinsInProgress[idx]->requester==rakNetGUID) - { - Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(unsigned char)); - p->data[0]=ID_FCM2_VERIFIED_JOIN_FAILED; - p->systemAddress=systemAddress; - p->systemAddress.systemIndex=(SystemIndex)-1; - p->guid=rakNetGUID; - p->wasGeneratedLocally=true; - rakPeerInterface->PushBackPacket(p, true); - - for (unsigned int j=0; j < joinsInProgress[idx]->vjipMembers.Size(); j++) - { - if ( joinsInProgress[idx]->vjipMembers[j].userData != 0) - { - MafiaNet::OP_DELETE(joinsInProgress[idx]->vjipMembers[j].userData, _FILE_AND_LINE_); - } - } - - MafiaNet::OP_DELETE(joinsInProgress[idx], _FILE_AND_LINE_); - joinsInProgress.RemoveAtIndex(idx); - } - else - { - idx++; - } - } - - UpdateVerifiedJoinInProgressMember(rakNetGUID, UNASSIGNED_RAKNET_GUID, JIPS_FAILED); - - for (idx=0; idx < fcm2ParticipantList.Size(); idx++) - { - if (fcm2ParticipantList[idx]->rakNetGuid==rakNetGUID) - { - fcm2ParticipantList[idx]=fcm2ParticipantList[fcm2ParticipantList.Size()-1]; -#ifdef DEBUG_FCM2 - printf("Popping participant %s\n", to_string(fcm2ParticipantList[fcm2ParticipantList.Size()-1]->rakNetGuid).c_str()); -#endif - - fcm2ParticipantList.Pop(); - if (rakNetGUID==hostRakNetGuid && ourFCMGuid!=0) - { - if (fcm2ParticipantList.Size()==0) - { - hostRakNetGuid=rakPeerInterface->GetMyGUID(); - hostFCM2Guid=ourFCMGuid; - } - else - { - CalculateHost(&hostRakNetGuid, &hostFCM2Guid); - } - PushNewHost(hostRakNetGuid, rakNetGUID); - } - return; - } - } - -} -MafiaNet::TimeUS FullyConnectedMesh2::GetElapsedRuntime(void) -{ - MafiaNet::TimeUS curTime= MafiaNet::GetTimeUS(); - if (curTime>startupTime) - return curTime-startupTime; - else - return 0; -} -void FullyConnectedMesh2::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) -{ - (void) isIncoming; - (void) rakNetGUID; - (void) systemAddress; - - UpdateVerifiedJoinInProgressMember(rakNetGUID, rakNetGUID, JIPS_CONNECTED); - - if (autoParticipateConnections) - AddParticipant(rakNetGUID); -} -void FullyConnectedMesh2::OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason) -{ - if (failedConnectionAttemptReason==FCAR_ALREADY_CONNECTED) - { - UpdateVerifiedJoinInProgressMember(packet->guid, packet->guid, JIPS_CONNECTED); - } - else - { - UpdateVerifiedJoinInProgressMember(packet->systemAddress, UNASSIGNED_RAKNET_GUID, JIPS_FAILED); - } -} -void FullyConnectedMesh2::Clear(void) -{ - for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) - { - MafiaNet::OP_DELETE(fcm2ParticipantList[i], _FILE_AND_LINE_); - } - fcm2ParticipantList.Clear(false, _FILE_AND_LINE_); - - for (unsigned int i=0; i < joinsInProgress.Size(); i++) - { - for (unsigned int j=0; j < joinsInProgress[i]->vjipMembers.Size(); j++) - { - if ( joinsInProgress[i]->vjipMembers[j].userData != 0) - { - MafiaNet::OP_DELETE(joinsInProgress[i]->vjipMembers[j].userData, _FILE_AND_LINE_); - } - } - - MafiaNet::OP_DELETE(joinsInProgress[i], _FILE_AND_LINE_); - } - joinsInProgress.Clear(true, _FILE_AND_LINE_); - - totalConnectionCount=0; - ourFCMGuid=0; - lastPushedHost=UNASSIGNED_RAKNET_GUID; -} -void FullyConnectedMesh2::PushNewHost(const RakNetGUID &guid, RakNetGUID oldHost) -{ - Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(oldHost)); - MafiaNet::BitStream bs(p->data,p->length,false); - bs.SetWriteOffset(0); - bs.Write((MessageID)ID_FCM2_NEW_HOST); - bs.Write(oldHost); - p->systemAddress=rakPeerInterface->GetSystemAddressFromGuid(guid); - p->systemAddress.systemIndex=(SystemIndex)-1; - p->guid=guid; - p->wasGeneratedLocally=true; - rakPeerInterface->PushBackPacket(p, true); - - lastPushedHost=guid; -} -void FullyConnectedMesh2::SendFCMGuidRequest(RakNetGUID rakNetGuid) -{ - if (rakNetGuid==rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)) - return; - - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_FCM2_REQUEST_FCMGUID); - if (ourFCMGuid==0) - { - bsOut.Write(false); - bsOut.Write(GetElapsedRuntime()); - } - else - { - bsOut.Write(true); - bsOut.Write(totalConnectionCount); - bsOut.Write(ourFCMGuid); - } - bsOut.Write(myContext); - myContext.ResetReadPointer(); - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,rakNetGuid,false); -} -void FullyConnectedMesh2::SendOurFCMGuid(SystemAddress addr) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_FCM2_INFORM_FCMGUID); - RakAssert(ourFCMGuid!=0); // Can't inform others of our FCM2Guid if it's unset! - bsOut.Write(ourFCMGuid); - bsOut.Write(totalConnectionCount); - bsOut.Write(myContext); - myContext.ResetReadPointer(); - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,addr,false); -} -void FullyConnectedMesh2::SendConnectionCountResponse(SystemAddress addr, unsigned int responseTotalConnectionCount) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_FCM2_RESPOND_CONNECTION_COUNT); - bsOut.Write(responseTotalConnectionCount); - //bsOut.Write(myContext); - //myContext.ResetReadPointer(); - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,addr,false); -} -void FullyConnectedMesh2::AssignOurFCMGuid(void) -{ - // Only assigned once ever - RakAssert(ourFCMGuid==0); - unsigned int randomNumber = randomMT(); - randomNumber ^= (unsigned int) (MafiaNet::GetTimeUS() & 0xFFFFFFFF); - randomNumber ^= (unsigned int) (rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS).g & 0xFFFFFFFF); - ourFCMGuid |= randomNumber; - uint64_t reponse64 = totalConnectionCount; - ourFCMGuid |= reponse64<<32; -} -void FullyConnectedMesh2::CalculateHost(RakNetGUID *rakNetGuid, FCM2Guid *fcm2Guid) -{ - // Can't calculate host without knowing our own - RakAssert(ourFCMGuid!=0); - - // Can't calculate host without being connected to anyone else - RakAssert(fcm2ParticipantList.Size()>0); - - // Return the lowest value of all FCM2Guid - FCM2Guid lowestFCMGuid=ourFCMGuid; - // SystemAddress associatedSystemAddress=UNASSIGNED_SYSTEM_ADDRESS; - RakNetGUID associatedRakNetGuid=rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); - - unsigned int idx; - for (idx=0; idx < fcm2ParticipantList.Size(); idx++) - { - if (fcm2ParticipantList[idx]->fcm2Guid!=0 && fcm2ParticipantList[idx]->fcm2Guidfcm2Guid; - associatedRakNetGuid=fcm2ParticipantList[idx]->rakNetGuid; - } - } - - *rakNetGuid=associatedRakNetGuid; - *fcm2Guid=lowestFCMGuid; -} -void FullyConnectedMesh2::OnRequestFCMGuid(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(sizeof(MessageID)); - bool hasRemoteFCMGuid=false; - bsIn.Read(hasRemoteFCMGuid); - MafiaNet::TimeUS senderElapsedRuntime=0; - unsigned int remoteTotalConnectionCount=0; - FCM2Guid theirFCMGuid=0; - if (hasRemoteFCMGuid) - { - bsIn.Read(remoteTotalConnectionCount); - bsIn.Read(theirFCMGuid); - } - else - { - bsIn.Read(senderElapsedRuntime); - } - /* - BitStream remoteContext; - bsIn.Read(remoteContext); - AddParticipantInternal(packet->guid,theirFCMGuid, &remoteContext); - */ - AddParticipantInternal(packet->guid,theirFCMGuid); - if (ourFCMGuid==0) - { - if (hasRemoteFCMGuid==false) - { - // Nobody has a fcmGuid - - MafiaNet::TimeUS ourElapsedRuntime = GetElapsedRuntime(); - if (ourElapsedRuntime>senderElapsedRuntime) - { - // We are probably host - SendConnectionCountResponse(packet->systemAddress, 2); - } - else - { - // They are probably host - SendConnectionCountResponse(packet->systemAddress, 1); - } - } - else - { - // They have a fcmGuid, we do not - IncrementTotalConnectionCount(remoteTotalConnectionCount+1); - - AssignOurFCMGuid(); - unsigned int idx; - for (idx=0; idx < fcm2ParticipantList.Size(); idx++) - SendOurFCMGuid(rakPeerInterface->GetSystemAddressFromGuid(fcm2ParticipantList[idx]->rakNetGuid)); - } - } - else - { - if (hasRemoteFCMGuid==false) - { - // We have a fcmGuid they do not - SendConnectionCountResponse(packet->systemAddress, totalConnectionCount+1); - } - else - { - // We both have fcmGuids - IncrementTotalConnectionCount(remoteTotalConnectionCount); - - SendOurFCMGuid(packet->systemAddress); - } - } - CalculateAndPushHost(); -} -/* -void FullyConnectedMesh2::OnUpdateUserContext(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(sizeof(MessageID)); - BitStream remoteContext; - bsIn.Read(remoteContext); - - for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) - { - if (fcm2ParticipantList[i]->rakNetGuid==packet->guid) - { - fcm2ParticipantList[i]->userContext.Reset(); - remoteContext.Read(fcm2ParticipantList[i]->userContext); - break; - } - } -} -*/ -void FullyConnectedMesh2::OnRespondConnectionCount(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(sizeof(MessageID)); - unsigned int responseTotalConnectionCount; - bsIn.Read(responseTotalConnectionCount); - /* - BitStream remoteContext; - bsIn.Read(remoteContext); - - for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) - { - if (fcm2ParticipantList[i]->rakNetGuid==packet->guid) - { - fcm2ParticipantList[i]->userContext.Reset(); - remoteContext.Read(fcm2ParticipantList[i]->userContext); - break; - } - } - */ - - IncrementTotalConnectionCount(responseTotalConnectionCount); - bool wasAssigned; - if (ourFCMGuid==0) - { - wasAssigned=true; - AssignOurFCMGuid(); - } - else - wasAssigned=false; - - // 1 is returned to give us lower priority, but the actual minimum is 2 - IncrementTotalConnectionCount(2); - - if (wasAssigned==true) - { - unsigned int idx; - for (idx=0; idx < fcm2ParticipantList.Size(); idx++) - SendOurFCMGuid(rakPeerInterface->GetSystemAddressFromGuid(fcm2ParticipantList[idx]->rakNetGuid)); - CalculateAndPushHost(); - } -} -void FullyConnectedMesh2::OnInformFCMGuid(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(sizeof(MessageID)); - - FCM2Guid theirFCMGuid; - unsigned int theirTotalConnectionCount; - bsIn.Read(theirFCMGuid); - bsIn.Read(theirTotalConnectionCount); - - BitStream remoteContext; - bsIn.Read(remoteContext); - - IncrementTotalConnectionCount(theirTotalConnectionCount); - - //if (AddParticipantInternal(packet->guid,theirFCMGuid, &remoteContext)) - if (AddParticipantInternal(packet->guid,theirFCMGuid)) - { - // 1/19/2010 - Relay increased total connection count in case new participant only connects to part of the mesh - unsigned int idx; - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_FCM2_UPDATE_MIN_TOTAL_CONNECTION_COUNT); - bsOut.Write(totalConnectionCount); - for (idx=0; idx < fcm2ParticipantList.Size(); idx++) - { - if (packet->guid!=fcm2ParticipantList[idx]->rakNetGuid) - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,fcm2ParticipantList[idx]->rakNetGuid,false); - } - } - - if (ourFCMGuid==0) - { - AssignOurFCMGuid(); - unsigned int idx; - for (idx=0; idx < fcm2ParticipantList.Size(); idx++) - SendOurFCMGuid(rakPeerInterface->GetSystemAddressFromGuid(fcm2ParticipantList[idx]->rakNetGuid)); - } - - CalculateAndPushHost(); -} -void FullyConnectedMesh2::OnUpdateMinTotalConnectionCount(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(sizeof(MessageID)); - unsigned int newMin; - bsIn.Read(newMin); - IncrementTotalConnectionCount(newMin); -} -void FullyConnectedMesh2::GetParticipantCount(unsigned int *participantListSize) const -{ - *participantListSize=fcm2ParticipantList.Size(); -} - -unsigned int FullyConnectedMesh2::GetParticipantCount(void) const -{ - return fcm2ParticipantList.Size(); -} -void FullyConnectedMesh2::CalculateAndPushHost(void) -{ - RakNetGUID newHostGuid; - FCM2Guid newFcmGuid; - if (ParticipantListComplete()) - { - CalculateHost(&newHostGuid, &newFcmGuid); - if (newHostGuid!=lastPushedHost) - { - hostRakNetGuid=newHostGuid; - hostFCM2Guid=newFcmGuid; - PushNewHost(hostRakNetGuid, lastPushedHost); - } - } -} -bool FullyConnectedMesh2::ParticipantListComplete(void) -{ - for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) - { - if (fcm2ParticipantList[i]->fcm2Guid==0) - return false; - } - return true; -} -void FullyConnectedMesh2::IncrementTotalConnectionCount(unsigned int i) -{ - if (i>totalConnectionCount) - { - totalConnectionCount=i; - // printf("totalConnectionCount=%i\n",i); - } -} -void FullyConnectedMesh2::SetConnectOnNewRemoteConnection(bool attemptConnection, MafiaNet::RakString pw) -{ - connectOnNewRemoteConnections=attemptConnection; - connectionPassword=pw; -} - -void FullyConnectedMesh2::ConnectToRemoteNewIncomingConnections(Packet *packet) -{ - unsigned int count; - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)); - bsIn.Read(count); - SystemAddress remoteAddress; - RakNetGUID remoteGuid; - char str[64]; - for (unsigned int i=0; i < count; i++) - { - bsIn.Read(remoteAddress); - bsIn.Read(remoteGuid); - remoteAddress.ToString(false,str,static_cast(64)); - rakPeerInterface->Connect(str,remoteAddress.GetPort(),connectionPassword.C_String(),(int) connectionPassword.GetLength()); - } -} -unsigned int FullyConnectedMesh2::GetTotalConnectionCount(void) const -{ - return totalConnectionCount; -} -void FullyConnectedMesh2::StartVerifiedJoin(RakNetGUID client) -{ - // Assert is because there is no point calling StartVerifiedJoin() if this client is already a participant - RakAssert(HasParticipant(client)==false); - RakAssert(client!=rakPeerInterface->GetMyGUID()); - - BitStream bsOut; - bsOut.Write((MessageID) ID_FCM2_VERIFIED_JOIN_START); - bsOut.WriteCasted(fcm2ParticipantList.Size()); - unsigned int i; - for (i=0; i < fcm2ParticipantList.Size(); i++) - { - bsOut.Write(fcm2ParticipantList[i]->rakNetGuid); - bsOut.Write(rakPeerInterface->GetSystemAddressFromGuid(fcm2ParticipantList[i]->rakNetGuid)); - - BitStream vjsOut; - //WriteVJSUserData(&vjsOut, fcm2ParticipantList[i]->rakNetGuid, &fcm2ParticipantList[i]->userContext ); - WriteVJSUserData(&vjsOut, fcm2ParticipantList[i]->rakNetGuid ); - bsOut.Write(vjsOut.GetNumberOfBitsUsed()); - bsOut.Write(&vjsOut); - bsOut.AlignWriteToByteBoundary(); - } - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, client, false); -} -void FullyConnectedMesh2::RespondOnVerifiedJoinCapable(Packet *packet, bool accept, BitStream *additionalData) -{ - VerifiedJoinInProgress vjip; - DecomposeJoinCapable(packet, &vjip); - - DataStructures::List participatingMembersOnClientSucceeded; - DataStructures::List participatingMembersOnClientFailed; - DataStructures::List participatingMembersNotOnClient; - DataStructures::List clientMembersNotParticipatingSucceeded; - DataStructures::List clientMembersNotParticipatingFailed; - CategorizeVJIP(&vjip, - participatingMembersOnClientSucceeded, - participatingMembersOnClientFailed, - participatingMembersNotOnClient, - clientMembersNotParticipatingSucceeded, - clientMembersNotParticipatingFailed); - - if (participatingMembersNotOnClient.Size()>0) - { - BitStream bsOut; - bsOut.Write((MessageID) ID_FCM2_VERIFIED_JOIN_START); - bsOut.WriteCasted(participatingMembersNotOnClient.Size()); - unsigned int i; - for (i=0; i < participatingMembersNotOnClient.Size(); i++) - { - bsOut.Write(participatingMembersNotOnClient[i]); - bsOut.Write(rakPeerInterface->GetSystemAddressFromGuid(participatingMembersNotOnClient[i])); - - bool written=false; - for (unsigned int j=0; j < fcm2ParticipantList.Size(); j++) - { - if (fcm2ParticipantList[j]->rakNetGuid == participatingMembersNotOnClient[i]) - { - written=true; - - BitStream vjsOut; - //WriteVJSUserData(&vjsOut, fcm2ParticipantList[j]->rakNetGuid, &fcm2ParticipantList[j]->userContext ); - WriteVJSUserData(&vjsOut, fcm2ParticipantList[j]->rakNetGuid ); - bsOut.Write(vjsOut.GetNumberOfBitsUsed()); - bsOut.Write(&vjsOut); - bsOut.AlignWriteToByteBoundary(); - break; - } - } - RakAssert(written==true); - } - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, packet->guid, false); - return; - } - - RakAssert(participatingMembersOnClientFailed.Size()==0); - RakAssert(participatingMembersNotOnClient.Size()==0); - - MafiaNet::BitStream bsOut; - if (accept) - { - bsOut.Write((MessageID)ID_FCM2_VERIFIED_JOIN_ACCEPTED); - bsOut.Write(packet->guid); - - // Tell client to disconnect from clientMembersNotParticipatingSucceeded - bsOut.WriteCasted(clientMembersNotParticipatingSucceeded.Size()); - for (unsigned int i=0; i < clientMembersNotParticipatingSucceeded.Size(); i++) - bsOut.Write(clientMembersNotParticipatingSucceeded[i]); - - // Tell client to call AddParticipant() for participatingMembersOnClientSucceeded - bsOut.WriteCasted(participatingMembersOnClientSucceeded.Size()); - for (unsigned int i=0; i < participatingMembersOnClientSucceeded.Size(); i++) - bsOut.Write(participatingMembersOnClientSucceeded[i]); - - if (additionalData) - bsOut.Write(additionalData); - - for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, fcm2ParticipantList[i]->rakNetGuid, false); - - // Process immediately - // This is so if another ID_FCM2_VERIFIED_JOIN_CAPABLE is buffered, it responds with ID_FCM2_VERIFIED_JOIN_START - AddParticipant(packet->guid); - - Packet *p = AllocatePacketUnified(bsOut.GetNumberOfBytesUsed()); - memcpy(p->data, bsOut.GetData(), bsOut.GetNumberOfBytesUsed()); - p->systemAddress=packet->systemAddress; - p->systemAddress.systemIndex=(SystemIndex)-1; - p->guid=packet->guid; - p->wasGeneratedLocally=true; - rakPeerInterface->PushBackPacket(p, true); - } - else - { - // Tell client rejected, otherwise process the same as ID_FCM2_VERIFIED_JOIN_FAILED - bsOut.Write((MessageID)ID_FCM2_VERIFIED_JOIN_REJECTED); - if (additionalData) - bsOut.Write(additionalData); - } - - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, packet->guid, false); -} -void FullyConnectedMesh2::GetVerifiedJoinRequiredProcessingList(RakNetGUID host, DataStructures::List &addresses, DataStructures::List &guids, DataStructures::List &userData) -{ - addresses.Clear(true, _FILE_AND_LINE_); - guids.Clear(true, _FILE_AND_LINE_); - - unsigned int curIndex = GetJoinsInProgressIndex(host); - if (curIndex!=(unsigned int) -1) - { - VerifiedJoinInProgress *vjip = joinsInProgress[curIndex]; - unsigned int j; - for (j=0; j < vjip->vjipMembers.Size(); j++) - { - if (vjip->vjipMembers[j].joinInProgressState==JIPS_PROCESSING) - { - addresses.Push(vjip->vjipMembers[j].systemAddress, _FILE_AND_LINE_); - guids.Push(vjip->vjipMembers[j].guid, _FILE_AND_LINE_); - userData.Push(vjip->vjipMembers[j].userData, _FILE_AND_LINE_); - } - } - } -} -void FullyConnectedMesh2::GetVerifiedJoinAcceptedAdditionalData(Packet *packet, bool *thisSystemAccepted, DataStructures::List &systemsAccepted, BitStream *additionalData) -{ - systemsAccepted.Clear(true, _FILE_AND_LINE_); - - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)); - RakNetGUID systemToAddGuid; - bsIn.Read(systemToAddGuid); - *thisSystemAccepted = systemToAddGuid == rakPeerInterface->GetMyGUID(); - unsigned short listSize; - bsIn.Read(listSize); - bsIn.IgnoreBytes(listSize*RakNetGUID::size()); - bsIn.Read(listSize); - if (systemToAddGuid==rakPeerInterface->GetMyGUID()) - { - for (unsigned short i=0; i < listSize; i++) - { - bsIn.Read(systemToAddGuid); - systemsAccepted.Push(systemToAddGuid, _FILE_AND_LINE_); - } - systemsAccepted.Push(packet->guid, _FILE_AND_LINE_); - } - else - { - systemsAccepted.Push(systemToAddGuid, _FILE_AND_LINE_); - bsIn.IgnoreBytes(listSize*RakNetGUID::size()); - } - if (additionalData) - { - additionalData->Reset(); - additionalData->Write(bsIn); - } -} -void FullyConnectedMesh2::GetVerifiedJoinRejectedAdditionalData(Packet *packet, BitStream *additionalData) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)); - if (additionalData) - { - additionalData->Reset(); - additionalData->Write(bsIn); - } -} -PluginReceiveResult FullyConnectedMesh2::OnVerifiedJoinStart(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(sizeof(MessageID)); - - unsigned short listSize; - bsIn.Read(listSize); - - unsigned int curIndex = GetJoinsInProgressIndex(packet->guid); - if (curIndex!=(unsigned int) -1) - { - // Got update to existing list - - VerifiedJoinInProgress *vjip = joinsInProgress[curIndex]; -// if (vjip->sentResults==false) -// { -// // Got ID_FCM2_VERIFIED_JOIN_START twice before sending ID_FCM2_VERIFIED_JOIN_CAPABLE -// RakAssert(vjip->sentResults!=false); -// return RR_STOP_PROCESSING_AND_DEALLOCATE; -// } - - for (unsigned int i=0; i < vjip->vjipMembers.Size(); i++) - { - vjip->vjipMembers[i].workingFlag=false; - } - - // Server has updated list of participants - for (unsigned short i=0; i < listSize; i++) - { - VerifiedJoinInProgressMember vjipm; - ReadVerifiedJoinInProgressMember(&bsIn, &vjipm); - - unsigned int j; - if (vjipm.guid!=UNASSIGNED_RAKNET_GUID) - j = GetVerifiedJoinInProgressMemberIndex(vjipm.guid, vjip); - else - j = GetVerifiedJoinInProgressMemberIndex(vjipm.systemAddress, vjip); - - if (j==(unsigned int)-1) - { - // New - vjipm.workingFlag=true; - - // 11/13/2013 - ReadVerifiedJoinInProgressMember already sets joinInProgressState - // http://www.jenkinssoftware.com/forum/index.php?topic=5211.0 - // vjipm.joinInProgressState=JIPS_PROCESSING; - vjip->vjipMembers.Push(vjipm, _FILE_AND_LINE_); - - // Allow resend of ID_FCM2_VERIFIED_JOIN_CAPABLE - //vjip->sentResults=false; - } - else - { - vjip->vjipMembers[j].workingFlag=true; - } - } - - for (unsigned int i=0; i < vjip->vjipMembers.Size(); i++) - { - if (vjip->vjipMembers[i].workingFlag==false) - vjip->vjipMembers[i].joinInProgressState=JIPS_UNNECESSARY; - } - - if (ProcessVerifiedJoinInProgressIfCompleted(vjip)) - { - // Completed - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - - // Else tell user about new list - return RR_CONTINUE_PROCESSING; - } - - VerifiedJoinInProgress *vjip = MafiaNet::OP_NEW(_FILE_AND_LINE_); - vjip->requester=packet->guid; - if (listSize==0) - { - //vjip->sentResults=true; - - // Send back result - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_FCM2_VERIFIED_JOIN_CAPABLE); - bsOut.WriteCasted(0); - WriteVJCUserData(&bsOut); - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, packet->guid, false); - //vjip->sentResults=true; - joinsInProgress.Push(vjip, _FILE_AND_LINE_); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - - //vjip->sentResults=false; - - for (unsigned short i=0; i < listSize; i++) - { - VerifiedJoinInProgressMember vjipm; - ReadVerifiedJoinInProgressMember(&bsIn, &vjipm); - vjip->vjipMembers.Push(vjipm, _FILE_AND_LINE_); - } - - joinsInProgress.Push(vjip, _FILE_AND_LINE_); - - // 11/13/2013 - ReadVerifiedJoinInProgressMember may set JIPS_CONNECTED, so this may already be done - // http://www.jenkinssoftware.com/forum/index.php?topic=5211.0 - if (ProcessVerifiedJoinInProgressIfCompleted(vjip)) - { - // Completed - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - - return RR_CONTINUE_PROCESSING; -} -void FullyConnectedMesh2::SkipToVJCUserData(MafiaNet::BitStream *bsIn) -{ - bsIn->IgnoreBytes(sizeof(MessageID)); - unsigned short listSize; - bsIn->Read(listSize); - for (unsigned short i=0; i < listSize; i++) - { - bsIn->IgnoreBytes(RakNetGUID::size()); - bsIn->IgnoreBytes(SystemAddress::size()); - bsIn->IgnoreBytes(sizeof(unsigned char)); - } -} -void FullyConnectedMesh2::DecomposeJoinCapable(Packet *packet, VerifiedJoinInProgress *vjip) -{ - MafiaNet::BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(sizeof(MessageID)); - - unsigned short listSize; - bsIn.Read(listSize); - - for (unsigned short i=0; i < listSize; i++) - { - VerifiedJoinInProgressMember member; - bsIn.Read(member.guid); - bsIn.Read(member.systemAddress); - bsIn.ReadCasted(member.joinInProgressState); - member.userData = 0; - member.workingFlag=false; - vjip->vjipMembers.Push(member, _FILE_AND_LINE_); - } -} -PluginReceiveResult FullyConnectedMesh2::OnVerifiedJoinCapable(Packet *packet) -{ - VerifiedJoinInProgress vjip; - DecomposeJoinCapable(packet, &vjip); - - // If this assert hits, AddParticipant() was called on this system, or another system, which it should not have been. - RakAssert(HasParticipant(packet->guid)==false); - - DataStructures::List participatingMembersOnClientSucceeded; - DataStructures::List participatingMembersOnClientFailed; - DataStructures::List participatingMembersNotOnClient; - DataStructures::List clientMembersNotParticipatingSucceeded; - DataStructures::List clientMembersNotParticipatingFailed; - CategorizeVJIP(&vjip, - participatingMembersOnClientSucceeded, - participatingMembersOnClientFailed, - participatingMembersNotOnClient, - clientMembersNotParticipatingSucceeded, - clientMembersNotParticipatingFailed); - - if (participatingMembersOnClientFailed.Size()>0) - { - // Send ID_FCM2_VERIFIED_JOIN_FAILED with GUIDs to disconnect - BitStream bsOut; - bsOut.Write((MessageID) ID_FCM2_VERIFIED_JOIN_FAILED); - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, packet->guid, false); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - - if (participatingMembersNotOnClient.Size()>0) - { - BitStream bsOut; - bsOut.Write((MessageID) ID_FCM2_VERIFIED_JOIN_START); - bsOut.WriteCasted(participatingMembersNotOnClient.Size()); - unsigned int i; - for (i=0; i < participatingMembersNotOnClient.Size(); i++) - { - bsOut.Write(participatingMembersNotOnClient[i]); - bsOut.Write(rakPeerInterface->GetSystemAddressFromGuid(participatingMembersNotOnClient[i])); - - bool written=false; - for (unsigned int j=0; j < fcm2ParticipantList.Size(); j++) - { - if (fcm2ParticipantList[j]->rakNetGuid == participatingMembersNotOnClient[i]) - { - written=true; - - BitStream vjsOut; - //WriteVJSUserData(&vjsOut, fcm2ParticipantList[j]->rakNetGuid, &fcm2ParticipantList[j]->userContext ); - WriteVJSUserData(&vjsOut, fcm2ParticipantList[j]->rakNetGuid ); - bsOut.Write(vjsOut.GetNumberOfBitsUsed()); - bsOut.Write(&vjsOut); - bsOut.AlignWriteToByteBoundary(); - break; - } - } - RakAssert(written); - } - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, packet->guid, false); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - - // Let server decide if to accept or reject via RespondOnVerifiedJoinCapable - return RR_CONTINUE_PROCESSING; -} -void FullyConnectedMesh2::OnVerifiedJoinFailed(RakNetGUID hostGuid, bool callCloseConnection) -{ - unsigned int curIndex = GetJoinsInProgressIndex(hostGuid); - if (curIndex==(unsigned int) -1) - return; - - if (callCloseConnection) - { - VerifiedJoinInProgress *vjip = joinsInProgress[curIndex]; - for (unsigned int j=0; j < vjip->vjipMembers.Size(); j++) - { - if (vjip->vjipMembers[j].joinInProgressState!=JIPS_FAILED) - { - rakPeerInterface->CloseConnection(vjip->vjipMembers[j].guid, true); - } - - if (vjip->vjipMembers[j].userData != 0) - MafiaNet::OP_DELETE(vjip->vjipMembers[j].userData, _FILE_AND_LINE_); - } - } - - for (unsigned int j=0; j < joinsInProgress[curIndex]->vjipMembers.Size(); j++) - { - if ( joinsInProgress[curIndex]->vjipMembers[j].userData != 0) - { - MafiaNet::OP_DELETE(joinsInProgress[curIndex]->vjipMembers[j].userData, _FILE_AND_LINE_); - } - } - - - // Clear joinsInProgress for packet->guid - MafiaNet::OP_DELETE(joinsInProgress[curIndex], _FILE_AND_LINE_); - joinsInProgress.RemoveAtIndex(curIndex); -} -void FullyConnectedMesh2::OnVerifiedJoinAccepted(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(sizeof(MessageID)); - - RakNetGUID systemToAddGuid; - bsIn.Read(systemToAddGuid); - - if (systemToAddGuid==rakPeerInterface->GetMyGUID()) - { - // My own system - unsigned int curIndex = GetJoinsInProgressIndex(packet->guid); - if (curIndex==(unsigned int)-1) - return; - - unsigned short listSize; - bsIn.Read(listSize); - for (unsigned short i=0; i < listSize; i++) - { - // List of clientMembersNotParticipatingSucceeded - RakNetGUID guid; - bsIn.Read(guid); - rakPeerInterface->CloseConnection(guid, true); - } - - bsIn.Read(listSize); - for (unsigned short i=0; i < listSize; i++) - { - // List of participatingMembersOnClientSucceeded - RakNetGUID guid; - bsIn.Read(guid); - AddParticipant(guid); - } - AddParticipant(packet->guid); - - for (unsigned int j=0; j < joinsInProgress[curIndex]->vjipMembers.Size(); j++) - { - if ( joinsInProgress[curIndex]->vjipMembers[j].userData != 0) - { - MafiaNet::OP_DELETE(joinsInProgress[curIndex]->vjipMembers[j].userData, _FILE_AND_LINE_); - } - } - - // Clear joinsInProgress for packet->guid - MafiaNet::OP_DELETE(joinsInProgress[curIndex], _FILE_AND_LINE_); - joinsInProgress.RemoveAtIndex(curIndex); - } - else - { - // Another system - ConnectionState cs = rakPeerInterface->GetConnectionState(systemToAddGuid); - RakAssert(cs==IS_CONNECTED); - if (cs==IS_CONNECTED) - AddParticipant(systemToAddGuid); - } -} -void FullyConnectedMesh2::OnVerifiedJoinRejected(Packet *packet) -{ - OnVerifiedJoinFailed(packet->guid, true); -} -unsigned int FullyConnectedMesh2::GetJoinsInProgressIndex(RakNetGUID requester) const -{ - for (unsigned int i=0; i < joinsInProgress.Size(); i++) - { - if (joinsInProgress[i]->requester==requester) - return i; - } - return (unsigned int) -1; -} -void FullyConnectedMesh2::UpdateVerifiedJoinInProgressMember(const AddressOrGUID systemIdentifier, RakNetGUID guidToAssign, FullyConnectedMesh2::JoinInProgressState newState) -{ - bool anythingChanged; - - for (unsigned int i=0; i < joinsInProgress.Size(); i++) - { - VerifiedJoinInProgress *vjip = joinsInProgress[i]; - //if (vjip->sentResults==true) - // continue; - anythingChanged=false; - - unsigned int j; - j = GetVerifiedJoinInProgressMemberIndex(systemIdentifier, vjip); - if (j!=(unsigned int)-1) - { - if (vjip->vjipMembers[j].guid==UNASSIGNED_RAKNET_GUID && guidToAssign!=UNASSIGNED_RAKNET_GUID) - vjip->vjipMembers[j].guid = guidToAssign; - - if (vjip->vjipMembers[j].joinInProgressState==JIPS_PROCESSING) - { - anythingChanged=true; - vjip->vjipMembers[j].joinInProgressState=newState; - } - } - - if (anythingChanged) - { - ProcessVerifiedJoinInProgressIfCompleted(vjip); - } - } -} -bool FullyConnectedMesh2::ProcessVerifiedJoinInProgressIfCompleted(VerifiedJoinInProgress *vjip) -{ - //if (vjip->sentResults) - // return true; - - // If no systems in processing state, send results to server - // Return true if this was done - bool anyProcessing=false; - for (unsigned int i=0; i < vjip->vjipMembers.Size(); i++) - { - if (vjip->vjipMembers[i].joinInProgressState==JIPS_PROCESSING) - { - anyProcessing=true; - break; - } - } - - if (anyProcessing==true) - return false; - - // Send results to server - BitStream bsOut; - WriteVerifiedJoinCapable(&bsOut, vjip); - WriteVJCUserData(&bsOut); - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, vjip->requester, false); - - //vjip->sentResults=true; - return true; -} -void FullyConnectedMesh2::WriteVerifiedJoinCapable(MafiaNet::BitStream *bsOut, VerifiedJoinInProgress *vjip) -{ - bsOut->Write((MessageID) ID_FCM2_VERIFIED_JOIN_CAPABLE); - bsOut->WriteCasted(vjip->vjipMembers.Size()); - unsigned int i; - for (i=0; i < vjip->vjipMembers.Size(); i++) - { - bsOut->Write(vjip->vjipMembers[i].guid); - bsOut->Write(vjip->vjipMembers[i].systemAddress); - bsOut->WriteCasted(vjip->vjipMembers[i].joinInProgressState); - } -} - -void FullyConnectedMesh2::ReadVerifiedJoinInProgressMember(MafiaNet::BitStream *bsIn, VerifiedJoinInProgressMember *vjipm) -{ - bsIn->Read(vjipm->guid); - bsIn->Read(vjipm->systemAddress); - ConnectionState cs = rakPeerInterface->GetConnectionState(vjipm->guid); - if (cs==IS_CONNECTED) - vjipm->joinInProgressState=JIPS_CONNECTED; - else if (cs==IS_DISCONNECTING || cs==IS_SILENTLY_DISCONNECTING) - vjipm->joinInProgressState=JIPS_FAILED; - else - vjipm->joinInProgressState=JIPS_PROCESSING; - - BitSize_t vjsUserDataSize; - bsIn->Read(vjsUserDataSize); - if (vjsUserDataSize > 0) - { - vjipm->userData = MafiaNet::OP_NEW(_FILE_AND_LINE_); - bsIn->Read(vjipm->userData, vjsUserDataSize); - } - else - vjipm->userData = 0; - bsIn->AlignReadToByteBoundary(); -} - -unsigned int FullyConnectedMesh2::GetVerifiedJoinInProgressMemberIndex(const AddressOrGUID systemIdentifier, VerifiedJoinInProgress *vjip) -{ - for (unsigned int j=0; j < vjip->vjipMembers.Size(); j++) - { - if ((systemIdentifier.rakNetGuid!=UNASSIGNED_RAKNET_GUID && vjip->vjipMembers[j].guid==systemIdentifier.rakNetGuid) || - (systemIdentifier.systemAddress!=UNASSIGNED_SYSTEM_ADDRESS && vjip->vjipMembers[j].systemAddress==systemIdentifier.systemAddress)) - { - return j; - } - } - return (unsigned int) -1; -} - -void FullyConnectedMesh2::CategorizeVJIP(VerifiedJoinInProgress *vjip, - DataStructures::List &participatingMembersOnClientSucceeded, - DataStructures::List &participatingMembersOnClientFailed, - DataStructures::List &participatingMembersNotOnClient, - DataStructures::List &clientMembersNotParticipatingSucceeded, - DataStructures::List &clientMembersNotParticipatingFailed) -{ - for (unsigned int i=0; i < vjip->vjipMembers.Size(); i++) - vjip->vjipMembers[i].workingFlag=false; - - for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) - { - unsigned int j = GetVerifiedJoinInProgressMemberIndex(fcm2ParticipantList[i]->rakNetGuid, vjip); - if (j==(unsigned int)-1) - { - participatingMembersNotOnClient.Push(fcm2ParticipantList[i]->rakNetGuid, _FILE_AND_LINE_); - } - else - { - if (vjip->vjipMembers[j].joinInProgressState==JIPS_FAILED) - participatingMembersOnClientFailed.Push(fcm2ParticipantList[i]->rakNetGuid, _FILE_AND_LINE_); - else - participatingMembersOnClientSucceeded.Push(fcm2ParticipantList[i]->rakNetGuid, _FILE_AND_LINE_); - vjip->vjipMembers[j].workingFlag=true; - } - } - - - for (unsigned int j=0; j < vjip->vjipMembers.Size(); j++) - { - if (vjip->vjipMembers[j].workingFlag==false) - { - if (vjip->vjipMembers[j].joinInProgressState==JIPS_FAILED) - clientMembersNotParticipatingFailed.Push(vjip->vjipMembers[j].guid, _FILE_AND_LINE_); - else - clientMembersNotParticipatingSucceeded.Push(vjip->vjipMembers[j].guid, _FILE_AND_LINE_); - } - } -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/GetTime.cpp b/vendors/mafianet/Source/src/GetTime.cpp deleted file mode 100644 index 772a733c6..000000000 --- a/vendors/mafianet/Source/src/GetTime.cpp +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// - - -#if defined(_WIN32) -#include "mafianet/WindowsIncludes.h" -// To call timeGetTime -// on Code::Blocks, this needs to be libwinmm.a instead -#pragma comment(lib, "Winmm.lib") - -#endif - -#include "mafianet/GetTime.h" - - - - -#if defined(_WIN32) -//DWORD mProcMask; -//DWORD mSysMask; -//HANDLE mThread; - - - - - - - - - -#else -#include -#include -MafiaNet::TimeUS initialTime; -#endif - -static bool initialized=false; - -#if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 -#include "mafianet/SimpleMutex.h" -MafiaNet::TimeUS lastNormalizedReturnedValue=0; -MafiaNet::TimeUS lastNormalizedInputValue=0; -/// This constraints timer forward jumps to 1 second, and does not let it jump backwards -/// See http://support.microsoft.com/kb/274323 where the timer can sometimes jump forward by hours or days -/// This also has the effect where debugging a sending system won't treat the time spent halted past 1 second as elapsed network time -MafiaNet::TimeUS NormalizeTime(MafiaNet::TimeUS timeIn) -{ - MafiaNet::TimeUS diff, lastNormalizedReturnedValueCopy; - static MafiaNet::SimpleMutex mutex; - - mutex.Lock(); - if (timeIn>=lastNormalizedInputValue) - { - diff = timeIn-lastNormalizedInputValue; - if (diff > GET_TIME_SPIKE_LIMIT) - lastNormalizedReturnedValue+=GET_TIME_SPIKE_LIMIT; - else - lastNormalizedReturnedValue+=diff; - } - else - lastNormalizedReturnedValue+=GET_TIME_SPIKE_LIMIT; - - lastNormalizedInputValue=timeIn; - lastNormalizedReturnedValueCopy=lastNormalizedReturnedValue; - mutex.Unlock(); - - return lastNormalizedReturnedValueCopy; -} -#endif // #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 -MafiaNet::Time MafiaNet::GetTime( void ) -{ - return (MafiaNet::Time)(GetTimeUS()/1000); -} -MafiaNet::TimeMS MafiaNet::GetTimeMS( void ) -{ - return (MafiaNet::TimeMS)(GetTimeUS()/1000); -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#if defined(_WIN32) -MafiaNet::TimeUS GetTimeUS_Windows( void ) -{ - if ( initialized == false) - { - initialized = true; - - // Save the current process -// HANDLE mProc = GetCurrentProcess(); - - // Get the current Affinity -#if defined (_M_X64) -// GetProcessAffinityMask(mProc, (PDWORD_PTR)&mProcMask, (PDWORD_PTR)&mSysMask); -#else -// GetProcessAffinityMask(mProc, &mProcMask, &mSysMask); -#endif -// mThread = GetCurrentThread(); - } - - // 9/26/2010 In China running LuDaShi, QueryPerformanceFrequency has to be called every time because CPU clock speeds can be different - MafiaNet::TimeUS curTime; - LARGE_INTEGER PerfVal; - LARGE_INTEGER yo1; - - QueryPerformanceFrequency( &yo1 ); - QueryPerformanceCounter( &PerfVal ); - - __int64 quotient, remainder; - quotient=((PerfVal.QuadPart) / yo1.QuadPart); - remainder=((PerfVal.QuadPart) % yo1.QuadPart); - curTime = (MafiaNet::TimeUS) quotient*(MafiaNet::TimeUS)1000000 + (remainder*(MafiaNet::TimeUS)1000000 / yo1.QuadPart); - -#if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 - return NormalizeTime(curTime); -#else - return curTime; -#endif // #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 -} -#elif defined(__GNUC__) || defined(__GCCXML__) || defined(__S3E__) -MafiaNet::TimeUS GetTimeUS_Linux( void ) -{ - timeval tp; - if ( initialized == false) - { - gettimeofday( &tp, 0 ); - initialized=true; - // I do this because otherwise MafiaNet::Time in milliseconds won't work as it will underflow when dividing by 1000 to do the conversion - initialTime = ( tp.tv_sec ) * (MafiaNet::TimeUS) 1000000 + ( tp.tv_usec ); - } - - // GCC - MafiaNet::TimeUS curTime; - gettimeofday( &tp, 0 ); - - curTime = ( tp.tv_sec ) * (MafiaNet::TimeUS) 1000000 + ( tp.tv_usec ); - -#if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 - return NormalizeTime(curTime - initialTime); -#else - return curTime - initialTime; -#endif // #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 -} -#endif - -MafiaNet::TimeUS MafiaNet::GetTimeUS( void ) -{ - - - - - - -#if defined(_WIN32) - return GetTimeUS_Windows(); -#else - return GetTimeUS_Linux(); -#endif -} -bool MafiaNet::GreaterThan(MafiaNet::Time a, MafiaNet::Time b) -{ - // a > b? - const MafiaNet::Time halfSpan =(MafiaNet::Time) (((MafiaNet::Time)(const MafiaNet::Time)-1)/(MafiaNet::Time)2); - return b!=a && b-a>halfSpan; -} -bool MafiaNet::LessThan(MafiaNet::Time a, MafiaNet::Time b) -{ - // a < b? - const MafiaNet::Time halfSpan = ((MafiaNet::Time)(const MafiaNet::Time)-1)/(MafiaNet::Time)2; - return b!=a && b-a /* _getche() */ -#elif defined(__S3E__) - -#else - -#include "mafianet/Getche.h" - -char _getche() -{ - - - struct termios oldt, - newt; - char ch; - tcgetattr( STDIN_FILENO, &oldt ); - newt = oldt; - newt.c_lflag &= ~( ICANON | ECHO ); - tcsetattr( STDIN_FILENO, TCSANOW, &newt ); - ch = getchar(); - tcsetattr( STDIN_FILENO, TCSANOW, &oldt ); - return ch; - -} -#endif diff --git a/vendors/mafianet/Source/src/Gets.cpp b/vendors/mafianet/Source/src/Gets.cpp deleted file mode 100644 index ae658a8af..000000000 --- a/vendors/mafianet/Source/src/Gets.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - */ - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -char * Gets ( char * str, int num ) -{ - fgets(str, num, stdin); - if (str[0]=='\n' || str[0]=='\r') - str[0]=0; - - size_t len=strlen(str); - if (len>0 && (str[len-1]=='\n' || str[len-1]=='\r')) - str[len-1]=0; - if (len>1 && (str[len-2]=='\n' || str[len-2]=='\r')) - str[len-2]=0; - - return str; -} - -#ifdef __cplusplus -} -#endif diff --git a/vendors/mafianet/Source/src/GridSectorizer.cpp b/vendors/mafianet/Source/src/GridSectorizer.cpp deleted file mode 100644 index 0080bc28b..000000000 --- a/vendors/mafianet/Source/src/GridSectorizer.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/assert.h" -#include "mafianet/GridSectorizer.h" -//#include -#include - -GridSectorizer::GridSectorizer() -{ - grid=0; -} -GridSectorizer::~GridSectorizer() -{ - if (grid) - MafiaNet::OP_DELETE_ARRAY(grid, _FILE_AND_LINE_); -} -void GridSectorizer::Init(const float _maxCellWidth, const float _maxCellHeight, const float minX, const float minY, const float maxX, const float maxY) -{ - RakAssert(_maxCellWidth > 0.0f && _maxCellHeight > 0.0f); - if (grid) - MafiaNet::OP_DELETE_ARRAY(grid, _FILE_AND_LINE_); - - cellOriginX=minX; - cellOriginY=minY; - gridWidth=maxX-minX; - gridHeight=maxY-minY; - gridCellWidthCount=(int) ceil(gridWidth/_maxCellWidth); - gridCellHeightCount=(int) ceil(gridHeight/_maxCellHeight); - // Make the cells slightly smaller, so we allocate an extra unneeded cell if on the edge. This way we don't go outside the array on rounding errors. - cellWidth=gridWidth/gridCellWidthCount; - cellHeight=gridHeight/gridCellHeightCount; - invCellWidth = 1.0f / cellWidth; - invCellHeight = 1.0f / cellHeight; - -#ifdef _USE_ORDERED_LIST - grid = MafiaNet::OP_NEW>(gridCellWidthCount*gridCellHeightCount, _FILE_AND_LINE_ ); - DataStructures::OrderedList::IMPLEMENT_DEFAULT_COMPARISON(); -#else - grid = MafiaNet::OP_NEW_ARRAY >(gridCellWidthCount*gridCellHeightCount, _FILE_AND_LINE_ ); -#endif -} -void GridSectorizer::AddEntry(void *entry, const float minX, const float minY, const float maxX, const float maxY) -{ - RakAssert(cellWidth>0.0f); - RakAssert(minX < maxX && minY < maxY); - - int xStart, yStart, xEnd, yEnd, xCur, yCur; - xStart=WorldToCellXOffsetAndClamped(minX); - yStart=WorldToCellYOffsetAndClamped(minY); - xEnd=WorldToCellXOffsetAndClamped(maxX); - yEnd=WorldToCellYOffsetAndClamped(maxY); - - for (xCur=xStart; xCur <= xEnd; ++xCur) - { - for (yCur=yStart; yCur <= yEnd; ++yCur) - { -#ifdef _USE_ORDERED_LIST - grid[yCur*gridCellWidthCount+xCur].Insert(entry,entry, true); -#else - grid[yCur*gridCellWidthCount+xCur].Insert(entry, _FILE_AND_LINE_); -#endif - } - } -} -#ifdef _USE_ORDERED_LIST -void GridSectorizer::RemoveEntry(void *entry, const float minX, const float minY, const float maxX, const float maxY) -{ - RakAssert(cellWidth>0.0f); - RakAssert(minX <= maxX && minY <= maxY); - - int xStart, yStart, xEnd, yEnd, xCur, yCur; - xStart=WorldToCellXOffsetAndClamped(minX); - yStart=WorldToCellYOffsetAndClamped(minY); - xEnd=WorldToCellXOffsetAndClamped(maxX); - yEnd=WorldToCellYOffsetAndClamped(maxY); - - for (xCur=xStart; xCur <= xEnd; ++xCur) - { - for (yCur=yStart; yCur <= yEnd; ++yCur) - { - grid[yCur*gridCellWidthCount+xCur].RemoveIfExists(entry); - } - } -} -void GridSectorizer::MoveEntry(void *entry, const float sourceMinX, const float sourceMinY, const float sourceMaxX, const float sourceMaxY, - const float destMinX, const float destMinY, const float destMaxX, const float destMaxY) -{ - RakAssert(cellWidth>0.0f); - RakAssert(sourceMinX < sourceMaxX && sourceMinY < sourceMaxY); - RakAssert(destMinX < destMaxX && destMinY < destMaxY); - - if (PositionCrossesCells(sourceMinX, sourceMinY, destMinX, destMinY)==false && - PositionCrossesCells(destMinX, destMinY, destMinX, destMinY)==false) - return; - - int xStartSource, yStartSource, xEndSource, yEndSource; - int xStartDest, yStartDest, xEndDest, yEndDest; - int xCur, yCur; - xStartSource=WorldToCellXOffsetAndClamped(sourceMinX); - yStartSource=WorldToCellYOffsetAndClamped(sourceMinY); - xEndSource=WorldToCellXOffsetAndClamped(sourceMaxX); - yEndSource=WorldToCellYOffsetAndClamped(sourceMaxY); - - xStartDest=WorldToCellXOffsetAndClamped(destMinX); - yStartDest=WorldToCellYOffsetAndClamped(destMinY); - xEndDest=WorldToCellXOffsetAndClamped(destMaxX); - yEndDest=WorldToCellYOffsetAndClamped(destMaxY); - - // Remove source that is not in dest - for (xCur=xStartSource; xCur <= xEndSource; ++xCur) - { - for (yCur=yStartSource; yCur <= yEndSource; ++yCur) - { - if (xCur < xStartDest || xCur > xEndDest || - yCur < yStartDest || yCur > yEndDest) - { - grid[yCur*gridCellWidthCount+xCur].RemoveIfExists(entry); - } - } - } - - // Add dest that is not in source - for (xCur=xStartDest; xCur <= xEndDest; ++xCur) - { - for (yCur=yStartDest; yCur <= yEndDest; ++yCur) - { - if (xCur < xStartSource || xCur > xEndSource || - yCur < yStartSource || yCur > yEndSource) - { - grid[yCur*gridCellWidthCount+xCur].Insert(entry,entry, true); - } - } - } -} -#endif -void GridSectorizer::GetEntries(DataStructures::List& intersectionList, const float minX, const float minY, const float maxX, const float maxY) -{ -#ifdef _USE_ORDERED_LIST - DataStructures::OrderedList* cell; -#else - DataStructures::List* cell; -#endif - int xStart, yStart, xEnd, yEnd, xCur, yCur; - unsigned index; - xStart=WorldToCellXOffsetAndClamped(minX); - yStart=WorldToCellYOffsetAndClamped(minY); - xEnd=WorldToCellXOffsetAndClamped(maxX); - yEnd=WorldToCellYOffsetAndClamped(maxY); - - intersectionList.Clear(true, _FILE_AND_LINE_); - for (xCur=xStart; xCur <= xEnd; ++xCur) - { - for (yCur=yStart; yCur <= yEnd; ++yCur) - { - cell = grid+yCur*gridCellWidthCount+xCur; - for (index=0; index < cell->Size(); ++index) - intersectionList.Insert(cell->operator [](index), _FILE_AND_LINE_); - } - } -} -bool GridSectorizer::PositionCrossesCells(const float originX, const float originY, const float destinationX, const float destinationY) const -{ - return originX/cellWidth!=destinationX/cellWidth || originY/cellHeight!=destinationY/cellHeight; -} -int GridSectorizer::WorldToCellX(const float input) const -{ - return (int)((input-cellOriginX)*invCellWidth); -} -int GridSectorizer::WorldToCellY(const float input) const -{ - return (int)((input-cellOriginY)*invCellHeight); -} -int GridSectorizer::WorldToCellXOffsetAndClamped(const float input) const -{ - int cell=WorldToCellX(input); - cell = cell > 0 ? cell : 0; // __max(cell,0); - cell = gridCellWidthCount-1 < cell ? gridCellWidthCount-1 : cell; // __min(gridCellWidthCount-1, cell); - return cell; -} -int GridSectorizer::WorldToCellYOffsetAndClamped(const float input) const -{ - int cell=WorldToCellY(input); - cell = cell > 0 ? cell : 0; // __max(cell,0); - cell = gridCellHeightCount-1 < cell ? gridCellHeightCount-1 : cell; // __min(gridCellHeightCount-1, cell); - return cell; -} -void GridSectorizer::Clear(void) -{ - int cur; - int count = gridCellWidthCount*gridCellHeightCount; - for (cur=0; cur -#include -#include -#include - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(HTTPConnection,HTTPConnection); - -HTTPConnection::HTTPConnection() : connectionState(CS_NONE) -{ - tcp=0; -} - -void HTTPConnection::Init(TCPInterface* _tcp, const char *_host, unsigned short _port) -{ - tcp=_tcp; - host=_host; - port=_port; -} - -void HTTPConnection::Post(const char *remote_path, const char *data, const char *_contentType) -{ - OutgoingCommand op; - op.contentType=_contentType; - op.data=data; - op.remotePath=remote_path; - op.isPost=true; - outgoingCommand.Push(op, _FILE_AND_LINE_ ); - //printf("Adding outgoing post\n"); -} - -void HTTPConnection::Get(const char *path) -{ - OutgoingCommand op; - op.remotePath=path; - op.isPost=false; - outgoingCommand.Push(op, _FILE_AND_LINE_ ); -} - -bool HTTPConnection::HasBadResponse(int *code, MafiaNet::RakString *data) -{ - if(badResponses.IsEmpty()) - return false; - - if (code) - *code = badResponses.Peek().code; - if (data) - *data = badResponses.Pop().data; - return true; -} -void HTTPConnection::CloseConnection() -{ - connectionState=CS_DISCONNECTING; -} -void HTTPConnection::Update(void) -{ - SystemAddress sa; - sa = tcp->HasCompletedConnectionAttempt(); - while (sa!=UNASSIGNED_SYSTEM_ADDRESS) - { -// printf("Connected\n"); - connectionState=CS_CONNECTED; - server=sa; - sa = tcp->HasCompletedConnectionAttempt(); - } - - sa = tcp->HasFailedConnectionAttempt(); - while (sa!=UNASSIGNED_SYSTEM_ADDRESS) - { - //printf("Failed connected\n"); - CloseConnection(); - sa = tcp->HasFailedConnectionAttempt(); - } - - sa = tcp->HasLostConnection(); - while (sa!=UNASSIGNED_SYSTEM_ADDRESS) - { - //printf("Lost connection\n"); - CloseConnection(); - sa = tcp->HasLostConnection(); - } - - - switch (connectionState) - { - case CS_NONE: - { - if (outgoingCommand.IsEmpty()) - return; - - //printf("Connecting\n"); - server = tcp->Connect(host, port, false); - connectionState = CS_CONNECTING; - } - break; - case CS_DISCONNECTING: - { - if (tcp->ReceiveHasPackets()==false) - { - if (incomingData.IsEmpty()==false) - { - results.Push(incomingData, _FILE_AND_LINE_ ); - } - incomingData.Clear(); - tcp->CloseConnection(server); - connectionState=CS_NONE; - } - } - break; - case CS_CONNECTING: - { - } - break; - case CS_CONNECTED: - { - //printf("Connected\n"); - if (outgoingCommand.IsEmpty()) - { - //printf("Closed connection (nothing to do)\n"); - CloseConnection(); - return; - } - -#if OPEN_SSL_CLIENT_SUPPORT==1 - tcp->StartSSLClient(server); -#endif - - //printf("Sending request\n"); - currentProcessingCommand = outgoingCommand.Pop(); - RakString request; - if (currentProcessingCommand.isPost) - { - request.Set("POST %s HTTP/1.0\r\n" - "Host: %s:%i\r\n" - "Content-Type: %s\r\n" - "Content-Length: %u\r\n" - "\r\n" - "%s", - currentProcessingCommand.remotePath.C_String(), - host.C_String(), - port, - currentProcessingCommand.contentType.C_String(), - (unsigned) currentProcessingCommand.data.GetLength(), - currentProcessingCommand.data.C_String()); - } - else - { - // request.Set("GET %s\r\n", host.C_String()); - // http://www.jenkinssoftware.com/forum/index.php?topic=4601.0;topicseen - request.Set("GET %s HTTP/1.0\r\n" - "Host: %s:%i\r\n" - "\r\n", - currentProcessingCommand.remotePath.C_String(), - host.C_String(), - port); - } - - // printf(request.C_String()); - // request.URLEncode(); - tcp->Send(request.C_String(), (unsigned int) request.GetLength(), server,false); - connectionState=CS_PROCESSING; - } - break; - case CS_PROCESSING: - { - } - } - -// if (connectionState==CS_PROCESSING && currentProcessingCommand.data.IsEmpty()==false) -// outgoingCommand.PushAtHead(currentProcessingCommand); -} -bool HTTPConnection::HasRead(void) const -{ - return results.IsEmpty()==false; -} -RakString HTTPConnection::Read(void) -{ - if (results.IsEmpty()) - return RakString(); - - MafiaNet::RakString resultStr = results.Pop(); - // const char *start_of_body = strstr(resultStr.C_String(), "\r\n\r\n"); - const char *start_of_body = strpbrk(resultStr.C_String(), "\001\002\003%"); - - if(start_of_body) - return MafiaNet::RakString::NonVariadic(start_of_body); - else - return resultStr; -} -SystemAddress HTTPConnection::GetServerAddress(void) const -{ - return server; -} -void HTTPConnection::ProcessTCPPacket(Packet *packet) -{ - RakAssert(packet); - - // read all the packets possible - if(packet->systemAddress == server) - { - if(incomingData.GetLength() == 0) - { - int response_code = atoi((char *)packet->data + strlen("HTTP/1.0 ")); - - if(response_code > 299) - { - badResponses.Push(BadResponse(packet->data, response_code), _FILE_AND_LINE_ ); - //printf("Closed connection (Bad response 2)\n"); - CloseConnection(); - return; - } - } - - MafiaNet::RakString incomingTemp = MafiaNet::RakString::NonVariadic((const char*) packet->data); - incomingTemp.URLDecode(); - incomingData += incomingTemp; - - // printf((const char*) packet->data); - // printf("\n"); - - RakAssert(strlen((char *)packet->data) == packet->length); // otherwise it contains Null bytes - - const char *start_of_body = strstr(incomingData, "\r\n\r\n"); - - // besides having the server close the connection, they may - // provide a length header and supply that many bytes - if( - // Why was start_of_body here? Makes the GET command fail - // start_of_body && - connectionState == CS_PROCESSING) - { - /* - // The stupid programmer that wrote this originally didn't think that just because the header contains this value doesn't mean you got the whole message - if (strstr((const char*) packet->data, "\r\nConnection: close\r\n")) - { - CloseConnection(); - } - else - { - */ - long length_of_headers; - if (start_of_body) - { - length_of_headers = (long)(start_of_body + 4 - incomingData.C_String()); - const char *length_header = strstr(incomingData, "\r\nLength: "); - - if(length_header) - { - long length = atol(length_header + 10) + length_of_headers; - - if((long) incomingData.GetLength() >= length) - { - //printf("Closed connection (Got all data due to length header)\n"); - CloseConnection(); - } - } - } - else - { - // No processing needed - } - - - //} - } - } -} - -bool HTTPConnection::IsBusy(void) const -{ - return connectionState != CS_NONE; -} - -int HTTPConnection::GetState(void) const -{ - return connectionState; -} - - -HTTPConnection::~HTTPConnection(void) -{ - if (tcp) - tcp->CloseConnection(server); -} - - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/HTTPConnection2.cpp b/vendors/mafianet/Source/src/HTTPConnection2.cpp deleted file mode 100644 index 5ac111a36..000000000 --- a/vendors/mafianet/Source/src/HTTPConnection2.cpp +++ /dev/null @@ -1,635 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_HTTPConnection2==1 && _RAKNET_SUPPORT_TCPInterface==1 - -#include "mafianet/HTTPConnection2.h" -#include "mafianet/TCPInterface.h" - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(HTTPConnection2,HTTPConnection2); - -HTTPConnection2::HTTPConnection2() -{ -} -HTTPConnection2::~HTTPConnection2() -{ - for (unsigned int i = 0; i < pendingRequests.Size(); ++i) { - MafiaNet::OP_DELETE(pendingRequests[i], _FILE_AND_LINE_); - } - for (unsigned int i = 0; i < sentRequests.Size(); ++i) { - MafiaNet::OP_DELETE(sentRequests[i], _FILE_AND_LINE_); - } - for (unsigned int i = 0; i < completedRequests.Size(); ++i) { - MafiaNet::OP_DELETE(completedRequests[i], _FILE_AND_LINE_); - } -} -bool HTTPConnection2::TransmitRequest(const char* stringToTransmit, const char* host, unsigned short port, bool useSSL, int ipVersion, SystemAddress useAddress, void *userData) -{ - Request *request = MafiaNet::OP_NEW(_FILE_AND_LINE_); - request->host=host; - request->chunked = false; - if (useAddress!=UNASSIGNED_SYSTEM_ADDRESS) - { - request->hostEstimatedAddress=useAddress; - if (IsConnected(useAddress)==false) - { - MafiaNet::OP_DELETE(request, _FILE_AND_LINE_); - return false; - } - } - else - { - // #med - this should be changed to not extract the port from the passed in host-address (which is overwritten directly below with the provided port anyway) - if (request->hostEstimatedAddress.FromString(host, '|', ipVersion)==false) - { - MafiaNet::OP_DELETE(request, _FILE_AND_LINE_); - return false; - } - } - request->hostEstimatedAddress.SetPortHostOrder(port); - request->port=port; - request->stringToTransmit=stringToTransmit; - request->contentLength=-1; - request->contentOffset=0; - request->useSSL=useSSL; - request->ipVersion=ipVersion; - request->userData=userData; - - if (IsConnected(request->hostEstimatedAddress)) - { - sentRequestsMutex.Lock(); - if (sentRequests.Size()==0) - { - request->hostCompletedAddress=request->hostEstimatedAddress; - sentRequests.Push(request, _FILE_AND_LINE_); - sentRequestsMutex.Unlock(); - - SendRequest(request); - } - else - { - // Request pending, push it - pendingRequestsMutex.Lock(); - pendingRequests.Push(request, _FILE_AND_LINE_); - pendingRequestsMutex.Unlock(); - - sentRequestsMutex.Unlock(); - } - } - else - { - pendingRequestsMutex.Lock(); - pendingRequests.Push(request, _FILE_AND_LINE_); - pendingRequestsMutex.Unlock(); - - if (ipVersion!=6) - { - tcpInterface->Connect(host, port, false, AF_INET); - } - else - { - #if RAKNET_SUPPORT_IPV6 - tcpInterface->Connect(host, port, false, AF_INET6); - #else - RakAssert("HTTPConnection2::TransmitRequest needs define RAKNET_SUPPORT_IPV6" && 0); - #endif - } - } - return true; -} -bool HTTPConnection2::GetResponse( RakString &stringTransmitted, RakString &hostTransmitted, RakString &responseReceived, SystemAddress &hostReceived, ptrdiff_t &contentOffset ) -{ - void *userData; - return GetResponse(stringTransmitted, hostTransmitted, responseReceived, hostReceived, contentOffset, &userData); - -} -bool HTTPConnection2::GetResponse( RakString &stringTransmitted, RakString &hostTransmitted, RakString &responseReceived, SystemAddress &hostReceived, ptrdiff_t &contentOffset, void **userData ) -{ - completedRequestsMutex.Lock(); - if (completedRequests.Size()>0) - { - Request *completedRequest = completedRequests[0]; - completedRequests.RemoveAtIndexFast(0); - completedRequestsMutex.Unlock(); - - responseReceived = completedRequest->stringReceived; - hostReceived = completedRequest->hostCompletedAddress; - stringTransmitted = completedRequest->stringToTransmit; - hostTransmitted = completedRequest->host; - contentOffset = completedRequest->contentOffset; - *userData = completedRequest->userData; - - MafiaNet::OP_DELETE(completedRequest, _FILE_AND_LINE_); - return true; - } - else - { - completedRequestsMutex.Unlock(); - } - return false; -} -bool HTTPConnection2::IsBusy(void) const -{ - return pendingRequests.Size()>0 || sentRequests.Size()>0; -} -bool HTTPConnection2::HasResponse(void) const -{ - return completedRequests.Size()>0; -} -int ReadChunkSize( char *txtStart, char **txtEnd ) -{ -// char lengthStr[32]; -// memset(lengthStr, 0, 32); -// memcpy(lengthStr, txtStart, txtEnd - txtStart); - return strtoul(txtStart, txtEnd,16); - // return atoi(lengthStr); -} -void ReadChunkBlock( size_t ¤tChunkSize, size_t &bytesReadSoFar, char *txtIn, RakString &txtOut) -{ - size_t bytesToRead; - size_t sLen; - - do - { - bytesToRead = currentChunkSize - bytesReadSoFar; - sLen = strlen(txtIn); - if (sLen < bytesToRead) - bytesToRead = sLen; - txtOut.AppendBytes(txtIn, bytesToRead); - txtIn += bytesToRead; - bytesReadSoFar += bytesToRead; - if (*txtIn == 0) - { - // currentChunkSize=0; - return; - } - // char *newLine = strstr(txtIn, "\r\n"); - if (txtIn[0] && txtIn[0]=='\r' && txtIn[1] && txtIn[1]=='\n' ) - txtIn += 2; // Newline - char *newLine; - currentChunkSize = ReadChunkSize(txtIn, &newLine); - RakAssert(currentChunkSize < 50000); // Sanity check - if (currentChunkSize == 0) - return; - if (newLine == 0) - return; - bytesReadSoFar=0; - txtIn = newLine + 2; - } while (txtIn); -} -PluginReceiveResult HTTPConnection2::OnReceive(Packet *packet) -{ - unsigned int i; - - bool locked=true; - sentRequestsMutex.Lock(); - for (i=0; i < sentRequests.Size(); i++) - { - Request *sentRequest = sentRequests[i]; - if (sentRequest->hostCompletedAddress==packet->systemAddress) - { - sentRequests.RemoveAtIndexFast(i); - locked=false; - sentRequestsMutex.Unlock(); - - /* - static FILE * pFile = 0; - if (pFile==0) - { - long lSize; - char * buffer; - size_t result; - - pFile = fopen ( "string_received.txt" , "rb" ); - if (pFile==nullptr) {fputs ("File error",stderr); exit (1);} - - // obtain file size: - fseek (pFile , 0 , SEEK_END); - lSize = ftell (pFile); - rewind (pFile); - - // allocate memory to contain the whole file: - buffer = (char*) malloc (sizeof(char)*lSize); - if (buffer == nullptr) {fputs ("Memory error",stderr); exit (2);} - - // copy the file into the buffer: - result = fread (buffer,1,lSize,pFile); - if (result != lSize) {fputs ("Reading error",stderr); exit (3);} - - packet->data=(unsigned char*) buffer; - packet->length=lSize; - } - */ - - - const char *isFirstChunk = strstr((char*) packet->data, "Transfer-Encoding: chunked"); - if (isFirstChunk) - { - //printf((char*) packet->data); - - locked=false; - sentRequestsMutex.Unlock(); - - sentRequest->chunked = true; - char *chunkStrStart = strstr((char*) packet->data, "\r\n\r\n"); - RakAssert(chunkStrStart); - - chunkStrStart += 4; // strlen("\r\n\r\n"); - char *body_header; // = strstr(chunkStrStart, "\r\n"); - sentRequest->thisChunkSize = ReadChunkSize(chunkStrStart, &body_header); - sentRequest->bytesReadForThisChunk = 0; - sentRequest->contentOffset = 0; - - if (sentRequest->thisChunkSize == 0) - { - // Done - completedRequestsMutex.Lock(); - completedRequests.Push(sentRequest, _FILE_AND_LINE_); - completedRequestsMutex.Unlock(); - - // If there is another command waiting for this server, send it - SendPendingRequestToConnectedSystem(packet->systemAddress); - } - else - { - - // char *offset = strstr((char*) packet->data+1, "2000"); - - body_header+=2; - ReadChunkBlock(sentRequest->thisChunkSize, sentRequest->bytesReadForThisChunk, body_header, sentRequest->stringReceived); - - if (sentRequest->thisChunkSize==0) - { - // Done - completedRequestsMutex.Lock(); - completedRequests.Push(sentRequest, _FILE_AND_LINE_); - completedRequestsMutex.Unlock(); - - // If there is another command waiting for this server, send it - SendPendingRequestToConnectedSystem(packet->systemAddress); - } - else - { - // Not done - sentRequestsMutex.Lock(); - sentRequests.Push(sentRequest, _FILE_AND_LINE_); - sentRequestsMutex.Unlock(); - } - } - } - else if (sentRequest->chunked) - { - ReadChunkBlock(sentRequest->thisChunkSize, sentRequest->bytesReadForThisChunk, (char*) packet->data, sentRequest->stringReceived); - - if (sentRequest->thisChunkSize==0) - { - // Done - completedRequestsMutex.Lock(); - completedRequests.Push(sentRequest, _FILE_AND_LINE_); - completedRequestsMutex.Unlock(); - - // If there is another command waiting for this server, send it - SendPendingRequestToConnectedSystem(packet->systemAddress); - } - else - { - // Not done - sentRequestsMutex.Lock(); - sentRequests.Push(sentRequest, _FILE_AND_LINE_); - sentRequestsMutex.Unlock(); - } - - } - else - { - sentRequest->stringReceived+=packet->data; - - if (sentRequest->contentLength==-1) - { - const char *length_header = strstr(sentRequest->stringReceived.C_String(), "Content-Length: "); - if(length_header) - { - length_header += 16; // strlen("Content-Length: "); - - unsigned int clLength; - for (clLength=0; length_header[clLength] && length_header[clLength] >= '0' && length_header[clLength] <= '9'; clLength++) - ; - if (clLength>0 && (length_header[clLength]=='\r' || length_header[clLength]=='\n')) - { - sentRequest->contentLength = RakString::ReadIntFromSubstring(length_header, 0, clLength); - } - } - } - - // If we know the content length, find \r\n\r\n - if (sentRequest->contentLength != -1) - { - if (sentRequest->contentLength > 0) - { - const char *body_header = strstr(sentRequest->stringReceived.C_String(), "\r\n\r\n"); - if (body_header) - { - body_header += 4; // strlen("\r\n\r\n"); - size_t slen = strlen(body_header); - //RakAssert(slen <= (size_t) sentRequest->contentLength); - if (slen >= (size_t) sentRequest->contentLength) - { - sentRequest->contentOffset = body_header - sentRequest->stringReceived.C_String(); - completedRequestsMutex.Lock(); - completedRequests.Push(sentRequest, _FILE_AND_LINE_); - completedRequestsMutex.Unlock(); - - // If there is another command waiting for this server, send it - SendPendingRequestToConnectedSystem(packet->systemAddress); - } - else - { - sentRequestsMutex.Lock(); - sentRequests.Push(sentRequest, _FILE_AND_LINE_); - sentRequestsMutex.Unlock(); - } - } - - else - { - sentRequestsMutex.Lock(); - sentRequests.Push(sentRequest, _FILE_AND_LINE_); - sentRequestsMutex.Unlock(); - } - } - else - { - sentRequest->contentOffset=-1; - completedRequestsMutex.Lock(); - completedRequests.Push(sentRequest, _FILE_AND_LINE_); - completedRequestsMutex.Unlock(); - - // If there is another command waiting for this server, send it - SendPendingRequestToConnectedSystem(packet->systemAddress); - } - } - else - { - const char *firstNewlineSet = strstr(sentRequest->stringReceived.C_String(), "\r\n\r\n"); - if (firstNewlineSet!=0) - { - ptrdiff_t offset = firstNewlineSet - sentRequest->stringReceived.C_String(); - if (sentRequest->stringReceived.C_String()[offset+4]==0) - sentRequest->contentOffset=-1; - else - sentRequest->contentOffset=offset+4; - completedRequestsMutex.Lock(); - completedRequests.Push(sentRequest, _FILE_AND_LINE_); - completedRequestsMutex.Unlock(); - - // If there is another command waiting for this server, send it - SendPendingRequestToConnectedSystem(packet->systemAddress); - } - else - { - sentRequestsMutex.Lock(); - sentRequests.Push(sentRequest, _FILE_AND_LINE_); - sentRequestsMutex.Unlock(); - } - } - } - - - break; - } - } - - if (locked==true) - sentRequestsMutex.Unlock(); - - return RR_CONTINUE_PROCESSING; -} - -void HTTPConnection2::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) -{ - (void) rakNetGUID; - (void) isIncoming; // unknown - - SendPendingRequestToConnectedSystem(systemAddress); -} -void HTTPConnection2::SendPendingRequestToConnectedSystem(SystemAddress sa) -{ - if (sa==UNASSIGNED_SYSTEM_ADDRESS) - return; - - unsigned int requestsSent=0; - - // Search through requests to find a match for this instance of TCPInterface and SystemAddress - unsigned int i; - i=0; - pendingRequestsMutex.Lock(); - while (i < pendingRequests.Size()) - { - Request *request = pendingRequests[i]; - if (request->hostEstimatedAddress==sa) - { - pendingRequests.RemoveAtIndex(i); - // Send this request - request->hostCompletedAddress=sa; - - sentRequestsMutex.Lock(); - sentRequests.Push(request, _FILE_AND_LINE_); - sentRequestsMutex.Unlock(); - - pendingRequestsMutex.Unlock(); - -#if OPEN_SSL_CLIENT_SUPPORT==1 - if (request->useSSL) - tcpInterface->StartSSLClient(sa); -#endif - - SendRequest(request); - requestsSent++; - pendingRequestsMutex.Lock(); - break; - } - else - { - i++; - } - } - pendingRequestsMutex.Unlock(); - - if (requestsSent==0) - { - pendingRequestsMutex.Lock(); - if (pendingRequests.Size() > 0) - { - // Just assign - Request *request = pendingRequests[0]; - pendingRequests.RemoveAtIndex(0); - - request->hostCompletedAddress=sa; - - sentRequestsMutex.Lock(); - sentRequests.Push(request, _FILE_AND_LINE_); - sentRequestsMutex.Unlock(); - pendingRequestsMutex.Unlock(); - - // Send -#if OPEN_SSL_CLIENT_SUPPORT==1 - if (request->useSSL) - tcpInterface->StartSSLClient(sa); -#endif - - - SendRequest(request); - } - else - { - pendingRequestsMutex.Unlock(); - } - } -} -void HTTPConnection2::RemovePendingRequest(SystemAddress sa) -{ - unsigned int i; - i=0; - pendingRequestsMutex.Lock(); - for (i=0; i < pendingRequests.Size(); i++) - { - Request *request = pendingRequests[i]; - if (request->hostEstimatedAddress==sa) - { - pendingRequests.RemoveAtIndex(i); - MafiaNet::OP_DELETE(request, _FILE_AND_LINE_); - } - else - i++; - } - - pendingRequestsMutex.Unlock(); -} -void HTTPConnection2::SendNextPendingRequest(void) -{ - // Send a pending request - pendingRequestsMutex.Lock(); - if (pendingRequests.Size()>0) - { - Request *pendingRequest = pendingRequests.Peek(); - pendingRequestsMutex.Unlock(); - - if (pendingRequest->ipVersion!=6) - { - tcpInterface->Connect(pendingRequest->host.C_String(), pendingRequest->port, false, AF_INET); - } - else - { -#if RAKNET_SUPPORT_IPV6 - tcpInterface->Connect(pendingRequest->host.C_String(), pendingRequest->port, false, AF_INET6); -#else - RakAssert("HTTPConnection2::TransmitRequest needs define RAKNET_SUPPORT_IPV6" && 0); -#endif - } - } - else - { - pendingRequestsMutex.Unlock(); - } -} - -void HTTPConnection2::OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason) -{ - (void) failedConnectionAttemptReason; - if (packet->systemAddress==UNASSIGNED_SYSTEM_ADDRESS) - return; - - RemovePendingRequest(packet->systemAddress); - - SendNextPendingRequest(); -} -void HTTPConnection2::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) lostConnectionReason; - (void) rakNetGUID; - - if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS) - return; - - // Update sent requests to completed requests - unsigned int i; - i=0; - sentRequestsMutex.Lock(); - while (i < sentRequests.Size()) - { - if (sentRequests[i]->hostCompletedAddress==systemAddress) - { - Request *sentRequest = sentRequests[i]; - if (sentRequest->chunked==false && sentRequest->stringReceived.IsEmpty()==false) - { - if (strstr(sentRequest->stringReceived.C_String(), "Content-Length: ")) - { - char *body_header = strstr((char*) sentRequest->stringReceived.C_String(), "\r\n\r\n"); - if (body_header) - { - body_header += 4; // strlen("\r\n\r\n"); - sentRequest->contentOffset = body_header - sentRequest->stringReceived.C_String(); - } - else - { - sentRequest->contentOffset = 0; - } - - } - else - { - sentRequest->contentOffset = 0; - } - } - - - completedRequestsMutex.Lock(); - completedRequests.Push(sentRequests[i], _FILE_AND_LINE_); - completedRequestsMutex.Unlock(); - - sentRequests.RemoveAtIndexFast(i); - } - else - { - i++; - } - } - sentRequestsMutex.Unlock(); - - SendNextPendingRequest(); -} -bool HTTPConnection2::IsConnected(SystemAddress sa) -{ - SystemAddress remoteSystems[64]; - unsigned short numberOfSystems=64; - tcpInterface->GetConnectionList(remoteSystems, &numberOfSystems); - for (unsigned int i=0; i < numberOfSystems; i++) - { - if (remoteSystems[i]==sa) - { - return true; - } - } - return false; -} -void HTTPConnection2::SendRequest(Request *request) -{ - tcpInterface->Send(request->stringToTransmit.C_String(), (unsigned int) request->stringToTransmit.GetLength(), request->hostCompletedAddress, false); -} - -#endif // #if _RAKNET_SUPPORT_HTTPConnection2==1 && _RAKNET_SUPPORT_TCPInterface==1 diff --git a/vendors/mafianet/Source/src/IncrementalReadInterface.cpp b/vendors/mafianet/Source/src/IncrementalReadInterface.cpp deleted file mode 100644 index 0bad8e857..000000000 --- a/vendors/mafianet/Source/src/IncrementalReadInterface.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/IncrementalReadInterface.h" -#include -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace MafiaNet; - -unsigned int IncrementalReadInterface::GetFilePart( const char *filename, unsigned int startReadBytes, unsigned int numBytesToRead, void *preallocatedDestination, FileListNodeContext context) -{ - FILE *fp; - if (fopen_s(&fp, filename, "rb")!=0) - return 0; - fseek(fp,startReadBytes,SEEK_SET); - unsigned int numRead = (unsigned int) fread(preallocatedDestination,1,numBytesToRead, fp); - fclose(fp); - return numRead; -} diff --git a/vendors/mafianet/Source/src/Itoa.cpp b/vendors/mafianet/Source/src/Itoa.cpp deleted file mode 100644 index d4ac0916f..000000000 --- a/vendors/mafianet/Source/src/Itoa.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/EmptyHeader.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// Fast itoa from http://www.jb.man.ac.uk/~slowe/cpp/itoa.html for Linux since it seems like Linux doesn't support this function. -// I modified it to remove the std dependencies. -char* Itoa( int value, char* result, int base ) - { - // check that the base if valid - if (base < 2 || base > 16) { *result = 0; return result; } - char* out = result; - int quotient = value; - - int absQModB; - - do { - // KevinJ - get rid of this dependency - //*out = "0123456789abcdef"[ std::abs( quotient % base ) ]; - absQModB=quotient % base; - if (absQModB < 0) - absQModB=-absQModB; - *out = "0123456789abcdef"[ absQModB ]; - ++out; - quotient /= base; - } while ( quotient ); - - // Only apply negative sign for base 10 - if ( value < 0 && base == 10) *out++ = '-'; - - // KevinJ - get rid of this dependency - // std::reverse( result, out ); - *out = 0; - - // KevinJ - My own reverse code - char *start = result; - char temp; - out--; - while (start < out) - { - temp=*start; - *start=*out; - *out=temp; - start++; - out--; - } - - return result; -} - -#ifdef __cplusplus -} -#endif diff --git a/vendors/mafianet/Source/src/LinuxStrings.cpp b/vendors/mafianet/Source/src/LinuxStrings.cpp deleted file mode 100644 index 0a5583a0c..000000000 --- a/vendors/mafianet/Source/src/LinuxStrings.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#if (defined(__GNUC__) || defined(__ARMCC_VERSION) || defined(__GCCXML__) || defined(__S3E__) ) && !defined(_WIN32) -#include -#ifndef _stricmp -int _stricmp(const char* s1, const char* s2) -{ - return strcasecmp(s1,s2); -} -#endif -int _strnicmp(const char* s1, const char* s2, size_t n) -{ - return strncasecmp(s1,s2,n); -} -#ifndef __APPLE__ -char *_strlwr(char * str ) -{ - if (str==0) - return 0; - for (int i=0; str[i]; i++) - { - if (str[i]>='A' && str[i]<='Z') - str[i]+='a'-'A'; - } - return str; -} -#endif -#endif diff --git a/vendors/mafianet/Source/src/LocklessTypes.cpp b/vendors/mafianet/Source/src/LocklessTypes.cpp deleted file mode 100644 index 90db56dc2..000000000 --- a/vendors/mafianet/Source/src/LocklessTypes.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/LocklessTypes.h" - -using namespace MafiaNet; - -LocklessUint32_t::LocklessUint32_t() -{ - value=0; -} -LocklessUint32_t::LocklessUint32_t(uint32_t initial) -{ - value=initial; -} -uint32_t LocklessUint32_t::Increment(void) -{ -#ifdef _WIN32 - return (uint32_t) InterlockedIncrement(&value); -#elif defined(ANDROID) || defined(__S3E__) || defined(__APPLE__) - uint32_t v; - mutex.Lock(); - ++value; - v=value; - mutex.Unlock(); - return v; -#else - return __sync_fetch_and_add (&value, (uint32_t) 1); -#endif -} -uint32_t LocklessUint32_t::Decrement(void) -{ -#ifdef _WIN32 - return (uint32_t) InterlockedDecrement(&value); -#elif defined(ANDROID) || defined(__S3E__) || defined(__APPLE__) - uint32_t v; - mutex.Lock(); - --value; - v=value; - mutex.Unlock(); - return v; -#else - return __sync_fetch_and_add (&value, (uint32_t) -1); -#endif -} diff --git a/vendors/mafianet/Source/src/LogCommandParser.cpp b/vendors/mafianet/Source/src/LogCommandParser.cpp deleted file mode 100644 index fdec20a93..000000000 --- a/vendors/mafianet/Source/src/LogCommandParser.cpp +++ /dev/null @@ -1,287 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_LogCommandParser==1 - -#include "mafianet/LogCommandParser.h" -#include "mafianet/TransportInterface.h" - -#include - -#include -#include -#include - -#include "mafianet/LinuxStrings.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(LogCommandParser,LogCommandParser); - -LogCommandParser::LogCommandParser() -{ - RegisterCommand(CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS,"Subscribe","[] - Subscribes to a named channel, or all channels"); - RegisterCommand(CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS,"Unsubscribe","[] - Unsubscribes from a named channel, or all channels"); - memset(channelNames,0,sizeof(channelNames)); -} -LogCommandParser::~LogCommandParser() -{ -} -bool LogCommandParser::OnCommand(const char *command, unsigned numParameters, char **parameterList, TransportInterface *transport, const SystemAddress &systemAddress, const char *originalString) -{ - (void) originalString; - - if (strcmp(command, "Subscribe")==0) - { - unsigned channelIndex; - if (numParameters==0) - { - Subscribe(systemAddress, 0); - transport->Send(systemAddress, "Subscribed to all channels.\r\n"); - } - else if (numParameters==1) - { - if ((channelIndex=Subscribe(systemAddress, parameterList[0]))!=(unsigned)-1) - { - transport->Send(systemAddress, "You are now subscribed to channel %s.\r\n", channelNames[channelIndex]); - } - else - { - transport->Send(systemAddress, "Cannot find channel %s.\r\n", parameterList[0]); - PrintChannels(systemAddress, transport); - } - } - else - { - transport->Send(systemAddress, "Subscribe takes either 0 or 1 parameters.\r\n"); - } - } - else if (strcmp(command, "Unsubscribe")==0) - { - unsigned channelIndex; - if (numParameters==0) - { - Unsubscribe(systemAddress, 0); - transport->Send(systemAddress, "Unsubscribed from all channels.\r\n"); - } - else if (numParameters==1) - { - if ((channelIndex=Unsubscribe(systemAddress, parameterList[0]))!=(unsigned)-1) - { - transport->Send(systemAddress, "You are now unsubscribed from channel %s.\r\n", channelNames[channelIndex]); - } - else - { - transport->Send(systemAddress, "Cannot find channel %s.\r\n", parameterList[0]); - PrintChannels(systemAddress, transport); - } - } - else - { - transport->Send(systemAddress, "Unsubscribe takes either 0 or 1 parameters.\r\n"); - } - } - - return true; -} -const char *LogCommandParser::GetName(void) const -{ - return "Logger"; -} -void LogCommandParser::SendHelp(TransportInterface *transport, const SystemAddress &systemAddress) -{ - transport->Send(systemAddress, "The logger will accept user log data via the Log(...) function.\r\n"); - transport->Send(systemAddress, "Each log is associated with a named channel.\r\n"); - transport->Send(systemAddress, "You can subscribe to or unsubscribe from named channels.\r\n"); - PrintChannels(systemAddress, transport); -} -void LogCommandParser::AddChannel(const char *channelName) -{ - unsigned channelIndex=0; - channelIndex = GetChannelIndexFromName(channelName); - // Each channel can only be added once. - RakAssert(channelIndex==(unsigned)-1); - - unsigned i; - for (i=0; i < 32; i++) - { - if (channelNames[i]==0) - { - // Assuming a persistent static string. - channelNames[i]=channelName; - return; - } - } - - // No more available channels - max 32 with this implementation where I save subscribed channels with bit operations - RakAssert(0); -} -void LogCommandParser::WriteLog(const char *channelName, const char *format, ...) -{ - if (channelName==0 || format==0) - return; - - unsigned channelIndex; - channelIndex = GetChannelIndexFromName(channelName); - if (channelIndex==(unsigned)-1) - { - AddChannel(channelName); - } - - char text[REMOTE_MAX_TEXT_INPUT]; - va_list ap; - va_start(ap, format); - vsnprintf_s(text, REMOTE_MAX_TEXT_INPUT-1, format, ap); - va_end(ap); - - // Make sure that text ends in \r\n - int textLen; - textLen=(int)strlen(text); - if (textLen==0) - return; - if (text[textLen-1]=='\n') - { - text[textLen-1]=0; - } - if (textLen < REMOTE_MAX_TEXT_INPUT-4) - strcat_s(text, "\r\n"); - else - { - text[textLen-3]='\r'; - text[textLen-2]='\n'; - text[textLen-1]=0; - } - - // For each user that subscribes to this channel, send to them. - unsigned i; - for (i=0; i < remoteUsers.Size(); i++) - { - if (remoteUsers[i].channels & (1 << channelIndex)) - { - trans->Send(remoteUsers[i].systemAddress, text); - } - } -} -void LogCommandParser::PrintChannels(const SystemAddress &systemAddress, TransportInterface *transport) const -{ - unsigned i; - bool anyChannels=false; - transport->Send(systemAddress, "CHANNELS:\r\n"); - for (i=0; i < 32; i++) - { - if (channelNames[i]) - { - transport->Send(systemAddress, "%i. %s\r\n", i+1,channelNames[i]); - anyChannels=true; - } - } - if (anyChannels==false) - transport->Send(systemAddress, "None.\r\n"); -} -void LogCommandParser::OnNewIncomingConnection(const SystemAddress &systemAddress, TransportInterface *transport) -{ - (void) systemAddress; - (void) transport; -} -void LogCommandParser::OnConnectionLost(const SystemAddress &systemAddress, TransportInterface *transport) -{ - (void) transport; - Unsubscribe(systemAddress, 0); -} -unsigned LogCommandParser::Unsubscribe(const SystemAddress &systemAddress, const char *channelName) -{ - unsigned i; - for (i=0; i < remoteUsers.Size(); i++) - { - if (remoteUsers[i].systemAddress==systemAddress) - { - if (channelName==0) - { - // Unsubscribe from all and delete this user. - remoteUsers[i]=remoteUsers[remoteUsers.Size()-1]; - remoteUsers.RemoveFromEnd(); - return 0; - } - else - { - unsigned channelIndex; - channelIndex = GetChannelIndexFromName(channelName); - if (channelIndex!=(unsigned)-1) - { - remoteUsers[i].channels&=0xFFFF ^ (1<filterSetID) - return -1; - else if (key==data->filterSetID) - return 0; - else - return 1; -} -STATIC_FACTORY_DEFINITIONS(MessageFilter,MessageFilter); - -MessageFilter::MessageFilter() -{ - whenLastTimeoutCheck= MafiaNet::GetTime(); -} -MessageFilter::~MessageFilter() -{ - Clear(); -} -void MessageFilter::SetAutoAddNewConnectionsToFilter(int filterSetID) -{ - autoAddNewConnectionsToFilter=filterSetID; -} -void MessageFilter::SetAllowMessageID(bool allow, int messageIDStart, int messageIDEnd,int filterSetID) -{ - RakAssert(messageIDStart <= messageIDEnd); - FilterSet *filterSet = GetFilterSetByID(filterSetID); - int i; - for (i=messageIDStart; i <= messageIDEnd; ++i) - filterSet->allowedIDs[i]=allow; -} -void MessageFilter::SetAllowRPC4(bool allow, const char* uniqueID, int filterSetID) -{ - FilterSet *filterSet = GetFilterSetByID(filterSetID); - bool objectExists; - unsigned int idx = filterSet->allowedRPC4.GetIndexFromKey(uniqueID, &objectExists); - if (allow) - { - if (objectExists==false) - { - filterSet->allowedRPC4.InsertAtIndex(uniqueID, idx, _FILE_AND_LINE_); - filterSet->allowedIDs[ID_RPC_PLUGIN]=true; - } - } - else - { - if (objectExists==true) - { - filterSet->allowedRPC4.RemoveAtIndex(idx); - if (filterSet->allowedRPC4.Size()==0) - { - filterSet->allowedIDs[ID_RPC_PLUGIN]=false; - } - } - } -} -void MessageFilter::SetActionOnDisallowedMessage(bool kickOnDisallowed, bool banOnDisallowed, MafiaNet::TimeMS banTimeMS, int filterSetID) -{ - FilterSet *filterSet = GetFilterSetByID(filterSetID); - filterSet->kickOnDisallowedMessage=kickOnDisallowed; - filterSet->disallowedMessageBanTimeMS=banTimeMS; - filterSet->banOnDisallowedMessage=banOnDisallowed; -} -void MessageFilter::SetDisallowedMessageCallback(int filterSetID, void *userData, void (*invalidMessageCallback)(RakPeerInterface *peer, AddressOrGUID systemAddress, int filterSetID, void *userData, unsigned char messageID)) -{ - FilterSet *filterSet = GetFilterSetByID(filterSetID); - filterSet->invalidMessageCallback=invalidMessageCallback; - filterSet->disallowedCallbackUserData=userData; -} -void MessageFilter::SetTimeoutCallback(int filterSetID, void *userData, void (*invalidMessageCallback)(RakPeerInterface *peer, AddressOrGUID systemAddress, int filterSetID, void *userData)) -{ - FilterSet *filterSet = GetFilterSetByID(filterSetID); - filterSet->timeoutCallback=invalidMessageCallback; - filterSet->timeoutUserData=userData; -} -void MessageFilter::SetFilterMaxTime(int allowedTimeMS, bool banOnExceed, MafiaNet::TimeMS banTimeMS, int filterSetID) -{ - FilterSet *filterSet = GetFilterSetByID(filterSetID); - filterSet->maxMemberTimeMS=allowedTimeMS; - filterSet->banOnFilterTimeExceed=banOnExceed; - filterSet->timeExceedBanTimeMS=banTimeMS; -} -int MessageFilter::GetSystemFilterSet(AddressOrGUID systemAddress) -{ -// bool objectExists; -// unsigned index = systemList.GetIndexFromKey(systemAddress, &objectExists); -// if (objectExists==false) -// return -1; -// else -// return systemList[index].filter->filterSetID; - - DataStructures::HashIndex index = systemList.GetIndexOf(systemAddress); - if (index.IsInvalid()) - return -1; - else - return systemList.ItemAtIndex(index).filter->filterSetID; -} -void MessageFilter::SetSystemFilterSet(AddressOrGUID addressOrGUID, int filterSetID) -{ - // Allocate this filter set if it doesn't exist. - RakAssert(addressOrGUID.IsUndefined()==false); -// bool objectExists; -// unsigned index = systemList.GetIndexFromKey(addressOrGUID, &objectExists); -// if (objectExists==false) - DataStructures::HashIndex index = systemList.GetIndexOf(addressOrGUID); - if (index.IsInvalid()) - { - if (filterSetID<0) - return; - - FilteredSystem filteredSystem; - filteredSystem.filter = GetFilterSetByID(filterSetID); - // filteredSystem.addressOrGUID=addressOrGUID; - filteredSystem.timeEnteredThisSet= MafiaNet::GetTimeMS(); - // systemList.Insert(addressOrGUID, filteredSystem, true, _FILE_AND_LINE_); - systemList.Push(addressOrGUID,filteredSystem,_FILE_AND_LINE_); - } - else - { - if (filterSetID>=0) - { - FilterSet *filterSet = GetFilterSetByID(filterSetID); - systemList.ItemAtIndex(index).timeEnteredThisSet= MafiaNet::GetTimeMS(); - systemList.ItemAtIndex(index).filter=filterSet; - } - else - { - systemList.RemoveAtIndex(index, _FILE_AND_LINE_); - } - } -} -unsigned MessageFilter::GetSystemCount(int filterSetID) const -{ - if (filterSetID==-1) - { - return systemList.Size(); - } - else - { - unsigned i; - unsigned count=0; - DataStructures::List< FilteredSystem > itemList; - DataStructures::List< AddressOrGUID > keyList; - systemList.GetAsList(itemList, keyList, _FILE_AND_LINE_); - for (i=0; i < itemList.Size(); i++) - if (itemList[i].filter->filterSetID==filterSetID) - ++count; - return count; - } -} -unsigned MessageFilter::GetFilterSetCount(void) const -{ - return filterList.Size(); -} -int MessageFilter::GetFilterSetIDByIndex(unsigned index) -{ - return filterList[index]->filterSetID; -} -void MessageFilter::DeleteFilterSet(int filterSetID) -{ - FilterSet *filterSet; - bool objectExists; - unsigned i,index; - index = filterList.GetIndexFromKey(filterSetID, &objectExists); - if (objectExists) - { - filterSet=filterList[index]; - DeallocateFilterSet(filterSet); - filterList.RemoveAtIndex(index); - - DataStructures::List< FilteredSystem > itemList; - DataStructures::List< AddressOrGUID > keyList; - systemList.GetAsList(itemList, keyList, _FILE_AND_LINE_); - for (i=0; i < itemList.Size(); i++) - { - if (itemList[i].filter==filterSet) - { - systemList.Remove(keyList[i], _FILE_AND_LINE_); - } - } - - /* - // Don't reference this pointer any longer - i=0; - while (i < systemList.Size()) - { - if (systemList[i].filter==filterSet) - systemList.RemoveAtIndex(i); - else - ++i; - } - */ - } -} -void MessageFilter::Clear(void) -{ - unsigned i; - systemList.Clear(_FILE_AND_LINE_); - for (i=0; i < filterList.Size(); i++) - DeallocateFilterSet(filterList[i]); - filterList.Clear(false, _FILE_AND_LINE_); -} -void MessageFilter::DeallocateFilterSet(FilterSet* filterSet) -{ - MafiaNet::OP_DELETE(filterSet, _FILE_AND_LINE_); -} -FilterSet* MessageFilter::GetFilterSetByID(int filterSetID) -{ - RakAssert(filterSetID>=0); - bool objectExists; - unsigned index; - index = filterList.GetIndexFromKey(filterSetID, &objectExists); - if (objectExists) - return filterList[index]; - else - { - FilterSet *newFilterSet = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - memset(newFilterSet->allowedIDs, 0, MESSAGE_FILTER_MAX_MESSAGE_ID * sizeof(bool)); - newFilterSet->banOnFilterTimeExceed=false; - newFilterSet->kickOnDisallowedMessage=false; - newFilterSet->banOnDisallowedMessage=false; - newFilterSet->disallowedMessageBanTimeMS=0; - newFilterSet->timeExceedBanTimeMS=0; - newFilterSet->maxMemberTimeMS=0; - newFilterSet->filterSetID=filterSetID; - newFilterSet->invalidMessageCallback=0; - newFilterSet->timeoutCallback=0; - newFilterSet->timeoutUserData=0; - filterList.Insert(filterSetID, newFilterSet, true, _FILE_AND_LINE_); - return newFilterSet; - } -} -void MessageFilter::OnInvalidMessage(FilterSet *filterSet, AddressOrGUID systemAddress, unsigned char messageID) -{ - if (filterSet->invalidMessageCallback) - filterSet->invalidMessageCallback(rakPeerInterface, systemAddress, filterSet->filterSetID, filterSet->disallowedCallbackUserData, messageID); - if (filterSet->banOnDisallowedMessage && rakPeerInterface) - { - char str1[64]; - systemAddress.systemAddress.ToString(false, str1, static_cast(64)); - rakPeerInterface->AddToBanList(str1, filterSet->disallowedMessageBanTimeMS); - } - if (filterSet->kickOnDisallowedMessage) - { - if (rakPeerInterface) - rakPeerInterface->CloseConnection(systemAddress, true, 0); -#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 - else - tcpInterface->CloseConnection(systemAddress.systemAddress); -#endif - } -} -void MessageFilter::Update(void) -{ - // Update all timers for all systems. If those systems' filter sets are expired, take the appropriate action. - MafiaNet::Time curTime = MafiaNet::GetTime(); - if (GreaterThan(curTime - 1000, whenLastTimeoutCheck)) - { - DataStructures::List< FilteredSystem > itemList; - DataStructures::List< AddressOrGUID > keyList; - systemList.GetAsList(itemList, keyList, _FILE_AND_LINE_); - - unsigned int index; - for (index=0; index < itemList.Size(); index++) - { - if (itemList[index].filter && - itemList[index].filter->maxMemberTimeMS>0 && - curTime-itemList[index].timeEnteredThisSet >= itemList[index].filter->maxMemberTimeMS) - { - if (itemList[index].filter->timeoutCallback) - itemList[index].filter->timeoutCallback(rakPeerInterface, keyList[index], itemList[index].filter->filterSetID, itemList[index].filter->timeoutUserData); - - if (itemList[index].filter->banOnFilterTimeExceed && rakPeerInterface) - { - char str1[64]; - keyList[index].ToString(false, str1, 64); - rakPeerInterface->AddToBanList(str1, itemList[index].filter->timeExceedBanTimeMS); - } - if (rakPeerInterface) - rakPeerInterface->CloseConnection(keyList[index], true, 0); -#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 - else - tcpInterface->CloseConnection(keyList[index].systemAddress); -#endif - - systemList.Remove(keyList[index], _FILE_AND_LINE_); - } - } - - whenLastTimeoutCheck=curTime+1000; - } -} -void MessageFilter::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) -{ - (void) systemAddress; - (void) rakNetGUID; - (void) isIncoming; - - AddressOrGUID aog; - aog.rakNetGuid=rakNetGUID; - aog.systemAddress=systemAddress; - - // New system, automatically assign to filter set if appropriate - if (autoAddNewConnectionsToFilter>=0 && systemList.HasData(aog)==false) - SetSystemFilterSet(aog, autoAddNewConnectionsToFilter); -} -void MessageFilter::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) rakNetGUID; - (void) lostConnectionReason; - - AddressOrGUID aog; - aog.rakNetGuid=rakNetGUID; - aog.systemAddress=systemAddress; - - // Lost system, remove from the list - systemList.Remove(aog, _FILE_AND_LINE_); -} - PluginReceiveResult MessageFilter::OnReceive(Packet *packet) -{ - DataStructures::HashIndex index; - unsigned char messageId; - - switch (packet->data[0]) - { - case ID_NEW_INCOMING_CONNECTION: - case ID_CONNECTION_REQUEST_ACCEPTED: - case ID_CONNECTION_LOST: - case ID_DISCONNECTION_NOTIFICATION: - case ID_CONNECTION_ATTEMPT_FAILED: - case ID_NO_FREE_INCOMING_CONNECTIONS: - case ID_IP_RECENTLY_CONNECTED: - case ID_CONNECTION_BANNED: - case ID_INVALID_PASSWORD: - case ID_UNCONNECTED_PONG: - case ID_ALREADY_CONNECTED: - case ID_ADVERTISE_SYSTEM: - case ID_REMOTE_DISCONNECTION_NOTIFICATION: - case ID_REMOTE_CONNECTION_LOST: - case ID_REMOTE_NEW_INCOMING_CONNECTION: - case ID_DOWNLOAD_PROGRESS: - break; - default: - if (packet->data[0]==ID_TIMESTAMP) - { - if (packet->lengthdata[sizeof(MessageID) + sizeof(MafiaNet::TimeMS)]; - } - else - messageId=packet->data[0]; - // If this system is filtered, check if this message is allowed. If not allowed, return RR_STOP_PROCESSING_AND_DEALLOCATE - // index = systemList.GetIndexFromKey(packet->addressOrGUID, &objectExists); - index = systemList.GetIndexOf(packet); - if (index.IsInvalid()) - break; - if (systemList.ItemAtIndex(index).filter->allowedIDs[messageId]==false) - { - OnInvalidMessage(systemList.ItemAtIndex(index).filter, packet, packet->data[0]); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - if (packet->data[0]==ID_RPC_PLUGIN) - { - MafiaNet::BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2); - MafiaNet::RakString functionName; - bsIn.ReadCompressed(functionName); - if (systemList.ItemAtIndex(index).filter->allowedRPC4.HasData(functionName)==false) - { - OnInvalidMessage(systemList.ItemAtIndex(index).filter, packet, packet->data[0]); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - } - - break; - } - - return RR_CONTINUE_PROCESSING; -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/NatPunchthroughClient.cpp b/vendors/mafianet/Source/src/NatPunchthroughClient.cpp deleted file mode 100644 index bc917c4d4..000000000 --- a/vendors/mafianet/Source/src/NatPunchthroughClient.cpp +++ /dev/null @@ -1,1221 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_NatPunchthroughClient==1 - -#include "mafianet/NatPunchthroughClient.h" -#include "mafianet/BitStream.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/peerinterface.h" -#include "mafianet/GetTime.h" -#include "mafianet/PacketLogger.h" -#include "mafianet/Itoa.h" - -using namespace MafiaNet; - -void NatPunchthroughDebugInterface_Printf::OnClientMessage(const char *msg) -{ - printf("%s\n", msg); -} -#if _RAKNET_SUPPORT_PacketLogger==1 -void NatPunchthroughDebugInterface_PacketLogger::OnClientMessage(const char *msg) -{ - if (pl) - { - pl->WriteMiscellaneous("Nat", msg); - } -} -#endif - -STATIC_FACTORY_DEFINITIONS(NatPunchthroughClient,NatPunchthroughClient); - -NatPunchthroughClient::NatPunchthroughClient() -{ - natPunchthroughDebugInterface=0; - mostRecentExternalPort=0; - sp.nextActionTime=0; - portStride=0; - hasPortStride=UNKNOWN_PORT_STRIDE; -} -NatPunchthroughClient::~NatPunchthroughClient() -{ - rakPeerInterface=0; - Clear(); -} -void NatPunchthroughClient::FindRouterPortStride(const SystemAddress &facilitator) -{ - ConnectionState cs = rakPeerInterface->GetConnectionState(facilitator); - if (cs!=IS_CONNECTED) - return; - if (hasPortStride!=UNKNOWN_PORT_STRIDE) - return; - - hasPortStride=CALCULATING_PORT_STRIDE; - portStrideCalTimeout = MafiaNet::GetTime()+5000; - - if (natPunchthroughDebugInterface) - { - natPunchthroughDebugInterface->OnClientMessage(RakString("Calculating port stride from %s", facilitator.ToString(true))); - } - - MafiaNet::BitStream outgoingBs; - outgoingBs.Write((MessageID)ID_NAT_REQUEST_BOUND_ADDRESSES); - rakPeerInterface->Send(&outgoingBs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,facilitator,false); -} -bool NatPunchthroughClient::OpenNAT(RakNetGUID destination, const SystemAddress &facilitator) -{ - ConnectionState cs = rakPeerInterface->GetConnectionState(facilitator); - if (cs!=IS_CONNECTED) - return false; - if (hasPortStride==UNKNOWN_PORT_STRIDE) - { - FindRouterPortStride(facilitator); - QueueOpenNAT(destination, facilitator); - } - else if (hasPortStride==CALCULATING_PORT_STRIDE) - { - QueueOpenNAT(destination, facilitator); - } - else - { - SendPunchthrough(destination, facilitator); - } - - return true; -} -/* -bool NatPunchthroughClient::OpenNATGroup(DataStructures::List destinationSystems, const SystemAddress &facilitator) -{ - ConnectionState cs = rakPeerInterface->GetConnectionState(facilitator); - if (cs!=IS_CONNECTED) - return false; - - unsigned long i; - for (i=0; i < destinationSystems.Size(); i++) - { - SendPunchthrough(destinationSystems[i], facilitator); - } - - GroupPunchRequest *gpr = MafiaNet::OP_NEW(_FILE_AND_LINE_); - gpr->facilitator=facilitator; - gpr->pendingList=destinationSystems; - groupPunchRequests.Push(gpr, _FILE_AND_LINE_); - - return true; -} -*/ -void NatPunchthroughClient::SetDebugInterface(NatPunchthroughDebugInterface *i) -{ - natPunchthroughDebugInterface=i; -} -void NatPunchthroughClient::Update(void) -{ - MafiaNet::Time time = MafiaNet::GetTime(); - - if (hasPortStride==CALCULATING_PORT_STRIDE && time > portStrideCalTimeout) - { - if (natPunchthroughDebugInterface) - { - natPunchthroughDebugInterface->OnClientMessage("CALCULATING_PORT_STRIDE timeout"); - } - - SendQueuedOpenNAT(); - hasPortStride=UNKNOWN_PORT_STRIDE; - } - - if (sp.nextActionTime && sp.nextActionTime < time) - { - MafiaNet::Time delta = time - sp.nextActionTime; - if (sp.testMode==SendPing::TESTING_INTERNAL_IPS) - { - SendOutOfBand(sp.internalIds[sp.attemptCount],ID_NAT_ESTABLISH_UNIDIRECTIONAL); - - if (++sp.retryCount>=pc.UDP_SENDS_PER_PORT_INTERNAL) - { - ++sp.attemptCount; - sp.retryCount=0; - } - - if (sp.attemptCount>=pc.MAXIMUM_NUMBER_OF_INTERNAL_IDS_TO_CHECK) - { - sp.testMode=SendPing::WAITING_FOR_INTERNAL_IPS_RESPONSE; - if (pc.INTERNAL_IP_WAIT_AFTER_ATTEMPTS>0) - { - sp.nextActionTime=time+pc.INTERNAL_IP_WAIT_AFTER_ATTEMPTS-delta; - } - else - { - sp.testMode=SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT; - sp.attemptCount=0; - sp.sentTTL=false; - } - } - else - { - sp.nextActionTime=time+pc.TIME_BETWEEN_PUNCH_ATTEMPTS_INTERNAL-delta; - } - } - else if (sp.testMode==SendPing::WAITING_FOR_INTERNAL_IPS_RESPONSE) - { - sp.testMode=SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT; - sp.attemptCount=0; - sp.sentTTL=false; - } - /* - else if (sp.testMode==SendPing::SEND_WITH_TTL) - { - // Send to unused port. We do not want the message to arrive, just to open our router's table - SystemAddress sa=sp.targetAddress; - int ttlSendIndex; - for (ttlSendIndex=0; ttlSendIndex <= pc.MAX_PREDICTIVE_PORT_RANGE; ttlSendIndex++) - { - sa.SetPortHostOrder((unsigned short) (sp.targetAddress.GetPort()+ttlSendIndex)); - SendTTL(sa); - } - - // Only do this stage once - // Wait 250 milliseconds for next stage. The delay is so that even with timing errors both systems send out the - // datagram with TTL before either sends a real one - sp.testMode=SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT; - sp.nextActionTime=time-delta+250; - } - */ - else if (sp.testMode==SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT) - { - if (sp.sentTTL==false) - { - SystemAddress sa=sp.targetAddress; - sa.SetPortHostOrder((unsigned short) (sa.GetPort()+sp.attemptCount)); - SendTTL(sa); - - if (natPunchthroughDebugInterface) - { - natPunchthroughDebugInterface->OnClientMessage(RakString("Send with TTL 2 to %s", sa.ToString(true))); - } - - sp.nextActionTime = time+pc.EXTERNAL_IP_WAIT_AFTER_FIRST_TTL-delta; - sp.sentTTL=true; - } - else - { - SystemAddress sa=sp.targetAddress; - sa.SetPortHostOrder((unsigned short) (sa.GetPort()+sp.attemptCount)); - SendOutOfBand(sa,ID_NAT_ESTABLISH_UNIDIRECTIONAL); - - IncrementExternalAttemptCount(time, delta); - - if (sp.attemptCount>pc.MAX_PREDICTIVE_PORT_RANGE) - { - sp.testMode=SendPing::WAITING_AFTER_ALL_ATTEMPTS; - sp.nextActionTime=time+pc.EXTERNAL_IP_WAIT_AFTER_ALL_ATTEMPTS-delta; - - // Skip TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT, etc. - /* - sp.testMode=SendPing::TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT; - sp.attemptCount=0; - */ - } - } - } - else if (sp.testMode==SendPing::TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT) - { - SystemAddress sa=sp.targetAddress; - if ( sp.targetGuid < rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS) ) - sa.SetPortHostOrder((unsigned short) (1024+sp.attemptCount)); - else - sa.SetPortHostOrder((unsigned short) (sa.GetPort()+sp.attemptCount)); - SendOutOfBand(sa,ID_NAT_ESTABLISH_UNIDIRECTIONAL); - - IncrementExternalAttemptCount(time, delta); - - if (sp.attemptCount>pc.MAX_PREDICTIVE_PORT_RANGE) - { - // From 1024 disabled, never helps as I've seen, but slows down the process by half - sp.testMode=SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_1024; - sp.attemptCount=0; - } - - } - else if (sp.testMode==SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_1024) - { - SystemAddress sa=sp.targetAddress; - if ( sp.targetGuid > rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS) ) - sa.SetPortHostOrder((unsigned short) (1024+sp.attemptCount)); - else - sa.SetPortHostOrder((unsigned short) (sa.GetPort()+sp.attemptCount)); - SendOutOfBand(sa,ID_NAT_ESTABLISH_UNIDIRECTIONAL); - - IncrementExternalAttemptCount(time, delta); - - if (sp.attemptCount>pc.MAX_PREDICTIVE_PORT_RANGE) - { - // From 1024 disabled, never helps as I've seen, but slows down the process by half - sp.testMode=SendPing::TESTING_EXTERNAL_IPS_1024_TO_1024; - sp.attemptCount=0; - } - } - else if (sp.testMode==SendPing::TESTING_EXTERNAL_IPS_1024_TO_1024) - { - SystemAddress sa=sp.targetAddress; - sa.SetPortHostOrder((unsigned short) (1024+sp.attemptCount)); - SendOutOfBand(sa,ID_NAT_ESTABLISH_UNIDIRECTIONAL); - - IncrementExternalAttemptCount(time, delta); - - if (sp.attemptCount>pc.MAX_PREDICTIVE_PORT_RANGE) - { - if (natPunchthroughDebugInterface) - { - char ipAddressString[32]; - sp.targetAddress.ToString(true, ipAddressString, static_cast(32)); - char guidString[128]; - sp.targetGuid.ToString(guidString, 128); - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("Likely bidirectional punchthrough failure to guid %s, system address %s.", guidString, ipAddressString)); - } - - sp.testMode=SendPing::WAITING_AFTER_ALL_ATTEMPTS; - sp.nextActionTime=time+pc.EXTERNAL_IP_WAIT_AFTER_ALL_ATTEMPTS-delta; - } - } - else if (sp.testMode==SendPing::WAITING_AFTER_ALL_ATTEMPTS) - { - // Failed. Tell the user - OnPunchthroughFailure(); - // UpdateGroupPunchOnNatResult(sp.facilitator, sp.targetGuid, sp.targetAddress, 1); - } - - if (sp.testMode==SendPing::PUNCHING_FIXED_PORT) - { - SendOutOfBand(sp.targetAddress,ID_NAT_ESTABLISH_BIDIRECTIONAL); - if (++sp.retryCount>=sp.punchingFixedPortAttempts) - { - if (natPunchthroughDebugInterface) - { - char ipAddressString[32]; - sp.targetAddress.ToString(true, ipAddressString, static_cast(32)); - char guidString[128]; - sp.targetGuid.ToString(guidString, 128); - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("Likely unidirectional punchthrough failure to guid %s, system address %s.", guidString, ipAddressString)); - } - - sp.testMode=SendPing::WAITING_AFTER_ALL_ATTEMPTS; - sp.nextActionTime=time+pc.EXTERNAL_IP_WAIT_AFTER_ALL_ATTEMPTS-delta; - } - else - { - if ((sp.retryCount%pc.UDP_SENDS_PER_PORT_EXTERNAL)==0) - sp.nextActionTime=time+pc.EXTERNAL_IP_WAIT_BETWEEN_PORTS-delta; - else - sp.nextActionTime=time+pc.TIME_BETWEEN_PUNCH_ATTEMPTS_EXTERNAL-delta; - } - } - } - - /* - // Remove elapsed groupRequestsInProgress - unsigned int i; - i=0; - while (i < groupRequestsInProgress.Size()) - { - if (time > groupRequestsInProgress[i].time) - groupRequestsInProgress.RemoveAtIndexFast(i); - else - i++; - } - */ -} -void NatPunchthroughClient::PushFailure(void) -{ - Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(unsigned char)); - p->data[0]=ID_NAT_PUNCHTHROUGH_FAILED; - p->systemAddress=sp.targetAddress; - p->systemAddress.systemIndex=(SystemIndex)-1; - p->guid=sp.targetGuid; - if (sp.weAreSender) - p->data[1]=1; - else - p->data[1]=0; - p->wasGeneratedLocally=true; - rakPeerInterface->PushBackPacket(p, true); -} -void NatPunchthroughClient::OnPunchthroughFailure(void) -{ - if (pc.retryOnFailure==false) - { - if (natPunchthroughDebugInterface) - { - char ipAddressString[32]; - sp.targetAddress.ToString(true, ipAddressString, static_cast(32)); - char guidString[128]; - sp.targetGuid.ToString(guidString, 128); - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("Failed punchthrough once. Returning failure to guid %s, system address %s to user.", guidString, ipAddressString)); - } - - PushFailure(); - OnReadyForNextPunchthrough(); - return; - } - - unsigned int i; - for (i=0; i < failedAttemptList.Size(); i++) - { - if (failedAttemptList[i].guid==sp.targetGuid) - { - if (natPunchthroughDebugInterface) - { - char ipAddressString[32]; - sp.targetAddress.ToString(true, ipAddressString, static_cast(32)); - char guidString[128]; - sp.targetGuid.ToString(guidString, 128); - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("Failed punchthrough twice. Returning failure to guid %s, system address %s to user.", guidString, ipAddressString)); - } - - // Failed a second time, so return failed to user - PushFailure(); - - OnReadyForNextPunchthrough(); - - failedAttemptList.RemoveAtIndexFast(i); - return; - } - } - - if (rakPeerInterface->GetConnectionState(sp.facilitator)!=IS_CONNECTED) - { - if (natPunchthroughDebugInterface) - { - char ipAddressString[32]; - sp.targetAddress.ToString(true, ipAddressString, static_cast(32)); - char guidString[128]; - sp.targetGuid.ToString(guidString, 128); - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("Not connected to facilitator, so cannot retry punchthrough after first failure. Returning failure onj guid %s, system address %s to user.", guidString, ipAddressString)); - } - - // Failed, and can't try again because no facilitator - PushFailure(); - return; - } - - if (natPunchthroughDebugInterface) - { - char ipAddressString[32]; - sp.targetAddress.ToString(true, ipAddressString, static_cast(32)); - char guidString[128]; - sp.targetGuid.ToString(guidString, 128); - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("First punchthrough failure on guid %s, system address %s. Reattempting.", guidString, ipAddressString)); - } - - // Failed the first time. Add to the failure queue and try again - AddrAndGuid aag; - aag.addr=sp.targetAddress; - aag.guid=sp.targetGuid; - failedAttemptList.Push(aag, _FILE_AND_LINE_); - - // Tell the server we are ready - OnReadyForNextPunchthrough(); - - // If we are the sender, try again, immediately if possible, else added to the queue on the faciltiator - if (sp.weAreSender) - SendPunchthrough(sp.targetGuid, sp.facilitator); -} -PluginReceiveResult NatPunchthroughClient::OnReceive(Packet *packet) -{ - switch (packet->data[0]) - { - case ID_NAT_GET_MOST_RECENT_PORT: - { - OnGetMostRecentPort(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - case ID_NAT_PUNCHTHROUGH_FAILED: - case ID_NAT_PUNCHTHROUGH_SUCCEEDED: - if (packet->wasGeneratedLocally==false) - return RR_STOP_PROCESSING_AND_DEALLOCATE; - break; - case ID_NAT_RESPOND_BOUND_ADDRESSES: - { - MafiaNet::BitStream bs(packet->data,packet->length,false); - bs.IgnoreBytes(sizeof(MessageID)); - unsigned char boundAddressCount; - bs.Read(boundAddressCount); - if (boundAddressCount<2) - { - if (natPunchthroughDebugInterface) - natPunchthroughDebugInterface->OnClientMessage(RakString("INCAPABLE_PORT_STRIDE. My external ID is %s", rakPeerInterface->GetExternalID(packet->systemAddress).ToString())); - - hasPortStride=INCAPABLE_PORT_STRIDE; - SendQueuedOpenNAT(); - } - SystemAddress boundAddresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS]; - for (int i=0; i < boundAddressCount && i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) - { - bs.Read(boundAddresses[i]); - if (boundAddresses[i]!=packet->systemAddress) - { - MafiaNet::BitStream outgoingBs; - outgoingBs.Write((MessageID)ID_NAT_PING); - uint16_t externalPort = rakPeerInterface->GetExternalID(packet->systemAddress).GetPort(); - outgoingBs.Write( externalPort ); - rakPeerInterface->SendOutOfBand((const char*) boundAddresses[i].ToString(false),boundAddresses[i].GetPort(),(const char*) outgoingBs.GetData(),outgoingBs.GetNumberOfBytesUsed()); - break; - } - } - } - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_OUT_OF_BAND_INTERNAL: - if (packet->length>=2 && packet->data[1]==ID_NAT_PONG) - { - MafiaNet::BitStream bs(packet->data,packet->length,false); - bs.IgnoreBytes(sizeof(MessageID)*2); - uint16_t externalPort; - bs.Read(externalPort); - uint16_t externalPort2; - bs.Read(externalPort2); - portStride = externalPort2 - externalPort; - mostRecentExternalPort = externalPort2; - hasPortStride=HAS_PORT_STRIDE; - - if (natPunchthroughDebugInterface) - natPunchthroughDebugInterface->OnClientMessage(RakString("HAS_PORT_STRIDE %i. First external port %i. Second external port %i.", portStride, externalPort, externalPort2)); - - SendQueuedOpenNAT(); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - else if (packet->length>=2 && - (packet->data[1]==ID_NAT_ESTABLISH_UNIDIRECTIONAL || packet->data[1]==ID_NAT_ESTABLISH_BIDIRECTIONAL) && - sp.nextActionTime!=0) - { - MafiaNet::BitStream bs(packet->data,packet->length,false); - bs.IgnoreBytes(2); - uint16_t sessionId; - bs.Read(sessionId); -// RakAssert(sessionId<100); - if (sessionId!=sp.sessionId) - break; - - char ipAddressString[32]; - packet->systemAddress.ToString(true,ipAddressString,static_cast(32)); - // sp.targetGuid==packet->guid is because the internal IP addresses reported may include loopbacks not reported by RakPeer::IsLocalIP() - if (packet->data[1]==ID_NAT_ESTABLISH_UNIDIRECTIONAL && sp.targetGuid==packet->guid) - { - - if (sp.testMode!=SendPing::PUNCHING_FIXED_PORT) - { - sp.testMode=SendPing::PUNCHING_FIXED_PORT; - sp.retryCount+=sp.attemptCount*pc.UDP_SENDS_PER_PORT_EXTERNAL; - sp.targetAddress=packet->systemAddress; - // Keeps trying until the other side gives up too, in case it is unidirectional - sp.punchingFixedPortAttempts=pc.UDP_SENDS_PER_PORT_EXTERNAL*(pc.MAX_PREDICTIVE_PORT_RANGE+1); - - if (natPunchthroughDebugInterface) - { - char guidString[128]; - sp.targetGuid.ToString(guidString, 128); - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("PUNCHING_FIXED_PORT: Received ID_NAT_ESTABLISH_UNIDIRECTIONAL from guid %s, system address %s.", guidString, ipAddressString)); - } - } - else { - if (natPunchthroughDebugInterface) - { - char guidString[128]; - sp.targetGuid.ToString(guidString, 128); - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("Received ID_NAT_ESTABLISH_UNIDIRECTIONAL from guid %s, system address %s.", guidString, ipAddressString)); - } - } - - SendOutOfBand(sp.targetAddress,ID_NAT_ESTABLISH_BIDIRECTIONAL); - } - else if (packet->data[1]==ID_NAT_ESTABLISH_BIDIRECTIONAL && - sp.targetGuid==packet->guid) - { - // They send back our port - unsigned short ourExternalPort; - bs.Read(ourExternalPort); - if (mostRecentExternalPort==0) - { - mostRecentExternalPort=ourExternalPort; - - if (natPunchthroughDebugInterface) - { - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("ID_NAT_ESTABLISH_BIDIRECTIONAL mostRecentExternalPort first time set to %i", mostRecentExternalPort)); - } - } - else - { - if (sp.testMode!=SendPing::TESTING_INTERNAL_IPS && sp.testMode!=SendPing::WAITING_FOR_INTERNAL_IPS_RESPONSE) - { - if (hasPortStride!=HAS_PORT_STRIDE) - { - portStride = ourExternalPort - mostRecentExternalPort; - hasPortStride=HAS_PORT_STRIDE; - - if (natPunchthroughDebugInterface) - { - natPunchthroughDebugInterface->OnClientMessage(RakString("ID_NAT_ESTABLISH_BIDIRECTIONAL: Estimated port stride from incoming connection at %i. ourExternalPort=%i mostRecentExternalPort=%i", portStride, ourExternalPort, mostRecentExternalPort)); - } - - SendQueuedOpenNAT(); - } - - //nextExternalPort += portStride * (pc.MAX_PREDICTIVE_PORT_RANGE+1); - mostRecentExternalPort = ourExternalPort; - - if (natPunchthroughDebugInterface) - { - natPunchthroughDebugInterface->OnClientMessage(RakString("ID_NAT_ESTABLISH_BIDIRECTIONAL: New mostRecentExternalPort %i", mostRecentExternalPort)); - } - } - } - SendOutOfBand(packet->systemAddress,ID_NAT_ESTABLISH_BIDIRECTIONAL); - - // Tell the user about the success - sp.targetAddress=packet->systemAddress; - PushSuccess(); - //UpdateGroupPunchOnNatResult(sp.facilitator, sp.targetGuid, sp.targetAddress, 1); - OnReadyForNextPunchthrough(); - bool removedFromFailureQueue=RemoveFromFailureQueue(); - - if (natPunchthroughDebugInterface) - { - char guidString[128]; - sp.targetGuid.ToString(guidString, 128); - if (removedFromFailureQueue) - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("Punchthrough to guid %s, system address %s succeeded on 2nd attempt.", guidString, ipAddressString)); - else - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("Punchthrough to guid %s, system address %s succeeded on 1st attempt.", guidString, ipAddressString)); - } - } - - // mostRecentNewExternalPort=packet->systemAddress.GetPort(); - } - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_NAT_ALREADY_IN_PROGRESS: - { - MafiaNet::BitStream incomingBs(packet->data, packet->length, false); - incomingBs.IgnoreBytes(sizeof(MessageID)); - RakNetGUID targetGuid; - incomingBs.Read(targetGuid); - // Don't update group, just use later message - // UpdateGroupPunchOnNatResult(packet->systemAddress, targetGuid, UNASSIGNED_SYSTEM_ADDRESS, 2); - if (natPunchthroughDebugInterface) - { - char guidString[128]; - targetGuid.ToString(guidString, 128); - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("Punchthrough retry to guid %s failed due to ID_NAT_ALREADY_IN_PROGRESS. Returning failure.", guidString)); - } - - } - break; - case ID_NAT_TARGET_NOT_CONNECTED: - case ID_NAT_CONNECTION_TO_TARGET_LOST: - case ID_NAT_TARGET_UNRESPONSIVE: - { - const char *reason; - if (packet->data[0]==ID_NAT_TARGET_NOT_CONNECTED) - reason=(char *)"ID_NAT_TARGET_NOT_CONNECTED"; - else if (packet->data[0]==ID_NAT_CONNECTION_TO_TARGET_LOST) - reason=(char *)"ID_NAT_CONNECTION_TO_TARGET_LOST"; - else - reason=(char *)"ID_NAT_TARGET_UNRESPONSIVE"; - - - MafiaNet::BitStream incomingBs(packet->data, packet->length, false); - incomingBs.IgnoreBytes(sizeof(MessageID)); - - RakNetGUID targetGuid; - incomingBs.Read(targetGuid); - //UpdateGroupPunchOnNatResult(packet->systemAddress, targetGuid, UNASSIGNED_SYSTEM_ADDRESS, 2); - - if (packet->data[0]==ID_NAT_CONNECTION_TO_TARGET_LOST || - packet->data[0]==ID_NAT_TARGET_UNRESPONSIVE) - { - uint16_t sessionId; - incomingBs.Read(sessionId); - if (sessionId!=sp.sessionId) - break; - } - - unsigned int i; - for (i=0; i < failedAttemptList.Size(); i++) - { - if (failedAttemptList[i].guid==targetGuid) - { - if (natPunchthroughDebugInterface) - { - char guidString[128]; - targetGuid.ToString(guidString, 128); - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("Punchthrough retry to guid %s failed due to %s.", guidString, reason)); - - } - - // If the retry target is not connected, or loses connection, or is not responsive, then previous failures cannot be retried. - - // Don't need to return failed, the other messages indicate failure anyway - /* - Packet *p = AllocatePacketUnified(sizeof(MessageID)); - p->data[0]=ID_NAT_PUNCHTHROUGH_FAILED; - p->systemAddress=failedAttemptList[i].addr; - p->systemAddress.systemIndex=(SystemIndex)-1; - p->guid=failedAttemptList[i].guid; - rakPeerInterface->PushBackPacket(p, false); - */ - - failedAttemptList.RemoveAtIndexFast(i); - break; - } - } - - if (natPunchthroughDebugInterface) - { - char guidString[128]; - targetGuid.ToString(guidString, 128); - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("Punchthrough attempt to guid %s failed due to %s.", guidString, reason)); - } - - // Stop trying punchthrough - sp.nextActionTime=0; - - /* - MafiaNet::BitStream bs(packet->data, packet->length, false); - bs.IgnoreBytes(sizeof(MessageID)); - RakNetGUID failedSystem; - bs.Read(failedSystem); - bool deletedFirst=false; - unsigned int i=0; - while (i < pendingOpenNAT.Size()) - { - if (pendingOpenNAT[i].destination==failedSystem) - { - if (i==0) - deletedFirst=true; - pendingOpenNAT.RemoveAtIndex(i); - } - else - i++; - } - // Failed while in progress. Go to next in attempt queue - if (deletedFirst && pendingOpenNAT.Size()) - { - SendPunchthrough(pendingOpenNAT[0].destination, pendingOpenNAT[0].facilitator); - sp.nextActionTime=0; - } - */ - } - break; - case ID_TIMESTAMP: - if (packet->data[sizeof(MessageID)+sizeof(MafiaNet::Time)]==ID_NAT_CONNECT_AT_TIME) - { - OnConnectAtTime(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - break; - } - return RR_CONTINUE_PROCESSING; -} -/* -void NatPunchthroughClient::ProcessNextPunchthroughQueue(void) -{ - // Go to the next attempt - if (pendingOpenNAT.Size()) - pendingOpenNAT.RemoveAtIndex(0); - - // Do next punchthrough attempt - if (pendingOpenNAT.Size()) - SendPunchthrough(pendingOpenNAT[0].destination, pendingOpenNAT[0].facilitator); - - sp.nextActionTime=0; -} -*/ -void NatPunchthroughClient::OnConnectAtTime(Packet *packet) -{ -// RakAssert(sp.nextActionTime==0); - - MafiaNet::BitStream bs(packet->data, packet->length, false); - bs.IgnoreBytes(sizeof(MessageID)); - bs.Read(sp.nextActionTime); - bs.IgnoreBytes(sizeof(MessageID)); - bs.Read(sp.sessionId); - bs.Read(sp.targetAddress); - int j; -// int k; -// k=0; - for (j=0; j < MAXIMUM_NUMBER_OF_INTERNAL_IDS; j++) - bs.Read(sp.internalIds[j]); - - // Prevents local testing - /* - for (j=0; j < MAXIMUM_NUMBER_OF_INTERNAL_IDS; j++) - { - SystemAddress id; - bs.Read(id); - char str[32]; - id.ToString(false,str); - if (rakPeerInterface->IsLocalIP(str)==false) - sp.internalIds[k++]=id; - } - */ - sp.attemptCount=0; - sp.retryCount=0; - if (pc.MAXIMUM_NUMBER_OF_INTERNAL_IDS_TO_CHECK>0) - { - sp.testMode=SendPing::TESTING_INTERNAL_IPS; - } - else - { - // TESTING: Try sending to unused ports on the remote system to reserve our own ports while not getting banned - //sp.testMode=SendPing::SEND_WITH_TTL; - sp.testMode=SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT; - sp.attemptCount=0; - sp.sentTTL=false; - } - bs.Read(sp.targetGuid); - bs.Read(sp.weAreSender); -} -void NatPunchthroughClient::SendTTL(const SystemAddress &sa) -{ - if (sa==UNASSIGNED_SYSTEM_ADDRESS) - return; - if (sa.GetPort()==0) - return; - - char ipAddressString[32]; - sa.ToString(false, ipAddressString,static_cast(32)); - // TTL of 1 doesn't get past the router, 2 might hit the other system on a LAN - rakPeerInterface->SendTTL(ipAddressString,sa.GetPort(), 2); -} - -const char *TestModeToString(NatPunchthroughClient::SendPing::TestMode tm) -{ - switch (tm) - { - case NatPunchthroughClient::SendPing::TESTING_INTERNAL_IPS: - return "TESTING_INTERNAL_IPS"; - break; - case NatPunchthroughClient::SendPing::WAITING_FOR_INTERNAL_IPS_RESPONSE: - return "WAITING_FOR_INTERNAL_IPS_RESPONSE"; - break; -// case NatPunchthroughClient::SendPing::SEND_WITH_TTL: -// return "SEND_WITH_TTL"; -// break; - case NatPunchthroughClient::SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT: - return "TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT"; - break; - case NatPunchthroughClient::SendPing::TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT: - return "TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT"; - break; - case NatPunchthroughClient::SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_1024: - return "TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_1024"; - break; - case NatPunchthroughClient::SendPing::TESTING_EXTERNAL_IPS_1024_TO_1024: - return "TESTING_EXTERNAL_IPS_1024_TO_1024"; - break; - case NatPunchthroughClient::SendPing::WAITING_AFTER_ALL_ATTEMPTS: - return "WAITING_AFTER_ALL_ATTEMPTS"; - break; - case NatPunchthroughClient::SendPing::PUNCHING_FIXED_PORT: - return "PUNCHING_FIXED_PORT"; - break; - } - return ""; -} -void NatPunchthroughClient::SendOutOfBand(SystemAddress sa, MessageID oobId) -{ - if (sa==UNASSIGNED_SYSTEM_ADDRESS) - return; - if (sa.GetPort()==0) - return; - - MafiaNet::BitStream oob; - oob.Write(oobId); - oob.Write(sp.sessionId); -// RakAssert(sp.sessionId<100); - if (oobId==ID_NAT_ESTABLISH_BIDIRECTIONAL) - oob.Write(sa.GetPort()); - char ipAddressString[32]; - sa.ToString(false, ipAddressString, static_cast(32)); - rakPeerInterface->SendOutOfBand((const char*) ipAddressString,sa.GetPort(),(const char*) oob.GetData(),oob.GetNumberOfBytesUsed()); - - if (natPunchthroughDebugInterface) - { - sa.ToString(true,ipAddressString,static_cast(32)); - char guidString[128]; - sp.targetGuid.ToString(guidString, 128); - - // server - diff = my time - // server = myTime + diff - MafiaNet::Time clockDifferential = rakPeerInterface->GetClockDifferential(sp.facilitator); - MafiaNet::Time serverTime = MafiaNet::GetTime() + clockDifferential; - - if (oobId==ID_NAT_ESTABLISH_UNIDIRECTIONAL) - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString(RAK_TIME_FORMAT_STRING ": %s: OOB ID_NAT_ESTABLISH_UNIDIRECTIONAL to guid %s, system address %s.\n", serverTime, TestModeToString(sp.testMode), guidString, ipAddressString)); - else - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString(RAK_TIME_FORMAT_STRING ": %s: OOB ID_NAT_ESTABLISH_BIDIRECTIONAL to guid %s, system address %s.\n", serverTime, TestModeToString(sp.testMode), guidString, ipAddressString)); - } -} -void NatPunchthroughClient::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) -{ - (void) rakNetGUID; - (void) isIncoming; - - // Try to track new port mappings on the router. Not reliable, but better than nothing. - SystemAddress ourExternalId = rakPeerInterface->GetExternalID(systemAddress); - if (ourExternalId!=UNASSIGNED_SYSTEM_ADDRESS && mostRecentExternalPort==0) { - mostRecentExternalPort=ourExternalId.GetPort(); - - if (natPunchthroughDebugInterface) - { - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("OnNewConnection mostRecentExternalPort first time set to %i", mostRecentExternalPort)); - } - } - - /* - unsigned int i; - i=0; - while (i < groupRequestsInProgress.Size()) - { - if (groupRequestsInProgress[i].guid==rakNetGUID) - { - groupRequestsInProgress.RemoveAtIndexFast(i); - } - else - { - i++; - } - } - */ -} - -void NatPunchthroughClient::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) systemAddress; - (void) rakNetGUID; - (void) lostConnectionReason; - - if (sp.facilitator==systemAddress) - { - // If we lose the connection to the facilitator, all previous failures not currently in progress are returned as such - unsigned int i=0; - while (i < failedAttemptList.Size()) - { - if (sp.nextActionTime!=0 && sp.targetGuid==failedAttemptList[i].guid) - { - i++; - continue; - } - - PushFailure(); - - failedAttemptList.RemoveAtIndexFast(i); - } - } - - /* - unsigned int i; - i=0; - while (i < groupPunchRequests.Size()) - { - if (groupPunchRequests[i]->facilitator==systemAddress) - { - MafiaNet::OP_DELETE(groupPunchRequests[i],_FILE_AND_LINE_); - groupPunchRequests.RemoveAtIndexFast(i); - } - else - { - i++; - } - } - */ - -} -void NatPunchthroughClient::GetUPNPPortMappings(char *externalPort, char *internalPort, const SystemAddress &natPunchthroughServerAddress) -{ - DataStructures::List< MafiaNet::RakNetSocket2* > sockets; - rakPeerInterface->GetSockets(sockets); - Itoa(sockets[0]->GetBoundAddress().GetPort(),internalPort,10); - if (mostRecentExternalPort==0) - mostRecentExternalPort=rakPeerInterface->GetExternalID(natPunchthroughServerAddress).GetPort(); - Itoa(mostRecentExternalPort,externalPort,10); -} -void NatPunchthroughClient::OnFailureNotification(Packet *packet) -{ - MafiaNet::BitStream incomingBs(packet->data,packet->length,false); - incomingBs.IgnoreBytes(sizeof(MessageID)); - RakNetGUID senderGuid; - incomingBs.Read(senderGuid); - - /* - unsigned int i; - i=0; - while (i < groupRequestsInProgress.Size()) - { - if (groupRequestsInProgress[i].guid==senderGuid) - { - groupRequestsInProgress.RemoveAtIndexFast(i); - break; - } - else - { - i++; - } - } - */ -} -void NatPunchthroughClient::OnGetMostRecentPort(Packet *packet) -{ - MafiaNet::BitStream incomingBs(packet->data,packet->length,false); - incomingBs.IgnoreBytes(sizeof(MessageID)); - uint16_t sessionId; - incomingBs.Read(sessionId); - - MafiaNet::BitStream outgoingBs; - outgoingBs.Write((MessageID)ID_NAT_GET_MOST_RECENT_PORT); - outgoingBs.Write(sessionId); - if (mostRecentExternalPort==0) - { - mostRecentExternalPort=rakPeerInterface->GetExternalID(packet->systemAddress).GetPort(); - RakAssert(mostRecentExternalPort!=0); - - if (natPunchthroughDebugInterface) - { - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("OnGetMostRecentPort mostRecentExternalPort first time set to %i", mostRecentExternalPort)); - } - } - - unsigned short portWithStride; - if (hasPortStride==HAS_PORT_STRIDE) - portWithStride = mostRecentExternalPort + portStride; - else - portWithStride = mostRecentExternalPort; - outgoingBs.Write(portWithStride); - - rakPeerInterface->Send(&outgoingBs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,packet->systemAddress,false); - sp.facilitator=packet->systemAddress; -} -/* -unsigned int NatPunchthroughClient::GetPendingOpenNATIndex(RakNetGUID destination, const SystemAddress &facilitator) -{ - unsigned int i; - for (i=0; i < pendingOpenNAT.Size(); i++) - { - if (pendingOpenNAT[i].destination==destination && pendingOpenNAT[i].facilitator==facilitator) - return i; - } - return (unsigned int) -1; -} -*/ -void NatPunchthroughClient::QueueOpenNAT(RakNetGUID destination, const SystemAddress &facilitator) -{ - DSTAndFac daf; - daf.destination=destination; - daf.facilitator=facilitator; - queuedOpenNat.Push(daf, _FILE_AND_LINE_); -} -void NatPunchthroughClient::SendQueuedOpenNAT(void) -{ - while (queuedOpenNat.IsEmpty()==false) - { - DSTAndFac daf = queuedOpenNat.Pop(); - SendPunchthrough(daf.destination, daf.facilitator); - } -} -void NatPunchthroughClient::SendPunchthrough(RakNetGUID destination, const SystemAddress &facilitator) -{ - MafiaNet::BitStream outgoingBs; - outgoingBs.Write((MessageID)ID_NAT_PUNCHTHROUGH_REQUEST); - outgoingBs.Write(destination); - rakPeerInterface->Send(&outgoingBs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,facilitator,false); - -// RakAssert(rakPeerInterface->GetSystemAddressFromGuid(destination)==UNASSIGNED_SYSTEM_ADDRESS); - - if (natPunchthroughDebugInterface) - { - char guidString[128]; - destination.ToString(guidString, 128); - natPunchthroughDebugInterface->OnClientMessage(MafiaNet::RakString("Starting ID_NAT_PUNCHTHROUGH_REQUEST to guid %s.", guidString)); - } -} -void NatPunchthroughClient::OnAttach(void) -{ - Clear(); -} -void NatPunchthroughClient::OnDetach(void) -{ - Clear(); -} -void NatPunchthroughClient::OnRakPeerShutdown(void) -{ - Clear(); -} -void NatPunchthroughClient::Clear(void) -{ - OnReadyForNextPunchthrough(); - - failedAttemptList.Clear(false, _FILE_AND_LINE_); - - queuedOpenNat.Clear(_FILE_AND_LINE_); - /* - groupRequestsInProgress.Clear(false, _FILE_AND_LINE_); - unsigned int i; - for (i=0; i < groupPunchRequests.Size(); i++) - { - MafiaNet::OP_DELETE(groupPunchRequests[i],_FILE_AND_LINE_); - } - groupPunchRequests.Clear(true, _FILE_AND_LINE_); - */ -} -PunchthroughConfiguration* NatPunchthroughClient::GetPunchthroughConfiguration(void) -{ - return &pc; -} -void NatPunchthroughClient::OnReadyForNextPunchthrough(void) -{ - if (rakPeerInterface==0) - return; - - sp.nextActionTime=0; - - MafiaNet::BitStream outgoingBs; - outgoingBs.Write((MessageID)ID_NAT_CLIENT_READY); - rakPeerInterface->Send(&outgoingBs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,sp.facilitator,false); -} - -void NatPunchthroughClient::PushSuccess(void) -{ - Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(unsigned char)); - p->data[0]=ID_NAT_PUNCHTHROUGH_SUCCEEDED; - p->systemAddress=sp.targetAddress; - p->systemAddress.systemIndex=(SystemIndex)-1; - p->guid=sp.targetGuid; - if (sp.weAreSender) - p->data[1]=1; - else - p->data[1]=0; - p->wasGeneratedLocally=true; - rakPeerInterface->PushBackPacket(p, true); -} -bool NatPunchthroughClient::RemoveFromFailureQueue(void) -{ - unsigned int i; - for (i=0; i < failedAttemptList.Size(); i++) - { - if (failedAttemptList[i].guid==sp.targetGuid) - { - // Remove from failure queue - failedAttemptList.RemoveAtIndexFast(i); - return true; - } - } - return false; -} - -void NatPunchthroughClient::IncrementExternalAttemptCount(MafiaNet::Time time, MafiaNet::Time delta) -{ - if (++sp.retryCount>=pc.UDP_SENDS_PER_PORT_EXTERNAL) - { - ++sp.attemptCount; - sp.retryCount=0; - sp.nextActionTime=time+pc.EXTERNAL_IP_WAIT_BETWEEN_PORTS-delta; - sp.sentTTL=false; - } - else - { - sp.nextActionTime=time+pc.TIME_BETWEEN_PUNCH_ATTEMPTS_EXTERNAL-delta; - } -} -/* -// 0=failed, 1=success, 2=ignore -void NatPunchthroughClient::UpdateGroupPunchOnNatResult(SystemAddress facilitator, RakNetGUID targetSystem, SystemAddress targetSystemAddress, int result) -{ - GroupPunchRequest *gpr; - unsigned long i,j,k; - i=0; - while (i < groupPunchRequests.Size()) - { - gpr = groupPunchRequests[i]; - if (gpr->facilitator==facilitator) - { - j=0; - while (j < gpr->pendingList.Size()) - { - if (gpr->pendingList[j]==targetSystem) - { - if (result==0) - { - gpr->failedList.Push(targetSystem, _FILE_AND_LINE_); - } - else if (result==1) - { - gpr->passedListGuid.Push(targetSystem, _FILE_AND_LINE_); - gpr->passedListAddress.Push(targetSystemAddress, _FILE_AND_LINE_); - } - else - { - gpr->ignoredList.Push(targetSystem, _FILE_AND_LINE_); - } - gpr->pendingList.RemoveAtIndex(j); - } - else - j++; - } - } - if (gpr->pendingList.Size()==0) - { - MafiaNet::BitStream output; - if (gpr->failedList.Size()==0) - { - output.Write(ID_NAT_GROUP_PUNCH_SUCCEEDED); - } - else - { - output.Write(ID_NAT_GROUP_PUNCH_FAILED); - } - - output.WriteCasted(gpr->passedListGuid.Size()); - for (k=0; k < gpr->passedListGuid.Size(); k++) - { - output.Write(gpr->passedListGuid[k]); - output.Write(gpr->passedListAddress[k]); - } - output.WriteCasted(gpr->ignoredList.Size()); - for (k=0; k < gpr->ignoredList.Size(); k++) - { - output.Write(gpr->ignoredList[k]); - } - output.WriteCasted(gpr->failedList.Size()); - for (k=0; k < gpr->failedList.Size(); k++) - { - output.Write(gpr->failedList[k]); - } - - Packet *p = AllocatePacketUnified(output.GetNumberOfBytesUsed()); - p->systemAddress=gpr->facilitator; - p->systemAddress.systemIndex=(SystemIndex)-1; - p->guid=rakPeerInterface->GetGuidFromSystemAddress(gpr->facilitator); - p->wasGeneratedLocally=true; - memcpy(p->data, output.GetData(), output.GetNumberOfBytesUsed()); - rakPeerInterface->PushBackPacket(p, true); - - groupPunchRequests.RemoveAtIndex(i); - MafiaNet::OP_DELETE(gpr, _FILE_AND_LINE_); - } - else - i++; - } -} -*/ - -#endif // _RAKNET_SUPPORT_* - diff --git a/vendors/mafianet/Source/src/NatPunchthroughServer.cpp b/vendors/mafianet/Source/src/NatPunchthroughServer.cpp deleted file mode 100644 index 627ec6a85..000000000 --- a/vendors/mafianet/Source/src/NatPunchthroughServer.cpp +++ /dev/null @@ -1,631 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_NatPunchthroughServer==1 - -#include "mafianet/NatPunchthroughServer.h" -#include "mafianet/SocketLayer.h" -#include "mafianet/BitStream.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/peerinterface.h" -#include "mafianet/MTUSize.h" -#include "mafianet/GetTime.h" -#include "mafianet/PacketLogger.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace MafiaNet; - -void NatPunchthroughServerDebugInterface_Printf::OnServerMessage(const char *msg) -{ - printf("%s\n", msg); -} -#if _RAKNET_SUPPORT_PacketLogger==1 -void NatPunchthroughServerDebugInterface_PacketLogger::OnServerMessage(const char *msg) -{ - if (pl) - { - pl->WriteMiscellaneous("Nat", msg); - } -} -#endif - -void NatPunchthroughServer::User::DeleteConnectionAttempt(NatPunchthroughServer::ConnectionAttempt *ca) -{ - unsigned int index = connectionAttempts.GetIndexOf(ca); - if ((unsigned int)index!=(unsigned int)-1) - { - MafiaNet::OP_DELETE(ca,_FILE_AND_LINE_); - connectionAttempts.RemoveAtIndex(index); - } -} -void NatPunchthroughServer::User::DerefConnectionAttempt(NatPunchthroughServer::ConnectionAttempt *ca) -{ - unsigned int index = connectionAttempts.GetIndexOf(ca); - if ((unsigned int)index!=(unsigned int)-1) - { - connectionAttempts.RemoveAtIndex(index); - } -} -bool NatPunchthroughServer::User::HasConnectionAttemptToUser(User *user) -{ - unsigned int index; - for (index=0; index < connectionAttempts.Size(); index++) - { - if (connectionAttempts[index]->recipient->guid==user->guid || - connectionAttempts[index]->sender->guid==user->guid) - return true; - } - return false; -} -void NatPunchthroughServer::User::LogConnectionAttempts(MafiaNet::RakString &rs) -{ - rs.Clear(); - unsigned int index; - char guidStr[128], ipStr[128]; - guid.ToString(guidStr, 128); - systemAddress.ToString(true,ipStr,static_cast(128)); - rs= MafiaNet::RakString("User systemAddress=%s guid=%s\n", ipStr, guidStr); - rs+= MafiaNet::RakString("%i attempts in list:\n", connectionAttempts.Size()); - for (index=0; index < connectionAttempts.Size(); index++) - { - rs+= MafiaNet::RakString("%i. SessionID=%i ", index+1, connectionAttempts[index]->sessionId); - if (connectionAttempts[index]->sender==this) - rs+="(We are sender) "; - else - rs+="(We are recipient) "; - if (isReady) - rs+="(READY TO START) "; - else - rs+="(NOT READY TO START) "; - if (connectionAttempts[index]->attemptPhase==NatPunchthroughServer::ConnectionAttempt::NAT_ATTEMPT_PHASE_NOT_STARTED) - rs+="(NOT_STARTED). "; - else - rs+="(GETTING_RECENT_PORTS). "; - if (connectionAttempts[index]->sender==this) - { - connectionAttempts[index]->recipient->guid.ToString(guidStr, 128); - connectionAttempts[index]->recipient->systemAddress.ToString(true,ipStr,static_cast(128)); - } - else - { - connectionAttempts[index]->sender->guid.ToString(guidStr, 128); - connectionAttempts[index]->sender->systemAddress.ToString(true,ipStr,static_cast(128)); - } - - rs+= MafiaNet::RakString("Target systemAddress=%s, guid=%s.\n", ipStr, guidStr); - } -} - -int MafiaNet::NatPunchthroughServer::NatPunchthroughUserComp( const RakNetGUID &key, User * const &data ) -{ - if (key < data->guid) - return -1; - if (key > data->guid) - return 1; - return 0; -} - -STATIC_FACTORY_DEFINITIONS(NatPunchthroughServer,NatPunchthroughServer); - -NatPunchthroughServer::NatPunchthroughServer() -{ - lastUpdate=0; - sessionId=0; - natPunchthroughServerDebugInterface=0; - for (int i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) - boundAddresses[i]=UNASSIGNED_SYSTEM_ADDRESS; - boundAddressCount=0; -} -NatPunchthroughServer::~NatPunchthroughServer() -{ - User *user, *otherUser; - ConnectionAttempt *connectionAttempt; - unsigned int j; - while(users.Size()) - { - user = users[0]; - for (j=0; j < user->connectionAttempts.Size(); j++) - { - connectionAttempt=user->connectionAttempts[j]; - if (connectionAttempt->sender==user) - otherUser=connectionAttempt->recipient; - else - otherUser=connectionAttempt->sender; - otherUser->DeleteConnectionAttempt(connectionAttempt); - } - MafiaNet::OP_DELETE(user,_FILE_AND_LINE_); - users[0]=users[users.Size()-1]; - users.RemoveAtIndex(users.Size()-1); - } -} -void NatPunchthroughServer::SetDebugInterface(NatPunchthroughServerDebugInterface *i) -{ - natPunchthroughServerDebugInterface=i; -} -void NatPunchthroughServer::Update(void) -{ - ConnectionAttempt *connectionAttempt; - User *user, *recipient; - unsigned int i,j; - MafiaNet::Time time = MafiaNet::GetTime(); - if (time > lastUpdate+250) - { - lastUpdate=time; - - for (i=0; i < users.Size(); i++) - { - user=users[i]; - for (j=0; j < user->connectionAttempts.Size(); j++) - { - connectionAttempt=user->connectionAttempts[j]; - if (connectionAttempt->sender==user) - { - if (connectionAttempt->attemptPhase!=ConnectionAttempt::NAT_ATTEMPT_PHASE_NOT_STARTED && - time > connectionAttempt->startTime && - time > 10000 + connectionAttempt->startTime ) // Formerly 5000, but sometimes false positives - { - MafiaNet::BitStream outgoingBs; - - // that other system might not be running the plugin - outgoingBs.Write((MessageID)ID_NAT_TARGET_UNRESPONSIVE); - outgoingBs.Write(connectionAttempt->recipient->guid); - outgoingBs.Write(connectionAttempt->sessionId); - rakPeerInterface->Send(&outgoingBs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,connectionAttempt->sender->systemAddress,false); - - // 05/28/09 Previously only told sender about ID_NAT_CONNECTION_TO_TARGET_LOST - // However, recipient may be expecting it due to external code - // In that case, recipient would never get any response if the sender dropped - outgoingBs.Reset(); - outgoingBs.Write((MessageID)ID_NAT_TARGET_UNRESPONSIVE); - outgoingBs.Write(connectionAttempt->sender->guid); - outgoingBs.Write(connectionAttempt->sessionId); - rakPeerInterface->Send(&outgoingBs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,connectionAttempt->recipient->systemAddress,false); - - connectionAttempt->sender->isReady=true; - connectionAttempt->recipient->isReady=true; - recipient=connectionAttempt->recipient; - - - if (natPunchthroughServerDebugInterface) - { - char str[1024]; - char addr1[128], addr2[128]; - // 8/01/09 Fixed bug where this was after DeleteConnectionAttempt() - connectionAttempt->sender->systemAddress.ToString(true,addr1,static_cast(128)); - connectionAttempt->recipient->systemAddress.ToString(true,addr2,static_cast(128)); - sprintf_s(str, "Sending ID_NAT_TARGET_UNRESPONSIVE to sender %s and recipient %s.", addr1, addr2); - natPunchthroughServerDebugInterface->OnServerMessage(str); - MafiaNet::RakString log; - connectionAttempt->sender->LogConnectionAttempts(log); - connectionAttempt->recipient->LogConnectionAttempts(log); - } - - - connectionAttempt->sender->DerefConnectionAttempt(connectionAttempt); - connectionAttempt->recipient->DeleteConnectionAttempt(connectionAttempt); - - StartPunchthroughForUser(user); - StartPunchthroughForUser(recipient); - - break; - } - } - } - } - } -} -PluginReceiveResult NatPunchthroughServer::OnReceive(Packet *packet) -{ - switch (packet->data[0]) - { - case ID_NAT_PUNCHTHROUGH_REQUEST: - OnNATPunchthroughRequest(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_NAT_GET_MOST_RECENT_PORT: - OnGetMostRecentPort(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_NAT_CLIENT_READY: - OnClientReady(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_NAT_REQUEST_BOUND_ADDRESSES: - { - MafiaNet::BitStream outgoingBs; - outgoingBs.Write((MessageID)ID_NAT_RESPOND_BOUND_ADDRESSES); - - if (boundAddresses[0]==UNASSIGNED_SYSTEM_ADDRESS) - { - DataStructures::List sockets; - rakPeerInterface->GetSockets(sockets); - for (unsigned i=0; i < sockets.Size() && i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) - { - boundAddresses[i]=sockets[i]->GetBoundAddress(); - boundAddressCount++; - } - } - - outgoingBs.Write(boundAddressCount); - for (int i=0; i < boundAddressCount; i++) - { - outgoingBs.Write(boundAddresses[i]); - } - - rakPeerInterface->Send(&outgoingBs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,packet->systemAddress,false); - } - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_NAT_PING: - { - } - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_OUT_OF_BAND_INTERNAL: - if (packet->length>=2 && packet->data[1]==ID_NAT_PING) - { - MafiaNet::BitStream bs(packet->data,packet->length,false); - bs.IgnoreBytes(sizeof(MessageID)*2); - uint16_t externalPort; - bs.Read(externalPort); - - MafiaNet::BitStream outgoingBs; - outgoingBs.Write((MessageID)ID_NAT_PONG); - outgoingBs.Write(externalPort); - uint16_t externalPort2 = packet->systemAddress.GetPort(); - outgoingBs.Write(externalPort2); - rakPeerInterface->SendOutOfBand((const char*) packet->systemAddress.ToString(false),packet->systemAddress.GetPort(),(const char*) outgoingBs.GetData(),outgoingBs.GetNumberOfBytesUsed()); - - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - } - return RR_CONTINUE_PROCESSING; -} -void NatPunchthroughServer::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) lostConnectionReason; - (void) systemAddress; - - unsigned int i=0; - bool objectExists; - i = users.GetIndexFromKey(rakNetGUID, &objectExists); - if (objectExists) - { - MafiaNet::BitStream outgoingBs; - DataStructures::List freedUpInProgressUsers; - User *user = users[i]; - User *otherUser; - unsigned int connectionAttemptIndex; - ConnectionAttempt *connectionAttempt; - for (connectionAttemptIndex=0; connectionAttemptIndex < user->connectionAttempts.Size(); connectionAttemptIndex++) - { - connectionAttempt=user->connectionAttempts[connectionAttemptIndex]; - outgoingBs.Reset(); - if (connectionAttempt->recipient==user) - { - otherUser=connectionAttempt->sender; - } - else - { - otherUser=connectionAttempt->recipient; - } - - // 05/28/09 Previously only told sender about ID_NAT_CONNECTION_TO_TARGET_LOST - // However, recipient may be expecting it due to external code - // In that case, recipient would never get any response if the sender dropped - outgoingBs.Write((MessageID)ID_NAT_CONNECTION_TO_TARGET_LOST); - outgoingBs.Write(rakNetGUID); - outgoingBs.Write(connectionAttempt->sessionId); - rakPeerInterface->Send(&outgoingBs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,otherUser->systemAddress,false); - - // 4/22/09 - Bug: was checking inProgress, legacy variable not used elsewhere - if (connectionAttempt->attemptPhase==ConnectionAttempt::NAT_ATTEMPT_PHASE_GETTING_RECENT_PORTS) - { - otherUser->isReady=true; - freedUpInProgressUsers.Insert(otherUser, _FILE_AND_LINE_ ); - } - - otherUser->DeleteConnectionAttempt(connectionAttempt); - } - - MafiaNet::OP_DELETE(users[i], _FILE_AND_LINE_); - users.RemoveAtIndex(i); - - for (i=0; i < freedUpInProgressUsers.Size(); i++) - { - StartPunchthroughForUser(freedUpInProgressUsers[i]); - } - } - - /* - // Also remove from groupPunchthroughRequests - for (i=0; i < users.Size(); i++) - { - bool objectExists; - unsigned int gprIndex; - gprIndex = users[i]->groupPunchthroughRequests.GetIndexFromKey(rakNetGUID, &objectExists); - if (objectExists) - { -// printf("DEBUG %i\n", __LINE__); - - MafiaNet::BitStream outgoingBs; - outgoingBs.Write((MessageID)ID_NAT_TARGET_NOT_CONNECTED); - outgoingBs.Write(rakNetGUID); - rakPeerInterface->Send(&outgoingBs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,users[i]->systemAddress,false); - - users[i]->groupPunchthroughRequests.RemoveAtIndex(gprIndex); - } - } - */ -} - -void NatPunchthroughServer::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) -{ - (void) systemAddress; - (void) isIncoming; - - User *user = MafiaNet::OP_NEW(_FILE_AND_LINE_); - user->guid=rakNetGUID; - user->mostRecentPort=0; - user->systemAddress=systemAddress; - user->isReady=true; - users.Insert(rakNetGUID, user, true, _FILE_AND_LINE_); - -// printf("Adding to users %s\n", rakNetGUID.ToString()); -// printf("DEBUG users[0] guid=%s\n", users[0]->guid.ToString()); -} -void NatPunchthroughServer::OnNATPunchthroughRequest(Packet *packet) -{ - MafiaNet::BitStream outgoingBs; - MafiaNet::BitStream incomingBs(packet->data, packet->length, false); - incomingBs.IgnoreBytes(sizeof(MessageID)); - RakNetGUID recipientGuid, senderGuid; - incomingBs.Read(recipientGuid); - senderGuid=packet->guid; - unsigned int i; - bool objectExists; - i = users.GetIndexFromKey(senderGuid, &objectExists); - RakAssert(objectExists); - - ConnectionAttempt *ca = MafiaNet::OP_NEW(_FILE_AND_LINE_); - ca->sender=users[i]; - ca->sessionId=sessionId++; - i = users.GetIndexFromKey(recipientGuid, &objectExists); - if (objectExists==false || ca->sender == ca->recipient) - { -// printf("DEBUG %i\n", __LINE__); -// printf("DEBUG recipientGuid=%s\n", recipientGuid.ToString()); -// printf("DEBUG users[0] guid=%s\n", users[0]->guid.ToString()); - - outgoingBs.Write((MessageID)ID_NAT_TARGET_NOT_CONNECTED); - outgoingBs.Write(recipientGuid); - rakPeerInterface->Send(&outgoingBs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,packet->systemAddress,false); - MafiaNet::OP_DELETE(ca,_FILE_AND_LINE_); - return; - } - ca->recipient=users[i]; - if (ca->recipient->HasConnectionAttemptToUser(ca->sender)) - { - outgoingBs.Write((MessageID)ID_NAT_ALREADY_IN_PROGRESS); - outgoingBs.Write(recipientGuid); - rakPeerInterface->Send(&outgoingBs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,packet->systemAddress,false); - MafiaNet::OP_DELETE(ca,_FILE_AND_LINE_); - return; - } - - ca->sender->connectionAttempts.Insert(ca, _FILE_AND_LINE_ ); - ca->recipient->connectionAttempts.Insert(ca, _FILE_AND_LINE_ ); - - StartPunchthroughForUser(ca->sender); -} -void NatPunchthroughServer::OnClientReady(Packet *packet) -{ - unsigned int i; - bool objectExists; - i = users.GetIndexFromKey(packet->guid, &objectExists); - if (objectExists) - { - users[i]->isReady=true; - StartPunchthroughForUser(users[i]); - } -} -void NatPunchthroughServer::OnGetMostRecentPort(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)); - uint16_t curSessionId; - unsigned short mostRecentPort; - bsIn.Read(curSessionId); - bsIn.Read(mostRecentPort); - - unsigned int i,j; - User *user; - ConnectionAttempt *connectionAttempt; - bool objectExists; - i = users.GetIndexFromKey(packet->guid, &objectExists); - - if (natPunchthroughServerDebugInterface) - { - MafiaNet::RakString log; - char addr1[128], addr2[128]; - packet->systemAddress.ToString(true,addr1,static_cast(128)); - packet->guid.ToString(addr2, 128); - log= MafiaNet::RakString("Got ID_NAT_GET_MOST_RECENT_PORT from systemAddress %s guid %s. port=%i. sessionId=%i. userFound=%i.", addr1, addr2, mostRecentPort, curSessionId, objectExists); - natPunchthroughServerDebugInterface->OnServerMessage(log.C_String()); - } - - if (objectExists) - { - user=users[i]; - user->mostRecentPort=mostRecentPort; - MafiaNet::Time time = MafiaNet::GetTime(); - - for (j=0; j < user->connectionAttempts.Size(); j++) - { - connectionAttempt=user->connectionAttempts[j]; - if (connectionAttempt->attemptPhase==ConnectionAttempt::NAT_ATTEMPT_PHASE_GETTING_RECENT_PORTS && - connectionAttempt->sender->mostRecentPort!=0 && - connectionAttempt->recipient->mostRecentPort!=0 && - // 04/29/08 add sessionId to prevent processing for other systems - connectionAttempt->sessionId== curSessionId) - { - SystemAddress senderSystemAddress = connectionAttempt->sender->systemAddress; - SystemAddress recipientSystemAddress = connectionAttempt->recipient->systemAddress; - SystemAddress recipientTargetAddress = recipientSystemAddress; - SystemAddress senderTargetAddress = senderSystemAddress; - recipientTargetAddress.SetPortHostOrder(connectionAttempt->recipient->mostRecentPort); - senderTargetAddress.SetPortHostOrder(connectionAttempt->sender->mostRecentPort); - - // Pick a time far enough in the future that both systems will have gotten the message - int targetPing = rakPeerInterface->GetAveragePing(recipientTargetAddress); - int senderPing = rakPeerInterface->GetAveragePing(senderSystemAddress); - MafiaNet::Time simultaneousAttemptTime; - if (targetPing==-1 || senderPing==-1) - simultaneousAttemptTime = time + 1500; - else - { - int largerPing = targetPing > senderPing ? targetPing : senderPing; - if (largerPing * 4 < 100) - simultaneousAttemptTime = time + 100; - else - simultaneousAttemptTime = time + (largerPing * 4); - } - - if (natPunchthroughServerDebugInterface) - { - MafiaNet::RakString log; - char addr1[128], addr2[128]; - recipientSystemAddress.ToString(true,addr1,static_cast(128)); - connectionAttempt->recipient->guid.ToString(addr2, 128); - log= MafiaNet::RakString("Sending ID_NAT_CONNECT_AT_TIME to recipient systemAddress %s guid %s", addr1, addr2); - natPunchthroughServerDebugInterface->OnServerMessage(log.C_String()); - } - - // Send to recipient timestamped message to connect at time - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_TIMESTAMP); - bsOut.Write(simultaneousAttemptTime); - bsOut.Write((MessageID)ID_NAT_CONNECT_AT_TIME); - bsOut.Write(connectionAttempt->sessionId); - bsOut.Write(senderTargetAddress); // Public IP, using most recent port - for (j=0; j < MAXIMUM_NUMBER_OF_INTERNAL_IDS; j++) // Internal IP - bsOut.Write(rakPeerInterface->GetInternalID(senderSystemAddress,j)); - bsOut.Write(connectionAttempt->sender->guid); - bsOut.Write(false); - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,recipientSystemAddress,false); - - - if (natPunchthroughServerDebugInterface) - { - MafiaNet::RakString log; - char addr1[128], addr2[128]; - senderSystemAddress.ToString(true,addr1,static_cast(128)); - connectionAttempt->sender->guid.ToString(addr2, 128); - log= MafiaNet::RakString("Sending ID_NAT_CONNECT_AT_TIME to sender systemAddress %s guid %s", addr1, addr2); - natPunchthroughServerDebugInterface->OnServerMessage(log.C_String()); - } - - - // Same for sender - bsOut.Reset(); - bsOut.Write((MessageID)ID_TIMESTAMP); - bsOut.Write(simultaneousAttemptTime); - bsOut.Write((MessageID)ID_NAT_CONNECT_AT_TIME); - bsOut.Write(connectionAttempt->sessionId); - bsOut.Write(recipientTargetAddress); // Public IP, using most recent port - for (j=0; j < MAXIMUM_NUMBER_OF_INTERNAL_IDS; j++) // Internal IP - bsOut.Write(rakPeerInterface->GetInternalID(recipientSystemAddress,j)); - bsOut.Write(connectionAttempt->recipient->guid); - bsOut.Write(true); - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,senderSystemAddress,false); - - connectionAttempt->recipient->DerefConnectionAttempt(connectionAttempt); - connectionAttempt->sender->DeleteConnectionAttempt(connectionAttempt); - - // 04/29/08 missing return - return; - } - } - } - else - { - - if (natPunchthroughServerDebugInterface) - { - MafiaNet::RakString log; - char addr1[128], addr2[128]; - packet->systemAddress.ToString(true,addr1,static_cast(128)); - packet->guid.ToString(addr2, 128); - log= MafiaNet::RakString("Ignoring ID_NAT_GET_MOST_RECENT_PORT from systemAddress %s guid %s", addr1, addr2); - natPunchthroughServerDebugInterface->OnServerMessage(log.C_String()); - } - - } -} -void NatPunchthroughServer::StartPunchthroughForUser(User *user) -{ - if (user->isReady==false) - return; - - ConnectionAttempt *connectionAttempt; - User *sender,*recipient,*otherUser; - unsigned int i; - for (i=0; i < user->connectionAttempts.Size(); i++) - { - connectionAttempt=user->connectionAttempts[i]; - if (connectionAttempt->sender==user) - { - otherUser=connectionAttempt->recipient; - sender=user; - recipient=otherUser; - } - else - { - otherUser=connectionAttempt->sender; - recipient=user; - sender=otherUser; - } - - if (otherUser->isReady) - { - if (natPunchthroughServerDebugInterface) - { - char str[1024]; - char addr1[128], addr2[128]; - sender->systemAddress.ToString(true,addr1,static_cast(128)); - recipient->systemAddress.ToString(true,addr2,static_cast(128)); - sprintf_s(str, "Sending NAT_ATTEMPT_PHASE_GETTING_RECENT_PORTS to sender %s and recipient %s.", addr1, addr2); - natPunchthroughServerDebugInterface->OnServerMessage(str); - } - - sender->isReady=false; - recipient->isReady=false; - connectionAttempt->attemptPhase=ConnectionAttempt::NAT_ATTEMPT_PHASE_GETTING_RECENT_PORTS; - connectionAttempt->startTime= MafiaNet::GetTime(); - - sender->mostRecentPort=0; - recipient->mostRecentPort=0; - - MafiaNet::BitStream outgoingBs; - outgoingBs.Write((MessageID)ID_NAT_GET_MOST_RECENT_PORT); - // 4/29/09 Write sessionID so we don't use returned port for a system we don't want - outgoingBs.Write(connectionAttempt->sessionId); - rakPeerInterface->Send(&outgoingBs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,sender->systemAddress,false); - rakPeerInterface->Send(&outgoingBs,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,recipient->systemAddress,false); - - // 4/22/09 - BUG: missing break statement here - break; - } - } -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/NatTypeDetectionClient.cpp b/vendors/mafianet/Source/src/NatTypeDetectionClient.cpp deleted file mode 100644 index c650e17d0..000000000 --- a/vendors/mafianet/Source/src/NatTypeDetectionClient.cpp +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_NatTypeDetectionClient==1 - -#include "mafianet/NatTypeDetectionClient.h" -#include "mafianet/smartptr.h" -#include "mafianet/BitStream.h" -#include "mafianet/SocketIncludes.h" -#include "mafianet/string.h" -#include "mafianet/peerinterface.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/SocketLayer.h" -#include "mafianet/SocketDefines.h" - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(NatTypeDetectionClient,NatTypeDetectionClient); - -NatTypeDetectionClient::NatTypeDetectionClient() -{ - c2=0; -} -NatTypeDetectionClient::~NatTypeDetectionClient() -{ - if (c2!=0) - { - MafiaNet::OP_DELETE(c2,_FILE_AND_LINE_); - } -} -void NatTypeDetectionClient::DetectNATType(SystemAddress _serverAddress) -{ - if (IsInProgress()) - return; - - if (c2==0) - { - DataStructures::List sockets; - rakPeerInterface->GetSockets(sockets); - //SystemAddress sockAddr; - //SocketLayer::GetSystemAddress(sockets[0], &sockAddr); - char str[64]; - //sockAddr.ToString(false,str); - sockets[0]->GetBoundAddress().ToString(false,str,static_cast(64)); - c2=CreateNonblockingBoundSocket(str -#ifdef __native_client__ - , sockets[0]->chromeInstance -#endif - ,this - ); - //c2Port=SocketLayer::GetLocalPort(c2); - } - -#if !defined(__native_client__) - if (c2->IsBerkleySocket()) - ((RNS2_Berkley*) c2)->CreateRecvPollingThread(0); -#endif - - serverAddress=_serverAddress; - - MafiaNet::BitStream bs; - bs.Write((unsigned char)ID_NAT_TYPE_DETECTION_REQUEST); - bs.Write(true); // IsRequest - bs.Write(c2->GetBoundAddress().GetPort()); - rakPeerInterface->Send(&bs,MafiaNet::Priority::Medium,MafiaNet::Reliability::Reliable,0,serverAddress,false); -} -void NatTypeDetectionClient::OnCompletion(NATTypeDetectionResult result) -{ - Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(unsigned char)*2); - //printf("Returning nat detection result to the user\n"); - p->data[0]=ID_NAT_TYPE_DETECTION_RESULT; - p->systemAddress=serverAddress; - p->systemAddress.systemIndex=(SystemIndex)-1; - p->guid=rakPeerInterface->GetGuidFromSystemAddress(serverAddress); - p->data[1]=(unsigned char) result; - p->wasGeneratedLocally=true; - rakPeerInterface->PushBackPacket(p, true); - - // Symmetric and port restricted are determined by server, so no need to notify server we are done - if (result!=NAT_TYPE_PORT_RESTRICTED && result!=NAT_TYPE_SYMMETRIC) - { - // Otherwise tell the server we got this message, so it stops sending tests to us - MafiaNet::BitStream bs; - bs.Write((unsigned char)ID_NAT_TYPE_DETECTION_REQUEST); - bs.Write(false); // Done - rakPeerInterface->Send(&bs,MafiaNet::Priority::High,MafiaNet::Reliability::Reliable,0,serverAddress,false); - } - - Shutdown(); -} -bool NatTypeDetectionClient::IsInProgress(void) const -{ - return serverAddress!=UNASSIGNED_SYSTEM_ADDRESS; -} -void NatTypeDetectionClient::Update(void) -{ - if (IsInProgress()) - { - RNS2RecvStruct *recvStruct; - bufferedPacketsMutex.Lock(); - if (bufferedPackets.Size()>0) - recvStruct=bufferedPackets.Pop(); - else - recvStruct=0; - bufferedPacketsMutex.Unlock(); - while (recvStruct) - { - if (recvStruct->bytesRead==1 && recvStruct->data[0]==NAT_TYPE_NONE) - { - OnCompletion(NAT_TYPE_NONE); - RakAssert(IsInProgress()==false); - } - DeallocRNS2RecvStruct(recvStruct, _FILE_AND_LINE_); - - bufferedPacketsMutex.Lock(); - if (bufferedPackets.Size()>0) - recvStruct=bufferedPackets.Pop(); - else - recvStruct=0; - bufferedPacketsMutex.Unlock(); - } - } -} -PluginReceiveResult NatTypeDetectionClient::OnReceive(Packet *packet) -{ - if (IsInProgress()) - { - switch (packet->data[0]) - { - case ID_OUT_OF_BAND_INTERNAL: - { - if (packet->length>=3 && packet->data[1]==ID_NAT_TYPE_DETECT) - { - OnCompletion((NATTypeDetectionResult)packet->data[2]); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - } - break; - case ID_NAT_TYPE_DETECTION_RESULT: - if (packet->wasGeneratedLocally==false) - { - OnCompletion((NATTypeDetectionResult)packet->data[1]); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - else - break; - case ID_NAT_TYPE_DETECTION_REQUEST: - OnTestPortRestricted(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - } - - return RR_CONTINUE_PROCESSING; -} -void NatTypeDetectionClient::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) lostConnectionReason; - (void) rakNetGUID; - - if (IsInProgress() && systemAddress==serverAddress) - Shutdown(); -} -void NatTypeDetectionClient::OnRakPeerShutdown(void) -{ - Shutdown(); -} -void NatTypeDetectionClient::OnDetach(void) -{ - Shutdown(); -} -void NatTypeDetectionClient::OnTestPortRestricted(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(sizeof(MessageID)); - MafiaNet::RakString s3p4StrAddress; - bsIn.Read(s3p4StrAddress); - unsigned short s3p4Port; - bsIn.Read(s3p4Port); - - DataStructures::List sockets; - rakPeerInterface->GetSockets(sockets); - SystemAddress s3p4Addr = sockets[0]->GetBoundAddress(); - s3p4Addr.FromStringExplicitPort(s3p4StrAddress.C_String(), s3p4Port); - - // Send off the RakNet socket to the specified address, message is unformatted - // Server does this twice, so don't have to unduly worry about packetloss - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID) NAT_TYPE_PORT_RESTRICTED); - bsOut.Write(rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); -// SocketLayer::SendTo_PC( sockets[0], (const char*) bsOut.GetData(), bsOut.GetNumberOfBytesUsed(), s3p4Addr, __FILE__, __LINE__ ); - - RNS2_SendParameters bsp; - bsp.data = (char*) bsOut.GetData(); - bsp.length = bsOut.GetNumberOfBytesUsed(); - bsp.systemAddress=s3p4Addr; - sockets[0]->Send(&bsp, _FILE_AND_LINE_); - -} -void NatTypeDetectionClient::Shutdown(void) -{ - serverAddress=UNASSIGNED_SYSTEM_ADDRESS; - if (c2!=0) - { -#if !defined(__native_client__) - if (c2->IsBerkleySocket()) - ((RNS2_Berkley *)c2)->BlockOnStopRecvPollingThread(); -#endif - - MafiaNet::OP_DELETE(c2, _FILE_AND_LINE_); - c2=0; - } - - bufferedPacketsMutex.Lock(); - while (bufferedPackets.Size()) - MafiaNet::OP_DELETE(bufferedPackets.Pop(), _FILE_AND_LINE_); - bufferedPacketsMutex.Unlock(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void NatTypeDetectionClient::DeallocRNS2RecvStruct(RNS2RecvStruct *s, const char *file, unsigned int line) -{ - MafiaNet::OP_DELETE(s, file, line); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -RNS2RecvStruct *NatTypeDetectionClient::AllocRNS2RecvStruct(const char *file, unsigned int line) -{ - return MafiaNet::OP_NEW(file,line); -} -void NatTypeDetectionClient::OnRNS2Recv(RNS2RecvStruct *recvStruct) -{ - bufferedPacketsMutex.Lock(); - bufferedPackets.Push(recvStruct,_FILE_AND_LINE_); - bufferedPacketsMutex.Unlock(); -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/NatTypeDetectionCommon.cpp b/vendors/mafianet/Source/src/NatTypeDetectionCommon.cpp deleted file mode 100644 index 8685858ae..000000000 --- a/vendors/mafianet/Source/src/NatTypeDetectionCommon.cpp +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NatTypeDetectionCommon.h" - -#if _RAKNET_SUPPORT_NatTypeDetectionServer==1 || _RAKNET_SUPPORT_NatTypeDetectionClient==1 - -#include "mafianet/SocketLayer.h" -#include "mafianet/SocketIncludes.h" -#include "mafianet/SocketDefines.h" - -using namespace MafiaNet; - -bool MafiaNet::CanConnect(NATTypeDetectionResult type1, NATTypeDetectionResult type2) -{ - /// If one system is NAT_TYPE_SYMMETRIC, the other must be NAT_TYPE_ADDRESS_RESTRICTED or less - /// If one system is NAT_TYPE_PORT_RESTRICTED, the other must be NAT_TYPE_PORT_RESTRICTED or less - bool connectionGraph[NAT_TYPE_COUNT][NAT_TYPE_COUNT] = - { - // None, Full Cone, Address Restricted, Port Restricted, Symmetric, Unknown, InProgress, Supports_UPNP - {true, true, true, true, true, false, false, true}, // None - {true, true, true, true, true, false, false, true}, // Full Cone - {true, true, true, true, true, false, false, true}, // Address restricted - {true, true, true, true, false, false, false, true}, // Port restricted - {true, true, true, false, false, false, false, true}, // Symmetric - {false, false, false, false, false, false, false, false}, // Unknown - {false, false, false, false, false, false, false, false}, // InProgress - {true, true, true, true, true, false, false, true} // Supports_UPNP - }; - - return connectionGraph[(int) type1][(int) type2]; -} - -const char *MafiaNet::NATTypeDetectionResultToString(NATTypeDetectionResult type) -{ - switch (type) - { - case NAT_TYPE_NONE: - return "None"; - case NAT_TYPE_FULL_CONE: - return "Full cone"; - case NAT_TYPE_ADDRESS_RESTRICTED: - return "Address restricted"; - case NAT_TYPE_PORT_RESTRICTED: - return "Port restricted"; - case NAT_TYPE_SYMMETRIC: - return "Symmetric"; - case NAT_TYPE_UNKNOWN: - return "Unknown"; - case NAT_TYPE_DETECTION_IN_PROGRESS: - return "In Progress"; - case NAT_TYPE_SUPPORTS_UPNP: - return "Supports UPNP"; - case NAT_TYPE_COUNT: - return "NAT_TYPE_COUNT"; - } - return "Error, unknown enum in NATTypeDetectionResult"; -} - -// None and relaxed can connect to anything -// Moderate can connect to moderate or less -// Strict can connect to relaxed or less -const char *MafiaNet::NATTypeDetectionResultToStringFriendly(NATTypeDetectionResult type) -{ - switch (type) - { - case NAT_TYPE_NONE: - return "Open"; - case NAT_TYPE_FULL_CONE: - return "Relaxed"; - case NAT_TYPE_ADDRESS_RESTRICTED: - return "Relaxed"; - case NAT_TYPE_PORT_RESTRICTED: - return "Moderate"; - case NAT_TYPE_SYMMETRIC: - return "Strict"; - case NAT_TYPE_UNKNOWN: - return "Unknown"; - case NAT_TYPE_DETECTION_IN_PROGRESS: - return "In Progress"; - case NAT_TYPE_SUPPORTS_UPNP: - return "Supports UPNP"; - case NAT_TYPE_COUNT: - return "NAT_TYPE_COUNT"; - } - return "Error, unknown enum in NATTypeDetectionResult"; -} - - -RakNetSocket2* MafiaNet::CreateNonblockingBoundSocket(const char *bindAddr -#ifdef __native_client__ - ,_PP_Instance_ chromeInstance -#endif - , RNS2EventHandler *eventHandler - ) -{ - RakNetSocket2 *r2 = RakNetSocket2Allocator::AllocRNS2(); -#if defined(__native_client__) - NativeClientBindParameters ncbp; - RNS2_NativeClient * nativeClientSocket = (RNS2_NativeClient*) r2; - ncbp.eventHandler=eventHandler; - ncbp.forceHostAddress=(char*) bindAddr; - ncbp.is_ipv6=false; - ncbp.nativeClientInstance=chromeInstance; - ncbp.port=0; - nativeClientSocket->Bind(&ncbp, _FILE_AND_LINE_); -#else - if (r2->IsBerkleySocket()) - { - RNS2_BerkleyBindParameters bbp; - bbp.port=0; - bbp.hostAddress=(char*)bindAddr; - bbp.addressFamily=AF_INET; - bbp.type=SOCK_DGRAM; - bbp.protocol=0; - bbp.nonBlockingSocket=true; - bbp.setBroadcast=true; - bbp.setIPHdrIncl=false; - bbp.doNotFragment=false; - bbp.pollingThreadPriority=0; - bbp.eventHandler=eventHandler; - bbp.remotePortRakNetWasStartedOn_PS3_PS4_PSP2=0; - RNS2BindResult br = ((RNS2_Berkley*) r2)->Bind(&bbp, _FILE_AND_LINE_); - - if (br==BR_FAILED_TO_BIND_SOCKET) - { - RakNetSocket2Allocator::DeallocRNS2(r2); - return 0; - } - else if (br==BR_FAILED_SEND_TEST) - { - RakNetSocket2Allocator::DeallocRNS2(r2); - return 0; - } - else - { - RakAssert(br==BR_SUCCESS); - } - - ((RNS2_Berkley*) r2)->CreateRecvPollingThread(0); - } - else - { - RakAssert("TODO" && 0); - } -#endif - - return r2; - - /* - #ifdef __native_client__ - RakNetSocket2 *s = SocketLayer::CreateBoundSocket( 0, 0, false, bindAddr, true, 0, AF_INET, chromeInstance ); - #else - RakNetSocket2 *s = SocketLayer::CreateBoundSocket( 0, 0, false, bindAddr, true, 0, AF_INET, 0 ); - #endif - - #ifdef _WIN32 - unsigned long nonblocking = 1; - s->IOCTLSocket( FIONBIO, &nonblocking ); - #elif defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3) || defined(_PS4) || defined(SN_TARGET_PSP2) - int sock_opt=1; - s->SetSockOpt(SOL_SOCKET, SO_NBIO, ( char * ) & sock_opt, sizeof ( sock_opt ) ); - #elif defined(__native_client__) - // Nop - #else - s->Fcntl( F_SETFL, O_NONBLOCK ); - #endif - return s; - */ -} - -/* -int MafiaNet::NatTypeRecvFrom(char *data, RakNetSocket2* socket, SystemAddress &sender, RNS2EventHandler *eventHandler) -{ -#if defined(__native_client__) - RakAssert("TODO" && 0); -#else - if (socket->IsBerkleySocket()) - { - RNS2RecvStruct *recvFromStruct; - recvFromStruct=AllocRNS2RecvStruct(_FILE_AND_LINE_); - if (recvFromStruct != nullptr) - { - recvFromStruct->socket=this; - socket->RecvFromBlocking(recvFromStruct); - } - if (recvFromStruct->bytesRead>0) - { - sender = recvFromStruct->systemAddress; - } - return recvFromStruct->bytesRead; - } - return 0; -#endif -} -*/ - -#endif // #if _RAKNET_SUPPORT_NatTypeDetectionServer==1 || _RAKNET_SUPPORT_NatTypeDetectionClient==1 diff --git a/vendors/mafianet/Source/src/NatTypeDetectionServer.cpp b/vendors/mafianet/Source/src/NatTypeDetectionServer.cpp deleted file mode 100644 index 19465d324..000000000 --- a/vendors/mafianet/Source/src/NatTypeDetectionServer.cpp +++ /dev/null @@ -1,445 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_NatTypeDetectionServer==1 - -#include "mafianet/NatTypeDetectionServer.h" -#include "mafianet/SocketLayer.h" -#include "mafianet/smartptr.h" -#include "mafianet/SocketIncludes.h" -#include "mafianet/peerinterface.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/GetTime.h" -#include "mafianet/BitStream.h" -#include "mafianet/SocketDefines.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -// #define NTDS_VERBOSE - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(NatTypeDetectionServer,NatTypeDetectionServer); - -NatTypeDetectionServer::NatTypeDetectionServer() -{ - s1p2=s2p3=s3p4=s4p5=0; -} -NatTypeDetectionServer::~NatTypeDetectionServer() -{ - Shutdown(); -} -void NatTypeDetectionServer::Startup( - const char *nonRakNetIP2, - const char *nonRakNetIP3, - const char *nonRakNetIP4 -#ifdef __native_client__ - ,_PP_Instance_ chromeInstance -#endif - ) -{ - DataStructures::List sockets; - rakPeerInterface->GetSockets(sockets); - char str[64]; - sockets[0]->GetBoundAddress().ToString(false,str,static_cast(64)); - s1p2= - CreateNonblockingBoundSocket(str, -#ifdef __native_client__ - chromeInstance, -#endif - this); - - s2p3= - CreateNonblockingBoundSocket(nonRakNetIP2, -#ifdef __native_client__ - chromeInstance, -#endif - this); - - - s3p4= - CreateNonblockingBoundSocket(nonRakNetIP3, -#ifdef __native_client__ - chromeInstance, -#endif - this); - - s4p5= - CreateNonblockingBoundSocket(nonRakNetIP4, -#ifdef __native_client__ - chromeInstance, -#endif - this); - - strcpy_s(s3p4Address, nonRakNetIP3); - - - #if !defined(__native_client__) - if (s3p4->IsBerkleySocket()) - ((RNS2_Berkley*) s3p4)->CreateRecvPollingThread(0); - #endif -} -void NatTypeDetectionServer::Shutdown() -{ - if (s1p2!=0) - { - MafiaNet::OP_DELETE(s1p2,_FILE_AND_LINE_); - s1p2=0; - } - if (s2p3!=0) - { - MafiaNet::OP_DELETE(s2p3,_FILE_AND_LINE_); - s2p3=0; - } - if (s3p4!=0) - { -#if !defined(__native_client__) - if (s3p4->IsBerkleySocket()) - ((RNS2_Berkley *)s3p4)->BlockOnStopRecvPollingThread(); -#endif - - MafiaNet::OP_DELETE(s3p4,_FILE_AND_LINE_); - s3p4=0; - } - if (s4p5!=0) - { - MafiaNet::OP_DELETE(s4p5,_FILE_AND_LINE_); - s4p5=0; - } - bufferedPacketsMutex.Lock(); - while (bufferedPackets.Size()) - MafiaNet::OP_DELETE(bufferedPackets.Pop(), _FILE_AND_LINE_); - bufferedPacketsMutex.Unlock(); -} -void NatTypeDetectionServer::Update(void) -{ - int i=0; - MafiaNet::TimeMS time = MafiaNet::GetTimeMS(); - MafiaNet::BitStream bs; - SystemAddress boundAddress; - - RNS2RecvStruct *recvStruct; - bufferedPacketsMutex.Lock(); - if (bufferedPackets.Size()>0) - recvStruct=bufferedPackets.Pop(); - else - recvStruct=0; - bufferedPacketsMutex.Unlock(); - while (recvStruct) - { - SystemAddress senderAddr = recvStruct->systemAddress; - char *data = recvStruct->data; - if (data[0]==NAT_TYPE_PORT_RESTRICTED && recvStruct->socket==s3p4) - { - MafiaNet::BitStream bsIn((unsigned char*) data,recvStruct->bytesRead,false); - RakNetGUID senderGuid; - bsIn.IgnoreBytes(sizeof(MessageID)); - bool readSuccess = bsIn.Read(senderGuid); - RakAssert(readSuccess); - if (readSuccess) - { - unsigned int j = GetDetectionAttemptIndex(senderGuid); - if (j!=(unsigned int)-1) - { - bs.Reset(); - bs.Write((unsigned char) ID_NAT_TYPE_DETECTION_RESULT); - // If different, then symmetric - if (senderAddr!=natDetectionAttempts[j].systemAddress) - { - -#ifdef NTDS_VERBOSE - printf("Determined client is symmetric\n"); -#endif - bs.Write((unsigned char) NAT_TYPE_SYMMETRIC); - } - else - { - // else port restricted -#ifdef NTDS_VERBOSE - - printf("Determined client is port restricted\n"); -#endif - bs.Write((unsigned char) NAT_TYPE_PORT_RESTRICTED); - } - - rakPeerInterface->Send(&bs,MafiaNet::Priority::High,MafiaNet::Reliability::Reliable,0,natDetectionAttempts[j].systemAddress,false); - - // Done - natDetectionAttempts.RemoveAtIndexFast(j); - } - else - { - // RakAssert("j==0 in Update when looking up GUID in NatTypeDetectionServer.cpp. Either a bug or a late resend" && 0); - } - } - else - { - // RakAssert("Didn't read GUID in Update in NatTypeDetectionServer.cpp. Message format error" && 0); - } - } - - DeallocRNS2RecvStruct(recvStruct, _FILE_AND_LINE_); - bufferedPacketsMutex.Lock(); - if (bufferedPackets.Size()>0) - recvStruct=bufferedPackets.Pop(); - else - recvStruct=0; - bufferedPacketsMutex.Unlock(); - } - - /* - - // Only socket that receives messages is s3p4, to see if the external address is different than that of the connection to rakPeerInterface - char data[ MAXIMUM_MTU_SIZE ]; - int len; - SystemAddress senderAddr; - len=NatTypeRecvFrom(data, s3p4, senderAddr); - // Client is asking us if this is port restricted. Only client requests of this type come in on s3p4 - while (len>0 && data[0]==NAT_TYPE_PORT_RESTRICTED) - { - MafiaNet::BitStream bsIn((unsigned char*) data,len,false); - RakNetGUID senderGuid; - bsIn.IgnoreBytes(sizeof(MessageID)); - bool readSuccess = bsIn.Read(senderGuid); - RakAssert(readSuccess); - if (readSuccess) - { - unsigned int i = GetDetectionAttemptIndex(senderGuid); - if (i!=(unsigned int)-1) - { - bs.Reset(); - bs.Write((unsigned char) ID_NAT_TYPE_DETECTION_RESULT); - // If different, then symmetric - if (senderAddr!=natDetectionAttempts[i].systemAddress) - { - - #ifdef NTDS_VERBOSE - printf("Determined client is symmetric\n"); - #endif - bs.Write((unsigned char) NAT_TYPE_SYMMETRIC); - } - else - { - // else port restricted - - #ifdef NTDS_VERBOSE - printf("Determined client is port restricted\n"); - #endif - bs.Write((unsigned char) NAT_TYPE_PORT_RESTRICTED); - } - - rakPeerInterface->Send(&bs,MafiaNet::Priority::High,MafiaNet::Reliability::Reliable,0,natDetectionAttempts[i].systemAddress,false); - - // Done - natDetectionAttempts.RemoveAtIndexFast(i); - } - else - { - // RakAssert("i==0 in Update when looking up GUID in NatTypeDetectionServer.cpp. Either a bug or a late resend" && 0); - } - } - else - { - // RakAssert("Didn't read GUID in Update in NatTypeDetectionServer.cpp. Message format error" && 0); - } - - len=NatTypeRecvFrom(data, s3p4, senderAddr); - } - */ - - - while (i < (int) natDetectionAttempts.Size()) - { - if (time > natDetectionAttempts[i].nextStateTime) - { - RNS2_SendParameters bsp; - natDetectionAttempts[i].detectionState=(NATDetectionState)((int)natDetectionAttempts[i].detectionState+1); - natDetectionAttempts[i].nextStateTime=time+natDetectionAttempts[i].timeBetweenAttempts; - SystemAddress saOut; - unsigned char c; - bs.Reset(); - switch (natDetectionAttempts[i].detectionState) - { - case STATE_TESTING_NONE_1: - case STATE_TESTING_NONE_2: - c = NAT_TYPE_NONE; - -#ifdef NTDS_VERBOSE - printf("Testing NAT_TYPE_NONE\n"); -#endif - // S4P5 sends to C2. If arrived, no NAT. Done. (Else S4P5 potentially banned, do not use again). - saOut=natDetectionAttempts[i].systemAddress; - saOut.SetPortHostOrder(natDetectionAttempts[i].c2Port); - // SocketLayer::SendTo_PC( s4p5, (const char*) &c, 1, saOut, __FILE__, __LINE__ ); - bsp.data = (char*) &c; - bsp.length = 1; - bsp.systemAddress = saOut; - s4p5->Send(&bsp, _FILE_AND_LINE_); - break; - case STATE_TESTING_FULL_CONE_1: - case STATE_TESTING_FULL_CONE_2: - -#ifdef NTDS_VERBOSE - printf("Testing NAT_TYPE_FULL_CONE\n"); -#endif - rakPeerInterface->WriteOutOfBandHeader(&bs); - bs.Write((unsigned char) ID_NAT_TYPE_DETECT); - bs.Write((unsigned char) NAT_TYPE_FULL_CONE); - // S2P3 sends to C1 (Different address, different port, to previously used port on client). If received, Full-cone nat. Done. (Else S2P3 potentially banned, do not use again). - saOut=natDetectionAttempts[i].systemAddress; - saOut.SetPortHostOrder(natDetectionAttempts[i].systemAddress.GetPort()); - // SocketLayer::SendTo_PC( s2p3, (const char*) bs.GetData(), bs.GetNumberOfBytesUsed(), saOut, __FILE__, __LINE__ ); - bsp.data = (char*) bs.GetData(); - bsp.length = bs.GetNumberOfBytesUsed(); - bsp.systemAddress = saOut; - s2p3->Send(&bsp, _FILE_AND_LINE_); - break; - case STATE_TESTING_ADDRESS_RESTRICTED_1: - case STATE_TESTING_ADDRESS_RESTRICTED_2: - -#ifdef NTDS_VERBOSE - printf("Testing NAT_TYPE_ADDRESS_RESTRICTED\n"); -#endif - rakPeerInterface->WriteOutOfBandHeader(&bs); - bs.Write((unsigned char) ID_NAT_TYPE_DETECT); - bs.Write((unsigned char) NAT_TYPE_ADDRESS_RESTRICTED); - // S1P2 sends to C1 (Same address, different port, to previously used port on client). If received, address-restricted cone nat. Done. - saOut=natDetectionAttempts[i].systemAddress; - saOut.SetPortHostOrder(natDetectionAttempts[i].systemAddress.GetPort()); - //SocketLayer::SendTo_PC( s1p2, (const char*) bs.GetData(), bs.GetNumberOfBytesUsed(), saOut, __FILE__, __LINE__ ); - bsp.data = (char*) bs.GetData(); - bsp.length = bs.GetNumberOfBytesUsed(); - bsp.systemAddress = saOut; - s1p2->Send(&bsp, _FILE_AND_LINE_); - break; - case STATE_TESTING_PORT_RESTRICTED_1: - case STATE_TESTING_PORT_RESTRICTED_2: - // C1 sends to S3P4. If address of C1 as seen by S3P4 is the same as the address of C1 as seen by S1P1, then port-restricted cone nat. Done - -#ifdef NTDS_VERBOSE - printf("Testing NAT_TYPE_PORT_RESTRICTED\n"); -#endif - bs.Write((unsigned char) ID_NAT_TYPE_DETECTION_REQUEST); - bs.Write(RakString::NonVariadic(s3p4Address)); - bs.Write(s3p4->GetBoundAddress().GetPort()); - rakPeerInterface->Send(&bs,MafiaNet::Priority::High,MafiaNet::Reliability::Reliable,0,natDetectionAttempts[i].systemAddress,false); - break; - default: - -#ifdef NTDS_VERBOSE - printf("Warning, exceeded final check STATE_TESTING_PORT_RESTRICTED_2.\nExpected that client would have sent NAT_TYPE_PORT_RESTRICTED on s3p4.\nDefaulting to Symmetric\n"); -#endif - bs.Write((unsigned char) ID_NAT_TYPE_DETECTION_RESULT); - bs.Write((unsigned char) NAT_TYPE_SYMMETRIC); - rakPeerInterface->Send(&bs,MafiaNet::Priority::High,MafiaNet::Reliability::Reliable,0,natDetectionAttempts[i].systemAddress,false); - natDetectionAttempts.RemoveAtIndexFast(i); - i--; - break; - } - - } - i++; - } -} -PluginReceiveResult NatTypeDetectionServer::OnReceive(Packet *packet) -{ - switch (packet->data[0]) - { - case ID_NAT_TYPE_DETECTION_REQUEST: - OnDetectionRequest(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - return RR_CONTINUE_PROCESSING; -} -void NatTypeDetectionServer::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) lostConnectionReason; - (void) rakNetGUID; - - unsigned int i = GetDetectionAttemptIndex(systemAddress); - if (i==(unsigned int)-1) - return; - natDetectionAttempts.RemoveAtIndexFast(i); -} -void NatTypeDetectionServer::OnDetectionRequest(Packet *packet) -{ - unsigned int i = GetDetectionAttemptIndex(packet->systemAddress); - - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(1); - bool isRequest=false; - bsIn.Read(isRequest); - if (isRequest) - { - if (i!=(unsigned int)-1) - return; // Already in progress - - NATDetectionAttempt nda; - nda.detectionState=STATE_NONE; - nda.systemAddress=packet->systemAddress; - nda.guid=packet->guid; - bsIn.Read(nda.c2Port); - nda.nextStateTime=0; - nda.timeBetweenAttempts=rakPeerInterface->GetLastPing(nda.systemAddress)*3+50; - natDetectionAttempts.Push(nda, _FILE_AND_LINE_); - } - else - { - if (i==(unsigned int)-1) - return; // Unknown - // They are done - natDetectionAttempts.RemoveAtIndexFast(i); - } - -} -unsigned int NatTypeDetectionServer::GetDetectionAttemptIndex(const SystemAddress &sa) -{ - for (unsigned int i=0; i < natDetectionAttempts.Size(); i++) - { - if (natDetectionAttempts[i].systemAddress==sa) - return i; - } - return (unsigned int) -1; -} -unsigned int NatTypeDetectionServer::GetDetectionAttemptIndex(RakNetGUID guid) -{ - for (unsigned int i=0; i < natDetectionAttempts.Size(); i++) - { - if (natDetectionAttempts[i].guid==guid) - return i; - } - return (unsigned int) -1; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void NatTypeDetectionServer::DeallocRNS2RecvStruct(RNS2RecvStruct *s, const char *file, unsigned int line) -{ - MafiaNet::OP_DELETE(s, file, line); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -RNS2RecvStruct *NatTypeDetectionServer::AllocRNS2RecvStruct(const char *file, unsigned int line) -{ - return MafiaNet::OP_NEW(file,line); -} - -void NatTypeDetectionServer::OnRNS2Recv(RNS2RecvStruct *recvStruct) -{ - bufferedPacketsMutex.Lock(); - bufferedPackets.Push(recvStruct,_FILE_AND_LINE_); - bufferedPacketsMutex.Unlock(); -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/NetworkIDManager.cpp b/vendors/mafianet/Source/src/NetworkIDManager.cpp deleted file mode 100644 index 4b8f5e9a2..000000000 --- a/vendors/mafianet/Source/src/NetworkIDManager.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// - - -#include "mafianet/NetworkIDManager.h" -#include "mafianet/NetworkIDObject.h" -#include "mafianet/assert.h" -#include "mafianet/GetTime.h" -#include "mafianet/sleep.h" -#include "mafianet/SuperFastHash.h" -#include "mafianet/peerinterface.h" - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(NetworkIDManager,NetworkIDManager) - -NetworkIDManager::NetworkIDManager() -{ - startingOffset = RakPeerInterface::Get64BitUniqueRandomNumber(); - Clear(); -} -NetworkIDManager::~NetworkIDManager(void) -{ - -} -void NetworkIDManager::Clear(void) -{ - memset(networkIdHash,0,sizeof(networkIdHash)); -} -NetworkIDObject *NetworkIDManager::GET_BASE_OBJECT_FROM_ID(NetworkID x) -{ - unsigned int hashIndex=NetworkIDToHashIndex(x); - NetworkIDObject *nio=networkIdHash[hashIndex]; - while (nio) - { - if (nio->GetNetworkID()==x) - return nio; - nio=nio->nextInstanceForNetworkIDManager; - } - return 0; -} -NetworkID NetworkIDManager::GetNewNetworkID(void) -{ - while (GET_BASE_OBJECT_FROM_ID(++startingOffset)) - ; - if (startingOffset==UNASSIGNED_NETWORK_ID) - { - while (GET_BASE_OBJECT_FROM_ID(++startingOffset)) - ; - } - return startingOffset; -} -unsigned int NetworkIDManager::NetworkIDToHashIndex(NetworkID networkId) -{ -// return SuperFastHash((const char*) &networkId.guid.g,sizeof(networkId.guid.g)) % NETWORK_ID_MANAGER_HASH_LENGTH; - return (unsigned int) (networkId % NETWORK_ID_MANAGER_HASH_LENGTH); -} -void NetworkIDManager::TrackNetworkIDObject(NetworkIDObject *networkIdObject) -{ - RakAssert(networkIdObject->GetNetworkIDManager()==this); - NetworkID rawId = networkIdObject->GetNetworkID(); - RakAssert(rawId!=UNASSIGNED_NETWORK_ID); - - networkIdObject->nextInstanceForNetworkIDManager=0; - - unsigned int hashIndex=NetworkIDToHashIndex(rawId); -// printf("TrackNetworkIDObject hashIndex=%i guid=%s\n",hashIndex, networkIdObject->GetNetworkID().guid.ToString()); // removeme - if (networkIdHash[hashIndex]==0) - { - networkIdHash[hashIndex]=networkIdObject; - return; - } - NetworkIDObject *nio=networkIdHash[hashIndex]; - // Duplicate insertion? - RakAssert(nio!=networkIdObject); - // Random GUID conflict? - RakAssert(nio->GetNetworkID()!=rawId); - - while (nio->nextInstanceForNetworkIDManager!=0) - { - nio=nio->nextInstanceForNetworkIDManager; - - // Duplicate insertion? - RakAssert(nio!=networkIdObject); - // Random GUID conflict? - RakAssert(nio->GetNetworkID()!=rawId); - } - - nio->nextInstanceForNetworkIDManager=networkIdObject; -} -void NetworkIDManager::StopTrackingNetworkIDObject(NetworkIDObject *networkIdObject) -{ - RakAssert(networkIdObject->GetNetworkIDManager()==this); - NetworkID rawId = networkIdObject->GetNetworkID(); - RakAssert(rawId!=UNASSIGNED_NETWORK_ID); - - // RakAssert(networkIdObject->GetNetworkID()!=UNASSIGNED_NETWORK_ID); - unsigned int hashIndex=NetworkIDToHashIndex(rawId); -// printf("hashIndex=%i\n",hashIndex); // removeme - NetworkIDObject *nio=networkIdHash[hashIndex]; - if (nio==0) - { - RakAssert("NetworkIDManager::StopTrackingNetworkIDObject didn't find object" && 0); - return; - } - if (nio==networkIdObject) - { - networkIdHash[hashIndex]=nio->nextInstanceForNetworkIDManager; - return; - } - - while (nio) - { - if (nio->nextInstanceForNetworkIDManager==networkIdObject) - { - nio->nextInstanceForNetworkIDManager=networkIdObject->nextInstanceForNetworkIDManager; - return; - } - nio=nio->nextInstanceForNetworkIDManager; - } - - RakAssert("NetworkIDManager::StopTrackingNetworkIDObject didn't find object" && 0); -} diff --git a/vendors/mafianet/Source/src/NetworkIDObject.cpp b/vendors/mafianet/Source/src/NetworkIDObject.cpp deleted file mode 100644 index 462f5ad31..000000000 --- a/vendors/mafianet/Source/src/NetworkIDObject.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// - - -#include "mafianet/NetworkIDObject.h" -#include "mafianet/NetworkIDManager.h" -#include "mafianet/assert.h" -#include "mafianet/alloca.h" - -using namespace MafiaNet; - -NetworkIDObject::NetworkIDObject() -{ - networkID=UNASSIGNED_NETWORK_ID; - parent=0; - networkIDManager=0; - nextInstanceForNetworkIDManager=0; -} -NetworkIDObject::~NetworkIDObject() -{ - if (networkIDManager) - networkIDManager->StopTrackingNetworkIDObject(this); -} -void NetworkIDObject::SetNetworkIDManager( NetworkIDManager *manager) -{ - if (manager==networkIDManager) - return; - - if (networkIDManager) - networkIDManager->StopTrackingNetworkIDObject(this); - - networkIDManager=manager; - if (networkIDManager==0) - { - networkID = UNASSIGNED_NETWORK_ID; - return; - } - - if (networkID == UNASSIGNED_NETWORK_ID) - { - // Prior ID not set - networkID = networkIDManager->GetNewNetworkID(); - } - - networkIDManager->TrackNetworkIDObject(this); -} -NetworkIDManager * NetworkIDObject::GetNetworkIDManager( void ) const -{ - return networkIDManager; -} -NetworkID NetworkIDObject::GetNetworkID( void ) -{ - return networkID; -} -void NetworkIDObject::SetNetworkID( NetworkID id ) -{ - if (networkID==id) - return; - - if ( id == UNASSIGNED_NETWORK_ID ) - { - SetNetworkIDManager(0); - return; - } - - if ( networkIDManager ) - networkIDManager->StopTrackingNetworkIDObject(this); - - networkID = id; - - if (networkIDManager) - networkIDManager->TrackNetworkIDObject(this); -} -void NetworkIDObject::SetParent( void *_parent ) -{ - parent=_parent; -} -void* NetworkIDObject::GetParent( void ) const -{ - return parent; -} diff --git a/vendors/mafianet/Source/src/PS4Includes.cpp b/vendors/mafianet/Source/src/PS4Includes.cpp deleted file mode 100644 index 9a1add790..000000000 --- a/vendors/mafianet/Source/src/PS4Includes.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* - * This file was taken from RakNet 4.082 without any modifications. - * Please see licenses/RakNet license.txt for the underlying license and related copyright. - */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/vendors/mafianet/Source/src/PacketConsoleLogger.cpp b/vendors/mafianet/Source/src/PacketConsoleLogger.cpp deleted file mode 100644 index 88f2599f0..000000000 --- a/vendors/mafianet/Source/src/PacketConsoleLogger.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_LogCommandParser==1 && _RAKNET_SUPPORT_PacketLogger==1 -#include "mafianet/PacketConsoleLogger.h" -#include "mafianet/LogCommandParser.h" -#include - -using namespace MafiaNet; - -PacketConsoleLogger::PacketConsoleLogger() -{ - logCommandParser=0; -} - -void PacketConsoleLogger::SetLogCommandParser(LogCommandParser *lcp) -{ - logCommandParser=lcp; - if (logCommandParser) - logCommandParser->AddChannel("PacketConsoleLogger"); -} -void PacketConsoleLogger::WriteLog(const char *str) -{ - if (logCommandParser) - logCommandParser->WriteLog("PacketConsoleLogger", str); -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/PacketFileLogger.cpp b/vendors/mafianet/Source/src/PacketFileLogger.cpp deleted file mode 100644 index cd170f229..000000000 --- a/vendors/mafianet/Source/src/PacketFileLogger.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_PacketLogger==1 - -#include "mafianet/PacketFileLogger.h" -#include "mafianet/GetTime.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" -#include "mafianet/memoryoverride.h" - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(PacketFileLogger,PacketFileLogger); - -PacketFileLogger::PacketFileLogger() -{ - packetLogFile=0; -} -PacketFileLogger::~PacketFileLogger() -{ - if (packetLogFile) - { - fflush(packetLogFile); - fclose(packetLogFile); - } -} -void PacketFileLogger::StartLog(const char *filenamePrefix) -{ - // Open file for writing - char filename[256]; - if (filenamePrefix) - sprintf_s(filename, "%s_%i.csv", filenamePrefix, (int)MafiaNet::GetTimeMS()); - else - sprintf_s(filename, "PacketLog_%i.csv", (int)MafiaNet::GetTimeMS()); - errno_t error = fopen_s(&packetLogFile, filename, "wt"); - LogHeader(); - if (error == 0) - { - fflush(packetLogFile); - } -} - -void PacketFileLogger::WriteLog(const char *str) -{ - if (packetLogFile) - { - fprintf(packetLogFile, "%s\n", str); - fflush(packetLogFile); - } -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/PacketLogger.cpp b/vendors/mafianet/Source/src/PacketLogger.cpp deleted file mode 100644 index 8c541ee03..000000000 --- a/vendors/mafianet/Source/src/PacketLogger.cpp +++ /dev/null @@ -1,544 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_PacketLogger==1 - -#include "mafianet/PacketLogger.h" -#include "mafianet/BitStream.h" -#include "mafianet/DS_List.h" -#include "mafianet/InternalPacket.h" -#include "mafianet/peerinterface.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/StringCompressor.h" -#include "mafianet/GetTime.h" -#include -#include -#include -#include "mafianet/Itoa.h" -#include -#include "mafianet/SocketIncludes.h" -#include "mafianet/gettimeofday.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(PacketLogger,PacketLogger); - -PacketLogger::PacketLogger() -{ - printId=true; - printAcks=true; - prefix[0]=0; - suffix[0]=0; - logDirectMessages=true; -} -PacketLogger::~PacketLogger() -{ -} -void PacketLogger::FormatLine(char* into, const char* dir, const char* type, unsigned int reliableMessageNumber, unsigned int frame - , unsigned char id, const BitSize_t bitLen, unsigned long long time, const SystemAddress& local, const SystemAddress& remote, - unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex) -{ - char numericID[16]; - const char* idToPrint = nullptr; - if (printId) - { - if (splitPacketCount > 0 && splitPacketCount != (unsigned int)-1) - idToPrint = "(SPLIT PACKET)"; - else - idToPrint = IDTOString(id); - } - // If printId is false, idToPrint will be nullptr, as it will - // in the case of an unrecognized id. Testing printId for false - // would just be redundant. - if (idToPrint == nullptr) - { - sprintf_s(numericID, "%5u", id); - idToPrint = numericID; - } - - FormatLine(into, dir, type, reliableMessageNumber, frame, idToPrint, bitLen, time, local, remote, splitPacketId, splitPacketIndex, splitPacketCount, orderingIndex); -} -void PacketLogger::FormatLine( -char* into, size_t intoLength, const char* dir, const char* type, unsigned int reliableMessageNumber, unsigned int frame, unsigned char id -, const BitSize_t bitLen, unsigned long long time, const SystemAddress& local, const SystemAddress& remote, -unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex) -{ - char numericID[16]; - const char* idToPrint = nullptr; - if(printId) - { - if (splitPacketCount>0 && splitPacketCount!=(unsigned int)-1) - idToPrint="(SPLIT PACKET)"; - else - idToPrint = IDTOString(id); - } - // If printId is false, idToPrint will be nullptr, as it will - // in the case of an unrecognized id. Testing printId for false - // would just be redundant. - if(idToPrint == nullptr) - { - sprintf_s(numericID, "%5u", id); - idToPrint = numericID; - } - - FormatLine(into, intoLength, dir, type, reliableMessageNumber, frame, idToPrint, bitLen, time, local, remote,splitPacketId,splitPacketIndex,splitPacketCount, orderingIndex); -} - -void PacketLogger::FormatLine( -char* into, size_t intoLength, const char* dir, const char* type, unsigned int reliableMessageNumber, unsigned int frame, const char* idToPrint -, const BitSize_t bitLen, unsigned long long time, const SystemAddress& local, const SystemAddress& remote, -unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex) -{ - char str1[64], str2[62]; - local.ToString(true, str1, static_cast(64)); - remote.ToString(true, str2, static_cast(62)); - char localtime[128]; - GetLocalTime(localtime); - char str3[64]; - if (reliableMessageNumber==(unsigned int)-1) - { - str3[0]='N'; - str3[1]='/'; - str3[2]='A'; - str3[3]=0; - } - else - { - sprintf_s(str3,"%5u",reliableMessageNumber); - } - - sprintf_s(into, intoLength, "%s,%s%s,%s,%s,%5u,%s,%u,%" PRINTF_64_BIT_MODIFIER "u,%s,%s,%i,%i,%i,%i,%s," - , localtime - , prefix - , dir - , type - , str3 - , frame - , idToPrint - , bitLen - , time - , str1 - , str2 - , splitPacketId - , splitPacketIndex - , splitPacketCount - , orderingIndex - , suffix - ); -} -void PacketLogger::FormatLine(char* into, const char* dir, const char* type, unsigned int reliableMessageNumber, unsigned int frame - , const char* idToPrint, const BitSize_t bitLen, unsigned long long time, const SystemAddress& local, const SystemAddress& remote, - unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex) -{ - char str1[64], str2[62]; - local.ToString(true, str1, static_cast(64)); - remote.ToString(true, str2, static_cast(62)); - char localtime[128]; - GetLocalTime(localtime); - char str3[64]; - if (reliableMessageNumber == (unsigned int)-1) - { - str3[0] = 'N'; - str3[1] = '/'; - str3[2] = 'A'; - str3[3] = 0; - } - else - { - sprintf_s(str3, "%5u", reliableMessageNumber); - } - -#pragma warning(push) -#pragma warning(disable:4996) - sprintf(into, "%s,%s%s,%s,%s,%5u,%s,%u,%" PRINTF_64_BIT_MODIFIER "u,%s,%s,%i,%i,%i,%i,%s," - , localtime - , prefix - , dir - , type - , str3 - , frame - , idToPrint - , bitLen - , time - , str1 - , str2 - , splitPacketId - , splitPacketIndex - , splitPacketCount - , orderingIndex - , suffix - ); -#pragma warning(pop) -} -void PacketLogger::OnDirectSocketSend(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) -{ - if (logDirectMessages==false) - return; - - char str[256]; - FormatLine(str, 256, "Snd", "Raw", 0, 0, data[0], bitsUsed, MafiaNet::GetTimeMS(), rakPeerInterface->GetExternalID(remoteSystemAddress), remoteSystemAddress, (unsigned int)-1,(unsigned int)-1,(unsigned int)-1,(unsigned int)-1); - AddToLog(str); -} - -void PacketLogger::LogHeader(void) -{ - // Last 5 are splitpacket id, split packet index, split packet count, ordering index, suffix - AddToLog("Clock,S|R,Typ,Reliable#,Frm #,PktID,BitLn,Time ,Local IP:Port ,RemoteIP:Port,SPID,SPIN,SPCO,OI,Suffix,Miscellaneous\n"); -} -void PacketLogger::OnDirectSocketReceive(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) -{ - if (logDirectMessages==false) - return; - - char str[256]; - FormatLine(str, 256, "Rcv", "Raw", 0, 0, data[0], bitsUsed, MafiaNet::GetTime(), rakPeerInterface->GetInternalID(UNASSIGNED_SYSTEM_ADDRESS), remoteSystemAddress,(unsigned int)-1,(unsigned int)-1,(unsigned int)-1,(unsigned int)-1); - AddToLog(str); -} -void PacketLogger::OnReliabilityLayerNotification(const char *errorMessage, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress, bool isError) -{ - char str[1024]; - char *type; - if (isError) - type=(char*) "RcvErr"; - else - type=(char*) "RcvWrn"; - FormatLine(str, 1024, type, errorMessage, 0, 0, "", bitsUsed, MafiaNet::GetTime(), rakPeerInterface->GetInternalID(UNASSIGNED_SYSTEM_ADDRESS), remoteSystemAddress,(unsigned int)-1,(unsigned int)-1,(unsigned int)-1,(unsigned int)-1); - AddToLog(str); - RakAssert(isError==false); -} -void PacketLogger::OnAck(unsigned int messageNumber, SystemAddress remoteSystemAddress, MafiaNet::TimeMS time) -{ - char str[256]; - char str1[64], str2[62]; - SystemAddress localSystemAddress = rakPeerInterface->GetExternalID(remoteSystemAddress); - localSystemAddress.ToString(true, str1, static_cast(64)); - remoteSystemAddress.ToString(true, str2, static_cast(62)); - char localtime[128]; - GetLocalTime(localtime); - - sprintf_s(str, "%s,Rcv,Ack,%i,,,,%" PRINTF_64_BIT_MODIFIER "u,%s,%s,,,,,," - , localtime - , messageNumber - , (unsigned long long) time - , str1 - , str2 - ); - AddToLog(str); -} -void PacketLogger::OnPushBackPacket(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) -{ - char str[256]; - char str1[64], str2[62]; - SystemAddress localSystemAddress = rakPeerInterface->GetExternalID(remoteSystemAddress); - localSystemAddress.ToString(true, str1, static_cast(64)); - remoteSystemAddress.ToString(true, str2, static_cast(62)); - MafiaNet::TimeMS time = MafiaNet::GetTimeMS(); - char localtime[128]; - GetLocalTime(localtime); - - sprintf_s(str, "%s,Lcl,PBP,,,%s,%i,%" PRINTF_64_BIT_MODIFIER "u,%s,%s,,,,,," - , localtime - , BaseIDTOString(data[0]) - , bitsUsed - , (unsigned long long) time - , str1 - , str2 - ); - AddToLog(str); -} -void PacketLogger::OnInternalPacket(InternalPacket *internalPacket, unsigned frameNumber, SystemAddress remoteSystemAddress, MafiaNet::TimeMS time, int isSend) -{ - char str[256]; - const char *sendTypes[] = - { - "Rcv", - "Snd", - "Err1", - "Err2", - "Err3", - "Err4", - "Err5", - "Err6", - }; - const char *sendType = sendTypes[isSend]; - SystemAddress localSystemAddress = rakPeerInterface->GetExternalID(remoteSystemAddress); - - unsigned int reliableMessageNumber; - if (internalPacket->reliability==MafiaNet::Reliability::Unreliable || internalPacket->reliability==MafiaNet::Reliability::UnreliableSequenced || internalPacket->reliability==MafiaNet::Reliability::UnreliableWithAckReceipt) - reliableMessageNumber=(unsigned int)-1; - else - reliableMessageNumber=internalPacket->reliableMessageNumber; - - if (internalPacket->data[0]==ID_TIMESTAMP) - { - FormatLine(str, 256, sendType, "Tms", reliableMessageNumber, frameNumber, internalPacket->data[1+sizeof(MafiaNet::Time)], internalPacket->dataBitLength, (unsigned long long)time, localSystemAddress, remoteSystemAddress, internalPacket->splitPacketId, internalPacket->splitPacketIndex, internalPacket->splitPacketCount, internalPacket->orderingIndex); - } - else - { - FormatLine(str, 256, sendType, "Nrm", reliableMessageNumber, frameNumber, internalPacket->data[0], internalPacket->dataBitLength, (unsigned long long)time, localSystemAddress, remoteSystemAddress, internalPacket->splitPacketId, internalPacket->splitPacketIndex, internalPacket->splitPacketCount, internalPacket->orderingIndex); - } - - AddToLog(str); -} -void PacketLogger::AddToLog(const char *str) -{ - WriteLog(str); -} -void PacketLogger::WriteLog(const char *str) -{ - RAKNET_DEBUG_PRINTF("%s\n", str); -} -void PacketLogger::WriteMiscellaneous(const char *type, const char *msg) -{ - char str[1024]; - char str1[64]; - SystemAddress localSystemAddress = rakPeerInterface->GetInternalID(); - localSystemAddress.ToString(true, str1, static_cast(64)); - MafiaNet::TimeMS time = MafiaNet::GetTimeMS(); - char localtime[128]; - GetLocalTime(localtime); - - sprintf_s(str, "%s,Lcl,%s,,,,,%" PRINTF_64_BIT_MODIFIER "u,%s,,,,,,,%s" - , localtime - , type - , (unsigned long long) time - , str1 - , msg - ); - - AddToLog(msg); -} -void PacketLogger::SetPrintID(bool print) -{ - printId=print; -} -void PacketLogger::SetPrintAcks(bool print) -{ - printAcks=print; -} -const char* PacketLogger::BaseIDTOString(unsigned char Id) -{ - if (Id >= ID_USER_PACKET_ENUM) - return 0; - - const char *IDTable[((int)ID_USER_PACKET_ENUM)+1]= - { - "ID_CONNECTED_PING", - "ID_UNCONNECTED_PING", - "ID_UNCONNECTED_PING_OPEN_CONNECTIONS", - "ID_CONNECTED_PONG", - "ID_DETECT_LOST_CONNECTIONS", - "ID_OPEN_CONNECTION_REQUEST_1", - "ID_OPEN_CONNECTION_REPLY_1", - "ID_OPEN_CONNECTION_REQUEST_2", - "ID_OPEN_CONNECTION_REPLY_2", - "ID_CONNECTION_REQUEST", - "ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY", - "ID_OUR_SYSTEM_REQUIRES_SECURITY", - "ID_PUBLIC_KEY_MISMATCH", - "ID_OUT_OF_BAND_INTERNAL", - "ID_SND_RECEIPT_ACKED", - "ID_SND_RECEIPT_LOSS", - "ID_CONNECTION_REQUEST_ACCEPTED", - "ID_CONNECTION_ATTEMPT_FAILED", - "ID_ALREADY_CONNECTED", - "ID_NEW_INCOMING_CONNECTION", - "ID_NO_FREE_INCOMING_CONNECTIONS", - "ID_DISCONNECTION_NOTIFICATION", - "ID_CONNECTION_LOST", - "ID_CONNECTION_BANNED", - "ID_INVALID_PASSWORD", - "ID_INCOMPATIBLE_PROTOCOL_VERSION", - "ID_IP_RECENTLY_CONNECTED", - "ID_TIMESTAMP", - "ID_UNCONNECTED_PONG", - "ID_ADVERTISE_SYSTEM", - "ID_DOWNLOAD_PROGRESS", - "ID_REMOTE_DISCONNECTION_NOTIFICATION", - "ID_REMOTE_CONNECTION_LOST", - "ID_REMOTE_NEW_INCOMING_CONNECTION", - "ID_FILE_LIST_TRANSFER_HEADER", - "ID_FILE_LIST_TRANSFER_FILE", - "ID_FILE_LIST_REFERENCE_PUSH_ACK", - "ID_DDT_DOWNLOAD_REQUEST", - "ID_TRANSPORT_STRING", - "ID_REPLICA_MANAGER_CONSTRUCTION", - "ID_REPLICA_MANAGER_SCOPE_CHANGE", - "ID_REPLICA_MANAGER_SERIALIZE", - "ID_REPLICA_MANAGER_DOWNLOAD_STARTED", - "ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE", - "ID_RAKVOICE_OPEN_CHANNEL_REQUEST", - "ID_RAKVOICE_OPEN_CHANNEL_REPLY", - "ID_RAKVOICE_CLOSE_CHANNEL", - "ID_RAKVOICE_DATA", - "ID_AUTOPATCHER_GET_CHANGELIST_SINCE_DATE", - "ID_AUTOPATCHER_CREATION_LIST", - "ID_AUTOPATCHER_DELETION_LIST", - "ID_AUTOPATCHER_GET_PATCH", - "ID_AUTOPATCHER_PATCH_LIST", - "ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR", - "ID_AUTOPATCHER_CANNOT_DOWNLOAD_ORIGINAL_UNMODIFIED_FILES", - "ID_AUTOPATCHER_FINISHED_INTERNAL", - "ID_AUTOPATCHER_FINISHED", - "ID_AUTOPATCHER_RESTART_APPLICATION", - "ID_NAT_PUNCHTHROUGH_REQUEST", - "ID_NAT_CONNECT_AT_TIME", - "ID_NAT_GET_MOST_RECENT_PORT", - "ID_NAT_CLIENT_READY", - "ID_NAT_TARGET_NOT_CONNECTED", - "ID_NAT_TARGET_UNRESPONSIVE", - "ID_NAT_CONNECTION_TO_TARGET_LOST", - "ID_NAT_ALREADY_IN_PROGRESS", - "ID_NAT_PUNCHTHROUGH_FAILED", - "ID_NAT_PUNCHTHROUGH_SUCCEEDED", - "ID_READY_EVENT_SET", - "ID_READY_EVENT_UNSET", - "ID_READY_EVENT_ALL_SET", - "ID_READY_EVENT_QUERY", - "ID_LOBBY_GENERAL", - "ID_RPC_REMOTE_ERROR", - "ID_RPC_PLUGIN", - "ID_FILE_LIST_REFERENCE_PUSH", - "ID_READY_EVENT_FORCE_ALL_SET", - "ID_ROOMS_EXECUTE_FUNC", - "ID_ROOMS_LOGON_STATUS", - "ID_ROOMS_HANDLE_CHANGE", - "ID_LOBBY2_SEND_MESSAGE", - "ID_LOBBY2_SERVER_ERROR", - "ID_FCM2_NEW_HOST", - "ID_FCM2_REQUEST_FCMGUID", - "ID_FCM2_RESPOND_CONNECTION_COUNT", - "ID_FCM2_INFORM_FCMGUID", - "ID_FCM2_UPDATE_MIN_TOTAL_CONNECTION_COUNT", - "ID_FCM2_VERIFIED_JOIN_START", - "ID_FCM2_VERIFIED_JOIN_CAPABLE", - "ID_FCM2_VERIFIED_JOIN_FAILED", - "ID_FCM2_VERIFIED_JOIN_ACCEPTED", - "ID_FCM2_VERIFIED_JOIN_REJECTED", - "ID_UDP_PROXY_GENERAL", - "ID_SQLite3_EXEC", - "ID_SQLite3_UNKNOWN_DB", - "ID_SQLLITE_LOGGER", - "ID_NAT_TYPE_DETECTION_REQUEST", - "ID_NAT_TYPE_DETECTION_RESULT", - "ID_ROUTER_2_INTERNAL", - "ID_ROUTER_2_FORWARDING_NO_PATH", - "ID_ROUTER_2_FORWARDING_ESTABLISHED", - "ID_ROUTER_2_REROUTED", - "ID_TEAM_BALANCER_INTERNAL", - "ID_TEAM_BALANCER_REQUESTED_TEAM_FULL", - "ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED", - "ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED", - "ID_TEAM_BALANCER_TEAM_ASSIGNED", - "ID_LIGHTSPEED_INTEGRATION", - "ID_XBOX_LOBBY", - "ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_SUCCESS", - "ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_SUCCESS", - "ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_FAILURE", - "ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_FAILURE", - "ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT", - "ID_TWO_WAY_AUTHENTICATION_NEGOTIATION", - "ID_CLOUD_POST_REQUEST", - "ID_CLOUD_RELEASE_REQUEST", - "ID_CLOUD_GET_REQUEST", - "ID_CLOUD_GET_RESPONSE", - "ID_CLOUD_UNSUBSCRIBE_REQUEST", - "ID_CLOUD_SERVER_TO_SERVER_COMMAND", - "ID_CLOUD_SUBSCRIPTION_NOTIFICATION", - "ID_LIB_VOICE", - "ID_RELAY_PLUGIN", - "ID_NAT_REQUEST_BOUND_ADDRESSES", - "ID_NAT_RESPOND_BOUND_ADDRESSES", - "ID_FCM2_UPDATE_USER_CONTEXT", - "ID_RESERVED_3", - "ID_RESERVED_4", - "ID_RESERVED_5", - "ID_RESERVED_6", - "ID_RESERVED_7", - "ID_RESERVED_8", - "ID_RESERVED_9", - "ID_USER_PACKET_ENUM" - }; - - return (char*)IDTable[Id]; -} -const char* PacketLogger::UserIDTOString(unsigned char Id) -{ - // Users should override this - static char str[256]; - Itoa(Id, str, 10); - return (const char*) str; -} -const char* PacketLogger::IDTOString(unsigned char Id) -{ - const char *out; - out=BaseIDTOString(Id); - if (out) - return out; - return UserIDTOString(Id); -} -void PacketLogger::SetPrefix(const char *_prefix) -{ - strncpy_s(prefix, _prefix, 255); - prefix[255]=0; -} -void PacketLogger::SetSuffix(const char *_suffix) -{ - strncpy_s(suffix, _suffix, 255); - suffix[255]=0; -} -void PacketLogger::GetLocalTime(char buffer[128]) -{ -#if defined(_WIN32) && !defined(__GNUC__) && !defined(__GCCXML__) - time_t rawtime; - struct timeval tv; - // If you get an arror about an incomplete type, just delete this file - struct timezone tz; - gettimeofday(&tv, &tz); - // time ( &rawtime ); - rawtime=tv.tv_sec; - - struct tm timeinfo; - localtime_s ( &timeinfo, &rawtime ); - strftime (buffer,128,"%x %X",&timeinfo); - char buff[32]; - sprintf_s(buff, ".%i", tv.tv_usec); - strcat_s(buffer,128,buff); - - // Commented version puts the time first - /* - struct tm timeinfo; - localtime_s ( &timeinfo, &rawtime ); - strftime (buffer,128,"%X",&timeinfo); - char buff[32]; - sprintf_s(buff, ".%i ", tv.tv_usec); - strcat_s(buffer,128,buff); - char buff2[32]; - strftime (buff2,32,"%x",&timeinfo); - strcat_s(buffer,128,buff2); - */ -#else - buffer[0]=0; -#endif -} -void PacketLogger::SetLogDirectMessages(bool send) -{ - logDirectMessages=send; -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/PacketOutputWindowLogger.cpp b/vendors/mafianet/Source/src/PacketOutputWindowLogger.cpp deleted file mode 100644 index 1f82014ea..000000000 --- a/vendors/mafianet/Source/src/PacketOutputWindowLogger.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_PacketLogger==1 - -#if defined(UNICODE) -#include "mafianet/wstring.h" -#endif - -#include "mafianet/PacketOutputWindowLogger.h" -#include "mafianet/string.h" -#if defined(_WIN32) -#include "mafianet/WindowsIncludes.h" -#endif - -using namespace MafiaNet; - -PacketOutputWindowLogger::PacketOutputWindowLogger() -{ -} -PacketOutputWindowLogger::~PacketOutputWindowLogger() -{ -} -void PacketOutputWindowLogger::WriteLog(const char *str) -{ -#if defined(_WIN32) - - #if defined(UNICODE) - MafiaNet::RakWString str2 = str; - str2+="\n"; - OutputDebugString(str2.C_String()); - #else - MafiaNet::RakString str2 = str; - str2+="\n"; - OutputDebugString(str2.C_String()); - #endif -// DS_APR -#elif defined(__native_client__) - fprintf(stderr, "%s\n", str); -// /DS_APR -#endif -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/PacketizedTCP.cpp b/vendors/mafianet/Source/src/PacketizedTCP.cpp deleted file mode 100644 index 665b10f70..000000000 --- a/vendors/mafianet/Source/src/PacketizedTCP.cpp +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 - -#include // used for std::min -#include "mafianet/PacketizedTCP.h" -#include "mafianet/NativeTypes.h" -#include "mafianet/BitStream.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/alloca.h" - -using namespace MafiaNet; - -typedef uint32_t PTCPHeader; - -STATIC_FACTORY_DEFINITIONS(PacketizedTCP,PacketizedTCP); - -PacketizedTCP::PacketizedTCP() -{ - -} -PacketizedTCP::~PacketizedTCP() -{ - ClearAllConnections(); -} - -void PacketizedTCP::Stop(void) -{ - unsigned int i; - TCPInterface::Stop(); - for (i=0; i < waitingPackets.Size(); i++) - DeallocatePacket(waitingPackets[i]); - ClearAllConnections(); -} - -void PacketizedTCP::Send( const char *data, unsigned length, const SystemAddress &systemAddress, bool broadcast ) -{ - PTCPHeader dataLength; - dataLength=length; -#ifndef __BITSTREAM_NATIVE_END - if (MafiaNet::BitStream::DoEndianSwap()) - MafiaNet::BitStream::ReverseBytes((unsigned char*) &length,(unsigned char*) &dataLength,sizeof(dataLength)); -#else - dataLength=length; -#endif - - unsigned int lengthsArray[2]; - const char *dataArray[2]; - dataArray[0]=(char*) &dataLength; - dataArray[1]=data; - lengthsArray[0]=sizeof(dataLength); - lengthsArray[1]=length; - TCPInterface::SendList(dataArray,lengthsArray,2,systemAddress,broadcast); -} -bool PacketizedTCP::SendList( const char **data, const unsigned int *lengths, const int numParameters, const SystemAddress &systemAddress, bool broadcast ) -{ - if (isStarted.GetValue()==0) - return false; - if (data==0) - return false; - if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS && broadcast==false) - return false; - PTCPHeader totalLengthOfUserData=0; - int i; - for (i=0; i < numParameters; i++) - { - if (lengths[i]>0) - totalLengthOfUserData+=lengths[i]; - } - if (totalLengthOfUserData==0) - return false; - - PTCPHeader dataLength; -#ifndef __BITSTREAM_NATIVE_END - if (MafiaNet::BitStream::DoEndianSwap()) - MafiaNet::BitStream::ReverseBytes((unsigned char*) &totalLengthOfUserData,(unsigned char*) &dataLength,sizeof(dataLength)); -#else - dataLength=totalLengthOfUserData; -#endif - - - unsigned int lengthsArray[512]; - const char *dataArray[512]; - dataArray[0]=(char*) &dataLength; - lengthsArray[0]=sizeof(dataLength); - for (i=0; i < 512 && i < numParameters; i++) - { - dataArray[i+1]=data[i]; - lengthsArray[i+1]=lengths[i]; - } - return TCPInterface::SendList(dataArray,lengthsArray,std::min(numParameters, 511)+1,systemAddress,broadcast); -} -void PacketizedTCP::PushNotificationsToQueues(void) -{ - SystemAddress sa; - sa = TCPInterface::HasNewIncomingConnection(); - if (sa!=UNASSIGNED_SYSTEM_ADDRESS) - { - _newIncomingConnections.Push(sa, _FILE_AND_LINE_ ); - AddToConnectionList(sa); - } - - sa = TCPInterface::HasFailedConnectionAttempt(); - if (sa!=UNASSIGNED_SYSTEM_ADDRESS) - { - _failedConnectionAttempts.Push(sa, _FILE_AND_LINE_ ); - } - - sa = TCPInterface::HasLostConnection(); - if (sa!=UNASSIGNED_SYSTEM_ADDRESS) - { - _lostConnections.Push(sa, _FILE_AND_LINE_ ); - RemoveFromConnectionList(sa); - } - - sa = TCPInterface::HasCompletedConnectionAttempt(); - if (sa!=UNASSIGNED_SYSTEM_ADDRESS) - { - _completedConnectionAttempts.Push(sa, _FILE_AND_LINE_ ); - AddToConnectionList(sa); - } -} -Packet* PacketizedTCP::Receive( void ) -{ - PushNotificationsToQueues(); - - unsigned int i; - for (i=0; i < messageHandlerList.Size(); i++) - messageHandlerList[i]->Update(); - - Packet *outgoingPacket=ReturnOutgoingPacket(); - if (outgoingPacket) - return outgoingPacket; - - Packet *incomingPacket; - incomingPacket = TCPInterface::ReceiveInt(); - unsigned int index; - - while (incomingPacket) - { - if (connections.Has(incomingPacket->systemAddress)) - index = connections.GetIndexAtKey(incomingPacket->systemAddress); - else - index=(unsigned int) -1; - if ((unsigned int)index==(unsigned int)-1) - { - DeallocatePacket(incomingPacket); - incomingPacket = TCPInterface::ReceiveInt(); - continue; - } - - - if (incomingPacket->deleteData==true) - { - // Came from network - SystemAddress systemAddressFromPacket; - if (index < connections.Size()) - { - DataStructures::ByteQueue *bq = connections[index]; - // Buffer data - bq->WriteBytes((const char*) incomingPacket->data,incomingPacket->length, _FILE_AND_LINE_); - systemAddressFromPacket=incomingPacket->systemAddress; - PTCPHeader dataLength; - - // Peek the header to see if a full message is waiting - bq->ReadBytes((char*) &dataLength,sizeof(PTCPHeader),true); - if (MafiaNet::BitStream::DoEndianSwap()) - MafiaNet::BitStream::ReverseBytesInPlace((unsigned char*) &dataLength,sizeof(dataLength)); - // Header indicates packet length. If enough data is available, read out and return one packet - if (bq->GetBytesWritten()>=dataLength+sizeof(PTCPHeader)) - { - do - { - bq->IncrementReadOffset(sizeof(PTCPHeader)); - outgoingPacket = MafiaNet::OP_NEW(_FILE_AND_LINE_); - outgoingPacket->length=dataLength; - outgoingPacket->bitSize=BYTES_TO_BITS(dataLength); - outgoingPacket->guid=UNASSIGNED_RAKNET_GUID; - outgoingPacket->systemAddress=systemAddressFromPacket; - outgoingPacket->deleteData=false; // Did not come from the network - outgoingPacket->data=(unsigned char*) rakMalloc_Ex(dataLength, _FILE_AND_LINE_); - if (outgoingPacket->data==0) - { - notifyOutOfMemory(_FILE_AND_LINE_); - MafiaNet::OP_DELETE(outgoingPacket,_FILE_AND_LINE_); - return 0; - } - bq->ReadBytes((char*) outgoingPacket->data,dataLength,false); - - waitingPackets.Push(outgoingPacket, _FILE_AND_LINE_ ); - - // Peek the header to see if a full message is waiting - if (bq->ReadBytes((char*) &dataLength,sizeof(PTCPHeader),true)) - { - if (MafiaNet::BitStream::DoEndianSwap()) - MafiaNet::BitStream::ReverseBytesInPlace((unsigned char*) &dataLength,sizeof(dataLength)); - } - else - break; - } while (bq->GetBytesWritten()>=dataLength+sizeof(PTCPHeader)); - } - else - { - - unsigned int oldWritten = bq->GetBytesWritten()-incomingPacket->length; - unsigned int newWritten = bq->GetBytesWritten(); - - // Return ID_DOWNLOAD_PROGRESS - if (newWritten/65536!=oldWritten/65536) - { - outgoingPacket = MafiaNet::OP_NEW(_FILE_AND_LINE_); - outgoingPacket->length=sizeof(MessageID) + - sizeof(unsigned int)*2 + - sizeof(unsigned int) + - 65536; - outgoingPacket->bitSize=BYTES_TO_BITS(incomingPacket->length); - outgoingPacket->guid=UNASSIGNED_RAKNET_GUID; - outgoingPacket->systemAddress=incomingPacket->systemAddress; - outgoingPacket->deleteData=false; - outgoingPacket->data=(unsigned char*) rakMalloc_Ex(outgoingPacket->length, _FILE_AND_LINE_); - if (outgoingPacket->data==0) - { - notifyOutOfMemory(_FILE_AND_LINE_); - MafiaNet::OP_DELETE(outgoingPacket,_FILE_AND_LINE_); - return 0; - } - - outgoingPacket->data[0]=(MessageID)ID_DOWNLOAD_PROGRESS; - unsigned int totalParts=dataLength/65536; - unsigned int partIndex=newWritten/65536; - unsigned int oneChunkSize=65536; - memcpy(outgoingPacket->data+sizeof(MessageID), &partIndex, sizeof(unsigned int)); - memcpy(outgoingPacket->data+sizeof(MessageID)+sizeof(unsigned int)*1, &totalParts, sizeof(unsigned int)); - memcpy(outgoingPacket->data+sizeof(MessageID)+sizeof(unsigned int)*2, &oneChunkSize, sizeof(unsigned int)); - bq->IncrementReadOffset(sizeof(PTCPHeader)); - bq->ReadBytes((char*) outgoingPacket->data+sizeof(MessageID)+sizeof(unsigned int)*3,oneChunkSize,true); - bq->DecrementReadOffset(sizeof(PTCPHeader)); - - waitingPackets.Push(outgoingPacket, _FILE_AND_LINE_ ); - } - } - - } - - DeallocatePacket(incomingPacket); - incomingPacket=0; - } - else - waitingPackets.Push(incomingPacket, _FILE_AND_LINE_ ); - - incomingPacket = TCPInterface::ReceiveInt(); - } - - return ReturnOutgoingPacket(); -} -Packet *PacketizedTCP::ReturnOutgoingPacket(void) -{ - Packet *outgoingPacket=0; - unsigned int i; - while (outgoingPacket==0 && waitingPackets.IsEmpty()==false) - { - outgoingPacket=waitingPackets.Pop(); - PluginReceiveResult pluginResult; - for (i=0; i < messageHandlerList.Size(); i++) - { - pluginResult=messageHandlerList[i]->OnReceive(outgoingPacket); - if (pluginResult==RR_STOP_PROCESSING_AND_DEALLOCATE) - { - DeallocatePacket( outgoingPacket ); - outgoingPacket=0; // Will do the loop again and get another packet - break; // break out of the enclosing for - } - else if (pluginResult==RR_STOP_PROCESSING) - { - outgoingPacket=0; - break; - } - } - } - - return outgoingPacket; -} -void PacketizedTCP::CloseConnection( SystemAddress systemAddress ) -{ - RemoveFromConnectionList(systemAddress); - TCPInterface::CloseConnection(systemAddress); -} -void PacketizedTCP::RemoveFromConnectionList(const SystemAddress &sa) -{ - if (sa==UNASSIGNED_SYSTEM_ADDRESS) - return; - if (connections.Has(sa)) - { - unsigned int index = connections.GetIndexAtKey(sa); - if (index!=(unsigned int)-1) - { - MafiaNet::OP_DELETE(connections[index],_FILE_AND_LINE_); - connections.RemoveAtIndex(index); - } - } -} -void PacketizedTCP::AddToConnectionList(const SystemAddress &sa) -{ - if (sa==UNASSIGNED_SYSTEM_ADDRESS) - return; - connections.SetNew(sa, MafiaNet::OP_NEW(_FILE_AND_LINE_)); -} -void PacketizedTCP::ClearAllConnections(void) -{ - unsigned int i; - for (i=0; i < connections.Size(); i++) - MafiaNet::OP_DELETE(connections[i],_FILE_AND_LINE_); - connections.Clear(); -} -SystemAddress PacketizedTCP::HasCompletedConnectionAttempt(void) -{ - PushNotificationsToQueues(); - - if (_completedConnectionAttempts.IsEmpty()==false) - return _completedConnectionAttempts.Pop(); - return UNASSIGNED_SYSTEM_ADDRESS; -} -SystemAddress PacketizedTCP::HasFailedConnectionAttempt(void) -{ - PushNotificationsToQueues(); - - if (_failedConnectionAttempts.IsEmpty()==false) - return _failedConnectionAttempts.Pop(); - return UNASSIGNED_SYSTEM_ADDRESS; -} -SystemAddress PacketizedTCP::HasNewIncomingConnection(void) -{ - PushNotificationsToQueues(); - - if (_newIncomingConnections.IsEmpty()==false) - return _newIncomingConnections.Pop(); - return UNASSIGNED_SYSTEM_ADDRESS; -} -SystemAddress PacketizedTCP::HasLostConnection(void) -{ - PushNotificationsToQueues(); - - if (_lostConnections.IsEmpty()==false) - return _lostConnections.Pop(); - return UNASSIGNED_SYSTEM_ADDRESS; -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/PeerHandle.cpp b/vendors/mafianet/Source/src/PeerHandle.cpp deleted file mode 100644 index a4acd2e6a..000000000 --- a/vendors/mafianet/Source/src/PeerHandle.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2026, MafiaHub - * - * This source code is licensed under the MIT-style license found in the - * license.txt file in the root directory of this source tree. - */ - -#include "mafianet/PeerHandle.h" - -#include - -#include "mafianet/MessageIdentifiers.h" // ID_TIMESTAMP - -namespace MafiaNet { - -// --- Compile-time contract: movable, non-copyable (acceptance criterion #1) --- -static_assert(std::is_move_constructible::value, "PacketPtr must be move-constructible"); -static_assert(std::is_move_assignable::value, "PacketPtr must be move-assignable"); -static_assert(!std::is_copy_constructible::value, "PacketPtr must NOT be copy-constructible"); -static_assert(!std::is_copy_assignable::value, "PacketPtr must NOT be copy-assignable"); -static_assert(std::is_move_constructible::value, "Peer must be move-constructible"); -static_assert(std::is_move_assignable::value, "Peer must be move-assignable"); -static_assert(!std::is_copy_constructible::value, "Peer must NOT be copy-constructible"); -static_assert(!std::is_copy_assignable::value, "Peer must NOT be copy-assignable"); - -// --- PacketPtr --- - -PacketPtr::~PacketPtr() { - if (p_) - owner_->DeallocatePacket(p_); -} - -PacketPtr::PacketPtr(PacketPtr&& o) noexcept : owner_(o.owner_), p_(o.p_) { - o.p_ = nullptr; -} - -PacketPtr& PacketPtr::operator=(PacketPtr&& o) noexcept { - if (this != &o) { - if (p_) - owner_->DeallocatePacket(p_); - owner_ = o.owner_; - p_ = o.p_; - o.p_ = nullptr; - } - return *this; -} - -unsigned char PacketPtr::id() const { - // Mirrors GetPacketIdentifier from the samples: an ID_TIMESTAMP prefix is - // followed by the MessageID + Time, then the real identifier byte. - if (p_ == nullptr || p_->length == 0) - return 255; - - if (static_cast(p_->data[0]) == ID_TIMESTAMP) { - // Guard against a truncated timestamp packet: relying on RakAssert alone - // would be an out-of-bounds read in release builds. - RakAssert(p_->length > sizeof(MessageID) + sizeof(Time)); - if (p_->length <= sizeof(MessageID) + sizeof(Time)) - return 255; - return static_cast(p_->data[sizeof(MessageID) + sizeof(Time)]); - } - return static_cast(p_->data[0]); -} - -// --- Peer --- - -Peer::~Peer() { - if (raw_) - RakPeerInterface::DestroyInstance(raw_); -} - -Peer::Peer(Peer&& o) noexcept : raw_(o.raw_) { - o.raw_ = nullptr; -} - -Peer& Peer::operator=(Peer&& o) noexcept { - if (this != &o) { - if (raw_) - RakPeerInterface::DestroyInstance(raw_); - raw_ = o.raw_; - o.raw_ = nullptr; - } - return *this; -} - -PacketPtr Peer::receive() { - // A moved-from Peer is empty; never dereference a null instance. - return raw_ ? PacketPtr(raw_, raw_->Receive()) : PacketPtr(nullptr, nullptr); -} - -} // namespace MafiaNet diff --git a/vendors/mafianet/Source/src/PluginInterface2.cpp b/vendors/mafianet/Source/src/PluginInterface2.cpp deleted file mode 100644 index 451e30a9a..000000000 --- a/vendors/mafianet/Source/src/PluginInterface2.cpp +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - - -#include "mafianet/PluginInterface2.h" -#include "mafianet/PacketizedTCP.h" -#include "mafianet/peerinterface.h" -#include "mafianet/BitStream.h" - -using namespace MafiaNet; - -PluginInterface2::PluginInterface2() -{ - rakPeerInterface=0; -#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 - tcpInterface=0; -#endif -} -PluginInterface2::~PluginInterface2() -{ - -} -void PluginInterface2::SendUnified( const MafiaNet::BitStream * bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ) -{ - if (rakPeerInterface) - { - rakPeerInterface->Send(bitStream,priority,reliability,orderingChannel,systemIdentifier,broadcast); - return; - } -#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 - else if (tcpInterface) - { - tcpInterface->Send((const char*) bitStream->GetData(), bitStream->GetNumberOfBytesUsed(), systemIdentifier.systemAddress, broadcast); - return; - } -#endif - - // Offline mode - if (broadcast==false && systemIdentifier.rakNetGuid==GetMyGUIDUnified()) - { -// Packet *packet = AllocatePacketUnified(bitStream->GetNumberOfBytesUsed()); -// memcpy(packet->data, bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); - Packet packet; - packet.bitSize=bitStream->GetNumberOfBitsUsed(); - packet.data=bitStream->GetData(); - packet.deleteData=false; - packet.guid=UNASSIGNED_RAKNET_GUID; - packet.length=bitStream->GetNumberOfBytesUsed(); - packet.systemAddress=UNASSIGNED_SYSTEM_ADDRESS; - packet.wasGeneratedLocally=false; - OnReceive(&packet); -// DeallocPacketUnified(packet); - - Update(); - } -} -void PluginInterface2::SendUnified( const char * data, const int length, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ) -{ - if (rakPeerInterface) - { - rakPeerInterface->Send(data, length, priority,reliability,orderingChannel,systemIdentifier,broadcast); - return; - } -#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 - else if (tcpInterface) - { - tcpInterface->Send(data, length, systemIdentifier.systemAddress, broadcast); - return; - } -#endif - - // Offline mode - if (broadcast==false && systemIdentifier.rakNetGuid==GetMyGUIDUnified()) - { - // Packet *packet = AllocatePacketUnified(bitStream->GetNumberOfBytesUsed()); - // memcpy(packet->data, bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); - Packet packet; - packet.bitSize=BYTES_TO_BITS(length); - packet.data=(unsigned char*) data; - packet.deleteData=false; - packet.guid=UNASSIGNED_RAKNET_GUID; - packet.length=length; - packet.systemAddress=UNASSIGNED_SYSTEM_ADDRESS; - packet.wasGeneratedLocally=false; - OnReceive(&packet); - // DeallocPacketUnified(packet); - - Update(); - } -} -Packet *PluginInterface2::AllocatePacketUnified(unsigned dataSize) -{ - if (rakPeerInterface) - { - return rakPeerInterface->AllocatePacket(dataSize); - } -#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 - else if (tcpInterface) - { - return tcpInterface->AllocatePacket(dataSize); - } -#endif - - Packet *packet = MafiaNet::OP_NEW(_FILE_AND_LINE_); - packet->data = (unsigned char*) rakMalloc_Ex(dataSize, _FILE_AND_LINE_); - packet->bitSize=BYTES_TO_BITS(dataSize); - packet->deleteData=true; - packet->guid=UNASSIGNED_RAKNET_GUID; - packet->systemAddress=UNASSIGNED_SYSTEM_ADDRESS; - packet->wasGeneratedLocally=false; - return packet; -} -void PluginInterface2::PushBackPacketUnified(Packet *packet, bool pushAtHead) -{ - if (rakPeerInterface) - { - rakPeerInterface->PushBackPacket(packet,pushAtHead); - return; - } -#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 - else if (tcpInterface) - { - tcpInterface->PushBackPacket(packet,pushAtHead); - return; - } -#endif - - OnReceive(packet); - Update(); -} -void PluginInterface2::DeallocPacketUnified(Packet *packet) -{ - if (rakPeerInterface) - { - rakPeerInterface->DeallocatePacket(packet); - return; - } -#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 - else if (tcpInterface) - { - tcpInterface->DeallocatePacket(packet); - return; - } -#endif - - rakFree_Ex(packet->data, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(packet, _FILE_AND_LINE_); -} -bool PluginInterface2::SendListUnified( const char **data, const int *lengths, const int numParameters, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ) -{ - if (rakPeerInterface) - { - return rakPeerInterface->SendList(data,lengths,numParameters,priority,reliability,orderingChannel,systemIdentifier,broadcast)!=0; - } -#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 - else if (tcpInterface) - { - return tcpInterface->SendList(data,(const unsigned int *) lengths,numParameters,systemIdentifier.systemAddress,broadcast ); - } -#endif - - if (broadcast==false && systemIdentifier.rakNetGuid==GetMyGUIDUnified()) - { - - unsigned int totalLength=0; - unsigned int lengthOffset; - int i; - for (i=0; i < numParameters; i++) - { - if (lengths[i]>0) - totalLength+=lengths[i]; - } - if (totalLength==0) - return false; - - char *dataAggregate; - dataAggregate = (char*) rakMalloc_Ex( (size_t) totalLength, _FILE_AND_LINE_ ); - if (dataAggregate==0) - { - notifyOutOfMemory(_FILE_AND_LINE_); - return false; - } - for (i=0, lengthOffset=0; i < numParameters; i++) - { - if (lengths[i]>0) - { - memcpy(dataAggregate+lengthOffset, data[i], lengths[i]); - lengthOffset+=lengths[i]; - } - } - - SendUnified(dataAggregate, totalLength, priority, reliability,orderingChannel, systemIdentifier, broadcast); - rakFree_Ex(dataAggregate, _FILE_AND_LINE_); - return true; - } - - return false; -} -void PluginInterface2::SetRakPeerInterface( RakPeerInterface *ptr ) -{ - rakPeerInterface=ptr; -} -#if _RAKNET_SUPPORT_TCPInterface==1 -void PluginInterface2::SetTCPInterface( TCPInterface *ptr ) -{ - tcpInterface=ptr; -} -#endif -RakNetGUID PluginInterface2::GetMyGUIDUnified(void) const -{ - if (rakPeerInterface) - return rakPeerInterface->GetMyGUID(); - return UNASSIGNED_RAKNET_GUID; -} diff --git a/vendors/mafianet/Source/src/PointGridSectorizer.cpp b/vendors/mafianet/Source/src/PointGridSectorizer.cpp deleted file mode 100644 index ce618b453..000000000 --- a/vendors/mafianet/Source/src/PointGridSectorizer.cpp +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright (c) 2026, MafiaHub - * - * This source code is licensed under the MIT-style license found in the - * license.txt file in the root directory of this source tree. - */ - -#include "mafianet/PointGridSectorizer.h" -#include -#include - -using namespace MafiaNet; - -static const unsigned int POINT_GRID_INITIAL_RECORD_CAPACITY=64; - -// Mixes the pointer bits (splitmix64 finalizer) so allocation alignment does -// not cluster table slots. -static inline uint64_t PointGridPtrHash(void *entry) -{ - uint64_t h = (uint64_t) (uintptr_t) entry; - h ^= h >> 33; - h *= 0xff51afd7ed558ccdULL; - h ^= h >> 33; - h *= 0xc4ceb9fe1a85ec53ULL; - h ^= h >> 33; - return h; -} - -PointGridSectorizer::PointGridSectorizer() -{ - grid=0; - records=0; - recordCapacity=0; - recordCount=0; - cellOriginX=cellOriginY=0.0f; - invCellWidth=invCellHeight=0.0f; - gridCellWidthCount=gridCellHeightCount=0; -} -PointGridSectorizer::~PointGridSectorizer() -{ - if (grid) - MafiaNet::OP_DELETE_ARRAY(grid, _FILE_AND_LINE_); - if (records) - MafiaNet::OP_DELETE_ARRAY(records, _FILE_AND_LINE_); -} -bool PointGridSectorizer::Init(const float _cellWidth, const float _cellHeight, const float minX, const float minY, const float maxX, const float maxY) -{ - // Tear down any previous state first; on failure the grid stays inert. - if (grid) - { - MafiaNet::OP_DELETE_ARRAY(grid, _FILE_AND_LINE_); - grid=0; - } - if (records) - { - MafiaNet::OP_DELETE_ARRAY(records, _FILE_AND_LINE_); - records=0; - } - recordCapacity=0; - recordCount=0; - gridCellWidthCount=gridCellHeightCount=0; - - // Invalid parameters are reported through the return value rather than an - // assert so the failure path stays exercisable in debug builds; the - // negated comparisons also reject NaN parameters. - if (!(_cellWidth > 0.0f) || !(_cellHeight > 0.0f) || !(minX < maxX) || !(minY < maxY)) - return false; - - const float gridWidth=maxX-minX; - const float gridHeight=maxY-minY; - const double cellsWide=ceil((double) gridWidth/_cellWidth); - const double cellsHigh=ceil((double) gridHeight/_cellHeight); - // Computed in double so a huge world / tiny cell combination is caught - // here instead of wrapping the int cell count (and the allocation size). - if (!(cellsWide >= 1.0) || !(cellsHigh >= 1.0) || cellsWide*cellsHigh > 2147483647.0) - return false; - - cellOriginX=minX; - cellOriginY=minY; - gridCellWidthCount=(int) cellsWide; - gridCellHeightCount=(int) cellsHigh; - // Make the cells slightly smaller, so we allocate an extra unneeded cell if on the edge. This way we don't go outside the array on rounding errors. - invCellWidth = (float) gridCellWidthCount / gridWidth; - invCellHeight = (float) gridCellHeightCount / gridHeight; - - // Records before grid: if the second allocation throws, grid==0 still - // marks the instance inert and the destructor frees what was allocated. - records = MafiaNet::OP_NEW_ARRAY(POINT_GRID_INITIAL_RECORD_CAPACITY, _FILE_AND_LINE_); - recordCapacity=POINT_GRID_INITIAL_RECORD_CAPACITY; - for (unsigned int i=0; i < recordCapacity; ++i) - records[i].entry=0; - grid = MafiaNet::OP_NEW_ARRAY >(gridCellWidthCount*gridCellHeightCount, _FILE_AND_LINE_ ); - return true; -} -bool PointGridSectorizer::AddEntry(void *entry, const float x, const float y) -{ - // Same upsert as MoveEntry: one record per pointer, relocate if already present. - return MoveEntry(entry, x, y); -} -bool PointGridSectorizer::RemoveEntry(void *entry) -{ - if (grid==0 || entry==0) - return false; - - EntryRecord *record = FindRecord(entry); - if (record==0) - return false; - RemoveFromCell(*record); - EraseRecord(record); - return true; -} -bool PointGridSectorizer::MoveEntry(void *entry, const float x, const float y) -{ - // A null entry would corrupt the record table (null marks empty slots). - if (grid==0 || entry==0) - return false; - - const int cellIndex = WorldToCellIndexClamped(x, y); - EntryRecord *record = FindRecord(entry); - if (record==0) - { - InsertRecord(entry, cellIndex, PushIntoCell(entry, cellIndex)); - return true; - } - if (record->cellIndex==cellIndex) - return false; - - RemoveFromCell(*record); - record->cellIndex=cellIndex; - record->slotIndex=PushIntoCell(entry, cellIndex); - return true; -} -void PointGridSectorizer::GetEntries(DataStructures::List &intersectionList, const float minX, const float minY, const float maxX, const float maxY) const -{ - // Reset without releasing the buffer (List::Clear deallocates >512-element - // blocks even with doNotDeallocateSmallBlocks), so a reused query list - // keeps its high-water-mark capacity instead of regrowing every call. - intersectionList.RemoveFromEnd(intersectionList.Size()); - if (grid==0) - return; - - const int xStart=WorldToCellXClamped(minX); - const int yStart=WorldToCellYClamped(minY); - const int xEnd=WorldToCellXClamped(maxX); - const int yEnd=WorldToCellYClamped(maxY); - - for (int yCur=yStart; yCur <= yEnd; ++yCur) - { - // Row-major: consecutive cells of a row are adjacent in memory, so - // sweeping mostly-empty regions stays cache-friendly. - const DataStructures::List *row = grid + yCur*gridCellWidthCount; - for (int xCur=xStart; xCur <= xEnd; ++xCur) - { - const DataStructures::List &cell = row[xCur]; - for (unsigned int index=0; index < cell.Size(); ++index) - intersectionList.Push(cell[index], _FILE_AND_LINE_); - } - } -} -bool PointGridSectorizer::HasEntry(void *entry) const -{ - return entry!=0 && FindRecord(entry)!=0; -} -unsigned int PointGridSectorizer::Size(void) const -{ - return recordCount; -} -void PointGridSectorizer::Clear(void) -{ - if (grid==0) - return; - const int count = gridCellWidthCount*gridCellHeightCount; - for (int cur=0; cur recordCapacity-(recordCapacity/4)) - GrowRecordTable(); - const unsigned int mask = recordCapacity-1; - unsigned int i = (unsigned int) PointGridPtrHash(entry) & mask; - while (records[i].entry != 0) - i = (i+1) & mask; - records[i].entry=entry; - records[i].cellIndex=cellIndex; - records[i].slotIndex=slotIndex; - recordCount++; -} -void PointGridSectorizer::EraseRecord(EntryRecord *record) -{ - const unsigned int mask = recordCapacity-1; - unsigned int hole = (unsigned int)(record-records); - records[hole].entry=0; - // Backward-shift deletion: pull each follower whose home slot is cyclically - // outside (hole, follower] back into the hole, so probe chains stay intact - // without tombstones. - unsigned int follower = hole; - for (;;) - { - follower = (follower+1) & mask; - if (records[follower].entry==0) - break; - const unsigned int home = (unsigned int) PointGridPtrHash(records[follower].entry) & mask; - const bool canFillHole = (follower > hole) ? (home <= hole || home > follower) : (home <= hole && home > follower); - if (canFillHole) - { - records[hole]=records[follower]; - records[follower].entry=0; - hole=follower; - } - } - recordCount--; -} -void PointGridSectorizer::GrowRecordTable(void) -{ - // Allocate and rehash into a temporary first: records/recordCapacity are - // only updated once the new table exists, so a throwing allocation cannot - // leave a doubled capacity (and probe mask) over the old half-size array. - const unsigned int newCapacity = recordCapacity*2; - EntryRecord *newRecords = MafiaNet::OP_NEW_ARRAY(newCapacity, _FILE_AND_LINE_); - for (unsigned int i=0; i < newCapacity; ++i) - newRecords[i].entry=0; - const unsigned int mask = newCapacity-1; - for (unsigned int i=0; i < recordCapacity; ++i) - { - if (records[i].entry==0) - continue; - unsigned int j = (unsigned int) PointGridPtrHash(records[i].entry) & mask; - while (newRecords[j].entry != 0) - j = (j+1) & mask; - newRecords[j]=records[i]; - } - MafiaNet::OP_DELETE_ARRAY(records, _FILE_AND_LINE_); - records=newRecords; - recordCapacity=newCapacity; -} -unsigned int PointGridSectorizer::PushIntoCell(void *entry, const int cellIndex) -{ - DataStructures::List &cell = grid[cellIndex]; - cell.Push(entry, _FILE_AND_LINE_); - return cell.Size()-1; -} -void PointGridSectorizer::RemoveFromCell(const EntryRecord &record) -{ - DataStructures::List &cell = grid[record.cellIndex]; - void *last = cell[cell.Size()-1]; - if (last != record.entry) - { - // Swap-remove: the last entry will fill the freed slot; fix its stored slot. - FindRecord(last)->slotIndex=record.slotIndex; - } - cell.RemoveAtIndexFast(record.slotIndex); -} -int PointGridSectorizer::WorldToCellXClamped(const float input) const -{ - // Clamp in float space BEFORE the int cast: casting NaN or a value beyond - // int range to int is undefined behavior (and saturates differently per - // platform). The negated comparison sends NaN to cell 0. - const float cell = (input-cellOriginX)*invCellWidth; - if (!(cell > 0.0f)) - return 0; - if (cell >= (float) gridCellWidthCount) - return gridCellWidthCount-1; - const int asInt = (int) cell; - return asInt < gridCellWidthCount ? asInt : gridCellWidthCount-1; -} -int PointGridSectorizer::WorldToCellYClamped(const float input) const -{ - const float cell = (input-cellOriginY)*invCellHeight; - if (!(cell > 0.0f)) - return 0; - if (cell >= (float) gridCellHeightCount) - return gridCellHeightCount-1; - const int asInt = (int) cell; - return asInt < gridCellHeightCount ? asInt : gridCellHeightCount-1; -} -int PointGridSectorizer::WorldToCellIndexClamped(const float x, const float y) const -{ - return WorldToCellYClamped(y)*gridCellWidthCount + WorldToCellXClamped(x); -} diff --git a/vendors/mafianet/Source/src/RPC4Plugin.cpp b/vendors/mafianet/Source/src/RPC4Plugin.cpp deleted file mode 100644 index 829b580c4..000000000 --- a/vendors/mafianet/Source/src/RPC4Plugin.cpp +++ /dev/null @@ -1,647 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_RPC4Plugin==1 - -#include "mafianet/RPC4Plugin.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/peerinterface.h" -#include "mafianet/PacketizedTCP.h" -#include "mafianet/sleep.h" -#include "mafianet/defines.h" -#include "mafianet/DS_Queue.h" -//#include "mafianet/GetTime.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(RPC4,RPC4); - -struct GlobalRegistration -{ - void ( *registerFunctionPointer ) (MafiaNet::BitStream *userData, Packet *packet, void *context ); - void ( *registerBlockingFunctionPointer ) (MafiaNet::BitStream *userData, MafiaNet::BitStream *returnData, Packet *packet, void *context ); - void *context; - char functionName[RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH]; - MessageID messageId; - int callPriority; -}; -static GlobalRegistration globalRegistrationBuffer[RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS]; -static unsigned int globalRegistrationIndex=0; - -RPC4GlobalRegistration::RPC4GlobalRegistration(const char* uniqueID, void ( *functionPointer ) (MafiaNet::BitStream *userData, Packet *packet, void *context ), void *context) -{ - RakAssert(globalRegistrationIndex!=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS); - unsigned int i; - for (i=0; uniqueID[i]; i++) - { - RakAssert(i<=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH-1); - globalRegistrationBuffer[globalRegistrationIndex].functionName[i]=uniqueID[i]; - } - globalRegistrationBuffer[globalRegistrationIndex].registerFunctionPointer=functionPointer; - globalRegistrationBuffer[globalRegistrationIndex].registerBlockingFunctionPointer=0; - globalRegistrationBuffer[globalRegistrationIndex].context=context; - globalRegistrationBuffer[globalRegistrationIndex].callPriority=0xFFFFFFFF; - globalRegistrationIndex++; -} -RPC4GlobalRegistration::RPC4GlobalRegistration(const char* uniqueID, void ( *functionPointer ) (MafiaNet::BitStream *userData, Packet *packet, void *context ), void *context, int callPriority) -{ - RakAssert(globalRegistrationIndex!=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS); - unsigned int i; - for (i=0; uniqueID[i]; i++) - { - RakAssert(i<=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH-1); - globalRegistrationBuffer[globalRegistrationIndex].functionName[i]=uniqueID[i]; - } - globalRegistrationBuffer[globalRegistrationIndex].registerFunctionPointer=functionPointer; - globalRegistrationBuffer[globalRegistrationIndex].registerBlockingFunctionPointer=0; - globalRegistrationBuffer[globalRegistrationIndex].context=context; - RakAssert(callPriority!=(int) 0xFFFFFFFF); - globalRegistrationBuffer[globalRegistrationIndex].callPriority=callPriority; - globalRegistrationIndex++; -} -RPC4GlobalRegistration::RPC4GlobalRegistration(const char* uniqueID, void ( *functionPointer ) (MafiaNet::BitStream *userData, MafiaNet::BitStream *returnData, Packet *packet, void *context ), void *context) -{ - RakAssert(globalRegistrationIndex!=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS); - unsigned int i; - for (i=0; uniqueID[i]; i++) - { - RakAssert(i<=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH-1); - globalRegistrationBuffer[globalRegistrationIndex].functionName[i]=uniqueID[i]; - } - globalRegistrationBuffer[globalRegistrationIndex].registerFunctionPointer=0; - globalRegistrationBuffer[globalRegistrationIndex].registerBlockingFunctionPointer=functionPointer; - globalRegistrationBuffer[globalRegistrationIndex].context=context; - globalRegistrationIndex++; -} -RPC4GlobalRegistration::RPC4GlobalRegistration(const char* uniqueID, MessageID messageId) -{ - RakAssert(globalRegistrationIndex!=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS); - unsigned int i; - for (i=0; uniqueID[i]; i++) - { - RakAssert(i<=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH-1); - globalRegistrationBuffer[globalRegistrationIndex].functionName[i]=uniqueID[i]; - } - globalRegistrationBuffer[globalRegistrationIndex].registerFunctionPointer=0; - globalRegistrationBuffer[globalRegistrationIndex].registerBlockingFunctionPointer=0; - globalRegistrationBuffer[globalRegistrationIndex].context=0; - globalRegistrationBuffer[globalRegistrationIndex].messageId=messageId; - globalRegistrationIndex++; -} - -enum RPC4Identifiers -{ - ID_RPC4_CALL, - ID_RPC4_RETURN, - ID_RPC4_SIGNAL, -}; -int RPC4::LocalSlotObjectComp( const LocalSlotObject &key, const LocalSlotObject &data ) -{ - if (key.callPriority>data.callPriority) - return -1; - if (key.callPriority==data.callPriority) - { - if (key.registrationCountmessageId) - return -1; - if (key > data->messageId) - return 1; - return 0; -} - -RPC4::RPC4() -{ - gotBlockingReturnValue=false; - nextSlotRegistrationCount=0; - interruptSignal=false; -} -RPC4::~RPC4() -{ - unsigned int i; - for (i=0; i < localCallbacks.Size(); i++) - { - MafiaNet::OP_DELETE(localCallbacks[i],_FILE_AND_LINE_); - } - - DataStructures::List keyList; - DataStructures::List outputList; - localSlots.GetAsList(outputList,keyList,_FILE_AND_LINE_); - unsigned int j; - for (j=0; j < outputList.Size(); j++) - { - MafiaNet::OP_DELETE(outputList[j],_FILE_AND_LINE_); - } - localSlots.Clear(_FILE_AND_LINE_); -} -bool RPC4::RegisterFunction(const char* uniqueID, void ( *functionPointer ) (MafiaNet::BitStream *userData, Packet *packet, void *context ), void *context) -{ - DataStructures::HashIndex skhi = registeredNonblockingFunctions.GetIndexOf(uniqueID); - if (skhi.IsInvalid()==false) - return false; - - RegisteredNonblockingFunction rnf; - rnf.functionPointer=functionPointer; - rnf.context=context; - registeredNonblockingFunctions.Push(uniqueID,rnf,_FILE_AND_LINE_); - return true; -} -void RPC4::RegisterSlot(const char *sharedIdentifier, void ( *functionPointer ) (MafiaNet::BitStream *userData, Packet *packet, void *context ), void *context, int callPriority) -{ - LocalSlotObject lso(nextSlotRegistrationCount++, callPriority, functionPointer, context); - DataStructures::HashIndex idx = GetLocalSlotIndex(sharedIdentifier); - LocalSlot *localSlot; - if (idx.IsInvalid()) - { - localSlot = MafiaNet::OP_NEW(_FILE_AND_LINE_); - localSlots.Push(sharedIdentifier, localSlot,_FILE_AND_LINE_); - } - else - { - localSlot=localSlots.ItemAtIndex(idx); - } - localSlot->slotObjects.Insert(lso,lso,true,_FILE_AND_LINE_); -} -bool RPC4::RegisterBlockingFunction(const char* uniqueID, void ( *functionPointer ) (MafiaNet::BitStream *userData, MafiaNet::BitStream *returnData, Packet *packet, void *context ), void *context) -{ - DataStructures::HashIndex skhi = registeredBlockingFunctions.GetIndexOf(uniqueID); - if (skhi.IsInvalid()==false) - return false; - - RegisteredBlockingFunction rbf; - rbf.functionPointer=functionPointer; - rbf.context=context; - registeredBlockingFunctions.Push(uniqueID,rbf,_FILE_AND_LINE_); - return true; -} -void RPC4::RegisterLocalCallback(const char* uniqueID, MessageID messageId) -{ - bool objectExists; - unsigned int index; - LocalCallback *lc; - MafiaNet::RakString str; - str=uniqueID; - index = localCallbacks.GetIndexFromKey(messageId,&objectExists); - if (objectExists) - { - lc = localCallbacks[index]; - index = lc->functions.GetIndexFromKey(str,&objectExists); - if (objectExists==false) - lc->functions.InsertAtIndex(str,index,_FILE_AND_LINE_); - } - else - { - lc = MafiaNet::OP_NEW(_FILE_AND_LINE_); - lc->messageId=messageId; - lc->functions.Insert(str,str,false,_FILE_AND_LINE_); - localCallbacks.InsertAtIndex(lc,index,_FILE_AND_LINE_); - } -} -bool RPC4::UnregisterFunction(const char* uniqueID) -{ - RegisteredNonblockingFunction f; - return registeredNonblockingFunctions.Pop(f,uniqueID,_FILE_AND_LINE_); -} -bool RPC4::UnregisterBlockingFunction(const char* uniqueID) -{ - RegisteredBlockingFunction f; - return registeredBlockingFunctions.Pop(f,uniqueID,_FILE_AND_LINE_); -} -bool RPC4::UnregisterLocalCallback(const char* uniqueID, MessageID messageId) -{ - bool objectExists; - unsigned int index, index2; - LocalCallback *lc; - MafiaNet::RakString str; - str=uniqueID; - index = localCallbacks.GetIndexFromKey(messageId,&objectExists); - if (objectExists) - { - lc = localCallbacks[index]; - index2 = lc->functions.GetIndexFromKey(str,&objectExists); - if (objectExists) - { - lc->functions.RemoveAtIndex(index2); - if (lc->functions.Size()==0) - { - MafiaNet::OP_DELETE(lc,_FILE_AND_LINE_); - localCallbacks.RemoveAtIndex(index); - return true; - } - } - } - return false; -} -bool RPC4::UnregisterSlot(const char* sharedIdentifier) -{ - DataStructures::HashIndex hi = localSlots.GetIndexOf(sharedIdentifier); - if (hi.IsInvalid()==false) - { - LocalSlot *ls = localSlots.ItemAtIndex(hi); - MafiaNet::OP_DELETE(ls, _FILE_AND_LINE_); - localSlots.RemoveAtIndex(hi, _FILE_AND_LINE_); - return true; - } - - return false; -} -void RPC4::CallLoopback( const char* uniqueID, MafiaNet::BitStream * bitStream ) -{ - Packet *p=0; - - DataStructures::HashIndex skhi = registeredNonblockingFunctions.GetIndexOf(uniqueID); - - if (skhi.IsInvalid()==true) - { - if (rakPeerInterface) - p=AllocatePacketUnified(sizeof(MessageID)+sizeof(unsigned char)+(unsigned int) strlen(uniqueID)+1); -#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 - else - p=tcpInterface->AllocatePacket(sizeof(MessageID)+sizeof(unsigned char)+(unsigned int) strlen(uniqueID)+1); -#endif - - if (rakPeerInterface) - p->guid=rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); -#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 - else - p->guid=UNASSIGNED_RAKNET_GUID; -#endif - - p->systemAddress=UNASSIGNED_SYSTEM_ADDRESS; - p->systemAddress.systemIndex=(SystemIndex)-1; - p->data[0]=ID_RPC_REMOTE_ERROR; - p->data[1]=RPC_ERROR_FUNCTION_NOT_REGISTERED; - strcpy_s((char*) p->data+2, p->length-2, uniqueID); - - PushBackPacketUnified(p,false); - - return; - } - - MafiaNet::BitStream out; - out.Write((MessageID) ID_RPC_PLUGIN); - out.Write((MessageID) ID_RPC4_CALL); - out.WriteCompressed(uniqueID); - out.Write(false); // nonblocking - if (bitStream) - { - bitStream->ResetReadPointer(); - out.AlignWriteToByteBoundary(); - out.Write(bitStream); - } - if (rakPeerInterface) - p=AllocatePacketUnified(out.GetNumberOfBytesUsed()); -#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 - else - p=tcpInterface->AllocatePacket(out.GetNumberOfBytesUsed()); -#endif - - if (rakPeerInterface) - p->guid=rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); -#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 - else - p->guid=UNASSIGNED_RAKNET_GUID; -#endif - p->systemAddress=UNASSIGNED_SYSTEM_ADDRESS; - p->systemAddress.systemIndex=(SystemIndex)-1; - memcpy(p->data,out.GetData(),out.GetNumberOfBytesUsed()); - PushBackPacketUnified(p,false); - return; -} -void RPC4::Call( const char* uniqueID, MafiaNet::BitStream * bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ) -{ - MafiaNet::BitStream out; - out.Write((MessageID) ID_RPC_PLUGIN); - out.Write((MessageID) ID_RPC4_CALL); - out.WriteCompressed(uniqueID); - out.Write(false); // Nonblocking - if (bitStream) - { - bitStream->ResetReadPointer(); - out.AlignWriteToByteBoundary(); - out.Write(bitStream); - } - SendUnified(&out,priority,reliability,orderingChannel,systemIdentifier,broadcast); -} -bool RPC4::CallBlocking( const char* uniqueID, MafiaNet::BitStream * bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, MafiaNet::BitStream *returnData ) -{ - MafiaNet::BitStream out; - out.Write((MessageID) ID_RPC_PLUGIN); - out.Write((MessageID) ID_RPC4_CALL); - out.WriteCompressed(uniqueID); - out.Write(true); // Blocking - if (bitStream) - { - bitStream->ResetReadPointer(); - out.AlignWriteToByteBoundary(); - out.Write(bitStream); - } - RakAssert(returnData); - RakAssert(rakPeerInterface); - ConnectionState cs; - cs = rakPeerInterface->GetConnectionState(systemIdentifier); - if (cs!=IS_CONNECTED) - return false; - - SendUnified(&out,priority,reliability,orderingChannel,systemIdentifier,false); - - returnData->Reset(); - blockingReturnValue.Reset(); - gotBlockingReturnValue=false; - Packet *packet; - DataStructures::Queue packetQueue; - while (gotBlockingReturnValue==false) - { - // TODO - block, filter until gotBlockingReturnValue==true or ID_CONNECTION_LOST or ID_DISCONNECTION_NOTIFICXATION or ID_RPC_REMOTE_ERROR/RPC_ERROR_FUNCTION_NOT_REGISTERED - RakSleep(30); - - packet=rakPeerInterface->Receive(); - - if (packet) - { - if ( - (packet->data[0]==ID_CONNECTION_LOST || packet->data[0]==ID_DISCONNECTION_NOTIFICATION) && - ((systemIdentifier.rakNetGuid!=UNASSIGNED_RAKNET_GUID && packet->guid==systemIdentifier.rakNetGuid) || - (systemIdentifier.systemAddress!=UNASSIGNED_SYSTEM_ADDRESS && packet->systemAddress==systemIdentifier.systemAddress)) - ) - { - // Push back to head in reverse order - rakPeerInterface->PushBackPacket(packet,true); - while (packetQueue.Size()) - rakPeerInterface->PushBackPacket(packetQueue.Pop(),true); - return false; - } - else if (packet->data[0]==ID_RPC_REMOTE_ERROR && packet->data[1]==RPC_ERROR_FUNCTION_NOT_REGISTERED) - { - MafiaNet::RakString functionName; - MafiaNet::BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2); - bsIn.Read(functionName); - if (functionName==uniqueID) - { - // Push back to head in reverse order - rakPeerInterface->PushBackPacket(packet,true); - while (packetQueue.Size()) - rakPeerInterface->PushBackPacket(packetQueue.Pop(),true); - return false; - } - else - { - packetQueue.PushAtHead(packet,0,_FILE_AND_LINE_); - } - } - else - { - packetQueue.PushAtHead(packet,0,_FILE_AND_LINE_); - } - } - } - - returnData->Write(blockingReturnValue); - returnData->ResetReadPointer(); - return true; -} -void RPC4::Signal(const char *sharedIdentifier, MafiaNet::BitStream *bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, bool invokeLocal) -{ - MafiaNet::BitStream out; - out.Write((MessageID) ID_RPC_PLUGIN); - out.Write((MessageID) ID_RPC4_SIGNAL); - out.WriteCompressed(sharedIdentifier); - if (bitStream) - { - bitStream->ResetReadPointer(); - out.AlignWriteToByteBoundary(); - out.Write(bitStream); - } - SendUnified(&out,priority,reliability,orderingChannel,systemIdentifier,broadcast); - - if (invokeLocal) - { - //TimeUS t1 = GetTimeUS(); - - DataStructures::HashIndex functionIndex; - functionIndex = localSlots.GetIndexOf(sharedIdentifier); - //TimeUS t2 = GetTimeUS(); - if (functionIndex.IsInvalid()) - return; - - Packet p; - p.guid=rakPeerInterface->GetMyGUID(); - p.systemAddress=rakPeerInterface->GetInternalID(UNASSIGNED_SYSTEM_ADDRESS); - p.wasGeneratedLocally=true; - MafiaNet::BitStream *bsptr, bstemp; - if (bitStream) - { - bitStream->ResetReadPointer(); - p.length=bitStream->GetNumberOfBytesUsed(); - p.bitSize=bitStream->GetNumberOfBitsUsed(); - bsptr=bitStream; - } - else - { - p.length=0; - p.bitSize=0; - bsptr=&bstemp; - } - - //TimeUS t3 = GetTimeUS(); - InvokeSignal(functionIndex, bsptr, &p); - //TimeUS t4 = GetTimeUS(); - //printf("b1: %I64d\n", t2-t1); - //printf("b2: %I64d\n", t3-t2); - //printf("b3: %I64d\n", t4-t3); - } -} -void RPC4::InvokeSignal(DataStructures::HashIndex functionIndex, MafiaNet::BitStream *serializedParameters, Packet *packet) -{ - if (functionIndex.IsInvalid()) - return; - - //TimeUS t1 = GetTimeUS(); - //TimeUS t2=0; - //TimeUS t3=0; - - interruptSignal=false; - LocalSlot *localSlot = localSlots.ItemAtIndex(functionIndex); - unsigned int i; - i=0; - while (i < localSlot->slotObjects.Size()) - { - //t2 = GetTimeUS(); - - localSlot->slotObjects[i].functionPointer(serializedParameters, packet, localSlot->slotObjects[i].context); - - //t3 = GetTimeUS(); - - // Not threadsafe - if (interruptSignal==true) - break; - - serializedParameters->ResetReadPointer(); - - i++; - } - - //TimeUS t4 = GetTimeUS(); - - //printf("b1: %I64d\n", t2-t1); - //printf("b2: %I64d\n", t3-t2); - //printf("b3: %I64d\n", t4-t3); -} -void RPC4::InterruptSignal(void) -{ - interruptSignal=true; -} -void RPC4::OnAttach(void) -{ - unsigned int i; - for (i=0; i < globalRegistrationIndex; i++) - { - if (globalRegistrationBuffer[i].registerFunctionPointer) - { - if (globalRegistrationBuffer[i].callPriority==(int)0xFFFFFFFF) - RegisterFunction(globalRegistrationBuffer[i].functionName, globalRegistrationBuffer[i].registerFunctionPointer, globalRegistrationBuffer[i].context); - else - RegisterSlot(globalRegistrationBuffer[i].functionName, globalRegistrationBuffer[i].registerFunctionPointer, globalRegistrationBuffer[i].context, globalRegistrationBuffer[i].callPriority); - } - else if (globalRegistrationBuffer[i].registerBlockingFunctionPointer) - RegisterBlockingFunction(globalRegistrationBuffer[i].functionName, globalRegistrationBuffer[i].registerBlockingFunctionPointer, globalRegistrationBuffer[i].context); - else - RegisterLocalCallback(globalRegistrationBuffer[i].functionName, globalRegistrationBuffer[i].messageId); - } -} -PluginReceiveResult RPC4::OnReceive(Packet *packet) -{ - if (packet->data[0]==ID_RPC_PLUGIN) - { - MafiaNet::BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2); - - if (packet->data[1]==ID_RPC4_CALL) - { - MafiaNet::RakString functionName; - bsIn.ReadCompressed(functionName); - bool isBlocking=false; - bsIn.Read(isBlocking); - if (isBlocking==false) - { - DataStructures::HashIndex skhi = registeredNonblockingFunctions.GetIndexOf(functionName.C_String()); - if (skhi.IsInvalid()) - { - MafiaNet::BitStream bsOut; - bsOut.Write((unsigned char) ID_RPC_REMOTE_ERROR); - bsOut.Write((unsigned char) RPC_ERROR_FUNCTION_NOT_REGISTERED); - bsOut.Write(functionName.C_String(),(unsigned int) functionName.GetLength()+1); - SendUnified(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,packet->systemAddress,false); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - - RegisteredNonblockingFunction rnf; - rnf = registeredNonblockingFunctions.ItemAtIndex(skhi); - bsIn.AlignReadToByteBoundary(); - rnf.functionPointer(&bsIn,packet,rnf.context); - } - else - { - DataStructures::HashIndex skhi = registeredBlockingFunctions.GetIndexOf(functionName.C_String()); - if (skhi.IsInvalid()) - { - MafiaNet::BitStream bsOut; - bsOut.Write((unsigned char) ID_RPC_REMOTE_ERROR); - bsOut.Write((unsigned char) RPC_ERROR_FUNCTION_NOT_REGISTERED); - bsOut.Write(functionName.C_String(),(unsigned int) functionName.GetLength()+1); - SendUnified(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,packet->systemAddress,false); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - - RegisteredBlockingFunction rbf; - rbf = registeredBlockingFunctions.ItemAtIndex(skhi); - MafiaNet::BitStream returnData; - bsIn.AlignReadToByteBoundary(); - rbf.functionPointer(&bsIn, &returnData, packet, rbf.context); - - MafiaNet::BitStream out; - out.Write((MessageID) ID_RPC_PLUGIN); - out.Write((MessageID) ID_RPC4_RETURN); - returnData.ResetReadPointer(); - out.AlignWriteToByteBoundary(); - out.Write(returnData); - SendUnified(&out,MafiaNet::Priority::Immediate,MafiaNet::Reliability::ReliableOrdered,0,packet->systemAddress,false); - } - } - else if (packet->data[1]==ID_RPC4_SIGNAL) - { - MafiaNet::RakString sharedIdentifier; - bsIn.ReadCompressed(sharedIdentifier); - DataStructures::HashIndex functionIndex; - functionIndex = localSlots.GetIndexOf(sharedIdentifier); - MafiaNet::BitStream serializedParameters; - bsIn.AlignReadToByteBoundary(); - bsIn.Read(&serializedParameters); - InvokeSignal(functionIndex, &serializedParameters, packet); - } - else - { - RakAssert(packet->data[1]==ID_RPC4_RETURN); - blockingReturnValue.Reset(); - blockingReturnValue.Write(bsIn); - gotBlockingReturnValue=true; - } - - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - - bool objectExists; - unsigned int index, index2; - index = localCallbacks.GetIndexFromKey(packet->data[0],&objectExists); - if (objectExists) - { - LocalCallback *lc; - lc = localCallbacks[index]; - for (index2=0; index2 < lc->functions.Size(); index2++) - { - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - - DataStructures::HashIndex skhi = registeredNonblockingFunctions.GetIndexOf(lc->functions[index2].C_String()); - if (skhi.IsInvalid()==false) - { - RegisteredNonblockingFunction rnf; - rnf = registeredNonblockingFunctions.ItemAtIndex(skhi); - bsIn.AlignReadToByteBoundary(); - rnf.functionPointer(&bsIn,packet,rnf.context); - } - } - } - - return RR_CONTINUE_PROCESSING; -} -DataStructures::HashIndex RPC4::GetLocalSlotIndex(const char *sharedIdentifier) -{ - return localSlots.GetIndexOf(sharedIdentifier); -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/Rackspace.cpp b/vendors/mafianet/Source/src/Rackspace.cpp deleted file mode 100644 index 4d57b92c1..000000000 --- a/vendors/mafianet/Source/src/Rackspace.cpp +++ /dev/null @@ -1,676 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_Rackspace==1 && _RAKNET_SUPPORT_TCPInterface==1 - -#include "mafianet/Rackspace.h" -#include "mafianet/string.h" -#include "mafianet/TCPInterface.h" - -using namespace MafiaNet; - -Rackspace::Rackspace() -{ - tcpInterface=0; -} - -Rackspace::~Rackspace() -{ - -} - -void Rackspace::AddEventCallback(Rackspace2EventCallback *callback) -{ - unsigned int idx = eventCallbacks.GetIndexOf(callback); - if (idx == (unsigned int)-1) - eventCallbacks.Push(callback,_FILE_AND_LINE_); -} -void Rackspace::RemoveEventCallback(Rackspace2EventCallback *callback) -{ - unsigned int idx = eventCallbacks.GetIndexOf(callback); - if (idx != (unsigned int)-1) - eventCallbacks.RemoveAtIndex(idx); -} -void Rackspace::ClearEventCallbacks(void) -{ - eventCallbacks.Clear(true, _FILE_AND_LINE_); -} -SystemAddress Rackspace::Authenticate(TCPInterface *_tcpInterface, const char *_authenticationURL, const char *_rackspaceCloudUsername, const char *_apiAccessKey) -{ - unsigned int index = GetOperationOfTypeIndex(RO_CONNECT_AND_AUTHENTICATE); - if (index!=(unsigned int)-1) - { - // In progress - return operations[index].connectionAddress; - } - - tcpInterface=_tcpInterface; - - rackspaceCloudUsername=_rackspaceCloudUsername; - apiAccessKey=_apiAccessKey; - - unsigned int i; - - RackspaceOperation ro; - ro.type=RO_CONNECT_AND_AUTHENTICATE; - ro.isPendingAuthentication=false; - - RakAssert(tcpInterface->WasStarted()); - ro.connectionAddress=tcpInterface->Connect(_authenticationURL,443,true); - if (ro.connectionAddress==UNASSIGNED_SYSTEM_ADDRESS) - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnConnectionAttemptFailure(RO_CONNECT_AND_AUTHENTICATE, _authenticationURL); - - return UNASSIGNED_SYSTEM_ADDRESS; - } - -#if OPEN_SSL_CLIENT_SUPPORT==1 - tcpInterface->StartSSLClient(ro.connectionAddress); -#endif - - MafiaNet::RakString command( - "GET /v1.0 HTTP/1.1\n" - "Host: %s\n" - "X-Auth-User: %s\n" - "X-Auth-Key: %s\n\n" - ,_authenticationURL, _rackspaceCloudUsername, _apiAccessKey); - tcpInterface->Send(command.C_String(), (unsigned int) command.GetLength(), ro.connectionAddress, false); - - operations.Insert(ro,_FILE_AND_LINE_); - return ro.connectionAddress; -} - -const char * Rackspace::EventTypeToString(RackspaceEventType eventType) -{ - switch (eventType) - { - case RET_Success_200: - return "Success_200"; - case RET_Success_201: - return "Success_201"; - case RET_Success_202: - return "Success_202"; - case RET_Success_203: - return "Success_203"; - case RET_Success_204: - return "Success_204"; - case RET_Cloud_Servers_Fault_500: - return "Cloud_Servers_Fault_500"; - case RET_Service_Unavailable_503: - return "Service_Unavailable_503"; - case RET_Unauthorized_401: - return "Unauthorized_401"; - case RET_Bad_Request_400: - return "Bad_Request_400"; - case RET_Over_Limit_413: - return "Over_Limit_413"; - case RET_Bad_Media_Type_415: - return "Bad_Media_Type_415"; - case RET_Item_Not_Found_404: - return "Item_Not_Found_404"; - case RET_Build_In_Progress_409: - return "Build_In_Progress_409"; - case RET_Resize_Not_Allowed_403: - return "Resize_Not_Allowed_403"; - case RET_Connection_Closed_Without_Reponse: - return "Connection_Closed_Without_Reponse"; - case RET_Unknown_Failure: - return "Unknown_Failure"; - } - return "Unknown event type (bug)"; -} -void Rackspace::AddOperation(RackspaceOperationType type, MafiaNet::RakString httpCommand, MafiaNet::RakString operation, MafiaNet::RakString xml) -{ - RackspaceOperation ro; - ro.type=type; - ro.httpCommand=httpCommand; - ro.operation=operation; - ro.xml=xml; - ro.isPendingAuthentication=HasOperationOfType(RO_CONNECT_AND_AUTHENTICATE); - if (ro.isPendingAuthentication==false) - { - if (ExecuteOperation(ro)) - operations.Insert(ro,_FILE_AND_LINE_); - } - else - operations.Insert(ro,_FILE_AND_LINE_); -} -void Rackspace::ListServers(void) -{ - AddOperation(RO_LIST_SERVERS, "GET", "servers", ""); -} -void Rackspace::ListServersWithDetails(void) -{ - AddOperation(RO_LIST_SERVERS_WITH_DETAILS, "GET", "servers/detail", ""); -} -void Rackspace::CreateServer(MafiaNet::RakString name, MafiaNet::RakString imageId, MafiaNet::RakString flavorId) -{ - MafiaNet::RakString xml( - "" - "" - "" - ,name.C_String() ,imageId.C_String(), flavorId.C_String()); - AddOperation(RO_CREATE_SERVER, "POST", "servers", xml); -} -void Rackspace::GetServerDetails(MafiaNet::RakString serverId) -{ - AddOperation(RO_GET_SERVER_DETAILS, "GET", MafiaNet::RakString("servers/%s", serverId.C_String()), ""); -} -void Rackspace::UpdateServerNameOrPassword(MafiaNet::RakString serverId, MafiaNet::RakString newName, MafiaNet::RakString newPassword) -{ - if (newName.IsEmpty() && newPassword.IsEmpty()) - return; - MafiaNet::RakString xml( - "" - "" - "", - rebootType.C_String()); - - AddOperation(RO_REBOOT_SERVER, "POST", MafiaNet::RakString("servers/%s/action", serverId.C_String()), xml); -} -void Rackspace::RebuildServer(MafiaNet::RakString serverId, MafiaNet::RakString imageId) -{ - MafiaNet::RakString xml( - "" - "", - imageId.C_String()); - - AddOperation(RO_REBUILD_SERVER, "POST", MafiaNet::RakString("servers/%s/action", serverId.C_String()), xml); -} -void Rackspace::ResizeServer(MafiaNet::RakString serverId, MafiaNet::RakString flavorId) -{ - MafiaNet::RakString xml( - "" - "", - flavorId.C_String()); - - AddOperation(RO_RESIZE_SERVER, "POST", MafiaNet::RakString("servers/%s/action", serverId.C_String()), xml); -} -void Rackspace::ConfirmResizedServer(MafiaNet::RakString serverId) -{ - MafiaNet::RakString xml( - "" - ""); - AddOperation(RO_CONFIRM_RESIZED_SERVER, "POST", MafiaNet::RakString("servers/%s/action", serverId.C_String()), xml); -} -void Rackspace::RevertResizedServer(MafiaNet::RakString serverId) -{ - MafiaNet::RakString xml( - "" - ""); - AddOperation(RO_REVERT_RESIZED_SERVER, "POST", MafiaNet::RakString("servers/%s/action", serverId.C_String()), xml); -} -void Rackspace::ListFlavors(void) -{ - AddOperation(RO_LIST_FLAVORS, "GET", "flavors", ""); -} -void Rackspace::GetFlavorDetails(MafiaNet::RakString flavorId) -{ - AddOperation(RO_GET_FLAVOR_DETAILS, "GET", MafiaNet::RakString("flavors/%s", flavorId.C_String()), ""); -} -void Rackspace::ListImages(void) -{ - AddOperation(RO_LIST_IMAGES, "GET", "images", ""); -} -void Rackspace::CreateImage(MafiaNet::RakString serverId, MafiaNet::RakString imageName) -{ - MafiaNet::RakString xml( - "" - "", - imageName.C_String(),serverId.C_String()); - - AddOperation(RO_CREATE_IMAGE, "POST", "images", xml); -} -void Rackspace::GetImageDetails(MafiaNet::RakString imageId) -{ - AddOperation(RO_GET_IMAGE_DETAILS, "GET", MafiaNet::RakString("images/%s", imageId.C_String()), ""); -} -void Rackspace::DeleteImage(MafiaNet::RakString imageId) -{ - AddOperation(RO_DELETE_IMAGE, "DELETE", MafiaNet::RakString("images/%s", imageId.C_String()), ""); -} -void Rackspace::ListSharedIPGroups(void) -{ - AddOperation(RO_LIST_SHARED_IP_GROUPS, "GET", "shared_ip_groups", ""); -} -void Rackspace::ListSharedIPGroupsWithDetails(void) -{ - AddOperation(RO_LIST_SHARED_IP_GROUPS_WITH_DETAILS, "GET", "shared_ip_groups/detail", ""); -} -void Rackspace::CreateSharedIPGroup(MafiaNet::RakString name, MafiaNet::RakString optionalServerId) -{ - MafiaNet::RakString xml( - "" - "", name.C_String()); - if (optionalServerId.IsEmpty()==false) - xml+= MafiaNet::RakString("", optionalServerId.C_String()); - xml+=""; - - AddOperation(RO_CREATE_SHARED_IP_GROUP, "POST", "shared_ip_groups", xml); -} -void Rackspace::GetSharedIPGroupDetails(MafiaNet::RakString groupId) -{ - AddOperation(RO_GET_SHARED_IP_GROUP_DETAILS, "GET", MafiaNet::RakString("shared_ip_groups/%s", groupId.C_String()), ""); -} -void Rackspace::DeleteSharedIPGroup(MafiaNet::RakString groupId) -{ - AddOperation(RO_DELETE_SHARED_IP_GROUP, "DELETE", MafiaNet::RakString("shared_ip_groups/%s", groupId.C_String()), ""); -} -void Rackspace::OnClosedConnection(SystemAddress systemAddress) -{ - if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS) - return; - - unsigned int i, operationsIndex; - operationsIndex=0; - while (operationsIndex < operations.Size()) - { - if (operations[operationsIndex].isPendingAuthentication==false && operations[operationsIndex].connectionAddress==systemAddress) - { - RackspaceOperation ro = operations[operationsIndex]; - operations.RemoveAtIndex(operationsIndex); - - MafiaNet::RakString packetDataString = ro.incomingStream; - const char *packetData = packetDataString.C_String(); - - char resultCodeStr[32]; - int resultCodeInt; - - RackspaceEventType rackspaceEventType; - char *result; - result=strstr((char*) packetData, "HTTP/1.1 "); - if (result!=0) - { - result+=strlen("HTTP/1.1 "); - for (i=0; i < sizeof(resultCodeStr)-1 && result[i] && result[i]>='0' && result[i]<='9'; i++) - resultCodeStr[i]=result[i]; - resultCodeStr[i]=0; - resultCodeInt=atoi(resultCodeStr); - - switch (resultCodeInt) - { - case 200: rackspaceEventType=RET_Success_200; break; - case 201: rackspaceEventType=RET_Success_201; break; - case 202: rackspaceEventType=RET_Success_202; break; - case 203: rackspaceEventType=RET_Success_203; break; - case 204: rackspaceEventType=RET_Success_204; break; - case 500: rackspaceEventType=RET_Cloud_Servers_Fault_500; break; - case 503: rackspaceEventType=RET_Service_Unavailable_503; break; - case 401: rackspaceEventType=RET_Unauthorized_401; break; - case 400: rackspaceEventType=RET_Bad_Request_400; break; - case 413: rackspaceEventType=RET_Over_Limit_413; break; - case 415: rackspaceEventType=RET_Bad_Media_Type_415; break; - case 404: rackspaceEventType=RET_Item_Not_Found_404; break; - case 409: rackspaceEventType=RET_Build_In_Progress_409; break; - case 403: rackspaceEventType=RET_Resize_Not_Allowed_403; break; - default: rackspaceEventType=RET_Unknown_Failure; break; - } - } - else - { - rackspaceEventType=RET_Connection_Closed_Without_Reponse; - } - - switch (ro.type) - { - case RO_CONNECT_AND_AUTHENTICATE: - { - if (rackspaceEventType==RET_Success_204) - { - MafiaNet::RakString header; - ReadLine(packetData, "X-Server-Management-Url: ", serverManagementURL); - serverManagementURL.SplitURI(header, serverManagementDomain, serverManagementPath); - ReadLine(packetData, "X-Storage-Url: ", storageURL); - storageURL.SplitURI(header, storageDomain, storagePath); - ReadLine(packetData, "X-CDN-Management-Url: ", cdnManagementURL); - cdnManagementURL.SplitURI(header, cdnManagementDomain, cdnManagementPath); - ReadLine(packetData, "X-Auth-Token: ", authToken); - ReadLine(packetData, "X-Storage-Token: ", storageToken); - - operationsIndex=0; - while (operationsIndex < operations.Size()) - { - if (operations[operationsIndex].isPendingAuthentication==true) - { - operations[operationsIndex].isPendingAuthentication=false; - if (ExecuteOperation(operations[operationsIndex])==false) - { - operations.RemoveAtIndex(operationsIndex); - } - else - operationsIndex++; - } - else - operationsIndex++; - } - - // Restart in list - operationsIndex=0; - } - - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnAuthenticationResult(rackspaceEventType, (const char*) packetData); - - break; - } - case RO_LIST_SERVERS: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnListServersResult(rackspaceEventType, (const char*) packetData); - break; - } - case RO_LIST_SERVERS_WITH_DETAILS: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnListServersWithDetailsResult(rackspaceEventType, (const char*) packetData); - break; - } - case RO_CREATE_SERVER: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnCreateServerResult(rackspaceEventType, (const char*) packetData); - break; - } - - case RO_GET_SERVER_DETAILS: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnGetServerDetails(rackspaceEventType, (const char*) packetData); - break; - } - case RO_UPDATE_SERVER_NAME_OR_PASSWORD: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnUpdateServerNameOrPassword(rackspaceEventType, (const char*) packetData); - break; - } - case RO_DELETE_SERVER: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnDeleteServer(rackspaceEventType, (const char*) packetData); - break; - } - case RO_LIST_SERVER_ADDRESSES: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnListServerAddresses(rackspaceEventType, (const char*) packetData); - break; - } - case RO_SHARE_SERVER_ADDRESS: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnShareServerAddress(rackspaceEventType, (const char*) packetData); - break; - } - case RO_DELETE_SERVER_ADDRESS: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnDeleteServerAddress(rackspaceEventType, (const char*) packetData); - break; - } - case RO_REBOOT_SERVER: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnRebootServer(rackspaceEventType, (const char*) packetData); - break; - } - case RO_REBUILD_SERVER: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnRebuildServer(rackspaceEventType, (const char*) packetData); - break; - } - case RO_RESIZE_SERVER: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnResizeServer(rackspaceEventType, (const char*) packetData); - break; - } - case RO_CONFIRM_RESIZED_SERVER: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnConfirmResizedServer(rackspaceEventType, (const char*) packetData); - break; - } - case RO_REVERT_RESIZED_SERVER: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnRevertResizedServer(rackspaceEventType, (const char*) packetData); - break; - } - - - case RO_LIST_FLAVORS: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnListFlavorsResult(rackspaceEventType, (const char*) packetData); - break; - } - case RO_GET_FLAVOR_DETAILS: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnGetFlavorDetailsResult(rackspaceEventType, (const char*) packetData); - break; - } - case RO_LIST_IMAGES: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnListImagesResult(rackspaceEventType, (const char*) packetData); - break; - } - case RO_CREATE_IMAGE: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnCreateImageResult(rackspaceEventType, (const char*) packetData); - break; - } - case RO_GET_IMAGE_DETAILS: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnGetImageDetailsResult(rackspaceEventType, (const char*) packetData); - break; - } - case RO_DELETE_IMAGE: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnDeleteImageResult(rackspaceEventType, (const char*) packetData); - break; - } - case RO_LIST_SHARED_IP_GROUPS: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnListSharedIPGroups(rackspaceEventType, (const char*) packetData); - break; - } - case RO_LIST_SHARED_IP_GROUPS_WITH_DETAILS: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnListSharedIPGroupsWithDetails(rackspaceEventType, (const char*) packetData); - break; - } - case RO_CREATE_SHARED_IP_GROUP: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnCreateSharedIPGroup(rackspaceEventType, (const char*) packetData); - break; - } - case RO_GET_SHARED_IP_GROUP_DETAILS: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnGetSharedIPGroupDetails(rackspaceEventType, (const char*) packetData); - break; - } - case RO_DELETE_SHARED_IP_GROUP: - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnDeleteSharedIPGroup(rackspaceEventType, (const char*) packetData); - break; - } - default: - break; - - } - } - else - { - operationsIndex++; - } - } -} -void Rackspace::OnReceive(Packet *packet) -{ - unsigned int operationsIndex; - for (operationsIndex=0; operationsIndex < operations.Size(); operationsIndex++) - { - if (operations[operationsIndex].isPendingAuthentication==false && operations[operationsIndex].connectionAddress==packet->systemAddress) - { - operations[operationsIndex].incomingStream+=packet->data; - } - } -} -bool Rackspace::ExecuteOperation(RackspaceOperation &ro) -{ - if (ConnectToServerManagementDomain(ro)==false) - return false; - - MafiaNet::RakString command( - "%s %s/%s HTTP/1.1\n" - "Host: %s\n" - "Content-Type: application/xml\n" - "Content-Length: %i\n" - "Accept: application/xml\n" - "X-Auth-Token: %s\n", - ro.httpCommand.C_String(), serverManagementPath.C_String(), ro.operation.C_String(), serverManagementDomain.C_String(), - ro.xml.GetLength(), - authToken.C_String()); - - if (ro.xml.IsEmpty()==false) - { - command+="\n"; - command+=ro.xml; - command+="\n"; - } - - command+="\n"; - - //printf(command.C_String()); - - tcpInterface->Send(command.C_String(), (unsigned int) command.GetLength(), ro.connectionAddress, false); - return true; -} -void Rackspace::ReadLine(const char *data, const char *stringStart, MafiaNet::RakString &output) -{ - output.Clear(); - - char *result, *resultEnd; - - result=strstr((char*) data, stringStart); - if (result==0) - { - RakAssert(0); - return; - } - - result+=strlen(stringStart); - if (result==0) - { - RakAssert(0); - return; - } - - output=result; - resultEnd=result; - while (*resultEnd && (*resultEnd!='\r') && (*resultEnd!='\n') ) - resultEnd++; - output.Truncate((unsigned int) (resultEnd-result)); -} - - -bool Rackspace::ConnectToServerManagementDomain(RackspaceOperation &ro) -{ - unsigned int i; - - ro.connectionAddress=tcpInterface->Connect(serverManagementDomain.C_String(),443,true); - if (ro.connectionAddress==UNASSIGNED_SYSTEM_ADDRESS) - { - for (i=0; i < eventCallbacks.Size(); i++) - eventCallbacks[i]->OnConnectionAttemptFailure(ro.type, serverManagementURL); - return false; - } - -#if OPEN_SSL_CLIENT_SUPPORT==1 - tcpInterface->StartSSLClient(ro.connectionAddress); -#endif - - return true; -} -bool Rackspace::HasOperationOfType(RackspaceOperationType t) -{ - unsigned int i; - for (i=0; i < operations.Size(); i++) - { - if (operations[i].type==t) - return true; - } - return false; -} -unsigned int Rackspace::GetOperationOfTypeIndex(RackspaceOperationType t) -{ - unsigned int i; - for (i=0; i < operations.Size(); i++) - { - if (operations[i].type==t) - return i; - } - return (unsigned int) -1; -} - -#endif diff --git a/vendors/mafianet/Source/src/RakMemoryOverride.cpp b/vendors/mafianet/Source/src/RakMemoryOverride.cpp deleted file mode 100644 index 0180a12ba..000000000 --- a/vendors/mafianet/Source/src/RakMemoryOverride.cpp +++ /dev/null @@ -1,311 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/memoryoverride.h" -#include "mafianet/assert.h" -#include - -#ifdef _RAKNET_SUPPORT_DL_MALLOC -#include "rdlmalloc.h" -#endif - - - - - - - -using namespace MafiaNet; - -#if _USE_RAK_MEMORY_OVERRIDE==1 - #if defined(malloc) - #pragma push_macro("malloc") - #undef malloc - #define RMO_MALLOC_UNDEF - #endif - - #if defined(realloc) - #pragma push_macro("realloc") - #undef realloc - #define RMO_REALLOC_UNDEF - #endif - - #if defined(free) - #pragma push_macro("free") - #undef free - #define RMO_FREE_UNDEF - #endif -#endif - -void DefaultOutOfMemoryHandler(const char *file, const long line) -{ - (void) file; - (void) line; - RakAssert(0); -} - -void * (*rakMalloc) (size_t size) = MafiaNet::_RakMalloc; -void* (*rakRealloc) (void *p, size_t size) = MafiaNet::_RakRealloc; -void (*rakFree) (void *p) = MafiaNet::_RakFree; -void* (*rakMalloc_Ex) (size_t size, const char *file, unsigned int line) = MafiaNet::_RakMalloc_Ex; -void* (*rakRealloc_Ex) (void *p, size_t size, const char *file, unsigned int line) = MafiaNet::_RakRealloc_Ex; -void (*rakFree_Ex) (void *p, const char *file, unsigned int line) = MafiaNet::_RakFree_Ex; -void (*notifyOutOfMemory) (const char *file, const long line)=DefaultOutOfMemoryHandler; -void * (*dlMallocMMap) (size_t size) = MafiaNet::_DLMallocMMap; -void * (*dlMallocDirectMMap) (size_t size) = MafiaNet::_DLMallocDirectMMap; -int (*dlMallocMUnmap) (void* ptr, size_t size) = MafiaNet::_DLMallocMUnmap; - -void SetMalloc( void* (*userFunction)(size_t size) ) -{ - rakMalloc=userFunction; -} -void SetRealloc( void* (*userFunction)(void *p, size_t size) ) -{ - rakRealloc=userFunction; -} -void SetFree( void (*userFunction)(void *p) ) -{ - rakFree=userFunction; -} -void SetMalloc_Ex( void* (*userFunction)(size_t size, const char *file, unsigned int line) ) -{ - rakMalloc_Ex=userFunction; -} -void SetRealloc_Ex( void* (*userFunction)(void *p, size_t size, const char *file, unsigned int line) ) -{ - rakRealloc_Ex=userFunction; -} -void SetFree_Ex( void (*userFunction)(void *p, const char *file, unsigned int line) ) -{ - rakFree_Ex=userFunction; -} -void SetNotifyOutOfMemory( void (*userFunction)(const char *file, const long line) ) -{ - notifyOutOfMemory=userFunction; -} -void SetDLMallocMMap( void* (*userFunction)(size_t size) ) -{ - dlMallocMMap=userFunction; -} -void SetDLMallocDirectMMap( void* (*userFunction)(size_t size) ) -{ - dlMallocDirectMMap=userFunction; -} -void SetDLMallocMUnmap( int (*userFunction)(void* ptr, size_t size) ) -{ - dlMallocMUnmap=userFunction; -} -void * (*GetMalloc()) (size_t size) -{ - return rakMalloc; -} -void * (*GetRealloc()) (void *p, size_t size) -{ - return rakRealloc; -} -void (*GetFree()) (void *p) -{ - return rakFree; -} -void * (*GetMalloc_Ex()) (size_t size, const char *file, unsigned int line) -{ - return rakMalloc_Ex; -} -void * (*GetRealloc_Ex()) (void *p, size_t size, const char *file, unsigned int line) -{ - return rakRealloc_Ex; -} -void (*GetFree_Ex()) (void *p, const char *file, unsigned int line) -{ - return rakFree_Ex; -} -void *(*GetDLMallocMMap())(size_t size) -{ - return dlMallocMMap; -} -void *(*GetDLMallocDirectMMap())(size_t size) -{ - return dlMallocDirectMMap; -} -int (*GetDLMallocMUnmap())(void* ptr, size_t size) -{ - return dlMallocMUnmap; -} -void* MafiaNet::_RakMalloc (size_t size) -{ - return malloc(size); -} - -void* MafiaNet::_RakRealloc (void *p, size_t size) -{ - return realloc(p,size); -} - -void MafiaNet::_RakFree (void *p) -{ - free(p); -} - -void* MafiaNet::_RakMalloc_Ex (size_t size, const char *file, unsigned int line) -{ - (void) file; - (void) line; - - return malloc(size); -} - -void* MafiaNet::_RakRealloc_Ex (void *p, size_t size, const char *file, unsigned int line) -{ - (void) file; - (void) line; - - return realloc(p,size); -} - -void MafiaNet::_RakFree_Ex (void *p, const char *file, unsigned int line) -{ - (void) file; - (void) line; - - free(p); -} -#ifdef _RAKNET_SUPPORT_DL_MALLOC -void * MafiaNet::_DLMallocMMap (size_t size) -{ - return RAK_MMAP_DEFAULT(size); -} -void * MafiaNet::_DLMallocDirectMMap (size_t size) -{ - return RAK_DIRECT_MMAP_DEFAULT(size); -} -int MafiaNet::_DLMallocMUnmap (void *p, size_t size) -{ - return RAK_MUNMAP_DEFAULT(p,size); -} - -static mspace rakNetFixedHeapMSpace=0; - -void* _DLMalloc(size_t size) -{ - return rak_mspace_malloc(rakNetFixedHeapMSpace,size); -} - -void* _DLRealloc(void *p, size_t size) -{ - return rak_mspace_realloc(rakNetFixedHeapMSpace,p,size); -} - -void _DLFree(void *p) -{ - if (p) - rak_mspace_free(rakNetFixedHeapMSpace,p); -} -void* _DLMalloc_Ex (size_t size, const char *file, unsigned int line) -{ - (void) file; - (void) line; - - return rak_mspace_malloc(rakNetFixedHeapMSpace,size); -} - -void* _DLRealloc_Ex (void *p, size_t size, const char *file, unsigned int line) -{ - (void) file; - (void) line; - - return rak_mspace_realloc(rakNetFixedHeapMSpace,p,size); -} - -void _DLFree_Ex (void *p, const char *file, unsigned int line) -{ - (void) file; - (void) line; - - if (p) - rak_mspace_free(rakNetFixedHeapMSpace,p); -} - -void UseRaknetFixedHeap(size_t initialCapacity, - void * (*yourMMapFunction) (size_t size), - void * (*yourDirectMMapFunction) (size_t size), - int (*yourMUnmapFunction) (void *p, size_t size)) -{ - SetDLMallocMMap(yourMMapFunction); - SetDLMallocDirectMMap(yourDirectMMapFunction); - SetDLMallocMUnmap(yourMUnmapFunction); - SetMalloc(_DLMalloc); - SetRealloc(_DLRealloc); - SetFree(_DLFree); - SetMalloc_Ex(_DLMalloc_Ex); - SetRealloc_Ex(_DLRealloc_Ex); - SetFree_Ex(_DLFree_Ex); - - rakNetFixedHeapMSpace=rak_create_mspace(initialCapacity, 0); -} -void FreeRakNetFixedHeap(void) -{ - if (rakNetFixedHeapMSpace) - { - rak_destroy_mspace(rakNetFixedHeapMSpace); - rakNetFixedHeapMSpace=0; - } - - SetMalloc(_RakMalloc); - SetRealloc(_RakRealloc); - SetFree(_RakFree); - SetMalloc_Ex(_RakMalloc_Ex); - SetRealloc_Ex(_RakRealloc_Ex); - SetFree_Ex(_RakFree_Ex); -} -#else -void * MafiaNet::_DLMallocMMap (size_t size) {(void) size; return 0;} -void * MafiaNet::_DLMallocDirectMMap (size_t size) {(void) size; return 0;} -int MafiaNet::_DLMallocMUnmap (void *p, size_t size) {(void) size; (void) p; return 0;} -void* _DLMalloc(size_t size) {(void) size; return 0;} -void* _DLRealloc(void *p, size_t size) {(void) p; (void) size; return 0;} -void _DLFree(void *p) {(void) p;} -void* _DLMalloc_Ex (size_t size, const char *file, unsigned int line) {(void) size; (void) file; (void) line; return 0;} -void* _DLRealloc_Ex (void *p, size_t size, const char *file, unsigned int line) {(void) p; (void) size; (void) file; (void) line; return 0;} -void _DLFree_Ex (void *p, const char *file, unsigned int line) {(void) p; (void) file; (void) line;} - -void UseRaknetFixedHeap(size_t initialCapacity, - void * (*yourMMapFunction) (size_t size), - void * (*yourDirectMMapFunction) (size_t size), - int (*yourMUnmapFunction) (void *p, size_t size)) -{ - (void) initialCapacity; - (void) yourMMapFunction; - (void) yourDirectMMapFunction; - (void) yourMUnmapFunction; -} -void FreeRakNetFixedHeap(void) {} -#endif - -#if _USE_RAK_MEMORY_OVERRIDE==1 - #if defined(RMO_MALLOC_UNDEF) - #pragma pop_macro("malloc") - #undef RMO_MALLOC_UNDEF - #endif - - #if defined(RMO_REALLOC_UNDEF) - #pragma pop_macro("realloc") - #undef RMO_REALLOC_UNDEF - #endif - - #if defined(RMO_FREE_UNDEF) - #pragma pop_macro("free") - #undef RMO_FREE_UNDEF - #endif -#endif diff --git a/vendors/mafianet/Source/src/RakNetCommandParser.cpp b/vendors/mafianet/Source/src/RakNetCommandParser.cpp deleted file mode 100644 index eeefae661..000000000 --- a/vendors/mafianet/Source/src/RakNetCommandParser.cpp +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_RakNetCommandParser==1 - -#include "mafianet/commandparser.h" -#include "mafianet/TransportInterface.h" -#include "mafianet/peerinterface.h" -#include "mafianet/BitStream.h" -#include "mafianet/assert.h" -#include -#include -#include - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(RakNetCommandParser,RakNetCommandParser); - -RakNetCommandParser::RakNetCommandParser() -{ - RegisterCommand(4, "Startup","( unsigned int maxConnections, unsigned short localPort, const char *forceHostAddress );"); - RegisterCommand(0,"InitializeSecurity","();"); - RegisterCommand(0,"DisableSecurity","( void );"); - RegisterCommand(1,"AddToSecurityExceptionList","( const char *ip );"); - RegisterCommand(1,"RemoveFromSecurityExceptionList","( const char *ip );"); - RegisterCommand(1,"IsInSecurityExceptionList","( const char *ip );"); - RegisterCommand(1,"SetMaximumIncomingConnections","( unsigned short numberAllowed );"); - RegisterCommand(0,"GetMaximumIncomingConnections","( void ) const;"); - RegisterCommand(4,"Connect","( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength );"); - RegisterCommand(2,"Disconnect","( unsigned int blockDuration, unsigned char orderingChannel=0 );"); - RegisterCommand(0,"IsActive","( void ) const;"); - RegisterCommand(0,"GetConnectionList","() const;"); - RegisterCommand(3,"CloseConnection","( const SystemAddress target, bool sendDisconnectionNotification, unsigned char orderingChannel=0 );"); - RegisterCommand(2,"IsConnected","( );"); - RegisterCommand(1,"GetIndexFromSystemAddress","( const SystemAddress systemAddress );"); - RegisterCommand(1,"GetSystemAddressFromIndex","( unsigned int index );"); - RegisterCommand(2,"AddToBanList","( const char *IP, MafiaNet::TimeMS milliseconds=0 );"); - RegisterCommand(1,"RemoveFromBanList","( const char *IP );"); - RegisterCommand(0,"ClearBanList","( void );"); - RegisterCommand(1,"IsBanned","( const char *IP );"); - RegisterCommand(1,"Ping1","( const SystemAddress target );"); - RegisterCommand(3,"Ping2","( const char* host, unsigned short remotePort, bool onlyReplyOnAcceptingConnections );"); - RegisterCommand(1,"GetAveragePing","( const SystemAddress systemAddress );"); - RegisterCommand(1,"GetLastPing","( const SystemAddress systemAddress ) const;"); - RegisterCommand(1,"GetLowestPing","( const SystemAddress systemAddress ) const;"); - RegisterCommand(1,"SetOccasionalPing","( bool doPing );"); - RegisterCommand(2,"SetOfflinePingResponse","( const char *data, const unsigned int length );"); - RegisterCommand(0,"GetInternalID","( void ) const;"); - RegisterCommand(1,"GetExternalID","( const SystemAddress target ) const;"); - RegisterCommand(2,"SetTimeoutTime","( MafiaNet::TimeMS timeMS, const SystemAddress target );"); -// RegisterCommand(1,"SetMTUSize","( int size );"); - RegisterCommand(0,"GetMTUSize","( void ) const;"); - RegisterCommand(0,"GetNumberOfAddresses","( void );"); - RegisterCommand(1,"GetLocalIP","( unsigned int index );"); - RegisterCommand(1,"AllowConnectionResponseIPMigration","( bool allow );"); - RegisterCommand(4,"AdvertiseSystem","( const char *host, unsigned short remotePort, const char *data, int dataLength );"); - RegisterCommand(2,"SetIncomingPassword","( const char* passwordData, int passwordDataLength );"); - RegisterCommand(0,"GetIncomingPassword","( void );"); - RegisterCommand(0,"IsNetworkSimulatorActive","( void );"); -} -RakNetCommandParser::~RakNetCommandParser() -{ -} -void RakNetCommandParser::SetRakPeerInterface(MafiaNet::RakPeerInterface *rakPeer) -{ - peer=rakPeer; -} -bool RakNetCommandParser::OnCommand(const char *command, unsigned numParameters, char **parameterList, TransportInterface *transport, const SystemAddress &systemAddress, const char *originalString) -{ - (void) originalString; - (void) numParameters; - - if (peer==0) - return false; - - if (strcmp(command, "Startup")==0) - { - MafiaNet::SocketDescriptor socketDescriptor((unsigned short)atoi(parameterList[1]), parameterList[2]); - ReturnResult(peer->Startup((unsigned short)atoi(parameterList[0]), &socketDescriptor, 1), command, transport, systemAddress); - } - else if (strcmp(command, "InitializeSecurity")==0) - { - ReturnResult(peer->InitializeSecurity(parameterList[0],parameterList[1]), command, transport, systemAddress); - } - else if (strcmp(command, "DisableSecurity")==0) - { - peer->DisableSecurity(); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "AddToSecurityExceptionList")==0) - { - peer->AddToSecurityExceptionList(parameterList[1]); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "RemoveFromSecurityExceptionList")==0) - { - peer->RemoveFromSecurityExceptionList(parameterList[1]); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "IsInSecurityExceptionList")==0) - { - ReturnResult(peer->IsInSecurityExceptionList(parameterList[1]),command, transport, systemAddress); - } - else if (strcmp(command, "SetMaximumIncomingConnections")==0) - { - peer->SetMaximumIncomingConnections((unsigned short)atoi(parameterList[0])); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "GetMaximumIncomingConnections")==0) - { - ReturnResult((int) peer->GetMaximumIncomingConnections(), command, transport, systemAddress); - } - else if (strcmp(command, "Connect")==0) - { - ReturnResult(peer->Connect(parameterList[0], (unsigned short)atoi(parameterList[1]),parameterList[2],atoi(parameterList[3]))== MafiaNet::CONNECTION_ATTEMPT_STARTED, command, transport, systemAddress); - } - else if (strcmp(command, "Disconnect")==0) - { - peer->Shutdown(atoi(parameterList[0]), (unsigned char)atoi(parameterList[1])); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "IsActive")==0) - { - ReturnResult(peer->IsActive(), command, transport, systemAddress); - } - else if (strcmp(command, "GetConnectionList")==0) - { - SystemAddress remoteSystems[32]; - unsigned short count=32; - unsigned i; - if (peer->GetConnectionList(remoteSystems, &count)) - { - if (count==0) - { - transport->Send(systemAddress, "GetConnectionList() returned no systems connected.\r\n"); - } - else - { - transport->Send(systemAddress, "GetConnectionList() returned:\r\n"); - for (i=0; i < count; i++) - { - char str1[64]; - remoteSystems[i].ToString(true, str1, static_cast(64)); - transport->Send(systemAddress, "%i %s\r\n", i, str1); - } - } - } - else - transport->Send(systemAddress, "GetConnectionList() returned false.\r\n"); - } - else if (strcmp(command, "CloseConnection")==0) - { - peer->CloseConnection(SystemAddress(parameterList[0]), atoi(parameterList[1])!=0,(unsigned char)atoi(parameterList[2])); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "GetConnectionState")==0) - { - ReturnResult((int) peer->GetConnectionState(SystemAddress(parameterList[0])), command, transport, systemAddress); - } - else if (strcmp(command, "GetIndexFromSystemAddress")==0) - { - ReturnResult(peer->GetIndexFromSystemAddress(SystemAddress(parameterList[0])), command, transport, systemAddress); - } - else if (strcmp(command, "GetSystemAddressFromIndex")==0) - { - ReturnResult(peer->GetSystemAddressFromIndex(atoi(parameterList[0])), command, transport, systemAddress); - } - else if (strcmp(command, "AddToBanList")==0) - { - peer->AddToBanList(parameterList[0], atoi(parameterList[1])); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "RemoveFromBanList")==0) - { - peer->RemoveFromBanList(parameterList[0]); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "ClearBanList")==0) - { - peer->ClearBanList(); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "IsBanned")==0) - { - ReturnResult(peer->IsBanned(parameterList[0]), command, transport, systemAddress); - } - else if (strcmp(command, "Ping1")==0) - { - peer->Ping(SystemAddress(parameterList[0])); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "Ping2")==0) - { - peer->Ping(parameterList[0], (unsigned short) atoi(parameterList[1]), atoi(parameterList[2])!=0); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "GetAveragePing")==0) - { - ReturnResult(peer->GetAveragePing(SystemAddress(parameterList[0])), command, transport, systemAddress); - } - else if (strcmp(command, "GetLastPing")==0) - { - ReturnResult(peer->GetLastPing(SystemAddress(parameterList[0])), command, transport, systemAddress); - } - else if (strcmp(command, "GetLowestPing")==0) - { - ReturnResult(peer->GetLowestPing(SystemAddress(parameterList[0])), command, transport, systemAddress); - } - else if (strcmp(command, "SetOccasionalPing")==0) - { - peer->SetOccasionalPing(atoi(parameterList[0])!=0); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "SetOfflinePingResponse")==0) - { - peer->SetOfflinePingResponse(parameterList[0], atoi(parameterList[1])); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "GetInternalID")==0) - { - ReturnResult(peer->GetInternalID(), command, transport, systemAddress); - } - else if (strcmp(command, "GetExternalID")==0) - { - ReturnResult(peer->GetExternalID(SystemAddress(parameterList[0])), command, transport, systemAddress); - } - else if (strcmp(command, "SetTimeoutTime")==0) - { - peer->SetTimeoutTime(atoi(parameterList[0]), SystemAddress(parameterList[1])); - ReturnResult(command, transport, systemAddress); - } - /* - else if (strcmp(command, "SetMTUSize")==0) - { - ReturnResult(peer->SetMTUSize(atoi(parameterList[0]), UNASSIGNED_SYSTEM_ADDRESS), command, transport, systemAddress); - } - */ - else if (strcmp(command, "GetMTUSize")==0) - { - ReturnResult(peer->GetMTUSize(UNASSIGNED_SYSTEM_ADDRESS), command, transport, systemAddress); - } - else if (strcmp(command, "GetNumberOfAddresses")==0) - { - ReturnResult((int)peer->GetNumberOfAddresses(), command, transport, systemAddress); - } - else if (strcmp(command, "GetLocalIP")==0) - { - ReturnResult((char*) peer->GetLocalIP(atoi(parameterList[0])), command, transport, systemAddress); - } - else if (strcmp(command, "AllowConnectionResponseIPMigration")==0) - { - peer->AllowConnectionResponseIPMigration(atoi(parameterList[0])!=0); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "AdvertiseSystem")==0) - { - peer->AdvertiseSystem(parameterList[0], (unsigned short) atoi(parameterList[1]),parameterList[2],atoi(parameterList[3])); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "SetIncomingPassword")==0) - { - peer->SetIncomingPassword(parameterList[0], atoi(parameterList[1])); - ReturnResult(command, transport, systemAddress); - } - else if (strcmp(command, "GetIncomingPassword")==0) - { - char password[256]; - int passwordLength; - peer->GetIncomingPassword(password, &passwordLength); - if (passwordLength) - ReturnResult((char*)password, command, transport, systemAddress); - else - ReturnResult(0, command, transport, systemAddress); - } - - return true; -} -const char *RakNetCommandParser::GetName(void) const -{ - return "RakNet"; -} -void RakNetCommandParser::SendHelp(TransportInterface *transport, const SystemAddress &systemAddress) -{ - if (peer) - { - transport->Send(systemAddress, "The RakNet parser provides mirror functions to RakPeer\r\n"); - transport->Send(systemAddress, "SystemAddresss take two parameters: send .\r\n"); - transport->Send(systemAddress, "For bool, send 1 or 0.\r\n"); - } - else - { - transport->Send(systemAddress, "Parser not active. Call SetRakPeerInterface.\r\n"); - } -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/RakNetSocket.cpp b/vendors/mafianet/Source/src/RakNetSocket.cpp deleted file mode 100644 index 378b6e612..000000000 --- a/vendors/mafianet/Source/src/RakNetSocket.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/* -#include "mafianet/socket.h" -#include "mafianet/memoryoverride.h" - -using namespace MafiaNet; - -#if defined(__native_client__) -using namespace pp; -#endif - -RakNetSocket::RakNetSocket() { - s = 0; - remotePortRakNetWasStartedOn_PS3_PSP2 = 0; - userConnectionSocketIndex = (unsigned int) -1; - socketFamily = 0; - blockingSocket = 0; - extraSocketOptions = 0; - chromeInstance = 0; - -#if defined (_WIN32) && defined(USE_WAIT_FOR_MULTIPLE_EVENTS) - recvEvent=INVALID_HANDLE_VALUE; -#endif - - #ifdef __native_client__ - s = 0; - sendInProgress = false; - nextSendSize = 0; - #endif -} -RakNetSocket::~RakNetSocket() -{ - #ifdef __native_client__ - if(s != 0) - ((PPB_UDPSocket_Private_0_4*) pp::Module::Get()->GetBrowserInterface(PPB_UDPSOCKET_PRIVATE_INTERFACE_0_4))->Close(s); - #else - if ((__UDPSOCKET__)s != 0) - closesocket__(s); - #endif - - -#if defined (_WIN32) && defined(USE_WAIT_FOR_MULTIPLE_EVENTS) - if (recvEvent!=INVALID_HANDLE_VALUE) - { - CloseHandle( recvEvent ); - recvEvent = INVALID_HANDLE_VALUE; - } -#endif -} -// -// void RakNetSocket::Accept( -// struct sockaddr *addr, -// int *addrlen) -// { -// accept__(s, addr, addrlen); -// } - -// -// void RakNetSocket::Close( void ) -// { -// closesocket__(s); -// } - -RakNetSocket* RakNetSocket::Create -#ifdef __native_client__ - (_PP_Instance_ _chromeInstance) -#else - (int af, - int type, - int protocol) -#endif -{ - __UDPSOCKET__ sock; - - #ifndef __native_client__ - RakAssert(type==SOCK_DGRAM); - #endif - - #ifdef __native_client__ - sock = ((PPB_UDPSocket_Private_0_4*) Module::Get()->GetBrowserInterface(PPB_UDPSOCKET_PRIVATE_INTERFACE_0_4))->Create(_chromeInstance); - #elif defined(SN_TARGET_PSP2) - sock = sceNetSocket( "RakNetSocket::Create", SCE_NET_AF_INET, SCE_NET_SOCK_DGRAM_P2P, 0 ); - #elif defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3) || defined(_PS4) - sock = socket__( AF_INET, SOCK_DGRAM_P2P, 0 ); - #else - sock = socket__(af, type, protocol); - #endif - - if (sock<0) - return 0; - RakNetSocket *rns = MafiaNet::OP_NEW(_FILE_AND_LINE_); - rns->s = sock; - #ifdef __native_client__ - rns->chromeInstance = _chromeInstance; - #endif - return rns; -} - -int RakNetSocket::Bind( - const struct sockaddr *addr, - int namelen) -{ - return bind__(s,addr,namelen); -} - -int RakNetSocket::IOCTLSocket( - long cmd, - unsigned long *argp) -{ - #if defined(_WIN32) - return ioctlsocket__(s,cmd,argp); - #else - return 0; - #endif -} - -int RakNetSocket::Listen ( - int backlog) -{ - return listen__(s,backlog); -} - -int RakNetSocket::SetSockOpt( - int level, - int optname, - const char * optval, - int optlen) -{ - return setsockopt__(s,level,optname,optval,optlen); -} - -int RakNetSocket::Shutdown( - int how) -{ - #ifndef SN_TARGET_PSP2 - return shutdown__(s,how); - #else - return 0; - #endif -} -*/ diff --git a/vendors/mafianet/Source/src/RakNetSocket2.cpp b/vendors/mafianet/Source/src/RakNetSocket2.cpp deleted file mode 100644 index 6575a8d69..000000000 --- a/vendors/mafianet/Source/src/RakNetSocket2.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/socket2.h" -#include "mafianet/memoryoverride.h" -#include "mafianet/assert.h" -#include "mafianet/sleep.h" -#include "mafianet/SocketDefines.h" -#include "mafianet/GetTime.h" -#include -#include // memcpy - -using namespace MafiaNet; - -#ifdef _WIN32 -#else -#include -#include -#include -#include // error numbers -#if !defined(ANDROID) -#include -#endif -#include -#include -#include -#include -#include -#endif - -#define RAKNET_SOCKET_2_INLINE_FUNCTIONS -#include "RakNetSocket2_Windows_Linux.cpp" -#include "RakNetSocket2_Windows_Linux_360.cpp" -#include "RakNetSocket2_Berkley.cpp" -#undef RAKNET_SOCKET_2_INLINE_FUNCTIONS - -#ifndef INVALID_SOCKET -#define INVALID_SOCKET -1 -#endif - -void RakNetSocket2Allocator::DeallocRNS2(RakNetSocket2 *s) { MafiaNet::OP_DELETE(s,_FILE_AND_LINE_);} -RakNetSocket2::RakNetSocket2() {eventHandler=0;} -RakNetSocket2::~RakNetSocket2() {} -void RakNetSocket2::SetRecvEventHandler(RNS2EventHandler *_eventHandler) {eventHandler=_eventHandler;} -RNS2Type RakNetSocket2::GetSocketType(void) const {return socketType;} -void RakNetSocket2::SetSocketType(RNS2Type t) {socketType=t;} -bool RakNetSocket2::IsBerkleySocket(void) const { - return true; // All supported platforms use Berkeley sockets -} -SystemAddress RakNetSocket2::GetBoundAddress(void) const {return boundAddress;} - -RakNetSocket2* RakNetSocket2Allocator::AllocRNS2(void) -{ - RakNetSocket2* s2; -#if defined(_WIN32) - s2 = MafiaNet::OP_NEW(_FILE_AND_LINE_); - s2->SetSocketType(RNS2T_WINDOWS); -#else - s2 = MafiaNet::OP_NEW(_FILE_AND_LINE_); - s2->SetSocketType(RNS2T_LINUX); -#endif - return s2; -} -void RakNetSocket2::GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) -{ -#if defined(_WIN32) - RNS2_Windows::GetMyIP( addresses ); -#else - RNS2_Linux::GetMyIP( addresses ); -#endif -} - -unsigned int RakNetSocket2::GetUserConnectionSocketIndex(void) const {return userConnectionSocketIndex;} -void RakNetSocket2::SetUserConnectionSocketIndex(unsigned int i) {userConnectionSocketIndex=i;} -RNS2EventHandler * RakNetSocket2::GetEventHandler(void) const {return eventHandler;} - -void RakNetSocket2::DomainNameToIP( const char *domainName, char ip[65] ) { - return DomainNameToIP_Berkley( domainName, ip ); -} - -bool IRNS2_Berkley::IsPortInUse(unsigned short port, const char *hostAddress, unsigned short addressFamily, int type ) { - RNS2_BerkleyBindParameters bbp; - bbp.remotePortRakNetWasStartedOn_PS3_PS4_PSP2=0; - bbp.port=port; bbp.hostAddress=(char*) hostAddress; bbp.addressFamily=addressFamily; - bbp.type=type; bbp.protocol=0; bbp.nonBlockingSocket=false; - bbp.setBroadcast=false; bbp.doNotFragment=false; bbp.protocol=0; - bbp.setIPHdrIncl=false; - SystemAddress boundAddress; - RNS2_Berkley *rns2 = (RNS2_Berkley*) RakNetSocket2Allocator::AllocRNS2(); - RNS2BindResult bindResult = rns2->Bind(&bbp, _FILE_AND_LINE_); - RakNetSocket2Allocator::DeallocRNS2(rns2); - return bindResult==BR_FAILED_TO_BIND_SOCKET; -} - -#if defined(__APPLE__) -void SocketReadCallback(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) -// This C routine is called by CFSocket when there's data waiting on our -// UDP socket. It just redirects the call to Objective-C code. -{ } -#endif - -RNS2BindResult RNS2_Berkley::BindShared( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ) { - RNS2BindResult br; -#if RAKNET_SUPPORT_IPV6==1 - br=BindSharedIPV4And6(bindParameters, file, line); -#else - br=BindSharedIPV4(bindParameters, file, line); -#endif - - if (br!=BR_SUCCESS) - return br; - - unsigned long zero=0; - RNS2_SendParameters bsp; - bsp.data=(char*) &zero; - bsp.length=4; - bsp.systemAddress=boundAddress; - bsp.ttl=0; - RNS2SendResult sr = Send(&bsp, _FILE_AND_LINE_); - if (sr<0) - return BR_FAILED_SEND_TEST; - - memcpy(&binding, bindParameters, sizeof(RNS2_BerkleyBindParameters)); - - /* -#if defined(__APPLE__) - const CFSocketContext context = { 0, this, nullptr, nullptr, nullptr }; - _cfSocket = CFSocketCreateWithNative(nullptr, rns2Socket, kCFSocketReadCallBack, SocketReadCallback, &context); -#endif - */ - - return br; -} - -RAK_THREAD_DECLARATION(RNS2_Berkley::RecvFromLoop) -{ - RNS2_Berkley *b = ( RNS2_Berkley * ) arguments; - - b->RecvFromLoopInt(); - return 0; -} -unsigned RNS2_Berkley::RecvFromLoopInt(void) -{ - isRecvFromLoopThreadActive.Increment(); - - while ( endThreads == false ) - { - RNS2RecvStruct *recvFromStruct; - recvFromStruct=binding.eventHandler->AllocRNS2RecvStruct(_FILE_AND_LINE_); - if (recvFromStruct != nullptr) - { - recvFromStruct->socket=this; - RecvFromBlocking(recvFromStruct); - - if (recvFromStruct->bytesRead>0) - { - RakAssert(recvFromStruct->systemAddress.GetPort()); - binding.eventHandler->OnRNS2Recv(recvFromStruct); - } - else - { - RakSleep(0); - binding.eventHandler->DeallocRNS2RecvStruct(recvFromStruct, _FILE_AND_LINE_); - } - } - } - isRecvFromLoopThreadActive.Decrement(); - - return 0; -} -RNS2_Berkley::RNS2_Berkley() -{ - rns2Socket=(RNS2Socket)INVALID_SOCKET; -} -RNS2_Berkley::~RNS2_Berkley() -{ - if (rns2Socket!=INVALID_SOCKET) - { - /* -#if defined(__APPLE__) - CFSocketInvalidate(_cfSocket); -#endif - */ - - closesocket__(rns2Socket); - } - -} -int RNS2_Berkley::CreateRecvPollingThread(int threadPriority) -{ - endThreads=false; - - int errorCode = MafiaNet::RakThread::Create(RecvFromLoop, this, threadPriority); - return errorCode; -} -void RNS2_Berkley::SignalStopRecvPollingThread(void) -{ - endThreads=true; -} -void RNS2_Berkley::BlockOnStopRecvPollingThread(void) -{ - endThreads=true; - - // Get recvfrom to unblock - RNS2_SendParameters bsp; - unsigned long zero=0; - bsp.data=(char*) &zero; - bsp.length=4; - bsp.systemAddress=boundAddress; - bsp.ttl=0; - Send(&bsp, _FILE_AND_LINE_); - - MafiaNet::TimeMS timeout = MafiaNet::GetTimeMS()+1000; - while ( isRecvFromLoopThreadActive.GetValue()>0 && MafiaNet::GetTimeMS()RakNetSendTo(sendParameters->data, sendParameters->length,sendParameters->systemAddress); - if (len>=0) - return len; - } - return Send_Windows_Linux_360NoVDP(rns2Socket,sendParameters, file, line); -} -void RNS2_Windows::GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) {return GetMyIP_Windows_Linux(addresses);} -void RNS2_Windows::SetSocketLayerOverride(SocketLayerOverride *_slo) {slo = _slo;} -SocketLayerOverride* RNS2_Windows::GetSocketLayerOverride(void) {return slo;} -#else -RNS2BindResult RNS2_Linux::Bind( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ) {return BindShared(bindParameters, file, line);} -RNS2SendResult RNS2_Linux::Send( RNS2_SendParameters *sendParameters, const char *file, unsigned int line ) {return Send_Windows_Linux_360NoVDP(rns2Socket,sendParameters, file, line);} -void RNS2_Linux::GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) {return GetMyIP_Windows_Linux(addresses);} -#endif // Linux diff --git a/vendors/mafianet/Source/src/RakNetSocket2_Berkley.cpp b/vendors/mafianet/Source/src/RakNetSocket2_Berkley.cpp deleted file mode 100644 index eeddc302b..000000000 --- a/vendors/mafianet/Source/src/RakNetSocket2_Berkley.cpp +++ /dev/null @@ -1,533 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/EmptyHeader.h" - -#ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS - -#ifndef RAKNETSOCKET2_BERKLEY_CPP -#define RAKNETSOCKET2_BERKLEY_CPP - -// Berkeley socket implementation for Windows and Linux - -#ifdef _WIN32 -#include // used for _tprintf() (via RAKNET_DEBUG_TPRINTF) -#else -#include "mafianet/LinuxStrings.h" // used for _stricmp() -#include // used for getaddrinfo() -#include // used for getaddrinfo() -#include // used for getaddrinfo() -#endif - -#include "mafianet/Itoa.h" -#include "mafianet/WSAStartupSingleton.h" - -// Domain name resolution functions -void DomainNameToIP_Berkley_IPV4And6( const char *domainName, char ip[65] ) -{ -#if RAKNET_SUPPORT_IPV6==1 - struct addrinfo hints, *res, *p; - int status; - memset(&hints, 0, sizeof hints); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_DGRAM; - - if ((status = getaddrinfo(domainName, nullptr, &hints, &res)) != 0) { - ip[0] = '\0'; - return; - } - - p=res; - void *addr; - if (p->ai_family == AF_INET) - { - struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr; - addr = &(ipv4->sin_addr); - inet_ntop(AF_INET, &ipv4->sin_addr, ip, 65); - } - else - { - struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr; - addr = &(ipv6->sin6_addr); - getnameinfo((struct sockaddr *)ipv6, sizeof(struct sockaddr_in6), ip, 65, nullptr, 0, NI_NUMERICHOST); - } - freeaddrinfo(res); -#else - (void) domainName; - (void) ip; -#endif -} - -void DomainNameToIP_Berkley_IPV4( const char *domainName, char ip[65] ) -{ - struct addrinfo *addressinfo = nullptr; - struct addrinfo *originalAddressInfo = nullptr; - WSAStartupSingleton::AddRef(); - int error = getaddrinfo(domainName, nullptr, nullptr, &addressinfo); - WSAStartupSingleton::Deref(); - - if ( error != 0 || addressinfo == 0 ) - { - ip[0] = '\0'; - return; - } - - originalAddressInfo = addressinfo; - - while (addressinfo != nullptr) { - if (addressinfo->ai_family == AF_INET) { - break; - } - addressinfo = addressinfo->ai_next; - } - - if (addressinfo == nullptr) { - ip[0] = '\0'; - freeaddrinfo(originalAddressInfo); - return; - } - - struct sockaddr_in *sockaddr_ipv4 = (struct sockaddr_in *) addressinfo->ai_addr; - inet_ntop(AF_INET, &sockaddr_ipv4->sin_addr, ip, 65); - freeaddrinfo(originalAddressInfo); -} - -void DomainNameToIP_Berkley( const char *domainName, char ip[65] ) -{ -#if RAKNET_SUPPORT_IPV6==1 - return DomainNameToIP_Berkley_IPV4And6(domainName, ip); -#else - return DomainNameToIP_Berkley_IPV4(domainName, ip); -#endif -} - -void RNS2_Berkley::SetSocketOptions(void) -{ - int r; - // This doubles the max throughput rate - int sock_opt=1024*256; - r = setsockopt__( rns2Socket, SOL_SOCKET, SO_RCVBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) ); - RakAssert(r==0); - - // Immediate hard close. Don't linger the socket, or recreating the socket quickly on Vista fails. - // Fail with voice and xbox - - sock_opt=0; - r = setsockopt__( rns2Socket, SOL_SOCKET, SO_LINGER, ( char * ) & sock_opt, sizeof ( sock_opt ) ); - // Do not assert, ignore failure - -#ifdef _WIN32 - // Disable SIO_UDP_CONNRESET behavior on Windows - // By default, if a UDP sendto() results in an ICMP "port unreachable" response, - // Windows will cause subsequent recvfrom() calls to fail with WSAECONNRESET (10054). - // This is undesirable for UDP applications that may send to unreachable hosts. - #ifndef SIO_UDP_CONNRESET - #define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR, 12) - #endif - BOOL bNewBehavior = FALSE; - DWORD dwBytesReturned = 0; - WSAIoctl(rns2Socket, SIO_UDP_CONNRESET, &bNewBehavior, sizeof(bNewBehavior), nullptr, 0, &dwBytesReturned, nullptr, nullptr); - // Ignore errors - this call may fail on older Windows versions -#endif - - // This doesn't make much difference: 10% maybe - // Not supported on console 2 - sock_opt=1024*16; - r = setsockopt__( rns2Socket, SOL_SOCKET, SO_SNDBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) ); - RakAssert(r==0); - -} - -void RNS2_Berkley::SetNonBlockingSocket(unsigned long nonblocking) -{ -#ifdef _WIN32 - SLNET_VERIFY( ioctlsocket__( rns2Socket, FIONBIO, &nonblocking ) == 0); -#else - if (nonblocking) - fcntl( rns2Socket, F_SETFL, O_NONBLOCK ); -#endif -} -void RNS2_Berkley::SetBroadcastSocket(int broadcast) -{ - setsockopt__( rns2Socket, SOL_SOCKET, SO_BROADCAST, ( char * ) & broadcast, sizeof( broadcast ) ); -} -void RNS2_Berkley::SetIPHdrIncl(int ipHdrIncl) -{ - - setsockopt__( rns2Socket, IPPROTO_IP, IP_HDRINCL, ( char * ) & ipHdrIncl, sizeof( ipHdrIncl ) ); - -} -void RNS2_Berkley::SetDoNotFragment( int opt ) -{ - #if defined( IP_DONTFRAGMENT ) - #if defined(_WIN32) && !defined(_DEBUG) - // If this assert hit you improperly linked against WSock32.h - RakAssert(IP_DONTFRAGMENT==14); - #endif - setsockopt__( rns2Socket, boundAddress.GetIPPROTO(), IP_DONTFRAGMENT, ( char * ) & opt, sizeof ( opt ) ); - #endif -} - -void RNS2_Berkley::GetSystemAddressIPV4 ( RNS2Socket rns2Socket, SystemAddress *systemAddressOut ) -{ - sockaddr_in sa; - memset(&sa,0,sizeof(sockaddr_in)); - socklen_t len = sizeof(sa); - //int r = - getsockname__(rns2Socket, (sockaddr*)&sa, &len); - systemAddressOut->SetPortNetworkOrder(sa.sin_port); - systemAddressOut->address.addr4.sin_addr.s_addr=sa.sin_addr.s_addr; - - if (systemAddressOut->address.addr4.sin_addr.s_addr == INADDR_ANY) - { - - - - - inet_pton(AF_INET, "127.0.0.1", &systemAddressOut->address.addr4.sin_addr.s_addr); - - } -} -void RNS2_Berkley::GetSystemAddressIPV4And6 ( RNS2Socket rns2Socket, SystemAddress *systemAddressOut ) -{ -#if RAKNET_SUPPORT_IPV6==1 - - socklen_t slen; - sockaddr_storage ss; - slen = sizeof(ss); - - if ( getsockname__(rns2Socket, (struct sockaddr *)&ss, &slen)!=0) - { -#if defined(_WIN32) && defined(_DEBUG) - DWORD dwIOError = GetLastError(); - LPVOID messageBuffer; - FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language - ( LPTSTR ) & messageBuffer, 0, nullptr); - // something has gone wrong here... - RAKNET_DEBUG_TPRINTF( _T("getsockname failed:Error code - %d\n%s"), dwIOError, static_cast(messageBuffer)); - - //Free the buffer. - LocalFree( messageBuffer ); -#endif - systemAddressOut->FromString(0); - return; - } - - if (ss.ss_family==AF_INET) - { - memcpy(&systemAddressOut->address.addr4,(sockaddr_in *)&ss,sizeof(sockaddr_in)); - systemAddressOut->debugPort=ntohs(systemAddressOut->address.addr4.sin_port); - - uint32_t zero = 0; - if (memcmp(&systemAddressOut->address.addr4.sin_addr.s_addr, &zero, sizeof(zero))==0) - systemAddressOut->SetToLoopback(4); - // systemAddressOut->address.addr4.sin_port=ntohs(systemAddressOut->address.addr4.sin_port); - } - else - { - memcpy(&systemAddressOut->address.addr6,(sockaddr_in6 *)&ss,sizeof(sockaddr_in6)); - systemAddressOut->debugPort=ntohs(systemAddressOut->address.addr6.sin6_port); - - char zero[16]; - memset(zero,0,sizeof(zero)); - if (memcmp(&systemAddressOut->address.addr4.sin_addr.s_addr, &zero, sizeof(zero))==0) - systemAddressOut->SetToLoopback(6); - - // systemAddressOut->address.addr6.sin6_port=ntohs(systemAddressOut->address.addr6.sin6_port); - } - -#else - (void) rns2Socket; - (void) systemAddressOut; - return; -#endif -} - -RNS2BindResult RNS2_Berkley::BindSharedIPV4( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ) { - - (void) file; - (void) line; - - int ret; - memset(&boundAddress.address.addr4,0,sizeof(sockaddr_in)); - boundAddress.address.addr4.sin_port = htons( bindParameters->port ); - rns2Socket = (int) socket__( bindParameters->addressFamily, bindParameters->type, bindParameters->protocol ); - if (rns2Socket == -1) - return BR_FAILED_TO_BIND_SOCKET; - - SetSocketOptions(); - SetNonBlockingSocket(bindParameters->nonBlockingSocket); - SetBroadcastSocket(bindParameters->setBroadcast); - SetIPHdrIncl(bindParameters->setIPHdrIncl); - - // Fill in the rest of the address structure - boundAddress.address.addr4.sin_family = AF_INET; - - if (bindParameters->hostAddress && bindParameters->hostAddress[0]) - { - inet_pton(AF_INET, bindParameters->hostAddress, &boundAddress.address.addr4.sin_addr.s_addr); - } - else - { - // RAKNET_DEBUG_PRINTF("Binding any on port %i\n", port); - boundAddress.address.addr4.sin_addr.s_addr = INADDR_ANY; - } - - // bind our name to the socket - ret = bind__( rns2Socket, ( struct sockaddr * ) &boundAddress.address.addr4, sizeof( boundAddress.address.addr4 ) ); - - if ( ret <= -1 ) - { -#if defined(_WIN32) - closesocket__(rns2Socket); - return BR_FAILED_TO_BIND_SOCKET; -#elif (defined(__GNUC__) || defined(__GCCXML__) ) && !defined(_WIN32) - closesocket__(rns2Socket); - switch (errno) - { - case EBADF: - RAKNET_DEBUG_PRINTF("bind__(): sockfd is not a valid descriptor.\n"); break; - case ENOTSOCK: - RAKNET_DEBUG_PRINTF("bind__(): Argument is a descriptor for a file, not a socket.\n"); break; - case EINVAL: - RAKNET_DEBUG_PRINTF("bind__(): The addrlen is wrong, or the socket was not in the AF_UNIX family.\n"); break; - case EROFS: - RAKNET_DEBUG_PRINTF("bind__(): The socket inode would reside on a read-only file system.\n"); break; - case EFAULT: - RAKNET_DEBUG_PRINTF("bind__(): my_addr points outside the user's accessible address space.\n"); break; - case ENAMETOOLONG: - RAKNET_DEBUG_PRINTF("bind__(): my_addr is too long.\n"); break; - case ENOENT: - RAKNET_DEBUG_PRINTF("bind__(): The file does not exist.\n"); break; - case ENOMEM: - RAKNET_DEBUG_PRINTF("bind__(): Insufficient kernel memory was available.\n"); break; - case ENOTDIR: - RAKNET_DEBUG_PRINTF("bind__(): A component of the path prefix is not a directory.\n"); break; - case EACCES: - // Port reserved on PS4 - RAKNET_DEBUG_PRINTF("bind__(): Search permission is denied on a component of the path prefix.\n"); break; - case ELOOP: - RAKNET_DEBUG_PRINTF("bind__(): Too many symbolic links were encountered in resolving my_addr.\n"); break; - default: - RAKNET_DEBUG_PRINTF("Unknown bind__() error %i.\n", errno); break; - } - - return BR_FAILED_TO_BIND_SOCKET; -#endif - } - - GetSystemAddressIPV4(rns2Socket, &boundAddress ); - return BR_SUCCESS; -} - -void PrepareAddrInfoHints2(addrinfo *hints) -{ - memset(hints, 0, sizeof(addrinfo)); // make sure the struct is empty - hints->ai_socktype = SOCK_DGRAM; // UDP sockets - hints->ai_flags = AI_PASSIVE; // fill in my IP for me -} - -RNS2BindResult RNS2_Berkley::BindSharedIPV4And6( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ) { - - (void) file; - (void) line; - (void) bindParameters; - -#if RAKNET_SUPPORT_IPV6==1 - - int ret=0; - struct addrinfo hints; - struct addrinfo *servinfo=0, *aip; // will point to the results - PrepareAddrInfoHints2(&hints); - hints.ai_family=bindParameters->addressFamily; - char portStr[32]; - Itoa(bindParameters->port,portStr,10); - - - // On Ubuntu, "" returns "No address associated with hostname" while 0 works. - if (bindParameters->hostAddress && - (_stricmp(bindParameters->hostAddress,"UNASSIGNED_SYSTEM_ADDRESS")==0 || bindParameters->hostAddress[0]==0)) - { - getaddrinfo(0, portStr, &hints, &servinfo); - } - else - { - getaddrinfo(bindParameters->hostAddress, portStr, &hints, &servinfo); - } - - // Try all returned addresses until one works - for (aip = servinfo; aip != nullptr; aip = aip->ai_next) - { - // Open socket. The address type depends on what - // getaddrinfo() gave us. - rns2Socket = socket__(aip->ai_family, aip->ai_socktype, aip->ai_protocol); - - if (rns2Socket == -1) - return BR_FAILED_TO_BIND_SOCKET; - - // For IPv6 sockets, set IPV6_V6ONLY to allow binding both IPv4 and IPv6 - // sockets to the same port. Without this, an IPv6 socket on Linux/Windows - // defaults to dual-stack mode (listening on both IPv4 and IPv6), which - // prevents a separate IPv4 socket from binding to the same port. - if (aip->ai_family == AF_INET6) - { - int ipv6only = 1; - setsockopt__(rns2Socket, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only)); - // Ignore errors - some platforms may not support this option - } - - ret = bind__(rns2Socket, aip->ai_addr, (int) aip->ai_addrlen ); - if (ret>=0) - { - if (aip->ai_family == AF_INET) - { - memcpy(&boundAddress.address.addr4, aip->ai_addr, sizeof(sockaddr_in)); - } - else - { - memcpy(&boundAddress.address.addr6, aip->ai_addr, sizeof(sockaddr_in6)); - } - - freeaddrinfo(servinfo); // free the linked-list - - SetSocketOptions(); - SetNonBlockingSocket(bindParameters->nonBlockingSocket); - SetBroadcastSocket(bindParameters->setBroadcast); - SetIPHdrIncl(bindParameters->setIPHdrIncl); - - GetSystemAddressIPV4And6( rns2Socket, &boundAddress ); - - return BR_SUCCESS; - } - else - { - closesocket__(rns2Socket); - } - } - - return BR_FAILED_TO_BIND_SOCKET; - -#else -return BR_REQUIRES_RAKNET_SUPPORT_IPV6_DEFINE; -#endif -} - -void RNS2_Berkley::RecvFromBlockingIPV4And6(RNS2RecvStruct *recvFromStruct) -{ -#if RAKNET_SUPPORT_IPV6==1 - - sockaddr_storage their_addr; - sockaddr* sockAddrPtr; - socklen_t sockLen; - socklen_t* socketlenPtr=(socklen_t*) &sockLen; - memset(&their_addr,0,sizeof(their_addr)); - int dataOutSize; - const int flag=0; - - { - sockLen=sizeof(their_addr); - sockAddrPtr=(sockaddr*) &their_addr; - } - - dataOutSize=MAXIMUM_MTU_SIZE; - - recvFromStruct->bytesRead = recvfrom__(rns2Socket, recvFromStruct->data, dataOutSize, flag, sockAddrPtr, socketlenPtr ); - -#if defined(_WIN32) && defined(_DEBUG) - if (recvFromStruct->bytesRead==-1) - { - DWORD dwIOError = GetLastError(); - // 10035 = WSAEWOULDBLOCK (expected for non-blocking sockets) - // 10054 = WSAECONNRESET (expected for UDP - prior sendto received ICMP port unreachable) - if (dwIOError != 10035 && dwIOError != 10054) - { - LPVOID messageBuffer; - FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language - ( LPTSTR ) & messageBuffer, 0, nullptr); - // I see this hit on XP with IPV6 for some reason - RAKNET_DEBUG_TPRINTF( _T("Warning: recvfrom failed:Error code - %d\n%s"), dwIOError, static_cast(messageBuffer) ); - LocalFree( messageBuffer ); - } - } -#endif - - if (recvFromStruct->bytesRead<=0) - return; - recvFromStruct->timeRead= MafiaNet::GetTimeUS(); - - { - if (their_addr.ss_family==AF_INET) - { - memcpy(&recvFromStruct->systemAddress.address.addr4,(sockaddr_in *)&their_addr,sizeof(sockaddr_in)); - recvFromStruct->systemAddress.debugPort=ntohs(recvFromStruct->systemAddress.address.addr4.sin_port); - // systemAddressOut->address.addr4.sin_port=ntohs( systemAddressOut->address.addr4.sin_port ); - } - else - { - memcpy(&recvFromStruct->systemAddress.address.addr6,(sockaddr_in6 *)&their_addr,sizeof(sockaddr_in6)); - recvFromStruct->systemAddress.debugPort=ntohs(recvFromStruct->systemAddress.address.addr6.sin6_port); - // systemAddressOut->address.addr6.sin6_port=ntohs( systemAddressOut->address.addr6.sin6_port ); - } - } - -#else - (void) recvFromStruct; -#endif -} - -void RNS2_Berkley::RecvFromBlockingIPV4(RNS2RecvStruct *recvFromStruct) -{ - sockaddr* sockAddrPtr; - socklen_t sockLen; - socklen_t* socketlenPtr=(socklen_t*) &sockLen; - sockaddr_in sa; - memset(&sa,0,sizeof(sockaddr_in)); - const int flag=0; - - { - sockLen=sizeof(sa); - sa.sin_family = AF_INET; - sa.sin_port=0; - sockAddrPtr=(sockaddr*) &sa; - } - - recvFromStruct->bytesRead = recvfrom__( GetSocket(), recvFromStruct->data, sizeof(recvFromStruct->data), flag, sockAddrPtr, socketlenPtr ); - - if (recvFromStruct->bytesRead<=0) - { - return; - } - recvFromStruct->timeRead= MafiaNet::GetTimeUS(); - - { - recvFromStruct->systemAddress.SetPortNetworkOrder( sa.sin_port ); - recvFromStruct->systemAddress.address.addr4.sin_addr.s_addr=sa.sin_addr.s_addr; - } -} - -void RNS2_Berkley::RecvFromBlocking(RNS2RecvStruct *recvFromStruct) -{ -#if RAKNET_SUPPORT_IPV6==1 - return RecvFromBlockingIPV4And6(recvFromStruct); -#else - return RecvFromBlockingIPV4(recvFromStruct); -#endif -} - -#endif // file header - -#endif // #ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS diff --git a/vendors/mafianet/Source/src/RakNetSocket2_Windows_Linux.cpp b/vendors/mafianet/Source/src/RakNetSocket2_Windows_Linux.cpp deleted file mode 100644 index 1c5c74111..000000000 --- a/vendors/mafianet/Source/src/RakNetSocket2_Windows_Linux.cpp +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2019, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/EmptyHeader.h" - -#ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS - -#ifndef RAKNETSOCKET2_WINDOWS_LINUX_CPP -#define RAKNETSOCKET2_WINDOWS_LINUX_CPP - -#ifndef _WIN32 -#include // used for getifaddrs() -#include // used for getifaddrs() -#endif // _WIN32 - -#include // used for std::string - -#ifdef _WIN32 - -// #med - consider replacing addressFamility parameter with includeIPv6 parameter for consistency with GetMyIP_Linux() -// based on https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer#1317284 -void GetMyIP_Windows(SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS], const ULONG addressFamily) -{ - ULONG outBufLen = 45 * 1024; // reserve 45 KB of memory which is the upper limit taken from the sample in MSDN (ie. 15 KB * 3 iterations) - PIP_ADAPTER_ADDRESSES pAddresses = static_cast(rakMalloc_Ex(outBufLen, _FILE_AND_LINE_)); - if (pAddresses == nullptr) { - // #med - error logging and/or throw exception? - return; - } - - DWORD error = GetAdaptersAddresses(addressFamily, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_FRIENDLY_NAME, nullptr, pAddresses, &outBufLen); - if (error != ERROR_SUCCESS) { - // #med - error logging and/or throw exception? - rakFree_Ex(pAddresses, _FILE_AND_LINE_); - return; - } - - PIP_ADAPTER_ADDRESSES pCurAdapter = pAddresses; - size_t outAddressIndex = 0; - while ((pCurAdapter != nullptr) && (outAddressIndex < MAXIMUM_NUMBER_OF_INTERNAL_IDS)) { - // skip loopback adapters - if (pCurAdapter->IfType != IF_TYPE_SOFTWARE_LOOPBACK) { - - // parse the adapter's unicast addresses - PIP_ADAPTER_UNICAST_ADDRESS curAddress = pCurAdapter->FirstUnicastAddress; - while ((curAddress != nullptr) && (outAddressIndex < MAXIMUM_NUMBER_OF_INTERNAL_IDS)) { - // note: we'd only requested IPV4 addresses, so this check should be redundant - double-check just to be on the safe side - // #med - log a warning - const ADDRESS_FAMILY curAddressFamily = curAddress->Address.lpSockaddr->sa_family; - if (curAddressFamily == AF_INET) { - const sockaddr_in*const curSocketAddress = reinterpret_cast(curAddress->Address.lpSockaddr); - - // #med - review, is this really necessary? - // skip source only addresses (aka: 0.0.0.0/8 - see RFC1700 p.4) - if (curSocketAddress->sin_addr.S_un.S_un_b.s_b1 != 0) { - // store the adapter's address - addresses[outAddressIndex++].address.addr4 = *curSocketAddress; - } - } -#if RAKNET_SUPPORT_IPV6 == 1 - else if (curAddressFamily == AF_INET6) { - // note: not const ptr since inet_ntop() requires non-const ptr - sockaddr_in6*const curSocketAddress = reinterpret_cast(curAddress->Address.lpSockaddr); - - char buffer[INET6_ADDRSTRLEN] = { 0 }; - // #med - add return value check - inet_ntop(AF_INET6, &(curSocketAddress->sin6_addr), buffer, INET6_ADDRSTRLEN); - - const std::string ipv6String(buffer); - - // detect and skip non-external addresses - bool isLocal = false; - bool isSpecial = false; - if (ipv6String.find("fe") == 0) { - const char c = ipv6String[2]; - if (c == '8' || c == '9' || c == 'a' || c == 'b') { - isLocal = true; - } - } - else if (ipv6String.find("2001:0:") == 0) { - isSpecial = true; - } - - if (!(isLocal || isSpecial)) { - // store the adapter's address - addresses[outAddressIndex++].address.addr6 = *curSocketAddress; - } - } -#endif // RAKNET_SUPPORT_IPV6 == 1 - // else skip the address (neither IPv4 nor IPv6 address) - - // continue with next address - curAddress = curAddress->Next; - } - } - - // continue with next adapter's addresses - pCurAdapter = pCurAdapter->Next; - } - rakFree_Ex(pAddresses, _FILE_AND_LINE_); - - while (outAddressIndex < MAXIMUM_NUMBER_OF_INTERNAL_IDS) { - addresses[outAddressIndex++] = UNASSIGNED_SYSTEM_ADDRESS; - } -} - -#else // _WIN32 - -// based on https://stackoverflow.com/questions/212528/get-the-ip-address-of-the-machine#265978 -void GetMyIP_Linux(SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS], const bool includeIPv6) -{ - struct ifaddrs *pAddresses = nullptr; - - // #med - add error check to getifaddrs()-call - getifaddrs(&pAddresses); - - struct ifaddrs *pCurAdapter = pAddresses; - size_t outAddressIndex = 0; - while ((pCurAdapter != nullptr) && (outAddressIndex < MAXIMUM_NUMBER_OF_INTERNAL_IDS)) { - // skip interfaces which don't have any address assigned (according to the manual, this would only apply for BSD, but still we'd check for null here just in case) - if (pCurAdapter->ifa_addr != nullptr) { - // skip loopback adapters - if ((pCurAdapter->ifa_flags & IFF_LOOPBACK) == 0) { - if (pCurAdapter->ifa_addr->sa_family == AF_INET) { - const sockaddr_in*const curSocketAddress = reinterpret_cast(pCurAdapter->ifa_addr); - - char buffer[INET_ADDRSTRLEN] = { 0 }; - // #med - add return value check - inet_ntop(AF_INET, &(curSocketAddress->sin_addr), buffer, INET_ADDRSTRLEN); - - const std::string ipv4String(buffer); - - // #med - review, is this really necessary? - // skip source only addresses (aka: 0.0.0.0/8 - see RFC1700 p.4) - if (ipv4String.find("0.") != 0) { - // store the adapter's address - addresses[outAddressIndex++].address.addr4 = *curSocketAddress; - } - } -#if RAKNET_SUPPORT_IPV6 == 1 - else if (includeIPv6 && pCurAdapter->ifa_addr->sa_family == AF_INET6) { - const sockaddr_in6*const curSocketAddress = reinterpret_cast(pCurAdapter->ifa_addr); - - char buffer[INET6_ADDRSTRLEN] = { 0 }; - // #med - add return value check - inet_ntop(AF_INET6, &(curSocketAddress->sin6_addr), buffer, INET6_ADDRSTRLEN); - - const std::string ipv6String(buffer); - - // detect and skip non-external addresses - bool isLocal = false; - bool isSpecial = false; - if (ipv6String.find("fe") == 0) { - const char c = ipv6String[2]; - if (c == '8' || c == '9' || c == 'a' || c == 'b') { - isLocal = true; - } - } - else if (ipv6String.find("2001:0:") == 0) { - isSpecial = true; - } - - if (!(isLocal || isSpecial)) { - // store the adapter's address - addresses[outAddressIndex++].address.addr6 = *curSocketAddress; - } - } -#endif // RAKNET_SUPPORT_IPV6 == 1 - // else skip the address (neither IPv4 nor IPv6 address) - } - } - - pCurAdapter = pCurAdapter->ifa_next; - } - - if (pAddresses != nullptr) - freeifaddrs(pAddresses); - - while (outAddressIndex < MAXIMUM_NUMBER_OF_INTERNAL_IDS) { - addresses[outAddressIndex++] = UNASSIGNED_SYSTEM_ADDRESS; - } -} - -#endif // _WIN32 - -void GetMyIP_Windows_Linux(SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS]) -{ -#if RAKNET_SUPPORT_IPV6 == 1 - -#ifdef _WIN32 - GetMyIP_Windows(addresses, AF_UNSPEC); -#else // _WIN32 - GetMyIP_Linux(addresses, true); -#endif // _WIN32 - -#else // RAKNET_SUPPORT_IPV6 == 1 - -#ifdef _WIN32 - GetMyIP_Windows(addresses, AF_INET); -#else // _WIN32 - GetMyIP_Linux(addresses, false); -#endif // _WIN32 - -#endif // RAKNET_SUPPORT_IPV6 == 1 -} - -#endif // RAKNETSOCKET2_WINDOWS_LINUX_CPP - -#endif // RAKNET_SOCKET_2_INLINE_FUNCTIONS diff --git a/vendors/mafianet/Source/src/RakNetSocket2_Windows_Linux_360.cpp b/vendors/mafianet/Source/src/RakNetSocket2_Windows_Linux_360.cpp deleted file mode 100644 index 6850ab3b8..000000000 --- a/vendors/mafianet/Source/src/RakNetSocket2_Windows_Linux_360.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/EmptyHeader.h" - -#ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS - -#ifndef RAKNETSOCKET2_WINDOWS_LINUX_360_CPP -#define RAKNETSOCKET2_WINDOWS_LINUX_360_CPP - -#if defined(_WIN32) || defined(__GNUC__) || defined(__GCCXML__) || defined(__S3E__) - -RNS2SendResult RNS2_Windows_Linux_360::Send_Windows_Linux_360NoVDP( RNS2Socket rns2Socket, RNS2_SendParameters *sendParameters, const char *file, unsigned int line ) { - - int len=0; - do - { - (void) file; - (void) line; - - - int oldTTL=-1; - if (sendParameters->ttl>0) - { - socklen_t opLen=sizeof(oldTTL); - // Get the current TTL - if (getsockopt__(rns2Socket, sendParameters->systemAddress.GetIPPROTO(), IP_TTL, ( char * ) & oldTTL, &opLen ) != -1) - { - int newTTL=sendParameters->ttl; - setsockopt__(rns2Socket, sendParameters->systemAddress.GetIPPROTO(), IP_TTL, ( char * ) & newTTL, sizeof ( newTTL ) ); - } - } - - - if (sendParameters->systemAddress.address.addr4.sin_family==AF_INET) - { - len = sendto__( rns2Socket, sendParameters->data, sendParameters->length, 0, ( const sockaddr* ) & sendParameters->systemAddress.address.addr4, sizeof( sockaddr_in ) ); - } - else - { -#if RAKNET_SUPPORT_IPV6==1 - len = sendto__( rns2Socket, sendParameters->data, sendParameters->length, 0, ( const sockaddr* ) & sendParameters->systemAddress.address.addr6, sizeof( sockaddr_in6 ) ); -#endif - } - - if (len<0) - { - RAKNET_DEBUG_PRINTF("sendto failed with code %i for char %i and length %i.\n", len, sendParameters->data[0], sendParameters->length); - } - - - if (oldTTL!=-1) - { - setsockopt__(rns2Socket, sendParameters->systemAddress.GetIPPROTO(), IP_TTL, ( char * ) & oldTTL, sizeof ( oldTTL ) ); - } - - } - while ( len == 0 ); - return len; -} - -#endif // Windows, Linux, 360 - -#endif // file header - -#endif // #ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS diff --git a/vendors/mafianet/Source/src/RakNetStatistics.cpp b/vendors/mafianet/Source/src/RakNetStatistics.cpp deleted file mode 100644 index 4462a2a9f..000000000 --- a/vendors/mafianet/Source/src/RakNetStatistics.cpp +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2019, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// - - - -#include "mafianet/statistics.h" -#include // sprintf -#include "mafianet/GetTime.h" -#include "mafianet/string.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace MafiaNet; - -// Verbosity level currently supports 0 (low), 1 (medium), 2 (high) -// Buffer must be hold enough to hold the output string. See the source to get an idea of how many bytes will be output -void RAK_DLL_EXPORT MafiaNet::StatisticsToString(RakNetStatistics *s, char *buffer, int verbosityLevel) -{ - if (s == 0) - { -#pragma warning(push) -#pragma warning(disable:4996) - sprintf(buffer, "stats is a null pointer in statsToString\n"); -#pragma warning(pop) - return; - } - - if (verbosityLevel == 0) - { -#pragma warning(push) -#pragma warning(disable:4996) - sprintf(buffer, - "Bytes per second sent %" PRINTF_64_BIT_MODIFIER "u\n" - "Bytes per second received %" PRINTF_64_BIT_MODIFIER "u\n" - "Current packetloss %.1f%%\n", - (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_SENT], - (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_RECEIVED], - s->packetlossLastSecond*100.0f - ); -#pragma warning(pop) - } - else if (verbosityLevel == 1) - { -#pragma warning(push) -#pragma warning(disable:4996) - sprintf(buffer, - "Actual bytes per second sent %" PRINTF_64_BIT_MODIFIER "u\n" - "Actual bytes per second received %" PRINTF_64_BIT_MODIFIER "u\n" - "Message bytes per second pushed %" PRINTF_64_BIT_MODIFIER "u\n" - "Total actual bytes sent %" PRINTF_64_BIT_MODIFIER "u\n" - "Total actual bytes received %" PRINTF_64_BIT_MODIFIER "u\n" - "Total message bytes pushed %" PRINTF_64_BIT_MODIFIER "u\n" - "Current packetloss %.1f%%\n" - "Average packetloss %.1f%%\n" - "Elapsed connection time in seconds %" PRINTF_64_BIT_MODIFIER "u\n", - (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_SENT], - (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_RECEIVED], - (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_PUSHED], - (long long unsigned int) s->runningTotal[ACTUAL_BYTES_SENT], - (long long unsigned int) s->runningTotal[ACTUAL_BYTES_RECEIVED], - (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_PUSHED], - s->packetlossLastSecond*100.0f, - s->packetlossTotal*100.0f, - (long long unsigned int) (uint64_t)((MafiaNet::GetTimeUS() - s->connectionStartTime) / 1000000) - ); -#pragma warning(pop) - - if (s->BPSLimitByCongestionControl != 0) - { - char buff2[128]; - sprintf_s(buff2, - "Send capacity %" PRINTF_64_BIT_MODIFIER "u bytes per second (%.0f%%)\n", - (long long unsigned int) s->BPSLimitByCongestionControl, - 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByCongestionControl - ); -#pragma warning(push) -#pragma warning(disable:4996) - strcat(buffer, buff2); -#pragma warning(pop) - } - if (s->BPSLimitByOutgoingBandwidthLimit != 0) - { - char buff2[128]; - sprintf_s(buff2, - "Send limit %" PRINTF_64_BIT_MODIFIER "u (%.0f%%)\n", - (long long unsigned int) s->BPSLimitByOutgoingBandwidthLimit, - 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByOutgoingBandwidthLimit - ); -#pragma warning(push) -#pragma warning(disable:4996) - strcat(buffer, buff2); -#pragma warning(pop) - } - } - else - { -#pragma warning(push) -#pragma warning(disable:4996) - sprintf(buffer, - "Actual bytes per second sent %" PRINTF_64_BIT_MODIFIER "u\n" - "Actual bytes per second received %" PRINTF_64_BIT_MODIFIER "u\n" - "Message bytes per second sent %" PRINTF_64_BIT_MODIFIER "u\n" - "Message bytes per second resent %" PRINTF_64_BIT_MODIFIER "u\n" - "Message bytes per second pushed %" PRINTF_64_BIT_MODIFIER "u\n" - "Message bytes per second returned %" PRINTF_64_BIT_MODIFIER "u\n" - "Message bytes per second ignored %" PRINTF_64_BIT_MODIFIER "u\n" - "Total bytes sent %" PRINTF_64_BIT_MODIFIER "u\n" - "Total bytes received %" PRINTF_64_BIT_MODIFIER "u\n" - "Total message bytes sent %" PRINTF_64_BIT_MODIFIER "u\n" - "Total message bytes resent %" PRINTF_64_BIT_MODIFIER "u\n" - "Total message bytes pushed %" PRINTF_64_BIT_MODIFIER "u\n" - "Total message bytes returned %" PRINTF_64_BIT_MODIFIER "u\n" - "Total message bytes ignored %" PRINTF_64_BIT_MODIFIER "u\n" - "Messages in send buffer, by priority %i,%i,%i,%i\n" - "Bytes in send buffer, by priority %i,%i,%i,%i\n" - "Messages in resend buffer %i\n" - "Bytes in resend buffer %" PRINTF_64_BIT_MODIFIER "u\n" - "Current packetloss %.1f%%\n" - "Average packetloss %.1f%%\n" - "Elapsed connection time in seconds %" PRINTF_64_BIT_MODIFIER "u\n", - (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_SENT], - (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_RECEIVED], - (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_SENT], - (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_RESENT], - (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_PUSHED], - (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_RECEIVED_PROCESSED], - (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_RECEIVED_IGNORED], - (long long unsigned int) s->runningTotal[ACTUAL_BYTES_SENT], - (long long unsigned int) s->runningTotal[ACTUAL_BYTES_RECEIVED], - (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_SENT], - (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_RESENT], - (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_PUSHED], - (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_RECEIVED_PROCESSED], - (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_RECEIVED_IGNORED], - s->messageInSendBuffer[(int)MafiaNet::Priority::Immediate], s->messageInSendBuffer[(int)MafiaNet::Priority::High], s->messageInSendBuffer[(int)MafiaNet::Priority::Medium], s->messageInSendBuffer[(int)MafiaNet::Priority::Low], - (unsigned int)s->bytesInSendBuffer[(int)MafiaNet::Priority::Immediate], (unsigned int)s->bytesInSendBuffer[(int)MafiaNet::Priority::High], (unsigned int)s->bytesInSendBuffer[(int)MafiaNet::Priority::Medium], (unsigned int)s->bytesInSendBuffer[(int)MafiaNet::Priority::Low], - s->messagesInResendBuffer, - (long long unsigned int) s->bytesInResendBuffer, - s->packetlossLastSecond*100.0f, - s->packetlossTotal*100.0f, - (long long unsigned int) (uint64_t)((MafiaNet::GetTimeUS() - s->connectionStartTime) / 1000000) - ); -#pragma warning(pop) - - if (s->BPSLimitByCongestionControl != 0) - { - char buff2[128]; - sprintf_s(buff2, - "Send capacity %" PRINTF_64_BIT_MODIFIER "u bytes per second (%.0f%%)\n", - (long long unsigned int) s->BPSLimitByCongestionControl, - 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByCongestionControl - ); -#pragma warning(push) -#pragma warning(disable:4996) - strcat(buffer, buff2); -#pragma warning(pop) - } - if (s->BPSLimitByOutgoingBandwidthLimit != 0) - { - char buff2[128]; - sprintf_s(buff2, - "Send limit %" PRINTF_64_BIT_MODIFIER "u (%.0f%%)\n", - (long long unsigned int) s->BPSLimitByOutgoingBandwidthLimit, - 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByOutgoingBandwidthLimit - ); -#pragma warning(push) -#pragma warning(disable:4996) - strcat(buffer, buff2); -#pragma warning(pop) - } - } -} -void RAK_DLL_EXPORT MafiaNet::StatisticsToString( RakNetStatistics *s, char *buffer, size_t bufferLength, int verbosityLevel ) -{ - if ( s == 0 ) - { - sprintf_s( buffer, bufferLength, "stats is a null pointer in statsToString\n" ); - return ; - } - - if (verbosityLevel==0) - { - sprintf_s(buffer, bufferLength, - "Bytes per second sent %" PRINTF_64_BIT_MODIFIER "u\n" - "Bytes per second received %" PRINTF_64_BIT_MODIFIER "u\n" - "Current packetloss %.1f%%\n", - (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_SENT], - (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_RECEIVED], - s->packetlossLastSecond*100.0f - ); - } - else if (verbosityLevel==1) - { - sprintf_s(buffer, bufferLength, - "Actual bytes per second sent %" PRINTF_64_BIT_MODIFIER "u\n" - "Actual bytes per second received %" PRINTF_64_BIT_MODIFIER "u\n" - "Message bytes per second pushed %" PRINTF_64_BIT_MODIFIER "u\n" - "Total actual bytes sent %" PRINTF_64_BIT_MODIFIER "u\n" - "Total actual bytes received %" PRINTF_64_BIT_MODIFIER "u\n" - "Total message bytes pushed %" PRINTF_64_BIT_MODIFIER "u\n" - "Current packetloss %.1f%%\n" - "Average packetloss %.1f%%\n" - "Elapsed connection time in seconds %" PRINTF_64_BIT_MODIFIER "u\n", - (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_SENT], - (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_RECEIVED], - (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_PUSHED], - (long long unsigned int) s->runningTotal[ACTUAL_BYTES_SENT], - (long long unsigned int) s->runningTotal[ACTUAL_BYTES_RECEIVED], - (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_PUSHED], - s->packetlossLastSecond*100.0f, - s->packetlossTotal*100.0f, - (long long unsigned int) (uint64_t)((MafiaNet::GetTimeUS()-s->connectionStartTime)/1000000) - ); - - if (s->BPSLimitByCongestionControl!=0) - { - char buff2[128]; - sprintf_s(buff2, - "Send capacity %" PRINTF_64_BIT_MODIFIER "u bytes per second (%.0f%%)\n", - (long long unsigned int) s->BPSLimitByCongestionControl, - 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByCongestionControl - ); - strcat_s(buffer,bufferLength,buff2); - } - if (s->BPSLimitByOutgoingBandwidthLimit!=0) - { - char buff2[128]; - sprintf_s(buff2, - "Send limit %" PRINTF_64_BIT_MODIFIER "u (%.0f%%)\n", - (long long unsigned int) s->BPSLimitByOutgoingBandwidthLimit, - 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByOutgoingBandwidthLimit - ); - strcat_s(buffer,bufferLength,buff2); - } - } - else - { - sprintf_s(buffer, bufferLength, - "Actual bytes per second sent %" PRINTF_64_BIT_MODIFIER "u\n" - "Actual bytes per second received %" PRINTF_64_BIT_MODIFIER "u\n" - "Message bytes per second sent %" PRINTF_64_BIT_MODIFIER "u\n" - "Message bytes per second resent %" PRINTF_64_BIT_MODIFIER "u\n" - "Message bytes per second pushed %" PRINTF_64_BIT_MODIFIER "u\n" - "Message bytes per second returned %" PRINTF_64_BIT_MODIFIER "u\n" - "Message bytes per second ignored %" PRINTF_64_BIT_MODIFIER "u\n" - "Total bytes sent %" PRINTF_64_BIT_MODIFIER "u\n" - "Total bytes received %" PRINTF_64_BIT_MODIFIER "u\n" - "Total message bytes sent %" PRINTF_64_BIT_MODIFIER "u\n" - "Total message bytes resent %" PRINTF_64_BIT_MODIFIER "u\n" - "Total message bytes pushed %" PRINTF_64_BIT_MODIFIER "u\n" - "Total message bytes returned %" PRINTF_64_BIT_MODIFIER "u\n" - "Total message bytes ignored %" PRINTF_64_BIT_MODIFIER "u\n" - "Messages in send buffer, by priority %i,%i,%i,%i\n" - "Bytes in send buffer, by priority %i,%i,%i,%i\n" - "Messages in resend buffer %i\n" - "Bytes in resend buffer %" PRINTF_64_BIT_MODIFIER "u\n" - "Current packetloss %.1f%%\n" - "Average packetloss %.1f%%\n" - "Elapsed connection time in seconds %" PRINTF_64_BIT_MODIFIER "u\n", - (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_SENT], - (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_RECEIVED], - (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_SENT], - (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_RESENT], - (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_PUSHED], - (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_RECEIVED_PROCESSED], - (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_RECEIVED_IGNORED], - (long long unsigned int) s->runningTotal[ACTUAL_BYTES_SENT], - (long long unsigned int) s->runningTotal[ACTUAL_BYTES_RECEIVED], - (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_SENT], - (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_RESENT], - (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_PUSHED], - (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_RECEIVED_PROCESSED], - (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_RECEIVED_IGNORED], - s->messageInSendBuffer[(int)MafiaNet::Priority::Immediate],s->messageInSendBuffer[(int)MafiaNet::Priority::High],s->messageInSendBuffer[(int)MafiaNet::Priority::Medium],s->messageInSendBuffer[(int)MafiaNet::Priority::Low], - (unsigned int) s->bytesInSendBuffer[(int)MafiaNet::Priority::Immediate],(unsigned int) s->bytesInSendBuffer[(int)MafiaNet::Priority::High],(unsigned int) s->bytesInSendBuffer[(int)MafiaNet::Priority::Medium],(unsigned int) s->bytesInSendBuffer[(int)MafiaNet::Priority::Low], - s->messagesInResendBuffer, - (long long unsigned int) s->bytesInResendBuffer, - s->packetlossLastSecond*100.0f, - s->packetlossTotal*100.0f, - (long long unsigned int) (uint64_t)((MafiaNet::GetTimeUS()-s->connectionStartTime)/1000000) - ); - - if (s->BPSLimitByCongestionControl!=0) - { - char buff2[128]; - sprintf_s(buff2, - "Send capacity %" PRINTF_64_BIT_MODIFIER "u bytes per second (%.0f%%)\n", - (long long unsigned int) s->BPSLimitByCongestionControl, - 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByCongestionControl - ); - strcat_s(buffer,bufferLength,buff2); - } - if (s->BPSLimitByOutgoingBandwidthLimit!=0) - { - char buff2[128]; - sprintf_s(buff2, - "Send limit %" PRINTF_64_BIT_MODIFIER "u (%.0f%%)\n", - (long long unsigned int) s->BPSLimitByOutgoingBandwidthLimit, - 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByOutgoingBandwidthLimit - ); - strcat_s(buffer,bufferLength,buff2); - } - } -} diff --git a/vendors/mafianet/Source/src/RakNetTransport2.cpp b/vendors/mafianet/Source/src/RakNetTransport2.cpp deleted file mode 100644 index b29abf429..000000000 --- a/vendors/mafianet/Source/src/RakNetTransport2.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_TelnetTransport==1 - -#include "mafianet/transport2.h" - -#include "mafianet/peerinterface.h" -#include "mafianet/BitStream.h" -#include "mafianet/MessageIdentifiers.h" -#include -#include -#include -#include "mafianet/LinuxStrings.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(RakNetTransport2,RakNetTransport2); - -RakNetTransport2::RakNetTransport2() -{ -} -RakNetTransport2::~RakNetTransport2() -{ - Stop(); -} -bool RakNetTransport2::Start(unsigned short port, bool serverMode) -{ - (void) port; - (void) serverMode; - return true; -} -void RakNetTransport2::Stop(void) -{ - newConnections.Clear(_FILE_AND_LINE_); - lostConnections.Clear(_FILE_AND_LINE_); - for (unsigned int i=0; i < packetQueue.Size(); i++) - { - rakFree_Ex(packetQueue[i]->data,_FILE_AND_LINE_); - MafiaNet::OP_DELETE(packetQueue[i],_FILE_AND_LINE_); - } - packetQueue.Clear(_FILE_AND_LINE_); -} -void RakNetTransport2::Send( SystemAddress systemAddress, const char *data, ... ) -{ - if (data==0 || data[0]==0) return; - - char text[REMOTE_MAX_TEXT_INPUT]; - va_list ap; - va_start(ap, data); - vsnprintf_s(text, REMOTE_MAX_TEXT_INPUT-1, data, ap); - va_end(ap); - - MafiaNet::BitStream str; - str.Write((MessageID)ID_TRANSPORT_STRING); - str.Write(text, (int) strlen(text)); - str.Write((unsigned char) 0); // Null terminate the string - rakPeerInterface->Send(&str, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, systemAddress, (systemAddress==UNASSIGNED_SYSTEM_ADDRESS)!=0); -} -void RakNetTransport2::CloseConnection( SystemAddress systemAddress ) -{ - rakPeerInterface->CloseConnection(systemAddress, true, 0); -} -Packet* RakNetTransport2::Receive( void ) -{ - if (packetQueue.Size()==0) - return 0; - return packetQueue.Pop(); -} -SystemAddress RakNetTransport2::HasNewIncomingConnection(void) -{ - if (newConnections.Size()) - return newConnections.Pop(); - return UNASSIGNED_SYSTEM_ADDRESS; -} -SystemAddress RakNetTransport2::HasLostConnection(void) -{ - if (lostConnections.Size()) - return lostConnections.Pop(); - return UNASSIGNED_SYSTEM_ADDRESS; -} -void RakNetTransport2::DeallocatePacket( Packet *packet ) -{ - rakFree_Ex(packet->data, _FILE_AND_LINE_ ); - MafiaNet::OP_DELETE(packet, _FILE_AND_LINE_ ); -} -PluginReceiveResult RakNetTransport2::OnReceive(Packet *packet) -{ - switch (packet->data[0]) - { - case ID_TRANSPORT_STRING: - { - if (packet->length==sizeof(MessageID)) - return RR_STOP_PROCESSING_AND_DEALLOCATE; - - Packet *p = MafiaNet::OP_NEW(_FILE_AND_LINE_); - *p=*packet; - p->bitSize-=8; - p->length--; - p->data=(unsigned char*) rakMalloc_Ex(p->length,_FILE_AND_LINE_); - memcpy(p->data, packet->data+1, p->length); - packetQueue.Push(p, _FILE_AND_LINE_ ); - - } - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - return RR_CONTINUE_PROCESSING; -} -void RakNetTransport2::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) rakNetGUID; - (void) lostConnectionReason; - lostConnections.Push(systemAddress, _FILE_AND_LINE_ ); -} -void RakNetTransport2::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) -{ - (void) rakNetGUID; - (void) isIncoming; - newConnections.Push(systemAddress, _FILE_AND_LINE_ ); -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/RakNetTypes.cpp b/vendors/mafianet/Source/src/RakNetTypes.cpp deleted file mode 100644 index 46c94aead..000000000 --- a/vendors/mafianet/Source/src/RakNetTypes.cpp +++ /dev/null @@ -1,790 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// - -#include "mafianet/types.h" -#include "mafianet/assert.h" -#include -#include -#include "mafianet/WindowsIncludes.h" -#include "mafianet/WSAStartupSingleton.h" -#include "mafianet/SocketDefines.h" -#include "mafianet/socket2.h" - -#if defined(_WIN32) -// extern __int64 _strtoui64(const char*, char**, int); // needed for Code::Blocks. Does not compile on Visual Studio 2010 -// IP_DONTFRAGMENT is different between winsock 1 and winsock 2. Therefore, Winsock2.h must be linked againt Ws2_32.lib -// winsock.h must be linked against WSock32.lib. If these two are mixed up the flag won't work correctly -#include "mafianet/WindowsIncludes.h" - -#else -#include // used for getnameinfo() -#include // used for getnameinfo() -#include -#include -#endif - -#include "mafianet/Itoa.h" -#include "mafianet/SocketLayer.h" -#include "mafianet/SuperFastHash.h" -#include -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace MafiaNet; - -const char *IPV6_LOOPBACK="::1"; -const char *IPV4_LOOPBACK="127.0.0.1"; - -AddressOrGUID::AddressOrGUID( Packet *packet ) -{ - rakNetGuid=packet->guid; - systemAddress=packet->systemAddress; -} - -unsigned long AddressOrGUID::ToInteger( const AddressOrGUID &aog ) -{ - if (aog.rakNetGuid!=UNASSIGNED_RAKNET_GUID) - return RakNetGUID::ToUint32(aog.rakNetGuid); - return SystemAddress::ToInteger(aog.systemAddress); -} -const char *AddressOrGUID::ToString(bool writePort) const -{ - if (rakNetGuid!=UNASSIGNED_RAKNET_GUID) - { - // Rotating static buffer, mirroring SystemAddress::ToString below. - // NOT THREADSAFE — for an owning, thread-safe string use - // MafiaNet::to_string(guid) from "mafianet/guid_util.h". - static unsigned char strIndex=0; - static char str[8][64]; - unsigned char lastStrIndex=strIndex; - strIndex++; - rakNetGuid.ToString(str[lastStrIndex&7], 64); - return (char*) str[lastStrIndex&7]; - } - return systemAddress.ToString(writePort); -} -void AddressOrGUID::ToString(bool writePort, char *dest) const -{ - if (rakNetGuid != UNASSIGNED_RAKNET_GUID) - return rakNetGuid.ToString(dest); - return systemAddress.ToString(writePort, dest); -} -void AddressOrGUID::ToString(bool writePort, char *dest, size_t destLength) const -{ - if (rakNetGuid!=UNASSIGNED_RAKNET_GUID) - return rakNetGuid.ToString(dest,destLength); - return systemAddress.ToString(writePort,dest,destLength); -} - -// Return false if IP address. Return true if domain -bool MafiaNet::NonNumericHostString( const char *host ) -{ - size_t i = 0; - while (host[i] != '\0') { - // IPV4: natpunch.slikesoft.com - // IPV6: fe80::7c:31f7:fec4:27de%14 - if ((host[i] >= 'g' && host[i] <= 'z') || - (host[i] >= 'G' && host[i] <= 'Z')) - return true; - ++i; - } - return false; -} - -SocketDescriptor::SocketDescriptor() { -#ifdef __native_client__ - blockingSocket=false; -#else - blockingSocket=true; -#endif - port=0; - hostAddress[0]=0; - remotePortRakNetWasStartedOn_PS3_PSP2=0; - extraSocketOptions=0; - socketFamily=AF_INET; -} -SocketDescriptor::SocketDescriptor(unsigned short _port, const char *_hostAddress) -{ - #ifdef __native_client__ - blockingSocket=false; - #else - blockingSocket=true; - #endif - remotePortRakNetWasStartedOn_PS3_PSP2=0; - port=_port; - if (_hostAddress) - strcpy_s(hostAddress, _hostAddress); - else - hostAddress[0]=0; - extraSocketOptions=0; - socketFamily=AF_INET; -} - -// Defaults to not in peer to peer mode for NetworkIDs. This only sends the localSystemAddress portion in the BitStream class -// This is what you want for client/server, where the server assigns all NetworkIDs and it is unnecessary to transmit the full structure. -// For peer to peer, this will transmit the systemAddress of the system that created the object in addition to localSystemAddress. This allows -// Any system to create unique ids locally. -// All systems must use the same value for this variable. -//bool RAK_DLL_EXPORT NetworkID::peerToPeerMode=false; - -SystemAddress& SystemAddress::operator = ( const SystemAddress& input ) -{ - memcpy(&address, &input.address, sizeof(address)); - systemIndex = input.systemIndex; - debugPort = input.debugPort; - return *this; -} -bool SystemAddress::EqualsExcludingPort( const SystemAddress& right ) const -{ - return (address.addr4.sin_family==AF_INET && address.addr4.sin_addr.s_addr==right.address.addr4.sin_addr.s_addr) -#if RAKNET_SUPPORT_IPV6==1 - || (address.addr4.sin_family==AF_INET6 && memcmp(address.addr6.sin6_addr.s6_addr, right.address.addr6.sin6_addr.s6_addr, sizeof(address.addr6.sin6_addr.s6_addr))==0) -#endif - ; -} -unsigned short SystemAddress::GetPort(void) const -{ - return ntohs(address.addr4.sin_port); -} -unsigned short SystemAddress::GetPortNetworkOrder(void) const -{ - return address.addr4.sin_port; -} -void SystemAddress::SetPortHostOrder(unsigned short s) -{ - address.addr4.sin_port=htons(s); - debugPort=s; -} -void SystemAddress::SetPortNetworkOrder(unsigned short s) -{ - address.addr4.sin_port=s; - debugPort=ntohs(s); -} -bool SystemAddress::operator==( const SystemAddress& right ) const -{ - return address.addr4.sin_port == right.address.addr4.sin_port && EqualsExcludingPort(right); -} - -bool SystemAddress::operator!=( const SystemAddress& right ) const -{ - return (*this==right)==false; -} - -bool SystemAddress::operator>( const SystemAddress& right ) const -{ - if (address.addr4.sin_port == right.address.addr4.sin_port) - { -#if RAKNET_SUPPORT_IPV6==1 - if (address.addr4.sin_family==AF_INET) - return address.addr4.sin_addr.s_addr>right.address.addr4.sin_addr.s_addr; - return memcmp(address.addr6.sin6_addr.s6_addr, right.address.addr6.sin6_addr.s6_addr, sizeof(address.addr6.sin6_addr.s6_addr))>0; -#else - return address.addr4.sin_addr.s_addr>right.address.addr4.sin_addr.s_addr; -#endif - } - return address.addr4.sin_port>right.address.addr4.sin_port; -} - -bool SystemAddress::operator<( const SystemAddress& right ) const -{ - if (address.addr4.sin_port == right.address.addr4.sin_port) - { -#if RAKNET_SUPPORT_IPV6==1 - if (address.addr4.sin_family==AF_INET) - return address.addr4.sin_addr.s_addr0; -#else - return address.addr4.sin_addr.s_addr(128)); - // TODO - what about 255.255.255.255? - if (strcmp(str, IPV6_LOOPBACK)==0) - { - if (boundAddressToSocket.GetIPVersion()==4) - { - FromString(IPV4_LOOPBACK,0,4); - } - } - else if (strcmp(str, IPV4_LOOPBACK)==0) - { -#if RAKNET_SUPPORT_IPV6==1 - if (boundAddressToSocket.GetIPVersion()==6) - { - FromString(IPV6_LOOPBACK,0,6); - } -#endif - -// if (boundAddressToSocket.GetIPVersion()==4) -// { -// // Some kind of bug with sendto: returns "The requested address is not valid in its context." if loopback doesn't have the same IP address -// address.addr4.sin_addr.s_addr=boundAddressToSocket.address.addr4.sin_addr.s_addr; -// } - } -} -bool SystemAddress::IsLANAddress(void) -{ -// return address.addr4.sin_addr.S_un.S_un_b.s_b1==10 || address.addr4.sin_addr.S_un.s_b1==192; -#if defined(__WIN32__) - return address.addr4.sin_addr.S_un.S_un_b.s_b1==10 || address.addr4.sin_addr.S_un.S_un_b.s_b1==192; -#else - return (address.addr4.sin_addr.s_addr >> 24) == 10 || (address.addr4.sin_addr.s_addr >> 24) == 192; -#endif -} -bool SystemAddress::SetBinaryAddress(const char *str, char portDelineator) -{ - size_t delimiterPos = 0; - size_t stringLength = strlen(str); - for (; delimiterPos < stringLength; ++delimiterPos) { - if (str[delimiterPos] == portDelineator) { - break; // found location of port delimiter - } - } - - if (NonNumericHostString(str)) { - //const char *ip = ( char* ) SocketLayer::DomainNameToIP( str ); - char ip[65]; - ip[0] = '\0'; - - // copy the plain hostname (excluding the (optional) port part) - // #med - change OP_NEW_ARRAY to support size_t type - char* hostname = OP_NEW_ARRAY(static_cast(delimiterPos + 1), _FILE_AND_LINE_); - strncpy_s(hostname, delimiterPos + 1, str, delimiterPos); - RakNetSocket2::DomainNameToIP(hostname, ip); - OP_DELETE_ARRAY(hostname, _FILE_AND_LINE_); - - if (ip[0] != '\0') { - inet_pton(AF_INET, ip, &address.addr4.sin_addr.s_addr); - } - else { - *this = UNASSIGNED_SYSTEM_ADDRESS; - return false; - } - } - else { - // Split the string into the first part, and the : part - char IPPart[22]; - // Only write the valid parts, don't change existing if invalid - // binaryAddress=UNASSIGNED_SYSTEM_ADDRESS.binaryAddress; - // port=UNASSIGNED_SYSTEM_ADDRESS.port; - size_t index = 0; - // #med - revise this --- if the hostname length > 22 we'd reject it rather than skipping what is beyond the max length... - for (; index < delimiterPos && index < 22; ++index) { - if (str[index] != '.' && (str[index] < '0' || str[index] > '9')) { - break; - } - IPPart[index] = str[index]; - } - IPPart[index] = '\0'; - if (index > 0) { - inet_pton(AF_INET, IPPart, &address.addr4.sin_addr.s_addr); - } - } - - char portPart[10]; - portPart[0] = '\0'; - if (str[delimiterPos] != '\0') { - size_t portIndex; - ++delimiterPos; // skip the delimiter - for (portIndex = 0; portIndex < 10 && str[delimiterPos] != '\0'; ++delimiterPos, ++portIndex) { - if (str[delimiterPos] < '0' || str[delimiterPos] > '9') { - break; - } - - portPart[portIndex] = str[delimiterPos]; - } - portPart[portIndex] = '\0'; - } - if (portPart[0] != '\0') { - // #med - missing / insufficient port range range - address.addr4.sin_port = htons((unsigned short)atoi(portPart)); - // #med - not set in IPv6 mode - debugPort = ntohs(address.addr4.sin_port); - } - return true; -} - -bool SystemAddress::FromString(const char *str, char portDelineator, int ipVersion) -{ -#if RAKNET_SUPPORT_IPV6!=1 - (void) ipVersion; - return SetBinaryAddress(str,portDelineator); -#else - if (str==0) - { - memset(&address,0,sizeof(address)); - address.addr4.sin_family=AF_INET; - return true; - } -#if RAKNET_SUPPORT_IPV6==1 - char ipPart[INET6_ADDRSTRLEN]; -#else - char ipPart[INET_ADDRSTRLEN]; -#endif - char portPart[32]; - - // TODO - what about 255.255.255.255? - if (ipVersion==4 && strcmp(str, IPV6_LOOPBACK) == 0) { - strcpy_s(ipPart,IPV4_LOOPBACK); - } - else if (ipVersion==6 && strcmp(str, IPV4_LOOPBACK) == 0) { - address.addr4.sin_family=AF_INET6; - strcpy_s(ipPart,IPV6_LOOPBACK); - } - - int i = 0; - for (; i < sizeof(ipPart) && str[i] != '\0'; ++i) { - if (str[i] == portDelineator) { - // #med - missing error checking, if portPart is non-numeric and/or exceeds max allowed port value - int j = 0; - ++i; // skip the delimiter - for (; j < sizeof(portPart) && str[i] != '\0'; ++i, ++j) { - portPart[j] = str[i]; - } - portPart[j] = '\0'; - i = i - j - 1; // reset the position to the last position, so the trailing '\0'-terminator is set correctly below - break; - } - ipPart[i] = str[i]; - } - ipPart[i] = '\0'; - - // needed for getaddrinfo - WSAStartupSingleton::AddRef(); - - // This could be a domain, or a printable address such as "192.0.2.1" or "2001:db8:63b3:1::3490" - // I want to convert it to its binary representation - addrinfo hints, *servinfo=0; - memset(&hints, 0, sizeof hints); - hints.ai_socktype = SOCK_DGRAM; - if (ipVersion==6) - hints.ai_family = AF_INET6; - else if (ipVersion==4) - hints.ai_family = AF_INET; - else - hints.ai_family = AF_UNSPEC; - INT error = getaddrinfo(ipPart, "", &hints, &servinfo); - if (servinfo==0 && error != 0) - { - if (ipVersion==6) - { - ipVersion=4; - hints.ai_family = AF_UNSPEC; - getaddrinfo(ipPart, "", &hints, &servinfo); - if (servinfo==0) - return false; - } - else - return false; - } - RakAssert(servinfo); - - unsigned short oldPort = address.addr4.sin_port; -#if RAKNET_SUPPORT_IPV6==1 - if (servinfo->ai_family == AF_INET) - { -// if (ipVersion==6) -// { -// address.addr4.sin_family=AF_INET6; -// memset(&address.addr6,0,sizeof(address.addr6)); -// memcpy(address.addr6.sin6_addr.s6_addr+12,&((struct sockaddr_in *)servinfo->ai_addr)->sin_addr.s_addr,sizeof(unsigned long)); -// } -// else -// { - address.addr4.sin_family=AF_INET; - memcpy(&address.addr4, (struct sockaddr_in *)servinfo->ai_addr,sizeof(struct sockaddr_in)); -// } - } - else - { - address.addr4.sin_family=AF_INET6; - memcpy(&address.addr6, (struct sockaddr_in6 *)servinfo->ai_addr,sizeof(struct sockaddr_in6)); - } -#else - address.addr4.sin_family=AF_INET4; - memcpy(&address.addr4, (struct sockaddr_in *)servinfo->ai_addr,sizeof(struct sockaddr_in)); -#endif - - freeaddrinfo(servinfo); // free the linked list - - // needed for getaddrinfo - WSAStartupSingleton::Deref(); - - // PORT - if (portPart[0]) - { - address.addr4.sin_port=htons((unsigned short) atoi(portPart)); - debugPort=ntohs(address.addr4.sin_port); - } - else - { - address.addr4.sin_port=oldPort; - } - - return true; -#endif // #if RAKNET_SUPPORT_IPV6!=1 -} -bool SystemAddress::FromStringExplicitPort(const char *str, unsigned short port, int ipVersion) -{ - bool b = FromString(str,(char) 0,ipVersion); - if (b==false) - { - *this=UNASSIGNED_SYSTEM_ADDRESS; - return false; - } - address.addr4.sin_port=htons(port); - debugPort=ntohs(address.addr4.sin_port); - return true; -} -void SystemAddress::CopyPort( const SystemAddress& right ) -{ - address.addr4.sin_port=right.address.addr4.sin_port; - debugPort=right.debugPort; -} -RakNetGUID::RakNetGUID() -{ - systemIndex=(SystemIndex)-1; - *this=UNASSIGNED_RAKNET_GUID; -} -bool RakNetGUID::operator==( const RakNetGUID& right ) const -{ - return g==right.g; -} -bool RakNetGUID::operator!=( const RakNetGUID& right ) const -{ - return g!=right.g; -} -bool RakNetGUID::operator > ( const RakNetGUID& right ) const -{ - return g > right.g; -} -bool RakNetGUID::operator < ( const RakNetGUID& right ) const -{ - return g < right.g; -} -void RakNetGUID::ToString(char *dest) const -{ - if (*this == UNASSIGNED_RAKNET_GUID) -#pragma warning(push) -#pragma warning(disable:4996) - strcpy(dest, "UNASSIGNED_RAKNET_GUID"); -#pragma warning(pop) - else - //sprintf_s(dest, destLength, "%u.%u.%u.%u.%u.%u", g[0], g[1], g[2], g[3], g[4], g[5]); -#pragma warning(push) -#pragma warning(disable:4996) - sprintf(dest, "%" PRINTF_64_BIT_MODIFIER "u", (long long unsigned int) g); -#pragma warning(pop) - // sprintf_s(dest, destLength, "%u.%u.%u.%u.%u.%u", g[0], g[1], g[2], g[3], g[4], g[5]); -} -void RakNetGUID::ToString(char *dest, size_t destLength) const -{ - if (*this==UNASSIGNED_RAKNET_GUID) - strcpy_s(dest, destLength, "UNASSIGNED_RAKNET_GUID"); - else - //sprintf_s(dest, destLength, "%u.%u.%u.%u.%u.%u", g[0], g[1], g[2], g[3], g[4], g[5]); - sprintf_s(dest, destLength, "%" PRINTF_64_BIT_MODIFIER "u", (long long unsigned int) g); - // sprintf_s(dest, destLength, "%u.%u.%u.%u.%u.%u", g[0], g[1], g[2], g[3], g[4], g[5]); -} -bool RakNetGUID::FromString(const char *source) -{ - if (source==0) - return false; - -#if defined(WIN32) - g=_strtoui64(source, nullptr, 10); -#else - // Changed from g=strtoull(source,0,10); for android - g=strtoull(source, nullptr, 10); -#endif - return true; - -} -unsigned long RakNetGUID::ToUint32( const RakNetGUID &g ) -{ - return ((unsigned long) (g.g >> 32)) ^ ((unsigned long) (g.g & 0xFFFFFFFF)); -} - -namespace MafiaNet -{ - // initialization list -#ifndef SWIG - const SystemAddress UNASSIGNED_SYSTEM_ADDRESS; - const RakNetGUID UNASSIGNED_RAKNET_GUID((uint64_t)-1); -#endif -} \ No newline at end of file diff --git a/vendors/mafianet/Source/src/RakPeer.cpp b/vendors/mafianet/Source/src/RakPeer.cpp deleted file mode 100644 index 0eb9550b7..000000000 --- a/vendors/mafianet/Source/src/RakPeer.cpp +++ /dev/null @@ -1,6571 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -// \file -// - - - -#define CAT_NEUTER_EXPORT /* Neuter dllimport for libcat */ - -#include "mafianet/defines.h" -#include "mafianet/peer.h" -#include "mafianet/types.h" - -#ifdef _WIN32 - -#else -#include -#endif - -// #if defined(new) -// #pragma push_macro("new") -// #undef new -// #define RMO_NEW_UNDEF_ALLOCATING_QUEUE -// #endif - -#include -#include // toupper -#include -#include "mafianet/GetTime.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/DS_HuffmanEncodingTree.h" -#include "mafianet/Rand.h" -#include "mafianet/PluginInterface2.h" -#include "mafianet/StringCompressor.h" -#include "mafianet/StringTable.h" -#include "mafianet/NetworkIDObject.h" -#include "mafianet/types.h" -#include "mafianet/DR_SHA1.h" -#include "mafianet/sleep.h" -#include "mafianet/assert.h" -#include "mafianet/version.h" -#include "mafianet/NetworkIDManager.h" -#include "mafianet/gettimeofday.h" -#include "mafianet/SignaledEvent.h" -#include "mafianet/SuperFastHash.h" -#include "mafianet/alloca.h" -#include "mafianet/WSAStartupSingleton.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -#ifdef USE_THREADED_SEND -#include "mafianet/SendToThread.h" -#endif - -#ifdef CAT_AUDIT -#define CAT_AUDIT_PRINTF(...) printf(__VA_ARGS__) -#else -#define CAT_AUDIT_PRINTF(...) -#endif - -namespace MafiaNet -{ -RAK_THREAD_DECLARATION(UpdateNetworkLoop); -RAK_THREAD_DECLARATION(RecvFromLoop); -RAK_THREAD_DECLARATION(UDTConnect); -} -#define REMOTE_SYSTEM_LOOKUP_HASH_MULTIPLE 8 - -#if !defined ( __APPLE__ ) && !defined ( __APPLE_CC__ ) -#include // malloc -#endif - - - -#if defined(_WIN32) -// -#else -/* -#include // Console 2 -#include -extern bool _extern_Console2LoadModules(void); -extern int _extern_Console2GetConnectionStatus(void); -extern int _extern_Console2GetLobbyStatus(void); -//extern bool Console2StartupFluff(unsigned int *); -extern void Console2ShutdownFluff(void); -//extern unsigned int Console2ActivateConnection(unsigned int, void *); -//extern bool Console2BlockOnEstablished(void); -extern void Console2GetIPAndPort(unsigned int, char *, unsigned short *, unsigned int ); -//extern void Console2DeactivateConnection(unsigned int, unsigned int); -*/ -#endif - - -static const int NUM_MTU_SIZES=3; - - - -static const int mtuSizes[NUM_MTU_SIZES]={MAXIMUM_MTU_SIZE, 1200, 576}; - - -// Note to self - if I change this it might affect RECIPIENT_OFFLINE_MESSAGE_INTERVAL in Natpunchthrough.cpp -//static const int MAX_OPEN_CONNECTION_REQUESTS=8; -//static const int TIME_BETWEEN_OPEN_CONNECTION_REQUESTS=500; - -using namespace MafiaNet; - -static RakNetRandom rnr; - -/* -struct RakPeerAndIndex -{ - RakNetSocket2 *s; - RakPeer *rakPeer; -}; -*/ - -static const unsigned int MAX_OFFLINE_DATA_LENGTH=400; // I set this because I limit ID_CONNECTION_REQUEST to 512 bytes, and the password is appended to that packet. - -// Used to distinguish between offline messages with data, and messages from the reliability layer -// Should be different than any message that could result from messages from the reliability layer -// Make sure highest bit is 0, so isValid in DatagramHeaderFormat is false -static const unsigned char OFFLINE_MESSAGE_DATA_ID[16]={0x00,0xFF,0xFF,0x00,0xFE,0xFE,0xFE,0xFE,0xFD,0xFD,0xFD,0xFD,0x12,0x34,0x56,0x78}; - -struct PacketFollowedByData -{ - Packet p; - unsigned char data[1]; -}; - -Packet *RakPeer::AllocPacket(unsigned dataSize, const char *file, unsigned int line) -{ - // Crashes when dataSize is 4 bytes - not sure why -// unsigned char *data = (unsigned char *) rakMalloc_Ex(sizeof(PacketFollowedByData)+dataSize, file, line); -// Packet *p = &((PacketFollowedByData *)data)->p; -// p->data=((PacketFollowedByData *)data)->data; -// p->length=dataSize; -// p->bitSize=BYTES_TO_BITS(dataSize); -// p->deleteData=false; -// p->guid=UNASSIGNED_RAKNET_GUID; -// return p; - - MafiaNet::Packet *p; - packetAllocationPoolMutex.Lock(); - p = packetAllocationPool.Allocate(file,line); - packetAllocationPoolMutex.Unlock(); - p = new ((void*)p) Packet; - p->data=(unsigned char*) rakMalloc_Ex(dataSize,file,line); - p->length=dataSize; - p->bitSize=BYTES_TO_BITS(dataSize); - p->deleteData=true; - p->guid=UNASSIGNED_RAKNET_GUID; - p->wasGeneratedLocally=false; - return p; -} - -Packet *RakPeer::AllocPacket(unsigned dataSize, unsigned char *data, const char *file, unsigned int line) -{ - // Packet *p = (Packet *)rakMalloc_Ex(sizeof(Packet), file, line); - MafiaNet::Packet *p; - packetAllocationPoolMutex.Lock(); - p = packetAllocationPool.Allocate(file,line); - packetAllocationPoolMutex.Unlock(); - p = new ((void*)p) Packet; - RakAssert(p); - p->data=data; - p->length=dataSize; - p->bitSize=BYTES_TO_BITS(dataSize); - p->deleteData=true; - p->guid=UNASSIGNED_RAKNET_GUID; - p->wasGeneratedLocally=false; - return p; -} - -STATIC_FACTORY_DEFINITIONS(RakPeerInterface,RakPeer) - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Constructor -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -RakPeer::RakPeer() -{ -#if LIBCAT_SECURITY==1 - // Encryption and security - CAT_AUDIT_PRINTF("AUDIT: Initializing RakPeer security flags: using_security = false, server_handshake = null, cookie_jar = null\n"); - _using_security = false; - _server_handshake = 0; - _cookie_jar = 0; -#endif - - StringCompressor::AddReference(); - MafiaNet::StringTable::AddReference(); - WSAStartupSingleton::AddRef(); - - defaultMTUSize = mtuSizes[NUM_MTU_SIZES-1]; - trackFrequencyTable = false; - maximumIncomingConnections = 0; - maximumNumberOfPeers = 0; - //remoteSystemListSize=0; - remoteSystemList = 0; - activeSystemList = 0; - activeSystemListSize=0; - remoteSystemLookup=0; - bytesSentPerSecond = bytesReceivedPerSecond = 0; - endThreads = true; - isMainLoopThreadActive = false; - incomingDatagramEventHandler=0; - - - - - - // isRecvfromThreadActive=false; -#if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 - occasionalPing = true; -#else - occasionalPing = false; -#endif - allowInternalRouting=false; - for (unsigned int i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) - ipList[i]=UNASSIGNED_SYSTEM_ADDRESS; - allowConnectionResponseIPMigration = false; - //incomingPasswordLength=outgoingPasswordLength=0; - incomingPasswordLength=0; - splitMessageProgressInterval=0; - //unreliableTimeout=0; - unreliableTimeout=1000; - maxOutgoingBPS=0; - firstExternalID=UNASSIGNED_SYSTEM_ADDRESS; - myGuid=UNASSIGNED_RAKNET_GUID; - userUpdateThreadPtr=0; - userUpdateThreadData=0; - -#ifdef _DEBUG - // Wait longer to disconnect in debug so I don't get disconnected while tracing - defaultTimeoutTime=30000; -#else - defaultTimeoutTime=10000; -#endif - -#ifdef _DEBUG - _packetloss=0.0; - _minExtraPing=0; - _extraPingVariance=0; -#endif - - bufferedCommands.SetPageSize(sizeof(BufferedCommandStruct)*16); - socketQueryOutput.SetPageSize(sizeof(SocketQueryOutput)*8); - - packetAllocationPoolMutex.Lock(); - packetAllocationPool.SetPageSize(sizeof(DataStructures::MemoryPool::MemoryWithPage)*32); - packetAllocationPoolMutex.Unlock(); - - remoteSystemIndexPool.SetPageSize(sizeof(DataStructures::MemoryPool::MemoryWithPage)*32); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - GenerateGUID(); - - quitAndDataEvents.InitEvent(); - limitConnectionFrequencyFromTheSameIP=false; - ResetSendReceipt(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Destructor -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -RakPeer::~RakPeer() -{ - Shutdown( 0, 0 ); - - // Free the ban list. - ClearBanList(); - - StringCompressor::RemoveReference(); - MafiaNet::StringTable::RemoveReference(); - WSAStartupSingleton::Deref(); - - quitAndDataEvents.CloseEvent(); - -#if LIBCAT_SECURITY==1 - // Encryption and security - CAT_AUDIT_PRINTF("AUDIT: Deleting RakPeer security objects, handshake = %x, cookie jar = %x\n", _server_handshake, _cookie_jar); - if (_server_handshake) MafiaNet::OP_DELETE(_server_handshake,_FILE_AND_LINE_); - if (_cookie_jar) MafiaNet::OP_DELETE(_cookie_jar,_FILE_AND_LINE_); -#endif - - - - - - - - - - - - - - - - -// for (unsigned int i=0; i < pluginListTS.Size(); i++) -// pluginListTS[i]->SetRakPeerInterface(0); -// for (unsigned int i=0; i < pluginListNTS.Size(); i++) -// pluginListNTS[i]->SetRakPeerInterface(0); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// \brief Starts the network threads, opens the listen port. -// You must call this before calling Connect(). -// Multiple calls while already active are ignored. To call this function again with different settings, you must first call Shutdown(). -// \note Call SetMaximumIncomingConnections if you want to accept incoming connections -// \param[in] maxConnections The maximum number of connections between this instance of RakPeer and another instance of RakPeer. Required so the network can preallocate and for thread safety. A pure client would set this to 1. A pure server would set it to the number of allowed clients.- A hybrid would set it to the sum of both types of connections -// \param[in] localPort The port to listen for connections on. -// \param[in] _threadSleepTimer How many ms to Sleep each internal update cycle. With new congestion control, the best results will be obtained by passing 10. -// \param[in] socketDescriptors An array of SocketDescriptor structures to force RakNet to listen on a particular IP address or port (or both). Each SocketDescriptor will represent one unique socket. Do not pass redundant structures. To listen on a specific port, you can pass &socketDescriptor, 1SocketDescriptor(myPort,0); such as for a server. For a client, it is usually OK to just pass SocketDescriptor(); -// \param[in] socketDescriptorCount The size of the \a socketDescriptors array. Pass 1 if you are not sure what to pass. -// \return False on failure (can't create socket or thread), true on success. -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -StartupResult RakPeer::Startup( unsigned int maxConnections, SocketDescriptor *socketDescriptors, unsigned socketDescriptorCount, int threadPriority ) -{ - if (IsActive()) - return RAKNET_ALREADY_STARTED; - - // If getting the guid failed in the constructor, try again - if (myGuid.g==0) - { - GenerateGUID(); - if (myGuid.g==0) - return COULD_NOT_GENERATE_GUID; - } - - if (threadPriority==-99999) - { - - -#if defined(_WIN32) - threadPriority=0; - - - - -#else - threadPriority=1000; -#endif - } - - - FillIPList(); - - if (myGuid==UNASSIGNED_RAKNET_GUID) - { - rnr.SeedMT( GenerateSeedFromGuid() ); - } - - //RakPeerAndIndex rpai[32]; - //RakAssert(socketDescriptorCount<32); - - RakAssert(socketDescriptors && socketDescriptorCount>=1); - - if (socketDescriptors==0 || socketDescriptorCount<1) - return INVALID_SOCKET_DESCRIPTORS; - - //unsigned short localPort; - //localPort=socketDescriptors[0].port; - - RakAssert( maxConnections > 0 ); - - if ( maxConnections <= 0 ) - return INVALID_MAX_CONNECTIONS; - - DerefAllSockets(); - - - unsigned i; - // Go through all socket descriptors and precreate sockets on the specified addresses - for (i=0; iSetUserConnectionSocketIndex(i); - #if defined(__native_client__) - NativeClientBindParameters ncbp; - RNS2_NativeClient * nativeClientSocket = (RNS2_NativeClient*) r2; - ncbp.eventHandler=this; - ncbp.forceHostAddress=(char*) socketDescriptors[i].hostAddress; - ncbp.is_ipv6=socketDescriptors[i].socketFamily==AF_INET6; - ncbp.nativeClientInstance=socketDescriptors[i].chromeInstance; - ncbp.port=socketDescriptors[i].port; - nativeClientSocket->Bind(&ncbp, _FILE_AND_LINE_); - #else - if (r2->IsBerkleySocket()) - { - RNS2_BerkleyBindParameters bbp; - bbp.port=socketDescriptors[i].port; - bbp.hostAddress=(char*) socketDescriptors[i].hostAddress; - bbp.addressFamily=socketDescriptors[i].socketFamily; - bbp.type=SOCK_DGRAM; - bbp.protocol=socketDescriptors[i].extraSocketOptions; - bbp.nonBlockingSocket=false; - bbp.setBroadcast=true; - bbp.setIPHdrIncl=false; - bbp.doNotFragment=false; - bbp.pollingThreadPriority=threadPriority; - bbp.eventHandler=this; - bbp.remotePortRakNetWasStartedOn_PS3_PS4_PSP2=socketDescriptors[i].remotePortRakNetWasStartedOn_PS3_PSP2; - RNS2BindResult br = ((RNS2_Berkley*) r2)->Bind(&bbp, _FILE_AND_LINE_); - - if ( - #if RAKNET_SUPPORT_IPV6==0 - socketDescriptors[i].socketFamily!=AF_INET || - #endif - br==BR_REQUIRES_RAKNET_SUPPORT_IPV6_DEFINE) - { - RakNetSocket2Allocator::DeallocRNS2(r2); - DerefAllSockets(); - return SOCKET_FAMILY_NOT_SUPPORTED; - } - else if (br==BR_FAILED_TO_BIND_SOCKET) - { - RakNetSocket2Allocator::DeallocRNS2(r2); - DerefAllSockets(); - return SOCKET_PORT_ALREADY_IN_USE; - } - else if (br==BR_FAILED_SEND_TEST) - { - RakNetSocket2Allocator::DeallocRNS2(r2); - DerefAllSockets(); - return SOCKET_FAILED_TEST_SEND; - } - else - { - RakAssert(br==BR_SUCCESS); - } - } - else - { - RakAssert("TODO" && 0); - } - #endif -/* - - SystemAddress saOut; - SocketLayer::GetSystemAddress( rns, &saOut ); - rns->SetBoundAddress(saOut); - rns->SetRemotePortRakNetWasStartedOn(socketDescriptors[i].remotePortRakNetWasStartedOn_PS3_PSP2); - rns->SetChromeInstance(socketDescriptors[i].chromeInstance); - rns->SetExtraSocketOptions(socketDescriptors[i].extraSocketOptions); - rns->SetUserConnectionSocketIndex(i); - rns->SetBlockingSocket(socketDescriptors[i].blockingSocket); - -#if RAKNET_SUPPORT_IPV6==0 - if (addrToBind==0) - rns->SetBoundAddressToLoopback(4); -#endif - - // GetBoundAddress is asynch, which isn't supported by this architecture -#if !defined(__native_client__) - int zero=0; - if (SocketLayer::SendTo(rns, (const char*) &zero,4, rns->GetBoundAddress(), _FILE_AND_LINE_)!=0) - { - DerefAllSockets(); - return SOCKET_FAILED_TEST_SEND; - } -#endif - */ - - socketList.Push(r2, _FILE_AND_LINE_ ); - - } - -#if !defined(__native_client__) - for (i=0; iIsBerkleySocket()) - ((RNS2_Berkley*) socketList[i])->CreateRecvPollingThread(threadPriority); - } -#endif - - for (i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) - { - if (ipList[i]==UNASSIGNED_SYSTEM_ADDRESS) - break; -#if !defined(__native_client__) - // #high - using the 1st socket here is flawed - in cases of having multiple sockets (f.e. different ports and different families (i.e. IPv4/IPv6) we must use the proper - // socket for each IP address in the list - if (socketList[0]->IsBerkleySocket()) - { - unsigned short port = ((RNS2_Berkley*)socketList[0])->GetBoundAddress().GetPort(); - ipList[i].SetPortHostOrder(port); - - } -#endif -// ipList[i].SetPort(((RNS2_360_720*)socketList[0])->GetBoundAddress().GetPort()); - } - - if ( maximumNumberOfPeers == 0 ) - { - // Don't allow more incoming connections than we have peers. - if ( maximumIncomingConnections > maxConnections ) - maximumIncomingConnections = maxConnections; - - maximumNumberOfPeers = maxConnections; - // 04/19/2006 - Don't overallocate because I'm no longer allowing connected pings. - // The disconnects are not consistently processed and the process was sloppy and complicated. - // Allocate 10% extra to handle new connections from players trying to connect when the server is full - //remoteSystemListSize = maxConnections;// * 11 / 10 + 1; - - // remoteSystemList in Single thread - //remoteSystemList = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - remoteSystemList = MafiaNet::OP_NEW_ARRAY(maximumNumberOfPeers, _FILE_AND_LINE_ ); - - remoteSystemLookup = MafiaNet::OP_NEW_ARRAY((unsigned int) maximumNumberOfPeers * REMOTE_SYSTEM_LOOKUP_HASH_MULTIPLE, _FILE_AND_LINE_ ); - - activeSystemList = MafiaNet::OP_NEW_ARRAY(maximumNumberOfPeers, _FILE_AND_LINE_ ); - - for ( i = 0; i < maximumNumberOfPeers; i++ ) - //for ( i = 0; i < remoteSystemListSize; i++ ) - { - // remoteSystemList in Single thread - remoteSystemList[ i ].isActive = false; - remoteSystemList[ i ].systemAddress = UNASSIGNED_SYSTEM_ADDRESS; - remoteSystemList[ i ].guid = UNASSIGNED_RAKNET_GUID; - remoteSystemList[ i ].myExternalSystemAddress = UNASSIGNED_SYSTEM_ADDRESS; - remoteSystemList[ i ].connectMode=RemoteSystemStruct::NO_ACTION; - remoteSystemList[ i ].MTUSize = defaultMTUSize; - remoteSystemList[ i ].remoteSystemIndex = (SystemIndex) i; - // One-time zero-init: the array is OP_NEW_ARRAY allocated with no member init, so prime the - // reason-payload fields here before ClearDisconnectReason() can ever free them. - remoteSystemList[ i ].disconnectReasonData = 0; - remoteSystemList[ i ].disconnectReasonLength = 0; -#ifdef _DEBUG - remoteSystemList[ i ].reliabilityLayer.ApplyNetworkSimulator(_packetloss, _minExtraPing, _extraPingVariance); -#endif - - // All entries in activeSystemList have valid pointers all the time. - activeSystemList[ i ] = &remoteSystemList[ i ]; - } - - for (i=0; i < (unsigned int) maximumNumberOfPeers*REMOTE_SYSTEM_LOOKUP_HASH_MULTIPLE; i++) - { - remoteSystemLookup[i]=0; - } - } - - // For histogram statistics - // nextReadBytesTime=0; - // lastSentBytes=lastReceivedBytes=0; - - if ( endThreads ) - { - updateCycleIsRunning = false; - endThreads = false; - firstExternalID=UNASSIGNED_SYSTEM_ADDRESS; - - ClearBufferedCommands(); - ClearBufferedPackets(); - ClearSocketQueryOutput(); - - if ( isMainLoopThreadActive == false ) - { -#if RAKPEER_USER_THREADED!=1 - - int errorCode; - - - - - - - - errorCode = MafiaNet::RakThread::Create(UpdateNetworkLoop, this, threadPriority); - - - if ( errorCode != 0 ) - { - Shutdown( 0, 0 ); - return FAILED_TO_CREATE_NETWORK_THREAD; - } -// RakAssert(isRecvFromLoopThreadActive.GetValue()==0); -#endif // RAKPEER_USER_THREADED!=1 - - /* - for (i=0; i(_FILE_AND_LINE_); - rpai->s=socketList[i]; - rpai->rakPeer=this; - -#if RAKPEER_USER_THREADED!=1 - - #if defined(SN_TARGET_PSP2) - sprintf_s(threadName, "RecvFromLoop_%p", this); - //errorCode = MafiaNet::RakThread::Create(RecvFromLoop, rpai, threadPriority, threadName, 1+i, runtime); - errorCode = MafiaNet::RakThread::Create(RecvFromLoop, rpai, threadPriority, threadName, 1024*1); - #else - errorCode = MafiaNet::RakThread::Create(RecvFromLoop, rpai, threadPriority); - #endif - - if ( errorCode != 0 ) - { - Shutdown( 0, 0 ); - return FAILED_TO_CREATE_NETWORK_THREAD; - } -#endif // RAKPEER_USER_THREADED!=1 - } - */ - - - /* -#if RAKPEER_USER_THREADED!=1 - - while ( isRecvFromLoopThreadActive.GetValue() < (uint32_t) socketDescriptorCount ) - RakSleep(10); - #endif // RAKPEER_USER_THREADED!=1 - */ - - } - -#if RAKPEER_USER_THREADED!=1 - // Wait for the threads to activate. When they are active they will set these variables to true - while ( isMainLoopThreadActive == false ) - RakSleep(10); -#endif // RAKPEER_USER_THREADED!=1 - } - - for (i=0; i < pluginListTS.Size(); i++) - { - pluginListTS[i]->OnRakPeerStartup(); - } - - for (i=0; i < pluginListNTS.Size(); i++) - { - pluginListNTS[i]->OnRakPeerStartup(); - } - -#ifdef USE_THREADED_SEND - MafiaNet::SendToThread::AddRef(); -#endif - - return RAKNET_STARTED; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Must be called while offline -// -// If you accept connections, you must call this or else security will not be enabled for incoming connections. -// -// This feature requires more round trips, bandwidth, and CPU time for the connection handshake -// x64 builds require under 25% of the CPU time of other builds -// -// See the Encryption sample for example usage -// -// Parameters: -// publicKey = A pointer to the public key for accepting new connections -// privateKey = A pointer to the private key for accepting new connections -// If the private keys are 0, then a new key will be generated when this function is called -// bRequireClientKey: Should be set to false for most servers. Allows the server to accept a public key from connecting clients as a proof of identity but eats twice as much CPU time as a normal connection -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -bool RakPeer::InitializeSecurity(const char *public_key, const char *private_key, bool bRequireClientKey) -{ -#if LIBCAT_SECURITY==1 - if ( endThreads == false ) - return false; - - // Copy client public key requirement flag - _require_client_public_key = bRequireClientKey; - - if (_server_handshake) - { - CAT_AUDIT_PRINTF("AUDIT: Deleting old server_handshake %x\n", _server_handshake); - MafiaNet::OP_DELETE(_server_handshake,_FILE_AND_LINE_); - } - if (_cookie_jar) - { - CAT_AUDIT_PRINTF("AUDIT: Deleting old cookie jar %x\n", _cookie_jar); - MafiaNet::OP_DELETE(_cookie_jar,_FILE_AND_LINE_); - } - - _server_handshake = MafiaNet::OP_NEW(_FILE_AND_LINE_); - _cookie_jar = MafiaNet::OP_NEW(_FILE_AND_LINE_); - - CAT_AUDIT_PRINTF("AUDIT: Created new server_handshake %x\n", _server_handshake); - CAT_AUDIT_PRINTF("AUDIT: Created new cookie jar %x\n", _cookie_jar); - CAT_AUDIT_PRINTF("AUDIT: Running _server_handshake->Initialize()\n"); - - if (_server_handshake->Initialize(public_key, private_key)) - { - CAT_AUDIT_PRINTF("AUDIT: Successfully initialized, filling cookie jar with goodies, storing public key and setting using security flag to true\n"); - - _server_handshake->FillCookieJar(_cookie_jar); - - memcpy(my_public_key, public_key, sizeof(my_public_key)); - - _using_security = true; - return true; - } - - CAT_AUDIT_PRINTF("AUDIT: Failure to initialize so deleting server handshake and cookie jar; also setting using_security flag = false\n"); - - MafiaNet::OP_DELETE(_server_handshake,_FILE_AND_LINE_); - _server_handshake=0; - MafiaNet::OP_DELETE(_cookie_jar,_FILE_AND_LINE_); - _cookie_jar=0; - _using_security = false; - return false; -#else - (void) public_key; - (void) private_key; - (void) bRequireClientKey; - - return false; -#endif -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description -// Must be called while offline -// Disables security for incoming connections. -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::DisableSecurity( void ) -{ -#if LIBCAT_SECURITY==1 - CAT_AUDIT_PRINTF("AUDIT: DisableSecurity() called, so deleting _server_handshake %x and cookie_jar %x\n", _server_handshake, _cookie_jar); - MafiaNet::OP_DELETE(_server_handshake,_FILE_AND_LINE_); - _server_handshake=0; - MafiaNet::OP_DELETE(_cookie_jar,_FILE_AND_LINE_); - _cookie_jar=0; - - _using_security = false; -#endif -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::AddToSecurityExceptionList(const char *ip) -{ - securityExceptionMutex.Lock(); - securityExceptionList.Insert(RakString(ip), _FILE_AND_LINE_); - securityExceptionMutex.Unlock(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::RemoveFromSecurityExceptionList(const char *ip) -{ - if (securityExceptionList.Size()==0) - return; - - if (ip==0) - { - securityExceptionMutex.Lock(); - securityExceptionList.Clear(false, _FILE_AND_LINE_); - securityExceptionMutex.Unlock(); - } - else - { - unsigned i=0; - securityExceptionMutex.Lock(); - while (i < securityExceptionList.Size()) - { - if (securityExceptionList[i].IPAddressMatch(ip)) - { - securityExceptionList[i]=securityExceptionList[securityExceptionList.Size()-1]; - securityExceptionList.RemoveAtIndex(securityExceptionList.Size()-1); - } - else - i++; - } - securityExceptionMutex.Unlock(); - } -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -bool RakPeer::IsInSecurityExceptionList(const char *ip) -{ - if (securityExceptionList.Size()==0) - return false; - - unsigned i=0; - securityExceptionMutex.Lock(); - for (; i < securityExceptionList.Size(); i++) - { - if (securityExceptionList[i].IPAddressMatch(ip)) - { - securityExceptionMutex.Unlock(); - return true; - } - } - securityExceptionMutex.Unlock(); - return false; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Sets how many incoming connections are allowed. If this is less than the number of players currently connected, no -// more players will be allowed to connect. If this is greater than the maximum number of peers allowed, it will be reduced -// to the maximum number of peers allowed. Defaults to 0. -// -// Parameters: -// numberAllowed - Maximum number of incoming connections allowed. -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::SetMaximumIncomingConnections( unsigned short numberAllowed ) -{ - maximumIncomingConnections = numberAllowed; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Returns the maximum number of incoming connections, which is always <= maxConnections -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -unsigned int RakPeer::GetMaximumIncomingConnections( void ) const -{ - return maximumIncomingConnections; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Returns how many open connections there are at this time -// \return the number of open connections -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -unsigned short RakPeer::NumberOfConnections(void) const -{ - DataStructures::List addresses; - DataStructures::List guids; - GetSystemList(addresses, guids); - return (unsigned short) addresses.Size(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Sets the password incoming connections must match in the call to Connect (defaults to none) -// Pass 0 to passwordData to specify no password -// -// Parameters: -// passwordData: A data block that incoming connections must match. This can be just a password, or can be a stream of data. -// - Specify 0 for no password data -// passwordDataLength: The length in bytes of passwordData -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::SetIncomingPassword( const char* passwordData, int passwordDataLength ) -{ - //if (passwordDataLength > MAX_OFFLINE_DATA_LENGTH) - // passwordDataLength=MAX_OFFLINE_DATA_LENGTH; - - if (passwordDataLength > 255) - passwordDataLength=255; - - if (passwordData==0) - passwordDataLength=0; - - // Not threadsafe but it's not important enough to lock. Who is going to change the password a lot during runtime? - // It won't overflow at least because incomingPasswordLength is an unsigned char - if (passwordDataLength>0) - memcpy(incomingPassword, passwordData, passwordDataLength); - incomingPasswordLength=(unsigned char)passwordDataLength; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::GetIncomingPassword( char* passwordData, int *passwordDataLength ) -{ - if (passwordData==0) - { - *passwordDataLength=incomingPasswordLength; - return; - } - - if (*passwordDataLength > incomingPasswordLength) - *passwordDataLength=incomingPasswordLength; - - if (*passwordDataLength>0) - memcpy(passwordData, incomingPassword, *passwordDataLength); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Call this to connect to the specified host (ip or domain name) and server port. -// Calling Connect and not calling SetMaximumIncomingConnections acts as a dedicated client. Calling both acts as a true peer. -// This is a non-blocking connection. You know the connection is successful when IsConnected() returns true -// or receive gets a packet with the type identifier ID_CONNECTION_REQUEST_ACCEPTED. If the connection is not -// successful, such as rejected connection or no response then neither of these things will happen. -// Requires that you first call Initialize -// -// Parameters: -// host: Either a dotted IP address or a domain name -// remotePort: Which port to connect to on the remote machine. -// passwordData: A data block that must match the data block on the server. This can be just a password, or can be a stream of data -// passwordDataLength: The length in bytes of passwordData -// -// Returns: -// True on successful initiation. False on incorrect parameters, internal error, or too many existing peers -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -ConnectionAttemptResult RakPeer::Connect( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, PublicKey *publicKey, unsigned connectionSocketIndex, unsigned sendConnectionAttemptCount, unsigned timeBetweenSendConnectionAttemptsMS, MafiaNet::TimeMS timeoutTime ) -{ - // If endThreads is true here you didn't call Startup() first. - if ( host == 0 || endThreads || connectionSocketIndex>=socketList.Size() ) - return INVALID_PARAMETER; - - RakAssert(remotePort!=0); - - connectionSocketIndex=GetRakNetSocketFromUserConnectionSocketIndex(connectionSocketIndex); - - if (passwordDataLength>255) - passwordDataLength=255; - - if (passwordData==0) - passwordDataLength=0; - - // Not threadsafe but it's not important enough to lock. Who is going to change the password a lot during runtime? - // It won't overflow at least because outgoingPasswordLength is an unsigned char -// if (passwordDataLength>0) -// memcpy(outgoingPassword, passwordData, passwordDataLength); -// outgoingPasswordLength=(unsigned char) passwordDataLength; - - // 04/02/09 - Can't remember why I disabled connecting to self, but it seems to work - // Connecting to ourselves in the same instance of the program? -// if ( ( strcmp( host, "127.0.0.1" ) == 0 || strcmp( host, "0.0.0.0" ) == 0 ) && remotePort == mySystemAddress[0].port ) -// return false; - - return SendConnectionRequest( host, remotePort, passwordData, passwordDataLength, publicKey, connectionSocketIndex, 0, sendConnectionAttemptCount, timeBetweenSendConnectionAttemptsMS, timeoutTime); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -ConnectionAttemptResult RakPeer::ConnectWithSocket(const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, RakNetSocket2* socket, PublicKey *publicKey, unsigned sendConnectionAttemptCount, unsigned timeBetweenSendConnectionAttemptsMS, MafiaNet::TimeMS timeoutTime) -{ - if ( host == 0 || endThreads || socket == 0 ) - return INVALID_PARAMETER; - - if (passwordDataLength>255) - passwordDataLength=255; - - if (passwordData==0) - passwordDataLength=0; - - return SendConnectionRequest( host, remotePort, passwordData, passwordDataLength, publicKey, 0, 0, sendConnectionAttemptCount, timeBetweenSendConnectionAttemptsMS, timeoutTime, socket ); - -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Stops the network threads and close all connections. Multiple calls are ok. -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::Shutdown( unsigned int blockDuration, unsigned char orderingChannel, MafiaNet::Priority disconnectionNotificationPriority ) -{ - unsigned i,j; - bool anyActive; - MafiaNet::TimeMS startWaitingTime; -// SystemAddress systemAddress; - MafiaNet::TimeMS time; - //unsigned short systemListSize = remoteSystemListSize; // This is done for threading reasons - unsigned int systemListSize = maximumNumberOfPeers; - - if ( blockDuration > 0 ) - { - for ( i = 0; i < systemListSize; i++ ) - { - // remoteSystemList in user thread - if (remoteSystemList[i].isActive) - NotifyAndFlagForShutdown(remoteSystemList[i].systemAddress, false, orderingChannel, disconnectionNotificationPriority); - } - - time = MafiaNet::GetTimeMS(); - startWaitingTime = time; - while ( time - startWaitingTime < blockDuration ) - { - anyActive=false; - for (j=0; j < systemListSize; j++) - { - // remoteSystemList in user thread - if (remoteSystemList[j].isActive) - { - anyActive=true; - break; - } - } - - // If this system is out of packets to send, then stop waiting - if ( anyActive==false ) - break; - - // This will probably cause the update thread to run which will probably - // send the disconnection notification - - RakSleep(15); - time = MafiaNet::GetTimeMS(); - } - } - for (i=0; i < pluginListTS.Size(); i++) - { - pluginListTS[i]->OnRakPeerShutdown(); - } - for (i=0; i < pluginListNTS.Size(); i++) - { - pluginListNTS[i]->OnRakPeerShutdown(); - } - - quitAndDataEvents.SetEvent(); - - endThreads = true; - -// MafiaNet::TimeMS timeout; -#if RAKPEER_USER_THREADED!=1 - -#if !defined(__native_client__) - for (i=0; i < socketList.Size(); i++) - { - if (socketList[i]->IsBerkleySocket()) - { - ((RNS2_Berkley *)socketList[i])->SignalStopRecvPollingThread(); - } - } -#endif - - /* - // Get recvfrom to unblock - for (i=0; i < socketList.Size(); i++) - { - if (SocketLayer::SendTo(socketList[i], (const char*) &i,1,socketList[i]->GetBoundAddress(), _FILE_AND_LINE_)!=0) - break; - } - */ - - while ( isMainLoopThreadActive ) - { - RakSleep(15); - } - - activeSystemListSize = 0; - - /* - timeout = MafiaNet::GetTimeMS()+1000; - while ( isRecvFromLoopThreadActive.GetValue()>0 && MafiaNet::GetTimeMS()GetBoundAddress(), _FILE_AND_LINE_); - } - - RakSleep(30); - } - */ - -#if !defined(__native_client__) - for (i=0; i < socketList.Size(); i++) - { - if (socketList[i]->IsBerkleySocket()) - { - ((RNS2_Berkley *)socketList[i])->BlockOnStopRecvPollingThread(); - } - } -#endif - - -#endif // RAKPEER_USER_THREADED!=1 - -// char c=0; -// unsigned int socketIndex; - // remoteSystemList in Single thread - for ( i = 0; i < systemListSize; i++ ) - { - // Reserve this reliability layer for ourselves - remoteSystemList[ i ].isActive = false; - - // Remove any remaining packets - RakAssert(remoteSystemList[ i ].MTUSize <= MAXIMUM_MTU_SIZE); - remoteSystemList[ i ].reliabilityLayer.Reset(false, remoteSystemList[ i ].MTUSize, false); - remoteSystemList[ i ].rakNetSocket = 0; - ClearDisconnectReason(&remoteSystemList[ i ]); - } - - - // Setting maximumNumberOfPeers to 0 allows remoteSystemList to be reallocated in Initialize. - // Setting remoteSystemListSize prevents threads from accessing the reliability layer - maximumNumberOfPeers = 0; - //remoteSystemListSize = 0; - - // Free any packets the user didn't deallocate - packetReturnMutex.Lock(); - for (i=0; i < packetReturnQueue.Size(); i++) - DeallocatePacket(packetReturnQueue[i]); - packetReturnQueue.Clear(_FILE_AND_LINE_); - packetReturnMutex.Unlock(); - packetAllocationPoolMutex.Lock(); - packetAllocationPool.Clear(_FILE_AND_LINE_); - packetAllocationPoolMutex.Unlock(); - - /* - if (isRecvFromLoopThreadActive.GetValue()>0) - { - timeout = MafiaNet::GetTimeMS()+1000; - while ( isRecvFromLoopThreadActive.GetValue()>0 && MafiaNet::GetTimeMS() addresses; - DataStructures::List guids; - GetSystemList(addresses, guids); - if (remoteSystems) - { - unsigned short i; - for (i=0; i < *numberOfSystems && i < addresses.Size(); i++) - remoteSystems[i]=addresses[i]; - *numberOfSystems=i; - } - else - { - *numberOfSystems=(unsigned short) addresses.Size(); - } - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -uint32_t RakPeer::GetNextSendReceipt(void) -{ - sendReceiptSerialMutex.Lock(); - uint32_t retVal = sendReceiptSerial; - sendReceiptSerialMutex.Unlock(); - return retVal; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -uint32_t RakPeer::IncrementNextSendReceipt(void) -{ - sendReceiptSerialMutex.Lock(); - uint32_t returned = sendReceiptSerial; - if (++sendReceiptSerial==0) - sendReceiptSerial=1; - sendReceiptSerialMutex.Unlock(); - return returned; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Sends a block of data to the specified system that you are connected to. -// This function only works while the client is connected (Use the Connect function). -// The first byte should be a message identifier starting at ID_USER_PACKET_ENUM -// -// Parameters: -// data: The block of data to send -// length: The size in bytes of the data to send -// bitStream: The bitstream to send -// priority: What priority level to send on. -// reliability: How reliability to send this data -// orderingChannel: When using ordered or sequenced packets, what channel to order these on. -// - Packets are only ordered relative to other packets on the same stream -// systemAddress: Who to send this packet to, or in the case of broadcasting who not to send it to. Use UNASSIGNED_SYSTEM_ADDRESS to specify none -// broadcast: True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. -// Returns: -// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -uint32_t RakPeer::Send( const char *data, const int length, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber ) -{ -#ifdef _DEBUG - RakAssert( data && length > 0 ); -#endif - RakAssert( !( (unsigned int)reliability >= MafiaNet::NUMBER_OF_RELIABILITIES || (int)reliability < 0 ) ); - RakAssert( !( (int)priority > (int)MafiaNet::NUMBER_OF_PRIORITIES || (int)priority < 0 ) ); - RakAssert( !( orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) ); - - if ( data == 0 || length < 0 ) - return 0; - - if ( remoteSystemList == 0 || endThreads == true ) - return 0; - - if ( broadcast == false && systemIdentifier.IsUndefined()) - return 0; - - uint32_t usedSendReceipt; - if (forceReceiptNumber!=0) - usedSendReceipt=forceReceiptNumber; - else - usedSendReceipt=IncrementNextSendReceipt(); - - if (broadcast==false && IsLoopbackAddress(systemIdentifier,true)) - { - SendLoopback(data,length); - - if (reliability>=MafiaNet::Reliability::UnreliableWithAckReceipt) - { - char buff[5]; - buff[0]=ID_SND_RECEIPT_ACKED; - sendReceiptSerialMutex.Lock(); - memcpy(buff+1, &sendReceiptSerial, 4); - sendReceiptSerialMutex.Unlock(); - SendLoopback( buff, 5 ); - } - - return usedSendReceipt; - } - - SendBuffered(data, length*8, priority, reliability, orderingChannel, systemIdentifier, broadcast, RemoteSystemStruct::NO_ACTION, usedSendReceipt); - - return usedSendReceipt; -} - -void RakPeer::SendLoopback( const char *data, const int length ) -{ - if ( data == 0 || length < 0 ) - return; - - Packet *packet = AllocPacket(length, _FILE_AND_LINE_); - memcpy(packet->data, data, length); - packet->systemAddress = GetLoopbackAddress(); - packet->guid=myGuid; - PushBackPacket(packet, false); -} - -uint32_t RakPeer::Send( const MafiaNet::BitStream * bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber ) -{ -#ifdef _DEBUG - RakAssert( bitStream->GetNumberOfBytesUsed() > 0 ); -#endif - - RakAssert( !( (unsigned int)reliability >= MafiaNet::NUMBER_OF_RELIABILITIES || (int)reliability < 0 ) ); - RakAssert( !( (int)priority > (int)MafiaNet::NUMBER_OF_PRIORITIES || (int)priority < 0 ) ); - RakAssert( !( orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) ); - - if ( bitStream->GetNumberOfBytesUsed() == 0 ) - return 0; - - if ( remoteSystemList == 0 || endThreads == true ) - return 0; - - if ( broadcast == false && systemIdentifier.IsUndefined() ) - return 0; - - uint32_t usedSendReceipt; - if (forceReceiptNumber!=0) - usedSendReceipt=forceReceiptNumber; - else - usedSendReceipt=IncrementNextSendReceipt(); - - if (broadcast==false && IsLoopbackAddress(systemIdentifier,true)) - { - SendLoopback((const char*) bitStream->GetData(),bitStream->GetNumberOfBytesUsed()); - if (reliability>=MafiaNet::Reliability::UnreliableWithAckReceipt) - { - char buff[5]; - buff[0]=ID_SND_RECEIPT_ACKED; - sendReceiptSerialMutex.Lock(); - memcpy(buff+1, &sendReceiptSerial,4); - sendReceiptSerialMutex.Unlock(); - SendLoopback( buff, 5 ); - } - return usedSendReceipt; - } - - // Sends need to be buffered and processed in the update thread because the systemAddress associated with the reliability layer can change, - // from that thread, resulting in a send to the wrong player! While I could mutex the systemAddress, that is much slower than doing this - SendBuffered((const char*)bitStream->GetData(), bitStream->GetNumberOfBitsUsed(), priority, reliability, orderingChannel, systemIdentifier, broadcast, RemoteSystemStruct::NO_ACTION, usedSendReceipt); - - - return usedSendReceipt; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Sends multiple blocks of data, concatenating them automatically. -// -// This is equivalent to: -// MafiaNet::BitStream bs; -// bs.WriteAlignedBytes(block1, blockLength1); -// bs.WriteAlignedBytes(block2, blockLength2); -// bs.WriteAlignedBytes(block3, blockLength3); -// Send(&bs, ...) -// -// This function only works while connected -// \param[in] data An array of pointers to blocks of data -// \param[in] lengths An array of integers indicating the length of each block of data -// \param[in] numParameters Length of the arrays data and lengths -// \param[in] priority What priority level to send on. See PacketPriority.h -// \param[in] reliability How reliability to send this data. See PacketPriority.h -// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream -// \param[in] systemIdentifier Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none -// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. -// \return False if we are not connected to the specified recipient. True otherwise -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -uint32_t RakPeer::SendList( const char **data, const int *lengths, const int numParameters, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber ) -{ -#ifdef _DEBUG - RakAssert( data ); -#endif - - if ( data == 0 || lengths == 0 ) - return 0; - - if ( remoteSystemList == 0 || endThreads == true ) - return 0; - - if (numParameters==0) - return 0; - - if (lengths==0) - return 0; - - if ( broadcast == false && systemIdentifier.IsUndefined() ) - return 0; - - uint32_t usedSendReceipt; - if (forceReceiptNumber!=0) - usedSendReceipt=forceReceiptNumber; - else - usedSendReceipt=IncrementNextSendReceipt(); - - SendBufferedList(data, lengths, numParameters, priority, reliability, orderingChannel, systemIdentifier, broadcast, RemoteSystemStruct::NO_ACTION, usedSendReceipt); - - return usedSendReceipt; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Gets a packet from the incoming packet queue. Use DeallocatePacket to deallocate the packet after you are done with it. -// Check the Packet struct at the top of CoreNetworkStructures.h for the format of the struct -// -// Returns: -// 0 if no packets are waiting to be handled, otherwise an allocated packet -// If the client is not active this will also return 0, as all waiting packets are flushed when the client is Disconnected -// This also updates all memory blocks associated with synchronized memory and distributed objects -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -Packet* RakPeer::Receive( void ) -{ - if ( !( IsActive() ) ) - return 0; - - MafiaNet::Packet *packet; -// Packet **threadPacket; - PluginReceiveResult pluginResult; - - int offset; - unsigned int i; - - // User should call RunUpdateCycle and RunRecvFromOnce to do this commented code - /* -#if RAKPEER_SINGLE_THREADED==1 - RakPeer::RecvFromStruct *recvFromStruct; - for (i=0; i < socketList.Size(); i++) - { - for(;;) - { - recvFromStruct=bufferedPackets.Allocate( _FILE_AND_LINE_ ); - recvFromStruct->s=socketList[i]->s; - recvFromStruct->remotePortRakNetWasStartedOn_PS3=socketList[i]->remotePortRakNetWasStartedOn_PS3_PSP2; - recvFromStruct->extraSocketOptions=socketList[i]->extraSocketOptions; - SocketLayer::RecvFromBlocking( - recvFromStruct->s, this, recvFromStruct->remotePortRakNetWasStartedOn_PS3, - recvFromStruct->extraSocketOptions, recvFromStruct->data, &recvFromStruct->bytesRead, &recvFromStruct->systemAddress, &recvFromStruct->timeRead); - if (recvFromStruct->bytesRead<=0) - { - bufferedPackets.Deallocate(recvFromStruct, _FILE_AND_LINE_); - break; - } - else - { - RakAssert(recvFromStruct->systemAddress.GetPort()); - bufferedPackets.Push(recvFromStruct); - } - } - } - - BitStream updateBitStream( MAXIMUM_MTU_SIZE -#if LIBCAT_SECURITY==1 - + cat::AuthenticatedEncryption::OVERHEAD_BYTES -#endif - ); - RunUpdateCycle(0, 0, updateBitStream); -#endif - */ - - for (i=0; i < pluginListTS.Size(); i++) - { - pluginListTS[i]->Update(); - } - for (i=0; i < pluginListNTS.Size(); i++) - { - pluginListNTS[i]->Update(); - } - - do - { - packetReturnMutex.Lock(); - if (packetReturnQueue.IsEmpty()) - packet=0; - else - packet = packetReturnQueue.Pop(); - packetReturnMutex.Unlock(); - if (packet==0) - return 0; - -// unsigned char msgId; - if ( ( packet->length >= sizeof(unsigned char) + sizeof(MafiaNet::Time ) ) && - ( (unsigned char) packet->data[ 0 ] == ID_TIMESTAMP ) ) - { - offset = sizeof(unsigned char); - ShiftIncomingTimestamp( packet->data + offset, packet->systemAddress ); -// msgId=packet->data[sizeof(unsigned char) + sizeof( MafiaNet::Time )]; - } -// else - // msgId=packet->data[0]; - - // Some locally generated packets need to be processed by plugins, for example ID_FCM2_NEW_HOST - // The plugin itself should intercept these messages generated remotely -// if (packet->wasGeneratedLocally) -// return packet; - - - CallPluginCallbacks(pluginListTS, packet); - CallPluginCallbacks(pluginListNTS, packet); - - for (i=0; i < pluginListTS.Size(); i++) - { - pluginResult=pluginListTS[i]->OnReceive(packet); - if (pluginResult==RR_STOP_PROCESSING_AND_DEALLOCATE) - { - DeallocatePacket( packet ); - packet=0; // Will do the loop again and get another packet - break; // break out of the enclosing for - } - else if (pluginResult==RR_STOP_PROCESSING) - { - packet=0; - break; - } - } - - for (i=0; i < pluginListNTS.Size(); i++) - { - pluginResult=pluginListNTS[i]->OnReceive(packet); - if (pluginResult==RR_STOP_PROCESSING_AND_DEALLOCATE) - { - DeallocatePacket( packet ); - packet=0; // Will do the loop again and get another packet - break; // break out of the enclosing for - } - else if (pluginResult==RR_STOP_PROCESSING) - { - packet=0; - break; - } - } - - } while(packet==0); - -#ifdef _DEBUG - RakAssert( packet->data ); -#endif - - return packet; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Call this to deallocate a packet returned by Receive -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::DeallocatePacket( Packet *packet ) -{ - if ( packet == 0 ) - return; - - if (packet->deleteData) - { - rakFree_Ex(packet->data, _FILE_AND_LINE_ ); - packet->~Packet(); - packetAllocationPoolMutex.Lock(); - packetAllocationPool.Release(packet,_FILE_AND_LINE_); - packetAllocationPoolMutex.Unlock(); - } - else - { - rakFree_Ex(packet, _FILE_AND_LINE_ ); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Return the total number of connections we are allowed -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -unsigned int RakPeer::GetMaximumNumberOfPeers( void ) const -{ - return maximumNumberOfPeers; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Close the connection to another host (if we initiated the connection it will disconnect, if they did it will kick them out). -// -// Parameters: -// target: Which connection to close -// sendDisconnectionNotification: True to send ID_DISCONNECTION_NOTIFICATION to the recipient. False to close it silently. -// channel: If blockDuration > 0, the disconnect packet will be sent on this channel -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::CloseConnection( const AddressOrGUID target, bool sendDisconnectionNotification, unsigned char orderingChannel, MafiaNet::Priority disconnectionNotificationPriority, const MafiaNet::BitStream *reasonData ) -{ - /* - // This only be called from the user thread, for the user shutting down. - // From the network thread, this should occur because of ID_DISCONNECTION_NOTIFICATION and ID_CONNECTION_LOST - unsigned j; - for (j=0; j < messageHandlerList.Size(); j++) - { - messageHandlerList[j]->OnClosedConnection( - target.systemAddress==UNASSIGNED_SYSTEM_ADDRESS ? GetSystemAddressFromGuid(target.rakNetGuid) : target.systemAddress, - target.rakNetGuid==UNASSIGNED_RAKNET_GUID ? GetGuidFromSystemAddress(target.systemAddress) : target.rakNetGuid, - LCR_CLOSED_BY_USER); - } - */ - - const SystemAddress address = (target.systemAddress == UNASSIGNED_SYSTEM_ADDRESS) ? GetSystemAddressFromGuid(target.rakNetGuid) : target.systemAddress; - int remoteSystemListIndex = GetIndexFromSystemAddress(address); - - // Resolve the socket to close on WITHOUT assuming a valid slot index. - // GetIndexFromSystemAddress returns -1 when the target isn't in the list; never - // coerce that to 0 — reading remoteSystemList[0] would crash if the list is - // unallocated, or target an unrelated peer's slot. When the index is valid use - // that slot's socket (it may itself be null during rapid connect/disconnect - // churn). Either way, fall back to the primary socket — the same pattern used by - // the BCS_CLOSE_CONNECTION path below. With no socket at all there is nothing to - // close, so bail out. - RakNetSocket2 *closeSocket = (remoteSystemListIndex != -1) ? remoteSystemList[remoteSystemListIndex].rakNetSocket : nullptr; - if (closeSocket == nullptr && socketList.Size() > 0) - closeSocket = socketList[0]; - if (closeSocket == nullptr) - return; - CloseConnectionInternal2(target, sendDisconnectionNotification, false, orderingChannel, disconnectionNotificationPriority, *closeSocket, reasonData); - - // 12/14/09 Return ID_CONNECTION_LOST when calling CloseConnection with sendDisconnectionNotification==false, elsewise it is never returned - if (sendDisconnectionNotification==false && GetConnectionState(target)==IS_CONNECTED) - { - Packet *packet=AllocPacket(sizeof( char ), _FILE_AND_LINE_); - packet->data[ 0 ] = ID_CONNECTION_LOST; // DeadConnection - packet->guid = target.rakNetGuid==UNASSIGNED_RAKNET_GUID ? GetGuidFromSystemAddress(target.systemAddress) : target.rakNetGuid; - packet->systemAddress = address; - packet->systemAddress.systemIndex = static_cast(remoteSystemListIndex == -1 ? 0 : remoteSystemListIndex); - packet->guid.systemIndex=packet->systemAddress.systemIndex; - packet->wasGeneratedLocally=true; // else processed twice - AddPacketToProducer(packet); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Cancel a pending connection attempt -// If we are already connected, the connection stays open -// \param[in] target Which system to cancel -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::CancelConnectionAttempt( const SystemAddress target ) -{ - unsigned int i; - - // Cancel pending connection attempt, if there is one - i=0; - requestedConnectionQueueMutex.Lock(); - while (i < requestedConnectionQueue.Size()) - { - if (requestedConnectionQueue[i]->systemAddress==target) - { -#if LIBCAT_SECURITY==1 - CAT_AUDIT_PRINTF("AUDIT: Deleting requestedConnectionQueue %i client_handshake %x\n", i, requestedConnectionQueue[ i ]->client_handshake); - MafiaNet::OP_DELETE(requestedConnectionQueue[i]->client_handshake, _FILE_AND_LINE_ ); -#endif - MafiaNet::OP_DELETE(requestedConnectionQueue[i], _FILE_AND_LINE_ ); - requestedConnectionQueue.RemoveAtIndex(i); - break; - } - else - i++; - } - requestedConnectionQueueMutex.Unlock(); - -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -ConnectionState RakPeer::GetConnectionState(const AddressOrGUID systemIdentifier) -{ - if (systemIdentifier.systemAddress!=UNASSIGNED_SYSTEM_ADDRESS) - { - unsigned int i=0; - requestedConnectionQueueMutex.Lock(); - for (; i < requestedConnectionQueue.Size(); i++) - { - if (requestedConnectionQueue[i]->systemAddress==systemIdentifier.systemAddress) - { - requestedConnectionQueueMutex.Unlock(); - return IS_PENDING; - } - } - requestedConnectionQueueMutex.Unlock(); - } - - int index; - if (systemIdentifier.systemAddress!=UNASSIGNED_SYSTEM_ADDRESS) - { - index = GetIndexFromSystemAddress(systemIdentifier.systemAddress, false); - } - else - { - index = GetIndexFromGuid(systemIdentifier.rakNetGuid); - } - - if (index==-1) - return IS_NOT_CONNECTED; - - if (remoteSystemList[index].isActive==false) - return IS_DISCONNECTED; - - switch (remoteSystemList[index].connectMode) - { - case RemoteSystemStruct::DISCONNECT_ASAP: - return IS_DISCONNECTING; - case RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY: - return IS_SILENTLY_DISCONNECTING; - case RemoteSystemStruct::DISCONNECT_ON_NO_ACK: - return IS_DISCONNECTING; - case RemoteSystemStruct::REQUESTED_CONNECTION: - return IS_CONNECTING; - case RemoteSystemStruct::HANDLING_CONNECTION_REQUEST: - return IS_CONNECTING; - case RemoteSystemStruct::UNVERIFIED_SENDER: - return IS_CONNECTING; - case RemoteSystemStruct::CONNECTED: - return IS_CONNECTED; - default: - return IS_NOT_CONNECTED; - } -} - - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Given a systemAddress, returns an index from 0 to the maximum number of players allowed - 1. -// -// Parameters -// systemAddress - The systemAddress to search for -// -// Returns -// An integer from 0 to the maximum number of peers -1, or -1 if that player is not found -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -int RakPeer::GetIndexFromSystemAddress( const SystemAddress systemAddress ) const -{ - return GetIndexFromSystemAddress(systemAddress, false); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// This function is only useful for looping through all players. -// -// Parameters -// index - an integer between 0 and the maximum number of players allowed - 1. -// -// Returns -// A valid systemAddress or UNASSIGNED_SYSTEM_ADDRESS if no such player at that index -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -SystemAddress RakPeer::GetSystemAddressFromIndex( unsigned int index ) -{ - // remoteSystemList in user thread - //if ( index >= 0 && index < remoteSystemListSize ) - if ( index < maximumNumberOfPeers ) - if (remoteSystemList[index].isActive && remoteSystemList[ index ].connectMode==RakPeer::RemoteSystemStruct::CONNECTED) // Don't give the user players that aren't fully connected, since sends will fail - return remoteSystemList[ index ].systemAddress; - - return UNASSIGNED_SYSTEM_ADDRESS; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Same as GetSystemAddressFromIndex but returns RakNetGUID -// \param[in] index Index should range between 0 and the maximum number of players allowed - 1. -// \return The RakNetGUID -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -RakNetGUID RakPeer::GetGUIDFromIndex( unsigned int index ) -{ - // remoteSystemList in user thread - //if ( index >= 0 && index < remoteSystemListSize ) - if ( index < maximumNumberOfPeers ) - if (remoteSystemList[index].isActive && remoteSystemList[ index ].connectMode==RakPeer::RemoteSystemStruct::CONNECTED) // Don't give the user players that aren't fully connected, since sends will fail - return remoteSystemList[ index ].guid; - - return UNASSIGNED_RAKNET_GUID; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Same as calling GetSystemAddressFromIndex and GetGUIDFromIndex for all systems, but more efficient -// Indices match each other, so \a addresses[0] and \a guids[0] refer to the same system -// \param[out] addresses All system addresses. Size of the list is the number of connections. Size of the list will match the size of the \a guids list. -// \param[out] guids All guids. Size of the list is the number of connections. Size of the list will match the size of the \a addresses list. -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::GetSystemList(DataStructures::List &addresses, DataStructures::List &guids) const -{ - addresses.Clear(false, _FILE_AND_LINE_); - guids.Clear(false, _FILE_AND_LINE_); - - if ( remoteSystemList == 0 || endThreads == true ) - return; - - unsigned int i; - for (i=0; i < activeSystemListSize; i++) - { - if ((activeSystemList[i])->isActive && - (activeSystemList[i])->connectMode==RakPeer::RemoteSystemStruct::CONNECTED) - { - addresses.Push((activeSystemList[i])->systemAddress, _FILE_AND_LINE_ ); - guids.Push((activeSystemList[i])->guid, _FILE_AND_LINE_ ); - } - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Bans an IP from connecting. Banned IPs persist between connections. -// -// Parameters -// IP - Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will ban -// All IP addresses starting with 128.0.0 -// milliseconds - how many ms for a temporary ban. Use 0 for a permanent ban -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::AddToBanList( const char *IP, MafiaNet::TimeMS milliseconds ) -{ - unsigned index; - MafiaNet::TimeMS time = MafiaNet::GetTimeMS(); - - if ( IP == 0 || IP[ 0 ] == 0 || strlen( IP ) > 15 ) - return ; - - // If this guy is already in the ban list, do nothing - index = 0; - - banListMutex.Lock(); - - for ( ; index < banList.Size(); index++ ) - { - if ( strcmp( IP, banList[ index ]->IP ) == 0 ) - { - // Already in the ban list. Just update the time - if (milliseconds==0) - banList[ index ]->timeout=0; // Infinite - else - banList[ index ]->timeout=time+milliseconds; - banListMutex.Unlock(); - return; - } - } - - banListMutex.Unlock(); - - BanStruct *banStruct = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - banStruct->IP = (char*) rakMalloc_Ex( 16, _FILE_AND_LINE_ ); - if (milliseconds==0) - banStruct->timeout=0; // Infinite - else - banStruct->timeout=time+milliseconds; - strcpy_s( banStruct->IP, 16, IP ); - banListMutex.Lock(); - banList.Insert( banStruct, _FILE_AND_LINE_ ); - banListMutex.Unlock(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Allows a previously banned IP to connect. -// -// Parameters -// IP - Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will ban -// All IP addresses starting with 128.0.0 -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::RemoveFromBanList( const char *IP ) -{ - unsigned index; - BanStruct *temp; - - if ( IP == 0 || IP[ 0 ] == 0 || strlen( IP ) > 15 ) - return ; - - index = 0; - temp=0; - - banListMutex.Lock(); - - for ( ; index < banList.Size(); index++ ) - { - if ( strcmp( IP, banList[ index ]->IP ) == 0 ) - { - temp = banList[ index ]; - banList[ index ] = banList[ banList.Size() - 1 ]; - banList.RemoveAtIndex( banList.Size() - 1 ); - break; - } - } - - banListMutex.Unlock(); - - if (temp) - { - rakFree_Ex(temp->IP, _FILE_AND_LINE_ ); - MafiaNet::OP_DELETE(temp, _FILE_AND_LINE_); - } - -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Allows all previously banned IPs to connect. -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::ClearBanList( void ) -{ - unsigned index; - index = 0; - banListMutex.Lock(); - - for ( ; index < banList.Size(); index++ ) - { - rakFree_Ex(banList[ index ]->IP, _FILE_AND_LINE_ ); - MafiaNet::OP_DELETE(banList[ index ], _FILE_AND_LINE_); - } - - banList.Clear(false, _FILE_AND_LINE_); - - banListMutex.Unlock(); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::SetLimitIPConnectionFrequency(bool b) -{ - limitConnectionFrequencyFromTheSameIP=b; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Determines if a particular IP is banned. -// -// Parameters -// IP - Complete dotted IP address -// -// Returns -// True if IP matches any IPs in the ban list, accounting for any wildcards. -// False otherwise. -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -bool RakPeer::IsBanned( const char *IP ) -{ - unsigned banListIndex, characterIndex; - MafiaNet::TimeMS time; - BanStruct *temp; - - if ( IP == 0 || IP[ 0 ] == 0 || strlen( IP ) > 15 ) - return false; - - banListIndex = 0; - - if ( banList.Size() == 0 ) - return false; // Skip the mutex if possible - - time = MafiaNet::GetTimeMS(); - - banListMutex.Lock(); - - while ( banListIndex < banList.Size() ) - { - if (banList[ banListIndex ]->timeout>0 && banList[ banListIndex ]->timeoutIP, _FILE_AND_LINE_ ); - MafiaNet::OP_DELETE(temp, _FILE_AND_LINE_); - } - else - { - characterIndex = 0; - - for(;;) - { - if ( banList[ banListIndex ]->IP[ characterIndex ] == IP[ characterIndex ] ) - { - // Equal characters - - if ( IP[ characterIndex ] == 0 ) - { - banListMutex.Unlock(); - // End of the string and the strings match - - return true; - } - - characterIndex++; - } - - else - { - if ( banList[ banListIndex ]->IP[ characterIndex ] == 0 || IP[ characterIndex ] == 0 ) - { - // End of one of the strings - break; - } - - // Characters do not match - if ( banList[ banListIndex ]->IP[ characterIndex ] == '*' ) - { - banListMutex.Unlock(); - - // Domain is banned. - return true; - } - - // Characters do not match and it is not a * - break; - } - } - - banListIndex++; - } - } - - banListMutex.Unlock(); - - // No match found. - return false; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Send a ping to the specified connected system. -// -// Parameters: -// target - who to ping -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::Ping( const SystemAddress target ) -{ - PingInternal(target, false, MafiaNet::Reliability::Unreliable); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Send a ping to the specified unconnected system. -// The remote system, if it is Initialized, will respond with ID_UNCONNECTED_PONG. -// The final ping time will be encoded in the following sizeof(MafiaNet::TimeMS) bytes. (Default is 4 bytes - See __GET_TIME_64BIT in types.h -// -// Parameters: -// host: Either a dotted IP address or a domain name. Can be 255.255.255.255 for LAN broadcast. -// remotePort: Which port to connect to on the remote machine. -// onlyReplyOnAcceptingConnections: Only request a reply if the remote system has open connections -// connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on. -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -bool RakPeer::Ping( const char* host, unsigned short remotePort, bool onlyReplyOnAcceptingConnections, unsigned connectionSocketIndex ) -{ - if ( host == 0 ) - return false; - - // If this assert hits then Startup wasn't called or the call failed. - RakAssert(connectionSocketIndex < socketList.Size()); - -// if ( IsActive() == false ) -// return; - - MafiaNet::BitStream bitStream( sizeof(unsigned char) + sizeof(MafiaNet::Time) ); - if ( onlyReplyOnAcceptingConnections ) - bitStream.Write((MessageID)ID_UNCONNECTED_PING_OPEN_CONNECTIONS); - else - bitStream.Write((MessageID)ID_UNCONNECTED_PING); - - bitStream.Write(MafiaNet::GetTime()); - - bitStream.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); - - bitStream.Write(GetMyGUID()); - - // No timestamp for 255.255.255.255 - unsigned int realIndex = GetRakNetSocketFromUserConnectionSocketIndex(connectionSocketIndex); - /* - - SystemAddress systemAddress; - systemAddress.FromStringExplicitPort(host,remotePort, socketList[realIndex]->GetBoundAddress().GetIPVersion()); - systemAddress.FixForIPVersion(socketList[realIndex]->GetBoundAddress()); - - unsigned i; - for (i=0; i < pluginListNTS.Size(); i++) - pluginListNTS[i]->OnDirectSocketSend((const char*)bitStream.GetData(), bitStream.GetNumberOfBitsUsed(), systemAddress); - SocketLayer::SendTo( socketList[realIndex], (const char*)bitStream.GetData(), (int) bitStream.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); - */ - - RNS2_SendParameters bsp; - bsp.data = (char*) bitStream.GetData() ; - bsp.length = bitStream.GetNumberOfBytesUsed(); - bsp.systemAddress.FromStringExplicitPort(host,remotePort, socketList[realIndex]->GetBoundAddress().GetIPVersion()); - if (bsp.systemAddress==UNASSIGNED_SYSTEM_ADDRESS) - return false; - bsp.systemAddress.FixForIPVersion(socketList[realIndex]->GetBoundAddress()); - unsigned i; - for (i=0; i < pluginListNTS.Size(); i++) - pluginListNTS[i]->OnDirectSocketSend((const char*)bitStream.GetData(), bitStream.GetNumberOfBitsUsed(), bsp.systemAddress); - socketList[realIndex]->Send(&bsp, _FILE_AND_LINE_); - - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Returns the average of all ping times read for a specified target -// -// Parameters: -// target - whose time to read -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -int RakPeer::GetAveragePing( const AddressOrGUID systemIdentifier ) -{ - int sum, quantity; - RemoteSystemStruct *remoteSystem = GetRemoteSystem( systemIdentifier, false, false ); - - if ( remoteSystem == 0 ) - return -1; - - for ( sum = 0, quantity = 0; quantity < PING_TIMES_ARRAY_SIZE; quantity++ ) - { - if ( remoteSystem->pingAndClockDifferential[ quantity ].pingTime == 65535 ) - break; - else - sum += remoteSystem->pingAndClockDifferential[ quantity ].pingTime; - } - - if ( quantity > 0 ) - return sum / quantity; - else - return -1; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Returns the last ping time read for the specific player or -1 if none read yet -// -// Parameters: -// target - whose time to read -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -int RakPeer::GetLastPing( const AddressOrGUID systemIdentifier ) const -{ - RemoteSystemStruct * remoteSystem = GetRemoteSystem( systemIdentifier, false, false ); - - if ( remoteSystem == 0 ) - return -1; - -// return (int)(remoteSystem->reliabilityLayer.GetAckPing()/(MafiaNet::TimeUS)1000); - - if ( remoteSystem->pingAndClockDifferentialWriteIndex == 0 ) - return remoteSystem->pingAndClockDifferential[ PING_TIMES_ARRAY_SIZE - 1 ].pingTime; - else - return remoteSystem->pingAndClockDifferential[ remoteSystem->pingAndClockDifferentialWriteIndex - 1 ].pingTime; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Returns the lowest ping time read or -1 if none read yet -// -// Parameters: -// target - whose time to read -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -int RakPeer::GetLowestPing( const AddressOrGUID systemIdentifier ) const -{ - RemoteSystemStruct * remoteSystem = GetRemoteSystem( systemIdentifier, false, false ); - - if ( remoteSystem == 0 ) - return -1; - - return remoteSystem->lowestPing; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Ping the remote systems every so often. This is off by default -// This will work anytime -// -// Parameters: -// doPing - True to start occasional pings. False to stop them. -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::SetOccasionalPing( bool doPing ) -{ - occasionalPing = doPing; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -/// Return the clock difference between your system and the specified system -/// Subtract the time from a time returned by the remote system to get that time relative to your own system -/// Returns 0 if the system is unknown -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -MafiaNet::Time RakPeer::GetClockDifferential( const AddressOrGUID systemIdentifier ) -{ - RemoteSystemStruct *remoteSystem = GetRemoteSystem(systemIdentifier, false, false); - if (remoteSystem == 0) - return 0; - return GetClockDifferentialInt(remoteSystem); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -MafiaNet::Time RakPeer::GetClockDifferentialInt(RemoteSystemStruct *remoteSystem) const -{ - int counter, lowestPingSoFar; - MafiaNet::Time clockDifferential; - - lowestPingSoFar = 65535; - - clockDifferential = 0; - - for ( counter = 0; counter < PING_TIMES_ARRAY_SIZE; counter++ ) - { - if ( remoteSystem->pingAndClockDifferential[ counter ].pingTime == 65535 ) - break; - - if ( remoteSystem->pingAndClockDifferential[ counter ].pingTime < lowestPingSoFar ) - { - clockDifferential = remoteSystem->pingAndClockDifferential[ counter ].clockDifferential; - lowestPingSoFar = remoteSystem->pingAndClockDifferential[ counter ].pingTime; - } - } - - return clockDifferential; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Length should be under 400 bytes, as a security measure against flood attacks -// Sets the data to send with an (LAN server discovery) /(offline ping) response -// See the Ping sample project for how this is used. -// data: a block of data to store, or 0 for none -// length: The length of data in bytes, or 0 for none -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::SetOfflinePingResponse( const char *data, const unsigned int length ) -{ - RakAssert(length < 400); - - rakPeerMutexes[ offlinePingResponse_Mutex ].Lock(); - offlinePingResponse.Reset(); - - if ( data && length > 0 ) - offlinePingResponse.Write( data, length ); - - rakPeerMutexes[ offlinePingResponse_Mutex ].Unlock(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Returns pointers to a copy of the data passed to SetOfflinePingResponse -// \param[out] data A pointer to a copy of the data passed to \a SetOfflinePingResponse() -// \param[out] length A pointer filled in with the length parameter passed to SetOfflinePingResponse() -// \sa SetOfflinePingResponse -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::GetOfflinePingResponse( char **data, unsigned int *length ) -{ - rakPeerMutexes[ offlinePingResponse_Mutex ].Lock(); - *data = (char*) offlinePingResponse.GetData(); - *length = (int) offlinePingResponse.GetNumberOfBytesUsed(); - rakPeerMutexes[ offlinePingResponse_Mutex ].Unlock(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Return the unique SystemAddress that represents you on the the network -// Note that unlike in previous versions, this is a struct and is not sequential -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -SystemAddress RakPeer::GetInternalID( const SystemAddress systemAddress, const int index ) const -{ - if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS) - { - return ipList[index]; - } - else - { - -// SystemAddress returnValue; - RemoteSystemStruct * remoteSystem = GetRemoteSystemFromSystemAddress( systemAddress, false, true ); - if (remoteSystem==0) - return UNASSIGNED_SYSTEM_ADDRESS; - - return remoteSystem->theirInternalSystemAddress[index]; - /* - sockaddr_in sa; - socklen_t len = sizeof(sa); - if (getsockname__(connectionSockets[remoteSystem->connectionSocketIndex], (sockaddr*)&sa, &len)!=0) - return UNASSIGNED_SYSTEM_ADDRESS; - returnValue.port=ntohs(sa.sin_port); - returnValue.binaryAddress=sa.sin_addr.s_addr; - return returnValue; -*/ - - - - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -/// \brief Sets your internal IP address, for platforms that do not support reading it, or to override a value -/// \param[in] systemAddress. The address to set. Use SystemAddress::FromString() if you want to use a dotted string -/// \param[in] index When you have multiple internal IDs, which index to set? -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::SetInternalID(SystemAddress systemAddress, int index) -{ - RakAssert(index >=0 && index < MAXIMUM_NUMBER_OF_INTERNAL_IDS); - ipList[index]=systemAddress; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Return the unique address identifier that represents you on the the network and is based on your external -// IP / port (the IP / port the specified player uses to communicate with you) -// Note that unlike in previous versions, this is a struct and is not sequential -// -// Parameters: -// target: Which remote system you are referring to for your external ID -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -SystemAddress RakPeer::GetExternalID( const SystemAddress target ) const -{ - unsigned i; - SystemAddress inactiveExternalId; - - inactiveExternalId=UNASSIGNED_SYSTEM_ADDRESS; - - if (target==UNASSIGNED_SYSTEM_ADDRESS) - return firstExternalID; - - // First check for active connection with this systemAddress - for ( i = 0; i < maximumNumberOfPeers; i++ ) - { - if (remoteSystemList[ i ].systemAddress == target ) - { - if ( remoteSystemList[ i ].isActive ) - return remoteSystemList[ i ].myExternalSystemAddress; - else if (remoteSystemList[ i ].myExternalSystemAddress!=UNASSIGNED_SYSTEM_ADDRESS) - inactiveExternalId=remoteSystemList[ i ].myExternalSystemAddress; - } - } - - return inactiveExternalId; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -const RakNetGUID RakPeer::GetMyGUID(void) const -{ - return myGuid; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -SystemAddress RakPeer::GetMyBoundAddress(const int socketIndex) -{ - DataStructures::List sockets; - GetSockets( sockets ); - if (sockets.Size()>0) - return sockets[socketIndex]->GetBoundAddress(); - else - return UNASSIGNED_SYSTEM_ADDRESS; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -const RakNetGUID& RakPeer::GetGuidFromSystemAddress( const SystemAddress input ) const -{ - if (input==UNASSIGNED_SYSTEM_ADDRESS) - return myGuid; - - if (input.systemIndex!=(SystemIndex)-1 && input.systemIndexreliabilityLayer.SetTimeoutTime(timeMS); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -MafiaNet::TimeMS RakPeer::GetTimeoutTime( const SystemAddress target ) -{ - if (target==UNASSIGNED_SYSTEM_ADDRESS) - { - return defaultTimeoutTime; - } - else - { - RemoteSystemStruct * remoteSystem = GetRemoteSystemFromSystemAddress( target, false, true ); - - if ( remoteSystem != 0 ) - return remoteSystem->reliabilityLayer.GetTimeoutTime(); - } - return defaultTimeoutTime; -} - - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Returns the current MTU size -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -int RakPeer::GetMTUSize( const SystemAddress target ) const -{ - if (target!=UNASSIGNED_SYSTEM_ADDRESS) - { - RemoteSystemStruct *rss=GetRemoteSystemFromSystemAddress(target, false, true); - if (rss) - return rss->MTUSize; - } - return defaultMTUSize; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Returns the number of IP addresses we have -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -unsigned int RakPeer::GetNumberOfAddresses( void ) -{ - if (IsActive() == false) { - FillIPList(); - } - - for (unsigned int i = 0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS && ipList[i] != UNASSIGNED_SYSTEM_ADDRESS; i++) { - if (ipList[i] == UNASSIGNED_SYSTEM_ADDRESS) { - return i; // first unassigned address entry found -> end of address list reached - } - } - - return MAXIMUM_NUMBER_OF_INTERNAL_IDS; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Returns an IP address at index 0 to GetNumberOfAddresses-1 -// \param[in] index index into the list of IP addresses -// \return The local IP address at this index -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -const char* RakPeer::GetLocalIP( unsigned int index ) -{ - if (IsActive()==false) - { - // Fill out ipList structure - - FillIPList(); - - } - - - static char str[128]; - ipList[index].ToString(false,str,static_cast(128)); - return str; - - - - -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Is this a local IP? -// \param[in] An IP address to check -// \return True if this is one of the IP addresses returned by GetLocalIP -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -bool RakPeer::IsLocalIP( const char *ip ) -{ - if (ip==0 || ip[0]==0) - return false; - - // #med - this should also check for "::1" here in IPv6 mode - if (strcmp(ip, "127.0.0.1")==0 || strcmp(ip, "localhost")==0) - return true; - - int num = GetNumberOfAddresses(); - int i; - for (i=0; i < num; i++) - { - if (strcmp(ip, GetLocalIP(i))==0) - return true; - } - - - - - return false; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Allow or disallow connection responses from any IP. Normally this should be false, but may be necessary -// when connection to servers with multiple IP addresses -// -// Parameters: -// allow - True to allow this behavior, false to not allow. Defaults to false. Value persists between connections -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::AllowConnectionResponseIPMigration( bool allow ) -{ - allowConnectionResponseIPMigration = allow; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Description: -// Sends a message ID_ADVERTISE_SYSTEM to the remote unconnected system. -// This will tell the remote system our external IP outside the LAN, and can be used for NAT punch through -// -// Requires: -// The sender and recipient must already be started via a successful call to Initialize -// -// host: Either a dotted IP address or a domain name -// remotePort: Which port to connect to on the remote machine. -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -bool RakPeer::AdvertiseSystem( const char *host, unsigned short remotePort, const char *data, int dataLength, unsigned connectionSocketIndex ) -{ - MafiaNet::BitStream bs; - bs.Write((MessageID)ID_ADVERTISE_SYSTEM); - bs.WriteAlignedBytes((const unsigned char*) data,dataLength); - return SendOutOfBand(host, remotePort, (const char*) bs.GetData(), bs.GetNumberOfBytesUsed(), connectionSocketIndex ); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Controls how often to return ID_DOWNLOAD_PROGRESS for large message downloads. -// ID_DOWNLOAD_PROGRESS is returned to indicate a new partial message chunk, roughly the MTU size, has arrived -// As it can be slow or cumbersome to get this notification for every chunk, you can set the interval at which it is returned. -// Defaults to 0 (never return this notification) -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::SetSplitMessageProgressInterval(int interval) -{ - RakAssert(interval>=0); - splitMessageProgressInterval=interval; - for ( unsigned short i = 0; i < maximumNumberOfPeers; i++ ) - remoteSystemList[ i ].reliabilityLayer.SetSplitMessageProgressInterval(splitMessageProgressInterval); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Returns what was passed to SetSplitMessageProgressInterval() -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -int RakPeer::GetSplitMessageProgressInterval(void) const -{ - return splitMessageProgressInterval; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Set how long to wait before giving up on sending an unreliable message -// Useful if the network is clogged up. -// Set to 0 or less to never timeout. Defaults to 0. -// timeoutMS How many ms to wait before simply not sending an unreliable message. -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::SetUnreliableTimeout(MafiaNet::TimeMS timeoutMS) -{ - unreliableTimeout=timeoutMS; - for ( unsigned short i = 0; i < maximumNumberOfPeers; i++ ) - remoteSystemList[ i ].reliabilityLayer.SetUnreliableTimeout(unreliableTimeout); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Send a message to host, with the IP socket option TTL set to 3 -// This message will not reach the host, but will open the router. -// Used for NAT-Punchthrough -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::SendTTL( const char* host, unsigned short remotePort, int ttl, unsigned connectionSocketIndex ) -{ -#if !defined(__native_client__) - char fakeData[2]; - fakeData[0]=0; - fakeData[1]=1; - unsigned int realIndex = GetRakNetSocketFromUserConnectionSocketIndex(connectionSocketIndex); - if (socketList[realIndex]->IsBerkleySocket()) - { - RNS2_SendParameters bsp; - bsp.data = (char*) fakeData; - bsp.length = 2; - bsp.systemAddress.FromStringExplicitPort(host,remotePort, socketList[realIndex]->GetBoundAddress().GetIPVersion()); - bsp.systemAddress.FixForIPVersion(socketList[realIndex]->GetBoundAddress()); - bsp.ttl=ttl; - unsigned i; - for (i=0; i < pluginListNTS.Size(); i++) - pluginListNTS[i]->OnDirectSocketSend((const char*)bsp.data, BYTES_TO_BITS(bsp.length), bsp.systemAddress); - socketList[realIndex]->Send(&bsp, _FILE_AND_LINE_); - } -#endif -} - - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Attatches a Plugin interface to run code automatically on message receipt in the Receive call -// -// \param messageHandler Pointer to a plugin to attach -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::AttachPlugin( PluginInterface2 *plugin ) -{ - bool isNotThreadsafe = plugin->UsesReliabilityLayer(); - if (isNotThreadsafe) - { - if (pluginListNTS.GetIndexOf(plugin)==MAX_UNSIGNED_LONG) - { - plugin->SetRakPeerInterface(this); - plugin->OnAttach(); - pluginListNTS.Insert(plugin, _FILE_AND_LINE_); - } - } - else - { - if (pluginListTS.GetIndexOf(plugin)==MAX_UNSIGNED_LONG) - { - plugin->SetRakPeerInterface(this); - plugin->OnAttach(); - pluginListTS.Insert(plugin, _FILE_AND_LINE_); - } - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Detaches a Plugin interface to run code automatically on message receipt -// -// \param messageHandler Pointer to a plugin to detach -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::DetachPlugin( PluginInterface2 *plugin ) -{ - if (plugin==0) - return; - - unsigned int index; - - bool isNotThreadsafe = plugin->UsesReliabilityLayer(); - if (isNotThreadsafe) - { - index = pluginListNTS.GetIndexOf(plugin); - if (index!=MAX_UNSIGNED_LONG) - { - // Unordered list so delete from end for speed - pluginListNTS[index]=pluginListNTS[pluginListNTS.Size()-1]; - pluginListNTS.RemoveFromEnd(); - } - } - else - { - index = pluginListTS.GetIndexOf(plugin); - if (index!=MAX_UNSIGNED_LONG) - { - // Unordered list so delete from end for speed - pluginListTS[index]=pluginListTS[pluginListTS.Size()-1]; - pluginListTS.RemoveFromEnd(); - } - } - plugin->OnDetach(); - plugin->SetRakPeerInterface(0); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Put a packet back at the end of the receive queue in case you don't want to deal with it immediately -// -// packet The packet you want to push back. -// pushAtHead True to push the packet so that the next receive call returns it. False to push it at the end of the queue (obviously pushing it at the end makes the packets out of order) -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::PushBackPacket( Packet *packet, bool pushAtHead) -{ - if (packet==0) - return; - - unsigned i; - for (i=0; i < pluginListTS.Size(); i++) - pluginListTS[i]->OnPushBackPacket((const char*) packet->data, packet->bitSize, packet->systemAddress); - for (i=0; i < pluginListNTS.Size(); i++) - pluginListNTS[i]->OnPushBackPacket((const char*) packet->data, packet->bitSize, packet->systemAddress); - - packetReturnMutex.Lock(); - if (pushAtHead) - packetReturnQueue.PushAtHead(packet,0,_FILE_AND_LINE_); - else - packetReturnQueue.Push(packet,_FILE_AND_LINE_); - packetReturnMutex.Unlock(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::ChangeSystemAddress(RakNetGUID guid, const SystemAddress &systemAddress) -{ - BufferedCommandStruct *bcs; - - bcs=bufferedCommands.Allocate( _FILE_AND_LINE_ ); - bcs->data = 0; - bcs->systemIdentifier.systemAddress=systemAddress; - bcs->systemIdentifier.rakNetGuid=guid; - bcs->command=BufferedCommandStruct::BCS_CHANGE_SYSTEM_ADDRESS; - bufferedCommands.Push(bcs); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -Packet* RakPeer::AllocatePacket(unsigned dataSize) -{ - return AllocPacket(dataSize, _FILE_AND_LINE_); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -RakNetSocket2* RakPeer::GetSocket( const SystemAddress target ) -{ - // Send a query to the thread to get the socket, and return when we got it - BufferedCommandStruct *bcs; - bcs=bufferedCommands.Allocate( _FILE_AND_LINE_ ); - bcs->command=BufferedCommandStruct::BCS_GET_SOCKET; - bcs->systemIdentifier=target; - bcs->data=0; - bufferedCommands.Push(bcs); - - // Block up to one second to get the socket, although it should actually take virtually no time - SocketQueryOutput *sqo; - MafiaNet::TimeMS stopWaiting = MafiaNet::GetTimeMS()+1000; - DataStructures::List output; - while (MafiaNet::GetTimeMS() < stopWaiting) - { - if (isMainLoopThreadActive==false) - return 0; - - RakSleep(0); - - sqo = socketQueryOutput.Pop(); - if (sqo) - { - output=sqo->sockets; - sqo->sockets.Clear(false, _FILE_AND_LINE_); - socketQueryOutput.Deallocate(sqo, _FILE_AND_LINE_); - if (output.Size()) - return output[0]; - break; - } - } - return 0; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::GetSockets( DataStructures::List &sockets ) -{ - sockets.Clear(false, _FILE_AND_LINE_); - - // Send a query to the thread to get the socket, and return when we got it - BufferedCommandStruct *bcs; - - bcs=bufferedCommands.Allocate( _FILE_AND_LINE_ ); - bcs->command=BufferedCommandStruct::BCS_GET_SOCKET; - bcs->systemIdentifier=UNASSIGNED_SYSTEM_ADDRESS; - bcs->data=0; - bufferedCommands.Push(bcs); - - // Block up to one second to get the socket, although it should actually take virtually no time - SocketQueryOutput *sqo; -// RakNetSocket2* output; - for(;;) - { - if (isMainLoopThreadActive==false) - return; - - RakSleep(0); - - sqo = socketQueryOutput.Pop(); - if (sqo) - { - sockets=sqo->sockets; - sqo->sockets.Clear(false, _FILE_AND_LINE_); - socketQueryOutput.Deallocate(sqo, _FILE_AND_LINE_); - return; - } - } - return; -} -void RakPeer::ReleaseSockets( DataStructures::List &sockets ) -{ - sockets.Clear(false,_FILE_AND_LINE_); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Adds simulated ping and packet loss to the outgoing data flow. -// To simulate bi-directional ping and packet loss, you should call this on both the sender and the recipient, with half the total ping and maxSendBPS value on each. -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::ApplyNetworkSimulator( float packetloss, unsigned short minExtraPing, unsigned short extraPingVariance) -{ -#ifndef _DEBUG - // unused parameters - (void)packetloss; - (void)minExtraPing; - (void)extraPingVariance; -#endif - -#ifdef _DEBUG - if (remoteSystemList) - { - unsigned short i; - for (i=0; i < maximumNumberOfPeers; i++) - //for (i=0; i < remoteSystemListSize; i++) - remoteSystemList[i].reliabilityLayer.ApplyNetworkSimulator(packetloss, minExtraPing, extraPingVariance); - } - - _packetloss=packetloss; - _minExtraPing=minExtraPing; - _extraPingVariance=extraPingVariance; -#endif -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void RakPeer::SetPerConnectionOutgoingBandwidthLimit( unsigned maxBitsPerSecond ) -{ - maxOutgoingBPS=maxBitsPerSecond; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Returns if you previously called ApplyNetworkSimulator -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -bool RakPeer::IsNetworkSimulatorActive( void ) -{ -#ifdef _DEBUG - return _packetloss>0 || _minExtraPing>0 || _extraPingVariance>0; -#else - return false; -#endif -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::WriteOutOfBandHeader(MafiaNet::BitStream *bitStream) -{ - bitStream->Write((MessageID)ID_OUT_OF_BAND_INTERNAL); - bitStream->Write(myGuid); - bitStream->WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::SetUserUpdateThread(void (*_userUpdateThreadPtr)(RakPeerInterface *, void *), void *_userUpdateThreadData) -{ - userUpdateThreadPtr=_userUpdateThreadPtr; - userUpdateThreadData=_userUpdateThreadData; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::SetIncomingDatagramEventHandler( bool (*_incomingDatagramEventHandler)(RNS2RecvStruct *) ) -{ - incomingDatagramEventHandler=_incomingDatagramEventHandler; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -bool RakPeer::SendOutOfBand(const char *host, unsigned short remotePort, const char *data, BitSize_t dataLength, unsigned connectionSocketIndex ) -{ - if ( IsActive() == false ) - return false; - - if (host==0 || host[0]==0) - return false; - - // If this assert hits then Startup wasn't called or the call failed. - RakAssert(connectionSocketIndex < socketList.Size()); - - // This is a security measure. Don't send data longer than this value - RakAssert(dataLength <= (MAX_OFFLINE_DATA_LENGTH + sizeof(unsigned char)+sizeof(MafiaNet::Time)+RakNetGUID::size()+sizeof(OFFLINE_MESSAGE_DATA_ID))); - - if (host==0) - return false; - - // 34 bytes - MafiaNet::BitStream bitStream; - WriteOutOfBandHeader(&bitStream); - - if (dataLength>0) - { - bitStream.Write(data, dataLength); - } - - unsigned int realIndex = GetRakNetSocketFromUserConnectionSocketIndex(connectionSocketIndex); - - /* - SystemAddress systemAddress; - systemAddress.FromStringExplicitPort(host,remotePort, socketList[realIndex]->GetBoundAddress().GetIPVersion()); - systemAddress.FixForIPVersion(socketList[realIndex]->GetBoundAddress()); - - unsigned i; - for (i=0; i < pluginListNTS.Size(); i++) - pluginListNTS[i]->OnDirectSocketSend((const char*)bitStream.GetData(), bitStream.GetNumberOfBitsUsed(), systemAddress); - - SocketLayer::SendTo( socketList[realIndex], (const char*)bitStream.GetData(), (int) bitStream.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); - */ - - RNS2_SendParameters bsp; - bsp.data = (char*) bitStream.GetData(); - bsp.length = bitStream.GetNumberOfBytesUsed(); - bsp.systemAddress.FromStringExplicitPort(host,remotePort, socketList[realIndex]->GetBoundAddress().GetIPVersion()); - bsp.systemAddress.FixForIPVersion(socketList[realIndex]->GetBoundAddress()); - unsigned i; - for (i=0; i < pluginListNTS.Size(); i++) - pluginListNTS[i]->OnDirectSocketSend((const char*)bsp.data, BYTES_TO_BITS(bsp.length), bsp.systemAddress); - socketList[realIndex]->Send(&bsp, _FILE_AND_LINE_); - - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -RakNetStatistics * RakPeer::GetStatistics( const SystemAddress systemAddress, RakNetStatistics *rns ) -{ - static RakNetStatistics staticStatistics; - RakNetStatistics *systemStats; - if (rns==0) - systemStats=&staticStatistics; - else - systemStats=rns; - - if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS) - { - bool firstWrite=false; - // Return a crude sum - for ( unsigned short i = 0; i < maximumNumberOfPeers; i++ ) - { - if (remoteSystemList[ i ].isActive) - { - RakNetStatistics rnsTemp; - remoteSystemList[ i ].reliabilityLayer.GetStatistics(&rnsTemp); - - if (firstWrite==false) - { - memcpy(systemStats, &rnsTemp, sizeof(RakNetStatistics)); - firstWrite=true; - } - else - (*systemStats)+=rnsTemp; - } - } - return systemStats; - } - else - { - RemoteSystemStruct * rss; - rss = GetRemoteSystemFromSystemAddress( systemAddress, false, false ); - if ( rss && endThreads==false ) - { - rss->reliabilityLayer.GetStatistics(systemStats); - return systemStats; - } - } - - return 0; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::GetStatisticsList(DataStructures::List &addresses, DataStructures::List &guids, DataStructures::List &statistics) -{ - addresses.Clear(false, _FILE_AND_LINE_); - guids.Clear(false, _FILE_AND_LINE_); - statistics.Clear(false, _FILE_AND_LINE_); - - if ( remoteSystemList == 0 || endThreads == true ) - return; - - unsigned int i; - for (i=0; i < activeSystemListSize; i++) - { - if ((activeSystemList[i])->isActive && - (activeSystemList[i])->connectMode==RakPeer::RemoteSystemStruct::CONNECTED) - { - addresses.Push((activeSystemList[i])->systemAddress, _FILE_AND_LINE_ ); - guids.Push((activeSystemList[i])->guid, _FILE_AND_LINE_ ); - RakNetStatistics rns; - (activeSystemList[i])->reliabilityLayer.GetStatistics(&rns); - statistics.Push(rns, _FILE_AND_LINE_); - } - } -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -bool RakPeer::GetStatistics( const unsigned int index, RakNetStatistics *rns ) -{ - if (index < maximumNumberOfPeers && remoteSystemList[ index ].isActive) - { - remoteSystemList[ index ].reliabilityLayer.GetStatistics(rns); - return true; - } - return false; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -unsigned int RakPeer::GetReceiveBufferSize(void) -{ - unsigned int size; - packetReturnMutex.Lock(); - size=packetReturnQueue.Size(); - packetReturnMutex.Unlock(); - return size; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -int RakPeer::GetIndexFromSystemAddress( const SystemAddress systemAddress, bool calledFromNetworkThread ) const -{ - unsigned i; - - if ( systemAddress == UNASSIGNED_SYSTEM_ADDRESS ) - return -1; - - if (systemAddress.systemIndex!=(SystemIndex)-1 && systemAddress.systemIndex < maximumNumberOfPeers && remoteSystemList[systemAddress.systemIndex].systemAddress==systemAddress && remoteSystemList[ systemAddress.systemIndex ].isActive) - return systemAddress.systemIndex; - - if (calledFromNetworkThread) - { - return GetRemoteSystemIndex(systemAddress); - } - else - { - // remoteSystemList in user and network thread - for ( i = 0; i < maximumNumberOfPeers; i++ ) - if ( remoteSystemList[ i ].isActive && remoteSystemList[ i ].systemAddress == systemAddress ) - return i; - - // If no active results found, try previously active results. - for ( i = 0; i < maximumNumberOfPeers; i++ ) - if ( remoteSystemList[ i ].systemAddress == systemAddress ) - return i; - } - - return -1; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -int RakPeer::GetIndexFromGuid( const RakNetGUID guid ) -{ - unsigned i; - - if ( guid == UNASSIGNED_RAKNET_GUID ) - return -1; - - if (guid.systemIndex!=(SystemIndex)-1 && guid.systemIndex < maximumNumberOfPeers && remoteSystemList[guid.systemIndex].guid==guid && remoteSystemList[ guid.systemIndex ].isActive) - return guid.systemIndex; - - // remoteSystemList in user and network thread - for ( i = 0; i < maximumNumberOfPeers; i++ ) - if ( remoteSystemList[ i ].isActive && remoteSystemList[ i ].guid == guid ) - return i; - - // If no active results found, try previously active results. - for ( i = 0; i < maximumNumberOfPeers; i++ ) - if ( remoteSystemList[ i ].guid == guid ) - return i; - - return -1; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -#if LIBCAT_SECURITY==1 -bool RakPeer::GenerateConnectionRequestChallenge(RequestedConnectionStruct *rcs,PublicKey *publicKey) -{ - CAT_AUDIT_PRINTF("AUDIT: In GenerateConnectionRequestChallenge()\n"); - - rcs->client_handshake = 0; - rcs->publicKeyMode = PKM_INSECURE_CONNECTION; - - if (!publicKey) return true; - - switch (publicKey->publicKeyMode) - { - default: - case PKM_INSECURE_CONNECTION: - break; - - case PKM_ACCEPT_ANY_PUBLIC_KEY: - CAT_OBJCLR(rcs->remote_public_key); - rcs->client_handshake = MafiaNet::OP_NEW(_FILE_AND_LINE_); - - rcs->publicKeyMode = PKM_ACCEPT_ANY_PUBLIC_KEY; - break; - - case PKM_USE_TWO_WAY_AUTHENTICATION: - if (publicKey->myPublicKey == 0 || publicKey->myPrivateKey == 0 || - publicKey->remoteServerPublicKey == 0) - { - return false; - } - - rcs->client_handshake = MafiaNet::OP_NEW(_FILE_AND_LINE_); - memcpy(rcs->remote_public_key, publicKey->remoteServerPublicKey, cat::EasyHandshake::PUBLIC_KEY_BYTES); - - if (!rcs->client_handshake->Initialize(publicKey->remoteServerPublicKey) || - !rcs->client_handshake->SetIdentity(publicKey->myPublicKey, publicKey->myPrivateKey) || - !rcs->client_handshake->GenerateChallenge(rcs->handshakeChallenge)) - { - CAT_AUDIT_PRINTF("AUDIT: Failure initializing new client_handshake object with identity for this RequestedConnectionStruct\n"); - MafiaNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); - rcs->client_handshake=0; - return false; - } - - CAT_AUDIT_PRINTF("AUDIT: Success initializing new client handshake object with identity for this RequestedConnectionStruct -- pre-generated challenge\n"); - - rcs->publicKeyMode = PKM_USE_TWO_WAY_AUTHENTICATION; - break; - - case PKM_USE_KNOWN_PUBLIC_KEY: - if (publicKey->remoteServerPublicKey == 0) - return false; - - rcs->client_handshake = MafiaNet::OP_NEW(_FILE_AND_LINE_); - memcpy(rcs->remote_public_key, publicKey->remoteServerPublicKey, cat::EasyHandshake::PUBLIC_KEY_BYTES); - - if (!rcs->client_handshake->Initialize(publicKey->remoteServerPublicKey) || - !rcs->client_handshake->GenerateChallenge(rcs->handshakeChallenge)) - { - CAT_AUDIT_PRINTF("AUDIT: Failure initializing new client_handshake object for this RequestedConnectionStruct\n"); - MafiaNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); - rcs->client_handshake=0; - return false; - } - - CAT_AUDIT_PRINTF("AUDIT: Success initializing new client handshake object for this RequestedConnectionStruct -- pre-generated challenge\n"); - - rcs->publicKeyMode = PKM_USE_KNOWN_PUBLIC_KEY; - break; - } - - return true; -} -#endif -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -ConnectionAttemptResult RakPeer::SendConnectionRequest( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, PublicKey *publicKey, unsigned connectionSocketIndex, unsigned int extraData, unsigned sendConnectionAttemptCount, unsigned timeBetweenSendConnectionAttemptsMS, MafiaNet::TimeMS timeoutTime ) -{ - RakAssert(passwordDataLength <= 256); - RakAssert(remotePort!=0); - SystemAddress systemAddress; - if (!systemAddress.FromStringExplicitPort(host,remotePort,socketList[connectionSocketIndex]->GetBoundAddress().GetIPVersion())) - return CANNOT_RESOLVE_DOMAIN_NAME; - - // Already connected? - if (GetRemoteSystemFromSystemAddress(systemAddress, false, true)) - return ALREADY_CONNECTED_TO_ENDPOINT; - - //RequestedConnectionStruct *rcs = (RequestedConnectionStruct *) rakMalloc_Ex(sizeof(RequestedConnectionStruct), _FILE_AND_LINE_); - RequestedConnectionStruct *rcs = MafiaNet::OP_NEW(_FILE_AND_LINE_); - - rcs->systemAddress=systemAddress; - rcs->nextRequestTime= MafiaNet::GetTimeMS(); - rcs->requestsMade=0; - rcs->data=0; - rcs->socket=0; - rcs->extraData=extraData; - rcs->socketIndex=connectionSocketIndex; - rcs->actionToTake=RequestedConnectionStruct::CONNECT; - rcs->sendConnectionAttemptCount=sendConnectionAttemptCount; - rcs->timeBetweenSendConnectionAttemptsMS=timeBetweenSendConnectionAttemptsMS; - memcpy(rcs->outgoingPassword, passwordData, passwordDataLength); - rcs->outgoingPasswordLength=(unsigned char) passwordDataLength; - rcs->timeoutTime=timeoutTime; - -#if LIBCAT_SECURITY==1 - CAT_AUDIT_PRINTF("AUDIT: In SendConnectionRequest()\n"); - if (!GenerateConnectionRequestChallenge(rcs,publicKey)) - return SECURITY_INITIALIZATION_FAILED; -#else - (void) publicKey; -#endif - - // Return false if already pending, else push on queue - unsigned int i=0; - requestedConnectionQueueMutex.Lock(); - for (; i < requestedConnectionQueue.Size(); i++) - { - if (requestedConnectionQueue[i]->systemAddress==systemAddress) - { - requestedConnectionQueueMutex.Unlock(); - // Not necessary - //MafiaNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); - MafiaNet::OP_DELETE(rcs,_FILE_AND_LINE_); - return CONNECTION_ATTEMPT_ALREADY_IN_PROGRESS; - } - } - requestedConnectionQueue.Push(rcs, _FILE_AND_LINE_ ); - requestedConnectionQueueMutex.Unlock(); - - return CONNECTION_ATTEMPT_STARTED; -} -ConnectionAttemptResult RakPeer::SendConnectionRequest( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, PublicKey *publicKey, unsigned connectionSocketIndex, unsigned int extraData, unsigned sendConnectionAttemptCount, unsigned timeBetweenSendConnectionAttemptsMS, MafiaNet::TimeMS timeoutTime, RakNetSocket2* socket ) -{ - RakAssert(passwordDataLength <= 256); - SystemAddress systemAddress; - systemAddress.FromStringExplicitPort(host,remotePort); - - // Already connected? - if (GetRemoteSystemFromSystemAddress(systemAddress, false, true)) - return ALREADY_CONNECTED_TO_ENDPOINT; - - //RequestedConnectionStruct *rcs = (RequestedConnectionStruct *) rakMalloc_Ex(sizeof(RequestedConnectionStruct), _FILE_AND_LINE_); - RequestedConnectionStruct *rcs = MafiaNet::OP_NEW(_FILE_AND_LINE_); - - rcs->systemAddress=systemAddress; - rcs->nextRequestTime= MafiaNet::GetTimeMS(); - rcs->requestsMade=0; - rcs->data=0; - rcs->socket=0; - rcs->extraData=extraData; - rcs->socketIndex=connectionSocketIndex; - rcs->actionToTake=RequestedConnectionStruct::CONNECT; - rcs->sendConnectionAttemptCount=sendConnectionAttemptCount; - rcs->timeBetweenSendConnectionAttemptsMS=timeBetweenSendConnectionAttemptsMS; - memcpy(rcs->outgoingPassword, passwordData, passwordDataLength); - rcs->outgoingPasswordLength=(unsigned char) passwordDataLength; - rcs->timeoutTime=timeoutTime; - rcs->socket=socket; - -#if LIBCAT_SECURITY==1 - if (!GenerateConnectionRequestChallenge(rcs,publicKey)) - return SECURITY_INITIALIZATION_FAILED; -#else - (void) publicKey; -#endif - - // Return false if already pending, else push on queue - unsigned int i=0; - requestedConnectionQueueMutex.Lock(); - for (; i < requestedConnectionQueue.Size(); i++) - { - if (requestedConnectionQueue[i]->systemAddress==systemAddress) - { - requestedConnectionQueueMutex.Unlock(); - // Not necessary - //MafiaNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); - MafiaNet::OP_DELETE(rcs,_FILE_AND_LINE_); - return CONNECTION_ATTEMPT_ALREADY_IN_PROGRESS; - } - } - requestedConnectionQueue.Push(rcs, _FILE_AND_LINE_ ); - requestedConnectionQueueMutex.Unlock(); - - return CONNECTION_ATTEMPT_STARTED; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::ValidateRemoteSystemLookup(void) const -{ -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -RakPeer::RemoteSystemStruct *RakPeer::GetRemoteSystem( const AddressOrGUID systemIdentifier, bool calledFromNetworkThread, bool onlyActive ) const -{ - if (systemIdentifier.rakNetGuid!=UNASSIGNED_RAKNET_GUID) - return GetRemoteSystemFromGUID(systemIdentifier.rakNetGuid, onlyActive); - else - return GetRemoteSystemFromSystemAddress(systemIdentifier.systemAddress, calledFromNetworkThread, onlyActive); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -RakPeer::RemoteSystemStruct *RakPeer::GetRemoteSystemFromSystemAddress( const SystemAddress systemAddress, bool calledFromNetworkThread, bool onlyActive ) const -{ - unsigned i; - - if ( systemAddress == UNASSIGNED_SYSTEM_ADDRESS ) - return 0; - - if (calledFromNetworkThread) - { - unsigned int index = GetRemoteSystemIndex(systemAddress); - if (index!=(unsigned int) -1) - { - if (onlyActive==false || remoteSystemList[ index ].isActive==true ) - { - RakAssert(remoteSystemList[index].systemAddress==systemAddress); - return remoteSystemList + index; - } - } - } - else - { - int deadConnectionIndex=-1; - - // Active connections take priority. But if there are no active connections, return the first systemAddress match found - for ( i = 0; i < maximumNumberOfPeers; i++ ) - { - if (remoteSystemList[ i ].systemAddress == systemAddress) - { - if ( remoteSystemList[ i ].isActive ) - return remoteSystemList + i; - else if (deadConnectionIndex==-1) - deadConnectionIndex=i; - } - } - - if (deadConnectionIndex!=-1 && onlyActive==false) - return remoteSystemList + deadConnectionIndex; - } - - return 0; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -RakPeer::RemoteSystemStruct *RakPeer::GetRemoteSystemFromGUID( const RakNetGUID guid, bool onlyActive ) const -{ - if (guid==UNASSIGNED_RAKNET_GUID) - return 0; - - unsigned i; - for ( i = 0; i < maximumNumberOfPeers; i++ ) - { - if (remoteSystemList[ i ].guid == guid && (onlyActive==false || remoteSystemList[ i ].isActive)) - { - return remoteSystemList + i; - } - } - return 0; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::ParseConnectionRequestPacket( RakPeer::RemoteSystemStruct *remoteSystem, const SystemAddress &systemAddress, const char *data, int byteSize ) -{ - MafiaNet::BitStream bs((unsigned char*) data,byteSize,false); - bs.IgnoreBytes(sizeof(MessageID)); - RakNetGUID guid; - bs.Read(guid); - MafiaNet::Time incomingTimestamp; - bs.Read(incomingTimestamp); - unsigned char doSecurity; - bs.Read(doSecurity); - -#if LIBCAT_SECURITY==1 - unsigned char doClientKey; - if (_using_security) - { - // Ignore message on bad state - if (doSecurity != 1 || !remoteSystem->reliabilityLayer.GetAuthenticatedEncryption()) - return; - - // Validate client proof of key - unsigned char proof[cat::EasyHandshake::PROOF_BYTES]; - bs.ReadAlignedBytes(proof, sizeof(proof)); - if (!remoteSystem->reliabilityLayer.GetAuthenticatedEncryption()->ValidateProof(proof, sizeof(proof))) - { - remoteSystem->connectMode = RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY; - return; - } - - CAT_OBJCLR(remoteSystem->client_public_key); - - bs.Read(doClientKey); - - // Check if client wants to prove identity - if (doClientKey == 1) - { - // Read identity proof - unsigned char ident[cat::EasyHandshake::IDENTITY_BYTES]; - bs.ReadAlignedBytes(ident, sizeof(ident)); - - // If we are listening to these proofs, - if (_require_client_public_key) - { - // Validate client identity - if (!_server_handshake->VerifyInitiatorIdentity(remoteSystem->answer, ident, remoteSystem->client_public_key)) - { - MafiaNet::BitStream bitStream; - bitStream.Write((MessageID)ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY); // Report an error since the client is not providing an identity when it is necessary to connect - bitStream.Write((unsigned char)2); // Indicate client identity is invalid - SendImmediate((char*) bitStream.GetData(), bitStream.GetNumberOfBytesUsed(), MafiaNet::Priority::Immediate, MafiaNet::Reliability::Reliable, 0, systemAddress, false, false, MafiaNet::GetTimeUS(), 0); - remoteSystem->connectMode = RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY; - return; - } - } - - // Otherwise ignore the client public key - } - else - { - // If no client key was provided but it is required, - if (_require_client_public_key) - { - MafiaNet::BitStream bitStream; - bitStream.Write((MessageID)ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY); // Report an error since the client is not providing an identity when it is necessary to connect - bitStream.Write((unsigned char)1); // Indicate client identity is missing - SendImmediate((char*) bitStream.GetData(), bitStream.GetNumberOfBytesUsed(), MafiaNet::Priority::Immediate, MafiaNet::Reliability::Reliable, 0, systemAddress, false, false, MafiaNet::GetTimeUS(), 0); - remoteSystem->connectMode = RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY; - return; - } - } - } -#endif // LIBCAT_SECURITY - - unsigned char *password = bs.GetData()+BITS_TO_BYTES(bs.GetReadOffset()); - int passwordLength = byteSize - BITS_TO_BYTES(bs.GetReadOffset()); - if ( incomingPasswordLength != passwordLength || - memcmp( password, incomingPassword, incomingPasswordLength ) != 0 ) - { - CAT_AUDIT_PRINTF("AUDIT: Invalid password\n"); - // This one we only send once since we don't care if it arrives. - MafiaNet::BitStream bitStream; - bitStream.Write((MessageID)ID_INVALID_PASSWORD); - bitStream.Write(GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); - SendImmediate((char*) bitStream.GetData(), bitStream.GetNumberOfBytesUsed(), MafiaNet::Priority::Immediate, MafiaNet::Reliability::Reliable, 0, systemAddress, false, false, MafiaNet::GetTimeUS(), 0); - remoteSystem->connectMode=RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY; - return; - } - - // OK - remoteSystem->connectMode=RemoteSystemStruct::HANDLING_CONNECTION_REQUEST; - - OnConnectionRequest( remoteSystem, incomingTimestamp ); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::OnConnectionRequest( RakPeer::RemoteSystemStruct *remoteSystem, MafiaNet::Time incomingTimestamp ) -{ - MafiaNet::BitStream bitStream; - bitStream.Write((MessageID)ID_CONNECTION_REQUEST_ACCEPTED); - bitStream.Write(remoteSystem->systemAddress); - SystemIndex systemIndex = (SystemIndex) GetIndexFromSystemAddress( remoteSystem->systemAddress, true ); - RakAssert(systemIndex!=65535); - bitStream.Write(systemIndex); - for (unsigned int i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) - bitStream.Write(ipList[i]); - bitStream.Write(incomingTimestamp); - bitStream.Write(MafiaNet::GetTime()); - - SendImmediate((char*)bitStream.GetData(), bitStream.GetNumberOfBitsUsed(), MafiaNet::Priority::Immediate, MafiaNet::Reliability::ReliableOrdered, 0, remoteSystem->systemAddress, false, false, MafiaNet::GetTimeUS(), 0); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::NotifyAndFlagForShutdown( const SystemAddress systemAddress, bool performImmediate, unsigned char orderingChannel, MafiaNet::Priority disconnectionNotificationPriority, const MafiaNet::BitStream *reasonData ) -{ - MafiaNet::BitStream temp( sizeof(unsigned char) ); - temp.Write( (MessageID)ID_DISCONNECTION_NOTIFICATION ); - // Optionally append a caller-supplied reason payload right after the 1-byte ID. The ID occupies exactly 8 bits so - // the payload stays byte-aligned; the remote reads it from packet->data+1 (length packet->length-1). Wire-backward - // compatible: peers that only inspect data[0] ignore the extra bytes. - if (reasonData != nullptr && reasonData->GetNumberOfBytesUsed() > 0) - temp.Write( (const char*)reasonData->GetData(), reasonData->GetNumberOfBytesUsed() ); - if (performImmediate) - { - SendImmediate((char*)temp.GetData(), temp.GetNumberOfBitsUsed(), disconnectionNotificationPriority, MafiaNet::Reliability::ReliableOrdered, orderingChannel, systemAddress, false, false, MafiaNet::GetTimeUS(), 0); - RemoteSystemStruct *rss=GetRemoteSystemFromSystemAddress(systemAddress, true, true); - rss->connectMode=RemoteSystemStruct::DISCONNECT_ASAP; - } - else - { - SendBuffered((const char*)temp.GetData(), temp.GetNumberOfBitsUsed(), disconnectionNotificationPriority, MafiaNet::Reliability::ReliableOrdered, orderingChannel, systemAddress, false, RemoteSystemStruct::DISCONNECT_ASAP, 0); - } -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::ClearDisconnectReason( RemoteSystemStruct *remoteSystem ) -{ - if (remoteSystem==0) - return; - if (remoteSystem->disconnectReasonData!=0) - { - rakFree_Ex(remoteSystem->disconnectReasonData, _FILE_AND_LINE_); - remoteSystem->disconnectReasonData=0; - } - remoteSystem->disconnectReasonLength=0; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -unsigned int RakPeer::GetNumberOfRemoteInitiatedConnections( void ) const -{ - if ( remoteSystemList == 0 || endThreads == true ) - return 0; - - unsigned int numberOfIncomingConnections; - numberOfIncomingConnections = 0; - unsigned int i; - for (i=0; i < activeSystemListSize; i++) - { - if ((activeSystemList[i])->isActive && - (activeSystemList[i])->connectMode==RakPeer::RemoteSystemStruct::CONNECTED && - (activeSystemList[i])->weInitiatedTheConnection==false - ) - { - numberOfIncomingConnections++; - } - } - return numberOfIncomingConnections; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -RakPeer::RemoteSystemStruct * RakPeer::AssignSystemAddressToRemoteSystemList( const SystemAddress systemAddress, RemoteSystemStruct::ConnectMode connectionMode, RakNetSocket2* incomingRakNetSocket, bool *thisIPConnectedRecently, SystemAddress bindingAddress, int incomingMTU, RakNetGUID guid, bool useSecurity ) -{ - RemoteSystemStruct * remoteSystem; - unsigned i,j,assignedIndex; - MafiaNet::TimeMS time = MafiaNet::GetTimeMS(); -#ifdef _DEBUG - RakAssert(systemAddress!=UNASSIGNED_SYSTEM_ADDRESS); -#endif - - if (limitConnectionFrequencyFromTheSameIP) - { - if (IsLoopbackAddress(systemAddress,false)==false) - { - for ( i = 0; i < maximumNumberOfPeers; i++ ) - { - if ( remoteSystemList[ i ].isActive==true && - remoteSystemList[ i ].systemAddress.EqualsExcludingPort(systemAddress) && - time >= remoteSystemList[ i ].connectionTime && - time - remoteSystemList[ i ].connectionTime < 100 - ) - { - // 4/13/09 Attackers can flood ID_OPEN_CONNECTION_REQUEST and use up all available connection slots - // Ignore connection attempts if this IP address connected within the last 100 milliseconds - *thisIPConnectedRecently=true; - ValidateRemoteSystemLookup(); - return 0; - } - } - } - } - - // Don't use a different port than what we received on - bindingAddress.CopyPort(incomingRakNetSocket->GetBoundAddress()); - - *thisIPConnectedRecently=false; - for ( assignedIndex = 0; assignedIndex < maximumNumberOfPeers; assignedIndex++ ) - { - if ( remoteSystemList[ assignedIndex ].isActive==false ) - { - // printf("--- Address %s has become active\n", systemAddress.ToString()); - - remoteSystem=remoteSystemList+assignedIndex; - ReferenceRemoteSystem(systemAddress, assignedIndex); - // Stale reason payload from a prior occupant of this slot must never leak into a new connection. - ClearDisconnectReason(remoteSystem); - remoteSystem->MTUSize=defaultMTUSize; - remoteSystem->guid=guid; - remoteSystem->isActive = true; // This one line causes future incoming packets to go through the reliability layer - // Reserve this reliability layer for ourselves. - if (incomingMTU > remoteSystem->MTUSize) - remoteSystem->MTUSize=incomingMTU; - RakAssert(remoteSystem->MTUSize <= MAXIMUM_MTU_SIZE); - remoteSystem->reliabilityLayer.Reset(true, remoteSystem->MTUSize, useSecurity); - remoteSystem->reliabilityLayer.SetSplitMessageProgressInterval(splitMessageProgressInterval); - remoteSystem->reliabilityLayer.SetUnreliableTimeout(unreliableTimeout); - remoteSystem->reliabilityLayer.SetTimeoutTime(defaultTimeoutTime); - AddToActiveSystemList(assignedIndex); - if (incomingRakNetSocket->GetBoundAddress()==bindingAddress) - { - remoteSystem->rakNetSocket=incomingRakNetSocket; - } - else - { - char str[256]; - bindingAddress.ToString(true,str,static_cast(256)); - // See if this is an internal IP address. - // If so, force binding on it so we reply on the same IP address as they sent to. - unsigned int ipListIndex, foundIndex=(unsigned int)-1; - - for (ipListIndex=0; ipListIndex < MAXIMUM_NUMBER_OF_INTERNAL_IDS; ipListIndex++) - { - if (ipList[ipListIndex]==UNASSIGNED_SYSTEM_ADDRESS) - break; - - if (bindingAddress.EqualsExcludingPort(ipList[ipListIndex])) - { - foundIndex=ipListIndex; - break; - } - } - - // 06/26/09 Unconfirmed report that Vista firewall blocks the reply if we force a binding - // For now use the incoming socket only - // Originally this code was to force a machine with multiple IP addresses to reply back on the IP - // that the datagram came in on - //if (1 || foundIndex==(unsigned int)-1) - //{ - // Must not be an internal LAN address. Just use whatever socket it came in on - remoteSystem->rakNetSocket=incomingRakNetSocket; - //} - //else - //{ - /* - // Force binding - unsigned int socketListIndex; - for (socketListIndex=0; socketListIndex < socketList.Size(); socketListIndex++) - { - if (socketList[socketListIndex]->GetBoundAddress()==bindingAddress) - { - // Force binding with existing socket - remoteSystem->rakNetSocket=socketList[socketListIndex]; - break; - } - } - - if (socketListIndex==socketList.Size()) - { - char ipListFoundIndexStr[128]; - ipList[foundIndex].ToString(false,str); - - // Force binding with new socket - RakNetSocket* rns(MafiaNet::OP_NEW(_FILE_AND_LINE_)); - if (incomingRakNetSocket->GetRemotePortRakNetWasStartedOn()==0) - rns = SocketLayer::CreateBoundSocket( this, bindingAddress.GetPort(), incomingRakNetSocket->GetBlockingSocket(), ipListFoundIndexStr, 0, incomingRakNetSocket->GetExtraSocketOptions(), incomingRakNetSocket->GetSocketFamily(), incomingRakNetSocket->GetChromeInstance() ); - else - rns = SocketLayer::CreateBoundSocket_PS3Lobby( bindingAddress.GetPort(), incomingRakNetSocket->GetBlockingSocket(), ipListFoundIndexStr, incomingRakNetSocket->GetSocketFamily() ); - - - if (rns==0) - { - // Can't bind. Just use whatever socket it came in on - remoteSystem->rakNetSocket=incomingRakNetSocket; - } - else - { - rns->GetBoundAddress()=bindingAddress; - rns->SetUserConnectionSocketIndex((unsigned int)-1); - socketList.Push(rns, _FILE_AND_LINE_ ); - remoteSystem->rakNetSocket=rns; - - -#ifdef _WIN32 - int highPriority=THREAD_PRIORITY_ABOVE_NORMAL; -#else - int highPriority=-10; -#endif - - highPriority=0; - - - } - } - - */ - //} - } - - for ( j = 0; j < (unsigned) PING_TIMES_ARRAY_SIZE; j++ ) - { - remoteSystem->pingAndClockDifferential[ j ].pingTime = 65535; - remoteSystem->pingAndClockDifferential[ j ].clockDifferential = 0; - } - - remoteSystem->connectMode=connectionMode; - remoteSystem->pingAndClockDifferentialWriteIndex = 0; - remoteSystem->lowestPing = 65535; - remoteSystem->nextPingTime = 0; // Ping immediately - remoteSystem->weInitiatedTheConnection = false; - remoteSystem->connectionTime = time; - remoteSystem->myExternalSystemAddress = UNASSIGNED_SYSTEM_ADDRESS; - remoteSystem->lastReliableSend=time; - -#ifdef _DEBUG - int indexLoopupCheck=GetIndexFromSystemAddress( systemAddress, true ); - if ((int) indexLoopupCheck!=(int) assignedIndex) - { - RakAssert((int) indexLoopupCheck==(int) assignedIndex); - } -#endif - - return remoteSystem; - } - } - - return 0; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Adjust the first four bytes (treated as unsigned int) of the pointer -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::ShiftIncomingTimestamp( unsigned char *data, const SystemAddress &systemAddress ) const -{ -#ifdef _DEBUG - RakAssert( IsActive() ); - RakAssert( data ); -#endif - - MafiaNet::BitStream timeBS( data, sizeof(MafiaNet::Time), false); - MafiaNet::Time encodedTimestamp; - timeBS.Read(encodedTimestamp); - - encodedTimestamp = encodedTimestamp - GetBestClockDifferential( systemAddress ); - timeBS.SetWriteOffset(0); - timeBS.Write(encodedTimestamp); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// Thanks to Chris Taylor (cat02e@fsu.edu) for the improved timestamping algorithm -MafiaNet::Time RakPeer::GetBestClockDifferential( const SystemAddress systemAddress ) const -{ - RemoteSystemStruct *remoteSystem = GetRemoteSystemFromSystemAddress( systemAddress, true, true ); - - if ( remoteSystem == 0 ) - return 0; - - return GetClockDifferentialInt(remoteSystem); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -unsigned int RakPeer::RemoteSystemLookupHashIndex(const SystemAddress &sa) const -{ - return SystemAddress::ToInteger(sa) % ((unsigned int) maximumNumberOfPeers * REMOTE_SYSTEM_LOOKUP_HASH_MULTIPLE); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::ReferenceRemoteSystem(const SystemAddress &sa, unsigned int remoteSystemListIndex) -{ -// #ifdef _DEBUG -// for ( unsigned int remoteSystemIndex = 0; remoteSystemIndex < maximumNumberOfPeers; ++remoteSystemIndex ) -// { -// if (remoteSystemList[remoteSystemIndex].isActive ) -// { -// unsigned int debugHashIndex = GetRemoteSystemIndex(remoteSystemList[remoteSystemIndex].systemAddress); -// RakAssert(debugHashIndex==remoteSystemIndex); -// } -// } -// #endif - - - SystemAddress oldAddress = remoteSystemList[remoteSystemListIndex].systemAddress; - if (oldAddress!=UNASSIGNED_SYSTEM_ADDRESS) - { - // The system might be active if rerouting -// RakAssert(remoteSystemList[remoteSystemListIndex].isActive==false); - - // Remove the reference if the reference is pointing to this inactive system - if (GetRemoteSystem(oldAddress)==&remoteSystemList[remoteSystemListIndex]) - DereferenceRemoteSystem(oldAddress); - } - DereferenceRemoteSystem(sa); - -// #ifdef _DEBUG -// for ( unsigned int remoteSystemIndex = 0; remoteSystemIndex < maximumNumberOfPeers; ++remoteSystemIndex ) -// { -// if (remoteSystemList[remoteSystemIndex].isActive ) -// { -// unsigned int debugHashIndex = GetRemoteSystemIndex(remoteSystemList[remoteSystemIndex].systemAddress); -// if (debugHashIndex!=remoteSystemIndex) -// { -// RakAssert(debugHashIndex==remoteSystemIndex); -// } -// } -// } -// #endif - - - remoteSystemList[remoteSystemListIndex].systemAddress=sa; - - unsigned int hashIndex = RemoteSystemLookupHashIndex(sa); - RemoteSystemIndex *rsi; - rsi = remoteSystemIndexPool.Allocate(_FILE_AND_LINE_); - if (remoteSystemLookup[hashIndex]==0) - { - rsi->next=0; - rsi->index=remoteSystemListIndex; - remoteSystemLookup[hashIndex]=rsi; - } - else - { - RemoteSystemIndex *cur = remoteSystemLookup[hashIndex]; - while (cur->next!=0) - { - cur=cur->next; - } - - rsi = remoteSystemIndexPool.Allocate(_FILE_AND_LINE_); - rsi->next=0; - rsi->index=remoteSystemListIndex; - cur->next=rsi; - } - -// #ifdef _DEBUG -// for ( unsigned int remoteSystemIndex = 0; remoteSystemIndex < maximumNumberOfPeers; ++remoteSystemIndex ) -// { -// if (remoteSystemList[remoteSystemIndex].isActive ) -// { -// unsigned int debugHashIndex = GetRemoteSystemIndex(remoteSystemList[remoteSystemIndex].systemAddress); -// RakAssert(debugHashIndex==remoteSystemIndex); -// } -// } -// #endif - - - RakAssert(GetRemoteSystemIndex(sa)==remoteSystemListIndex); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::DereferenceRemoteSystem(const SystemAddress &sa) -{ - unsigned int hashIndex = RemoteSystemLookupHashIndex(sa); - RemoteSystemIndex *cur = remoteSystemLookup[hashIndex]; - RemoteSystemIndex *last = 0; - while (cur!=0) - { - if (remoteSystemList[cur->index].systemAddress==sa) - { - if (last==0) - { - remoteSystemLookup[hashIndex]=cur->next; - } - else - { - last->next=cur->next; - } - remoteSystemIndexPool.Release(cur,_FILE_AND_LINE_); - break; - } - last=cur; - cur=cur->next; - } -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -unsigned int RakPeer::GetRemoteSystemIndex(const SystemAddress &sa) const -{ - unsigned int hashIndex = RemoteSystemLookupHashIndex(sa); - RemoteSystemIndex *cur = remoteSystemLookup[hashIndex]; - while (cur!=0) - { - if (remoteSystemList[cur->index].systemAddress==sa) - return cur->index; - cur=cur->next; - } - return (unsigned int) -1; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -RakPeer::RemoteSystemStruct* RakPeer::GetRemoteSystem(const SystemAddress &sa) const -{ - unsigned int remoteSystemIndex = GetRemoteSystemIndex(sa); - if (remoteSystemIndex==(unsigned int)-1) - return 0; - return remoteSystemList + remoteSystemIndex; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::ClearRemoteSystemLookup(void) -{ - remoteSystemIndexPool.Clear(_FILE_AND_LINE_); - MafiaNet::OP_DELETE_ARRAY(remoteSystemLookup,_FILE_AND_LINE_); - remoteSystemLookup=0; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::AddToActiveSystemList(unsigned int remoteSystemListIndex) -{ - activeSystemList[activeSystemListSize++]=remoteSystemList+remoteSystemListIndex; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::RemoveFromActiveSystemList(const SystemAddress &sa) -{ - unsigned int i; - for (i=0; i < activeSystemListSize; i++) - { - RemoteSystemStruct *rss=activeSystemList[i]; - if (rss->systemAddress==sa) - { - activeSystemList[i]=activeSystemList[activeSystemListSize-1]; - activeSystemListSize--; - return; - } - } - RakAssert("activeSystemList invalid, entry not found in RemoveFromActiveSystemList. Ensure that AddToActiveSystemList and RemoveFromActiveSystemList are called by the same thread." && 0); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -/* -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -unsigned int RakPeer::LookupIndexUsingHashIndex(const SystemAddress &sa) const -{ - unsigned int scanCount=0; - unsigned int index = RemoteSystemLookupHashIndex(sa); - if (remoteSystemLookup[index].index==(unsigned int)-1) - return (unsigned int) -1; - while (remoteSystemList[remoteSystemLookup[index].index].systemAddress!=sa) - { - if (++index==(unsigned int) maximumNumberOfPeers*REMOTE_SYSTEM_LOOKUP_HASH_MULTIPLE) - index=0; - if (++scanCount>(unsigned int) maximumNumberOfPeers*REMOTE_SYSTEM_LOOKUP_HASH_MULTIPLE) - return (unsigned int) -1; - if (remoteSystemLookup[index].index==-1) - return (unsigned int) -1; - } - return index; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -unsigned int RakPeer::RemoteSystemListIndexUsingHashIndex(const SystemAddress &sa) const -{ - unsigned int index = LookupIndexUsingHashIndex(sa); - if (index!=(unsigned int) -1) - { - return remoteSystemLookup[index].index; - } - return (unsigned int) -1; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -unsigned int RakPeer::FirstFreeRemoteSystemLookupIndex(const SystemAddress &sa) const -{ -// unsigned int collisionCount=0; - unsigned int index = RemoteSystemLookupHashIndex(sa); - while (remoteSystemLookup[index].index!=(unsigned int)-1) - { - if (++index==(unsigned int) maximumNumberOfPeers*REMOTE_SYSTEM_LOOKUP_HASH_MULTIPLE) - index=0; -// collisionCount++; - } -// printf("%i collisions. Using index %i\n", collisionCount, index); - return index; -} -*/ -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -bool RakPeer::IsLoopbackAddress(const AddressOrGUID &systemIdentifier, bool matchPort) const -{ - if (systemIdentifier.rakNetGuid!=UNASSIGNED_RAKNET_GUID) - return systemIdentifier.rakNetGuid==myGuid; - - for (int i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS && ipList[i]!=UNASSIGNED_SYSTEM_ADDRESS; i++) - { - if (matchPort) - { - if (ipList[i]==systemIdentifier.systemAddress) - return true; - } - else - { - if (ipList[i].EqualsExcludingPort(systemIdentifier.systemAddress)) - return true; - } - } - - return (matchPort==true && systemIdentifier.systemAddress==firstExternalID) || - (matchPort==false && systemIdentifier.systemAddress.EqualsExcludingPort(firstExternalID)); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -SystemAddress RakPeer::GetLoopbackAddress(void) const -{ - - return ipList[0]; - - - -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -bool RakPeer::AllowIncomingConnections(void) const -{ - return GetNumberOfRemoteInitiatedConnections() < GetMaximumIncomingConnections(); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::DeallocRNS2RecvStruct(RNS2RecvStruct *s, const char *file, unsigned int line) -{ - bufferedPacketsFreePoolMutex.Lock(); - bufferedPacketsFreePool.Push(s, file, line); - bufferedPacketsFreePoolMutex.Unlock(); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -RNS2RecvStruct *RakPeer::AllocRNS2RecvStruct(const char *file, unsigned int line) -{ - bufferedPacketsFreePoolMutex.Lock(); - if (bufferedPacketsFreePool.Size()>0) - { - RNS2RecvStruct *s = bufferedPacketsFreePool.Pop(); - bufferedPacketsFreePoolMutex.Unlock(); - return s; - } - else - { - bufferedPacketsFreePoolMutex.Unlock(); - return MafiaNet::OP_NEW(file,line); - } -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::ClearBufferedPackets(void) -{ - bufferedPacketsFreePoolMutex.Lock(); - while (bufferedPacketsFreePool.Size()>0) - MafiaNet::OP_DELETE(bufferedPacketsFreePool.Pop(), _FILE_AND_LINE_); - bufferedPacketsFreePoolMutex.Unlock(); - - bufferedPacketsQueueMutex.Lock(); - while (bufferedPacketsQueue.Size()>0) - MafiaNet::OP_DELETE(bufferedPacketsQueue.Pop(), _FILE_AND_LINE_); - bufferedPacketsQueueMutex.Unlock(); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::SetupBufferedPackets(void) -{ -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::PushBufferedPacket(RNS2RecvStruct * p) -{ - bufferedPacketsQueueMutex.Lock(); - bufferedPacketsQueue.Push(p, _FILE_AND_LINE_); - bufferedPacketsQueueMutex.Unlock(); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -RNS2RecvStruct *RakPeer::PopBufferedPacket(void) -{ - bufferedPacketsQueueMutex.Lock(); - if (bufferedPacketsQueue.Size()>0) - { - RNS2RecvStruct *s = bufferedPacketsQueue.Pop(); - bufferedPacketsQueueMutex.Unlock(); - return s; - } - bufferedPacketsQueueMutex.Unlock(); - return 0; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::PingInternal( const SystemAddress target, bool performImmediate, MafiaNet::Reliability reliability ) -{ - if ( IsActive() == false ) - return ; - - MafiaNet::BitStream bitStream(sizeof(unsigned char)+sizeof(MafiaNet::Time)); - bitStream.Write((MessageID)ID_CONNECTED_PING); - bitStream.Write(MafiaNet::GetTime()); - if (performImmediate) - SendImmediate( (char*)bitStream.GetData(), bitStream.GetNumberOfBitsUsed(), MafiaNet::Priority::Immediate, reliability, 0, target, false, false, MafiaNet::GetTimeUS(), 0 ); - else - Send( &bitStream, MafiaNet::Priority::Immediate, reliability, 0, target, false ); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::CloseConnectionInternal( const AddressOrGUID& systemIdentifier, bool sendDisconnectionNotification, bool performImmediate, unsigned char orderingChannel, MafiaNet::Priority disconnectionNotificationPriority ) -{ - RakAssert(orderingChannel < 32); - - if (systemIdentifier.IsUndefined()) - return; - - if (remoteSystemList == 0 || endThreads == true) - return; - - // #med - this is flawed and needs to be resolved properly - socketList[0] is not correct here - CloseConnectionInternal2(systemIdentifier, sendDisconnectionNotification, performImmediate, orderingChannel, disconnectionNotificationPriority, *(socketList[0])); -} - -// #med - better integrate directly in CloseConnectionInternal2() -void RakPeer::CloseConnectionInternal2(const AddressOrGUID& systemIdentifier, bool sendDisconnectionNotification, bool performImmediate, unsigned char orderingChannel, MafiaNet::Priority disconnectionNotificationPriority, RakNetSocket2& socket, const MafiaNet::BitStream *reasonData) -{ - RakAssert(orderingChannel < 32); - - if (systemIdentifier.IsUndefined()) - return; - - if ( remoteSystemList == 0 || endThreads == true ) - return; - - SystemAddress target; - if (systemIdentifier.systemAddress!=UNASSIGNED_SYSTEM_ADDRESS) - { - target=systemIdentifier.systemAddress; - } - else - { - target=GetSystemAddressFromGuid(systemIdentifier.rakNetGuid); - } - - if (target != UNASSIGNED_SYSTEM_ADDRESS && performImmediate) { - target.FixForIPVersion(socket.GetBoundAddress()); - } - - if (sendDisconnectionNotification) - { - NotifyAndFlagForShutdown(target, performImmediate, orderingChannel, disconnectionNotificationPriority, reasonData); - } - else - { - if (performImmediate) - { - unsigned int index = GetRemoteSystemIndex(target); - if (index!=(unsigned int) -1) - { - if ( remoteSystemList[index].isActive ) - { - RemoveFromActiveSystemList(target); - - // Found the index to stop - // printf("--- Address %s has become inactive\n", remoteSystemList[index].systemAddress.ToString()); - remoteSystemList[index].isActive = false; - - remoteSystemList[index].guid=UNASSIGNED_RAKNET_GUID; - - // Reserve this reliability layer for ourselves - //remoteSystemList[ remoteSystemLookup[index].index ].systemAddress = UNASSIGNED_SYSTEM_ADDRESS; - - // Clear any remaining messages - RakAssert(remoteSystemList[index].MTUSize <= MAXIMUM_MTU_SIZE); - remoteSystemList[index].reliabilityLayer.Reset(false, remoteSystemList[index].MTUSize, false); - - // Free any stashed disconnect-reason payload (e.g. delivered already, or never consumed) - ClearDisconnectReason(&remoteSystemList[index]); - - // Not using this socket - remoteSystemList[index].rakNetSocket = 0; - } - } - } - else - { - BufferedCommandStruct *bcs; - bcs=bufferedCommands.Allocate( _FILE_AND_LINE_ ); - bcs->command=BufferedCommandStruct::BCS_CLOSE_CONNECTION; - bcs->systemIdentifier=target; - // #med - review whether this is safe here - can't the socket be closed/released before its used? - bcs->socket = &socket; - bcs->data=0; - bcs->orderingChannel=orderingChannel; - bcs->priority=disconnectionNotificationPriority; - bufferedCommands.Push(bcs); - } - } -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::SendBuffered( const char *data, BitSize_t numberOfBitsToSend, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, RemoteSystemStruct::ConnectMode connectionMode, uint32_t receipt ) -{ - BufferedCommandStruct *bcs; - - bcs=bufferedCommands.Allocate( _FILE_AND_LINE_ ); - bcs->data = (char*) rakMalloc_Ex( (size_t) BITS_TO_BYTES(numberOfBitsToSend), _FILE_AND_LINE_ ); // Making a copy doesn't lose efficiency because I tell the reliability layer to use this allocation for its own copy - if (bcs->data==0) - { - notifyOutOfMemory(_FILE_AND_LINE_); - bufferedCommands.Deallocate(bcs, _FILE_AND_LINE_); - return; - } - - RakAssert( !( (unsigned int)reliability >= MafiaNet::NUMBER_OF_RELIABILITIES || (int)reliability < 0 ) ); - RakAssert( !( (int)priority > (int)MafiaNet::NUMBER_OF_PRIORITIES || (int)priority < 0 ) ); - RakAssert( !( orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) ); - - memcpy(bcs->data, data, (size_t) BITS_TO_BYTES(numberOfBitsToSend)); - bcs->numberOfBitsToSend=numberOfBitsToSend; - bcs->priority=priority; - bcs->reliability=reliability; - bcs->orderingChannel=orderingChannel; - bcs->systemIdentifier=systemIdentifier; - bcs->broadcast=broadcast; - bcs->connectionMode=connectionMode; - bcs->receipt=receipt; - bcs->command=BufferedCommandStruct::BCS_SEND; - bufferedCommands.Push(bcs); - - if (priority==MafiaNet::Priority::Immediate) - { - // Forces pending sends to go out now, rather than waiting to the next update interval - quitAndDataEvents.SetEvent(); - } -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::SendBufferedList( const char **data, const int *lengths, const int numParameters, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, RemoteSystemStruct::ConnectMode connectionMode, uint32_t receipt ) -{ - BufferedCommandStruct *bcs; - unsigned int totalLength=0; - unsigned int lengthOffset; - int i; - for (i=0; i < numParameters; i++) - { - if (lengths[i]>0) - totalLength+=lengths[i]; - } - if (totalLength==0) - return; - - char *dataAggregate; - dataAggregate = (char*) rakMalloc_Ex( (size_t) totalLength, _FILE_AND_LINE_ ); // Making a copy doesn't lose efficiency because I tell the reliability layer to use this allocation for its own copy - if (dataAggregate==0) - { - notifyOutOfMemory(_FILE_AND_LINE_); - return; - } - for (i=0, lengthOffset=0; i < numParameters; i++) - { - if (lengths[i]>0) - { - memcpy(dataAggregate+lengthOffset, data[i], lengths[i]); - lengthOffset+=lengths[i]; - } - } - - if (broadcast==false && IsLoopbackAddress(systemIdentifier,true)) - { - SendLoopback(dataAggregate,totalLength); - rakFree_Ex(dataAggregate,_FILE_AND_LINE_); - return; - } - - RakAssert( !( (unsigned int)reliability >= MafiaNet::NUMBER_OF_RELIABILITIES || (int)reliability < 0 ) ); - RakAssert( !( (int)priority > (int)MafiaNet::NUMBER_OF_PRIORITIES || (int)priority < 0 ) ); - RakAssert( !( orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) ); - - bcs=bufferedCommands.Allocate( _FILE_AND_LINE_ ); - bcs->data = dataAggregate; - bcs->numberOfBitsToSend=BYTES_TO_BITS(totalLength); - bcs->priority=priority; - bcs->reliability=reliability; - bcs->orderingChannel=orderingChannel; - bcs->systemIdentifier=systemIdentifier; - bcs->broadcast=broadcast; - bcs->connectionMode=connectionMode; - bcs->receipt=receipt; - bcs->command=BufferedCommandStruct::BCS_SEND; - bufferedCommands.Push(bcs); - - if (priority==MafiaNet::Priority::Immediate) - { - // Forces pending sends to go out now, rather than waiting to the next update interval - quitAndDataEvents.SetEvent(); - } -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -bool RakPeer::SendImmediate( char *data, BitSize_t numberOfBitsToSend, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, bool useCallerDataAllocation, MafiaNet::TimeUS currentTime, uint32_t receipt ) -{ - unsigned *sendList; - unsigned sendListSize; - bool callerDataAllocationUsed; - unsigned int remoteSystemIndex, sendListIndex; // Iterates into the list of remote systems -// unsigned numberOfBytesUsed = (unsigned) BITS_TO_BYTES(numberOfBitsToSend); - callerDataAllocationUsed=false; - - sendListSize=0; - - if (systemIdentifier.systemAddress!=UNASSIGNED_SYSTEM_ADDRESS) - remoteSystemIndex=GetIndexFromSystemAddress( systemIdentifier.systemAddress, true ); - else if (systemIdentifier.rakNetGuid!=UNASSIGNED_RAKNET_GUID) - remoteSystemIndex=GetSystemIndexFromGuid(systemIdentifier.rakNetGuid); - else - remoteSystemIndex=(unsigned int) -1; - - // 03/06/06 - If broadcast is false, use the optimized version of GetIndexFromSystemAddress - if (broadcast==false) - { - if (remoteSystemIndex==(unsigned int) -1) - { -#ifdef _DEBUG -// int debugIndex = GetRemoteSystemIndex(systemIdentifier.systemAddress); -#endif - return false; - } - - #if USE_ALLOCA==1 - sendList=(unsigned *)alloca(sizeof(unsigned)); - #else - sendList = (unsigned *) rakMalloc_Ex(sizeof(unsigned), _FILE_AND_LINE_); - #endif - - if (remoteSystemList[remoteSystemIndex].isActive && - remoteSystemList[remoteSystemIndex].connectMode!=RemoteSystemStruct::DISCONNECT_ASAP && - remoteSystemList[remoteSystemIndex].connectMode!=RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY && - remoteSystemList[remoteSystemIndex].connectMode!=RemoteSystemStruct::DISCONNECT_ON_NO_ACK) - { - sendList[0]=remoteSystemIndex; - sendListSize=1; - } - } - else - { - #if USE_ALLOCA==1 - sendList=(unsigned *)alloca(sizeof(unsigned)*maximumNumberOfPeers); - #else - sendList = (unsigned *) rakMalloc_Ex(sizeof(unsigned)*maximumNumberOfPeers, _FILE_AND_LINE_); - #endif - - // remoteSystemList in network thread - unsigned int idx; - for ( idx = 0; idx < maximumNumberOfPeers; idx++ ) - { - if (remoteSystemIndex!=(unsigned int) -1 && idx==remoteSystemIndex) - continue; - - if ( remoteSystemList[ idx ].isActive && remoteSystemList[ idx ].systemAddress != UNASSIGNED_SYSTEM_ADDRESS ) - sendList[sendListSize++]=idx; - } - } - - if (sendListSize==0) - { - #if !defined(USE_ALLOCA) - rakFree_Ex(sendList, _FILE_AND_LINE_ ); - #endif - - return false; - } - - for (sendListIndex=0; sendListIndex < sendListSize; sendListIndex++) - { - // Send may split the packet and thus deallocate data. Don't assume data is valid if we use the callerAllocationData - bool useData = useCallerDataAllocation && callerDataAllocationUsed==false && sendListIndex+1==sendListSize; - remoteSystemList[sendList[sendListIndex]].reliabilityLayer.Send( data, numberOfBitsToSend, priority, reliability, orderingChannel, useData==false, remoteSystemList[sendList[sendListIndex]].MTUSize, currentTime, receipt ); - if (useData) - callerDataAllocationUsed=true; - - if (reliability==MafiaNet::Reliability::Reliable || - reliability==MafiaNet::Reliability::ReliableOrdered || - reliability==MafiaNet::Reliability::ReliableSequenced || - reliability==MafiaNet::Reliability::ReliableWithAckReceipt || - reliability==MafiaNet::Reliability::ReliableOrderedWithAckReceipt -// || -// reliability==RELIABLE_SEQUENCED_WITH_ACK_RECEIPT - ) - remoteSystemList[sendList[sendListIndex]].lastReliableSend=(MafiaNet::TimeMS)(currentTime/(MafiaNet::TimeUS)1000); - } - -#if !defined(USE_ALLOCA) - rakFree_Ex(sendList, _FILE_AND_LINE_ ); -#endif - - // Return value only meaningful if true was passed for useCallerDataAllocation. Means the reliability layer used that data copy, so the caller should not deallocate it - return callerDataAllocationUsed; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::ResetSendReceipt(void) -{ - sendReceiptSerialMutex.Lock(); - sendReceiptSerial=1; - sendReceiptSerialMutex.Unlock(); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::OnConnectedPong(MafiaNet::Time sendPingTime, MafiaNet::Time sendPongTime, RemoteSystemStruct *remoteSystem) -{ - MafiaNet::Time ping; -// MafiaNet::TimeMS lastPing; - MafiaNet::Time time = MafiaNet::GetTime(); // Update the time value to be accurate - if (time > sendPingTime) - ping = time - sendPingTime; - else - ping=0; - -// lastPing = remoteSystem->pingAndClockDifferential[ remoteSystem->pingAndClockDifferentialWriteIndex ].pingTime; - - remoteSystem->pingAndClockDifferential[ remoteSystem->pingAndClockDifferentialWriteIndex ].pingTime = ( unsigned short ) ping; - // Thanks to Chris Taylor (cat02e@fsu.edu) for the improved timestamping algorithm - // Divide each integer by 2, rather than the sum by 2, to prevent overflow - remoteSystem->pingAndClockDifferential[ remoteSystem->pingAndClockDifferentialWriteIndex ].clockDifferential = sendPongTime - ( time/2 + sendPingTime/2 ); - - if ( remoteSystem->lowestPing == (unsigned short)-1 || remoteSystem->lowestPing > (int) ping ) - remoteSystem->lowestPing = (unsigned short) ping; - - if ( ++( remoteSystem->pingAndClockDifferentialWriteIndex ) == (MafiaNet::Time) PING_TIMES_ARRAY_SIZE ) - remoteSystem->pingAndClockDifferentialWriteIndex = 0; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::ClearBufferedCommands(void) -{ - BufferedCommandStruct *bcs; - - while ((bcs=bufferedCommands.Pop())!=0) - { - if (bcs->data) - rakFree_Ex(bcs->data, _FILE_AND_LINE_ ); - - bufferedCommands.Deallocate(bcs, _FILE_AND_LINE_); - } - bufferedCommands.Clear(_FILE_AND_LINE_); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::ClearSocketQueryOutput(void) -{ - socketQueryOutput.Clear(_FILE_AND_LINE_); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::ClearRequestedConnectionList(void) -{ - DataStructures::Queue freeQueue; - requestedConnectionQueueMutex.Lock(); - while (requestedConnectionQueue.Size()) - freeQueue.Push(requestedConnectionQueue.Pop(), _FILE_AND_LINE_ ); - requestedConnectionQueueMutex.Unlock(); - unsigned i; - for (i=0; i < freeQueue.Size(); i++) - { -#if LIBCAT_SECURITY==1 - CAT_AUDIT_PRINTF("AUDIT: In ClearRequestedConnectionList(), Deleting freeQueue index %i client_handshake %x\n", i, freeQueue[i]->client_handshake); - MafiaNet::OP_DELETE(freeQueue[i]->client_handshake,_FILE_AND_LINE_); -#endif - MafiaNet::OP_DELETE(freeQueue[i], _FILE_AND_LINE_ ); - } -} -inline void RakPeer::AddPacketToProducer(MafiaNet::Packet *p) -{ - packetReturnMutex.Lock(); - packetReturnQueue.Push(p,_FILE_AND_LINE_); - packetReturnMutex.Unlock(); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -union Buff6AndBuff8 -{ - unsigned char buff6[6]; - uint64_t buff8; -}; -uint64_t RakPeerInterface::Get64BitUniqueRandomNumber(void) -{ - // Mac address is a poor solution because you can't have multiple connections from the same system - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#if defined(_WIN32) - uint64_t g= MafiaNet::GetTimeUS(); - - MafiaNet::TimeUS lastTime, thisTime; - int j; - // Sleep a small random time, then use the last 4 bits as a source of randomness - for (j=0; j < 8; j++) - { - lastTime = MafiaNet::GetTimeUS(); - RakSleep(1); - RakSleep(0); - thisTime = MafiaNet::GetTimeUS(); - MafiaNet::TimeUS diff = thisTime-lastTime; - unsigned int diff4Bits = (unsigned int) (diff & 15); - diff4Bits <<= 32-4; - diff4Bits >>= j*4; - ((char*)&g)[j] ^= diff4Bits; - } - return g; - -#else - struct timeval tv; - gettimeofday(&tv, nullptr); - return tv.tv_usec + tv.tv_sec * 1000000; -#endif -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::GenerateGUID(void) -{ - myGuid.g=Get64BitUniqueRandomNumber(); - -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// void MafiaNet::ProcessPortUnreachable( SystemAddress systemAddress, RakPeer *rakPeer ) -// { -// (void) binaryAddress; -// (void) port; -// (void) rakPeer; -// -// } -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -namespace MafiaNet { -bool ProcessOfflineNetworkPacket( SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNetSocket2* rakNetSocket, bool *isOfflineMessage, MafiaNet::TimeUS timeRead ) -{ - (void) timeRead; - RakPeer::RemoteSystemStruct *remoteSystem; - MafiaNet::Packet *packet; - unsigned i; - - - char str1[64]; - systemAddress.ToString(false, str1,static_cast(64)); - if (rakPeer->IsBanned( str1 )) - { - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketReceive(data, length*8, systemAddress); - - MafiaNet::BitStream bs; - bs.Write((MessageID)ID_CONNECTION_BANNED); - bs.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); - bs.Write(rakPeer->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); - - - RNS2_SendParameters bsp; - bsp.data = (char*) bs.GetData(); - bsp.length = bs.GetNumberOfBytesUsed(); - bsp.systemAddress = systemAddress; - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketSend((char*) bs.GetData(), bs.GetNumberOfBitsUsed(), systemAddress); - rakNetSocket->Send(&bsp, _FILE_AND_LINE_); - -/* - unsigned i; - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketSend((char*) bs.GetData(), bs.GetNumberOfBitsUsed(), systemAddress); - SocketLayer::SendTo( rakNetSocket, (char*) bs.GetData(), bs.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); - */ - - return true; - } - - - - // The reason for all this is that the reliability layer has no way to tell between offline messages that arrived late for a player that is now connected, - // and a regular encoding. So I insert OFFLINE_MESSAGE_DATA_ID into the stream, the encoding of which is essentially impossible to hit by chance - if (length <=2) - { - *isOfflineMessage=true; - } - else if ( - ((unsigned char)data[0] == ID_UNCONNECTED_PING || - (unsigned char)data[0] == ID_UNCONNECTED_PING_OPEN_CONNECTIONS) && - length >= sizeof(unsigned char) + sizeof(MafiaNet::Time) + sizeof(OFFLINE_MESSAGE_DATA_ID)) - { - *isOfflineMessage=memcmp(data+sizeof(unsigned char) + sizeof(MafiaNet::Time), OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID))==0; - } - else if ((unsigned char)data[0] == ID_UNCONNECTED_PONG && (size_t) length >= sizeof(unsigned char) + sizeof(MafiaNet::TimeMS) + RakNetGUID::size() + sizeof(OFFLINE_MESSAGE_DATA_ID)) - { - *isOfflineMessage=memcmp(data+sizeof(unsigned char) + sizeof(MafiaNet::Time) + RakNetGUID::size(), OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID))==0; - } - else if ( - (unsigned char)data[0] == ID_OUT_OF_BAND_INTERNAL && - (size_t) length >= sizeof(MessageID) + RakNetGUID::size() + sizeof(OFFLINE_MESSAGE_DATA_ID)) - { - *isOfflineMessage=memcmp(data+sizeof(MessageID) + RakNetGUID::size(), OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID))==0; - } - else if ( - ( - (unsigned char)data[0] == ID_OPEN_CONNECTION_REPLY_1 || - (unsigned char)data[0] == ID_OPEN_CONNECTION_REPLY_2 || - (unsigned char)data[0] == ID_OPEN_CONNECTION_REQUEST_1 || - (unsigned char)data[0] == ID_OPEN_CONNECTION_REQUEST_2 || - (unsigned char)data[0] == ID_CONNECTION_ATTEMPT_FAILED || - (unsigned char)data[0] == ID_NO_FREE_INCOMING_CONNECTIONS || - (unsigned char)data[0] == ID_CONNECTION_BANNED || - (unsigned char)data[0] == ID_ALREADY_CONNECTED || - (unsigned char)data[0] == ID_IP_RECENTLY_CONNECTED) && - (size_t) length >= sizeof(MessageID) + RakNetGUID::size() + sizeof(OFFLINE_MESSAGE_DATA_ID)) - { - *isOfflineMessage=memcmp(data+sizeof(MessageID), OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID))==0; - } - else if (((unsigned char)data[0] == ID_INCOMPATIBLE_PROTOCOL_VERSION&& - (size_t) length == sizeof(MessageID)*2 + RakNetGUID::size() + sizeof(OFFLINE_MESSAGE_DATA_ID))) - { - *isOfflineMessage=memcmp(data+sizeof(MessageID)*2, OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID))==0; - } - else - { - *isOfflineMessage=false; - } - - if (*isOfflineMessage) - { - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketReceive(data, length*8, systemAddress); - - // These are all messages from unconnected systems. Messages here can be any size, but are never processed from connected systems. - if ( ( (unsigned char) data[ 0 ] == ID_UNCONNECTED_PING_OPEN_CONNECTIONS - || (unsigned char)(data)[0] == ID_UNCONNECTED_PING) && length >= sizeof(unsigned char)+sizeof(MafiaNet::Time)+sizeof(OFFLINE_MESSAGE_DATA_ID) ) - { - if ( (unsigned char)(data)[0] == ID_UNCONNECTED_PING || - rakPeer->AllowIncomingConnections() ) // Open connections with players - { - MafiaNet::BitStream inBitStream( (unsigned char *) data, length, false ); - inBitStream.IgnoreBits(8); - MafiaNet::Time sendPingTime; - inBitStream.Read(sendPingTime); - inBitStream.IgnoreBytes(sizeof(OFFLINE_MESSAGE_DATA_ID)); - RakNetGUID remoteGuid=UNASSIGNED_RAKNET_GUID; - inBitStream.Read(remoteGuid); - - MafiaNet::BitStream outBitStream; - outBitStream.Write((MessageID)ID_UNCONNECTED_PONG); // Should be named ID_UNCONNECTED_PONG eventually - outBitStream.Write(sendPingTime); - outBitStream.Write(rakPeer->myGuid); - outBitStream.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); - - rakPeer->rakPeerMutexes[ RakPeer::offlinePingResponse_Mutex ].Lock(); - // They are connected, so append offline ping data - outBitStream.Write( (char*)rakPeer->offlinePingResponse.GetData(), rakPeer->offlinePingResponse.GetNumberOfBytesUsed() ); - rakPeer->rakPeerMutexes[ RakPeer::offlinePingResponse_Mutex ].Unlock(); - - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*)outBitStream.GetData(), outBitStream.GetNumberOfBytesUsed(), systemAddress); - - RNS2_SendParameters bsp; - bsp.data = (char*) outBitStream.GetData(); - bsp.length = outBitStream.GetNumberOfBytesUsed(); - bsp.systemAddress = systemAddress; - rakNetSocket->Send(&bsp, _FILE_AND_LINE_); - - // SocketLayer::SendTo( rakNetSocket, (const char*)outBitStream.GetData(), (unsigned int) outBitStream.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); - - packet=rakPeer->AllocPacket(sizeof(MessageID), _FILE_AND_LINE_); - packet->data[0]=data[0]; - packet->systemAddress = systemAddress; - packet->guid=remoteGuid; - packet->systemAddress.systemIndex = ( SystemIndex ) rakPeer->GetIndexFromSystemAddress( systemAddress, true ); - packet->guid.systemIndex=packet->systemAddress.systemIndex; - rakPeer->AddPacketToProducer(packet); - } - } - // UNCONNECTED MESSAGE Pong with no data. - else if ((unsigned char) data[ 0 ] == ID_UNCONNECTED_PONG && (size_t) length >= sizeof(unsigned char)+sizeof(MafiaNet::Time)+RakNetGUID::size()+sizeof(OFFLINE_MESSAGE_DATA_ID) && (size_t) length < sizeof(unsigned char)+sizeof(MafiaNet::Time)+RakNetGUID::size()+sizeof(OFFLINE_MESSAGE_DATA_ID)+MAX_OFFLINE_DATA_LENGTH) - { - packet=rakPeer->AllocPacket((unsigned int) (length-sizeof(OFFLINE_MESSAGE_DATA_ID)-RakNetGUID::size()-sizeof(MafiaNet::Time)+sizeof(MafiaNet::TimeMS)), _FILE_AND_LINE_); - MafiaNet::BitStream bsIn((unsigned char*) data, length, false); - bsIn.IgnoreBytes(sizeof(unsigned char)); - MafiaNet::Time ping; - bsIn.Read(ping); - bsIn.Read(packet->guid); - - MafiaNet::BitStream bsOut((unsigned char*) packet->data, packet->length, false); - bsOut.ResetWritePointer(); - bsOut.Write((unsigned char)ID_UNCONNECTED_PONG); - MafiaNet::TimeMS pingMS=(MafiaNet::TimeMS)ping; - bsOut.Write(pingMS); - bsOut.WriteAlignedBytes( - (const unsigned char*)data+sizeof(unsigned char)+sizeof(MafiaNet::Time)+RakNetGUID::size()+sizeof(OFFLINE_MESSAGE_DATA_ID), - length-sizeof(unsigned char)-sizeof(MafiaNet::Time)-RakNetGUID::size()-sizeof(OFFLINE_MESSAGE_DATA_ID) - ); - - packet->systemAddress = systemAddress; - packet->systemAddress.systemIndex = ( SystemIndex ) rakPeer->GetIndexFromSystemAddress( systemAddress, true ); - packet->guid.systemIndex=packet->systemAddress.systemIndex; - rakPeer->AddPacketToProducer(packet); - } - else if ((unsigned char) data[ 0 ] == ID_OUT_OF_BAND_INTERNAL && - (size_t) length > sizeof(OFFLINE_MESSAGE_DATA_ID)+sizeof(MessageID)+RakNetGUID::size() && - (size_t) length < MAX_OFFLINE_DATA_LENGTH+sizeof(OFFLINE_MESSAGE_DATA_ID)+sizeof(MessageID)+RakNetGUID::size()) - { - unsigned int dataLength = (unsigned int) (length-sizeof(OFFLINE_MESSAGE_DATA_ID)-RakNetGUID::size()-sizeof(MessageID)); - RakAssert(dataLength<1024); - packet=rakPeer->AllocPacket(dataLength+1, _FILE_AND_LINE_); - RakAssert(packet->length<1024); - - MafiaNet::BitStream bs2((unsigned char*) data, length, false); - bs2.IgnoreBytes(sizeof(MessageID)); - bs2.Read(packet->guid); - - if (data[sizeof(OFFLINE_MESSAGE_DATA_ID)+sizeof(MessageID) + RakNetGUID::size()]==ID_ADVERTISE_SYSTEM) - { - packet->length--; - packet->bitSize=BYTES_TO_BITS(packet->length); - packet->data[0]=ID_ADVERTISE_SYSTEM; - memcpy(packet->data+1, data+sizeof(OFFLINE_MESSAGE_DATA_ID)+sizeof(MessageID)*2 + RakNetGUID::size(), dataLength-1); - } - else - { - packet->data[0]=ID_OUT_OF_BAND_INTERNAL; - memcpy(packet->data+1, data+sizeof(OFFLINE_MESSAGE_DATA_ID)+sizeof(MessageID) + RakNetGUID::size(), dataLength); - } - - packet->systemAddress = systemAddress; - packet->systemAddress.systemIndex = ( SystemIndex ) rakPeer->GetIndexFromSystemAddress( systemAddress, true ); - packet->guid.systemIndex=packet->systemAddress.systemIndex; - rakPeer->AddPacketToProducer(packet); - } - else if ((unsigned char)(data)[0] == (MessageID)ID_OPEN_CONNECTION_REPLY_1) - { - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketReceive(data, length*8, systemAddress); - - MafiaNet::BitStream bsIn((unsigned char*) data,length,false); - bsIn.IgnoreBytes(sizeof(MessageID)); - bsIn.IgnoreBytes(sizeof(OFFLINE_MESSAGE_DATA_ID)); - RakNetGUID serverGuid; - bsIn.Read(serverGuid); - unsigned char serverHasSecurity; - uint32_t cookie; - (void) cookie; - bsIn.Read(serverHasSecurity); - // Even if the server has security, it may not be required of us if we are in the security exception list - if (serverHasSecurity) - { - bsIn.Read(cookie); - } - - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_OPEN_CONNECTION_REQUEST_2); - bsOut.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); - if (serverHasSecurity) - bsOut.Write(cookie); - - rakPeer->requestedConnectionQueueMutex.Lock(); - for (i=0; i < rakPeer->requestedConnectionQueue.Size(); i++) - { - RakPeer::RequestedConnectionStruct *rcs; - rcs=rakPeer->requestedConnectionQueue[i]; - if (rcs->systemAddress==systemAddress) - { - if (serverHasSecurity) - { -#if LIBCAT_SECURITY==1 - unsigned char public_key[cat::EasyHandshake::PUBLIC_KEY_BYTES]; - bsIn.ReadAlignedBytes(public_key, sizeof(public_key)); - - if (rcs->publicKeyMode==PKM_ACCEPT_ANY_PUBLIC_KEY) - { - memcpy(rcs->remote_public_key, public_key, cat::EasyHandshake::PUBLIC_KEY_BYTES); - if (!rcs->client_handshake->Initialize(public_key) || - !rcs->client_handshake->GenerateChallenge(rcs->handshakeChallenge)) - { - CAT_AUDIT_PRINTF("AUDIT: Server passed a bad public key with PKM_ACCEPT_ANY_PUBLIC_KEY"); - rakPeer->requestedConnectionQueueMutex.Unlock(); - return true; - } - } - - if (cat::SecureEqual(public_key, - rcs->remote_public_key, - cat::EasyHandshake::PUBLIC_KEY_BYTES)==false) - { - rakPeer->requestedConnectionQueueMutex.Unlock(); - CAT_AUDIT_PRINTF("AUDIT: Expected public key does not match what was sent by server -- Reporting back ID_PUBLIC_KEY_MISMATCH to user\n"); - - packet=rakPeer->AllocPacket(sizeof( char ), _FILE_AND_LINE_); - packet->data[ 0 ] = ID_PUBLIC_KEY_MISMATCH; // Attempted a connection and couldn't - packet->bitSize = ( sizeof( char ) * 8); - packet->systemAddress = rcs->systemAddress; - packet->guid=serverGuid; - rakPeer->AddPacketToProducer(packet); - return true; - } - - if (rcs->client_handshake==0) - { - // Message does not contain a challenge - // We might still pass if we are in the security exception list - bsOut.Write((unsigned char)0); - } - else - { - // Message contains a challenge - bsOut.Write((unsigned char)1); - // challenge - CAT_AUDIT_PRINTF("AUDIT: Sending challenge\n"); - bsOut.WriteAlignedBytes((const unsigned char*) rcs->handshakeChallenge,cat::EasyHandshake::CHALLENGE_BYTES); - } -#else // LIBCAT_SECURITY - // Message does not contain a challenge - bsOut.Write((unsigned char)0); -#endif // LIBCAT_SECURITY - } - else - { - // Server does not need security -#if LIBCAT_SECURITY==1 - if (rcs->client_handshake!=0) - { - rakPeer->requestedConnectionQueueMutex.Unlock(); - CAT_AUDIT_PRINTF("AUDIT: Security disabled by server but we expected security (indicated by client_handshake not null) so failing!\n"); - - packet=rakPeer->AllocPacket(sizeof( char ), _FILE_AND_LINE_); - packet->data[ 0 ] = ID_OUR_SYSTEM_REQUIRES_SECURITY; // Attempted a connection and couldn't - packet->bitSize = ( sizeof( char ) * 8); - packet->systemAddress = rcs->systemAddress; - packet->guid=serverGuid; - rakPeer->AddPacketToProducer(packet); - return true; - } -#endif // LIBCAT_SECURITY - - } - - uint16_t mtu; - bsIn.Read(mtu); - - // Binding address - bsOut.Write(rcs->systemAddress); - rakPeer->requestedConnectionQueueMutex.Unlock(); - // MTU - bsOut.Write(mtu); - // Our guid - bsOut.Write(rakPeer->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); - - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*) bsOut.GetData(), bsOut.GetNumberOfBitsUsed(), rcs->systemAddress); - - // SocketLayer::SendTo( rakPeer->socketList[rcs->socketIndex], (const char*) bsOut.GetData(), bsOut.GetNumberOfBytesUsed(), rcs->systemAddress, _FILE_AND_LINE_ ); - - RNS2_SendParameters bsp; - bsp.data = (char*) bsOut.GetData(); - bsp.length = bsOut.GetNumberOfBytesUsed(); - bsp.systemAddress = systemAddress; - rakNetSocket->Send(&bsp, _FILE_AND_LINE_); - - return true; - } - } - rakPeer->requestedConnectionQueueMutex.Unlock(); - } - else if ((unsigned char)(data)[0] == (MessageID)ID_OPEN_CONNECTION_REPLY_2) - { - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketReceive(data, length*8, systemAddress); - - MafiaNet::BitStream bs((unsigned char*) data,length,false); - bs.IgnoreBytes(sizeof(MessageID)); - bs.IgnoreBytes(sizeof(OFFLINE_MESSAGE_DATA_ID)); - RakNetGUID guid; - bs.Read(guid); - SystemAddress bindingAddress; - bool b = bs.Read(bindingAddress); - RakAssert(b); - uint16_t mtu; - b=bs.Read(mtu); - RakAssert(b); - bool doSecurity=false; - b=bs.Read(doSecurity); - RakAssert(b); - -#if LIBCAT_SECURITY==1 - char answer[cat::EasyHandshake::ANSWER_BYTES]; - CAT_AUDIT_PRINTF("AUDIT: Got ID_OPEN_CONNECTION_REPLY_2 and given doSecurity=%i\n", (int)doSecurity); - if (doSecurity) - { - CAT_AUDIT_PRINTF("AUDIT: Reading cookie and public key\n"); - bs.ReadAlignedBytes((unsigned char*) answer, sizeof(answer)); - } - cat::ClientEasyHandshake *client_handshake=0; -#endif // LIBCAT_SECURITY - - RakPeer::RequestedConnectionStruct *rcs; - bool unlock=true; - rakPeer->requestedConnectionQueueMutex.Lock(); - for (i=0; i < rakPeer->requestedConnectionQueue.Size(); i++) - { - rcs=rakPeer->requestedConnectionQueue[i]; - - - if (rcs->systemAddress==systemAddress) - { -#if LIBCAT_SECURITY==1 - CAT_AUDIT_PRINTF("AUDIT: System address matches an entry in the requestedConnectionQueue and doSecurity=%i\n", (int)doSecurity); - if (doSecurity) - { - if (rcs->client_handshake==0) - { - CAT_AUDIT_PRINTF("AUDIT: Server wants security but we didn't set a public key -- Reporting back ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY to user\n"); - rakPeer->requestedConnectionQueueMutex.Unlock(); - - packet=rakPeer->AllocPacket(2, _FILE_AND_LINE_); - packet->data[ 0 ] = ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY; // Attempted a connection and couldn't - packet->data[ 1 ] = 0; // Indicate server public key is missing - packet->bitSize = ( sizeof( char ) * 8); - packet->systemAddress = rcs->systemAddress; - packet->guid=guid; - rakPeer->AddPacketToProducer(packet); - return true; - } - - CAT_AUDIT_PRINTF("AUDIT: Looks good, preparing to send challenge to server! client_handshake = %x\n", client_handshake); - } - -#endif // LIBCAT_SECURITY - - rakPeer->requestedConnectionQueueMutex.Unlock(); - unlock=false; - - RakAssert(rcs->actionToTake==RakPeer::RequestedConnectionStruct::CONNECT); - // You might get this when already connected because of cross-connections - bool thisIPConnectedRecently=false; - remoteSystem=rakPeer->GetRemoteSystemFromSystemAddress( systemAddress, true, true ); - if (remoteSystem==0) - { - if (rcs->socket == 0) - { - remoteSystem=rakPeer->AssignSystemAddressToRemoteSystemList(systemAddress, RakPeer::RemoteSystemStruct::UNVERIFIED_SENDER, rakNetSocket, &thisIPConnectedRecently, bindingAddress, mtu, guid, doSecurity); - } - else - { - remoteSystem=rakPeer->AssignSystemAddressToRemoteSystemList(systemAddress, RakPeer::RemoteSystemStruct::UNVERIFIED_SENDER, rcs->socket, &thisIPConnectedRecently, bindingAddress, mtu, guid, doSecurity); - } - } - - // 4/13/09 Attackers can flood ID_OPEN_CONNECTION_REQUEST and use up all available connection slots - // Ignore connection attempts if this IP address connected within the last 100 milliseconds - if (thisIPConnectedRecently==false) - { - // Don't check GetRemoteSystemFromGUID, server will verify - if (remoteSystem) - { - // Move pointer from RequestedConnectionStruct to RemoteSystemStruct -#if LIBCAT_SECURITY==1 - cat::u8 ident[cat::EasyHandshake::IDENTITY_BYTES]; - bool doIdentity = false; - - if (rcs->client_handshake) - { - CAT_AUDIT_PRINTF("AUDIT: Processing answer\n"); - if (rcs->publicKeyMode == PKM_USE_TWO_WAY_AUTHENTICATION) - { - if (!rcs->client_handshake->ProcessAnswerWithIdentity(answer, ident, remoteSystem->reliabilityLayer.GetAuthenticatedEncryption())) - { - CAT_AUDIT_PRINTF("AUDIT: Processing answer -- Invalid Answer\n"); - return true; - } - - doIdentity = true; - } - else - { - if (!rcs->client_handshake->ProcessAnswer(answer, remoteSystem->reliabilityLayer.GetAuthenticatedEncryption())) - { - CAT_AUDIT_PRINTF("AUDIT: Processing answer -- Invalid Answer\n"); - return true; - } - } - CAT_AUDIT_PRINTF("AUDIT: Success!\n"); - - MafiaNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); - rcs->client_handshake=0; - } -#endif // LIBCAT_SECURITY - - remoteSystem->weInitiatedTheConnection=true; - remoteSystem->connectMode=RakPeer::RemoteSystemStruct::REQUESTED_CONNECTION; - if (rcs->timeoutTime!=0) - remoteSystem->reliabilityLayer.SetTimeoutTime(rcs->timeoutTime); - - MafiaNet::BitStream temp; - temp.Write( (MessageID)ID_CONNECTION_REQUEST); - temp.Write(rakPeer->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); - temp.Write(MafiaNet::GetTime()); - -#if LIBCAT_SECURITY==1 - temp.Write((unsigned char)(doSecurity ? 1 : 0)); - - if (doSecurity) - { - unsigned char proof[32]; - remoteSystem->reliabilityLayer.GetAuthenticatedEncryption()->GenerateProof(proof, sizeof(proof)); - temp.WriteAlignedBytes(proof, sizeof(proof)); - - temp.Write((unsigned char)(doIdentity ? 1 : 0)); - - if (doIdentity) - { - temp.WriteAlignedBytes(ident, sizeof(ident)); - } - } -#else - temp.Write((unsigned char)0); -#endif // LIBCAT_SECURITY - - if ( rcs->outgoingPasswordLength > 0 ) - temp.Write( ( char* ) rcs->outgoingPassword, rcs->outgoingPasswordLength ); - - rakPeer->SendImmediate((char*)temp.GetData(), temp.GetNumberOfBitsUsed(), MafiaNet::Priority::Immediate, MafiaNet::Reliability::Reliable, 0, systemAddress, false, false, timeRead, 0 ); - } - else - { - // Failed, no connections available anymore - packet=rakPeer->AllocPacket(sizeof( char ), _FILE_AND_LINE_); - packet->data[ 0 ] = ID_CONNECTION_ATTEMPT_FAILED; // Attempted a connection and couldn't - packet->bitSize = ( sizeof( char ) * 8); - packet->systemAddress = rcs->systemAddress; - packet->guid=guid; - rakPeer->AddPacketToProducer(packet); - } - } - - rakPeer->requestedConnectionQueueMutex.Lock(); - for (unsigned int k=0; k < rakPeer->requestedConnectionQueue.Size(); k++) - { - if (rakPeer->requestedConnectionQueue[k]->systemAddress==systemAddress) - { - rakPeer->requestedConnectionQueue.RemoveAtIndex(k); - break; - } - } - rakPeer->requestedConnectionQueueMutex.Unlock(); - -#if LIBCAT_SECURITY==1 - CAT_AUDIT_PRINTF("AUDIT: Deleting client_handshake object %x and rcs->client_handshake object %x\n", client_handshake, rcs->client_handshake); - MafiaNet::OP_DELETE(client_handshake,_FILE_AND_LINE_); - MafiaNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); -#endif // LIBCAT_SECURITY - MafiaNet::OP_DELETE(rcs,_FILE_AND_LINE_); - - break; - } - } - - if (unlock) - rakPeer->requestedConnectionQueueMutex.Unlock(); - - return true; - - } - else if ((unsigned char)(data)[0] == (MessageID)ID_CONNECTION_ATTEMPT_FAILED || - (unsigned char)(data)[0] == (MessageID)ID_NO_FREE_INCOMING_CONNECTIONS || - (unsigned char)(data)[0] == (MessageID)ID_CONNECTION_BANNED || - (unsigned char)(data)[0] == (MessageID)ID_ALREADY_CONNECTED || - (unsigned char)(data)[0] == (MessageID)ID_INVALID_PASSWORD || - (unsigned char)(data)[0] == (MessageID)ID_IP_RECENTLY_CONNECTED || - (unsigned char)(data)[0] == (MessageID)ID_INCOMPATIBLE_PROTOCOL_VERSION) - { - - MafiaNet::BitStream bs((unsigned char*) data,length,false); - bs.IgnoreBytes(sizeof(MessageID)); - bs.IgnoreBytes(sizeof(OFFLINE_MESSAGE_DATA_ID)); - if ((unsigned char)(data)[0] == (MessageID)ID_INCOMPATIBLE_PROTOCOL_VERSION) - bs.IgnoreBytes(sizeof(unsigned char)); - - RakNetGUID guid; - bs.Read(guid); - - RakPeer::RequestedConnectionStruct *rcs; - bool connectionAttemptCancelled=false; - rakPeer->requestedConnectionQueueMutex.Lock(); - for (i=0; i < rakPeer->requestedConnectionQueue.Size(); i++) - { - rcs=rakPeer->requestedConnectionQueue[i]; - if (rcs->actionToTake==RakPeer::RequestedConnectionStruct::CONNECT && rcs->systemAddress==systemAddress) - { - connectionAttemptCancelled=true; - rakPeer->requestedConnectionQueue.RemoveAtIndex(i); - -#if LIBCAT_SECURITY==1 - CAT_AUDIT_PRINTF("AUDIT: Connection attempt canceled so deleting rcs->client_handshake object %x\n", rcs->client_handshake); - MafiaNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); -#endif // LIBCAT_SECURITY - MafiaNet::OP_DELETE(rcs,_FILE_AND_LINE_); - break; - } - } - - rakPeer->requestedConnectionQueueMutex.Unlock(); - - if (connectionAttemptCancelled) - { - // Tell user of connection attempt failed - packet=rakPeer->AllocPacket(sizeof( char ), _FILE_AND_LINE_); - packet->data[ 0 ] = data[0]; // Attempted a connection and couldn't - packet->bitSize = ( sizeof( char ) * 8); - packet->systemAddress = systemAddress; - packet->guid=guid; - rakPeer->AddPacketToProducer(packet); - } - } - else if ((unsigned char)(data)[0] == ID_OPEN_CONNECTION_REQUEST_1 && length > (int) (1+sizeof(OFFLINE_MESSAGE_DATA_ID))) - {/* - static int x = 0; - ++x; - - SystemAddress *addr = (SystemAddress*)&systemAddress; - addr->binaryAddress += x;*/ - - //RAKNET_DEBUG_PRINTF("%i:IOCR, ", __LINE__); - char remoteProtocol=data[1+sizeof(OFFLINE_MESSAGE_DATA_ID)]; - if (remoteProtocol!=RAKNET_PROTOCOL_VERSION) - { - MafiaNet::BitStream bs; - bs.Write((MessageID)ID_INCOMPATIBLE_PROTOCOL_VERSION); - bs.Write((unsigned char)RAKNET_PROTOCOL_VERSION); - bs.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); - bs.Write(rakPeer->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); - - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketSend((char*)bs.GetData(), bs.GetNumberOfBitsUsed(), systemAddress); - - // SocketLayer::SendTo( rakNetSocket, (char*)bs.GetData(), bs.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); - - RNS2_SendParameters bsp; - bsp.data = (char*) bs.GetData(); - bsp.length = bs.GetNumberOfBytesUsed(); - bsp.systemAddress = systemAddress; - - rakNetSocket->Send(&bsp, _FILE_AND_LINE_); - return true; - } - - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketReceive(data, length*8, systemAddress); - - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_OPEN_CONNECTION_REPLY_1); - bsOut.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); - bsOut.Write(rakPeer->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); -#if LIBCAT_SECURITY==1 - if (rakPeer->_using_security) - { - bsOut.Write((unsigned char) 1); // HasCookie Yes - // Write cookie - uint32_t cookie = rakPeer->_cookie_jar->Generate(&systemAddress.address,sizeof(systemAddress.address)); - CAT_AUDIT_PRINTF("AUDIT: Writing cookie %i to %i:%i\n", cookie, systemAddress); - bsOut.Write(cookie); - // Write my public key - bsOut.WriteAlignedBytes((const unsigned char *) rakPeer->my_public_key,sizeof(rakPeer->my_public_key)); - } - else -#endif // LIBCAT_SECURITY - bsOut.Write((unsigned char) 0); // HasCookie oN - - // MTU. Lower MTU if it is exceeds our own limit - if (length+UDP_HEADER_SIZE > MAXIMUM_MTU_SIZE) - bsOut.WriteCasted(MAXIMUM_MTU_SIZE); - else - bsOut.WriteCasted(length+UDP_HEADER_SIZE); - - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*) bsOut.GetData(), bsOut.GetNumberOfBitsUsed(), systemAddress); - // SocketLayer::SendTo( rakNetSocket, (const char*) bsOut.GetData(), bsOut.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); - - RNS2_SendParameters bsp; - bsp.data = (char*) bsOut.GetData(); - bsp.length = bsOut.GetNumberOfBytesUsed(); - bsp.systemAddress = systemAddress; - rakNetSocket->Send(&bsp, _FILE_AND_LINE_); - } - else if ((unsigned char)(data)[0] == ID_OPEN_CONNECTION_REQUEST_2) - { - SystemAddress bindingAddress; - RakNetGUID guid; - MafiaNet::BitStream bsOut; - MafiaNet::BitStream bs((unsigned char*) data, length, false); - bs.IgnoreBytes(sizeof(MessageID)); - bs.IgnoreBytes(sizeof(OFFLINE_MESSAGE_DATA_ID)); - - bool requiresSecurityOfThisClient=false; -#if LIBCAT_SECURITY==1 - char remoteHandshakeChallenge[cat::EasyHandshake::CHALLENGE_BYTES]; - - if (rakPeer->_using_security) - { - systemAddress.ToString(false, str1, static_cast(64)); - requiresSecurityOfThisClient=rakPeer->IsInSecurityExceptionList(str1)==false; - - uint32_t cookie; - bs.Read(cookie); - CAT_AUDIT_PRINTF("AUDIT: Got cookie %i from %i:%i\n", cookie, systemAddress); - if (rakPeer->_cookie_jar->Verify(&systemAddress.address,sizeof(systemAddress.address), cookie)==false) - { - return true; - } - CAT_AUDIT_PRINTF("AUDIT: Cookie good!\n"); - - unsigned char clientWroteChallenge; - bs.Read(clientWroteChallenge); - - if (requiresSecurityOfThisClient==true && clientWroteChallenge==0) - { - // Fail, client doesn't support security, and it is required - return true; - } - - if (clientWroteChallenge) - { - bs.ReadAlignedBytes((unsigned char*) remoteHandshakeChallenge, cat::EasyHandshake::CHALLENGE_BYTES); -#ifdef CAT_AUDIT - printf("AUDIT: RECV CHALLENGE "); - for (int ii = 0; ii < sizeof(remoteHandshakeChallenge); ++ii) - { - printf("%02x", (cat::u8)remoteHandshakeChallenge[ii]); - } - printf("\n"); -#endif - } - } -#endif // LIBCAT_SECURITY - - bs.Read(bindingAddress); - uint16_t mtu; - bs.Read(mtu); - bs.Read(guid); - - RakPeer::RemoteSystemStruct *rssFromSA = rakPeer->GetRemoteSystemFromSystemAddress( systemAddress, true, true ); - bool IPAddrInUse = rssFromSA != 0 && rssFromSA->isActive; - RakPeer::RemoteSystemStruct *rssFromGuid = rakPeer->GetRemoteSystemFromGUID(guid, true); - bool GUIDInUse = rssFromGuid != 0 && rssFromGuid->isActive; - - // IPAddrInUse, GuidInUse, outcome - // TRUE, , TRUE , ID_OPEN_CONNECTION_REPLY if they are the same, else ID_ALREADY_CONNECTED - // FALSE, , TRUE , ID_ALREADY_CONNECTED (someone else took this guid) - // TRUE, , FALSE , ID_ALREADY_CONNECTED (silently disconnected, restarted rakNet) - // FALSE , FALSE , Allow connection - - int outcome; - if (IPAddrInUse & GUIDInUse) - { - if (rssFromSA==rssFromGuid && rssFromSA->connectMode==RakPeer::RemoteSystemStruct::UNVERIFIED_SENDER) - { - // ID_OPEN_CONNECTION_REPLY if they are the same - outcome=1; - - // Note to self: If REQUESTED_CONNECTION, this means two systems attempted to connect to each other at the same time, and one finished first. - // Returns ID)_CONNECTION_REQUEST_ACCEPTED to one system, and ID_ALREADY_CONNECTED followed by ID_NEW_INCOMING_CONNECTION to another - } - else - { - // ID_ALREADY_CONNECTED (restarted raknet, connected again from same ip, plus someone else took this guid) - outcome=2; - } - } - else if (IPAddrInUse==false && GUIDInUse==true) - { - // ID_ALREADY_CONNECTED (someone else took this guid) - outcome=3; - } - else if (IPAddrInUse==true && GUIDInUse==false) - { - // ID_ALREADY_CONNECTED (silently disconnected, restarted rakNet) - outcome=4; - } - else - { - // Allow connection - outcome=0; - } - - MafiaNet::BitStream bsAnswer; - bsAnswer.Write((MessageID)ID_OPEN_CONNECTION_REPLY_2); - bsAnswer.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); - bsAnswer.Write(rakPeer->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); - bsAnswer.Write(systemAddress); - bsAnswer.Write(mtu); - bsAnswer.Write(requiresSecurityOfThisClient); - - if (outcome==1) - { - // Duplicate connection request packet from packetloss - // Send back the same answer -#if LIBCAT_SECURITY==1 - if (requiresSecurityOfThisClient) - { - CAT_AUDIT_PRINTF("AUDIT: Resending public key and answer from packetloss. Sending ID_OPEN_CONNECTION_REPLY_2\n"); - bsAnswer.WriteAlignedBytes((const unsigned char *) rssFromSA->answer,sizeof(rssFromSA->answer)); - } -#endif // LIBCAT_SECURITY - - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*) bsAnswer.GetData(), bsAnswer.GetNumberOfBitsUsed(), systemAddress); - // SocketLayer::SendTo( rakNetSocket, (const char*) bsAnswer.GetData(), bsAnswer.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); - - RNS2_SendParameters bsp; - bsp.data = (char*) bsAnswer.GetData(); - bsp.length = bsAnswer.GetNumberOfBytesUsed(); - bsp.systemAddress = systemAddress; - rakNetSocket->Send(&bsp, _FILE_AND_LINE_); - - return true; - } - else if (outcome!=0) - { - bsOut.Write((MessageID)ID_ALREADY_CONNECTED); - bsOut.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); - bsOut.Write(rakPeer->myGuid); - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*) bsOut.GetData(), bsOut.GetNumberOfBitsUsed(), systemAddress); - // SocketLayer::SendTo( rakNetSocket, (const char*) bsOut.GetData(), bsOut.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); - RNS2_SendParameters bsp; - bsp.data = (char*) bsOut.GetData(); - bsp.length = bsOut.GetNumberOfBytesUsed(); - bsp.systemAddress = systemAddress; - rakNetSocket->Send(&bsp, _FILE_AND_LINE_); - - return true; - } - - if (rakPeer->AllowIncomingConnections()==false) - { - bsOut.Write((MessageID)ID_NO_FREE_INCOMING_CONNECTIONS); - bsOut.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); - bsOut.Write(rakPeer->myGuid); - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*) bsOut.GetData(), bsOut.GetNumberOfBitsUsed(), systemAddress); - //SocketLayer::SendTo( rakNetSocket, (const char*) bsOut.GetData(), bsOut.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); - RNS2_SendParameters bsp; - bsp.data = (char*) bsOut.GetData(); - bsp.length = bsOut.GetNumberOfBytesUsed(); - bsp.systemAddress = systemAddress; - rakNetSocket->Send(&bsp, _FILE_AND_LINE_); - - return true; - } - - bool thisIPConnectedRecently=false; - rssFromSA = rakPeer->AssignSystemAddressToRemoteSystemList(systemAddress, RakPeer::RemoteSystemStruct::UNVERIFIED_SENDER, rakNetSocket, &thisIPConnectedRecently, bindingAddress, mtu, guid, requiresSecurityOfThisClient); - - if (thisIPConnectedRecently==true) - { - bsOut.Write((MessageID)ID_IP_RECENTLY_CONNECTED); - bsOut.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); - bsOut.Write(rakPeer->myGuid); - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*) bsOut.GetData(), bsOut.GetNumberOfBitsUsed(), systemAddress); - //SocketLayer::SendTo( rakNetSocket, (const char*) bsOut.GetData(), bsOut.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); - - RNS2_SendParameters bsp; - bsp.data = (char*) bsOut.GetData(); - bsp.length = bsOut.GetNumberOfBytesUsed(); - bsp.systemAddress = systemAddress; - rakNetSocket->Send(&bsp, _FILE_AND_LINE_); - - return true; - } - -#if LIBCAT_SECURITY==1 - if (requiresSecurityOfThisClient) - { - CAT_AUDIT_PRINTF("AUDIT: Writing public key. Sending ID_OPEN_CONNECTION_REPLY_2\n"); - if (rakPeer->_server_handshake->ProcessChallenge(remoteHandshakeChallenge, rssFromSA->answer, rssFromSA->reliabilityLayer.GetAuthenticatedEncryption() )) - { - CAT_AUDIT_PRINTF("AUDIT: Challenge good!\n"); - // Keep going to OK block - } - else - { - CAT_AUDIT_PRINTF("AUDIT: Challenge BAD!\n"); - - // Unassign this remote system - rakPeer->DereferenceRemoteSystem(systemAddress); - return true; - } - - bsAnswer.WriteAlignedBytes((const unsigned char *) rssFromSA->answer,sizeof(rssFromSA->answer)); - } -#endif // LIBCAT_SECURITY - - for (i=0; i < rakPeer->pluginListNTS.Size(); i++) - rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*) bsAnswer.GetData(), bsAnswer.GetNumberOfBitsUsed(), systemAddress); - // SocketLayer::SendTo( rakNetSocket, (const char*) bsAnswer.GetData(), bsAnswer.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); - RNS2_SendParameters bsp; - bsp.data = (char*) bsAnswer.GetData(); - bsp.length = bsAnswer.GetNumberOfBytesUsed(); - bsp.systemAddress = systemAddress; - rakNetSocket->Send(&bsp, _FILE_AND_LINE_); - } - return true; - } - - return false; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -// #med - deprecate this overload --- socketList[0] is not really ensured to be the correctly bound socket at all! -void ProcessNetworkPacket( SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, MafiaNet::TimeUS timeRead, BitStream &updateBitStream ) -{ - ProcessNetworkPacket(systemAddress,data,length,rakPeer,rakPeer->socketList[0],timeRead, updateBitStream); -} -void ProcessNetworkPacket( SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNetSocket2* rakNetSocket, MafiaNet::TimeUS timeRead, BitStream &updateBitStream ) -{ -#if LIBCAT_SECURITY==1 -#ifdef CAT_AUDIT - printf("AUDIT: RECV "); - for (int ii = 0; ii < length; ++ii) - { - printf("%02x", (cat::u8)data[ii]); - } - printf("\n"); -#endif -#endif // LIBCAT_SECURITY - - RakAssert(systemAddress.GetPort()); - bool isOfflineMessage; - if (ProcessOfflineNetworkPacket(systemAddress, data, length, rakPeer, rakNetSocket, &isOfflineMessage, timeRead)) - { - return; - } - -// MafiaNet::Packet *packet; - RakPeer::RemoteSystemStruct *remoteSystem; - - // See if this datagram came from a connected system - remoteSystem = rakPeer->GetRemoteSystemFromSystemAddress( systemAddress, true, true ); - if ( remoteSystem ) - { - // Handle regular incoming data - // HandleSocketReceiveFromConnectedPlayer is only safe to be called from the same thread as Update, which is this thread - if ( isOfflineMessage==false) - { - remoteSystem->reliabilityLayer.HandleSocketReceiveFromConnectedPlayer( - data, length, systemAddress, rakPeer->pluginListNTS, remoteSystem->MTUSize, - rakNetSocket, &rnr, timeRead, updateBitStream); - } - } - else - { - // int a=5; - // printf("--- Packet from unknown system %s\n", systemAddress.ToString()); - } -} - -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -unsigned int RakPeer::GenerateSeedFromGuid(void) -{ - /* - // Construct a random seed based on the initial guid value, and the last digits of the difference to each subsequent number - // This assumes that only the last 3 bits of each guidId integer has a meaningful amount of randomness between it and the prior number - unsigned int t = guid.g[0]; - unsigned int i; - for (i=1; i < sizeof(guid.g) / sizeof(guid.g[0]); i++) - { - unsigned int diff = guid.g[i]-guid.g[i-1]; - unsigned int diff3Bits = diff & 0x0007; - diff3Bits <<= 29; - diff3Bits >>= (i-1)*3; - t ^= diff3Bits; - } - - return t; - */ - return (unsigned int) ((myGuid.g >> 32) ^ myGuid.g); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void RakPeer::DerefAllSockets(void) -{ - unsigned int i; - for (i=0; i < socketList.Size(); i++) - { - MafiaNet::OP_DELETE(socketList[i], _FILE_AND_LINE_); - } - socketList.Clear(false, _FILE_AND_LINE_); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -unsigned int RakPeer::GetRakNetSocketFromUserConnectionSocketIndex(unsigned int userIndex) const -{ - unsigned int i; - for (i=0; i < socketList.Size(); i++) - { - if (socketList[i]->GetUserConnectionSocketIndex()==userIndex) - return i; - } - RakAssert("GetRakNetSocketFromUserConnectionSocketIndex failed" && 0); - return (unsigned int) -1; -} - -/* -// DS_APR -void RakPeer::ProcessChromePacket(RakNetSocket2 *s, const char *buffer, int dataSize, const SystemAddress& recvFromAddress, MafiaNet::TimeUS timeRead) -{ - RakAssert(buffer); - RakAssert(dataSize > 0); - RakAssert(recvFromAddress.GetPort()); - - RNS2RecvStruct *recvFromStruct; - recvFromStruct=bufferedPackets.Allocate( _FILE_AND_LINE_ ); - RakAssert(dataSize <= (int)sizeof(recvFromStruct->data)); - memcpy(recvFromStruct->data, buffer, dataSize); - recvFromStruct->bytesRead=dataSize; - recvFromStruct->systemAddress=recvFromAddress; - recvFromStruct->timeRead=timeRead; - bufferedPackets.Push(recvFromStruct); -} -*/ - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -/* -bool RakPeer::RunRecvFromOnce( RakNetSocket *s ) -{ - RakPeer::RecvFromStruct *recvFromStruct; - - recvFromStruct=bufferedPackets.Allocate( _FILE_AND_LINE_ ); - if (recvFromStruct != nullptr) - { - recvFromStruct->s=s; - SocketLayer::RecvFromBlocking(s, this, recvFromStruct->data, &recvFromStruct->bytesRead, &recvFromStruct->systemAddress, &recvFromStruct->timeRead); - - if (recvFromStruct->bytesRead>0) - { - RakAssert(recvFromStruct->systemAddress.GetPort()); - bufferedPackets.Push(recvFromStruct); - quitAndDataEvents.SetEvent(); - - // Got data - return true; - } - else - { - bufferedPackets.Deallocate(recvFromStruct, _FILE_AND_LINE_); - } - } - // No data - return false; -} -*/ -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -bool RakPeer::RunUpdateCycle(BitStream &updateBitStream ) -{ - RakPeer::RemoteSystemStruct * remoteSystem; - unsigned int activeSystemListIndex; - Packet *packet; - // int currentSentBytes,currentReceivedBytes; -// unsigned numberOfBytesUsed; -// BitSize_t numberOfBitsUsed; - //SystemAddress authoritativeClientSystemAddress; - BitSize_t bitSize; - unsigned int byteSize; - unsigned char *data; - SystemAddress systemAddress; - BufferedCommandStruct *bcs; - bool callerDataAllocationUsed; - RakNetStatistics *rnss; - MafiaNet::TimeUS timeNS=0; - MafiaNet::Time timeMS=0; - - // This is here so RecvFromBlocking actually gets data from the same thread - -#if defined(_WIN32) - // #high - review this - this is hardly correct to only work with the first socket here... - if (socketList[0]->GetSocketType()==RNS2T_WINDOWS && ((RNS2_Windows*)socketList[0])->GetSocketLayerOverride()) - { - int len; - SystemAddress sender; - char dataOut[ MAXIMUM_MTU_SIZE ]; - do { - len = ((RNS2_Windows*)socketList[0])->GetSocketLayerOverride()->RakNetRecvFrom(dataOut,&sender,true); - if (len>0) - ProcessNetworkPacket( sender, dataOut, len, this, socketList[0], MafiaNet::GetTimeUS(), updateBitStream ); - } while (len>0); - } -#endif - -// unsigned int socketListIndex; - RNS2RecvStruct *recvFromStruct; - while ((recvFromStruct=PopBufferedPacket())!=0) - { - /* - for (socketListIndex=0; socketListIndex < socketList.Size(); socketListIndex++) - { - if ((RakNetSocket*) socketList[socketListIndex]==recvFromStruct->s) - break; - } - if (socketListIndex!=socketList.Size()) - */ - ProcessNetworkPacket(recvFromStruct->systemAddress, recvFromStruct->data, recvFromStruct->bytesRead, this, recvFromStruct->socket, recvFromStruct->timeRead, updateBitStream); - DeallocRNS2RecvStruct(recvFromStruct, _FILE_AND_LINE_); - } - - while ((bcs=bufferedCommands.PopInaccurate())!=0) - { - if (bcs->command==BufferedCommandStruct::BCS_SEND) - { - // GetTime is a very slow call so do it once and as late as possible - if (timeNS==0) - { - timeNS = MafiaNet::GetTimeUS(); - timeMS = (MafiaNet::TimeMS)(timeNS/(MafiaNet::TimeUS)1000); - } - - callerDataAllocationUsed=SendImmediate((char*)bcs->data, bcs->numberOfBitsToSend, bcs->priority, bcs->reliability, bcs->orderingChannel, bcs->systemIdentifier, bcs->broadcast, true, timeNS, bcs->receipt); - if ( callerDataAllocationUsed==false ) - rakFree_Ex(bcs->data, _FILE_AND_LINE_ ); - - // Set the new connection state AFTER we call sendImmediate in case we are setting it to a disconnection state, which does not allow further sends - if (bcs->connectionMode!=RemoteSystemStruct::NO_ACTION ) - { - remoteSystem=GetRemoteSystem( bcs->systemIdentifier, true, true ); - if (remoteSystem) - remoteSystem->connectMode=bcs->connectionMode; - } - } - else if (bcs->command==BufferedCommandStruct::BCS_CLOSE_CONNECTION) - { - // bcs->socket may be null: the socket can be released between queuing this - // command and processing it here (e.g. during rapid connect/disconnect churn). - // RakAssert is a no-op in release (NDEBUG), so guard explicitly and fall back - // to the primary socket to avoid dereferencing null in CloseConnectionInternal2. - RakNetSocket2 *closeSocket = bcs->socket; - if (closeSocket == nullptr && socketList.Size() > 0) - closeSocket = socketList[0]; - if (closeSocket != nullptr) - CloseConnectionInternal2(bcs->systemIdentifier, false, true, bcs->orderingChannel, bcs->priority, *closeSocket); - } - else if (bcs->command==BufferedCommandStruct::BCS_CHANGE_SYSTEM_ADDRESS) - { - // Reroute - RakPeer::RemoteSystemStruct *rssFromGuid = GetRemoteSystem(bcs->systemIdentifier.rakNetGuid,true,true); - if (rssFromGuid!=0) - { - unsigned int existingSystemIndex = GetRemoteSystemIndex(rssFromGuid->systemAddress); - ReferenceRemoteSystem(bcs->systemIdentifier.systemAddress, existingSystemIndex); - } - } - else if (bcs->command==BufferedCommandStruct::BCS_GET_SOCKET) - { - SocketQueryOutput *sqo; - if (bcs->systemIdentifier.IsUndefined()) - { - sqo = socketQueryOutput.Allocate( _FILE_AND_LINE_ ); - sqo->sockets=socketList; - socketQueryOutput.Push(sqo); - } - else - { - remoteSystem=GetRemoteSystem( bcs->systemIdentifier, true, true ); - sqo = socketQueryOutput.Allocate( _FILE_AND_LINE_ ); - - sqo->sockets.Clear(false, _FILE_AND_LINE_); - if (remoteSystem) - { - sqo->sockets.Push(remoteSystem->rakNetSocket, _FILE_AND_LINE_ ); - } - else - { - // Leave empty smart pointer - } - socketQueryOutput.Push(sqo); - } - - } - -#ifdef _DEBUG - bcs->data=0; -#endif - - bufferedCommands.Deallocate(bcs, _FILE_AND_LINE_); - } - - if (requestedConnectionQueue.IsEmpty()==false) - { - if (timeNS==0) - { - timeNS = MafiaNet::GetTimeUS(); - timeMS = (MafiaNet::TimeMS)(timeNS/(MafiaNet::TimeUS)1000); - } - - bool condition1, condition2; - unsigned requestedConnectionQueueIndex=0; - requestedConnectionQueueMutex.Lock(); - while (requestedConnectionQueueIndex < requestedConnectionQueue.Size()) - { - RequestedConnectionStruct *rcs; - rcs = requestedConnectionQueue[requestedConnectionQueueIndex]; - requestedConnectionQueueMutex.Unlock(); - if (rcs->nextRequestTime < timeMS) - { - condition1=rcs->requestsMade==rcs->sendConnectionAttemptCount+1; - condition2=(bool)((rcs->systemAddress==UNASSIGNED_SYSTEM_ADDRESS)==1); - // If too many requests made or a hole then remove this if possible, otherwise invalidate it - if (condition1 || condition2) - { - if (rcs->data) - { - rakFree_Ex(rcs->data, _FILE_AND_LINE_ ); - rcs->data=0; - } - - if (condition1 && !condition2 && rcs->actionToTake==RequestedConnectionStruct::CONNECT) - { - // Tell user of connection attempt failed - packet=AllocPacket(sizeof( char ), _FILE_AND_LINE_); - packet->data[ 0 ] = ID_CONNECTION_ATTEMPT_FAILED; // Attempted a connection and couldn't - packet->bitSize = ( sizeof( char ) * 8); - packet->systemAddress = rcs->systemAddress; - AddPacketToProducer(packet); - } - -#if LIBCAT_SECURITY==1 - CAT_AUDIT_PRINTF("AUDIT: Connection attempt FAILED so deleting rcs->client_handshake object %x\n", rcs->client_handshake); - MafiaNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); -#endif - MafiaNet::OP_DELETE(rcs,_FILE_AND_LINE_); - - requestedConnectionQueueMutex.Lock(); - for (unsigned int k=0; k < requestedConnectionQueue.Size(); k++) - { - if (requestedConnectionQueue[k]==rcs) - { - requestedConnectionQueue.RemoveAtIndex(k); - break; - } - } - requestedConnectionQueueMutex.Unlock(); - } - else - { - - int MTUSizeIndex = rcs->requestsMade / (rcs->sendConnectionAttemptCount/NUM_MTU_SIZES); - if (MTUSizeIndex>=NUM_MTU_SIZES) - MTUSizeIndex=NUM_MTU_SIZES-1; - rcs->requestsMade++; - rcs->nextRequestTime=timeMS+rcs->timeBetweenSendConnectionAttemptsMS; - - MafiaNet::BitStream bitStream; - //WriteOutOfBandHeader(&bitStream, ID_USER_PACKET_ENUM); - bitStream.Write((MessageID)ID_OPEN_CONNECTION_REQUEST_1); - bitStream.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); - bitStream.Write((MessageID)RAKNET_PROTOCOL_VERSION); - bitStream.PadWithZeroToByteLength(mtuSizes[MTUSizeIndex]-UDP_HEADER_SIZE); - - char str[256]; - rcs->systemAddress.ToString(true,str,static_cast(256)); - - //RAKNET_DEBUG_PRINTF("%i:IOCR, ", __LINE__); - - unsigned i; - for (i=0; i < pluginListNTS.Size(); i++) - pluginListNTS[i]->OnDirectSocketSend((const char*) bitStream.GetData(), bitStream.GetNumberOfBitsUsed(), rcs->systemAddress); - - RakNetSocket2 *socketToUse; - if (rcs->socket == 0) - socketToUse = socketList[rcs->socketIndex]; - else - socketToUse = rcs->socket; - - rcs->systemAddress.FixForIPVersion(socketToUse->GetBoundAddress()); -#if !defined(__native_client__) - if (socketToUse->IsBerkleySocket()) - ((RNS2_Berkley*)socketToUse)->SetDoNotFragment(1); -#endif - -// SocketLayer::SetDoNotFragment(socketToUse, 1); - MafiaNet::Time sendToStart= MafiaNet::GetTime(); - - RNS2_SendParameters bsp; - bsp.data = (char*) bitStream.GetData(); - bsp.length = bitStream.GetNumberOfBytesUsed(); - bsp.systemAddress = rcs->systemAddress; - if (socketToUse->Send(&bsp, _FILE_AND_LINE_) == 10040) - // if (SocketLayer::SendTo( socketToUse, (const char*) bitStream.GetData(), bitStream.GetNumberOfBytesUsed(), rcs->systemAddress, _FILE_AND_LINE_ )==-10040) - { - // Don't use this MTU size again - rcs->requestsMade = (unsigned char) ((MTUSizeIndex + 1) * (rcs->sendConnectionAttemptCount/NUM_MTU_SIZES)); - rcs->nextRequestTime=timeMS; - } - else - { - MafiaNet::Time sendToEnd= MafiaNet::GetTime(); - if (sendToEnd-sendToStart>100) - { - // Drop to lowest MTU - int lowestMtuIndex = rcs->sendConnectionAttemptCount/NUM_MTU_SIZES * (NUM_MTU_SIZES - 1); - if (lowestMtuIndex > rcs->requestsMade) - { - rcs->requestsMade = (unsigned char) lowestMtuIndex; - rcs->nextRequestTime=timeMS; - } - else - rcs->requestsMade=(unsigned char)(rcs->sendConnectionAttemptCount+1); - } - } - // SocketLayer::SetDoNotFragment(socketToUse, 0); -#if !defined(__native_client__) - if (socketToUse->IsBerkleySocket()) - ((RNS2_Berkley*)socketToUse)->SetDoNotFragment(0); -#endif - - requestedConnectionQueueIndex++; - } - } - else - requestedConnectionQueueIndex++; - - requestedConnectionQueueMutex.Lock(); - } - requestedConnectionQueueMutex.Unlock(); - } - - // remoteSystemList in network thread - for ( activeSystemListIndex = 0; activeSystemListIndex < activeSystemListSize; ++activeSystemListIndex ) - //for ( remoteSystemIndex = 0; remoteSystemIndex < remoteSystemListSize; ++remoteSystemIndex ) - { - // I'm using systemAddress from remoteSystemList but am not locking it because this loop is called very frequently and it doesn't - // matter if we miss or do an extra update. The reliability layers themselves never care which player they are associated with - //systemAddress = remoteSystemList[ remoteSystemIndex ].systemAddress; - // Allow the systemAddress for this remote system list to change. We don't care if it changes now. - // remoteSystemList[ remoteSystemIndex ].allowSystemAddressAssigment=true; - - - // Found an active remote system - remoteSystem = activeSystemList[ activeSystemListIndex ]; - systemAddress = remoteSystem->systemAddress; - RakAssert(systemAddress!=UNASSIGNED_SYSTEM_ADDRESS); - // Update is only safe to call from the same thread that calls HandleSocketReceiveFromConnectedPlayer, - // which is this thread - - if (timeNS==0) - { - timeNS = MafiaNet::GetTimeUS(); - timeMS = (MafiaNet::TimeMS)(timeNS/(MafiaNet::TimeUS)1000); - //RAKNET_DEBUG_PRINTF("timeNS = %I64i timeMS=%i\n", timeNS, timeMS); - } - - - if (timeMS > remoteSystem->lastReliableSend && timeMS-remoteSystem->lastReliableSend > remoteSystem->reliabilityLayer.GetTimeoutTime()/2 && remoteSystem->connectMode==RemoteSystemStruct::CONNECTED) - { - // If no reliable packets are waiting for an ack, do a one byte reliable send so that disconnections are noticed - RakNetStatistics rakNetStatistics; - rnss=remoteSystem->reliabilityLayer.GetStatistics(&rakNetStatistics); - if (rnss->messagesInResendBuffer==0) - { - PingInternal( systemAddress, true, MafiaNet::Reliability::Reliable ); - - //remoteSystem->lastReliableSend=timeMS+remoteSystem->reliabilityLayer.GetTimeoutTime(); - remoteSystem->lastReliableSend=timeMS; - } - } - - if (endThreads) - // for the final call, make sure we send out any outstanding ACKs - remoteSystem->reliabilityLayer.UpdateAndForceACKs( remoteSystem->rakNetSocket, systemAddress, remoteSystem->MTUSize, timeNS, maxOutgoingBPS, pluginListNTS, &rnr, updateBitStream ); // systemAddress only used for the internet simulator test - else - remoteSystem->reliabilityLayer.Update( remoteSystem->rakNetSocket, systemAddress, remoteSystem->MTUSize, timeNS, maxOutgoingBPS, pluginListNTS, &rnr, updateBitStream ); // systemAddress only used for the internet simulator test - - // Check for failure conditions - if ( remoteSystem->reliabilityLayer.IsDeadConnection() || - ((remoteSystem->connectMode==RemoteSystemStruct::DISCONNECT_ASAP || remoteSystem->connectMode==RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY) && remoteSystem->reliabilityLayer.IsOutgoingDataWaiting()==false) || - (remoteSystem->connectMode==RemoteSystemStruct::DISCONNECT_ON_NO_ACK && (remoteSystem->reliabilityLayer.AreAcksWaiting()==false || remoteSystem->reliabilityLayer.AckTimeout(timeMS)==true)) || - (( - (remoteSystem->connectMode==RemoteSystemStruct::REQUESTED_CONNECTION || - remoteSystem->connectMode==RemoteSystemStruct::HANDLING_CONNECTION_REQUEST || - remoteSystem->connectMode==RemoteSystemStruct::UNVERIFIED_SENDER) - && timeMS > remoteSystem->connectionTime && timeMS - remoteSystem->connectionTime > 10000)) - ) - { - // RAKNET_DEBUG_PRINTF("timeMS=%i remoteSystem->connectionTime=%i\n", timeMS, remoteSystem->connectionTime ); - - // Failed. Inform the user? - // TODO - RakNet 4.0 - Return a different message identifier for DISCONNECT_ASAP_SILENTLY and DISCONNECT_ASAP than for DISCONNECT_ON_NO_ACK - // The first two mean we called CloseConnection(), the last means the other system sent us ID_DISCONNECTION_NOTIFICATION - if (remoteSystem->connectMode==RemoteSystemStruct::CONNECTED || remoteSystem->connectMode==RemoteSystemStruct::REQUESTED_CONNECTION - || remoteSystem->connectMode==RemoteSystemStruct::DISCONNECT_ASAP || remoteSystem->connectMode==RemoteSystemStruct::DISCONNECT_ON_NO_ACK) - { - -// MafiaNet::BitStream undeliveredMessages; -// remoteSystem->reliabilityLayer.GetUndeliveredMessages(&undeliveredMessages,remoteSystem->MTUSize); - -// packet=AllocPacket(sizeof( char ) + undeliveredMessages.GetNumberOfBytesUsed()); - // A graceful remote disconnect (DISCONNECT_ON_NO_ACK) may carry a reason payload stashed when the - // notification arrived. Only ID_DISCONNECTION_NOTIFICATION carries it; ID_CONNECTION_LOST and - // ID_CONNECTION_ATTEMPT_FAILED are locally synthesized and stay payload-less. - const bool attachReason = remoteSystem->connectMode==RemoteSystemStruct::DISCONNECT_ON_NO_ACK && remoteSystem->disconnectReasonData!=0; - const unsigned int reasonLength = attachReason ? remoteSystem->disconnectReasonLength : 0; - packet=AllocPacket(sizeof( char ) + reasonLength, _FILE_AND_LINE_); - if (remoteSystem->connectMode==RemoteSystemStruct::REQUESTED_CONNECTION) - packet->data[ 0 ] = ID_CONNECTION_ATTEMPT_FAILED; // Attempted a connection and couldn't - else if (remoteSystem->connectMode==RemoteSystemStruct::CONNECTED) - packet->data[ 0 ] = ID_CONNECTION_LOST; // DeadConnection - else - packet->data[ 0 ] = ID_DISCONNECTION_NOTIFICATION; // DeadConnection - - if (attachReason) - memcpy(packet->data + sizeof(unsigned char), remoteSystem->disconnectReasonData, reasonLength); - -// memcpy(packet->data+1, undeliveredMessages.GetData(), undeliveredMessages.GetNumberOfBytesUsed()); - - packet->guid = remoteSystem->guid; - packet->systemAddress = systemAddress; - packet->systemAddress.systemIndex = remoteSystem->remoteSystemIndex; - packet->guid.systemIndex=packet->systemAddress.systemIndex; - - AddPacketToProducer(packet); - } - // else connection shutting down, don't bother telling the user - -#ifdef _DO_PRINTF - RAKNET_DEBUG_PRINTF("Connection dropped for player %i:%i\n", systemAddress); -#endif - // we are about to close the connection to the remote system, we'd still make sure to send any outstanding ACKs, so for the remote system not unnecessarily waiting for these until its timeout - // (and trying to resend them unnecessarily) - remoteSystem->reliabilityLayer.UpdateAndForceACKs(remoteSystem->rakNetSocket, systemAddress, remoteSystem->MTUSize, timeNS, maxOutgoingBPS, pluginListNTS, &rnr, updateBitStream); - - CloseConnectionInternal2(systemAddress, false, true, 0, MafiaNet::Priority::Low, *(remoteSystem->rakNetSocket)); - continue; - } - - // Ping this guy if it is time to do so - if ( remoteSystem->connectMode==RemoteSystemStruct::CONNECTED && timeMS > remoteSystem->nextPingTime && ( occasionalPing || remoteSystem->lowestPing == (unsigned short)-1 ) ) - { - remoteSystem->nextPingTime = timeMS + 5000; - PingInternal( systemAddress, true, MafiaNet::Reliability::Unreliable ); - - // Update again immediately after this tick so the ping goes out right away - quitAndDataEvents.SetEvent(); - } - - // Find whoever has the lowest player ID - //if (systemAddress < authoritativeClientSystemAddress) - // authoritativeClientSystemAddress=systemAddress; - - // Does the reliability layer have any packets waiting for us? - // To be thread safe, this has to be called in the same thread as HandleSocketReceiveFromConnectedPlayer - bitSize = remoteSystem->reliabilityLayer.Receive( &data ); - - while ( bitSize > 0 ) - { - // These types are for internal use and should never arrive from a network packet - if (data[0]==ID_CONNECTION_ATTEMPT_FAILED) - { - RakAssert(0); - bitSize=0; - continue; - } - - // Fast and easy - just use the data that was returned - byteSize = (unsigned int) BITS_TO_BYTES( bitSize ); - - // For unknown senders we only accept a few specific packets - if (remoteSystem->connectMode==RemoteSystemStruct::UNVERIFIED_SENDER) - { - if ( (unsigned char)(data)[0] == ID_CONNECTION_REQUEST ) - { - ParseConnectionRequestPacket(remoteSystem, systemAddress, (const char*)data, byteSize); - rakFree_Ex(data, _FILE_AND_LINE_ ); - } - else - { - CloseConnectionInternal2(systemAddress, false, true, 0, MafiaNet::Priority::Low, *(remoteSystem->rakNetSocket)); -#ifdef _DO_PRINTF - RAKNET_DEBUG_PRINTF("Temporarily banning %i:%i for sending nonsense data\n", systemAddress); -#endif - - char str1[64]; - systemAddress.ToString(false, str1, static_cast(64)); - AddToBanList(str1, remoteSystem->reliabilityLayer.GetTimeoutTime()); - - - rakFree_Ex(data, _FILE_AND_LINE_ ); - } - } - else - { - // However, if we are connected we still take a connection request in case both systems are trying to connect to each other - // at the same time - if ( (unsigned char)(data)[0] == ID_CONNECTION_REQUEST ) - { - // 04/27/06 This is wrong. With cross connections, we can both have initiated the connection are in state REQUESTED_CONNECTION - // 04/28/06 Downgrading connections from connected will close the connection due to security at ((remoteSystem->connectMode!=RemoteSystemStruct::CONNECTED && time > remoteSystem->connectionTime && time - remoteSystem->connectionTime > 10000)) - if (remoteSystem->connectMode==RemoteSystemStruct::REQUESTED_CONNECTION) - { - ParseConnectionRequestPacket(remoteSystem, systemAddress, (const char*)data, byteSize); - } - else - { - - MafiaNet::BitStream bs((unsigned char*) data,byteSize,false); - bs.IgnoreBytes(sizeof(MessageID)); - bs.IgnoreBytes(sizeof(OFFLINE_MESSAGE_DATA_ID)); - bs.IgnoreBytes(RakNetGUID::size()); - MafiaNet::Time incomingTimestamp; - bs.Read(incomingTimestamp); - - // Got a connection request message from someone we are already connected to. Just reply normally. - // This can happen due to race conditions with the fully connected mesh - OnConnectionRequest( remoteSystem, incomingTimestamp ); - } - rakFree_Ex(data, _FILE_AND_LINE_ ); - } - else if ( (unsigned char) data[ 0 ] == ID_NEW_INCOMING_CONNECTION && byteSize > sizeof(unsigned char)+sizeof(unsigned int)+sizeof(unsigned short)+sizeof(MafiaNet::Time)*2 ) - { - if (remoteSystem->connectMode==RemoteSystemStruct::HANDLING_CONNECTION_REQUEST) - { - remoteSystem->connectMode=RemoteSystemStruct::CONNECTED; - PingInternal( systemAddress, true, MafiaNet::Reliability::Unreliable ); - - // Update again immediately after this tick so the ping goes out right away - quitAndDataEvents.SetEvent(); - - MafiaNet::BitStream inBitStream((unsigned char *) data, byteSize, false); - SystemAddress bsSystemAddress; - - inBitStream.IgnoreBits(8); - inBitStream.Read(bsSystemAddress); - for (unsigned int i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) - inBitStream.Read(remoteSystem->theirInternalSystemAddress[i]); - - MafiaNet::Time sendPingTime, sendPongTime; - inBitStream.Read(sendPingTime); - inBitStream.Read(sendPongTime); - OnConnectedPong(sendPingTime,sendPongTime,remoteSystem); - - // Overwrite the data in the packet - // NewIncomingConnectionStruct newIncomingConnectionStruct; - // MafiaNet::BitStream nICS_BS( data, NewIncomingConnectionStruct_Size, false ); - // newIncomingConnectionStruct.Deserialize( nICS_BS ); - - remoteSystem->myExternalSystemAddress = bsSystemAddress; - - // Bug: If A connects to B through R, A's firstExternalID is set to R. If A tries to send to R, sends to loopback because R==firstExternalID - // Correct fix is to specify in Connect() if target is through a proxy. - // However, in practice you have to connect to something else first anyway to know about the proxy. So setting once only is good enough - if (firstExternalID==UNASSIGNED_SYSTEM_ADDRESS) - { - firstExternalID=bsSystemAddress; - firstExternalID.debugPort=ntohs(firstExternalID.address.addr4.sin_port); - } - - // Send this info down to the game - packet=AllocPacket(byteSize, data, _FILE_AND_LINE_); - packet->bitSize = bitSize; - packet->systemAddress = systemAddress; - packet->systemAddress.systemIndex = remoteSystem->remoteSystemIndex; - packet->guid = remoteSystem->guid; - packet->guid.systemIndex=packet->systemAddress.systemIndex; - AddPacketToProducer(packet); - } - else - { - // Send to game even if already connected. This could happen when connecting to 127.0.0.1 - // Ignore, already connected - // rakFree_Ex(data, _FILE_AND_LINE_ ); - } - } - else if ( (unsigned char) data[ 0 ] == ID_CONNECTED_PONG && byteSize == sizeof(unsigned char)+sizeof(MafiaNet::Time)*2 ) - { - MafiaNet::Time sendPingTime, sendPongTime; - - // Copy into the ping times array the current time - the value returned - // First extract the sent ping - MafiaNet::BitStream inBitStream( (unsigned char *) data, byteSize, false ); - //PingStruct ps; - //ps.Deserialize(psBS); - inBitStream.IgnoreBits(8); - inBitStream.Read(sendPingTime); - inBitStream.Read(sendPongTime); - - OnConnectedPong(sendPingTime,sendPongTime,remoteSystem); - - rakFree_Ex(data, _FILE_AND_LINE_ ); - } - else if ( (unsigned char)data[0] == ID_CONNECTED_PING && byteSize == sizeof(unsigned char)+sizeof(MafiaNet::Time) ) - { - MafiaNet::BitStream inBitStream( (unsigned char *) data, byteSize, false ); - inBitStream.IgnoreBits(8); - MafiaNet::Time sendPingTime; - inBitStream.Read(sendPingTime); - - MafiaNet::BitStream outBitStream; - outBitStream.Write((MessageID)ID_CONNECTED_PONG); - outBitStream.Write(sendPingTime); - outBitStream.Write(MafiaNet::GetTime()); - SendImmediate( (char*)outBitStream.GetData(), outBitStream.GetNumberOfBitsUsed(), MafiaNet::Priority::Immediate, MafiaNet::Reliability::Unreliable, 0, systemAddress, false, false, MafiaNet::GetTimeUS(), 0 ); - - // Update again immediately after this tick so the ping goes out right away - quitAndDataEvents.SetEvent(); - - rakFree_Ex(data, _FILE_AND_LINE_ ); - } - else if ( (unsigned char) data[ 0 ] == ID_DISCONNECTION_NOTIFICATION ) - { - // Stash any reason payload (everything after the 1-byte ID) so it can ride along with the - // user-facing notification packet synthesized once outstanding ACKs are flushed. This raw - // reliability-layer buffer is freed below, so the bytes have to be copied out now. - ClearDisconnectReason(remoteSystem); - if (byteSize > sizeof(unsigned char)) - { - const unsigned int reasonLength = byteSize - (unsigned int) sizeof(unsigned char); - remoteSystem->disconnectReasonData = (unsigned char*) rakMalloc_Ex(reasonLength, _FILE_AND_LINE_); - if (remoteSystem->disconnectReasonData != 0) - { - memcpy(remoteSystem->disconnectReasonData, data + sizeof(unsigned char), reasonLength); - remoteSystem->disconnectReasonLength = reasonLength; - } - } - - // We shouldn't close the connection immediately because we need to ack the ID_DISCONNECTION_NOTIFICATION - remoteSystem->connectMode=RemoteSystemStruct::DISCONNECT_ON_NO_ACK; - rakFree_Ex(data, _FILE_AND_LINE_ ); - - // AddPacketToProducer(packet); - } - else if ( (unsigned char)(data)[0] == ID_DETECT_LOST_CONNECTIONS && byteSize == sizeof(unsigned char) ) - { - // Do nothing - rakFree_Ex(data, _FILE_AND_LINE_ ); - } - else if ( (unsigned char)(data)[0] == ID_INVALID_PASSWORD ) - { - if (remoteSystem->connectMode==RemoteSystemStruct::REQUESTED_CONNECTION) - { - packet=AllocPacket(byteSize, data, _FILE_AND_LINE_); - packet->bitSize = bitSize; - packet->systemAddress = systemAddress; - packet->systemAddress.systemIndex = remoteSystem->remoteSystemIndex; - packet->guid = remoteSystem->guid; - packet->guid.systemIndex=packet->systemAddress.systemIndex; - AddPacketToProducer(packet); - - remoteSystem->connectMode=RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY; - } - else - { - rakFree_Ex(data, _FILE_AND_LINE_ ); - } - } - else if ( (unsigned char)(data)[0] == ID_CONNECTION_REQUEST_ACCEPTED ) - { - if (byteSize > sizeof(MessageID)+sizeof(unsigned int)+sizeof(unsigned short)+sizeof(SystemIndex)+sizeof(MafiaNet::Time)*2) - { - // Make sure this connection accept is from someone we wanted to connect to - bool allowConnection, alreadyConnected; - - if (remoteSystem->connectMode==RemoteSystemStruct::HANDLING_CONNECTION_REQUEST || - remoteSystem->connectMode==RemoteSystemStruct::REQUESTED_CONNECTION || - allowConnectionResponseIPMigration) - allowConnection=true; - else - allowConnection=false; - - if (remoteSystem->connectMode==RemoteSystemStruct::HANDLING_CONNECTION_REQUEST) - alreadyConnected=true; - else - alreadyConnected=false; - - if ( allowConnection ) - { - SystemAddress externalID; - SystemIndex systemIndex; -// SystemAddress internalID; - - MafiaNet::BitStream inBitStream((unsigned char *) data, byteSize, false); - inBitStream.IgnoreBits(8); - // inBitStream.Read(remotePort); - inBitStream.Read(externalID); - inBitStream.Read(systemIndex); - for (unsigned int i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) - inBitStream.Read(remoteSystem->theirInternalSystemAddress[i]); - - MafiaNet::Time sendPingTime, sendPongTime; - inBitStream.Read(sendPingTime); - inBitStream.Read(sendPongTime); - OnConnectedPong(sendPingTime, sendPongTime, remoteSystem); - - // Find a free remote system struct to use - // MafiaNet::BitStream casBitS(data, byteSize, false); - // ConnectionAcceptStruct cas; - // cas.Deserialize(casBitS); - // systemAddress.GetPort() = remotePort; - - // The remote system told us our external IP, so save it - remoteSystem->myExternalSystemAddress = externalID; - remoteSystem->connectMode=RemoteSystemStruct::CONNECTED; - - // Bug: If A connects to B through R, A's firstExternalID is set to R. If A tries to send to R, sends to loopback because R==firstExternalID - // Correct fix is to specify in Connect() if target is through a proxy. - // However, in practice you have to connect to something else first anyway to know about the proxy. So setting once only is good enough - if (firstExternalID==UNASSIGNED_SYSTEM_ADDRESS) - { - firstExternalID=externalID; - firstExternalID.debugPort=ntohs(firstExternalID.address.addr4.sin_port); - } - - // Send the connection request complete to the game - packet=AllocPacket(byteSize, data, _FILE_AND_LINE_); - packet->bitSize = byteSize * 8; - packet->systemAddress = systemAddress; - packet->systemAddress.systemIndex = ( SystemIndex ) GetIndexFromSystemAddress( systemAddress, true ); - packet->guid = remoteSystem->guid; - packet->guid.systemIndex=packet->systemAddress.systemIndex; - AddPacketToProducer(packet); - - MafiaNet::BitStream outBitStream; - outBitStream.Write((MessageID)ID_NEW_INCOMING_CONNECTION); - outBitStream.Write(systemAddress); - for (unsigned int i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) - outBitStream.Write(ipList[i]); - outBitStream.Write(sendPongTime); - outBitStream.Write(MafiaNet::GetTime()); - - SendImmediate( (char*)outBitStream.GetData(), outBitStream.GetNumberOfBitsUsed(), MafiaNet::Priority::Immediate, MafiaNet::Reliability::ReliableOrdered, 0, systemAddress, false, false, MafiaNet::GetTimeUS(), 0 ); - - if (alreadyConnected==false) - { - PingInternal( systemAddress, true, MafiaNet::Reliability::Unreliable ); - } - } - else - { - // Ignore, already connected - rakFree_Ex(data, _FILE_AND_LINE_ ); - } - } - else - { - // Version mismatch error? - RakAssert(0); - rakFree_Ex(data, _FILE_AND_LINE_ ); - } - } - else - { - // What do I do if I get a message from a system, before I am fully connected? - // I can either ignore it or give it to the user - // It seems like giving it to the user is a better option - if ((data[0]>=(MessageID)ID_TIMESTAMP || data[0]==ID_SND_RECEIPT_ACKED || data[0]==ID_SND_RECEIPT_LOSS) && - remoteSystem->isActive - ) - { - packet=AllocPacket(byteSize, data, _FILE_AND_LINE_); - packet->bitSize = bitSize; - packet->systemAddress = systemAddress; - packet->systemAddress.systemIndex = remoteSystem->remoteSystemIndex; - packet->guid = remoteSystem->guid; - packet->guid.systemIndex=packet->systemAddress.systemIndex; - AddPacketToProducer(packet); - } - else - { - rakFree_Ex(data, _FILE_AND_LINE_ ); - } - } - } - - // Does the reliability layer have any more packets waiting for us? - // To be thread safe, this has to be called in the same thread as HandleSocketReceiveFromConnectedPlayer - bitSize = remoteSystem->reliabilityLayer.Receive( &data ); - } - - } - - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void RakPeer::OnRNS2Recv(RNS2RecvStruct *recvStruct) -{ - if (incomingDatagramEventHandler) - { - if (incomingDatagramEventHandler(recvStruct)!=true) - return; - } - - PushBufferedPacket(recvStruct); - quitAndDataEvents.SetEvent(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -/* -RAK_THREAD_DECLARATION(MafiaNet::RecvFromLoop) -{ -#if defined(SN_TARGET_PSP2) - RakPeerAndIndex *rpai = ( RakPeerAndIndex * ) RakThread::GetRealThreadArgument(callGetRealThreadArgument); -#else - RakPeerAndIndex *rpai = ( RakPeerAndIndex * ) arguments; -#endif - RakPeer * rakPeer = rpai->rakPeer; - RakNetSocket *s = rpai->s; - MafiaNet::OP_DELETE(rpai,_FILE_AND_LINE_); - - rakPeer->isRecvFromLoopThreadActive.Increment(); - - while ( rakPeer->endThreads == false ) - { - if (rakPeer->RunRecvFromOnce(s)==false && - s->GetBlockingSocket()==false) - RakSleep(0); - } - rakPeer->isRecvFromLoopThreadActive.Decrement(); - -#if defined(SN_TARGET_PSP2) - return sceKernelExitDeleteThread(0); -#else - return 0; -#endif -} -*/ - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -RAK_THREAD_DECLARATION(MafiaNet::UpdateNetworkLoop) -{ - - - - RakPeer * rakPeer = ( RakPeer * ) arguments; - - -/* - // 11/15/05 - this is slower than Sleep() -#ifdef _WIN32 -#if (_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400) - // Lets see if these timers give better performance than Sleep - HANDLE timerHandle; - LARGE_INTEGER dueTime; - - if ( rakPeer->threadSleepTimer <= 0 ) - rakPeer->threadSleepTimer = 1; - - // 2nd parameter of false means synchronization timer instead of manual-reset timer - timerHandle = CreateWaitableTimer( nullptr, FALSE, 0 ); - - RakAssert( timerHandle ); - - dueTime.QuadPart = -10000 * rakPeer->threadSleepTimer; // 10000 is 1 ms? - - BOOL success = SetWaitableTimer( timerHandle, &dueTime, rakPeer->threadSleepTimer, nullptr, nullptr, FALSE ); - (void) success; - RakAssert( success ); - -#endif -#endif -*/ - - BitStream updateBitStream( MAXIMUM_MTU_SIZE -#if LIBCAT_SECURITY==1 - + cat::AuthenticatedEncryption::OVERHEAD_BYTES -#endif - ); -// - rakPeer->isMainLoopThreadActive = true; - - bool running = true; - while ( running ) - { - if (rakPeer->endThreads) { - // allow just one more final update-run prior to shutting down this thread to make sure that outstanding acks are still sent and the peers don't unnecessary wait for already retrieved packets - // note: this fixes part of SLNET-123 - running = false; - } -// #ifdef _DEBUG -// // Sanity check, make sure RunUpdateCycle does not block or not otherwise get called for a long time -// RakNetTime thisCall=MafiaNet::GetTime(); -// RakAssert(thisCall-lastCall<250); -// lastCall=thisCall; -// #endif - if (rakPeer->userUpdateThreadPtr) - rakPeer->userUpdateThreadPtr(rakPeer, rakPeer->userUpdateThreadData); - - rakPeer->RunUpdateCycle(updateBitStream); - - // Pending sends go out this often, unless quitAndDataEvents is set - rakPeer->quitAndDataEvents.WaitOnEvent(10); - - /* - -// #if ((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)) && -#if defined(USE_WAIT_FOR_MULTIPLE_EVENTS) && defined(_WIN32) - - if (rakPeer->threadSleepTimer>0) - { - WSAEVENT eventArray[256]; - unsigned int i, eventArrayIndex; - for (i=0,eventArrayIndex=0; i < rakPeer->socketList.Size(); i++) - { - if (rakPeer->socketList[i]->recvEvent!=INVALID_HANDLE_VALUE) - { - eventArray[eventArrayIndex]=rakPeer->socketList[i]->recvEvent; - eventArrayIndex++; - if (eventArrayIndex==256) - break; - } - } - WSAWaitForMultipleEvents(eventArrayIndex,(const HANDLE*) &eventArray,FALSE,rakPeer->threadSleepTimer,FALSE); - } - else - { - RakSleep(0); - } - -#else // ((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)) && defined(USE_WAIT_FOR_MULTIPLE_EVENTS) - #pragma message("-- RakNet: Using Sleep(). Uncomment USE_WAIT_FOR_MULTIPLE_EVENTS in defines.h if you want to use WaitForSingleObject instead. --") - - RakSleep( rakPeer->threadSleepTimer ); -#endif - */ - } - - rakPeer->isMainLoopThreadActive = false; - - /* -#ifdef _WIN32 -#if (_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400) - CloseHandle(timerHandle); -#endif -#endif - */ - - - - - return 0; - -} - -void RakPeer::CallPluginCallbacks(DataStructures::List &pluginList, Packet *packet) -{ - for (unsigned int i=0; i < pluginList.Size(); i++) - { - switch (packet->data[0]) - { - case ID_DISCONNECTION_NOTIFICATION: - pluginList[i]->OnClosedConnection(packet->systemAddress, packet->guid, LCR_DISCONNECTION_NOTIFICATION); - break; - case ID_CONNECTION_LOST: - pluginList[i]->OnClosedConnection(packet->systemAddress, packet->guid, LCR_CONNECTION_LOST); - break; - case ID_NEW_INCOMING_CONNECTION: - pluginList[i]->OnNewConnection(packet->systemAddress, packet->guid, true); - break; - case ID_CONNECTION_REQUEST_ACCEPTED: - pluginList[i]->OnNewConnection(packet->systemAddress, packet->guid, false); - break; - case ID_CONNECTION_ATTEMPT_FAILED: - pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_CONNECTION_ATTEMPT_FAILED); - break; - case ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY: - pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY); - break; - case ID_OUR_SYSTEM_REQUIRES_SECURITY: - pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_OUR_SYSTEM_REQUIRES_SECURITY); - break; - case ID_PUBLIC_KEY_MISMATCH: - pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_PUBLIC_KEY_MISMATCH); - break; - case ID_ALREADY_CONNECTED: - pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_ALREADY_CONNECTED); - break; - case ID_NO_FREE_INCOMING_CONNECTIONS: - pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_NO_FREE_INCOMING_CONNECTIONS); - break; - case ID_CONNECTION_BANNED: - pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_CONNECTION_BANNED); - break; - case ID_INVALID_PASSWORD: - pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_INVALID_PASSWORD); - break; - case ID_INCOMPATIBLE_PROTOCOL_VERSION: - pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_INCOMPATIBLE_PROTOCOL); - break; - case ID_IP_RECENTLY_CONNECTED: - pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_IP_RECENTLY_CONNECTED); - break; - } - } -} - -void RakPeer::FillIPList(void) -{ - if (ipList[0]!=UNASSIGNED_SYSTEM_ADDRESS) - return; - - // Fill out ipList structure - RakNetSocket2::GetMyIP( ipList ); - - // Sort the addresses from lowest to highest - int startingIdx = 0; - while (startingIdx < MAXIMUM_NUMBER_OF_INTERNAL_IDS-1 && ipList[startingIdx] != UNASSIGNED_SYSTEM_ADDRESS) - { - int lowestIdx = startingIdx; - for (int curIdx = startingIdx + 1; curIdx < MAXIMUM_NUMBER_OF_INTERNAL_IDS-1 && ipList[curIdx] != UNASSIGNED_SYSTEM_ADDRESS; curIdx++ ) - { - if (ipList[curIdx] < ipList[startingIdx]) - { - lowestIdx = curIdx; - } - } - if (startingIdx != lowestIdx) - { - SystemAddress temp = ipList[startingIdx]; - ipList[startingIdx] = ipList[lowestIdx]; - ipList[lowestIdx] = temp; - } - ++startingIdx; - } -} - - -// #if defined(RMO_NEW_UNDEF_ALLOCATING_QUEUE) -// #pragma pop_macro("new") -// #undef RMO_NEW_UNDEF_ALLOCATING_QUEUE -// #endif - diff --git a/vendors/mafianet/Source/src/RakSleep.cpp b/vendors/mafianet/Source/src/RakSleep.cpp deleted file mode 100644 index df28f9245..000000000 --- a/vendors/mafianet/Source/src/RakSleep.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#if defined(_WIN32) -#include "mafianet/WindowsIncludes.h" // Sleep - - - - - - - -#else -#include -#include -#include -pthread_mutex_t fakeMutex = PTHREAD_MUTEX_INITIALIZER; -pthread_cond_t fakeCond = PTHREAD_COND_INITIALIZER; -#endif - -#include "mafianet/sleep.h" - -void RakSleep(unsigned int ms) -{ -#ifdef _WIN32 - Sleep(ms); - - - - - - - -#else - //Single thread sleep code thanks to Furquan Shaikh, http://somethingswhichidintknow.blogspot.com/2009/09/sleep-in-pthread.html - //Modified slightly from the original - struct timespec timeToWait; - struct timeval now; - int rt; - - gettimeofday(&now, nullptr); - - long seconds = ms/1000; - long nanoseconds = (ms - seconds * 1000) * 1000000; - timeToWait.tv_sec = now.tv_sec + seconds; - timeToWait.tv_nsec = now.tv_usec*1000 + nanoseconds; - - if (timeToWait.tv_nsec >= 1000000000) - { - timeToWait.tv_nsec -= 1000000000; - timeToWait.tv_sec++; - } - - pthread_mutex_lock(&fakeMutex); - rt = pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait); - pthread_mutex_unlock(&fakeMutex); -#endif -} diff --git a/vendors/mafianet/Source/src/RakString.cpp b/vendors/mafianet/Source/src/RakString.cpp deleted file mode 100644 index a887add35..000000000 --- a/vendors/mafianet/Source/src/RakString.cpp +++ /dev/null @@ -1,1700 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/string.h" -#include "mafianet/assert.h" -#include "mafianet/memoryoverride.h" -#include "mafianet/BitStream.h" -#include -#include -#include "mafianet/LinuxStrings.h" -#include "mafianet/StringCompressor.h" -#include "mafianet/SimpleMutex.h" -#include -#include "mafianet/Itoa.h" -#include -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace MafiaNet; - -//DataStructures::MemoryPool RakString::pool; -RakString::SharedString RakString::emptyString={0,0,0,(char*) "",(char*) ""}; -//RakString::SharedString *RakString::sharedStringFreeList=0; -//unsigned int RakString::sharedStringFreeListAllocationCount=0; -DataStructures::List RakString::freeList; - -class RakStringCleanup -{ -public: - ~RakStringCleanup() - { - MafiaNet::RakString::FreeMemoryNoMutex(); - } -}; - -static RakStringCleanup cleanup; - -SimpleMutex& GetPoolMutex(void) -{ - static SimpleMutex poolMutex; - return poolMutex; -} - -int MafiaNet::RakString::RakStringComp( RakString const &key, RakString const &data ) -{ - return key.StrCmp(data); -} - -RakString::RakString() -{ - sharedString=&emptyString; -} -RakString::RakString( RakString::SharedString *_sharedString ) -{ - sharedString=_sharedString; -} -RakString::RakString(char input) -{ - char str[2]; - str[0]=input; - str[1]=0; - Assign(str); -} -RakString::RakString(unsigned char input) -{ - char str[2]; - str[0]=(char) input; - str[1]=0; - Assign(str); -} -RakString::RakString(const unsigned char *format, ...){ - va_list ap; - va_start(ap, format); - Assign((const char*) format,ap); - va_end(ap); -} -RakString::RakString(const char *format, ...){ - va_list ap; - va_start(ap, format); - Assign(format,ap); - va_end(ap); -} -RakString::RakString( const RakString & rhs) -{ - if (rhs.sharedString==&emptyString) - { - sharedString=&emptyString; - return; - } - - rhs.sharedString->refCountMutex->Lock(); - if (rhs.sharedString->refCount==0) - { - sharedString=&emptyString; - } - else - { - rhs.sharedString->refCount++; - sharedString=rhs.sharedString; - } - rhs.sharedString->refCountMutex->Unlock(); -} -RakString::~RakString() -{ - Free(); -} -RakString& RakString::operator = ( const RakString& rhs ) -{ - Free(); - if (rhs.sharedString==&emptyString) - return *this; - - rhs.sharedString->refCountMutex->Lock(); - if (rhs.sharedString->refCount==0) - { - sharedString=&emptyString; - } - else - { - sharedString=rhs.sharedString; - sharedString->refCount++; - } - rhs.sharedString->refCountMutex->Unlock(); - return *this; -} -RakString& RakString::operator = ( const char *str ) -{ - Free(); - Assign(str); - return *this; -} -RakString& RakString::operator = ( char *str ) -{ - return operator = ((const char*)str); -} -RakString& RakString::operator = ( const unsigned char *str ) -{ - return operator = ((const char*)str); -} -RakString& RakString::operator = ( char unsigned *str ) -{ - return operator = ((const char*)str); -} -RakString& RakString::operator = ( const char c ) -{ - char buff[2]; - buff[0]=c; - buff[1]=0; - return operator = ((const char*)buff); -} -void RakString::Realloc(SharedString *inSharedString, size_t bytes) -{ - if (bytes<= inSharedString->bytesUsed) - return; - - RakAssert(bytes>0); - size_t oldBytes = inSharedString->bytesUsed; - size_t newBytes; - const size_t smallStringSize = 128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2; - newBytes = GetSizeToAllocate(bytes); - if (oldBytes <=(size_t) smallStringSize && newBytes > (size_t) smallStringSize) - { - inSharedString->bigString=(char*) rakMalloc_Ex(newBytes, _FILE_AND_LINE_); - strcpy_s(inSharedString->bigString, newBytes, inSharedString->smallString); - inSharedString->c_str= inSharedString->bigString; - } - else if (oldBytes > smallStringSize) - { - inSharedString->bigString=(char*) rakRealloc_Ex(inSharedString->bigString,newBytes, _FILE_AND_LINE_); - inSharedString->c_str= inSharedString->bigString; - } - inSharedString->bytesUsed=newBytes; -} -RakString& RakString::operator +=( const RakString& rhs) -{ - if (rhs.IsEmpty()) - return *this; - - if (IsEmpty()) - { - return operator=(rhs); - } - else - { - Clone(); - size_t strLen=rhs.GetLength()+GetLength()+1; - Realloc(sharedString, strLen+GetLength()); - strcat_s(sharedString->c_str,sharedString->bytesUsed,rhs.C_String()); - } - return *this; -} -RakString& RakString::operator +=( const char *str ) -{ - if (str==0 || str[0]==0) - return *this; - - if (IsEmpty()) - { - Assign(str); - } - else - { - Clone(); - size_t strLen=strlen(str)+GetLength()+1; - Realloc(sharedString, strLen); - strcat_s(sharedString->c_str,sharedString->bytesUsed,str); - } - return *this; -} -RakString& RakString::operator +=( char *str ) -{ - return operator += ((const char*)str); -} -RakString& RakString::operator +=( const unsigned char *str ) -{ - return operator += ((const char*)str); -} -RakString& RakString::operator +=( unsigned char *str ) -{ - return operator += ((const char*)str); -} -RakString& RakString::operator +=( const char c ) -{ - char buff[2]; - buff[0]=c; - buff[1]=0; - return operator += ((const char*)buff); -} -unsigned char RakString::operator[] ( const unsigned int position ) const -{ - RakAssert(positionc_str[position]; -} -bool RakString::operator==(const RakString &rhs) const -{ - return strcmp(sharedString->c_str,rhs.sharedString->c_str)==0; -} -bool RakString::operator==(const char *str) const -{ - return strcmp(sharedString->c_str,str)==0; -} -bool RakString::operator==(char *str) const -{ - return strcmp(sharedString->c_str,str)==0; -} -bool RakString::operator < ( const RakString& right ) const -{ - return strcmp(sharedString->c_str,right.C_String()) < 0; -} -bool RakString::operator <= ( const RakString& right ) const -{ - return strcmp(sharedString->c_str,right.C_String()) <= 0; -} -bool RakString::operator > ( const RakString& right ) const -{ - return strcmp(sharedString->c_str,right.C_String()) > 0; -} -bool RakString::operator >= ( const RakString& right ) const -{ - return strcmp(sharedString->c_str,right.C_String()) >= 0; -} -bool RakString::operator!=(const RakString &rhs) const -{ - return strcmp(sharedString->c_str,rhs.sharedString->c_str)!=0; -} -bool RakString::operator!=(const char *str) const -{ - return strcmp(sharedString->c_str,str)!=0; -} -bool RakString::operator!=(char *str) const -{ - return strcmp(sharedString->c_str,str)!=0; -} -const MafiaNet::RakString operator+(const MafiaNet::RakString &lhs, const MafiaNet::RakString &rhs) -{ - if (lhs.IsEmpty() && rhs.IsEmpty()) - { - return RakString(&RakString::emptyString); - } - if (lhs.IsEmpty()) - { - rhs.sharedString->refCountMutex->Lock(); - if (rhs.sharedString->refCount==0) - { - rhs.sharedString->refCountMutex->Unlock(); - lhs.sharedString->refCountMutex->Lock(); - lhs.sharedString->refCount++; - lhs.sharedString->refCountMutex->Unlock(); - return RakString(lhs.sharedString); - } - else - { - rhs.sharedString->refCount++; - rhs.sharedString->refCountMutex->Unlock(); - return RakString(rhs.sharedString); - } - // rhs.sharedString->refCountMutex->Unlock(); - } - if (rhs.IsEmpty()) - { - lhs.sharedString->refCountMutex->Lock(); - lhs.sharedString->refCount++; - lhs.sharedString->refCountMutex->Unlock(); - return RakString(lhs.sharedString); - } - - size_t len1 = lhs.GetLength(); - size_t len2 = rhs.GetLength(); - size_t allocatedBytes = len1 + len2 + 1; - allocatedBytes = RakString::GetSizeToAllocate(allocatedBytes); - RakString::SharedString *sharedString; - - RakString::LockMutex(); - // sharedString = RakString::pool.Allocate( _FILE_AND_LINE_ ); - if (RakString::freeList.Size()==0) - { - //RakString::sharedStringFreeList=(RakString::SharedString*) rakRealloc_Ex(RakString::sharedStringFreeList,(RakString::sharedStringFreeListAllocationCount+1024)*sizeof(RakString::SharedString), _FILE_AND_LINE_); - unsigned i; - for (i=0; i < 128; i++) - { - // RakString::freeList.Insert(RakString::sharedStringFreeList+i+RakString::sharedStringFreeListAllocationCount); - RakString::SharedString *ss; - ss = (RakString::SharedString*) rakMalloc_Ex(sizeof(RakString::SharedString), _FILE_AND_LINE_); - ss->refCountMutex= MafiaNet::OP_NEW(_FILE_AND_LINE_); - RakString::freeList.Insert(ss, _FILE_AND_LINE_); - - } - //RakString::sharedStringFreeListAllocationCount+=1024; - } - sharedString = RakString::freeList[RakString::freeList.Size()-1]; - RakString::freeList.RemoveAtIndex(RakString::freeList.Size()-1); - RakString::UnlockMutex(); - - const int smallStringSize = 128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2; - sharedString->bytesUsed=allocatedBytes; - sharedString->refCount=1; - if (allocatedBytes <= (size_t) smallStringSize) - { - sharedString->c_str=sharedString->smallString; - } - else - { - sharedString->bigString=(char*)rakMalloc_Ex(sharedString->bytesUsed, _FILE_AND_LINE_); - sharedString->c_str=sharedString->bigString; - } - - strcpy_s(sharedString->c_str, sharedString->bytesUsed, lhs); - strcat_s(sharedString->c_str, sharedString->bytesUsed, rhs); - - return RakString(sharedString); -} -const char * RakString::ToLower(void) -{ - Clone(); - - size_t strLen = strlen(sharedString->c_str); - unsigned i; - for (i=0; i < strLen; i++) - sharedString->c_str[i]=ToLower(sharedString->c_str[i]); - return sharedString->c_str; -} -const char * RakString::ToUpper(void) -{ - Clone(); - - size_t strLen = strlen(sharedString->c_str); - unsigned i; - for (i=0; i < strLen; i++) - sharedString->c_str[i]=ToUpper(sharedString->c_str[i]); - return sharedString->c_str; -} -void RakString::Set(const char *format, ...) -{ - va_list ap; - va_start(ap, format); - Clear(); - Assign(format,ap); - va_end(ap); -} -bool RakString::IsEmpty(void) const -{ - return sharedString==&emptyString; -} -size_t RakString::GetLength(void) const -{ - return strlen(sharedString->c_str); -} -// http://porg.es/blog/counting-characters-in-utf-8-strings-is-faster -int porges_strlen2(char *s) -{ - int i = 0; - int iBefore = 0; - int count = 0; - - while (s[i] > 0) -ascii: i++; - - count += i-iBefore; - while (s[i]) - { - if (s[i] > 0) - { - iBefore = i; - goto ascii; - } - else - switch (0xF0 & s[i]) - { - case 0xE0: i += 3; break; - case 0xF0: i += 4; break; - default: i += 2; break; - } - ++count; - } - return count; -} -size_t RakString::GetLengthUTF8(void) const -{ - return porges_strlen2(sharedString->c_str); -} -void RakString::Replace(unsigned index, unsigned count, unsigned char c) -{ - RakAssert(index+count < GetLength()); - Clone(); - unsigned countIndex=0; - while (countIndexc_str[index]=c; - index++; - countIndex++; - } - -} -void RakString::SetChar( unsigned index, unsigned char c ) -{ - RakAssert(index < GetLength()); - Clone(); - sharedString->c_str[index]=c; -} -void RakString::SetChar( unsigned index, MafiaNet::RakString s ) -{ - RakAssert(index < GetLength()); - Clone(); - MafiaNet::RakString firstHalf = SubStr(0, index); - MafiaNet::RakString secondHalf = SubStr(index+1, (unsigned int)-1); - *this = firstHalf; - *this += s; - *this += secondHalf; -} - -#ifdef _WIN32 -WCHAR * RakString::ToWideChar(void) -{ - // - // Special case of nullptr or empty input string - // - if ( (sharedString->c_str == nullptr) || (*sharedString->c_str == '\0') ) - { - // Return empty string - WCHAR* buf = MafiaNet::OP_NEW_ARRAY(1, __FILE__, __LINE__); - buf[0] = L'\0'; - return buf; - } - - // - // Get size of destination UTF-16 buffer, in WCHAR's - // - int cchUTF16 = ::MultiByteToWideChar( - CP_UTF8, // convert from UTF-8 - 0, // Flags - sharedString->c_str, // source UTF-8 string - -1, // -1 means string is zero-terminated - nullptr, // unused - no conversion done in this step - 0 // request size of destination buffer, in WCHAR's - ); - - if ( cchUTF16 == 0 ) - { - RakAssert("RakString::ToWideChar exception from cchUTF16==0" && 0); - return 0; - } - - // - // Allocate destination buffer to store UTF-16 string - // - WCHAR * pszUTF16 = MafiaNet::OP_NEW_ARRAY(cchUTF16,__FILE__,__LINE__); - - // - // Do the conversion from UTF-8 to UTF-16 - // - int result = ::MultiByteToWideChar( - CP_UTF8, // convert from UTF-8 - 0, // Buffer - sharedString->c_str, // source UTF-8 string - -1, // -1 means string is zero-terminated - pszUTF16, // destination buffer - cchUTF16 // size of destination buffer, in WCHAR's - ); - - if ( result == 0 ) - { - RakAssert("RakString::ToWideChar exception from MultiByteToWideChar" && 0); - return 0; - } - - return pszUTF16; -} -void RakString::DeallocWideChar(WCHAR * w) -{ - MafiaNet::OP_DELETE_ARRAY(w,__FILE__,__LINE__); -} -void RakString::FromWideChar(const wchar_t *source) -{ - Clear(); - size_t bufSize = wcslen(source)*4; - - // #low - add return value indicating to the caller whether we succeeded (and then handle error case / or thrown an exception) - if (bufSize > static_cast(std::numeric_limits::max())) { - RakAssert("RakString::FromWideChar given string is too long and cannot be converted"); - return; - } - - Allocate(bufSize); - WideCharToMultiByte ( CP_ACP, // ANSI code page - - - - WC_COMPOSITECHECK, // Check for accented characters - - source, // Source Unicode string - -1, // -1 means string is zero-terminated - sharedString->c_str, // Destination char string - static_cast(bufSize), // Size of buffer - nullptr, // No default character - nullptr ); // Don't care about this flag - - -} -MafiaNet::RakString RakString::FromWideChar_S(const wchar_t *source) -{ - MafiaNet::RakString rs; - rs.FromWideChar(source); - return rs; -} -#endif -size_t RakString::Find(const char *stringToFind,size_t pos) -{ - size_t len=GetLength(); - if (pos>=len || stringToFind==0 || stringToFind[0]==0) - { - return (size_t) -1; - } - size_t matchLen= strlen(stringToFind); - size_t matchPos=0; - size_t iStart=0; - - for (size_t i=pos;ic_str[i]) - { - if(matchPos==0) - { - iStart=i; - } - matchPos++; - } - else - { - matchPos=0; - } - - if (matchPos>=matchLen) - { - return iStart; - } - } - - return (size_t) -1; -} - -void RakString::TruncateUTF8(unsigned int length) -{ - int i = 0; - unsigned int count = 0; - - while (sharedString->c_str[i]!=0) - { - if (count==length) - { - sharedString->c_str[i]=0; - return; - } - else if (sharedString->c_str[i]>0) - { - i++; - } - else - { - switch (0xF0 & sharedString->c_str[i]) - { - case 0xE0: i += 3; break; - case 0xF0: i += 4; break; - default: i += 2; break; - } - } - - count++; - } -} - -void RakString::Truncate(unsigned int length) -{ - if (length < GetLength()) - { - SetChar(length, 0); - } -} - -RakString RakString::SubStr(unsigned int index, size_t count) const -{ - size_t length = GetLength(); - if (index >= length || count==0) - return RakString(); - RakString copy; - size_t numBytes = length-index; - if (count < numBytes) - numBytes=count; - copy.Allocate(numBytes+1); - size_t i; - for (i=0; i < numBytes; i++) - copy.sharedString->c_str[i]=sharedString->c_str[index+i]; - copy.sharedString->c_str[i]=0; - return copy; -} -void RakString::Erase(unsigned int index, unsigned int count) -{ - size_t len = GetLength(); - RakAssert(index+count <= len); - - Clone(); - unsigned i; - for (i=index; i < len-count; i++) - { - sharedString->c_str[i]=sharedString->c_str[i+count]; - } - sharedString->c_str[i]=0; -} -void RakString::TerminateAtLastCharacter(char c) -{ - int i, len=(int) GetLength(); - for (i=len-1; i >= 0; i--) - { - if (sharedString->c_str[i]==c) - { - Clone(); - sharedString->c_str[i]=0; - return; - } - } -} -void RakString::StartAfterLastCharacter(char c) -{ - int i, len=(int) GetLength(); - for (i=len-1; i >= 0; i--) - { - if (sharedString->c_str[i]==c) - { - ++i; - if (i < len) - { - *this = SubStr(i,GetLength()-i); - } - return; - } - } -} -void RakString::TerminateAtFirstCharacter(char c) -{ - unsigned int i, len=(unsigned int) GetLength(); - for (i=0; i < len; i++) - { - if (sharedString->c_str[i]==c) - { - if (i > 0) - { - Clone(); - sharedString->c_str[i]=0; - } - } - } -} -void RakString::StartAfterFirstCharacter(char c) -{ - unsigned int i, len=(unsigned int) GetLength(); - for (i=0; i < len; i++) - { - if (sharedString->c_str[i]==c) - { - ++i; - if (i < len) - { - *this = SubStr(i,GetLength()-i); - } - return; - } - } -} -int RakString::GetCharacterCount(char c) -{ - int count=0; - unsigned int i, len=(unsigned int) GetLength(); - for (i=0; i < len; i++) - { - if (sharedString->c_str[i]==c) - { - ++count; - } - } - return count; -} -void RakString::RemoveCharacter(char c) -{ - if (c==0) - return; - - unsigned int readIndex, writeIndex=0; - for (readIndex=0; sharedString->c_str[readIndex]; readIndex++) - { - if (sharedString->c_str[readIndex]!=c) - sharedString->c_str[writeIndex++]=sharedString->c_str[readIndex]; - else - Clone(); - } - sharedString->c_str[writeIndex]=0; - if (writeIndex==0) - Clear(); -} -int RakString::StrCmp(const RakString &rhs) const -{ - return strcmp(sharedString->c_str, rhs.C_String()); -} -int RakString::StrNCmp(const RakString &rhs, size_t num) const -{ - return strncmp(sharedString->c_str, rhs.C_String(), num); -} -int RakString::StrICmp(const RakString &rhs) const -{ - return _stricmp(sharedString->c_str, rhs.C_String()); -} -void RakString::Printf(void) -{ - RAKNET_DEBUG_PRINTF("%s", sharedString->c_str); -} -void RakString::FPrintf(FILE *fp) -{ - fprintf(fp,"%s", sharedString->c_str); -} -bool RakString::IPAddressMatch(const char *IP) -{ - unsigned characterIndex; - - if ( IP == 0 || IP[ 0 ] == 0 || strlen( IP ) > 15 ) - return false; - - characterIndex = 0; - - for(;;) - { - if (sharedString->c_str[ characterIndex ] == IP[ characterIndex ] ) - { - // Equal characters - if ( IP[ characterIndex ] == 0 ) - { - // End of the string and the strings match - - return true; - } - - characterIndex++; - } - - else - { - if ( sharedString->c_str[ characterIndex ] == 0 || IP[ characterIndex ] == 0 ) - { - // End of one of the strings - break; - } - - // Characters do not match - if ( sharedString->c_str[ characterIndex ] == '*' ) - { - // Domain is banned. - return true; - } - - // Characters do not match and it is not a * - break; - } - } - - - // No match found. - return false; -} -bool RakString::ContainsNonprintableExceptSpaces(void) const -{ - size_t strLen = strlen(sharedString->c_str); - unsigned i; - for (i=0; i < strLen; i++) - { - if (sharedString->c_str[i] < ' ' || sharedString->c_str[i] >126) - return true; - } - return false; -} -bool RakString::IsEmailAddress(void) const -{ - if (IsEmpty()) - return false; - size_t strLen = strlen(sharedString->c_str); - if (strLen < 6) // a@b.de - return false; - if (sharedString->c_str[strLen-4]!='.' && sharedString->c_str[strLen-3]!='.') // .com, .net., .org, .de - return false; - unsigned i; - // Has non-printable? - for (i=0; i < strLen; i++) - { - if (sharedString->c_str[i] <= ' ' || sharedString->c_str[i] >126) - return false; - } - int atCount=0; - for (i=0; i < strLen; i++) - { - if (sharedString->c_str[i]=='@') - { - atCount++; - } - } - if (atCount!=1) - return false; - int dotCount=0; - for (i=0; i < strLen; i++) - { - if (sharedString->c_str[i]=='.') - { - dotCount++; - } - } - if (dotCount==0) - return false; - - // There's more I could check, but this is good enough - return true; -} -MafiaNet::RakString& RakString::URLEncode(void) -{ - RakString result; - size_t strLen = strlen(sharedString->c_str); - result.Allocate(strLen*3); - char *output=result.sharedString->c_str; - unsigned int outputIndex=0; - unsigned i; - unsigned char c; - for (i=0; i < strLen; i++) - { - c=sharedString->c_str[i]; - if ( - (c<=47) || - (c>=58 && c<=64) || - (c>=91 && c<=96) || - (c>=123) - ) - { - char buff[3]; - Itoa(c, buff, 16); - output[outputIndex++]='%'; - output[outputIndex++]=buff[0]; - output[outputIndex++]=buff[1]; - } - else - { - output[outputIndex++]=c; - } - } - - output[outputIndex]=0; - - *this = result; - return *this; -} -MafiaNet::RakString& RakString::URLDecode(void) -{ - RakString result; - size_t strLen = strlen(sharedString->c_str); - result.Allocate(strLen); - char *output=result.sharedString->c_str; - unsigned int outputIndex=0; - char c; - char hexDigits[2]; - char hexValues[2]; - unsigned int i; - for (i=0; i < strLen; i++) - { - c=sharedString->c_str[i]; - if (c=='%') - { - hexDigits[0]=sharedString->c_str[++i]; - hexDigits[1]=sharedString->c_str[++i]; - - if (hexDigits[0]==' ') - hexValues[0]=0; - - if (hexDigits[0]>='A' && hexDigits[0]<='F') - hexValues[0]=hexDigits[0]-'A'+10; - if (hexDigits[0]>='a' && hexDigits[0]<='f') - hexValues[0]=hexDigits[0]-'a'+10; - else - hexValues[0]=hexDigits[0]-'0'; - - if (hexDigits[1]>='A' && hexDigits[1]<='F') - hexValues[1]=hexDigits[1]-'A'+10; - if (hexDigits[1]>='a' && hexDigits[1]<='f') - hexValues[1]=hexDigits[1]-'a'+10; - else - hexValues[1]=hexDigits[1]-'0'; - - output[outputIndex++]=hexValues[0]*16+hexValues[1]; - } - else - { - output[outputIndex++]=c; - } - } - - output[outputIndex]=0; - - *this = result; - return *this; -} -void RakString::SplitURI(MafiaNet::RakString &header, MafiaNet::RakString &domain, MafiaNet::RakString &path) -{ - header.Clear(); - domain.Clear(); - path.Clear(); - - size_t strLen = strlen(sharedString->c_str); - - char c; - unsigned int i=0; - if (strncmp(sharedString->c_str, "http://", 7)==0) - i+=(unsigned int) strlen("http://"); - else if (strncmp(sharedString->c_str, "https://", 8)==0) - i+=(unsigned int) strlen("https://"); - - if (strncmp(sharedString->c_str, "www.", 4)==0) - i+=(unsigned int) strlen("www."); - - if (i!=0) - { - header.Allocate(i+1); - strncpy_s(header.sharedString->c_str, header.sharedString->bytesUsed, sharedString->c_str, i); - header.sharedString->c_str[i]=0; - } - - - domain.Allocate(strLen-i+1); - char *domainOutput=domain.sharedString->c_str; - unsigned int outputIndex=0; - for (; i < strLen; i++) - { - c=sharedString->c_str[i]; - if (c=='/') - { - break; - } - else - { - domainOutput[outputIndex++]=sharedString->c_str[i]; - } - } - - domainOutput[outputIndex]=0; - - path.Allocate(strLen-header.GetLength()-outputIndex+1); - outputIndex=0; - char *pathOutput=path.sharedString->c_str; - for (; i < strLen; i++) - { - pathOutput[outputIndex++]=sharedString->c_str[i]; - } - pathOutput[outputIndex]=0; -} -MafiaNet::RakString& RakString::SQLEscape(void) -{ - int strLen=(int)GetLength(); - int escapedCharacterCount=0; - int index; - for (index=0; index < strLen; index++) - { - if (sharedString->c_str[index]=='\'' || - sharedString->c_str[index]=='"' || - sharedString->c_str[index]=='\\') - escapedCharacterCount++; - } - if (escapedCharacterCount==0) - return *this; - - Clone(); - Realloc(sharedString, strLen+escapedCharacterCount); - int writeIndex, readIndex; - writeIndex = strLen+escapedCharacterCount; - readIndex=strLen; - while (readIndex>=0) - { - if (sharedString->c_str[readIndex]=='\'' || - sharedString->c_str[readIndex]=='"' || - sharedString->c_str[readIndex]=='\\') - { - sharedString->c_str[writeIndex--]=sharedString->c_str[readIndex--]; - sharedString->c_str[writeIndex--]='\\'; - } - else - { - sharedString->c_str[writeIndex--]=sharedString->c_str[readIndex--]; - } - } - return *this; -} -MafiaNet::RakString RakString::FormatForPUTOrPost(const char* type, const char* uri, const char* contentType, const char* body, const char* extraHeaders) -{ - RakString out; - RakString host; - RakString remotePath; - MafiaNet::RakString header; - RakString uriRs; - uriRs = uri; - uriRs.SplitURI(header, host, remotePath); - - if (host.IsEmpty() || remotePath.IsEmpty()) - return out; - -// RakString bodyEncoded = body; -// bodyEncoded.URLEncode(); - - if (extraHeaders!=0 && extraHeaders[0]) - { - out.Set("%s %s HTTP/1.1\r\n" - "%s\r\n" - "Host: %s\r\n" - "Content-Type: %s\r\n" - "Content-Length: %u\r\n" - "\r\n" - "%s", - type, - remotePath.C_String(), - extraHeaders, - host.C_String(), - contentType, - //bodyEncoded.GetLength(), - //bodyEncoded.C_String()); - strlen(body), - body); - } - else - { - out.Set("%s %s HTTP/1.1\r\n" - "Host: %s\r\n" - "Content-Type: %s\r\n" - "Content-Length: %u\r\n" - "\r\n" - "%s", - type, - remotePath.C_String(), - host.C_String(), - contentType, - //bodyEncoded.GetLength(), - //bodyEncoded.C_String()); - strlen(body), - body); - } - - return out; -} -RakString RakString::FormatForPOST(const char* uri, const char* contentType, const char* body, const char* extraHeaders) -{ - return FormatForPUTOrPost("POST", uri, contentType, body, extraHeaders); -} -RakString RakString::FormatForPUT(const char* uri, const char* contentType, const char* body, const char* extraHeaders) -{ - return FormatForPUTOrPost("PUT", uri, contentType, body, extraHeaders); -} -RakString RakString::FormatForGET(const char* uri, const char* extraHeaders) -{ - RakString out; - RakString host; - RakString remotePath; - MafiaNet::RakString header; - MafiaNet::RakString uriRs; - uriRs = uri; - - uriRs.SplitURI(header, host, remotePath); - if (host.IsEmpty() || remotePath.IsEmpty()) - return out; - - if (extraHeaders && extraHeaders[0]) - { - out.Set("GET %s HTTP/1.1\r\n" - "%s\r\n" - "Host: %s\r\n" - "\r\n", - remotePath.C_String(), - extraHeaders, - host.C_String()); - } - else - { - out.Set("GET %s HTTP/1.1\r\n" - "Host: %s\r\n" - "\r\n", - remotePath.C_String(), - host.C_String()); - - } - - - return out; -} -RakString RakString::FormatForDELETE(const char* uri, const char* extraHeaders) -{ - RakString out; - RakString host; - RakString remotePath; - MafiaNet::RakString header; - MafiaNet::RakString uriRs; - uriRs = uri; - - uriRs.SplitURI(header, host, remotePath); - if (host.IsEmpty() || remotePath.IsEmpty()) - return out; - - if (extraHeaders && extraHeaders[0]) - { - out.Set("DELETE %s HTTP/1.1\r\n" - "%s\r\n" - "Content-Length: 0\r\n" - "Host: %s\r\n" - "Connection: close\r\n" - "\r\n", - remotePath.C_String(), - extraHeaders, - host.C_String()); - } - else - { - out.Set("DELETE %s HTTP/1.1\r\n" - "Content-Length: 0\r\n" - "Host: %s\r\n" - "Connection: close\r\n" - "\r\n", - remotePath.C_String(), - host.C_String()); - } - - return out; -} -MafiaNet::RakString& RakString::MakeFilePath(void) -{ - if (IsEmpty()) - return *this; - - MafiaNet::RakString fixedString = *this; - fixedString.Clone(); - for (int i=0; fixedString.sharedString->c_str[i]; i++) - { -#ifdef _WIN32 - if (fixedString.sharedString->c_str[i]=='/') - fixedString.sharedString->c_str[i]='\\'; -#else - if (fixedString.sharedString->c_str[i]=='\\') - fixedString.sharedString->c_str[i]='/'; -#endif - } - -#ifdef _WIN32 - if (fixedString.sharedString->c_str[strlen(fixedString.sharedString->c_str)-1]!='\\') - { - fixedString+='\\'; - } -#else - if (fixedString.sharedString->c_str[strlen(fixedString.sharedString->c_str)-1]!='/') - { - fixedString+='/'; - } -#endif - - if (fixedString!=*this) - *this = fixedString; - return *this; -} -void RakString::FreeMemory(void) -{ - LockMutex(); - FreeMemoryNoMutex(); - UnlockMutex(); -} -void RakString::FreeMemoryNoMutex(void) -{ - for (unsigned int i=0; i < freeList.Size(); i++) - { - MafiaNet::OP_DELETE(freeList[i]->refCountMutex,_FILE_AND_LINE_); - rakFree_Ex(freeList[i], _FILE_AND_LINE_ ); - } - freeList.Clear(false, _FILE_AND_LINE_); -} -void RakString::Serialize(BitStream *bs) const -{ - Serialize(sharedString->c_str, bs); -} -void RakString::Serialize(const char *str, BitStream *bs) -{ - unsigned short l = (unsigned short) strlen(str); - bs->Write(l); - bs->WriteAlignedBytes((const unsigned char*) str, (const unsigned int) l); -} -void RakString::SerializeCompressed(BitStream *bs, uint8_t languageId, bool writeLanguageId) const -{ - SerializeCompressed(C_String(), bs, languageId, writeLanguageId); -} -void RakString::SerializeCompressed(const char *str, BitStream *bs, uint8_t languageId, bool writeLanguageId) -{ - if (writeLanguageId) - bs->WriteCompressed(languageId); - StringCompressor::Instance()->EncodeString(str,0xFFFF,bs,languageId); -} -bool RakString::Deserialize(BitStream *bs) -{ - Clear(); - - bool b; - unsigned short l; - b=bs->Read(l); - if (l>0) - { - Allocate(((unsigned int) l)+1); - b=bs->ReadAlignedBytes((unsigned char*) sharedString->c_str, l); - if (b) - sharedString->c_str[l]=0; - else - Clear(); - } - else - bs->AlignReadToByteBoundary(); - return b; -} -bool RakString::Deserialize(char *str, BitStream *bs) -{ - bool b; - unsigned short l; - b=bs->Read(l); - if (b && l>0) - b=bs->ReadAlignedBytes((unsigned char*) str, l); - - if (b==false) - str[0]=0; - - str[l]=0; - return b; -} -bool RakString::DeserializeCompressed(BitStream *bs, bool readLanguageId) -{ - uint8_t languageId; - if (readLanguageId) - bs->ReadCompressed(languageId); - else - languageId=0; - return StringCompressor::Instance()->DecodeString(this,0xFFFF,bs,languageId); -} -bool RakString::DeserializeCompressed(char *str, BitStream *bs, bool readLanguageId) -{ - uint8_t languageId; - if (readLanguageId) - bs->ReadCompressed(languageId); - else - languageId=0; - return StringCompressor::Instance()->DecodeString(str,0xFFFF,bs,languageId); -} -const char *RakString::ToString(int64_t i) -{ - static int index=0; - static char buff[64][64]; -#if defined(_WIN32) - sprintf_s(buff[index], "%I64d", i); -#else - sprintf_s(buff[index], "%lld", (long long unsigned int) i); -#endif - int lastIndex=index; - if (++index==64) - index=0; - return buff[lastIndex]; -} -const char *RakString::ToString(uint64_t i) -{ - static int index=0; - static char buff[64][64]; -#if defined(_WIN32) - sprintf_s(buff[index], "%I64u", i); -#else - sprintf_s(buff[index], "%llu", (long long unsigned int) i); -#endif - int lastIndex=index; - if (++index==64) - index=0; - return buff[lastIndex]; -} -void RakString::Clear(void) -{ - Free(); -} -void RakString::Allocate(size_t len) -{ - RakString::LockMutex(); - // sharedString = RakString::pool.Allocate( _FILE_AND_LINE_ ); - if (RakString::freeList.Size()==0) - { - //RakString::sharedStringFreeList=(RakString::SharedString*) rakRealloc_Ex(RakString::sharedStringFreeList,(RakString::sharedStringFreeListAllocationCount+1024)*sizeof(RakString::SharedString), _FILE_AND_LINE_); - unsigned i; - for (i=0; i < 128; i++) - { - // RakString::freeList.Insert(RakString::sharedStringFreeList+i+RakString::sharedStringFreeListAllocationCount); - // RakString::freeList.Insert((RakString::SharedString*)rakMalloc_Ex(sizeof(RakString::SharedString), _FILE_AND_LINE_), _FILE_AND_LINE_); - - RakString::SharedString *ss; - ss = (RakString::SharedString*) rakMalloc_Ex(sizeof(RakString::SharedString), _FILE_AND_LINE_); - ss->refCountMutex= MafiaNet::OP_NEW(_FILE_AND_LINE_); - RakString::freeList.Insert(ss, _FILE_AND_LINE_); - } - //RakString::sharedStringFreeListAllocationCount+=1024; - } - sharedString = RakString::freeList[RakString::freeList.Size()-1]; - RakString::freeList.RemoveAtIndex(RakString::freeList.Size()-1); - RakString::UnlockMutex(); - - const size_t smallStringSize = 128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2; - sharedString->refCount=1; - if (len <= smallStringSize) - { - sharedString->bytesUsed=smallStringSize; - sharedString->c_str=sharedString->smallString; - } - else - { - sharedString->bytesUsed=len<<1; - sharedString->bigString=(char*)rakMalloc_Ex(sharedString->bytesUsed, _FILE_AND_LINE_); - sharedString->c_str=sharedString->bigString; - } -} -void RakString::Assign(const char *str) -{ - if (str==0 || str[0]==0) - { - sharedString=&emptyString; - return; - } - - size_t len = strlen(str)+1; - Allocate(len); - memcpy(sharedString->c_str, str, len); -} -void RakString::Assign(const char *str, va_list ap) -{ - if (str==0 || str[0]==0) - { - sharedString=&emptyString; - return; - } - - char stackBuff[512]; - int numChars = vsnprintf_s(stackBuff, 511, str, ap); - if (numChars != -1) - { - Assign(stackBuff); - return; - } - char *buff=0, *newBuff; - size_t buffSize=8096; - for(;;) - { - newBuff = (char*) rakRealloc_Ex(buff, buffSize,__FILE__,__LINE__); - if (newBuff==0) - { - notifyOutOfMemory(_FILE_AND_LINE_); - if (buff!=0) - { - Assign(buff); - rakFree_Ex(buff,__FILE__,__LINE__); - } - else - { - Assign(stackBuff); - } - return; - } - buff=newBuff; - if (vsnprintf_s(buff, buffSize, buffSize-1, str, ap)!=-1) - { - Assign(buff); - rakFree_Ex(buff,__FILE__,__LINE__); - return; - } - buffSize*=2; - } -} -MafiaNet::RakString RakString::Assign(const char *str,size_t pos, size_t n ) -{ - size_t incomingLen=strlen(str); - - Clone(); - - if (str==0 || str[0]==0||pos>=incomingLen) - { - sharedString=&emptyString; - return (*this); - } - - if (pos+n>=incomingLen) - { - n=incomingLen-pos; - - } - const char * tmpStr=&(str[pos]); - - size_t len = n+1; - Allocate(len); - memcpy(sharedString->c_str, tmpStr, len); - sharedString->c_str[n]=0; - - return (*this); -} - -MafiaNet::RakString RakString::NonVariadic(const char *str) -{ - MafiaNet::RakString rs; - rs=str; - return rs; -} -unsigned long RakString::ToInteger(const char *str) -{ - unsigned long hash = 0; - int c = *str; - - while (c) { - hash = c + (hash << 6) + (hash << 16) - hash; - c = *(++str); - } - - return hash; -} -unsigned long RakString::ToInteger(const RakString &rs) -{ - return RakString::ToInteger(rs.C_String()); -} -int RakString::ReadIntFromSubstring(const char *str, size_t pos, size_t n) -{ - char tmp[32]; - if (n >= 32) - return 0; - for (size_t i=0; i < n; i++) - tmp[i]=str[i+pos]; - return atoi(tmp); -} -void RakString::AppendBytes(const char *bytes, size_t count) -{ - if (IsEmpty()) - { - Allocate(count); - memcpy(sharedString->c_str, bytes, count+1); - sharedString->c_str[count]=0; - } - else - { - Clone(); - unsigned int length=(unsigned int) GetLength(); - Realloc(sharedString, count+length+1); - memcpy(sharedString->c_str+length, bytes, count); - sharedString->c_str[length+count]=0; - } - - -} -void RakString::Clone(void) -{ - RakAssert(sharedString!=&emptyString); - if (sharedString==&emptyString) - { - return; - } - - // Empty or solo then no point to cloning - sharedString->refCountMutex->Lock(); - if (sharedString->refCount==1) - { - sharedString->refCountMutex->Unlock(); - return; - } - - sharedString->refCount--; - sharedString->refCountMutex->Unlock(); - Assign(sharedString->c_str); -} -void RakString::Free(void) -{ - if (sharedString==&emptyString) - return; - sharedString->refCountMutex->Lock(); - sharedString->refCount--; - if (sharedString->refCount==0) - { - sharedString->refCountMutex->Unlock(); - const size_t smallStringSize = 128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2; - if (sharedString->bytesUsed>smallStringSize) - rakFree_Ex(sharedString->bigString, _FILE_AND_LINE_ ); - /* - poolMutex->Lock(); - pool.Release(sharedString); - poolMutex->Unlock(); - */ - - RakString::LockMutex(); - RakString::freeList.Insert(sharedString, _FILE_AND_LINE_); - RakString::UnlockMutex(); - - sharedString=&emptyString; - } - else - { - sharedString->refCountMutex->Unlock(); - } - sharedString=&emptyString; -} -unsigned char RakString::ToLower(unsigned char c) -{ - if (c >= 'A' && c <= 'Z') - return c-'A'+'a'; - return c; -} -unsigned char RakString::ToUpper(unsigned char c) -{ - if (c >= 'a' && c <= 'z') - return c-'a'+'A'; - return c; -} -void RakString::LockMutex(void) -{ - GetPoolMutex().Lock(); -} -void RakString::UnlockMutex(void) -{ - GetPoolMutex().Unlock(); -} - -/* -#include "mafianet/string.h" -#include -#include "mafianet/GetTime.h" - -using namespace MafiaNet; - -int main(void) -{ - RakString s3("Hello world"); - RakString s5=s3; - - RakString s1; - RakString s2('a'); - - RakString s4("%i %f", 5, 6.0); - - RakString s6=s3; - RakString s7=s6; - RakString s8=s6; - RakString s9; - s9=s9; - RakString s10(s3); - RakString s11=s10 + s4 + s9 + s2; - s11+=RakString("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); - RakString s12("Test"); - s12+=s11; - bool b1 = s12==s12; - s11=s5; - s12.ToUpper(); - s12.ToLower(); - RakString s13; - bool b3 = s13.IsEmpty(); - s13.Set("blah %s", s12.C_String()); - bool b4 = s13.IsEmpty(); - size_t i1=s13.GetLength(); - s3.Clear(_FILE_AND_LINE_); - s4.Clear(_FILE_AND_LINE_); - s5.Clear(_FILE_AND_LINE_); - s5.Clear(_FILE_AND_LINE_); - s6.Printf(); - s7.Printf(); - RAKNET_DEBUG_PRINTF("\n"); - - static const int repeatCount=750; - DataStructures::List rakStringList; - DataStructures::List stdStringList; - DataStructures::List referenceStringList; - char *c; - unsigned i; - MafiaNet::TimeMS beforeReferenceList, beforeRakString, beforeStdString, afterStdString; - - unsigned loop; - for (loop=0; loop<2; loop++) - { - beforeReferenceList=MafiaNet::GetTimeMS(); - for (i=0; i < repeatCount; i++) - { - c = MafiaNet::OP_NEW_ARRAY(56,_FILE_AND_LINE_ ); - strcpy_s(c, 56, "Aalsdkj alsdjf laksdjf ;lasdfj ;lasjfd"); - referenceStringList.Insert(c); - } - beforeRakString=MafiaNet::GetTimeMS(); - for (i=0; i < repeatCount; i++) - rakStringList.Insert("Aalsdkj alsdjf laksdjf ;lasdfj ;lasjfd"); - beforeStdString=MafiaNet::GetTimeMS(); - - for (i=0; i < repeatCount; i++) - stdStringList.Insert("Aalsdkj alsdjf laksdjf ;lasdfj ;lasjfd"); - afterStdString=MafiaNet::GetTimeMS(); - RAKNET_DEBUG_PRINTF("Insertion 1 Ref=%i Rak=%i, Std=%i\n", beforeRakString-beforeReferenceList, beforeStdString-beforeRakString, afterStdString-beforeStdString); - - beforeReferenceList=MafiaNet::GetTimeMS(); - for (i=0; i < repeatCount; i++) - { - MafiaNet::OP_DELETE_ARRAY(referenceStringList[0], _FILE_AND_LINE_); - referenceStringList.RemoveAtIndex(0); - } - beforeRakString=MafiaNet::GetTimeMS(); - for (i=0; i < repeatCount; i++) - rakStringList.RemoveAtIndex(0); - beforeStdString=MafiaNet::GetTimeMS(); - for (i=0; i < repeatCount; i++) - stdStringList.RemoveAtIndex(0); - afterStdString=MafiaNet::GetTimeMS(); - RAKNET_DEBUG_PRINTF("RemoveHead Ref=%i Rak=%i, Std=%i\n", beforeRakString-beforeReferenceList, beforeStdString-beforeRakString, afterStdString-beforeStdString); - - beforeReferenceList=MafiaNet::GetTimeMS(); - for (i=0; i < repeatCount; i++) - { - c = MafiaNet::OP_NEW_ARRAY(56, _FILE_AND_LINE_ ); - strcpy_s(c, 56, "Aalsdkj alsdjf laksdjf ;lasdfj ;lasjfd"); - referenceStringList.Insert(0); - } - beforeRakString=MafiaNet::GetTimeMS(); - for (i=0; i < repeatCount; i++) - rakStringList.Insert("Aalsdkj alsdjf laksdjf ;lasdfj ;lasjfd"); - beforeStdString=MafiaNet::GetTimeMS(); - for (i=0; i < repeatCount; i++) - stdStringList.Insert("Aalsdkj alsdjf laksdjf ;lasdfj ;lasjfd"); - afterStdString=MafiaNet::GetTimeMS(); - RAKNET_DEBUG_PRINTF("Insertion 2 Ref=%i Rak=%i, Std=%i\n", beforeRakString-beforeReferenceList, beforeStdString-beforeRakString, afterStdString-beforeStdString); - - beforeReferenceList=MafiaNet::GetTimeMS(); - for (i=0; i < repeatCount; i++) - { - MafiaNet::OP_DELETE_ARRAY(referenceStringList[referenceStringList.Size()-1], _FILE_AND_LINE_); - referenceStringList.RemoveAtIndex(referenceStringList.Size()-1); - } - beforeRakString=MafiaNet::GetTimeMS(); - for (i=0; i < repeatCount; i++) - rakStringList.RemoveAtIndex(rakStringList.Size()-1); - beforeStdString=MafiaNet::GetTimeMS(); - for (i=0; i < repeatCount; i++) - stdStringList.RemoveAtIndex(stdStringList.Size()-1); - afterStdString=MafiaNet::GetTimeMS(); - RAKNET_DEBUG_PRINTF("RemoveTail Ref=%i Rak=%i, Std=%i\n", beforeRakString-beforeReferenceList, beforeStdString-beforeRakString, afterStdString-beforeStdString); - - } - - printf("Done."); - char str[128]; - Gets(str, sizeof(str)); - return 1; -} -*/ diff --git a/vendors/mafianet/Source/src/RakThread.cpp b/vendors/mafianet/Source/src/RakThread.cpp deleted file mode 100644 index 77157e680..000000000 --- a/vendors/mafianet/Source/src/RakThread.cpp +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/thread.h" -#include "mafianet/assert.h" -#include "mafianet/defines.h" -#include "mafianet/sleep.h" -#include "mafianet/memoryoverride.h" - -using namespace MafiaNet; - -#if defined(_WIN32) - #include "mafianet/WindowsIncludes.h" - #include - #include -#else -#include -#endif - -#if defined(_WIN32) -int RakThread::Create( unsigned __stdcall start_address( void* ), void *arglist, int priority) - - - -#else -int RakThread::Create( void* start_address( void* ), void *arglist, int priority) -#endif -{ -#ifdef _WIN32 - HANDLE threadHandle; - unsigned threadID = 0; - - threadHandle = (HANDLE) _beginthreadex(nullptr, MAX_ALLOCA_STACK_ALLOCATION*2, start_address, arglist, 0, &threadID ); - - SetThreadPriority(threadHandle, priority); - - if (threadHandle==0) - { - return 1; - } - else - { - CloseHandle( threadHandle ); - return 0; - } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#else - pthread_t threadHandle; - // Create thread linux - pthread_attr_t attr; - sched_param param; - param.sched_priority=priority; - pthread_attr_init( &attr ); - pthread_attr_setschedparam(&attr, ¶m); - - - - - - pthread_attr_setstacksize(&attr, MAX_ALLOCA_STACK_ALLOCATION*2); - - pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_DETACHED ); - int res = pthread_create( &threadHandle, &attr, start_address, arglist ); - RakAssert(res==0 && "pthread_create in RakThread.cpp failed.") - return res; -#endif -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/vendors/mafianet/Source/src/RakWString.cpp b/vendors/mafianet/Source/src/RakWString.cpp deleted file mode 100644 index 4b11617b5..000000000 --- a/vendors/mafianet/Source/src/RakWString.cpp +++ /dev/null @@ -1,468 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/wstring.h" -#include "mafianet/BitStream.h" -#include -#include -#include -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace MafiaNet; - -// From http://www.joelonsoftware.com/articles/Unicode.html -// Only code points 128 and above are stored using 2, 3, in fact, up to 6 bytes. -#define MAX_BYTES_PER_UNICODE_CHAR sizeof(wchar_t) - -RakWString::RakWString() -{ - c_str=0; - c_strCharLength=0; -} -RakWString::RakWString( const RakString &right ) -{ - c_str=0; - c_strCharLength=0; - *this=right; -} -RakWString::RakWString( const char *input ) -{ - c_str=0; - c_strCharLength=0; - *this = input; -} -RakWString::RakWString( const wchar_t *input ) -{ - c_str=0; - c_strCharLength=0; - *this = input; -} -RakWString::RakWString( const RakWString & right) -{ - c_str=0; - c_strCharLength=0; - *this = right; -} -RakWString::~RakWString() -{ - rakFree_Ex(c_str,_FILE_AND_LINE_); -} -RakWString& RakWString::operator = ( const RakWString& right ) -{ - Clear(); - if (right.IsEmpty()) - return *this; - c_str = (wchar_t *) rakMalloc_Ex( (right.GetLength() + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); - if (!c_str) - { - c_strCharLength=0; - notifyOutOfMemory(_FILE_AND_LINE_); - return *this; - } - c_strCharLength = right.GetLength(); - memcpy(c_str,right.C_String(),(right.GetLength() + 1) * MAX_BYTES_PER_UNICODE_CHAR); - - return *this; -} -RakWString& RakWString::operator = ( const RakString& right ) -{ - return *this = right.C_String(); -} -RakWString& RakWString::operator = ( const wchar_t * const str ) -{ - Clear(); - if (str==0) - return *this; - c_strCharLength = wcslen(str); - if (c_strCharLength==0) - return *this; - c_str = (wchar_t *) rakMalloc_Ex( (c_strCharLength + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); - if (!c_str) - { - c_strCharLength=0; - notifyOutOfMemory(_FILE_AND_LINE_); - return *this; - } - wcscpy_s(c_str,c_strCharLength+1,str); - - return *this; -} -RakWString& RakWString::operator = ( wchar_t *str ) -{ - *this = ( const wchar_t * const) str; - return *this; -} -RakWString& RakWString::operator = ( const char * const str ) -{ - Clear(); - -// Not supported on android -#if !defined(ANDROID) - if (str==0) - return *this; - if (str[0]==0) - return *this; - - mbstowcs_s(&c_strCharLength, nullptr, 0, str, 0); - c_str = (wchar_t *) rakMalloc_Ex( (c_strCharLength + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); - if (!c_str) - { - c_strCharLength=0; - notifyOutOfMemory(_FILE_AND_LINE_); - return *this; - } - - mbstowcs_s(&c_strCharLength, c_str, c_strCharLength + 1, str, c_strCharLength); - if (c_strCharLength == (size_t) (-1)) - { - RAKNET_DEBUG_PRINTF("Couldn't convert string--invalid multibyte character.\n"); - Clear(); - return *this; - } -#else - // mbstowcs not supported on android - RakAssert("mbstowcs not supported on Android" && 0); -#endif // defined(ANDROID) - - return *this; -} -RakWString& RakWString::operator = ( char *str ) -{ - *this = ( const char * const) str; - return *this; -} -RakWString& RakWString::operator +=( const RakWString& right) -{ - if (right.IsEmpty()) - return *this; - size_t newCharLength = c_strCharLength + right.GetLength(); - wchar_t *newCStr; - bool isEmpty = IsEmpty(); - if (isEmpty) - newCStr = (wchar_t *) rakMalloc_Ex( (newCharLength + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); - else - newCStr = (wchar_t *) rakRealloc_Ex( c_str, (newCharLength + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); - if (!newCStr) - { - notifyOutOfMemory(_FILE_AND_LINE_); - return *this; - } - c_str = newCStr; - c_strCharLength = newCharLength; - if (isEmpty) - { - memcpy(newCStr,right.C_String(),(right.GetLength() + 1) * MAX_BYTES_PER_UNICODE_CHAR); - } - else - { - wcscat_s(c_str, newCharLength + 1, right.C_String()); - } - - return *this; -} -RakWString& RakWString::operator += ( const wchar_t * const right ) -{ - if (right==0) - return *this; - size_t rightLength = wcslen(right); - size_t newCharLength = c_strCharLength + rightLength; - wchar_t *newCStr; - bool isEmpty = IsEmpty(); - if (isEmpty) - newCStr = (wchar_t *) rakMalloc_Ex( (newCharLength + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); - else - newCStr = (wchar_t *) rakRealloc_Ex( c_str, (newCharLength + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); - if (!newCStr) - { - notifyOutOfMemory(_FILE_AND_LINE_); - return *this; - } - c_str = newCStr; - c_strCharLength = newCharLength; - if (isEmpty) - { - memcpy(newCStr,right,(rightLength + 1) * MAX_BYTES_PER_UNICODE_CHAR); - } - else - { - wcscat_s(c_str, newCharLength + 1, right); - } - - return *this; -} -RakWString& RakWString::operator += ( wchar_t *right ) -{ - return *this += (const wchar_t * const) right; -} -bool RakWString::operator==(const RakWString &right) const -{ - if (GetLength()!=right.GetLength()) - return false; - return wcscmp(C_String(),right.C_String())==0; -} -bool RakWString::operator < ( const RakWString& right ) const -{ - return wcscmp(C_String(),right.C_String())<0; -} -bool RakWString::operator <= ( const RakWString& right ) const -{ - return wcscmp(C_String(),right.C_String())<=0; -} -bool RakWString::operator > ( const RakWString& right ) const -{ - return wcscmp(C_String(),right.C_String())>0; -} -bool RakWString::operator >= ( const RakWString& right ) const -{ - return wcscmp(C_String(),right.C_String())>=0; -} -bool RakWString::operator!=(const RakWString &right) const -{ - if (GetLength()!=right.GetLength()) - return true; - return wcscmp(C_String(),right.C_String())!=0; -} -void RakWString::Set( wchar_t *str ) -{ - *this = str; -} -bool RakWString::IsEmpty(void) const -{ - return GetLength()==0; -} -size_t RakWString::GetLength(void) const -{ - return c_strCharLength; -} -unsigned long RakWString::ToInteger(const RakWString &rs) -{ - unsigned long hash = 0; - int c; - - const char *str = (const char *)rs.C_String(); - size_t i; - for (i=0; i < rs.GetLength()*MAX_BYTES_PER_UNICODE_CHAR*sizeof(wchar_t); i++) - { - c = *str++; - hash = c + (hash << 6) + (hash << 16) - hash; - } - - return hash; -} -int RakWString::StrCmp(const RakWString &right) const -{ - return wcscmp(C_String(), right.C_String()); -} -int RakWString::StrICmp(const RakWString &right) const -{ -#ifdef _WIN32 - return _wcsicmp(C_String(), right.C_String()); -#else - // Not supported - return wcscmp(C_String(), right.C_String()); -#endif -} -void RakWString::Clear(void) -{ - rakFree_Ex(c_str,_FILE_AND_LINE_); - c_str=0; - c_strCharLength=0; -} -void RakWString::Printf(void) -{ - printf("%ls", C_String()); -} -void RakWString::FPrintf(FILE *fp) -{ - fprintf(fp,"%ls", C_String()); -} -void RakWString::Serialize(BitStream *bs) const -{ - Serialize(C_String(), bs); -} -void RakWString::Serialize(const wchar_t * const str, BitStream *bs) -{ -#if 0 - char *multiByteBuffer; - size_t allocated = wcslen(str)*MAX_BYTES_PER_UNICODE_CHAR; - multiByteBuffer = (char*) rakMalloc_Ex(allocated, _FILE_AND_LINE_); - size_t used = wcstombs(multiByteBuffer, str, allocated); - bs->WriteCasted(used); - bs->WriteAlignedBytes((const unsigned char*) multiByteBuffer,(const unsigned int) used); - rakFree_Ex(multiByteBuffer, _FILE_AND_LINE_); -#else - size_t mbByteLength = wcslen(str); - bs->WriteCasted(mbByteLength); - for (unsigned int i=0; i < mbByteLength; i++) - { - uint16_t t; - t = (uint16_t) str[i]; - // Force endian swapping, and write to 16 bits - bs->Write(t); - } -#endif -} -bool RakWString::Deserialize(BitStream *bs) -{ - Clear(); - - size_t mbByteLength; - bs->ReadCasted(mbByteLength); - if (mbByteLength>0) - { -#if 0 - char *multiByteBuffer; - multiByteBuffer = (char*) rakMalloc_Ex(mbByteLength+1, _FILE_AND_LINE_); - bool result = bs->ReadAlignedBytes((unsigned char*) multiByteBuffer,(const unsigned int) mbByteLength); - if (result==false) - { - rakFree_Ex(multiByteBuffer, _FILE_AND_LINE_); - return false; - } - multiByteBuffer[mbByteLength]=0; - c_str = (wchar_t *) rakMalloc_Ex( (mbByteLength + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); - mbstowcs_s(&c_strCharLength, c_str, mbByteLength + 1, multiByteBuffer, mbByteLength); - rakFree_Ex(multiByteBuffer, _FILE_AND_LINE_); - c_str[c_strCharLength]=0; -#else - c_str = (wchar_t*) rakMalloc_Ex((mbByteLength+1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); - c_strCharLength = mbByteLength; - for (unsigned int i=0; i < mbByteLength; i++) - { - uint16_t t; - // Force endian swapping, and read 16 bits - bs->Read(t); - c_str[i]=t; - } - c_str[mbByteLength]=0; -#endif - return true; - } - else - { - return true; - } -} -bool RakWString::Deserialize(wchar_t *str, BitStream *bs) -{ - size_t mbByteLength; - bs->ReadCasted(mbByteLength); - if (mbByteLength > 0) - { -#if 0 - char *multiByteBuffer; - multiByteBuffer = (char*)rakMalloc_Ex(mbByteLength + 1, _FILE_AND_LINE_); - bool result = bs->ReadAlignedBytes((unsigned char*)multiByteBuffer, (const unsigned int)mbByteLength); - if (result == false) - { - rakFree_Ex(multiByteBuffer, _FILE_AND_LINE_); - return false; - } - multiByteBuffer[mbByteLength] = 0; - size_t c_strCharLength; - mbstowcs(&c_strCharLength, str, multiByteBuffer, mbByteLength); - rakFree_Ex(multiByteBuffer, _FILE_AND_LINE_); - str[c_strCharLength] = 0; -#else - for (unsigned int i = 0; i < mbByteLength; i++) - { - uint16_t t; - // Force endian swapping, and read 16 bits - bs->Read(t); - str[i] = t; - } - str[mbByteLength] = 0; -#endif - return true; - } - else - { -#pragma warning(push) -#pragma warning(disable:4996) - wcscpy(str, L""); -#pragma warning(pop) - } - return true; -} -bool RakWString::Deserialize(wchar_t *str, size_t strLength, BitStream *bs) -{ - size_t mbByteLength; - bs->ReadCasted(mbByteLength); - if (mbByteLength>0) - { -#if 0 - char *multiByteBuffer; - multiByteBuffer = (char*) rakMalloc_Ex(mbByteLength+1, _FILE_AND_LINE_); - bool result = bs->ReadAlignedBytes((unsigned char*) multiByteBuffer,(const unsigned int) mbByteLength); - if (result==false) - { - rakFree_Ex(multiByteBuffer, _FILE_AND_LINE_); - return false; - } - multiByteBuffer[mbByteLength]=0; - size_t c_strCharLength; - mbstowcs_s(&c_strCharLength, str, strLength, multiByteBuffer, mbByteLength); - rakFree_Ex(multiByteBuffer, _FILE_AND_LINE_); - str[c_strCharLength]=0; -#else - for (unsigned int i=0; i < mbByteLength; i++) - { - uint16_t t; - // Force endian swapping, and read 16 bits - bs->Read(t); - str[i]=t; - } - str[mbByteLength]=0; -#endif - return true; - } - else - { - wcscpy_s(str,strLength,L""); - } - return true; -} - -const MafiaNet::RakWString operator+(const MafiaNet::RakWString &lhs, const MafiaNet::RakWString &rhs) -{ - MafiaNet::RakWString returnvalue(lhs); - returnvalue += rhs; - return returnvalue; -} - -/* -MafiaNet::BitStream bsTest; -MafiaNet::RakWString testString("cat"), testString2; -testString = "Hllo"; -testString = L"Hello"; -testString += L" world"; -testString2 += testString2; -MafiaNet::RakWString ts3(L" from here"); -testString2+=ts3; -MafiaNet::RakWString ts4(L" 222"); -testString2=ts4; -MafiaNet::RakString rs("rakstring"); -testString2+=rs; -testString2=rs; -bsTest.Write(L"one"); -bsTest.Write(testString2); -bsTest.SetReadOffset(0); -MafiaNet::RakWString ts5, ts6; -wchar_t buff[99]; -wchar_t *wptr = (wchar_t*)buff; -bsTest.Read(wptr); -bsTest.Read(ts5); -*/ diff --git a/vendors/mafianet/Source/src/Rand.cpp b/vendors/mafianet/Source/src/Rand.cpp deleted file mode 100644 index da4b4ffe5..000000000 --- a/vendors/mafianet/Source/src/Rand.cpp +++ /dev/null @@ -1,283 +0,0 @@ -/** -* -* Grabbed by Kevin from http://www.math.keio.ac.jp/~matumoto/cokus.c -* This is the ``Mersenne Twister'' random number generator MT19937, which -* generates pseudorandom integers uniformly distributed in 0..(2^32 - 1) -* starting from any odd seed in 0..(2^32 - 1). This version is a recode -* by Shawn Cokus (Cokus@math.washington.edu) on March 8, 1998 of a version by -* Takuji Nishimura (who had suggestions from Topher Cooper and Marc Rieffel in -* July-August 1997). -* -* Effectiveness of the recoding (on Goedel2.math.washington.edu, a DEC Alpha -* running OSF/1) using GCC -O3 as a compiler: before recoding: 51.6 sec. to -* generate 300 million random numbers; after recoding: 24.0 sec. for the same -* (i.e., 46.5% of original time), so speed is now about 12.5 million random -* number generations per second on this machine. -* -* According to the URL -* (and paraphrasing a bit in places), the Mersenne Twister is ``designed -* with consideration of the flaws of various existing generators,'' has -* a period of 2^19937 - 1, gives a sequence that is 623-dimensionally -* equidistributed, and ``has passed many stringent tests, including the -* die-hard test of G. Marsaglia and the load test of P. Hellekalek and -* S. Wegenkittl.'' It is efficient in memory usage (typically using 2506 -* to 5012 bytes of static data, depending on data type sizes, and the code -* is quite short as well). It generates random numbers in batches of 624 -* at a time, so the caching and pipelining of modern systems is exploited. -* It is also divide- and mod-free. -* -* Licensing is free http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/elicense.html -* -* The code as Shawn received it included the following notice: -* -* Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. When -* you use this, send an e-mail to with -* an appropriate reference to your work. -* -* It would be nice to CC: when you write. -* -* Note from SLikeSoft: The mail addresses here seem to be dead ends and we could not determine any current ways to contact the authors. -*/ - -/* - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include -#include -#include -#include "mafianet/Rand.h" - -// -// uint32 must be an unsigned integer type capable of holding at least 32 -// bits; exactly 32 should be fastest, but 64 is better on an Alpha with -// GCC at -O3 optimization so try your options and see what's best for you -// - -//typedef unsigned int uint32; - -#define N (624) // length of state vector -#define M (397) // a period parameter -#define K (0x9908B0DFU) // a magic constant -#define hiBit(u) ((u) & 0x80000000U) // mask all but highest bit of u -#define loBit(u) ((u) & 0x00000001U) // mask all but lowest bit of u -#define loBits(u) ((u) & 0x7FFFFFFFU) // mask the highest bit of u -#define mixBits(u, v) (hiBit(u)|loBits(v)) // move hi bit of u to hi bit of v - -static unsigned int _state[ N + 1 ]; // state vector + 1 extra to not violate ANSI C -static unsigned int *_next; // next random value is computed from here -static int _left = -1; // can *next++ this many times before reloading - -using namespace MafiaNet; - -void seedMT( unsigned int seed, unsigned int *state, unsigned int *&next, int &left ); -unsigned int reloadMT( unsigned int *state, unsigned int *&next, int &left ); -unsigned int randomMT( unsigned int *state, unsigned int *&next, int &left ); -void fillBufferMT( void *buffer, unsigned int bytes, unsigned int *state, unsigned int *&next, int &left ); -float frandomMT( unsigned int *state, unsigned int *&next, int &left ); - -// Uses global vars -void seedMT( unsigned int seed ) -{ - seedMT(seed, _state, _next, _left); -} -unsigned int reloadMT( void ) -{ - return reloadMT(_state, _next, _left); -} -unsigned int randomMT( void ) -{ - return randomMT(_state, _next, _left); -} -float frandomMT( void ) -{ - return frandomMT(_state, _next, _left); -} -void fillBufferMT( void *buffer, unsigned int bytes ) -{ - fillBufferMT(buffer, bytes, _state, _next, _left); -} - -void seedMT( unsigned int seed, unsigned int *state, unsigned int *&next, int &left ) // Defined in cokus_c.c -{ - (void) next; - - // - // We initialize state[0..(N-1)] via the generator - // - // x_new = (69069 * x_old) mod 2^32 - // - // from Line 15 of Table 1, p. 106, Sec. 3.3.4 of Knuth's - // _The Art of Computer Programming_, Volume 2, 3rd ed. - // - // Notes (SJC): I do not know what the initial state requirements - // of the Mersenne Twister are, but it seems this seeding generator - // could be better. It achieves the maximum period for its modulus - // (2^30) iff x_initial is odd (p. 20-21, Sec. 3.2.1.2, Knuth); if - // x_initial can be even, you have sequences like 0, 0, 0, ...; - // 2^31, 2^31, 2^31, ...; 2^30, 2^30, 2^30, ...; 2^29, 2^29 + 2^31, - // 2^29, 2^29 + 2^31, ..., etc. so I force seed to be odd below. - // - // Even if x_initial is odd, if x_initial is 1 mod 4 then - // - // the lowest bit of x is always 1, - // the next-to-lowest bit of x is always 0, - // the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... , - // the 3rd-from-lowest bit of x 4-cycles ... 0 1 1 0 0 1 1 0 ... , - // the 4th-from-lowest bit of x has the 8-cycle ... 0 0 0 1 1 1 1 0 ... , - // ... - // - // and if x_initial is 3 mod 4 then - // - // the lowest bit of x is always 1, - // the next-to-lowest bit of x is always 1, - // the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... , - // the 3rd-from-lowest bit of x 4-cycles ... 0 0 1 1 0 0 1 1 ... , - // the 4th-from-lowest bit of x has the 8-cycle ... 0 0 1 1 1 1 0 0 ... , - // ... - // - // The generator's potency (min. s>=0 with (69069-1)^s = 0 mod 2^32) is - // 16, which seems to be alright by p. 25, Sec. 3.2.1.3 of Knuth. It - // also does well in the dimension 2..5 spectral tests, but it could be - // better in dimension 6 (Line 15, Table 1, p. 106, Sec. 3.3.4, Knuth). - // - // Note that the random number user does not see the values generated - // here directly since reloadMT() will always munge them first, so maybe - // none of all of this matters. In fact, the seed values made here could - // even be extra-special desirable if the Mersenne Twister theory says - // so-- that's why the only change I made is to restrict to odd seeds. - // - - unsigned int x = ( seed | 1U ) & 0xFFFFFFFFU, *s = state; - int j; - - for ( left = 0, *s++ = x, j = N; --j; - *s++ = ( x *= 69069U ) & 0xFFFFFFFFU ) - - ; -} - - -unsigned int reloadMT( unsigned int *state, unsigned int *&next, int &left ) -{ - unsigned int * p0 = state, *p2 = state + 2, *pM = state + M, s0, s1; - int j; - - if ( left < -1 ) - seedMT( 4357U ); - - left = N - 1, next = state + 1; - - for ( s0 = state[ 0 ], s1 = state[ 1 ], j = N - M + 1; --j; s0 = s1, s1 = *p2++ ) - * p0++ = *pM++ ^ ( mixBits( s0, s1 ) >> 1 ) ^ ( loBit( s1 ) ? K : 0U ); - - for ( pM = state, j = M; --j; s0 = s1, s1 = *p2++ ) - * p0++ = *pM++ ^ ( mixBits( s0, s1 ) >> 1 ) ^ ( loBit( s1 ) ? K : 0U ); - - s1 = state[ 0 ], *p0 = *pM ^ ( mixBits( s0, s1 ) >> 1 ) ^ ( loBit( s1 ) ? K : 0U ); - - s1 ^= ( s1 >> 11 ); - - s1 ^= ( s1 << 7 ) & 0x9D2C5680U; - - s1 ^= ( s1 << 15 ) & 0xEFC60000U; - - return ( s1 ^ ( s1 >> 18 ) ); -} - - -unsigned int randomMT( unsigned int *state, unsigned int *&next, int &left ) -{ - unsigned int y; - - if ( --left < 0 ) - return ( reloadMT(state, next, left) ); - - y = *next++; - - y ^= ( y >> 11 ); - - y ^= ( y << 7 ) & 0x9D2C5680U; - - y ^= ( y << 15 ) & 0xEFC60000U; - - return ( y ^ ( y >> 18 ) ); - - // This change made so the value returned is in the same range as what rand() returns - // return(y ^ (y >> 18)) % 32767; -} - -void fillBufferMT( void *buffer, unsigned int bytes, unsigned int *state, unsigned int *&next, int &left ) -{ - unsigned int offset=0; - unsigned int r; - while (bytes-offset>=sizeof(r)) - { - r = randomMT(state, next, left); - memcpy((char*)buffer+offset, &r, sizeof(r)); - offset+=sizeof(r); - } - - r = randomMT(state, next, left); - memcpy((char*)buffer+offset, &r, bytes-offset); -} - -float frandomMT( unsigned int *state, unsigned int *&next, int &left ) -{ - return ( float ) ( ( double ) randomMT(state, next, left) / 4294967296.0 ); -} -RakNetRandom::RakNetRandom() -{ - left=-1; -} -RakNetRandom::~RakNetRandom() -{ -} -void RakNetRandom::SeedMT( unsigned int seed ) -{ - printf("%i\n",seed); - seedMT(seed, state, next, left); -} - -unsigned int RakNetRandom::ReloadMT( void ) -{ - return reloadMT(state, next, left); -} - -unsigned int RakNetRandom::RandomMT( void ) -{ - return randomMT(state, next, left); -} - -float RakNetRandom::FrandomMT( void ) -{ - return frandomMT(state, next, left); -} - -void RakNetRandom::FillBufferMT( void *buffer, unsigned int bytes ) -{ - fillBufferMT(buffer, bytes, state, next, left); -} - -/* -int main(void) -{ -int j; - -// you can seed with any uint32, but the best are odds in 0..(2^32 - 1) - -seedMT(4357U); - -// print the first 2,002 random numbers seven to a line as an example - -for(j=0; j<2002; j++) -RAKNET_DEBUG_PRINTF(" %10lu%s", (unsigned int) randomMT(), (j%7)==6 ? "\n" : ""); - -return(EXIT_SUCCESS); -} - -*/ - diff --git a/vendors/mafianet/Source/src/RandSync.cpp b/vendors/mafianet/Source/src/RandSync.cpp deleted file mode 100644 index 40478a862..000000000 --- a/vendors/mafianet/Source/src/RandSync.cpp +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/RandSync.h" -#include "mafianet/BitStream.h" -#include -#include - -namespace MafiaNet -{ - -RakNetRandomSync::RakNetRandomSync() -{ - seed = (uint32_t) -1; - callCount = 0; - usedValueBufferCount = 0; -} -RakNetRandomSync::~RakNetRandomSync() -{ -} -void RakNetRandomSync::SeedMT( uint32_t _seed ) -{ - seed = _seed; - rnr.SeedMT( seed ); - callCount = 0; - usedValueBufferCount = 0; -} -void RakNetRandomSync::SeedMT( uint32_t _seed, uint32_t skipValues ) -{ - SeedMT(_seed); - Skip(skipValues); -} -float RakNetRandomSync::FrandomMT( void ) -{ - return ( float ) ( ( double ) RandomMT() / (double) UINT_MAX ); -} -unsigned int RakNetRandomSync::RandomMT( void ) -{ - if (usedValueBufferCount > 0) - { - --usedValueBufferCount; - if (usedValueBufferCount < usedValues.Size()) - { - // The remote system had less calls than the current system, so return values from the past - return usedValues[usedValues.Size()-usedValueBufferCount-1]; - } - else - { - // Unknown past value, too far back - // Return true random - return rnr.RandomMT(); - } - } - else - { - // Get random number and store what it is - usedValues.Push(rnr.RandomMT(), _FILE_AND_LINE_); - ++callCount; - while (usedValues.Size()>64) - usedValues.Pop(); - return usedValues[usedValues.Size()-1]; - } -} -uint32_t RakNetRandomSync::GetSeed( void ) const -{ - return seed; -} -uint32_t RakNetRandomSync::GetCallCount( void ) const -{ - return callCount; -} -void RakNetRandomSync::SetCallCount( uint32_t i ) -{ - callCount = i; -} -void RakNetRandomSync::SerializeConstruction(MafiaNet::BitStream *constructionBitstream) -{ - constructionBitstream->Write(seed); - constructionBitstream->Write(callCount); -} -bool RakNetRandomSync::DeserializeConstruction(MafiaNet::BitStream *constructionBitstream) -{ - uint32_t _seed; - uint32_t _skipValues; - constructionBitstream->Read(_seed); - bool success = constructionBitstream->Read(_skipValues); - if (success) - SeedMT(_seed, _skipValues); - return success; -} -void RakNetRandomSync::Serialize(MafiaNet::BitStream *outputBitstream) -{ - outputBitstream->Write(callCount); -} -void RakNetRandomSync::Deserialize(MafiaNet::BitStream *outputBitstream) -{ - uint32_t _callCount; - outputBitstream->Read(_callCount); - if (_callCount < callCount ) - { - // We locally read more values than the remote system - // The next n calls should come from buffered values - usedValueBufferCount = callCount - _callCount; - } - else if (_callCount > callCount ) - { - // Remote system read more values than us - uint32_t diff = _callCount - callCount; - if (diff <= usedValueBufferCount) - usedValueBufferCount -= diff; - if (diff > 0) - Skip(diff); - } -} -void RakNetRandomSync::Skip( uint32_t count ) -{ - for (uint32_t i = 0; i < count; i++) - rnr.RandomMT(); - callCount+=count; -} - -} // namespace MafiaNet - -/* -RakNetRandomSync r1, r2; -BitStream bsTest; -r1.SeedMT(0); -r1.SerializeConstruction(&bsTest); -bsTest.SetReadOffset(0); -r2.DeserializeConstruction(&bsTest); -printf("1. (r1) %f\n", r1.FrandomMT()); -printf("1. (r2) %f\n", r2.FrandomMT()); -printf("2. (r1) %f\n", r1.FrandomMT()); -printf("2. (r2) %f\n", r2.FrandomMT()); -printf("3. (r1) %f\n", r1.FrandomMT()); -printf("3. (r2) %f\n", r2.FrandomMT()); -printf("4. (r1) %f\n", r1.FrandomMT()); -printf("4. (r2) %f\n", r2.FrandomMT()); -printf("5. (r2) %f\n", r2.FrandomMT()); -printf("6. (r2) %f\n", r2.FrandomMT()); -printf("7. (r2) %f\n", r2.FrandomMT()); -bsTest.Reset(); -r1.Serialize(&bsTest); -bsTest.SetReadOffset(0); -r2.Deserialize(&bsTest); -printf("Synched r2 to match r1\n"); -printf("5. (r1) %f\n", r1.FrandomMT()); -printf("5. (r2) %f --Should continue sequence from 5-\n", r2.FrandomMT()); -printf("6. (r1) %f\n", r1.FrandomMT()); -printf("6. (r2) %f\n", r2.FrandomMT()); -printf("7. (r1) %f -- Extra call to r1, no r2 equivalent --\n", r1.FrandomMT()); -printf("8. (r1) %f -- Extra call to r1, no r2 equivalent --\n", r1.FrandomMT()); -bsTest.Reset(); -r1.Serialize(&bsTest); -bsTest.SetReadOffset(0); -r2.Deserialize(&bsTest); -printf("Synched r2 to match r1\n"); -printf("9. (r1) %f\n", r1.FrandomMT()); -printf("9. (r2) %f --SKIPPED 7,8, SHOULD MATCH 9-\n", r2.FrandomMT()); -*/ diff --git a/vendors/mafianet/Source/src/ReadyEvent.cpp b/vendors/mafianet/Source/src/ReadyEvent.cpp deleted file mode 100644 index 73ae516e5..000000000 --- a/vendors/mafianet/Source/src/ReadyEvent.cpp +++ /dev/null @@ -1,570 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_ReadyEvent==1 - -#include "mafianet/ReadyEvent.h" -#include "mafianet/peerinterface.h" -#include "mafianet/BitStream.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/assert.h" - -using namespace MafiaNet; - -int MafiaNet::ReadyEvent::RemoteSystemCompByGuid( const RakNetGUID &key, const RemoteSystem &data ) -{ - if (key < data.rakNetGuid) - return -1; - else if (key==data.rakNetGuid) - return 0; - else - return 1; -} - -int MafiaNet::ReadyEvent::ReadyEventNodeComp( const int &key, ReadyEvent::ReadyEventNode * const &data ) -{ - if (key < data->eventId) - return -1; - else if (key==data->eventId) - return 0; - else - return 1; -} - -STATIC_FACTORY_DEFINITIONS(ReadyEvent,ReadyEvent); - -ReadyEvent::ReadyEvent() -{ - channel=0; -} - -ReadyEvent::~ReadyEvent() -{ - Clear(); -} - - -bool ReadyEvent::SetEvent(int eventId, bool isReady) -{ - bool objectExists; - unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); - if (objectExists==false) - { - // Totally new event - CreateNewEvent(eventId, isReady); - } - else - { - return SetEventByIndex(eventIndex, isReady); - } - return true; -} -void ReadyEvent::ForceCompletion(int eventId) -{ - bool objectExists; - unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); - if (objectExists==false) - { - // Totally new event - CreateNewEvent(eventId, true); - eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); - } - - ReadyEventNode *ren = readyEventNodeList[eventIndex]; - ren->eventStatus=ID_READY_EVENT_FORCE_ALL_SET; - UpdateReadyStatus(eventIndex); -} -bool ReadyEvent::DeleteEvent(int eventId) -{ - bool objectExists; - unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); - if (objectExists) - { - MafiaNet::OP_DELETE(readyEventNodeList[eventIndex], _FILE_AND_LINE_); - readyEventNodeList.RemoveAtIndex(eventIndex); - return true; - } - return false; -} -bool ReadyEvent::IsEventSet(int eventId) -{ - bool objectExists; - unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); - if (objectExists) - { - return readyEventNodeList[eventIndex]->eventStatus==ID_READY_EVENT_SET || readyEventNodeList[eventIndex]->eventStatus==ID_READY_EVENT_ALL_SET; - } - return false; -} -bool ReadyEvent::IsEventCompletionProcessing(int eventId) const -{ - bool objectExists; - unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); - if (objectExists) - { - bool anyAllReady=false; - bool allAllReady=true; - ReadyEventNode *ren = readyEventNodeList[eventIndex]; - if (ren->eventStatus==ID_READY_EVENT_FORCE_ALL_SET) - return false; - for (unsigned i=0; i < ren->systemList.Size(); i++) - { - if (ren->systemList[i].lastReceivedStatus==ID_READY_EVENT_ALL_SET) - anyAllReady=true; - else - allAllReady=false; - } - return anyAllReady==true && allAllReady==false; - } - return false; -} -bool ReadyEvent::IsEventCompleted(int eventId) const -{ - bool objectExists; - unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); - if (objectExists) - { - return IsEventCompletedByIndex(eventIndex); - } - return false; -} - -bool ReadyEvent::HasEvent(int eventId) -{ - return readyEventNodeList.HasData(eventId); -} - -unsigned ReadyEvent::GetEventListSize(void) const -{ - return readyEventNodeList.Size(); -} - -int ReadyEvent::GetEventAtIndex(unsigned index) const -{ - return readyEventNodeList[index]->eventId; -} - -bool ReadyEvent::AddToWaitList(int eventId, RakNetGUID guid) -{ - bool eventExists; - unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &eventExists); - if (eventExists==false) - eventIndex=CreateNewEvent(eventId, false); - - // Don't do this, otherwise if we are trying to start a 3 player game, it will not allow the 3rd player to hit ready if the first two players have already done so - //if (IsLocked(eventIndex)) - // return false; // Not in the list, but event is already completed, or is starting to complete, and adding more waiters would fail this. - - unsigned i; - unsigned numAdded=0; - if (guid==UNASSIGNED_RAKNET_GUID) - { - for (i=0; i < rakPeerInterface->GetMaximumNumberOfPeers(); i++) - { - RakNetGUID firstGuid = rakPeerInterface->GetGUIDFromIndex(i); - if (firstGuid!=UNASSIGNED_RAKNET_GUID) - { - numAdded+=AddToWaitListInternal(eventIndex, firstGuid); - } - } - } - else - { - numAdded=AddToWaitListInternal(eventIndex, guid); - } - - if (numAdded>0) - UpdateReadyStatus(eventIndex); - return numAdded>0; -} -bool ReadyEvent::RemoveFromWaitList(int eventId, RakNetGUID guid) -{ - bool eventExists; - unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &eventExists); - if (eventExists) - { - if (guid==UNASSIGNED_RAKNET_GUID) - { - // Remove all waiters - readyEventNodeList[eventIndex]->systemList.Clear(false, _FILE_AND_LINE_); - UpdateReadyStatus(eventIndex); - } - else - { - bool systemExists; - unsigned systemIndex = readyEventNodeList[eventIndex]->systemList.GetIndexFromKey(guid, &systemExists); - if (systemExists) - { - bool isCompleted = IsEventCompletedByIndex(eventIndex); - readyEventNodeList[eventIndex]->systemList.RemoveAtIndex(systemIndex); - - if (isCompleted==false && IsEventCompletedByIndex(eventIndex)) - PushCompletionPacket(readyEventNodeList[eventIndex]->eventId); - - UpdateReadyStatus(eventIndex); - - return true; - } - } - } - - return false; -} -bool ReadyEvent::IsInWaitList(int eventId, RakNetGUID guid) -{ - bool objectExists; - unsigned readyIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); - if (objectExists) - { - return readyEventNodeList[readyIndex]->systemList.HasData(guid); - } - return false; -} - -unsigned ReadyEvent::GetRemoteWaitListSize(int eventId) const -{ - bool objectExists; - unsigned readyIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); - if (objectExists) - { - return readyEventNodeList[readyIndex]->systemList.Size(); - } - return 0; -} - -RakNetGUID ReadyEvent::GetFromWaitListAtIndex(int eventId, unsigned index) const -{ - bool objectExists; - unsigned readyIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); - if (objectExists) - { - return readyEventNodeList[readyIndex]->systemList[index].rakNetGuid; - } - return UNASSIGNED_RAKNET_GUID; -} -ReadyEventSystemStatus ReadyEvent::GetReadyStatus(int eventId, RakNetGUID guid) -{ - bool objectExists; - unsigned readyIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); - if (objectExists) - { - ReadyEventNode *ren = readyEventNodeList[readyIndex]; - unsigned systemIndex = ren->systemList.GetIndexFromKey(guid, &objectExists); - if (objectExists==false) - return RES_NOT_WAITING; - if (ren->systemList[systemIndex].lastReceivedStatus==ID_READY_EVENT_SET) - return RES_READY; - if (ren->systemList[systemIndex].lastReceivedStatus==ID_READY_EVENT_UNSET) - return RES_WAITING; - if (ren->systemList[systemIndex].lastReceivedStatus==ID_READY_EVENT_ALL_SET) - return RES_ALL_READY; - } - - return RES_UNKNOWN_EVENT; -} -void ReadyEvent::SetSendChannel(unsigned char newChannel) -{ - channel=newChannel; -} -PluginReceiveResult ReadyEvent::OnReceive(Packet *packet) -{ - unsigned char packetIdentifier; - packetIdentifier = ( unsigned char ) packet->data[ 0 ]; - -// bool doPrint = packet->systemAddress.GetPort()==60002 || rakPeerInterface->GetInternalID(UNASSIGNED_SYSTEM_ADDRESS).GetPort()==60002; - - switch (packetIdentifier) - { - case ID_READY_EVENT_UNSET: - case ID_READY_EVENT_SET: - case ID_READY_EVENT_ALL_SET: -// if (doPrint) {if (packet->systemAddress.GetPort()==60002) RAKNET_DEBUG_PRINTF("FROM 60002: "); else if (rakPeerInterface->GetInternalID(UNASSIGNED_SYSTEM_ADDRESS).port==60002) RAKNET_DEBUG_PRINTF("TO 60002: "); RAKNET_DEBUG_PRINTF("ID_READY_EVENT_SET\n");} - OnReadyEventPacketUpdate(packet); - return RR_CONTINUE_PROCESSING; - case ID_READY_EVENT_FORCE_ALL_SET: - OnReadyEventForceAllSet(packet); - return RR_CONTINUE_PROCESSING; - case ID_READY_EVENT_QUERY: -// if (doPrint) {if (packet->systemAddress.GetPort()==60002) RAKNET_DEBUG_PRINTF("FROM 60002: "); else if (rakPeerInterface->GetInternalID(UNASSIGNED_SYSTEM_ADDRESS).port==60002) RAKNET_DEBUG_PRINTF("TO 60002: "); RAKNET_DEBUG_PRINTF("ID_READY_EVENT_QUERY\n");} - OnReadyEventQuery(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - - return RR_CONTINUE_PROCESSING; -} -bool ReadyEvent::AddToWaitListInternal(unsigned eventIndex, RakNetGUID guid) -{ - ReadyEventNode *ren = readyEventNodeList[eventIndex]; - bool objectExists; - unsigned systemIndex = ren->systemList.GetIndexFromKey(guid, &objectExists); - if (objectExists==false) - { - RemoteSystem rs; - rs.lastReceivedStatus=ID_READY_EVENT_UNSET; - rs.lastSentStatus=ID_READY_EVENT_UNSET; - rs.rakNetGuid=guid; - ren->systemList.InsertAtIndex(rs,systemIndex, _FILE_AND_LINE_); - - SendReadyStateQuery(ren->eventId, guid); - return true; - } - return false; -} -void ReadyEvent::OnReadyEventForceAllSet(Packet *packet) -{ - MafiaNet::BitStream incomingBitStream(packet->data, packet->length, false); - incomingBitStream.IgnoreBits(8); - int eventId; - incomingBitStream.Read(eventId); - bool objectExists; - unsigned readyIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); - if (objectExists) - { - ReadyEventNode *ren = readyEventNodeList[readyIndex]; - if (ren->eventStatus!=ID_READY_EVENT_FORCE_ALL_SET) - { - ren->eventStatus=ID_READY_EVENT_FORCE_ALL_SET; - PushCompletionPacket(ren->eventId); - } - } -} -void ReadyEvent::OnReadyEventPacketUpdate(Packet *packet) -{ - MafiaNet::BitStream incomingBitStream(packet->data, packet->length, false); - incomingBitStream.IgnoreBits(8); - int eventId; - incomingBitStream.Read(eventId); - bool objectExists; - unsigned readyIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); - if (objectExists) - { - ReadyEventNode *ren = readyEventNodeList[readyIndex]; - bool systemExists; - unsigned systemIndex = ren->systemList.GetIndexFromKey(packet->guid, &systemExists); - if (systemExists) - { - // Just return if no change - if (ren->systemList[systemIndex].lastReceivedStatus==packet->data[0]) - return; - - bool wasCompleted = IsEventCompletedByIndex(readyIndex); - ren->systemList[systemIndex].lastReceivedStatus=packet->data[0]; - // If forced all set, doesn't matter what the new packet is - if (ren->eventStatus==ID_READY_EVENT_FORCE_ALL_SET) - return; - UpdateReadyStatus(readyIndex); - if (wasCompleted==false && IsEventCompletedByIndex(readyIndex)) - PushCompletionPacket(readyIndex); - } - } -} -void ReadyEvent::OnReadyEventQuery(Packet *packet) -{ - MafiaNet::BitStream incomingBitStream(packet->data, packet->length, false); - incomingBitStream.IgnoreBits(8); - int eventId; - incomingBitStream.Read(eventId); - bool objectExists; - unsigned readyIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); - if (objectExists) - { - unsigned systemIndex = readyEventNodeList[readyIndex]->systemList.GetIndexFromKey(packet->guid,&objectExists); - // Force the non-default send, because our initial send may have arrived at a system that didn't yet create the ready event - if (objectExists) - SendReadyUpdate(readyIndex, systemIndex, true); - } -} -void ReadyEvent::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) systemAddress; - (void) rakNetGUID; - (void) lostConnectionReason; - - RemoveFromAllLists(rakNetGUID); -} -void ReadyEvent::OnRakPeerShutdown(void) -{ - Clear(); -} - -bool ReadyEvent::SetEventByIndex(int eventIndex, bool isReady) -{ - ReadyEventNode *ren = readyEventNodeList[eventIndex]; - if ((ren->eventStatus==ID_READY_EVENT_ALL_SET || ren->eventStatus==ID_READY_EVENT_SET) && isReady==true) - return false; // Success - no change - if (ren->eventStatus==ID_READY_EVENT_UNSET && isReady==false) - return false; // Success - no change - if (ren->eventStatus==ID_READY_EVENT_FORCE_ALL_SET) - return false; // Can't change - - if (isReady) - ren->eventStatus=ID_READY_EVENT_SET; - else - ren->eventStatus=ID_READY_EVENT_UNSET; - - UpdateReadyStatus(eventIndex); - - // Check if now completed, and if so, tell the user about it - if (IsEventCompletedByIndex(eventIndex)) - { - PushCompletionPacket(ren->eventId); - } - - return true; -} - -bool ReadyEvent::IsEventCompletedByIndex(unsigned eventIndex) const -{ - ReadyEventNode *ren = readyEventNodeList[eventIndex]; - unsigned i; - if (ren->eventStatus==ID_READY_EVENT_FORCE_ALL_SET) - return true; - if (ren->eventStatus!=ID_READY_EVENT_ALL_SET) - return false; - for (i=0; i < ren->systemList.Size(); i++) - if (ren->systemList[i].lastReceivedStatus!=ID_READY_EVENT_ALL_SET) - return false; - return true; -} - -void ReadyEvent::Clear(void) -{ - unsigned i; - for (i=0; i < readyEventNodeList.Size(); i++) - { - MafiaNet::OP_DELETE(readyEventNodeList[i], _FILE_AND_LINE_); - } - readyEventNodeList.Clear(false, _FILE_AND_LINE_); -} - -unsigned ReadyEvent::CreateNewEvent(int eventId, bool isReady) -{ - ReadyEventNode *ren = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - ren->eventId=eventId; - if (isReady==false) - ren->eventStatus=ID_READY_EVENT_UNSET; - else - ren->eventStatus=ID_READY_EVENT_SET; - return readyEventNodeList.Insert(eventId, ren, true, _FILE_AND_LINE_); -} -void ReadyEvent::UpdateReadyStatus(unsigned eventIndex) -{ - ReadyEventNode *ren = readyEventNodeList[eventIndex]; - bool anyUnset; - unsigned i; - if (ren->eventStatus==ID_READY_EVENT_SET) - { - // If you are set, and no other systems are ID_READY_EVENT_UNSET, then change your status to ID_READY_EVENT_ALL_SET - anyUnset=false; - for (i=0; i < ren->systemList.Size(); i++) - { - if (ren->systemList[i].lastReceivedStatus==ID_READY_EVENT_UNSET) - { - anyUnset=true; - break; - } - } - if (anyUnset==false) - { - ren->eventStatus=ID_READY_EVENT_ALL_SET; - } - } - else if (ren->eventStatus==ID_READY_EVENT_ALL_SET) - { - // If you are all set, and any systems are ID_READY_EVENT_UNSET, then change your status to ID_READY_EVENT_SET - anyUnset=false; - for (i=0; i < ren->systemList.Size(); i++) - { - if (ren->systemList[i].lastReceivedStatus==ID_READY_EVENT_UNSET) - { - anyUnset=true; - break; - } - } - if (anyUnset==true) - { - ren->eventStatus=ID_READY_EVENT_SET; - } - } - BroadcastReadyUpdate(eventIndex, false); -} -void ReadyEvent::SendReadyUpdate(unsigned eventIndex, unsigned systemIndex, bool forceIfNotDefault) -{ - ReadyEventNode *ren = readyEventNodeList[eventIndex]; - MafiaNet::BitStream bs; - // I do this rather than write true or false, so users that do not use BitStreams can still read the data - if ((ren->eventStatus!=ren->systemList[systemIndex].lastSentStatus) || - (forceIfNotDefault && ren->eventStatus!=ID_READY_EVENT_UNSET)) - { - bs.Write(ren->eventStatus); - bs.Write(ren->eventId); - SendUnified(&bs, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, channel, ren->systemList[systemIndex].rakNetGuid, false); - - ren->systemList[systemIndex].lastSentStatus=ren->eventStatus; - } - -} -void ReadyEvent::BroadcastReadyUpdate(unsigned eventIndex, bool forceIfNotDefault) -{ - ReadyEventNode *ren = readyEventNodeList[eventIndex]; - unsigned systemIndex; - for (systemIndex=0; systemIndex < ren->systemList.Size(); systemIndex++) - { - SendReadyUpdate(eventIndex, systemIndex, forceIfNotDefault); - } -} -void ReadyEvent::SendReadyStateQuery(unsigned eventId, RakNetGUID guid) -{ - MafiaNet::BitStream bs; - bs.Write((MessageID)ID_READY_EVENT_QUERY); - bs.Write(eventId); - SendUnified(&bs, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, channel, guid, false); -} -void ReadyEvent::RemoveFromAllLists(RakNetGUID guid) -{ - unsigned eventIndex; - for (eventIndex=0; eventIndex < readyEventNodeList.Size(); eventIndex++) - { - bool isCompleted = IsEventCompletedByIndex(eventIndex); - bool systemExists; - unsigned systemIndex; - - systemIndex = readyEventNodeList[eventIndex]->systemList.GetIndexFromKey(guid, &systemExists); - if (systemExists) - readyEventNodeList[eventIndex]->systemList.RemoveAtIndex(systemIndex); - - UpdateReadyStatus(eventIndex); - - if (isCompleted==false && IsEventCompletedByIndex(eventIndex)) - PushCompletionPacket(readyEventNodeList[eventIndex]->eventId); - } -} -void ReadyEvent::PushCompletionPacket(unsigned eventId) -{ - (void) eventId; - // Not necessary - /* - // Pass a packet to the user that we are now completed, as setting ourselves to signaled was the last thing being waited on - Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(int)); - MafiaNet::BitStream bs(p->data, sizeof(MessageID)+sizeof(int), false); - bs.SetWriteOffset(0); - bs.Write((MessageID)ID_READY_EVENT_ALL_SET); - bs.Write(eventId); - rakPeerInterface->PushBackPacket(p, false); - */ -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/RelayPlugin.cpp b/vendors/mafianet/Source/src/RelayPlugin.cpp deleted file mode 100644 index 82088248d..000000000 --- a/vendors/mafianet/Source/src/RelayPlugin.cpp +++ /dev/null @@ -1,437 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_RelayPlugin==1 - -#include "mafianet/RelayPlugin.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/peerinterface.h" -#include "mafianet/BitStream.h" - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(RelayPlugin,RelayPlugin); - -RelayPlugin::RelayPlugin() -{ - acceptAddParticipantRequests=false; -} - -RelayPlugin::~RelayPlugin() -{ - DataStructures::List itemList; - DataStructures::List keyList; - strToGuidHash.GetAsList(itemList, keyList, _FILE_AND_LINE_); - guidToStrHash.Clear(_FILE_AND_LINE_); - for (unsigned int i=0; i < itemList.Size(); i++) - MafiaNet::OP_DELETE(itemList[i], _FILE_AND_LINE_); - for (unsigned int i=0; i < chatRooms.Size(); i++) - MafiaNet::OP_DELETE(chatRooms[i], _FILE_AND_LINE_); -} - -RelayPluginEnums RelayPlugin::AddParticipantOnServer(const RakString &key, const RakNetGUID &guid) -{ - ConnectionState cs = rakPeerInterface->GetConnectionState(guid); - if (cs!=IS_CONNECTED) - return RPE_ADD_CLIENT_TARGET_NOT_CONNECTED; - - if (strToGuidHash.HasData(key)==true) - return RPE_ADD_CLIENT_NAME_ALREADY_IN_USE; // Name already in use - - // If GUID is already in use, remove existing - StrAndGuidAndRoom *strAndGuidExisting; - if (guidToStrHash.Pop(strAndGuidExisting, guid, _FILE_AND_LINE_)) - { - strToGuidHash.Remove(strAndGuidExisting->str, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(strAndGuidExisting, _FILE_AND_LINE_); - } - - StrAndGuidAndRoom *strAndGuid = MafiaNet::OP_NEW(_FILE_AND_LINE_); - strAndGuid->guid=guid; - strAndGuid->str=key; - - strToGuidHash.Push(key, strAndGuid, _FILE_AND_LINE_); - guidToStrHash.Push(guid, strAndGuid, _FILE_AND_LINE_); - - return RPE_ADD_CLIENT_SUCCESS; -} -void RelayPlugin::RemoveParticipantOnServer(const RakNetGUID &guid) -{ - StrAndGuidAndRoom *strAndGuid; - if (guidToStrHash.Pop(strAndGuid, guid, _FILE_AND_LINE_)) - { - LeaveGroup(&strAndGuid); - strToGuidHash.Remove(strAndGuid->str, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(strAndGuid, _FILE_AND_LINE_); - } -} - -void RelayPlugin::SetAcceptAddParticipantRequests(bool accept) -{ - acceptAddParticipantRequests=accept; -} -void RelayPlugin::AddParticipantRequestFromClient(const RakString &key, const RakNetGUID &relayPluginServerGuid) -{ - BitStream bsOut; - bsOut.WriteCasted(ID_RELAY_PLUGIN); - bsOut.WriteCasted(RPE_ADD_CLIENT_REQUEST_FROM_CLIENT); - bsOut.WriteCompressed(key); - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, relayPluginServerGuid, false); -} -void RelayPlugin::RemoveParticipantRequestFromClient(const RakNetGUID &relayPluginServerGuid) -{ - BitStream bsOut; - bsOut.WriteCasted(ID_RELAY_PLUGIN); - bsOut.WriteCasted(RPE_REMOVE_CLIENT_REQUEST_FROM_CLIENT); - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, relayPluginServerGuid, false); -} -// Send a message to a server running RelayPlugin, to forward a message to the system identified by \a key -void RelayPlugin::SendToParticipant(const RakNetGUID &relayPluginServerGuid, const RakString &key, BitStream *bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel) -{ - BitStream bsOut; - bsOut.WriteCasted(ID_RELAY_PLUGIN); - bsOut.WriteCasted(RPE_MESSAGE_TO_SERVER_FROM_CLIENT); - bsOut.WriteCasted(priority); - bsOut.WriteCasted(reliability); - bsOut.Write(orderingChannel); - bsOut.WriteCompressed(key); - bsOut.Write(bitStream); - SendUnified(&bsOut, priority, reliability, orderingChannel, relayPluginServerGuid, false); -} -void RelayPlugin::SendGroupMessage(const RakNetGUID &relayPluginServerGuid, BitStream *bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel) -{ - BitStream bsOut; - bsOut.WriteCasted(ID_RELAY_PLUGIN); - bsOut.WriteCasted(RPE_GROUP_MESSAGE_FROM_CLIENT); - bsOut.WriteCasted(priority); - bsOut.WriteCasted(reliability); - bsOut.Write(orderingChannel); - bsOut.Write(bitStream); - SendUnified(&bsOut, priority, reliability, orderingChannel, relayPluginServerGuid, false); -} -void RelayPlugin::LeaveGroup(const RakNetGUID &relayPluginServerGuid) -{ - BitStream bsOut; - bsOut.WriteCasted(ID_RELAY_PLUGIN); - bsOut.WriteCasted(RPE_LEAVE_GROUP_REQUEST_FROM_CLIENT); - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, relayPluginServerGuid, false); -} -void RelayPlugin::GetGroupList(const RakNetGUID &relayPluginServerGuid) -{ - BitStream bsOut; - bsOut.WriteCasted(ID_RELAY_PLUGIN); - bsOut.WriteCasted(RPE_GET_GROUP_LIST_REQUEST_FROM_CLIENT); - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, relayPluginServerGuid, false); -} -PluginReceiveResult RelayPlugin::OnReceive(Packet *packet) -{ - if (packet->data[0]==ID_RELAY_PLUGIN) - { - switch (packet->data[1]) - { - case RPE_MESSAGE_TO_SERVER_FROM_CLIENT: - { - BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - MafiaNet::Priority priority; - MafiaNet::Reliability reliability; - char orderingChannel; - unsigned char cIn; - bsIn.Read(cIn); - priority = (MafiaNet::Priority) cIn; - bsIn.Read(cIn); - reliability = (MafiaNet::Reliability) cIn; - bsIn.Read(orderingChannel); - RakString key; - bsIn.ReadCompressed(key); - BitStream bsData; - bsIn.Read(&bsData); - StrAndGuidAndRoom **strAndGuid = strToGuidHash.Peek(key); - StrAndGuidAndRoom **strAndGuidSender = guidToStrHash.Peek(packet->guid); - if (strAndGuid && strAndGuidSender) - { - BitStream bsOut; - bsOut.WriteCasted(ID_RELAY_PLUGIN); - bsOut.WriteCasted(RPE_MESSAGE_TO_CLIENT_FROM_SERVER); - bsOut.WriteCompressed( (*strAndGuidSender)->str ); - bsOut.AlignWriteToByteBoundary(); - bsOut.Write(bsData); - SendUnified(&bsOut, priority, reliability, orderingChannel, (*strAndGuid)->guid, false); - } - - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - - case RPE_ADD_CLIENT_REQUEST_FROM_CLIENT: - { - BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - RakString key; - bsIn.ReadCompressed(key); - BitStream bsOut; - bsOut.WriteCasted(ID_RELAY_PLUGIN); - if (acceptAddParticipantRequests) - bsOut.WriteCasted(AddParticipantOnServer(key, packet->guid)); - else - bsOut.WriteCasted(RPE_ADD_CLIENT_NOT_ALLOWED); - bsOut.WriteCompressed(key); - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, packet->systemAddress, false); - - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - case RPE_REMOVE_CLIENT_REQUEST_FROM_CLIENT: - { - RemoveParticipantOnServer(packet->guid); - } - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case RPE_GROUP_MESSAGE_FROM_CLIENT: - { - OnGroupMessageFromClient(packet); - } - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case RPE_JOIN_GROUP_REQUEST_FROM_CLIENT: - { - OnJoinGroupRequestFromClient(packet); - } - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case RPE_LEAVE_GROUP_REQUEST_FROM_CLIENT: - { - OnLeaveGroupRequestFromClient(packet); - } - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case RPE_GET_GROUP_LIST_REQUEST_FROM_CLIENT: - { - SendChatRoomsList(packet->guid); - } - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - - } - - return RR_CONTINUE_PROCESSING; -} - -void RelayPlugin::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) lostConnectionReason; - (void) systemAddress; - - RemoveParticipantOnServer(rakNetGUID); -} - -RelayPlugin::RP_Group* RelayPlugin::JoinGroup(RP_Group* room, StrAndGuidAndRoom **strAndGuidSender) -{ - if (strAndGuidSender==0) - return 0; - - NotifyUsersInRoom(room, RPE_USER_ENTERED_ROOM, (*strAndGuidSender)->str); - StrAndGuid sag; - sag.guid=(*strAndGuidSender)->guid; - sag.str=(*strAndGuidSender)->str; - - room->usersInRoom.Push(sag, _FILE_AND_LINE_); - (*strAndGuidSender)->currentRoom=room->roomName; - - return room; -} -void RelayPlugin::JoinGroupRequest(const RakNetGUID &relayPluginServerGuid, RakString groupName) -{ - BitStream bsOut; - bsOut.WriteCasted(ID_RELAY_PLUGIN); - bsOut.WriteCasted(RPE_JOIN_GROUP_REQUEST_FROM_CLIENT); - bsOut.WriteCompressed(groupName); - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, relayPluginServerGuid, false); -} -RelayPlugin::RP_Group* RelayPlugin::JoinGroup(RakNetGUID userGuid, RakString roomName) -{ - StrAndGuidAndRoom **strAndGuidSender = guidToStrHash.Peek(userGuid); - if (strAndGuidSender) - { - if (roomName.IsEmpty()) - return 0; - - if ((*strAndGuidSender)->currentRoom==roomName) - return 0; - - if ((*strAndGuidSender)->currentRoom.IsEmpty()==false) - LeaveGroup(strAndGuidSender); - - RakString userName = (*strAndGuidSender)->str; - - for (unsigned int i=0; i < chatRooms.Size(); i++) - { - if (chatRooms[i]->roomName==roomName) - { - // Join existing room - return JoinGroup(chatRooms[i],strAndGuidSender); - } - } - - // Create new room - RP_Group *room = MafiaNet::OP_NEW(_FILE_AND_LINE_); - room->roomName=roomName; - chatRooms.Push(room, _FILE_AND_LINE_); - return JoinGroup(room,strAndGuidSender); - } - - return 0; -} -void RelayPlugin::LeaveGroup(StrAndGuidAndRoom **strAndGuidSender) -{ - if (strAndGuidSender==0) - return; - - RakString userName = (*strAndGuidSender)->str; - for (unsigned int i=0; i < chatRooms.Size(); i++) - { - if (chatRooms[i]->roomName==(*strAndGuidSender)->currentRoom) - { - (*strAndGuidSender)->currentRoom.Clear(); - - RP_Group *room = chatRooms[i]; - for (unsigned int j=0; j < room->usersInRoom.Size(); j++) - { - if (room->usersInRoom[j].guid==(*strAndGuidSender)->guid) - { - room->usersInRoom.RemoveAtIndexFast(j); - - if (room->usersInRoom.Size()==0) - { - MafiaNet::OP_DELETE(room, _FILE_AND_LINE_); - chatRooms.RemoveAtIndexFast(i); - return; - } - } - } - - NotifyUsersInRoom(room, RPE_USER_LEFT_ROOM, userName); - - return; - - } - } -} -void RelayPlugin::NotifyUsersInRoom(RP_Group *room, int msg, const RakString& message) -{ - for (unsigned int i=0; i < room->usersInRoom.Size(); i++) - { - BitStream bsOut; - bsOut.WriteCasted(ID_RELAY_PLUGIN); - bsOut.WriteCasted(msg); - bsOut.WriteCompressed(message); - - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, room->usersInRoom[i].guid, false); - } -} -void RelayPlugin::SendMessageToRoom(StrAndGuidAndRoom **strAndGuidSender, BitStream* message) -{ - if ((*strAndGuidSender)->currentRoom.IsEmpty()) - return; - - for (unsigned int i=0; i < chatRooms.Size(); i++) - { - if (chatRooms[i]->roomName==(*strAndGuidSender)->currentRoom) - { - BitStream bsOut; - bsOut.WriteCasted(ID_RELAY_PLUGIN); - bsOut.WriteCasted(RPE_GROUP_MSG_FROM_SERVER); - message->ResetReadPointer(); - bsOut.WriteCompressed((*strAndGuidSender)->str); - bsOut.AlignWriteToByteBoundary(); - bsOut.Write(message); - - RP_Group *room = chatRooms[i]; - for (unsigned int j=0; j < room->usersInRoom.Size(); j++) - { - if (room->usersInRoom[j].guid!=(*strAndGuidSender)->guid) - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, room->usersInRoom[j].guid, false); - } - - break; - } - } -} -void RelayPlugin::SendChatRoomsList(RakNetGUID target) -{ - BitStream bsOut; - bsOut.WriteCasted(ID_RELAY_PLUGIN); - bsOut.WriteCasted(RPE_GET_GROUP_LIST_REPLY_FROM_SERVER); - bsOut.WriteCasted(chatRooms.Size()); - for (unsigned int i=0; i < chatRooms.Size(); i++) - { - bsOut.WriteCompressed(chatRooms[i]->roomName); - bsOut.WriteCasted(chatRooms[i]->usersInRoom.Size()); - } - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, target, false); -} -void RelayPlugin::OnGroupMessageFromClient(Packet *packet) -{ - BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - - MafiaNet::Priority priority; - MafiaNet::Reliability reliability; - char orderingChannel; - unsigned char cIn; - bsIn.Read(cIn); - priority = (MafiaNet::Priority) cIn; - bsIn.Read(cIn); - reliability = (MafiaNet::Reliability) cIn; - bsIn.Read(orderingChannel); - BitStream bsData; - bsIn.Read(&bsData); - - StrAndGuidAndRoom **strAndGuidSender = guidToStrHash.Peek(packet->guid); - if (strAndGuidSender) - { - SendMessageToRoom(strAndGuidSender,&bsData); - } -} -void RelayPlugin::OnJoinGroupRequestFromClient(Packet *packet) -{ - BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - RakString groupName; - bsIn.ReadCompressed(groupName); - RelayPlugin::RP_Group *groupJoined = JoinGroup(packet->guid, groupName); - - BitStream bsOut; - bsOut.WriteCasted(ID_RELAY_PLUGIN); - if (groupJoined) - { - bsOut.WriteCasted(RPE_JOIN_GROUP_SUCCESS); - bsOut.WriteCasted(groupJoined->usersInRoom.Size()); - for (unsigned int i=0; i < groupJoined->usersInRoom.Size(); i++) - { - bsOut.WriteCompressed(groupJoined->usersInRoom[i].str); - } - } - else - { - bsOut.WriteCasted(RPE_JOIN_GROUP_FAILURE); - } - - SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, packet->guid, false); -} -void RelayPlugin::OnLeaveGroupRequestFromClient(Packet *packet) -{ - BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - StrAndGuidAndRoom **strAndGuidSender = guidToStrHash.Peek(packet->guid); - if (strAndGuidSender) - LeaveGroup(strAndGuidSender); -} -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/ReliabilityLayer.cpp b/vendors/mafianet/Source/src/ReliabilityLayer.cpp deleted file mode 100644 index 6f718f7ed..000000000 --- a/vendors/mafianet/Source/src/ReliabilityLayer.cpp +++ /dev/null @@ -1,4031 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// - - - -#include "mafianet/ReliabilityLayer.h" -#include "mafianet/GetTime.h" -#include "mafianet/SocketLayer.h" -#include "mafianet/PluginInterface2.h" -#include "mafianet/assert.h" -#include "mafianet/Rand.h" -#include "mafianet/MessageIdentifiers.h" -#ifdef USE_THREADED_SEND -#include "mafianet/SendToThread.h" -#endif -#include -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace MafiaNet; - -// Can't figure out which library has this function on the PS3 -double Ceil(double d) {if (((double)((int)d))==d) return d; return (int) (d+1.0);} - -// #if defined(new) -// #pragma push_macro("new") -// #undef new -// #define RELIABILITY_LAYER_NEW_UNDEF_ALLOCATING_QUEUE -// #endif - - -//#define _DEBUG_LOGGER - -#if CC_TIME_TYPE_BYTES==4 -static const CCTimeType MAX_TIME_BETWEEN_PACKETS= 350; // 350 milliseconds -static const CCTimeType HISTOGRAM_RESTART_CYCLE=10000; // Every 10 seconds reset the histogram -#else -static const CCTimeType MAX_TIME_BETWEEN_PACKETS= 350000; // 350 milliseconds -//static const CCTimeType HISTOGRAM_RESTART_CYCLE=10000000; // Every 10 seconds reset the histogram -#endif -static const int DEFAULT_HAS_RECEIVED_PACKET_QUEUE_SIZE=512; -static const CCTimeType STARTING_TIME_BETWEEN_PACKETS=MAX_TIME_BETWEEN_PACKETS; -//static const long double TIME_BETWEEN_PACKETS_INCREASE_MULTIPLIER_DEFAULT=.02; -//static const long double TIME_BETWEEN_PACKETS_DECREASE_MULTIPLIER_DEFAULT=1.0 / 9.0; - -typedef uint32_t BitstreamLengthEncoding; - -//#define PRINT_TO_FILE_RELIABLE_ORDERED_TEST -#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST -static unsigned int packetNumber=0; -static FILE *fp=0; -#endif - -//#define FLIP_SEND_ORDER_TEST -//#define LOG_TRIVIAL_NOTIFICATIONS - -BPSTracker::TimeAndValue2::TimeAndValue2() {} -BPSTracker::TimeAndValue2::~TimeAndValue2() {} -BPSTracker::TimeAndValue2::TimeAndValue2(MafiaNet::TimeUS t, uint64_t v1) : value1(v1), time(t) {} -//BPSTracker::TimeAndValue2::TimeAndValue2(MafiaNet::TimeUS t, uint64_t v1, uint64_t v2) : time(t), value1(v1), value2(v2) {} -BPSTracker::BPSTracker() {Reset(_FILE_AND_LINE_);} -BPSTracker::~BPSTracker() {} -//void BPSTracker::Reset(const char *file, unsigned int line) {total1=total2=lastSec1=lastSec2=0; dataQueue.Clear(file,line);} -void BPSTracker::Reset(const char *file, unsigned int line) {total1=lastSec1=0; dataQueue.Clear(file,line);} -//void BPSTracker::Push2(RakNetTimeUS time, uint64_t value1, uint64_t value2) {dataQueue.Push(TimeAndValue2(time,value1,value2),_FILE_AND_LINE_); total1+=value1; lastSec1+=value1; total2+=value2; lastSec2+=value2;} -//uint64_t BPSTracker::GetBPS2(RakNetTimeUS time) {ClearExpired2(time); return lastSec2;} -//void BPSTracker::GetBPS1And2(RakNetTimeUS time, uint64_t &out1, uint64_t &out2) {ClearExpired2(time); out1=lastSec1; out2=lastSec2;} -uint64_t BPSTracker::GetTotal1(void) const {return total1;} -//uint64_t BPSTracker::GetTotal2(void) const {return total2;} - -// void BPSTracker::ClearExpired2(MafiaNet::TimeUS time) { -// MafiaNet::TimeUS threshold=time; -// if (threshold < 1000000) -// return; -// threshold-=1000000; -// while (dataQueue.IsEmpty()==false && dataQueue.Peek().time < threshold) -// { -// lastSec1-=dataQueue.Peek().value1; -// lastSec2-=dataQueue.Peek().value2; -// dataQueue.Pop(); -// } -// } -void BPSTracker::ClearExpired1(MafiaNet::TimeUS time) -{ - while (dataQueue.IsEmpty()==false && -#if CC_TIME_TYPE_BYTES==8 - dataQueue.Peek().time+1000000 < time -#else - dataQueue.Peek().time+1000 < time -#endif - ) - { - lastSec1-=dataQueue.Peek().value1; - dataQueue.Pop(); - } -} - -struct DatagramHeaderFormat -{ -#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 - CCTimeType sourceSystemTime; -#endif - DatagramSequenceNumberType datagramNumber; - - // Use floats to save bandwidth - // float B; // Link capacity - float AS; // Data arrival rate - bool isACK; - bool isNAK; - bool isPacketPair; - bool hasBAndAS; - bool isContinuousSend; - bool needsBAndAs; - bool isValid; // To differentiate between what I serialized, and offline data - - static BitSize_t GetDataHeaderBitLength() - { - return BYTES_TO_BITS(GetDataHeaderByteLength()); - } - - static unsigned int GetDataHeaderByteLength() - { - //return 2 + 3 + sizeof(MafiaNet::TimeMS) + sizeof(float)*2; - return 2 + 3 + -#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 - sizeof(RakNetTimeMS) + -#endif - sizeof(float)*1; - } - - void Serialize(MafiaNet::BitStream *b) - { - // Not endian safe - // RakAssert(GetDataHeaderByteLength()==sizeof(DatagramHeaderFormat)); - // b->WriteAlignedBytes((const unsigned char*) this, sizeof(DatagramHeaderFormat)); - // return; - - b->Write(true); // IsValid - if (isACK) { - b->Write(true); // IsACK - b->Write(hasBAndAS); - b->AlignWriteToByteBoundary(); -#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS == 1 - MafiaNet::TimeMS timeMSLow = (MafiaNet::TimeMS)sourceSystemTime&0xFFFFFFFF; - b->Write(timeMSLow); -#endif - if (hasBAndAS) { - // b->Write(B); - b->Write(AS); - } - } - else if (isNAK) { - b->Write(false); // isACK - b->Write(true); // isNAK - } - else { - b->Write(false); // isACK - b->Write(false); // isNAK - b->Write(isPacketPair); - b->Write(isContinuousSend); - b->Write(needsBAndAs); - b->AlignWriteToByteBoundary(); -#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS == 1 - MafiaNet::TimeMS timeMSLow = (MafiaNet::TimeMS)sourceSystemTime&0xFFFFFFFF; - b->Write(timeMSLow); -#endif - b->Write(datagramNumber); - } - } - - void Deserialize(MafiaNet::BitStream *b) - { - // Not endian safe - // b->ReadAlignedBytes((unsigned char*) this, sizeof(DatagramHeaderFormat)); - // return; - - b->Read(isValid); - b->Read(isACK); - if (isACK) { - isNAK = false; - isPacketPair = false; - b->Read(hasBAndAS); - b->AlignReadToByteBoundary(); -#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS == 1 - MafiaNet::TimeMS timeMS; - b->Read(timeMS); - sourceSystemTime = (CCTimeType)timeMS; -#endif - if (hasBAndAS) { - // b->Read(B); - b->Read(AS); - } - } - else { - b->Read(isNAK); - if (isNAK) { - isPacketPair = false; - } - else { - b->Read(isPacketPair); - b->Read(isContinuousSend); - b->Read(needsBAndAs); - b->AlignReadToByteBoundary(); -#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS == 1 - MafiaNet::TimeMS timeMS; b->Read(timeMS); sourceSystemTime=(CCTimeType) timeMS; -#endif - b->Read(datagramNumber); - } - } - } -}; - -#ifdef _WIN32 -//#define _DEBUG_LOGGER -#ifdef _DEBUG_LOGGER -#include "mafianet/WindowsIncludes.h" -#endif -#endif - -//#define DEBUG_SPLIT_PACKET_PROBLEMS -#if defined (DEBUG_SPLIT_PACKET_PROBLEMS) -static int waitFlag = -1; -#endif - -using namespace MafiaNet; - -SplitPacketSort::SplitPacketSort() : - m_data(nullptr), - m_allocationSize(0), - m_addedPacketsCount(0) -{ -} - -SplitPacketSort::~SplitPacketSort() -{ - if (m_allocationSize) { - OP_DELETE_ARRAY(m_data, _FILE_AND_LINE_); - } -} - -void SplitPacketSort::Preallocate(InternalPacket *internalPacket, const char *file, unsigned int line) -{ - RakAssert(m_data == nullptr); - m_allocationSize = internalPacket->splitPacketCount; - m_data = OP_NEW_ARRAY((int)m_allocationSize, file, line); - m_packetId = internalPacket->splitPacketId; - - for (size_t i = 0; i < m_allocationSize; ++i) { - m_data[i] = nullptr; - } -} - -bool SplitPacketSort::AllPacketsAdded() const -{ - return GetAllocSize() == GetNumAddedPackets(); -} - -size_t SplitPacketSort::GetAllocSize() const -{ - return m_allocationSize; -} - -unsigned int SplitPacketSort::GetNumAddedPackets() const -{ - return m_addedPacketsCount; -} - -SplitPacketIdType SplitPacketSort::GetPacketId() const -{ - RakAssert(m_data != nullptr); - return m_packetId; -} - -InternalPacket*& SplitPacketSort::operator[](size_t index) -{ - RakAssert(m_data != nullptr); - RakAssert(index < m_allocationSize); - return m_data[index]; -} - -bool SplitPacketSort::Add(InternalPacket *internalPacket) -{ - RakAssert(m_data != nullptr); - RakAssert(internalPacket->splitPacketIndex < m_allocationSize); - RakAssert(m_packetId == internalPacket->splitPacketId); - RakAssert(m_data[internalPacket->splitPacketIndex] == nullptr); - - if (m_data[internalPacket->splitPacketIndex] == nullptr) { - m_data[internalPacket->splitPacketIndex] = internalPacket; - ++m_addedPacketsCount; - return true; - } - return false; -} - -int MafiaNet::SplitPacketChannelComp( SplitPacketIdType const &key, SplitPacketChannel* const &data ) -{ -#if PREALLOCATE_LARGE_MESSAGES==1 - if (key < data->returnedPacket->splitPacketId) - return -1; - if (key == data->returnedPacket->splitPacketId) - return 0; -#else - if (key < data->splitPacketList.GetPacketId()) - return -1; - if (key == data->splitPacketList.GetPacketId()) - return 0; -#endif - return 1; -} - -// DEFINE_MULTILIST_PTR_TO_MEMBER_COMPARISONS( InternalPacket, SplitPacketIndexType, splitPacketIndex ) -/* -bool operator<( const DataStructures::MLKeyRef &inputKey, const InternalPacket *cls ) -{ - return inputKey.Get() < cls->splitPacketIndex; -} -bool operator>( const DataStructures::MLKeyRef &inputKey, const InternalPacket *cls ) -{ - return inputKey.Get() > cls->splitPacketIndex; -} -bool operator==( const DataStructures::MLKeyRef &inputKey, const InternalPacket *cls ) -{ - return inputKey.Get() == cls->splitPacketIndex; -} -/// Semi-hack: This is necessary to call Sort() -bool operator<( const DataStructures::MLKeyRef &inputKey, const InternalPacket *cls ) -{ - return inputKey.Get()->splitPacketIndex < cls->splitPacketIndex; -} -bool operator>( const DataStructures::MLKeyRef &inputKey, const InternalPacket *cls ) -{ - return inputKey.Get()->splitPacketIndex > cls->splitPacketIndex; -} -bool operator==( const DataStructures::MLKeyRef &inputKey, const InternalPacket *cls ) -{ - return inputKey.Get()->splitPacketIndex == cls->splitPacketIndex; -} -*/ - -int SplitPacketIndexComp( SplitPacketIndexType const &key, InternalPacket* const &data ) -{ -if (key < data->splitPacketIndex) -return -1; -if (key == data->splitPacketIndex) -return 0; -return 1; -} - -//------------------------------------------------------------------------------------------------------- -// Constructor -//------------------------------------------------------------------------------------------------------- -// Add 21 to the default MTU so if we encrypt it can hold potentially 21 more bytes of extra data + padding. -ReliabilityLayer::ReliabilityLayer() -{ - -#ifdef _DEBUG - // Wait longer to disconnect in debug so I don't get disconnected while tracing - timeoutTime = 30000; -#else - timeoutTime = 10000; -#endif - -#ifdef _DEBUG - minExtraPing = extraPingVariance = 0; - packetloss = (double)minExtraPing; -#endif - - -#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST - if (fp==0 && 0) - { - fopen_s(&fp, "reliableorderedoutput.txt", "wt"); - } -#endif - - InitializeVariables(); -//int i = sizeof(InternalPacket); - datagramHistoryMessagePool.SetPageSize(sizeof(MessageNumberNode)*128); - internalPacketPool.SetPageSize(sizeof(InternalPacket)*INTERNAL_PACKET_PAGE_SIZE); - refCountedDataPool.SetPageSize(sizeof(InternalPacketRefCountedData)*32); -} - -//------------------------------------------------------------------------------------------------------- -// Destructor -//------------------------------------------------------------------------------------------------------- -ReliabilityLayer::~ReliabilityLayer() -{ - FreeMemory( true ); // Free all memory immediately -} -//------------------------------------------------------------------------------------------------------- -// Resets the layer for reuse -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::Reset(bool resetVariables, int mtuSize, bool _useSecurity) -{ - FreeMemory(true); // true because making a memory reset pending in the update cycle causes resets after reconnects. Instead, just call Reset from a single thread - if (resetVariables) { - InitializeVariables(); - -#if LIBCAT_SECURITY == 1 - useSecurity = _useSecurity; - - if (_useSecurity) { - mtuSize -= cat::AuthenticatedEncryption::OVERHEAD_BYTES; - } -#else - (void) _useSecurity; -#endif // LIBCAT_SECURITY - congestionManager.Init(MafiaNet::GetTimeUS(), mtuSize - UDP_HEADER_SIZE); - } -} - -//------------------------------------------------------------------------------------------------------- -// Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable packet -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::SetTimeoutTime(MafiaNet::TimeMS time) -{ - timeoutTime = time; -} - -//------------------------------------------------------------------------------------------------------- -// Returns the value passed to SetTimeoutTime. or the default if it was never called -//------------------------------------------------------------------------------------------------------- -MafiaNet::TimeMS ReliabilityLayer::GetTimeoutTime() -{ - return timeoutTime; -} - -//------------------------------------------------------------------------------------------------------- -// Initialize the variables -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::InitializeVariables() -{ - memset( orderedWriteIndex, 0, NUMBER_OF_ORDERED_STREAMS * sizeof(OrderingIndexType)); - memset( sequencedWriteIndex, 0, NUMBER_OF_ORDERED_STREAMS * sizeof(OrderingIndexType) ); - memset( orderedReadIndex, 0, NUMBER_OF_ORDERED_STREAMS * sizeof(OrderingIndexType) ); - memset( highestSequencedReadIndex, 0, NUMBER_OF_ORDERED_STREAMS * sizeof(OrderingIndexType) ); - memset( &statistics, 0, sizeof( statistics ) ); - memset( &heapIndexOffsets, 0, sizeof( heapIndexOffsets ) ); - - statistics.connectionStartTime = MafiaNet::GetTimeUS(); - splitPacketId = 0; - elapsedTimeSinceLastUpdate=0; - throughputCapCountdown=0; - sendReliableMessageNumberIndex = 0; - internalOrderIndex=0; - timeToNextUnreliableCull=0; - unreliableLinkedListHead=0; - lastUpdateTime= MafiaNet::GetTimeUS(); - bandwidthExceededStatistic=false; - remoteSystemTime=0; - unreliableTimeout=0; - lastBpsClear=0; - - // Disable packet pairs - countdownToNextPacketPair=15; - - nextAllowedThroughputSample=0; - deadConnection = cheater = false; - timeOfLastContinualSend=0; - - // timeResendQueueNonEmpty = 0; - timeLastDatagramArrived= MafiaNet::GetTimeMS(); - // packetlossThisSample=false; - // backoffThisSample=0; - // packetlossThisSampleResendCount=0; - // lastPacketlossTime=0; - statistics.messagesInResendBuffer=0; - statistics.bytesInResendBuffer=0; - - receivedPacketsBaseIndex=0; - resetReceivedPackets=true; - receivePacketCount=0; - - // SetPing( 1000 ); - - timeBetweenPackets=STARTING_TIME_BETWEEN_PACKETS; - - ackPingIndex=0; - ackPingSum=(CCTimeType)0; - - nextSendTime=lastUpdateTime; - //nextLowestPingReset=(CCTimeType)0; - // continuousSend=false; - - // histogramStart=(CCTimeType)0; - // histogramBitsSent=0; - unacknowledgedBytes=0; - resendLinkedListHead=0; - totalUserDataBytesAcked=0; - - datagramHistoryPopCount=0; - - InitHeapWeights(); - for (int i=0; i < MafiaNet::NUMBER_OF_PRIORITIES; i++) - { - statistics.messageInSendBuffer[i]=0; - statistics.bytesInSendBuffer[i]=0.0; - } - - for (int i=0; i < RNS_PER_SECOND_METRICS_COUNT; i++) - { - bpsMetrics[i].Reset(_FILE_AND_LINE_); - } -} - -//------------------------------------------------------------------------------------------------------- -// Frees all allocated memory -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::FreeMemory( bool freeAllImmediately ) -{ - (void) freeAllImmediately; - FreeThreadSafeMemory(); -} - -void ReliabilityLayer::FreeThreadSafeMemory( void ) -{ - unsigned i,j; - InternalPacket *internalPacket; - - ClearPacketsAndDatagrams(); - - for (i=0; i < splitPacketChannelList.Size(); i++) - { - for (j=0; j < splitPacketChannelList[i]->splitPacketList.GetAllocSize(); j++) - { - internalPacket = splitPacketChannelList[i]->splitPacketList[j]; - if (internalPacket != nullptr) { - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_); - ReleaseToInternalPacketPool(internalPacket); - } - } -#if PREALLOCATE_LARGE_MESSAGES==1 - if (splitPacketChannelList[i]->returnedPacket) - { - FreeInternalPacketData(splitPacketChannelList[i]->returnedPacket, __FILE__, __LINE__ ); - ReleaseToInternalPacketPool( splitPacketChannelList[i]->returnedPacket ); - } -#endif - MafiaNet::OP_DELETE(splitPacketChannelList[i], __FILE__, __LINE__); - } - splitPacketChannelList.Clear(false, _FILE_AND_LINE_); - - while ( outputQueue.Size() > 0 ) - { - internalPacket = outputQueue.Pop(); - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); - ReleaseToInternalPacketPool( internalPacket ); - } - - outputQueue.ClearAndForceAllocation( 32, _FILE_AND_LINE_ ); - - /* - for ( i = 0; i < orderingList.Size(); i++ ) - { - if ( orderingList[ i ] ) - { - DataStructures::LinkedList* theList = orderingList[ i ]; - - if ( theList ) - { - while ( theList->Size() ) - { - internalPacket = orderingList[ i ]->Pop(); - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); - ReleaseToInternalPacketPool( internalPacket ); - } - - MafiaNet::OP_DELETE(theList, _FILE_AND_LINE_); - } - } - } - - orderingList.Clear(false, _FILE_AND_LINE_); - */ - - for (i=0; i < NUMBER_OF_ORDERED_STREAMS; i++) - { - for (j=0; j < orderingHeaps[i].Size(); j++) - { - FreeInternalPacketData(orderingHeaps[i][j], _FILE_AND_LINE_ ); - ReleaseToInternalPacketPool( orderingHeaps[i][j] ); - } - orderingHeaps[i].Clear(true, _FILE_AND_LINE_); - } - - //resendList.ForEachData(DeleteInternalPacket); - // resendTree.Clear(_FILE_AND_LINE_); - memset(resendBuffer, 0, sizeof(resendBuffer)); - statistics.messagesInResendBuffer=0; - statistics.bytesInResendBuffer=0; - - if (resendLinkedListHead) - { - InternalPacket *prev; - InternalPacket *iter = resendLinkedListHead; - - for(;;) - { - if (iter->data) - FreeInternalPacketData(iter, _FILE_AND_LINE_ ); - prev=iter; - iter=iter->resendNext; - if (iter==resendLinkedListHead) - { - ReleaseToInternalPacketPool(prev); - break; - } - ReleaseToInternalPacketPool(prev); - } - resendLinkedListHead=0; - } - unacknowledgedBytes=0; - - // acknowlegements.Clear(_FILE_AND_LINE_); - - for ( j=0 ; j < outgoingPacketBuffer.Size(); j++ ) - { - if ( outgoingPacketBuffer[ j ]->data) - FreeInternalPacketData( outgoingPacketBuffer[ j ], _FILE_AND_LINE_ ); - ReleaseToInternalPacketPool( outgoingPacketBuffer[ j ] ); - } - - outgoingPacketBuffer.Clear(true, _FILE_AND_LINE_); - -#ifdef _DEBUG - for (i = 0; i < delayList.Size(); i++ ) - MafiaNet::OP_DELETE(delayList[ i ], __FILE__, __LINE__); - delayList.Clear(__FILE__, __LINE__); -#endif - - unreliableWithAckReceiptHistory.Clear(false, _FILE_AND_LINE_); - - packetsToSendThisUpdate.Clear(false, _FILE_AND_LINE_); - packetsToSendThisUpdate.Preallocate(512, _FILE_AND_LINE_); - packetsToDeallocThisUpdate.Clear(false, _FILE_AND_LINE_); - packetsToDeallocThisUpdate.Preallocate(512, _FILE_AND_LINE_); - packetsToSendThisUpdateDatagramBoundaries.Clear(false, _FILE_AND_LINE_); - packetsToSendThisUpdateDatagramBoundaries.Preallocate(128, _FILE_AND_LINE_); - datagramSizesInBytes.Clear(false, _FILE_AND_LINE_); - datagramSizesInBytes.Preallocate(128, _FILE_AND_LINE_); - - internalPacketPool.Clear(_FILE_AND_LINE_); - - refCountedDataPool.Clear(_FILE_AND_LINE_); - - /* - DataStructures::Page *cur = datagramMessageIDTree.GetListHead(); - while (cur) - { - int treeIndex; - for (treeIndex=0; treeIndex < cur->size; treeIndex++) - ReleaseToDatagramMessageIDPool(cur->data[treeIndex]); - cur=cur->resendNext; - } - datagramMessageIDTree.Clear(_FILE_AND_LINE_); - datagramMessageIDPool.Clear(_FILE_AND_LINE_); - */ - - while (datagramHistory.Size()) - { - RemoveFromDatagramHistory(datagramHistoryPopCount); - datagramHistory.Pop(); - datagramHistoryPopCount++; - } - datagramHistoryMessagePool.Clear(_FILE_AND_LINE_); - datagramHistoryPopCount=0; - - acknowlegements.Clear(); - NAKs.Clear(); - - unreliableLinkedListHead=0; -} - -//------------------------------------------------------------------------------------------------------- -// Packets are read directly from the socket layer and skip the reliability -//layer because unconnected players do not use the reliability layer -// This function takes packet data after a player has been confirmed as -//connected. The game should not use that data directly -// because some data is used internally, such as packet acknowledgment and -//split packets -//------------------------------------------------------------------------------------------------------- -bool ReliabilityLayer::HandleSocketReceiveFromConnectedPlayer( - const char *buffer, unsigned int length, SystemAddress &systemAddress, DataStructures::List &messageHandlerList, int mtuSize, - RakNetSocket2 *s, RakNetRandom *rnr, CCTimeType timeRead, BitStream &updateBitStream) -{ - // unreferenced parameters - (void)mtuSize; - - RakAssert(buffer != nullptr); - -#if CC_TIME_TYPE_BYTES == 4 - timeRead /= 1000; -#endif - - bpsMetrics[(int)ACTUAL_BYTES_RECEIVED].Push1(timeRead, length); - - if (length <= 2 || buffer == nullptr) { // Length of 1 is a connection request resend that we just ignore - for (unsigned int messageHandlerIndex = 0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("length <= 2 || buffer == nullptr", BYTES_TO_BITS(length), systemAddress, true); - return true; - } - - timeLastDatagramArrived = MafiaNet::GetTimeMS(); - - // CCTimeType time; -// bool indexFound; -// int count, size; - DatagramSequenceNumberType holeCount; - unsigned i; - -#if LIBCAT_SECURITY == 1 - if (useSecurity) { - unsigned int received = length; - - if (!auth_enc.Decrypt((cat::u8*)buffer, received)) { - return false; - } - - length = received; - } -#endif - - MafiaNet::BitStream socketData((unsigned char*)buffer, length, false); // Convert the incoming data to a bitstream for easy parsing - // time = MafiaNet::GetTimeUS(); - - // Set to the current time if it is not zero, and we get incoming data - // if (timeResendQueueNonEmpty!=0) - // timeResendQueueNonEmpty=timeRead; - - DatagramHeaderFormat dhf; - dhf.Deserialize(&socketData); - if (!dhf.isValid) { - for (unsigned int messageHandlerIndex = 0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) { - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("!dhf.isValid", BYTES_TO_BITS(length), systemAddress, true); - } - - return true; - } - if (dhf.isACK) { - DatagramSequenceNumberType datagramNumber; - // datagramNumber=dhf.datagramNumber; - -#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS == 1 - MafiaNet::TimeMS timeMSLow = (MafiaNet::TimeMS)timeRead&0xFFFFFFFF; - CCTimeType rtt = timeMSLow-dhf.sourceSystemTime; -#if CC_TIME_TYPE_BYTES == 4 - if (rtt > 10000) -#else - if (rtt > 10000000) -#endif - { - // Sanity check. This could happen due to type overflow, especially since I only send the low 4 bytes to reduce bandwidth - rtt=(CCTimeType) congestionManager.GetRTT(); - } - // RakAssert(rtt < 500000); - // printf("%i ", (MafiaNet::TimeMS)(rtt/1000)); - ackPing = rtt; -#endif - -#ifdef _DEBUG - if (!dhf.hasBAndAS) { - // dhf.B=0; - dhf.AS = 0; - } -#endif - // congestionManager.OnAck(timeRead, rtt, dhf.hasBAndAS, dhf.B, dhf.AS, totalUserDataBytesAcked ); - - incomingAcks.Clear(); - if (!incomingAcks.Deserialize(&socketData)) { - for (unsigned int messageHandlerIndex = 0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) { - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("incomingAcks.Deserialize failed", BYTES_TO_BITS(length), systemAddress, true); - } - - return false; - } - - unsigned int k = 0; - while (k < unreliableWithAckReceiptHistory.Size()) { - if (incomingAcks.IsWithinRange(unreliableWithAckReceiptHistory[k].datagramNumber)) { - InternalPacket *ackReceipt = AllocateFromInternalPacketPool(); - AllocInternalPacketData(ackReceipt, 5, false, _FILE_AND_LINE_); - ackReceipt->dataBitLength = BYTES_TO_BITS(5); - ackReceipt->data[0] = (MessageID)ID_SND_RECEIPT_ACKED; - memcpy(ackReceipt->data + sizeof(MessageID), &unreliableWithAckReceiptHistory[k].sendReceiptSerial, sizeof(uint32_t)); - outputQueue.Push(ackReceipt, _FILE_AND_LINE_); - - // Remove, swap with last - unreliableWithAckReceiptHistory.RemoveAtIndex(k); - } else { - k++; - } - } - - // early out, if we've got no outstanding datagramHistory entries - if (datagramHistory.IsEmpty()) { - receivePacketCount++; - return true; - } - - for (i = 0; i < incomingAcks.ranges.Size(); i++) { - // note: minIndex is ensured to be always <= maxIndex - otherwise Deserialize() would have failed - RakAssert(incomingAcks.ranges[i].minIndex <= incomingAcks.ranges[i].maxIndex); - - if (incomingAcks.ranges[i].maxIndex == (uint24_t)(0xFFFFFFFF)) { - for (unsigned int messageHandlerIndex = 0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) { - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("incomingAcks maxIndex is max value", BYTES_TO_BITS(length), systemAddress, true); - } - - // it's an invalid incoming package --- let's abort processing (there's no point in continuing processing other ranges if the package is invalid) - return false; - } - - for (datagramNumber = incomingAcks.ranges[i].minIndex; datagramNumber <= incomingAcks.ranges[i].maxIndex; datagramNumber++) { - const DatagramSequenceNumberType offsetIntoList = datagramNumber - datagramHistoryPopCount; - if (offsetIntoList >= datagramHistory.Size()) { - // reached the end of the datagramHistory list - hence, we are done - receivePacketCount++; - return true; - } - - CCTimeType whenSent; - MessageNumberNode *messageNumberNode = GetMessageNumberNodeByDatagramIndex(datagramNumber, &whenSent); - if (messageNumberNode) { - // printf("%p Got ack for %i\n", this, datagramNumber.val); -#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 - congestionManager.OnAck(timeRead, rtt, dhf.hasBAndAS, 0, dhf.AS, totalUserDataBytesAcked, bandwidthExceededStatistic, datagramNumber); -#else - CCTimeType ping; - if (timeRead > whenSent) { - ping = timeRead - whenSent; - } else { - ping = 0; - } - congestionManager.OnAck(timeRead, ping, dhf.hasBAndAS, 0, dhf.AS, totalUserDataBytesAcked, bandwidthExceededStatistic, datagramNumber); -#endif - while (messageNumberNode) { - // TESTING1 -// printf("Remove %i on ack for datagramNumber=%i.\n", messageNumberNode->messageNumber.val, datagramNumber.val); - - RemovePacketFromResendListAndDeleteOlderReliableSequenced(messageNumberNode->messageNumber, timeRead, messageHandlerList, systemAddress); - messageNumberNode = messageNumberNode->next; - } - - RemoveFromDatagramHistory(datagramNumber); - } -// else if (isReliable) { -// // Previously used slot, rather than empty unreliable slot -// printf("%p Ack %i is duplicate\n", this, datagramNumber.val); -// -// congestionManager.OnDuplicateAck(timeRead, datagramNumber); -// } - } - } - } else if (dhf.isNAK) { - // early out, if we've got no outstanding datagramHistory entries - if (datagramHistory.IsEmpty()) { - receivePacketCount++; - return true; - } - - DatagramSequenceNumberType messageNumber; - DataStructures::RangeList incomingNAKs; - if (!incomingNAKs.Deserialize(&socketData)) { - for (unsigned int messageHandlerIndex = 0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) { - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("incomingNAKs.Deserialize failed", BYTES_TO_BITS(length), systemAddress, true); - } - - // it's an invalid incoming package --- let's abort processing (there's no point in continuing processing other ranges if the package is invalid) - return false; - } - for (i = 0; i < incomingNAKs.ranges.Size(); i++) { - // note: minIndex is ensured to be always <= maxIndex - otherwise Deserialize() would have failed - RakAssert(incomingNAKs.ranges[i].minIndex <= incomingNAKs.ranges[i].maxIndex); - - if (incomingNAKs.ranges[i].maxIndex == (uint24_t)(0xFFFFFFFF)) { - for (unsigned int messageHandlerIndex = 0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) { - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("incomingNAKs maxIndex is max value", BYTES_TO_BITS(length), systemAddress, true); - } - - return false; - } - // Sanity check - //RakAssert(incomingNAKs.ranges[i].maxIndex.val-incomingNAKs.ranges[i].minIndex.val<1000); - for (messageNumber = incomingNAKs.ranges[i].minIndex; messageNumber <= incomingNAKs.ranges[i].maxIndex; messageNumber++) { - congestionManager.OnNAK(timeRead, messageNumber); - - // REMOVEME - // printf("%p NAK %i\n", this, dhf.datagramNumber.val); - - const DatagramSequenceNumberType offsetIntoList = messageNumber - datagramHistoryPopCount; - if (offsetIntoList >= datagramHistory.Size()) { - // reached the end of the datagramHistory list - hence, we are done - receivePacketCount++; - return true; - } - - CCTimeType timeSent; - MessageNumberNode *messageNumberNode = GetMessageNumberNodeByDatagramIndex(messageNumber, &timeSent); - while (messageNumberNode) { - // Update timers so resends occur immediately - InternalPacket *internalPacket = resendBuffer[messageNumberNode->messageNumber & (uint32_t) RESEND_BUFFER_ARRAY_MASK]; - if (internalPacket) { - if (internalPacket->nextActionTime != 0) { - internalPacket->nextActionTime = timeRead; - } - } - - messageNumberNode = messageNumberNode->next; - } - } - } - } else { - uint32_t skippedMessageCount; - if (!congestionManager.OnGotPacket(dhf.datagramNumber, dhf.isContinuousSend, timeRead, length, &skippedMessageCount)) { - for (unsigned int messageHandlerIndex = 0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) { - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("congestionManager.OnGotPacket failed", BYTES_TO_BITS(length), systemAddress, true); - } - - return true; - } - if (dhf.isPacketPair) { - congestionManager.OnGotPacketPair(dhf.datagramNumber, length, timeRead); - } - - DatagramHeaderFormat dhfNAK; - dhfNAK.isNAK = true; - uint32_t skippedMessageOffset; - for (skippedMessageOffset = skippedMessageCount; skippedMessageOffset > 0; skippedMessageOffset--) { - NAKs.Insert(dhf.datagramNumber - skippedMessageOffset); - } - remoteSystemNeedsBAndAS = dhf.needsBAndAs; - - // Ack dhf.datagramNumber - // Ack even unreliable messages for congestion control, just don't resend them on no ack -#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 - SendAcknowledgementPacket(dhf.datagramNumber, dhf.sourceSystemTime); -#else - SendAcknowledgementPacket(dhf.datagramNumber, 0); -#endif - - InternalPacket* internalPacket = CreateInternalPacketFromBitStream(&socketData, timeRead); - if (internalPacket == 0) { - for (unsigned int messageHandlerIndex = 0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) { - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("CreateInternalPacketFromBitStream failed", BYTES_TO_BITS(length), systemAddress, true); - } - - return true; - } - - while (internalPacket) { - for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) { -#if CC_TIME_TYPE_BYTES==4 - messageHandlerList[messageHandlerIndex]->OnInternalPacket(internalPacket, receivePacketCount, systemAddress, timeRead, false); -#else - messageHandlerList[messageHandlerIndex]->OnInternalPacket(internalPacket, receivePacketCount, systemAddress, (MafiaNet::TimeMS)(timeRead/(CCTimeType)1000), false); -#endif - } - - { - - // resetReceivedPackets is set from a non-threadsafe function. - // We do the actual reset in this function so the data is not modified by multiple threads - if (resetReceivedPackets) { - hasReceivedPacketQueue.ClearAndForceAllocation(DEFAULT_HAS_RECEIVED_PACKET_QUEUE_SIZE, _FILE_AND_LINE_); - receivedPacketsBaseIndex=0; - resetReceivedPackets=false; - } - - // Check for corrupt orderingChannel - if ( - internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::UnreliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrdered - ) - { - if (internalPacket->orderingChannel >= NUMBER_OF_ORDERED_STREAMS) { - for (unsigned int messageHandlerIndex = 0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) { - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("internalPacket->orderingChannel >= NUMBER_OF_ORDERED_STREAMS", BYTES_TO_BITS(length), systemAddress, true); - } - - bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_IGNORED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); - - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_); - ReleaseToInternalPacketPool(internalPacket); - goto CONTINUE_SOCKET_DATA_PARSE_LOOP; - } - } - - // 8/12/09 was previously not checking if the message was reliable. However, on packetloss this would mean you'd eventually exceed the - // hole count because unreliable messages were never resent, and you'd stop getting messages - if (internalPacket->reliability == MafiaNet::Reliability::Reliable || internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced || internalPacket->reliability == MafiaNet::Reliability::ReliableOrdered) { - // If the following conditional is true then this either a duplicate packet - // or an older out of order packet - // The subtraction unsigned overflow is intentional - holeCount = (DatagramSequenceNumberType)(internalPacket->reliableMessageNumber - receivedPacketsBaseIndex); - const DatagramSequenceNumberType typeRange = (DatagramSequenceNumberType)(const uint32_t)-1; - - // TESTING1 -// printf("waiting on reliableMessageNumber=%i holeCount=%i datagramNumber=%i\n", receivedPacketsBaseIndex.val, holeCount.val, dhf.datagramNumber.val); - - if (holeCount == (DatagramSequenceNumberType)0) { - // Got what we were expecting - if (hasReceivedPacketQueue.Size()) { - hasReceivedPacketQueue.Pop(); - } - ++receivedPacketsBaseIndex; - } else if (holeCount > typeRange/(DatagramSequenceNumberType) 2) { - bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_IGNORED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); - - for (unsigned int messageHandlerIndex = 0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) { - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("holeCount > typeRange/(DatagramSequenceNumberType) 2", BYTES_TO_BITS(length), systemAddress, false); - } - - // Duplicate packet - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_); - ReleaseToInternalPacketPool(internalPacket); - - goto CONTINUE_SOCKET_DATA_PARSE_LOOP; - } else if ((unsigned int)holeCount < hasReceivedPacketQueue.Size()) { - // Got a higher count out of order packet that was missing in the sequence or we already got - if (hasReceivedPacketQueue[holeCount] != false) { // non-zero means this is a hole -#ifdef LOG_TRIVIAL_NOTIFICATIONS - for (unsigned int messageHandlerIndex = 0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) { - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("Higher count pushed to hasReceivedPacketQueue", BYTES_TO_BITS(length), systemAddress, false); - } -#endif - - // Fill in the hole - hasReceivedPacketQueue[holeCount] = false; // We got the packet at holeCount - } else { - bpsMetrics[(int)USER_MESSAGE_BYTES_RECEIVED_IGNORED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); - -#ifdef LOG_TRIVIAL_NOTIFICATIONS - for (unsigned int messageHandlerIndex = 0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) { - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("Duplicate packet ignored", BYTES_TO_BITS(length), systemAddress, false); - } -#endif - - // Duplicate packet - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_); - ReleaseToInternalPacketPool(internalPacket); - - goto CONTINUE_SOCKET_DATA_PARSE_LOOP; - } - } else { // holeCount>=receivedPackets.Size() - if (holeCount > (DatagramSequenceNumberType)1000000) { - RakAssert("Hole count too high. See ReliabilityLayer.h" && 0); - - for (unsigned int messageHandlerIndex = 0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) { - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("holeCount > 1000000", BYTES_TO_BITS(length), systemAddress, true); - } - - bpsMetrics[(int)USER_MESSAGE_BYTES_RECEIVED_IGNORED].Push1(timeRead, BITS_TO_BYTES(internalPacket->dataBitLength)); - - // Would crash due to out of memory! - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_); - ReleaseToInternalPacketPool(internalPacket); - - goto CONTINUE_SOCKET_DATA_PARSE_LOOP; - } - -#ifdef LOG_TRIVIAL_NOTIFICATIONS - for (unsigned int messageHandlerIndex = 0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) { - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("Adding to hasReceivedPacketQueue later ordered message", BYTES_TO_BITS(length), systemAddress, false); - } -#endif - - // Fix - sending on a higher priority gives us a very very high received packets base index if we formerly had pre-split a lot of messages and - // used that as the message number. Because of this, a lot of time is spent in this linear loop and the timeout time expires because not - // all of the message is sent in time. - // Fixed by late assigning message IDs on the sender - - // Add 0 times to the queue until (reliableMessageNumber - baseIndex) < queue size. - while ((unsigned int)(holeCount) > hasReceivedPacketQueue.Size()) { - hasReceivedPacketQueue.Push(true, _FILE_AND_LINE_); // time+(CCTimeType)60 * (CCTimeType)1000 * (CCTimeType)1000); // Didn't get this packet - set the time to give up waiting - } - hasReceivedPacketQueue.Push(false, _FILE_AND_LINE_ ); // Got the packet -#ifdef _DEBUG - // If this assert hits then DatagramSequenceNumberType has overflowed - RakAssert(hasReceivedPacketQueue.Size() < (unsigned int)((DatagramSequenceNumberType)(const uint32_t)(-1))); -#endif - } - - while (hasReceivedPacketQueue.Size() > 0 && !hasReceivedPacketQueue.Peek()) { - hasReceivedPacketQueue.Pop(); - ++receivedPacketsBaseIndex; - } - } - - // If the allocated buffer is > DEFAULT_HAS_RECEIVED_PACKET_QUEUE_SIZE and it is 3x greater than the number of elements actually being used - if (hasReceivedPacketQueue.AllocationSize() > (unsigned int)DEFAULT_HAS_RECEIVED_PACKET_QUEUE_SIZE && hasReceivedPacketQueue.AllocationSize() > hasReceivedPacketQueue.Size() * 3) { - hasReceivedPacketQueue.Compress(_FILE_AND_LINE_); - } - - - /* - if (internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced || internalPacket->reliability == MafiaNet::Reliability::UnreliableSequenced) { -#ifdef _DEBUG - RakAssert(internalPacket->orderingChannel < NUMBER_OF_ORDERED_STREAMS); -#endif - - if (internalPacket->orderingChannel >= NUMBER_OF_ORDERED_STREAMS) { - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_); - ReleaseToInternalPacketPool(internalPacket); - - for (unsigned int messageHandlerIndex = 0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) { - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("internalPacket->orderingChannel >= NUMBER_OF_ORDERED_STREAMS", BYTES_TO_BITS(length), systemAddress); - } - - bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_IGNORED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); - - goto CONTINUE_SOCKET_DATA_PARSE_LOOP; - } - - if (!IsOlderOrderedPacket(internalPacket->orderingIndex, waitingForSequencedPacketReadIndex[internalPacket->orderingChannel])) { - // Is this a split packet? - if (internalPacket->splitPacketCount > 0) { - // Generate the split - // Verify some parameters to make sure we don't get junk data - - - // Check for a rebuilt packet - InsertIntoSplitPacketList(internalPacket, timeRead); - bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_PROCESSED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); - - // Sequenced - internalPacket = BuildPacketFromSplitPacketList( internalPacket->splitPacketId, timeRead, - s, systemAddress, rnr, remotePortRakNetWasStartedOn_PS3, extraSocketOptions); - - if (internalPacket) { - // Update our index to the newest packet - waitingForSequencedPacketReadIndex[ internalPacket->orderingChannel ] = internalPacket->orderingIndex + (OrderingIndexType)1; - - // If there is a rebuilt packet, add it to the output queue - outputQueue.Push(internalPacket, _FILE_AND_LINE_); - internalPacket = 0; - } - - // else don't have all the parts yet - } else { - // Update our index to the newest packet - waitingForSequencedPacketReadIndex[ internalPacket->orderingChannel ] = internalPacket->orderingIndex + (OrderingIndexType)1; - - // Not a split packet. Add the packet to the output queue - bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_PROCESSED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); - outputQueue.Push( internalPacket, _FILE_AND_LINE_ ); - internalPacket = 0; - } - } else { - // Older sequenced packet. Discard it - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); - ReleaseToInternalPacketPool( internalPacket ); - - bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_IGNORED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); - } - - goto CONTINUE_SOCKET_DATA_PARSE_LOOP; - } - - // Is this an unsequenced split packet? - if ( internalPacket->splitPacketCount > 0 ) - { - // Check for a rebuilt packet - if ( internalPacket->reliability != MafiaNet::Reliability::ReliableOrdered ) - internalPacket->orderingChannel = 255; // Use 255 to designate not sequenced and not ordered - - InsertIntoSplitPacketList( internalPacket, timeRead ); - - internalPacket = BuildPacketFromSplitPacketList( internalPacket->splitPacketId, timeRead, - s, systemAddress, rnr, remotePortRakNetWasStartedOn_PS3, extraSocketOptions); - - if ( internalPacket == 0 ) - { - - // Don't have all the parts yet - goto CONTINUE_SOCKET_DATA_PARSE_LOOP; - } - } - */ - - /* - if ( internalPacket->reliability == MafiaNet::Reliability::ReliableOrdered ) - { -#ifdef _DEBUG - RakAssert( internalPacket->orderingChannel < NUMBER_OF_ORDERED_STREAMS ); -#endif - - if ( internalPacket->orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) - { - // Invalid packet - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); - ReleaseToInternalPacketPool( internalPacket ); - - bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_IGNORED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); - - goto CONTINUE_SOCKET_DATA_PARSE_LOOP; - } - - bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_PROCESSED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); - - if ( waitingForOrderedPacketReadIndex[ internalPacket->orderingChannel ] == internalPacket->orderingIndex ) - { - // Get the list to hold ordered packets for this stream - DataStructures::LinkedList *orderingListAtOrderingStream; - unsigned char orderingChannelCopy = internalPacket->orderingChannel; - - // Push the packet for the user to read - outputQueue.Push( internalPacket, _FILE_AND_LINE_ ); - internalPacket = 0; // Don't reference this any longer since other threads access it - - // Wait for the resendNext ordered packet in sequence - waitingForOrderedPacketReadIndex[ orderingChannelCopy ] ++; // This wraps - - orderingListAtOrderingStream = GetOrderingListAtOrderingStream( orderingChannelCopy ); - - if ( orderingListAtOrderingStream != 0) - { - while ( orderingListAtOrderingStream->Size() > 0 ) - { - // Cycle through the list until nothing is found - orderingListAtOrderingStream->Beginning(); - indexFound=false; - size=orderingListAtOrderingStream->Size(); - count=0; - - while (count++ < size) - { - if ( orderingListAtOrderingStream->Peek()->orderingIndex == waitingForOrderedPacketReadIndex[ orderingChannelCopy ] ) - { - outputQueue.Push( orderingListAtOrderingStream->Pop(), _FILE_AND_LINE_ ); - waitingForOrderedPacketReadIndex[ orderingChannelCopy ]++; - indexFound=true; - } - else - (*orderingListAtOrderingStream)++; - } - - if (indexFound==false) - break; - } - } - internalPacket = 0; - } - else - { - // This is a newer ordered packet than we are waiting for. Store it for future use - AddToOrderingList( internalPacket ); - } - - - goto CONTINUE_SOCKET_DATA_PARSE_LOOP; - } - */ - - // Is this a split packet? If so then reassemble - if ( internalPacket->splitPacketCount > 0 ) - { - // Check for a rebuilt packet - if ( internalPacket->reliability != MafiaNet::Reliability::ReliableOrdered && internalPacket->reliability!=MafiaNet::Reliability::ReliableSequenced && internalPacket->reliability!=MafiaNet::Reliability::UnreliableSequenced) - internalPacket->orderingChannel = 255; // Use 255 to designate not sequenced and not ordered - - InsertIntoSplitPacketList( internalPacket, timeRead ); - - internalPacket = BuildPacketFromSplitPacketList( internalPacket->splitPacketId, timeRead, - s, systemAddress, rnr, updateBitStream); - - if ( internalPacket == 0 ) - { -#ifdef LOG_TRIVIAL_NOTIFICATIONS - for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("BuildPacketFromSplitPacketList did not return anything.", BYTES_TO_BITS(length), systemAddress, false); -#endif - - // Don't have all the parts yet - goto CONTINUE_SOCKET_DATA_PARSE_LOOP; - } - } - -#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST - unsigned char packetId; - char *type="UNDEFINED"; -#endif - if (internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::UnreliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrdered) - { -#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST - - // ___________________ - BitStream bitStream(internalPacket->data, BITS_TO_BYTES(internalPacket->dataBitLength), false); - unsigned int receivedPacketNumber; - MafiaNet::Time receivedTime; - unsigned char streamNumber; - MafiaNet::Reliability reliability; - // ___________________ - - - bitStream.IgnoreBits(8); // Ignore ID_TIMESTAMP - bitStream.Read(receivedTime); - bitStream.Read(packetId); - bitStream.Read(receivedPacketNumber); - bitStream.Read(streamNumber); - bitStream.Read(reliability); - if (packetId==ID_USER_PACKET_ENUM+1) - { - - if (reliability==MafiaNet::Reliability::UnreliableSequenced) - type="UnreliableSequenced"; - else if (reliability==MafiaNet::Reliability::ReliableOrdered) - type="ReliableOrdered"; - else - type="ReliableSequenced"; - } - // ___________________ -#endif - - - if (internalPacket->orderingIndex==orderedReadIndex[internalPacket->orderingChannel]) - { - // Has current ordering index - if (internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::UnreliableSequenced) - { - // Is sequenced - if (IsOlderOrderedPacket(internalPacket->sequencingIndex,highestSequencedReadIndex[internalPacket->orderingChannel])==false) - { - // Expected or highest known value - -#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST - if (packetId==ID_USER_PACKET_ENUM+1 && fp) - { - fprintf(fp, "Returning %i, %s by fallthrough. OI=%i. SI=%i.\n", receivedPacketNumber, type, internalPacket->orderingIndex.val, internalPacket->sequencingIndex); - fflush(fp); - } - - if (packetId==ID_USER_PACKET_ENUM+1) - { - if (receivedPacketNumberorderingChannel] = internalPacket->sequencingIndex+(OrderingIndexType)1; - - // Fallthrough, returned to user below - } - else - { -#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST - if (packetId==ID_USER_PACKET_ENUM+1 && fp) - { - fprintf(fp, "Discarding %i, %s late sequenced. OI=%i. SI=%i.\n", receivedPacketNumber, type, internalPacket->orderingIndex.val, internalPacket->sequencingIndex); - fflush(fp); - } -#endif - -#ifdef LOG_TRIVIAL_NOTIFICATIONS - for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("Sequenced rejected: lower than highest known value", BYTES_TO_BITS(length), systemAddress, false); -#endif - - // Lower than highest known value - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); - ReleaseToInternalPacketPool( internalPacket ); - - goto CONTINUE_SOCKET_DATA_PARSE_LOOP; - } - } - else - { - // Push to output buffer immediately - bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_PROCESSED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); - outputQueue.Push( internalPacket, _FILE_AND_LINE_ ); - -#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST - if (packetId==ID_USER_PACKET_ENUM+1 && fp) - { - fprintf(fp, "outputting immediate %i, %s. OI=%i. SI=%i.", receivedPacketNumber, type, internalPacket->orderingIndex.val, internalPacket->sequencingIndex); - if (orderingHeaps[internalPacket->orderingChannel].Size()==0) - fprintf(fp, "heap empty\n"); - else - fprintf(fp, "heap head=%i\n", orderingHeaps[internalPacket->orderingChannel].Peek()->orderingIndex.val); - - if (receivedPacketNumberorderingChannel]++; - highestSequencedReadIndex[internalPacket->orderingChannel] = 0; - - // Return off heap until order lost - while (orderingHeaps[internalPacket->orderingChannel].Size()>0 && - orderingHeaps[internalPacket->orderingChannel].Peek()->orderingIndex==orderedReadIndex[internalPacket->orderingChannel]) - { - internalPacket = orderingHeaps[internalPacket->orderingChannel].Pop(0); - -#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST - BitStream bitStream2(internalPacket->data, BITS_TO_BYTES(internalPacket->dataBitLength), false); - bitStream2.IgnoreBits(8); // Ignore ID_TIMESTAMP - bitStream2.Read(receivedTime); - bitStream2.IgnoreBits(8); // Ignore ID_USER_ENUM+1 - bitStream2.Read(receivedPacketNumber); - bitStream2.Read(streamNumber); - bitStream2.Read(reliability); - char *type="UNDEFINED"; - if (reliability==MafiaNet::Reliability::UnreliableSequenced) - type="UnreliableSequenced"; - else if (reliability==MafiaNet::Reliability::ReliableOrdered) - type="ReliableOrdered"; - - if (packetId==ID_USER_PACKET_ENUM+1 && fp) - { - fprintf(fp, "Heap pop %i, %s. OI=%i. SI=%i.\n", receivedPacketNumber, type, internalPacket->orderingIndex.val, internalPacket->sequencingIndex); - fflush(fp); - - if (receivedPacketNumberdataBitLength)); - outputQueue.Push( internalPacket, _FILE_AND_LINE_ ); - - if (internalPacket->reliability == MafiaNet::Reliability::ReliableOrdered) - { - orderedReadIndex[internalPacket->orderingChannel]++; - } - else - { - highestSequencedReadIndex[internalPacket->orderingChannel] = internalPacket->sequencingIndex; - } - } - - // Done - goto CONTINUE_SOCKET_DATA_PARSE_LOOP; - } - } - else if (IsOlderOrderedPacket(internalPacket->orderingIndex,orderedReadIndex[internalPacket->orderingChannel])==false) - { - // internalPacket->_orderingIndex is greater - // If a message has a greater ordering index, and is sequenced or ordered, buffer it - // Sequenced has a lower heap weight, ordered has max sequenced weight - - // Keep orderedHoleCount count small - if (orderingHeaps[internalPacket->orderingChannel].Size()==0) - heapIndexOffsets[internalPacket->orderingChannel]=orderedReadIndex[internalPacket->orderingChannel]; - - reliabilityHeapWeightType orderedHoleCount = internalPacket->orderingIndex-heapIndexOffsets[internalPacket->orderingChannel]; - reliabilityHeapWeightType weight = orderedHoleCount*1048576; - if (internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::UnreliableSequenced) - weight+=internalPacket->sequencingIndex; - else - weight+=(1048576-1); - orderingHeaps[internalPacket->orderingChannel].Push(weight, internalPacket, _FILE_AND_LINE_); - -#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST - if (packetId==ID_USER_PACKET_ENUM+1 && fp) - { - fprintf(fp, "Heap push %i, %s, weight=%" PRINTF_64_BIT_MODIFIER "u. OI=%i. waiting on %i. SI=%i.\n", receivedPacketNumber, type, weight, internalPacket->orderingIndex.val, orderedReadIndex[internalPacket->orderingChannel].val, internalPacket->sequencingIndex); - fflush(fp); - } -#endif - -#ifdef LOG_TRIVIAL_NOTIFICATIONS - for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("Larger number ordered packet leaving holes", BYTES_TO_BITS(length), systemAddress, false); -#endif - - // Buffered, nothing to do - goto CONTINUE_SOCKET_DATA_PARSE_LOOP; - } - else - { - // Out of order - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); - ReleaseToInternalPacketPool( internalPacket ); - -#ifdef LOG_TRIVIAL_NOTIFICATIONS - for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) - messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("Rejected older resend", BYTES_TO_BITS(length), systemAddress, false); -#endif - - // Ignored, nothing to do - goto CONTINUE_SOCKET_DATA_PARSE_LOOP; - } - - } - - bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_PROCESSED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); - - // Nothing special about this packet. Add it to the output queue - outputQueue.Push( internalPacket, _FILE_AND_LINE_ ); - - internalPacket = 0; - } - - // Used for a goto to jump to the resendNext packet immediately - -CONTINUE_SOCKET_DATA_PARSE_LOOP: - // Parse the bitstream to create an internal packet - internalPacket = CreateInternalPacketFromBitStream( &socketData, timeRead ); - } - - } - - // #med - review --- is this correct to not increase in error cases? - receivePacketCount++; - - return true; -} - -//------------------------------------------------------------------------------------------------------- -// This gets an end-user packet already parsed out. Returns number of BITS put into the buffer -//------------------------------------------------------------------------------------------------------- -BitSize_t ReliabilityLayer::Receive( unsigned char **data ) -{ - InternalPacket * internalPacket; - - if ( outputQueue.Size() > 0 ) - { - // #ifdef _DEBUG - // RakAssert(bitStream->GetNumberOfBitsUsed()==0); - // #endif - internalPacket = outputQueue.Pop(); - - BitSize_t bitLength; - *data = internalPacket->data; - bitLength = internalPacket->dataBitLength; - ReleaseToInternalPacketPool( internalPacket ); - return bitLength; - } - - else - { - return 0; - } - -} - -//------------------------------------------------------------------------------------------------------- -// Puts data on the send queue -// bitStream contains the data to send -// priority is what priority to send the data at -// reliability is what reliability to use -// ordering channel is from 0 to 255 and specifies what stream to use -//------------------------------------------------------------------------------------------------------- -bool ReliabilityLayer::Send( char *data, BitSize_t numberOfBitsToSend, MafiaNet::Priority priority, MafiaNet::Reliability reliability, unsigned char orderingChannel, bool makeDataCopy, int MTUSize, CCTimeType currentTime, uint32_t receipt ) -{ -#ifdef _DEBUG - RakAssert( !( (unsigned int)reliability >= MafiaNet::NUMBER_OF_RELIABILITIES || (int)reliability < 0 ) ); - RakAssert( !( (int)priority > (int)MafiaNet::NUMBER_OF_PRIORITIES || (int)priority < 0 ) ); - RakAssert( !( orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) ); - RakAssert( numberOfBitsToSend > 0 ); -#endif - -#if CC_TIME_TYPE_BYTES==4 - currentTime/=1000; -#endif - - (void) MTUSize; - - // int a = BITS_TO_BYTES(numberOfBitsToSend); - - // Fix any bad parameters - if ( reliability > MafiaNet::Reliability::ReliableOrderedWithAckReceipt || (int)reliability < 0 ) - reliability = MafiaNet::Reliability::Reliable; - - if ( (int)priority > (int)MafiaNet::NUMBER_OF_PRIORITIES || (int)priority < 0 ) - priority = MafiaNet::Priority::High; - - if ( orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) - orderingChannel = 0; - - unsigned int numberOfBytesToSend=(unsigned int) BITS_TO_BYTES(numberOfBitsToSend); - if ( numberOfBitsToSend == 0 ) - { - return false; - } - InternalPacket * internalPacket = AllocateFromInternalPacketPool(); - if (internalPacket==0) - { - notifyOutOfMemory(_FILE_AND_LINE_); - return false; // Out of memory - } - - bpsMetrics[(int) USER_MESSAGE_BYTES_PUSHED].Push1(currentTime,numberOfBytesToSend); - - internalPacket->creationTime = currentTime; - - if ( makeDataCopy ) - { - AllocInternalPacketData(internalPacket, numberOfBytesToSend, true, _FILE_AND_LINE_ ); - //internalPacket->data = (unsigned char*) rakMalloc_Ex( numberOfBytesToSend, _FILE_AND_LINE_ ); - memcpy( internalPacket->data, data, numberOfBytesToSend ); - } - else - { - // Allocated the data elsewhere, delete it in here - //internalPacket->data = ( unsigned char* ) data; - AllocInternalPacketData(internalPacket, (unsigned char*) data ); - } - - internalPacket->dataBitLength = numberOfBitsToSend; - internalPacket->messageInternalOrder = internalOrderIndex++; - internalPacket->priority = priority; - internalPacket->reliability = reliability; - internalPacket->sendReceiptSerial=receipt; - - // Calculate if I need to split the packet - // int headerLength = BITS_TO_BYTES( GetMessageHeaderLengthBits( internalPacket, true ) ); - - unsigned int maxDataSizeBytes = GetMaxDatagramSizeExcludingMessageHeaderBytes() - BITS_TO_BYTES(GetMaxMessageHeaderLengthBits()); - - bool splitPacket = numberOfBytesToSend > maxDataSizeBytes; - - // If a split packet, we might have to upgrade the reliability - if ( splitPacket ) - { - // Split packets cannot be unreliable, in case that one part doesn't arrive and the whole cannot be reassembled. - // One part could not arrive either due to packetloss or due to unreliable discard - if (internalPacket->reliability==MafiaNet::Reliability::Unreliable) - internalPacket->reliability=MafiaNet::Reliability::Reliable; - else if (internalPacket->reliability==MafiaNet::Reliability::UnreliableWithAckReceipt) - internalPacket->reliability=MafiaNet::Reliability::ReliableWithAckReceipt; - else if (internalPacket->reliability==MafiaNet::Reliability::UnreliableSequenced) - internalPacket->reliability=MafiaNet::Reliability::ReliableSequenced; -// else if (internalPacket->reliability==UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT) -// internalPacket->reliability=RELIABLE_SEQUENCED_WITH_ACK_RECEIPT; - } - - // ++sendMessageNumberIndex; - - if ( internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::UnreliableSequenced -// || -// internalPacket->reliability == RELIABLE_SEQUENCED_WITH_ACK_RECEIPT || -// internalPacket->reliability == UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT - ) - { - // Assign the sequence stream and index - internalPacket->orderingChannel = orderingChannel; - internalPacket->orderingIndex = orderedWriteIndex[ orderingChannel ]; - internalPacket->sequencingIndex = sequencedWriteIndex[ orderingChannel ]++; - - // This packet supersedes all other sequenced packets on the same ordering channel - // Delete all packets in all send lists that are sequenced and on the same ordering channel - // UPDATE: - // Disabled. We don't have enough info to consistently do this. Sometimes newer data does supercede - // older data such as with constantly declining health, but not in all cases. - // For example, with sequenced unreliable sound packets just because you send a newer one doesn't mean you - // don't need the older ones because the odds are they will still arrive in order - /* - for (int i=0; i < MafiaNet::NUMBER_OF_PRIORITIES; i++) - { - DeleteSequencedPacketsInList(orderingChannel, sendQueue[i]); - } - */ - } - else if ( internalPacket->reliability == MafiaNet::Reliability::ReliableOrdered || internalPacket->reliability == MafiaNet::Reliability::ReliableOrderedWithAckReceipt ) - { - // Assign the ordering channel and index - internalPacket->orderingChannel = orderingChannel; - internalPacket->orderingIndex = orderedWriteIndex[ orderingChannel ] ++; - sequencedWriteIndex[ orderingChannel ]=0; - } - - if ( splitPacket ) // If it uses a secure header it will be generated here - { - // Must split the packet. This will also generate the SHA1 if it is required. It also adds it to the send list. - //InternalPacket packetCopy; - //memcpy(&packetCopy, internalPacket, sizeof(InternalPacket)); - //sendPacketSet[priority].CancelWriteLock(internalPacket); - //SplitPacket( &packetCopy, MTUSize ); - SplitPacket( internalPacket ); - //MafiaNet::OP_DELETE_ARRAY(packetCopy.data, _FILE_AND_LINE_); - return true; - } - - RakAssert(internalPacket->dataBitLengthdataBitLengthmessageNumberAssigned==false); - outgoingPacketBuffer.Push( GetNextWeight((int)internalPacket->priority), internalPacket, _FILE_AND_LINE_ ); - RakAssert(outgoingPacketBuffer.Size()==0 || outgoingPacketBuffer.Peek()->dataBitLengthpriority]++; - statistics.bytesInSendBuffer[(int)internalPacket->priority]+=(double) BITS_TO_BYTES(internalPacket->dataBitLength); - - // sendPacketSet[priority].WriteUnlock(); - return true; -} -//------------------------------------------------------------------------------------------------------- -// Run this once per game cycle. Handles internal lists and actually does the send -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::Update( RakNetSocket2 *s, SystemAddress &systemAddress, int MTUSize, CCTimeType time, - unsigned bitsPerSecondLimit, - DataStructures::List &messageHandlerList, - RakNetRandom *rnr, - BitStream &updateBitStream) -{ - UpdateInternal(s, systemAddress, MTUSize, time, bitsPerSecondLimit, messageHandlerList, rnr, updateBitStream, false); -} - -void ReliabilityLayer::UpdateAndForceACKs( RakNetSocket2 *s, SystemAddress &systemAddress, int MTUSize, CCTimeType time, - unsigned bitsPerSecondLimit, - DataStructures::List &messageHandlerList, - RakNetRandom *rnr, - BitStream &updateBitStream) -{ - UpdateInternal(s, systemAddress, MTUSize, time, bitsPerSecondLimit, messageHandlerList, rnr, updateBitStream, true); -} - -void ReliabilityLayer::UpdateInternal( RakNetSocket2 *s, SystemAddress &systemAddress, int MTUSize, CCTimeType time, - unsigned bitsPerSecondLimit, - DataStructures::List &messageHandlerList, - RakNetRandom *rnr, - BitStream &updateBitStream, bool forceSendACKs) -{ - (void) MTUSize; - - MafiaNet::TimeMS timeMs; -#if CC_TIME_TYPE_BYTES==4 - time/=1000; - timeMs=time; -#else - timeMs=(MafiaNet::TimeMS) (time/(CCTimeType)1000); -#endif - -#ifdef _DEBUG - while (delayList.Size()) - { - if (delayList.Peek()->sendTime <= timeMs) - { - DataAndTime *dat = delayList.Pop(); -// SocketLayer::SendTo( dat->s, dat->data, dat->length, systemAddress, __FILE__, __LINE__ ); - - RNS2_SendParameters bsp; - bsp.data = (char*) dat->data; - bsp.length = dat->length; - bsp.systemAddress = systemAddress; - dat->s->Send(&bsp, _FILE_AND_LINE_); - - MafiaNet::OP_DELETE(dat,__FILE__,__LINE__); - } - else - { - break; - } - } -#endif - - // This line is necessary because the timer isn't accurate - if ((!forceSendACKs) && (time <= lastUpdateTime)) - { - // Always set the last time in case of overflow - lastUpdateTime=time; - return; - } - - CCTimeType timeSinceLastTick = time - lastUpdateTime; - lastUpdateTime=time; -#if CC_TIME_TYPE_BYTES==4 - if (timeSinceLastTick>100) - timeSinceLastTick=100; -#else - if (timeSinceLastTick>100000) - timeSinceLastTick=100000; -#endif - - if (unreliableTimeout>0) - { - if (timeSinceLastTick>=timeToNextUnreliableCull) - { - if (unreliableLinkedListHead) - { - // Cull out all unreliable messages that have exceeded the timeout - InternalPacket *cur = unreliableLinkedListHead; - InternalPacket *end = unreliableLinkedListHead->unreliablePrev; - - for(;;) - { - if (time > cur->creationTime+(CCTimeType)unreliableTimeout) - { - // Flag invalid, and clear the memory. Still needs to be removed from the sendPacketSet later - // This fixes a problem where a remote system disconnects, but we don't know it yet, and memory consumption increases to a huge value - FreeInternalPacketData(cur, _FILE_AND_LINE_ ); - cur->data=0; - InternalPacket *next = cur->unreliableNext; - RemoveFromUnreliableLinkedList(cur); - - if (cur==end) - break; - - cur=next; - } - else - { - // if (cur==end) - // break; - // - // cur=cur->unreliableNext; - - // They should be inserted in-order, so no need to iterate past the first failure - break; - } - } - } - - timeToNextUnreliableCull=unreliableTimeout/(CCTimeType)2; - } - else - { - timeToNextUnreliableCull-=timeSinceLastTick; - } - } - - - // Due to thread vagarities and the way I store the time to avoid slow calls to MafiaNet::GetTime - // time may be less than lastAck -#if CC_TIME_TYPE_BYTES==4 - if ( statistics.messagesInResendBuffer!=0 && AckTimeout(time) ) -#else - if ( statistics.messagesInResendBuffer!=0 && AckTimeout(MafiaNet::TimeMS(time/(CCTimeType)1000)) ) -#endif - { - // SHOW - dead connection - // We've waited a very long time for a reliable packet to get an ack and it never has - deadConnection = true; - return; - } - - if (forceSendACKs || congestionManager.ShouldSendACKs(time,timeSinceLastTick)) - { - SendACKs(s, systemAddress, time, rnr, updateBitStream); - } - - if (NAKs.Size()>0) - { - updateBitStream.Reset(); - DatagramHeaderFormat dhfNAK; - dhfNAK.isNAK=true; - dhfNAK.isACK=false; - dhfNAK.isPacketPair=false; - dhfNAK.Serialize(&updateBitStream); - NAKs.Serialize(&updateBitStream, GetMaxDatagramSizeExcludingMessageHeaderBits(), true); - SendBitStream( s, systemAddress, &updateBitStream, rnr, time ); - } - - DatagramHeaderFormat dhf; - dhf.needsBAndAs=congestionManager.GetIsInSlowStart(); - dhf.isContinuousSend=bandwidthExceededStatistic; - // bandwidthExceededStatistic=sendPacketSet[0].IsEmpty()==false || - // sendPacketSet[1].IsEmpty()==false || - // sendPacketSet[2].IsEmpty()==false || - // sendPacketSet[3].IsEmpty()==false; - bandwidthExceededStatistic=outgoingPacketBuffer.Size()>0; - - const bool hasDataToSendOrResend = IsResendQueueEmpty()==false || bandwidthExceededStatistic; - RakAssert(MafiaNet::NUMBER_OF_PRIORITIES==4); - congestionManager.Update(time, hasDataToSendOrResend); - - statistics.BPSLimitByOutgoingBandwidthLimit = BITS_TO_BYTES(bitsPerSecondLimit); - statistics.BPSLimitByCongestionControl = congestionManager.GetBytesPerSecondLimitByCongestionControl(); - - unsigned int i; - if (time > lastBpsClear+ -#if CC_TIME_TYPE_BYTES==4 - 100 -#else - 100000 -#endif - ) - { - for (i=0; i < RNS_PER_SECOND_METRICS_COUNT; i++) - { - bpsMetrics[i].ClearExpired1(time); - } - - lastBpsClear=time; - } - - if (unreliableWithAckReceiptHistory.Size()>0) - { - i=0; - while (i < unreliableWithAckReceiptHistory.Size()) - { - //if (unreliableWithAckReceiptHistory[i].nextActionTime < time) - if (time - unreliableWithAckReceiptHistory[i].nextActionTime < (((CCTimeType)-1)/2) ) - { - InternalPacket *ackReceipt = AllocateFromInternalPacketPool(); - AllocInternalPacketData(ackReceipt, 5, false, _FILE_AND_LINE_ ); - ackReceipt->dataBitLength=BYTES_TO_BITS(5); - ackReceipt->data[0]=(MessageID)ID_SND_RECEIPT_LOSS; - memcpy(ackReceipt->data+sizeof(MessageID), &unreliableWithAckReceiptHistory[i].sendReceiptSerial, sizeof(uint32_t)); - outputQueue.Push(ackReceipt, _FILE_AND_LINE_ ); - - // Remove, swap with last - unreliableWithAckReceiptHistory.RemoveAtIndex(i); - } - else - i++; - } - } - - if (hasDataToSendOrResend==true) - { - InternalPacket *internalPacket; - // bool forceSend=false; - bool pushedAnything; - BitSize_t nextPacketBitLength; - dhf.isACK=false; - dhf.isNAK=false; - dhf.hasBAndAS=false; - ResetPacketsAndDatagrams(); - - int transmissionBandwidth = congestionManager.GetTransmissionBandwidth(time, timeSinceLastTick, unacknowledgedBytes,dhf.isContinuousSend); - int retransmissionBandwidth = congestionManager.GetRetransmissionBandwidth(time, timeSinceLastTick, unacknowledgedBytes,dhf.isContinuousSend); - if (retransmissionBandwidth>0 || transmissionBandwidth>0) - { - statistics.isLimitedByCongestionControl=false; - - allDatagramSizesSoFar=0; - - // Keep filling datagrams until we exceed retransmission bandwidth - while ((int)BITS_TO_BYTES(allDatagramSizesSoFar)messageNumberAssigned==true); - - //if ( internalPacket->nextActionTime < time ) - if ( time - internalPacket->nextActionTime < (((CCTimeType)-1)/2) ) - { - nextPacketBitLength = internalPacket->headerLength + internalPacket->dataBitLength; - if ( datagramSizeSoFar + nextPacketBitLength > GetMaxDatagramSizeExcludingMessageHeaderBits() ) - { - // Gathers all PushPackets() - PushDatagram(); - break; - } - - PopListHead(false); - - CC_DEBUG_PRINTF_2("Rs %i ", internalPacket->reliableMessageNumber.val); - - bpsMetrics[(int) USER_MESSAGE_BYTES_RESENT].Push1(time,BITS_TO_BYTES(internalPacket->dataBitLength)); - - // Testing1 -// if (internalPacket->reliability==MafiaNet::Reliability::ReliableOrdered || internalPacket->reliability==MafiaNet::Reliability::ReliableOrderedWithAckReceipt) -// printf("RESEND reliableMessageNumber %i with datagram %i\n", internalPacket->reliableMessageNumber.val, congestionManager.GetNextDatagramSequenceNumber().val); - - PushPacket(time,internalPacket,true); // Affects GetNewTransmissionBandwidth() - internalPacket->timesSent++; - congestionManager.OnResend(time, internalPacket->nextActionTime); - internalPacket->retransmissionTime = congestionManager.GetRTOForRetransmission(internalPacket->timesSent); - internalPacket->nextActionTime = internalPacket->retransmissionTime+time; - - pushedAnything=true; - - for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) - { -#if CC_TIME_TYPE_BYTES==4 - messageHandlerList[messageHandlerIndex]->OnInternalPacket(internalPacket, packetsToSendThisUpdateDatagramBoundaries.Size()+congestionManager.GetNextDatagramSequenceNumber(), systemAddress, (MafiaNet::TimeMS) time, true); -#else - messageHandlerList[messageHandlerIndex]->OnInternalPacket(internalPacket, packetsToSendThisUpdateDatagramBoundaries.Size()+congestionManager.GetNextDatagramSequenceNumber(), systemAddress, (MafiaNet::TimeMS)(time/(CCTimeType)1000), true); -#endif - } - - // Put the packet back into the resend list at the correct spot - // Don't make a copy since I'm reinserting an allocated struct - InsertPacketIntoResendList( internalPacket, time, false, false ); - - // Removeme - // printf("Resend:%i ", internalPacket->reliableMessageNumber); - } - else - { - // Filled one datagram. - // If the 2nd and it's time to send a datagram pair, will be marked as a pair - PushDatagram(); - break; - } - } - - if (pushedAnything==false) - break; - } - } - else - { - statistics.isLimitedByCongestionControl=true; - } - - if ((int)BITS_TO_BYTES(allDatagramSizesSoFar)messageNumberAssigned==false); - RakAssert(outgoingPacketBuffer.Size()==0 || outgoingPacketBuffer.Peek()->dataBitLengthdata==0) - { - //sendPacketSet[ i ].Pop(); - outgoingPacketBuffer.Pop(0); - RakAssert(outgoingPacketBuffer.Size()==0 || outgoingPacketBuffer.Peek()->dataBitLengthpriority]--; - statistics.bytesInSendBuffer[(int)internalPacket->priority]-=(double) BITS_TO_BYTES(internalPacket->dataBitLength); - ReleaseToInternalPacketPool( internalPacket ); - continue; - } - - internalPacket->headerLength=GetMessageHeaderLengthBits(internalPacket); - nextPacketBitLength = internalPacket->headerLength + internalPacket->dataBitLength; - if ( datagramSizeSoFar + nextPacketBitLength > GetMaxDatagramSizeExcludingMessageHeaderBits() ) - { - // Hit MTU. May still push packets if smaller ones exist at a lower priority - RakAssert(datagramSizeSoFar!=0); - RakAssert(internalPacket->dataBitLengthreliability == MafiaNet::Reliability::Reliable || - internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrdered || - internalPacket->reliability == MafiaNet::Reliability::ReliableWithAckReceipt || -// internalPacket->reliability == RELIABLE_SEQUENCED_WITH_ACK_RECEIPT || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrderedWithAckReceipt - ) - isReliable = true; - else - isReliable = false; - - //sendPacketSet[ i ].Pop(); - outgoingPacketBuffer.Pop(0); - RakAssert(outgoingPacketBuffer.Size()==0 || outgoingPacketBuffer.Peek()->dataBitLengthmessageNumberAssigned==false); - statistics.messageInSendBuffer[(int)internalPacket->priority]--; - statistics.bytesInSendBuffer[(int)internalPacket->priority]-=(double) BITS_TO_BYTES(internalPacket->dataBitLength); - if (isReliable - /* - I thought about this and agree that UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT and RELIABLE_SEQUENCED_WITH_ACK_RECEIPT is not useful unless you also know if the message was discarded. - - The problem is that internally, message numbers are only assigned to reliable messages, because message numbers are only used to discard duplicate message receipt and only reliable messages get sent more than once. However, without message numbers getting assigned and transmitted, there is no way to tell the sender about which messages were discarded. In fact, in looking this over I realized that UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT introduced a bug, because the remote system assumes all message numbers are used (no holes). With that send type, on packetloss, a permanent hole would have been created which eventually would cause the system to discard all further packets. - - So I have two options. Either do not support ack receipts when sending sequenced, or write complex and major new systems. UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT would need to send the message ID number on a special channel which allows for non-delivery. And both of them would need to have a special range list to indicate which message numbers were not delivered, so when acks are sent that can be indicated as well. A further problem is that the ack itself can be lost - it is possible that the message can arrive but be discarded, yet the ack is lost. On resend, the resent message would be ignored as duplicate, and you'd never get the discard message either (unless I made a special buffer for that case too). -*/ -// || - // If needs an ack receipt, keep the internal packet around in the list -// internalPacket->reliability == MafiaNet::Reliability::UnreliableWithAckReceipt || -// internalPacket->reliability == UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT - ) - { - internalPacket->messageNumberAssigned=true; - internalPacket->reliableMessageNumber=sendReliableMessageNumberIndex; - internalPacket->retransmissionTime = congestionManager.GetRTOForRetransmission(internalPacket->timesSent+1); - internalPacket->nextActionTime = internalPacket->retransmissionTime+time; -#if CC_TIME_TYPE_BYTES==4 - const CCTimeType threshhold = 10000; -#else - const CCTimeType threshhold = 10000000; -#endif - if (internalPacket->nextActionTime-time > threshhold) - { - // int a=5; - RakAssert(time-internalPacket->nextActionTime < threshhold); - } - //resendTree.Insert( internalPacket->reliableMessageNumber, internalPacket); - if (resendBuffer[internalPacket->reliableMessageNumber & (uint32_t) RESEND_BUFFER_ARRAY_MASK]!=0) - { - // bool overflow = ResendBufferOverflow(); - RakAssert(0); - } - resendBuffer[internalPacket->reliableMessageNumber & (uint32_t) RESEND_BUFFER_ARRAY_MASK] = internalPacket; - statistics.messagesInResendBuffer++; - statistics.bytesInResendBuffer+=BITS_TO_BYTES(internalPacket->dataBitLength); - - // printf("pre:%i ", unacknowledgedBytes); - - InsertPacketIntoResendList( internalPacket, time, true, isReliable); - - - // printf("post:%i ", unacknowledgedBytes); - sendReliableMessageNumberIndex++; - } - else if (internalPacket->reliability == MafiaNet::Reliability::UnreliableWithAckReceipt) - { - unreliableWithAckReceiptHistory.Push(UnreliableWithAckReceiptNode( - congestionManager.GetNextDatagramSequenceNumber() + packetsToSendThisUpdateDatagramBoundaries.Size(), - internalPacket->sendReceiptSerial, - congestionManager.GetRTOForRetransmission(internalPacket->timesSent+1)+time - ), _FILE_AND_LINE_); - } - - // If isReliable is false, the packet and its contents will be added to a list to be freed in ClearPacketsAndDatagrams - // However, the internalPacket structure will remain allocated and be in the resendBuffer list if it requires a receipt - bpsMetrics[(int) USER_MESSAGE_BYTES_SENT].Push1(time,BITS_TO_BYTES(internalPacket->dataBitLength)); - - // Testing1 -// if (internalPacket->reliability==MafiaNet::Reliability::ReliableOrdered || internalPacket->reliability==MafiaNet::Reliability::ReliableOrderedWithAckReceipt) -// printf("SEND reliableMessageNumber %i in datagram %i\n", internalPacket->reliableMessageNumber.val, congestionManager.GetNextDatagramSequenceNumber().val); - - PushPacket(time,internalPacket, isReliable); - internalPacket->timesSent++; - - for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) - { -#if CC_TIME_TYPE_BYTES==4 - messageHandlerList[messageHandlerIndex]->OnInternalPacket(internalPacket, packetsToSendThisUpdateDatagramBoundaries.Size()+congestionManager.GetNextDatagramSequenceNumber(), systemAddress, (MafiaNet::TimeMS)time, true); -#else - messageHandlerList[messageHandlerIndex]->OnInternalPacket(internalPacket, packetsToSendThisUpdateDatagramBoundaries.Size()+congestionManager.GetNextDatagramSequenceNumber(), systemAddress, (MafiaNet::TimeMS)(time/(CCTimeType)1000), true); -#endif - } - pushedAnything=true; - - if (ResendBufferOverflow()) - break; - } - // if (ResendBufferOverflow()) - // break; - // }z - - // No datagrams pushed? - if (datagramSizeSoFar==0) - break; - - // Filled one datagram. - // If the 2nd and it's time to send a datagram pair, will be marked as a pair - PushDatagram(); - } - } - - - for (unsigned int datagramIndex=0; datagramIndex < packetsToSendThisUpdateDatagramBoundaries.Size(); datagramIndex++) - { - if (datagramIndex>0) - dhf.isContinuousSend=true; - MessageNumberNode* messageNumberNode = 0; - dhf.datagramNumber=congestionManager.GetAndIncrementNextDatagramSequenceNumber(); - dhf.isPacketPair=datagramsToSendThisUpdateIsPair[datagramIndex]; - - //printf("%p pushing datagram %i\n", this, dhf.datagramNumber.val); - - bool isSecondOfPacketPair=dhf.isPacketPair && datagramIndex>0 && datagramsToSendThisUpdateIsPair[datagramIndex-1]; - unsigned int msgIndex, msgTerm; - if (datagramIndex==0) - { - msgIndex=0; - msgTerm=packetsToSendThisUpdateDatagramBoundaries[0]; - } - else - { - msgIndex=packetsToSendThisUpdateDatagramBoundaries[datagramIndex-1]; - msgTerm=packetsToSendThisUpdateDatagramBoundaries[datagramIndex]; - } - - // More accurate time to reset here -#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 - dhf.sourceSystemTime= MafiaNet::GetTimeUS(); -#endif - updateBitStream.Reset(); - dhf.Serialize(&updateBitStream); - CC_DEBUG_PRINTF_2("S%i ",dhf.datagramNumber.val); - - while (msgIndex < msgTerm) - { - // If reliable or needs receipt - if ( packetsToSendThisUpdate[msgIndex]->reliability != MafiaNet::Reliability::Unreliable && - packetsToSendThisUpdate[msgIndex]->reliability != MafiaNet::Reliability::UnreliableSequenced - ) - { - if (messageNumberNode==0) - { - messageNumberNode = AddFirstToDatagramHistory(dhf.datagramNumber, packetsToSendThisUpdate[msgIndex]->reliableMessageNumber, time); - } - else - { - messageNumberNode = AddSubsequentToDatagramHistory(messageNumberNode, packetsToSendThisUpdate[msgIndex]->reliableMessageNumber); - } - } - - RakAssert(updateBitStream.GetNumberOfBytesUsed()<=MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE); - WriteToBitStreamFromInternalPacket( &updateBitStream, packetsToSendThisUpdate[msgIndex], time ); - RakAssert(updateBitStream.GetNumberOfBytesUsed()<=MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE); - msgIndex++; - } - - if (isSecondOfPacketPair) - { - // Pad to size of first datagram - RakAssert(updateBitStream.GetNumberOfBytesUsed()<=MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE); - updateBitStream.PadWithZeroToByteLength(datagramSizesInBytes[datagramIndex-1]); - RakAssert(updateBitStream.GetNumberOfBytesUsed()<=MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE); - } - - if (messageNumberNode==0) - { - // Unreliable, add dummy node - AddFirstToDatagramHistory(dhf.datagramNumber, time); - } - - // Store what message ids were sent with this datagram - // datagramMessageIDTree.Insert(dhf.datagramNumber,idList); - - congestionManager.OnSendBytes(time,UDP_HEADER_SIZE+DatagramHeaderFormat::GetDataHeaderByteLength()); - - SendBitStream( s, systemAddress, &updateBitStream, rnr, time ); - - bandwidthExceededStatistic=outgoingPacketBuffer.Size()>0; - // bandwidthExceededStatistic=sendPacketSet[0].IsEmpty()==false || - // sendPacketSet[1].IsEmpty()==false || - // sendPacketSet[2].IsEmpty()==false || - // sendPacketSet[3].IsEmpty()==false; - - - - if (bandwidthExceededStatistic==true) - timeOfLastContinualSend=time; - else - timeOfLastContinualSend=0; - } - - ClearPacketsAndDatagrams(); - - // Any data waiting to send after attempting to send, then bandwidth is exceeded - bandwidthExceededStatistic=outgoingPacketBuffer.Size()>0; - // bandwidthExceededStatistic=sendPacketSet[0].IsEmpty()==false || - // sendPacketSet[1].IsEmpty()==false || - // sendPacketSet[2].IsEmpty()==false || - // sendPacketSet[3].IsEmpty()==false; - } - - - // Keep on top of deleting old unreliable split packets so they don't clog the list. - //DeleteOldUnreliableSplitPackets( time ); -} - -//------------------------------------------------------------------------------------------------------- -// Writes a bitstream to the socket -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::SendBitStream( RakNetSocket2 *s, SystemAddress &systemAddress, MafiaNet::BitStream *bitStream, RakNetRandom *rnr, CCTimeType currentTime) -{ - (void) systemAddress; - (void) rnr; - - unsigned int length; - - length = (unsigned int) bitStream->GetNumberOfBytesUsed(); - - -#ifdef _DEBUG - if (packetloss > 0.0) - { - if (frandomMT() < packetloss) - return; - } - - if (minExtraPing > 0 || extraPingVariance > 0) - { -#ifdef FLIP_SEND_ORDER_TEST - // Flip order of sends without delaying them for testing - DataAndTime *dat = MafiaNet::OP_NEW(__FILE__,__LINE__); - memcpy(dat->data, ( char* ) bitStream->GetData(), length ); - dat->s=s; - dat->length=length; - dat->sendTime = 0; - dat->remotePortRakNetWasStartedOn_PS3=remotePortRakNetWasStartedOn_PS3; - dat->extraSocketOptions=extraSocketOptions; - delayList.PushAtHead(dat, 0, _FILE_AND_LINE_); -#else - MafiaNet::TimeMS delay = minExtraPing; - if (extraPingVariance>0) - delay += (randomMT() % extraPingVariance); - if (delay > 0) - { - DataAndTime *dat = MafiaNet::OP_NEW(__FILE__,__LINE__); - memcpy(dat->data, ( char* ) bitStream->GetData(), length ); - dat->s=s; - dat->length=length; - dat->sendTime = MafiaNet::GetTimeMS() + delay; - for (unsigned int i=0; i < delayList.Size(); i++) - { - if (dat->sendTime < delayList[i]->sendTime) - { - delayList.PushAtHead(dat, i, __FILE__, __LINE__); - dat=0; - break; - } - } - if (dat!=0) - delayList.Push(dat,__FILE__,__LINE__); - return; - } -#endif - } -#endif - -#if LIBCAT_SECURITY==1 - if (useSecurity) - { - unsigned char *buffer = reinterpret_cast( bitStream->GetData() ); - - int buffer_size = bitStream->GetNumberOfBitsAllocated() / 8; - - // Verify there is enough room for encrypted output and encrypt - // Encrypt() will increase length - SLNET_VERIFY(auth_enc.Encrypt(buffer, buffer_size, length)); - } -#endif - - bpsMetrics[(int) ACTUAL_BYTES_SENT].Push1(currentTime,length); - - RakAssert(length <= congestionManager.GetMTU()); - -#ifdef USE_THREADED_SEND - SendToThread::SendToThreadBlock *block = SendToThread::AllocateBlock(); - memcpy(block->data, bitStream->GetData(), length); - block->dataWriteOffset=length; - block->extraSocketOptions=extraSocketOptions; - block->remotePortRakNetWasStartedOn_PS3=remotePortRakNetWasStartedOn_PS3; - block->s=s; - block->systemAddress=systemAddress; - SendToThread::ProcessBlock(block); -#else - // SocketLayer::SendTo( s, ( char* ) bitStream->GetData(), length, systemAddress, __FILE__, __LINE__ ); - - RNS2_SendParameters bsp; - bsp.data = (char*) bitStream->GetData(); - bsp.length = length; - bsp.systemAddress = systemAddress; - s->Send(&bsp, _FILE_AND_LINE_); -#endif -} - -//------------------------------------------------------------------------------------------------------- -// Are we waiting for any data to be sent out or be processed by the player? -//------------------------------------------------------------------------------------------------------- -bool ReliabilityLayer::IsOutgoingDataWaiting(void) -{ - if (outgoingPacketBuffer.Size()>0) - return true; - - // unsigned i; - // for ( i = 0; i < MafiaNet::NUMBER_OF_PRIORITIES; i++ ) - // { - // if (sendPacketSet[ i ].Size() > 0) - // return true; - // } - - return - //acknowlegements.Size() > 0 || - //resendTree.IsEmpty()==false;// || outputQueue.Size() > 0 || orderingList.Size() > 0 || splitPacketChannelList.Size() > 0; - statistics.messagesInResendBuffer!=0; -} -bool ReliabilityLayer::AreAcksWaiting(void) -{ - return acknowlegements.Size() > 0; -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::ApplyNetworkSimulator( double _packetloss, MafiaNet::TimeMS _minExtraPing, MafiaNet::TimeMS _extraPingVariance ) -{ -#ifndef _DEBUG - // unused parameters - (void)_packetloss; - (void)_minExtraPing; - (void)_extraPingVariance; -#endif - -#ifdef _DEBUG - packetloss=_packetloss; - minExtraPing=_minExtraPing; - extraPingVariance=_extraPingVariance; - // if (ping < (unsigned int)(minExtraPing+extraPingVariance)*2) - // ping=(minExtraPing+extraPingVariance)*2; -#endif -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::SetSplitMessageProgressInterval(int interval) -{ - splitMessageProgressInterval=interval; -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::SetUnreliableTimeout(MafiaNet::TimeMS timeoutMS) -{ -#if CC_TIME_TYPE_BYTES==4 - unreliableTimeout=timeoutMS; -#else - unreliableTimeout=(CCTimeType)timeoutMS*(CCTimeType)1000; -#endif -} - -//------------------------------------------------------------------------------------------------------- -// This will return true if we should not send at this time -//------------------------------------------------------------------------------------------------------- -bool ReliabilityLayer::IsSendThrottled( int MTUSize ) -{ - (void) MTUSize; - - return false; - // return resendList.Size() > windowSize; - - // Disabling this, because it can get stuck here forever - /* - unsigned packetsWaiting; - unsigned resendListDataSize=0; - unsigned i; - for (i=0; i < resendList.Size(); i++) - { - if (resendList[i]) - resendListDataSize+=resendList[i]->dataBitLength; - } - packetsWaiting = 1 + ((BITS_TO_BYTES(resendListDataSize)) / (MTUSize - UDP_HEADER_SIZE - 10)); // 10 to roughly estimate the raknet header - - return packetsWaiting >= windowSize; - */ -} - -//------------------------------------------------------------------------------------------------------- -// We lost a packet -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::UpdateWindowFromPacketloss( CCTimeType time ) -{ - (void) time; -} - -//------------------------------------------------------------------------------------------------------- -// Increase the window size -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::UpdateWindowFromAck( CCTimeType time ) -{ - (void) time; -} - -//------------------------------------------------------------------------------------------------------- -// Does what the function name says -//------------------------------------------------------------------------------------------------------- -unsigned ReliabilityLayer::RemovePacketFromResendListAndDeleteOlderReliableSequenced( const MessageNumberType messageNumber, CCTimeType time, DataStructures::List &messageHandlerList, const SystemAddress &systemAddress ) -{ - (void) time; - (void) messageNumber; - InternalPacket * internalPacket; - //InternalPacket *temp; -// MafiaNet::Reliability reliability; // What type of reliability algorithm to use with this packet -// unsigned char orderingChannel; // What ordering channel this packet is on, if the reliability type uses ordering channels -// OrderingIndexType orderingIndex; // The ID used as identification for ordering channels - // unsigned j; - - for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) - { -#if CC_TIME_TYPE_BYTES==4 - messageHandlerList[messageHandlerIndex]->OnAck(messageNumber, systemAddress, time); -#else - messageHandlerList[messageHandlerIndex]->OnAck(messageNumber, systemAddress, (MafiaNet::TimeMS)(time/(CCTimeType)1000)); -#endif - } - - // Testing1 -// if (resendLinkedListHead) -// { -// InternalPacket *internalPacket = resendLinkedListHead; -// do -// { -// internalPacket=internalPacket->resendNext; -// printf("%i ", internalPacket->reliableMessageNumber.val); -// } while (internalPacket!=resendLinkedListHead); -// printf("\n"); -// } - - // bool deleted; - // deleted=resendTree.Delete(messageNumber, internalPacket); - internalPacket = resendBuffer[messageNumber & RESEND_BUFFER_ARRAY_MASK]; - // May ask to remove twice, for example resend twice, then second ack - if (internalPacket && internalPacket->reliableMessageNumber==messageNumber) - { - // ValidateResendList(); - resendBuffer[messageNumber & RESEND_BUFFER_ARRAY_MASK]=0; - CC_DEBUG_PRINTF_2("AckRcv %i ", messageNumber); - - statistics.messagesInResendBuffer--; - statistics.bytesInResendBuffer-=BITS_TO_BYTES(internalPacket->dataBitLength); - -// orderingIndex = internalPacket->orderingIndex; - totalUserDataBytesAcked+=(double) BITS_TO_BYTES(internalPacket->headerLength+internalPacket->dataBitLength); - - // Return receipt if asked for - if (internalPacket->reliability>=MafiaNet::Reliability::ReliableWithAckReceipt && - (internalPacket->splitPacketCount==0 || internalPacket->splitPacketIndex+1==internalPacket->splitPacketCount) - ) - { - InternalPacket *ackReceipt = AllocateFromInternalPacketPool(); - AllocInternalPacketData(ackReceipt, 5, false, _FILE_AND_LINE_ ); - ackReceipt->dataBitLength=BYTES_TO_BITS(5); - ackReceipt->data[0]=(MessageID)ID_SND_RECEIPT_ACKED; - memcpy(ackReceipt->data+sizeof(MessageID), &internalPacket->sendReceiptSerial, sizeof(internalPacket->sendReceiptSerial)); - outputQueue.Push(ackReceipt, _FILE_AND_LINE_ ); - } - - bool isReliable; - if ( internalPacket->reliability == MafiaNet::Reliability::Reliable || - internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrdered || - internalPacket->reliability == MafiaNet::Reliability::ReliableWithAckReceipt || -// internalPacket->reliability == RELIABLE_SEQUENCED_WITH_ACK_RECEIPT || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrderedWithAckReceipt - ) - isReliable = true; - else - isReliable = false; - - RemoveFromList(internalPacket, isReliable); - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); - ReleaseToInternalPacketPool( internalPacket ); - - - return 0; - } - else - { - - } - - return (unsigned)-1; -} - -//------------------------------------------------------------------------------------------------------- -// Acknowledge receipt of the packet with the specified messageNumber -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::SendAcknowledgementPacket( const DatagramSequenceNumberType messageNumber, CCTimeType time ) -{ - - // REMOVEME - // printf("%p Send ack %i\n", this, messageNumber.val); - - nextAckTimeToSend=time; - acknowlegements.Insert(messageNumber); - - //printf("ACK_DG:%i ", messageNumber.val); - - CC_DEBUG_PRINTF_2("AckPush %i ", messageNumber); - -} - -//------------------------------------------------------------------------------------------------------- -// Parse an internalPacket and figure out how many header bits would be -// written. Returns that number -//------------------------------------------------------------------------------------------------------- -BitSize_t ReliabilityLayer::GetMaxMessageHeaderLengthBits( void ) -{ - InternalPacket ip; - ip.reliability=MafiaNet::Reliability::ReliableSequenced; - ip.splitPacketCount=1; - return GetMessageHeaderLengthBits(&ip); -} -//------------------------------------------------------------------------------------------------------- -BitSize_t ReliabilityLayer::GetMessageHeaderLengthBits( const InternalPacket *const internalPacket ) -{ - BitSize_t bitLength; - - // bitStream->AlignWriteToByteBoundary(); // Potentially unaligned - // tempChar=(unsigned char)internalPacket->reliability; bitStream->WriteBits( (const unsigned char *)&tempChar, 3, true ); // 3 bits to write reliability. - // bool hasSplitPacket = internalPacket->splitPacketCount>0; bitStream->Write(hasSplitPacket); // Write 1 bit to indicate if splitPacketCount>0 - bitLength = 8*1; - - // bitStream->AlignWriteToByteBoundary(); - // RakAssert(internalPacket->dataBitLength < 65535); - // unsigned short s; s = (unsigned short) internalPacket->dataBitLength; bitStream->WriteAlignedVar16((const char*)& s); - bitLength += 8*2; - - if ( internalPacket->reliability == MafiaNet::Reliability::Reliable || - internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrdered || - internalPacket->reliability == MafiaNet::Reliability::ReliableWithAckReceipt || -// internalPacket->reliability == RELIABLE_SEQUENCED_WITH_ACK_RECEIPT || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrderedWithAckReceipt - ) - bitLength += 8*3; // bitStream->Write(internalPacket->reliableMessageNumber); // Message sequence number - // bitStream->AlignWriteToByteBoundary(); // Potentially nothing else to write - - - - if ( internalPacket->reliability == MafiaNet::Reliability::UnreliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced - ) - { - bitLength += 8*3;; // bitStream->Write(internalPacket->_sequencingIndex); // Used for MafiaNet::Reliability::UnreliableSequenced, MafiaNet::Reliability::ReliableSequenced, MafiaNet::Reliability::ReliableOrdered. - } - - if ( internalPacket->reliability == MafiaNet::Reliability::UnreliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrdered || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrderedWithAckReceipt - ) - { - bitLength += 8*3; // bitStream->Write(internalPacket->orderingIndex); // Used for MafiaNet::Reliability::UnreliableSequenced, MafiaNet::Reliability::ReliableSequenced, MafiaNet::Reliability::ReliableOrdered. - bitLength += 8*1; // tempChar=internalPacket->orderingChannel; bitStream->WriteAlignedVar8((const char*)& tempChar); // Used for MafiaNet::Reliability::UnreliableSequenced, MafiaNet::Reliability::ReliableSequenced, MafiaNet::Reliability::ReliableOrdered. 5 bits needed, write one byte - } - if (internalPacket->splitPacketCount>0) - { - bitLength += 8*4; // bitStream->WriteAlignedVar32((const char*)& internalPacket->splitPacketCount); RakAssert(sizeof(SplitPacketIndexType)==4); // Only needed if splitPacketCount>0. 4 bytes - bitLength += 8*sizeof(SplitPacketIdType); // bitStream->WriteAlignedVar16((const char*)& internalPacket->splitPacketId); RakAssert(sizeof(SplitPacketIdType)==2); // Only needed if splitPacketCount>0. - bitLength += 8*4; // bitStream->WriteAlignedVar32((const char*)& internalPacket->splitPacketIndex); // Only needed if splitPacketCount>0. 4 bytes - } - - return bitLength; -} - -//------------------------------------------------------------------------------------------------------- -// Parse an internalPacket and create a bitstream to represent this data -//------------------------------------------------------------------------------------------------------- -BitSize_t ReliabilityLayer::WriteToBitStreamFromInternalPacket(MafiaNet::BitStream *bitStream, const InternalPacket *const internalPacket, CCTimeType curTime ) -{ - (void) curTime; - - BitSize_t start = bitStream->GetNumberOfBitsUsed(); - unsigned char tempChar; - - // (Incoming data may be all zeros due to padding) - bitStream->AlignWriteToByteBoundary(); // Potentially unaligned - if (internalPacket->reliability==MafiaNet::Reliability::UnreliableWithAckReceipt) - tempChar=(unsigned char)MafiaNet::Reliability::Unreliable; - else if (internalPacket->reliability==MafiaNet::Reliability::ReliableWithAckReceipt) - tempChar=(unsigned char)MafiaNet::Reliability::Reliable; - else if (internalPacket->reliability==MafiaNet::Reliability::ReliableOrderedWithAckReceipt) - tempChar=(unsigned char)MafiaNet::Reliability::ReliableOrdered; - else - tempChar=(unsigned char)internalPacket->reliability; - - bitStream->WriteBits( (const unsigned char *)&tempChar, 3, true ); // 3 bits to write reliability. - - bool hasSplitPacket = internalPacket->splitPacketCount>0; bitStream->Write(hasSplitPacket); // Write 1 bit to indicate if splitPacketCount>0 - bitStream->AlignWriteToByteBoundary(); - RakAssert(internalPacket->dataBitLength < 65535); - unsigned short s; s = (unsigned short) internalPacket->dataBitLength; bitStream->WriteAlignedVar16((const char*)& s); - if ( internalPacket->reliability == MafiaNet::Reliability::Reliable || - internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrdered || - internalPacket->reliability == MafiaNet::Reliability::ReliableWithAckReceipt || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrderedWithAckReceipt - ) - bitStream->Write(internalPacket->reliableMessageNumber); // Used for all reliable types - bitStream->AlignWriteToByteBoundary(); // Potentially nothing else to write - - if ( internalPacket->reliability == MafiaNet::Reliability::UnreliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced - ) - { - bitStream->Write(internalPacket->sequencingIndex); // Used for MafiaNet::Reliability::UnreliableSequenced, MafiaNet::Reliability::ReliableSequenced, MafiaNet::Reliability::ReliableOrdered. - } - - if ( internalPacket->reliability == MafiaNet::Reliability::UnreliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrdered || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrderedWithAckReceipt - ) - { - bitStream->Write(internalPacket->orderingIndex); // Used for MafiaNet::Reliability::UnreliableSequenced, MafiaNet::Reliability::ReliableSequenced, MafiaNet::Reliability::ReliableOrdered. - tempChar=internalPacket->orderingChannel; bitStream->WriteAlignedVar8((const char*)& tempChar); // Used for MafiaNet::Reliability::UnreliableSequenced, MafiaNet::Reliability::ReliableSequenced, MafiaNet::Reliability::ReliableOrdered. 5 bits needed, write one byte - } - - if (internalPacket->splitPacketCount>0) - { - // printf("Write before\n"); - // bitStream->PrintBits(); - - bitStream->WriteAlignedVar32((const char*)& internalPacket->splitPacketCount); RakAssert(sizeof(SplitPacketIndexType)==4); // Only needed if splitPacketCount>0. 4 bytes - bitStream->WriteAlignedVar16((const char*)& internalPacket->splitPacketId); RakAssert(sizeof(SplitPacketIdType)==2); // Only needed if splitPacketCount>0. - bitStream->WriteAlignedVar32((const char*)& internalPacket->splitPacketIndex); // Only needed if splitPacketCount>0. 4 bytes - - // printf("Write after\n"); - // bitStream->PrintBits(); - } - - // Write the actual data. - bitStream->WriteAlignedBytes( ( unsigned char* ) internalPacket->data, BITS_TO_BYTES( internalPacket->dataBitLength ) ); - - return bitStream->GetNumberOfBitsUsed() - start; -} - -//------------------------------------------------------------------------------------------------------- -// Parse a bitstream and create an internal packet to represent this data -//------------------------------------------------------------------------------------------------------- -InternalPacket* ReliabilityLayer::CreateInternalPacketFromBitStream(MafiaNet::BitStream *bitStream, CCTimeType time ) -{ - bool bitStreamSucceeded; - InternalPacket* internalPacket; - unsigned char tempChar; - bool hasSplitPacket=false; - bool readSuccess; - - if ( bitStream->GetNumberOfUnreadBits() < (int) sizeof( internalPacket->reliableMessageNumber ) * 8 ) - return 0; // leftover bits - - internalPacket = AllocateFromInternalPacketPool(); - if (internalPacket==0) - { - // Out of memory - RakAssert(0); - return 0; - } - internalPacket->creationTime = time; - - // (Incoming data may be all zeros due to padding) - bitStream->AlignReadToByteBoundary(); // Potentially unaligned - bitStream->ReadBits( ( unsigned char* ) ( &( tempChar ) ), 3 ); - internalPacket->reliability = ( const MafiaNet::Reliability ) tempChar; - readSuccess=bitStream->Read(hasSplitPacket); // Read 1 bit to indicate if splitPacketCount>0 - bitStream->AlignReadToByteBoundary(); - unsigned short s; bitStream->ReadAlignedVar16((char*)&s); internalPacket->dataBitLength=s; // Length of message (2 bytes) - if ( internalPacket->reliability == MafiaNet::Reliability::Reliable || - internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrdered - // I don't write ACK_RECEIPT to the remote system -// || -// internalPacket->reliability == MafiaNet::Reliability::ReliableWithAckReceipt || -// internalPacket->reliability == RELIABLE_SEQUENCED_WITH_ACK_RECEIPT || -// internalPacket->reliability == MafiaNet::Reliability::ReliableOrderedWithAckReceipt - ) - bitStream->Read(internalPacket->reliableMessageNumber); // Message sequence number - else - internalPacket->reliableMessageNumber=(MessageNumberType)(const uint32_t)-1; - bitStream->AlignReadToByteBoundary(); // Potentially nothing else to Read - - if ( internalPacket->reliability == MafiaNet::Reliability::UnreliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced - ) - { - bitStream->Read(internalPacket->sequencingIndex); // Used for MafiaNet::Reliability::UnreliableSequenced, MafiaNet::Reliability::ReliableSequenced, MafiaNet::Reliability::ReliableOrdered. - } - - if ( internalPacket->reliability == MafiaNet::Reliability::UnreliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableSequenced || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrdered || - internalPacket->reliability == MafiaNet::Reliability::ReliableOrderedWithAckReceipt - ) - { - bitStream->Read(internalPacket->orderingIndex); // Used for MafiaNet::Reliability::UnreliableSequenced, MafiaNet::Reliability::ReliableSequenced, MafiaNet::Reliability::ReliableOrdered. 4 bytes. - readSuccess=bitStream->ReadAlignedVar8((char*)& internalPacket->orderingChannel); // Used for MafiaNet::Reliability::UnreliableSequenced, MafiaNet::Reliability::ReliableSequenced, MafiaNet::Reliability::ReliableOrdered. 5 bits needed, Read one byte - } - else - internalPacket->orderingChannel=0; - - if (hasSplitPacket) - { -// printf("Read before\n"); -// bitStream->PrintBits(); - - bitStream->ReadAlignedVar32((char*)& internalPacket->splitPacketCount); // Only needed if splitPacketCount>0. 4 bytes - bitStream->ReadAlignedVar16((char*)& internalPacket->splitPacketId); // Only needed if splitPacketCount>0. - readSuccess=bitStream->ReadAlignedVar32((char*)& internalPacket->splitPacketIndex); // Only needed if splitPacketCount>0. 4 bytes - RakAssert(readSuccess); - -// printf("Read after\n"); -// bitStream->PrintBits(); - } - else - { - internalPacket->splitPacketCount=0; - } - - if (readSuccess==false || - internalPacket->dataBitLength==0 || - (unsigned int)internalPacket->reliability>=MafiaNet::NUMBER_OF_RELIABILITIES || - internalPacket->orderingChannel>=32 || - (hasSplitPacket && (internalPacket->splitPacketIndex >= internalPacket->splitPacketCount))) - { - // If this assert hits, encoding is garbage - RakAssert("Encoding is garbage" && 0); - ReleaseToInternalPacketPool( internalPacket ); - return 0; - } - - // Allocate memory to hold our data - AllocInternalPacketData(internalPacket, BITS_TO_BYTES( internalPacket->dataBitLength ), false, _FILE_AND_LINE_ ); - RakAssert(BITS_TO_BYTES( internalPacket->dataBitLength )data == 0) - { - RakAssert("Out of memory in ReliabilityLayer::CreateInternalPacketFromBitStream" && 0); - notifyOutOfMemory(_FILE_AND_LINE_); - ReleaseToInternalPacketPool( internalPacket ); - return 0; - } - - // Set the last byte to 0 so if ReadBits does not read a multiple of 8 the last bits are 0'ed out - internalPacket->data[ BITS_TO_BYTES( internalPacket->dataBitLength ) - 1 ] = 0; - - // Read the data the packet holds - bitStreamSucceeded = bitStream->ReadAlignedBytes( ( unsigned char* ) internalPacket->data, BITS_TO_BYTES( internalPacket->dataBitLength ) ); - - if ( bitStreamSucceeded == false ) - { - // If this hits, most likely the variable buff is too small in RunUpdateCycle in RakPeer.cpp - RakAssert("Couldn't read all the data" && 0); - - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); - ReleaseToInternalPacketPool( internalPacket ); - return 0; - } - - return internalPacket; -} - - -//------------------------------------------------------------------------------------------------------- -// Get the SHA1 code -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::GetSHA1( unsigned char * const buffer, unsigned int - nbytes, char code[ SHA1_LENGTH ] ) -{ - CSHA1 sha1; - - sha1.Reset(); - sha1.Update( ( unsigned char* ) buffer, nbytes ); - sha1.Final(); - memcpy( code, sha1.GetHash(), SHA1_LENGTH ); -} - -//------------------------------------------------------------------------------------------------------- -// Check the SHA1 code -//------------------------------------------------------------------------------------------------------- -bool ReliabilityLayer::CheckSHA1( char code[ SHA1_LENGTH ], unsigned char * - const buffer, unsigned int nbytes ) -{ - char code2[ SHA1_LENGTH ]; - GetSHA1( buffer, nbytes, code2 ); - - for ( int i = 0; i < SHA1_LENGTH; i++ ) - if ( code[ i ] != code2[ i ] ) - return false; - - return true; -} - -/* -//------------------------------------------------------------------------------------------------------- -// Search the specified list for sequenced packets on the specified ordering -// stream, optionally skipping those with splitPacketId, and delete them -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::DeleteSequencedPacketsInList( unsigned char orderingChannel, DataStructures::List&theList, int splitPacketId ) -{ - unsigned i = 0; - - while ( i < theList.Size() ) - { - if ( ( - theList[ i ]->reliability == MafiaNet::Reliability::ReliableSequenced || - theList[ i ]->reliability == MafiaNet::Reliability::UnreliableSequenced -// || -// theList[ i ]->reliability == RELIABLE_SEQUENCED_WITH_ACK_RECEIPT || -// theList[ i ]->reliability == UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT - ) && - theList[ i ]->orderingChannel == orderingChannel && ( splitPacketId == -1 || theList[ i ]->splitPacketId != (unsigned int) splitPacketId ) ) - { - InternalPacket * internalPacket = theList[ i ]; - theList.RemoveAtIndex( i ); - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); - ReleaseToInternalPacketPool( internalPacket ); - } - - else - i++; - } -} - -//------------------------------------------------------------------------------------------------------- -// Search the specified list for sequenced packets with a value less than orderingIndex and delete them -// Note - I added functionality so you can use the Queue as a list (in this case for searching) but it is less efficient to do so than a regular list -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::DeleteSequencedPacketsInList( unsigned char orderingChannel, DataStructures::Queue&theList ) -{ - InternalPacket * internalPacket; - int listSize = theList.Size(); - int i = 0; - - while ( i < listSize ) - { - if ( ( - theList[ i ]->reliability == MafiaNet::Reliability::ReliableSequenced || - theList[ i ]->reliability == MafiaNet::Reliability::UnreliableSequenced -// || -// theList[ i ]->reliability == RELIABLE_SEQUENCED_WITH_ACK_RECEIPT || -// theList[ i ]->reliability == UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT - ) && theList[ i ]->orderingChannel == orderingChannel ) - { - internalPacket = theList[ i ]; - theList.RemoveAtIndex( i ); - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); - ReleaseToInternalPacketPool( internalPacket ); - listSize--; - } - - else - i++; - } -} -*/ - -//------------------------------------------------------------------------------------------------------- -// Returns true if newPacketOrderingIndex is older than the waitingForPacketOrderingIndex -//------------------------------------------------------------------------------------------------------- -bool ReliabilityLayer::IsOlderOrderedPacket( OrderingIndexType newPacketOrderingIndex, OrderingIndexType waitingForPacketOrderingIndex ) -{ - OrderingIndexType maxRange = (OrderingIndexType) (const uint32_t)-1; - - if ( waitingForPacketOrderingIndex > maxRange/(OrderingIndexType)2 ) - { - if ( newPacketOrderingIndex >= waitingForPacketOrderingIndex - maxRange/(OrderingIndexType)2+(OrderingIndexType)1 && newPacketOrderingIndex < waitingForPacketOrderingIndex ) - { - return true; - } - } - - else - if ( newPacketOrderingIndex >= ( OrderingIndexType ) ( waitingForPacketOrderingIndex - (( OrderingIndexType ) maxRange/(OrderingIndexType)2+(OrderingIndexType)1) ) || - newPacketOrderingIndex < waitingForPacketOrderingIndex ) - { - return true; - } - - // Old packet - return false; -} - -//------------------------------------------------------------------------------------------------------- -// Split the passed packet into chunks under MTU_SIZEbytes (including headers) and save those new chunks -// Optimized version -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::SplitPacket( InternalPacket *internalPacket ) -{ - // Doing all sizes in bytes in this function so I don't write partial bytes with split packets - internalPacket->splitPacketCount = 1; // This causes GetMessageHeaderLengthBits to account for the split packet header - unsigned int headerLength = (unsigned int) BITS_TO_BYTES( GetMessageHeaderLengthBits( internalPacket ) ); - unsigned int dataByteLength = (unsigned int) BITS_TO_BYTES( internalPacket->dataBitLength ); - int maximumSendBlockBytes, byteOffset, bytesToSend; - SplitPacketIndexType splitPacketIndex; - int i; - InternalPacket **internalPacketArray; - - maximumSendBlockBytes = GetMaxDatagramSizeExcludingMessageHeaderBytes() - BITS_TO_BYTES(GetMaxMessageHeaderLengthBits()); - - // Calculate how many packets we need to create - internalPacket->splitPacketCount = ( ( dataByteLength - 1 ) / ( maximumSendBlockBytes ) + 1 ); - - // Optimization - // internalPacketArray = MafiaNet::OP_NEW(internalPacket->splitPacketCount, _FILE_AND_LINE_ ); - bool usedAlloca=false; -#if USE_ALLOCA==1 - if (sizeof( InternalPacket* ) * internalPacket->splitPacketCount < MAX_ALLOCA_STACK_ALLOCATION) - { - internalPacketArray = ( InternalPacket** ) alloca( sizeof( InternalPacket* ) * internalPacket->splitPacketCount ); - usedAlloca=true; - } - else -#endif - internalPacketArray = (InternalPacket**) rakMalloc_Ex( sizeof(InternalPacket*) * internalPacket->splitPacketCount, _FILE_AND_LINE_ ); - - for ( i = 0; i < ( int ) internalPacket->splitPacketCount; i++ ) - { - internalPacketArray[ i ] = AllocateFromInternalPacketPool(); - - //internalPacketArray[ i ] = (InternalPacket*) alloca( sizeof( InternalPacket ) ); - // internalPacketArray[ i ] = sendPacketSet[internalPacket->priority].WriteLock(); - *internalPacketArray[ i ]=*internalPacket; - internalPacketArray[ i ]->messageNumberAssigned=false; - - if (i!=0) - internalPacket->messageInternalOrder = internalOrderIndex++; - } - - // This identifies which packet this is in the set - splitPacketIndex = 0; - - InternalPacketRefCountedData *refCounter=0; - - // Do a loop to send out all the packets - do - { - byteOffset = splitPacketIndex * maximumSendBlockBytes; - bytesToSend = dataByteLength - byteOffset; - - if ( bytesToSend > maximumSendBlockBytes ) - bytesToSend = maximumSendBlockBytes; - - // Copy over our chunk of data - - AllocInternalPacketData(internalPacketArray[ splitPacketIndex ], &refCounter, internalPacket->data, internalPacket->data + byteOffset); - // internalPacketArray[ splitPacketIndex ]->data = (unsigned char*) rakMalloc_Ex( bytesToSend, _FILE_AND_LINE_ ); - // memcpy( internalPacketArray[ splitPacketIndex ]->data, internalPacket->data + byteOffset, bytesToSend ); - - if ( bytesToSend != maximumSendBlockBytes ) - internalPacketArray[ splitPacketIndex ]->dataBitLength = internalPacket->dataBitLength - splitPacketIndex * ( maximumSendBlockBytes << 3 ); - else - internalPacketArray[ splitPacketIndex ]->dataBitLength = bytesToSend << 3; - - internalPacketArray[ splitPacketIndex ]->splitPacketIndex = splitPacketIndex; - internalPacketArray[ splitPacketIndex ]->splitPacketId = splitPacketId; - internalPacketArray[ splitPacketIndex ]->splitPacketCount = internalPacket->splitPacketCount; - RakAssert(internalPacketArray[ splitPacketIndex ]->dataBitLengthsplitPacketCount ); - - splitPacketId++; // It's ok if this wraps to 0 - - // InternalPacket *workingPacket; - - // Tell the heap we are going to push a list of elements where each element in the list follows the heap order - RakAssert(outgoingPacketBuffer.Size()==0 || outgoingPacketBuffer.Peek()->dataBitLengthsplitPacketCount; i++ ) - { - internalPacketArray[ i ]->headerLength=headerLength; - RakAssert(internalPacketArray[ i ]->dataBitLengthpriority ].Push( internalPacketArray[ i ], _FILE_AND_LINE_ ); - RakAssert(internalPacketArray[ i ]->dataBitLengthmessageNumberAssigned==false); - outgoingPacketBuffer.PushSeries(GetNextWeight((int)internalPacketArray[ i ]->priority), internalPacketArray[ i ], _FILE_AND_LINE_); - RakAssert(outgoingPacketBuffer.Size()==0 || outgoingPacketBuffer.Peek()->dataBitLengthpriority]++; - statistics.bytesInSendBuffer[(int)(int)internalPacketArray[ i ]->priority]+=(double) BITS_TO_BYTES(internalPacketArray[ i ]->dataBitLength); - // workingPacket=sendPacketSet[internalPacket->priority].WriteLock(); - // memcpy(workingPacket, internalPacketArray[ i ], sizeof(InternalPacket)); - // sendPacketSet[internalPacket->priority].WriteUnlock(); - } - - // Do not delete, original is referenced by all split packets to avoid numerous allocations. See AllocInternalPacketData above - // FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); - ReleaseToInternalPacketPool( internalPacket ); - - if (usedAlloca==false) - rakFree_Ex(internalPacketArray, _FILE_AND_LINE_ ); -} - -//------------------------------------------------------------------------------------------------------- -// Insert a packet into the split packet list -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::InsertIntoSplitPacketList( InternalPacket * internalPacket, CCTimeType time ) -{ - bool objectExists; - unsigned index; - // Find in splitPacketChannelList if a SplitPacketChannel with this splitPacketId was already allocated. If not, allocate and insert the channel into the list. - index=splitPacketChannelList.GetIndexFromKey(internalPacket->splitPacketId, &objectExists); - if (objectExists==false) - { - SplitPacketChannel *newChannel = MafiaNet::OP_NEW( __FILE__, __LINE__ ); -#if PREALLOCATE_LARGE_MESSAGES==1 - index=splitPacketChannelList.Insert(internalPacket->splitPacketId, newChannel, true, __FILE__,__LINE__); - newChannel->returnedPacket=CreateInternalPacketCopy( internalPacket, 0, 0, time ); - newChannel->gotFirstPacket=false; - newChannel->splitPacketsArrived=0; - AllocInternalPacketData(newChannel->returnedPacket, BITS_TO_BYTES( internalPacket->dataBitLength*internalPacket->splitPacketCount ), false, __FILE__, __LINE__ ); - RakAssert(newChannel->returnedPacket->data); -#else - newChannel->firstPacket=0; - index=splitPacketChannelList.Insert(internalPacket->splitPacketId, newChannel, true, __FILE__,__LINE__); - // Preallocate to the final size, to avoid runtime copies - newChannel->splitPacketList.Preallocate(internalPacket, __FILE__,__LINE__); - -#endif - } - -#if PREALLOCATE_LARGE_MESSAGES==1 - splitPacketChannelList[index]->lastUpdateTime=time; - splitPacketChannelList[index]->splitPacketsArrived++; - splitPacketChannelList[index]->returnedPacket->dataBitLength+=internalPacket->dataBitLength; - - bool dealloc; - if (internalPacket->splitPacketIndex==0) - { - splitPacketChannelList[index]->gotFirstPacket=true; - splitPacketChannelList[index]->stride=BITS_TO_BYTES(internalPacket->dataBitLength); - - for (unsigned int j=0; j < splitPacketChannelList[index]->splitPacketList.Size(); j++) - { - memcpy(splitPacketChannelList[index]->returnedPacket->data+internalPacket->splitPacketIndex*splitPacketChannelList[index]->stride, internalPacket->data, (size_t) BITS_TO_BYTES(internalPacket->dataBitLength)); - FreeInternalPacketData(splitPacketChannelList[index]->splitPacketList[j], __FILE__, __LINE__ ); - ReleaseToInternalPacketPool(splitPacketChannelList[index]->splitPacketList[j]); - } - - memcpy(splitPacketChannelList[index]->returnedPacket->data, internalPacket->data, (size_t) BITS_TO_BYTES(internalPacket->dataBitLength)); - splitPacketChannelList[index]->splitPacketList.Clear(true,__FILE__,__LINE__); - dealloc=true; - } - else - { - if (splitPacketChannelList[index]->gotFirstPacket==true) - { - memcpy(splitPacketChannelList[index]->returnedPacket->data+internalPacket->splitPacketIndex*splitPacketChannelList[index]->stride, internalPacket->data, (size_t) BITS_TO_BYTES(internalPacket->dataBitLength)); - dealloc=true; - } - else - { - splitPacketChannelList[index]->splitPacketList.Push(internalPacket,__FILE__,__LINE__); - dealloc=false; - } - } - - if (splitPacketChannelList[index]->gotFirstPacket==true && - splitMessageProgressInterval && - // splitPacketChannelList[index]->firstPacket && - // splitPacketChannelList[index]->splitPacketList.Size()!=splitPacketChannelList[index]->firstPacket->splitPacketCount && - // (splitPacketChannelList[index]->splitPacketList.Size()%splitMessageProgressInterval)==0 - splitPacketChannelList[index]->gotFirstPacket && - splitPacketChannelList[index]->splitPacketsArrived!=splitPacketChannelList[index]->returnedPacket->splitPacketCount && - (splitPacketChannelList[index]->splitPacketsArrived%splitMessageProgressInterval)==0 - ) - { - // Return ID_DOWNLOAD_PROGRESS - // Write splitPacketIndex (SplitPacketIndexType) - // Write splitPacketCount (SplitPacketIndexType) - // Write byteLength (4) - // Write data, splitPacketChannelList[index]->splitPacketList[0]->data - InternalPacket *progressIndicator = AllocateFromInternalPacketPool(); - // unsigned int len = sizeof(MessageID) + sizeof(unsigned int)*2 + sizeof(unsigned int) + (unsigned int) BITS_TO_BYTES(splitPacketChannelList[index]->firstPacket->dataBitLength); - unsigned int l = (unsigned int) splitPacketChannelList[index]->stride; - const unsigned int len = sizeof(MessageID) + sizeof(unsigned int)*2 + sizeof(unsigned int) + l; - AllocInternalPacketData(progressIndicator, len, false, __FILE__, __LINE__ ); - progressIndicator->dataBitLength=BYTES_TO_BITS(len); - progressIndicator->data[0]=(MessageID)ID_DOWNLOAD_PROGRESS; - unsigned int temp; - // temp=splitPacketChannelList[index]->splitPacketList.Size(); - temp=splitPacketChannelList[index]->splitPacketsArrived; - memcpy(progressIndicator->data+sizeof(MessageID), &temp, sizeof(unsigned int)); - temp=(unsigned int)internalPacket->splitPacketCount; - memcpy(progressIndicator->data+sizeof(MessageID)+sizeof(unsigned int)*1, &temp, sizeof(unsigned int)); - // temp=(unsigned int) BITS_TO_BYTES(splitPacketChannelList[index]->firstPacket->dataBitLength); - temp=(unsigned int) BITS_TO_BYTES(l); - memcpy(progressIndicator->data+sizeof(MessageID)+sizeof(unsigned int)*2, &temp, sizeof(unsigned int)); - //memcpy(progressIndicator->data+sizeof(MessageID)+sizeof(unsigned int)*3, splitPacketChannelList[index]->firstPacket->data, (size_t) BITS_TO_BYTES(splitPacketChannelList[index]->firstPacket->dataBitLength)); - memcpy(progressIndicator->data+sizeof(MessageID)+sizeof(unsigned int)*3, splitPacketChannelList[index]->returnedPacket->data, (size_t) BITS_TO_BYTES(l)); - } - - if (dealloc) - { - FreeInternalPacketData(internalPacket, __FILE__, __LINE__ ); - ReleaseToInternalPacketPool(internalPacket); - } -#else - // Insert the packet into the SplitPacketChannel - if (!splitPacketChannelList[index]->splitPacketList.Add(internalPacket)) { - FreeInternalPacketData(internalPacket, _FILE_AND_LINE_); - ReleaseToInternalPacketPool(internalPacket); - return; - } - - splitPacketChannelList[index]->lastUpdateTime=time; - - // If the index is 0, then this is the first packet. Record this so it can be returned to the user with download progress - if (internalPacket->splitPacketIndex==0) - splitPacketChannelList[index]->firstPacket=internalPacket; - - // Return download progress if we have the first packet, the list is not complete, and there are enough packets to justify it - if (splitMessageProgressInterval && - splitPacketChannelList[index]->firstPacket && - splitPacketChannelList[index]->splitPacketList.GetNumAddedPackets()!=splitPacketChannelList[index]->firstPacket->splitPacketCount && - (splitPacketChannelList[index]->splitPacketList.GetNumAddedPackets()%splitMessageProgressInterval)==0) - { - // Return ID_DOWNLOAD_PROGRESS - // Write splitPacketIndex (SplitPacketIndexType) - // Write splitPacketCount (SplitPacketIndexType) - // Write byteLength (4) - // Write data, splitPacketChannelList[index]->splitPacketList[0]->data - InternalPacket *progressIndicator = AllocateFromInternalPacketPool(); - unsigned int length = sizeof(MessageID) + sizeof(unsigned int)*2 + sizeof(unsigned int) + (unsigned int) BITS_TO_BYTES(splitPacketChannelList[index]->firstPacket->dataBitLength); - AllocInternalPacketData(progressIndicator, length, false, __FILE__, __LINE__ ); - progressIndicator->dataBitLength=BYTES_TO_BITS(length); - progressIndicator->data[0]=(MessageID)ID_DOWNLOAD_PROGRESS; - unsigned int temp; - temp=splitPacketChannelList[index]->splitPacketList.GetNumAddedPackets(); - memcpy(progressIndicator->data+sizeof(MessageID), &temp, sizeof(unsigned int)); - temp=(unsigned int)internalPacket->splitPacketCount; - memcpy(progressIndicator->data+sizeof(MessageID)+sizeof(unsigned int)*1, &temp, sizeof(unsigned int)); - temp=(unsigned int) BITS_TO_BYTES(splitPacketChannelList[index]->firstPacket->dataBitLength); - memcpy(progressIndicator->data+sizeof(MessageID)+sizeof(unsigned int)*2, &temp, sizeof(unsigned int)); - - memcpy(progressIndicator->data+sizeof(MessageID)+sizeof(unsigned int)*3, splitPacketChannelList[index]->firstPacket->data, (size_t) BITS_TO_BYTES(splitPacketChannelList[index]->firstPacket->dataBitLength)); - outputQueue.Push(progressIndicator, __FILE__, __LINE__ ); - } - -#endif -} - -//------------------------------------------------------------------------------------------------------- -// Take all split chunks with the specified splitPacketId and try to -//reconstruct a packet. If we can, allocate and return it. Otherwise return 0 -// Optimized version -//------------------------------------------------------------------------------------------------------- -InternalPacket * ReliabilityLayer::BuildPacketFromSplitPacketList( SplitPacketChannel *splitPacketChannel, CCTimeType time ) -{ -#if PREALLOCATE_LARGE_MESSAGES==1 - InternalPacket *returnedPacket=splitPacketChannel->returnedPacket; - MafiaNet::OP_DELETE(splitPacketChannel, __FILE__, __LINE__); - (void) time; - return returnedPacket; -#else - size_t j; - InternalPacket * internalPacket, *splitPacket; - // int splitPacketPartLength; - - // Reconstruct - internalPacket = CreateInternalPacketCopy( splitPacketChannel->splitPacketList[0], 0, 0, time ); - internalPacket->dataBitLength=0; - for (j=0; j < splitPacketChannel->splitPacketList.GetAllocSize(); j++) - internalPacket->dataBitLength+=splitPacketChannel->splitPacketList[j]->dataBitLength; - // splitPacketPartLength=BITS_TO_BYTES(splitPacketChannel->firstPacket->dataBitLength); - - internalPacket->data = (unsigned char*) rakMalloc_Ex( (size_t) BITS_TO_BYTES( internalPacket->dataBitLength ), _FILE_AND_LINE_ ); - internalPacket->allocationScheme=InternalPacket::NORMAL; - - BitSize_t offset = 0; - for (j=0; j < splitPacketChannel->splitPacketList.GetAllocSize(); j++) - { - splitPacket = splitPacketChannel->splitPacketList[j]; - memcpy(internalPacket->data + BITS_TO_BYTES(offset), splitPacket->data, (size_t)BITS_TO_BYTES(splitPacket->dataBitLength)); - offset += splitPacket->dataBitLength; - } - - for (j=0; j < splitPacketChannel->splitPacketList.GetAllocSize(); j++) - { - FreeInternalPacketData(splitPacketChannel->splitPacketList[j], _FILE_AND_LINE_ ); - ReleaseToInternalPacketPool(splitPacketChannel->splitPacketList[j]); - } - MafiaNet::OP_DELETE(splitPacketChannel, __FILE__, __LINE__); - - return internalPacket; -#endif -} -//------------------------------------------------------------------------------------------------------- -InternalPacket * ReliabilityLayer::BuildPacketFromSplitPacketList( SplitPacketIdType inSplitPacketId, CCTimeType time, - RakNetSocket2 *s, SystemAddress &systemAddress, RakNetRandom *rnr, - BitStream &updateBitStream) -{ - unsigned int i; - bool objectExists; - SplitPacketChannel *splitPacketChannel; - InternalPacket * internalPacket; - - // Find in splitPacketChannelList the SplitPacketChannel with this splitPacketId - i=splitPacketChannelList.GetIndexFromKey(inSplitPacketId, &objectExists); - splitPacketChannel=splitPacketChannelList[i]; - -#if PREALLOCATE_LARGE_MESSAGES==1 - if (splitPacketChannel->splitPacketsArrived==splitPacketChannel->returnedPacket->splitPacketCount) -#else - if (splitPacketChannel->splitPacketList.AllPacketsAdded()) -#endif - { - // Ack immediately, because for large files this can take a long time - SendACKs(s, systemAddress, time, rnr, updateBitStream); - internalPacket=BuildPacketFromSplitPacketList(splitPacketChannel,time); - splitPacketChannelList.RemoveAtIndex(i); - return internalPacket; - } - else - { - return 0; - } -} -/* -//------------------------------------------------------------------------------------------------------- -// Delete any unreliable split packets that have long since expired -void ReliabilityLayer::DeleteOldUnreliableSplitPackets( CCTimeType time ) -{ -unsigned i,j; -i=0; -while (i < splitPacketChannelList.Size()) -{ -#if CC_TIME_TYPE_BYTES==4 -if (time > splitPacketChannelList[i]->lastUpdateTime + timeoutTime && -#else -if (time > splitPacketChannelList[i]->lastUpdateTime + (CCTimeType)timeoutTime*(CCTimeType)1000 && -#endif -(splitPacketChannelList[i]->splitPacketList[0]->reliability==MafiaNet::Reliability::Unreliable || splitPacketChannelList[i]->splitPacketList[0]->reliability==MafiaNet::Reliability::UnreliableSequenced)) -{ -for (j=0; j < splitPacketChannelList[i]->splitPacketList.Size(); j++) -{ -MafiaNet::OP_DELETE_ARRAY(splitPacketChannelList[i]->splitPacketList[j]->data, _FILE_AND_LINE_); -ReleaseToInternalPacketPool(splitPacketChannelList[i]->splitPacketList[j]); -} -MafiaNet::OP_DELETE(splitPacketChannelList[i], _FILE_AND_LINE_); -splitPacketChannelList.RemoveAtIndex(i); -} -else -i++; -} -} -*/ - -//------------------------------------------------------------------------------------------------------- -// Creates a copy of the specified internal packet with data copied from the original starting at dataByteOffset for dataByteLength bytes. -// Does not copy any split data parameters as that information is always generated does not have any reason to be copied -//------------------------------------------------------------------------------------------------------- -InternalPacket * ReliabilityLayer::CreateInternalPacketCopy( InternalPacket *original, int dataByteOffset, int dataByteLength, CCTimeType time ) -{ - InternalPacket * copy = AllocateFromInternalPacketPool(); -#ifdef _DEBUG - // Remove accessing undefined memory error - memset( copy, 255, sizeof( InternalPacket ) ); -#endif - // Copy over our chunk of data - - if ( dataByteLength > 0 ) - { - AllocInternalPacketData(copy, BITS_TO_BYTES(dataByteLength ), false, _FILE_AND_LINE_ ); - memcpy( copy->data, original->data + dataByteOffset, dataByteLength ); - } - else - copy->data = 0; - - copy->dataBitLength = dataByteLength << 3; - copy->creationTime = time; - copy->nextActionTime = 0; - copy->orderingIndex = original->orderingIndex; - copy->sequencingIndex = original->sequencingIndex; - copy->orderingChannel = original->orderingChannel; - copy->reliableMessageNumber = original->reliableMessageNumber; - copy->priority = original->priority; - copy->reliability = original->reliability; -#if PREALLOCATE_LARGE_MESSAGES==1 - copy->splitPacketCount = original->splitPacketCount; - copy->splitPacketId = original->splitPacketId; - copy->splitPacketIndex = original->splitPacketIndex; -#endif - - return copy; -} - -//------------------------------------------------------------------------------------------------------- -// Get the specified ordering list -//------------------------------------------------------------------------------------------------------- -/* -DataStructures::LinkedList *ReliabilityLayer::GetOrderingListAtOrderingStream( unsigned char orderingChannel ) -{ - if ( orderingChannel >= orderingList.Size() ) - return 0; - - return orderingList[ orderingChannel ]; -} - -//------------------------------------------------------------------------------------------------------- -// Add the internal packet to the ordering list in order based on order index -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::AddToOrderingList( InternalPacket * internalPacket ) -{ - } -*/ - -//------------------------------------------------------------------------------------------------------- -// Inserts a packet into the resend list in order -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::InsertPacketIntoResendList( InternalPacket *internalPacket, CCTimeType time, bool firstResend, bool modifyUnacknowledgedBytes ) -{ - (void) firstResend; - (void) time; - (void) internalPacket; - - AddToListTail(internalPacket, modifyUnacknowledgedBytes); - RakAssert(internalPacket->nextActionTime!=0); - -} - -//------------------------------------------------------------------------------------------------------- -// Were you ever unable to deliver a packet despite retries? -//------------------------------------------------------------------------------------------------------- -bool ReliabilityLayer::IsDeadConnection( void ) const -{ - return deadConnection; -} - -//------------------------------------------------------------------------------------------------------- -// Causes IsDeadConnection to return true -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::KillConnection( void ) -{ - deadConnection=true; -} - - -//------------------------------------------------------------------------------------------------------- -// Statistics -//------------------------------------------------------------------------------------------------------- -RakNetStatistics * ReliabilityLayer::GetStatistics( RakNetStatistics *rns ) -{ - unsigned i; - MafiaNet::TimeUS time = MafiaNet::GetTimeUS(); - uint64_t uint64Denominator; - double doubleDenominator; - - for (i=0; i < RNS_PER_SECOND_METRICS_COUNT; i++) - { - statistics.valueOverLastSecond[i]=bpsMetrics[i].GetBPS1Threadsafe(time); - statistics.runningTotal[i]=bpsMetrics[i].GetTotal1(); - } - - memcpy(rns, &statistics, sizeof(statistics)); - - if (rns->valueOverLastSecond[USER_MESSAGE_BYTES_SENT]+rns->valueOverLastSecond[USER_MESSAGE_BYTES_RESENT]>0) - rns->packetlossLastSecond=(float)((double) rns->valueOverLastSecond[USER_MESSAGE_BYTES_RESENT]/((double) rns->valueOverLastSecond[USER_MESSAGE_BYTES_SENT]+(double) rns->valueOverLastSecond[USER_MESSAGE_BYTES_RESENT])); - else - rns->packetlossLastSecond=0.0f; - - rns->packetlossTotal=0.0f; - uint64Denominator=(rns->runningTotal[USER_MESSAGE_BYTES_SENT]+rns->runningTotal[USER_MESSAGE_BYTES_RESENT]); - if (uint64Denominator!=0&&rns->runningTotal[USER_MESSAGE_BYTES_SENT]/uint64Denominator>0) - { - doubleDenominator=((double) rns->runningTotal[USER_MESSAGE_BYTES_SENT]+(double) rns->runningTotal[USER_MESSAGE_BYTES_RESENT]); - if(doubleDenominator!=0) - { - rns->packetlossTotal=(float)((double) rns->runningTotal[USER_MESSAGE_BYTES_RESENT]/doubleDenominator); - } - } - - rns->isLimitedByCongestionControl=statistics.isLimitedByCongestionControl; - rns->BPSLimitByCongestionControl=statistics.BPSLimitByCongestionControl; - rns->isLimitedByOutgoingBandwidthLimit=statistics.isLimitedByOutgoingBandwidthLimit; - rns->BPSLimitByOutgoingBandwidthLimit=statistics.BPSLimitByOutgoingBandwidthLimit; - - return rns; -} - -//------------------------------------------------------------------------------------------------------- -// Returns the number of packets in the resend queue, not counting holes -//------------------------------------------------------------------------------------------------------- -unsigned int ReliabilityLayer::GetResendListDataSize(void) const -{ - // Not accurate but thread-safe. The commented version might crash if the queue is cleared while we loop through it - // return resendTree.Size(); - return statistics.messagesInResendBuffer; -} - -//------------------------------------------------------------------------------------------------------- -bool ReliabilityLayer::AckTimeout(MafiaNet::Time curTime) -{ - // I check timeLastDatagramArrived-curTime because with threading it is possible that timeLastDatagramArrived is - // slightly greater than curTime, in which case this is NOT an ack timeout - return (timeLastDatagramArrived-curTime)>10000 && curTime-timeLastDatagramArrived>timeoutTime; -} -//------------------------------------------------------------------------------------------------------- -CCTimeType ReliabilityLayer::GetNextSendTime(void) const -{ - return nextSendTime; -} -//------------------------------------------------------------------------------------------------------- -CCTimeType ReliabilityLayer::GetTimeBetweenPackets(void) const -{ - return timeBetweenPackets; -} -//------------------------------------------------------------------------------------------------------- -#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 -CCTimeType ReliabilityLayer::GetAckPing(void) const -{ - return ackPing; -} -#endif -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::ResetPacketsAndDatagrams(void) -{ - packetsToSendThisUpdate.Clear(true, _FILE_AND_LINE_); - packetsToDeallocThisUpdate.Clear(true, _FILE_AND_LINE_); - packetsToSendThisUpdateDatagramBoundaries.Clear(true, _FILE_AND_LINE_); - datagramsToSendThisUpdateIsPair.Clear(true, _FILE_AND_LINE_); - datagramSizesInBytes.Clear(true, _FILE_AND_LINE_); - datagramSizeSoFar=0; -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::PushPacket(CCTimeType time, InternalPacket *internalPacket, bool isReliable) -{ - BitSize_t bitsForThisPacket=BYTES_TO_BITS(BITS_TO_BYTES(internalPacket->dataBitLength)+BITS_TO_BYTES(internalPacket->headerLength)); - datagramSizeSoFar+=bitsForThisPacket; - RakAssert(BITS_TO_BYTES(datagramSizeSoFar)headerLength==GetMessageHeaderLengthBits(internalPacket)); - -// This code tells me how much time elapses between when you send, and when the message actually goes out -// if (internalPacket->data[0]==0) -// { -// MafiaNet::TimeMS t; -// MafiaNet::BitStream bs(internalPacket->data+1,sizeof(t),false); -// bs.Read(t); -// MafiaNet::TimeMS curTime=MafiaNet::GetTimeMS(); -// MafiaNet::TimeMS diff = curTime-t; -// } - - congestionManager.OnSendBytes(time, BITS_TO_BYTES(internalPacket->dataBitLength)+BITS_TO_BYTES(internalPacket->headerLength)); -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::PushDatagram(void) -{ - if (datagramSizeSoFar>0) - { - packetsToSendThisUpdateDatagramBoundaries.Push(packetsToSendThisUpdate.Size(), _FILE_AND_LINE_ ); - datagramsToSendThisUpdateIsPair.Push(false, _FILE_AND_LINE_ ); - RakAssert(BITS_TO_BYTES(datagramSizeSoFar)=2) - { - datagramsToSendThisUpdateIsPair[datagramsToSendThisUpdateIsPair.Size()-2]=true; - datagramsToSendThisUpdateIsPair[datagramsToSendThisUpdateIsPair.Size()-1]=true; - return true; - } - return false; -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::ClearPacketsAndDatagrams(void) -{ - unsigned int i; - for (i=0; i < packetsToDeallocThisUpdate.Size(); i++) - { - // packetsToDeallocThisUpdate holds a boolean indicating if packetsToSendThisUpdate at this index should be freed - if (packetsToDeallocThisUpdate[i]) - { - RemoveFromUnreliableLinkedList(packetsToSendThisUpdate[i]); - FreeInternalPacketData(packetsToSendThisUpdate[i], _FILE_AND_LINE_ ); - // if (keepInternalPacketIfNeedsAck==false || packetsToSendThisUpdate[i]->reliabilityresendNext=internalPacket; - internalPacket->resendPrev=internalPacket; - resendLinkedListHead=internalPacket; - return; - } - internalPacket->resendPrev->resendNext = internalPacket->resendNext; - internalPacket->resendNext->resendPrev = internalPacket->resendPrev; - internalPacket->resendNext=resendLinkedListHead; - internalPacket->resendPrev=resendLinkedListHead->resendPrev; - internalPacket->resendPrev->resendNext=internalPacket; - resendLinkedListHead->resendPrev=internalPacket; - resendLinkedListHead=internalPacket; - RakAssert(internalPacket->headerLength+internalPacket->dataBitLength>0); - - //ValidateResendList(); -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::RemoveFromList(InternalPacket *internalPacket, bool modifyUnacknowledgedBytes) -{ - InternalPacket *newPosition; - internalPacket->resendPrev->resendNext = internalPacket->resendNext; - internalPacket->resendNext->resendPrev = internalPacket->resendPrev; - newPosition = internalPacket->resendNext; - if ( internalPacket == resendLinkedListHead ) - resendLinkedListHead = newPosition; - if (resendLinkedListHead==internalPacket) - resendLinkedListHead=0; - - if (modifyUnacknowledgedBytes) - { - RakAssert(unacknowledgedBytes>=BITS_TO_BYTES(internalPacket->headerLength+internalPacket->dataBitLength)); - unacknowledgedBytes-=BITS_TO_BYTES(internalPacket->headerLength+internalPacket->dataBitLength); - // printf("-unacknowledgedBytes:%i ", unacknowledgedBytes); - - -// ValidateResendList(); - } -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::AddToListTail(InternalPacket *internalPacket, bool modifyUnacknowledgedBytes) -{ - if (modifyUnacknowledgedBytes) - { - unacknowledgedBytes+=BITS_TO_BYTES(internalPacket->headerLength+internalPacket->dataBitLength); - // printf("+unacknowledgedBytes:%i ", unacknowledgedBytes); - } - - if (resendLinkedListHead==0) - { - internalPacket->resendNext=internalPacket; - internalPacket->resendPrev=internalPacket; - resendLinkedListHead=internalPacket; - return; - } - internalPacket->resendNext=resendLinkedListHead; - internalPacket->resendPrev=resendLinkedListHead->resendPrev; - internalPacket->resendPrev->resendNext=internalPacket; - resendLinkedListHead->resendPrev=internalPacket; - -// ValidateResendList(); - -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::PopListHead(bool modifyUnacknowledgedBytes) -{ - RakAssert(resendLinkedListHead!=0); - RemoveFromList(resendLinkedListHead, modifyUnacknowledgedBytes); -} -//------------------------------------------------------------------------------------------------------- -bool ReliabilityLayer::IsResendQueueEmpty(void) const -{ - return resendLinkedListHead==0; -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::SendACKs(RakNetSocket2 *s, SystemAddress &systemAddress, CCTimeType time, RakNetRandom *rnr, BitStream &updateBitStream) -{ - BitSize_t maxDatagramPayload = GetMaxDatagramSizeExcludingMessageHeaderBits(); - - while (acknowlegements.Size()>0) - { - // Send acks - updateBitStream.Reset(); - DatagramHeaderFormat dhf; - dhf.isACK=true; - dhf.isNAK=false; - dhf.isPacketPair=false; -#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 - dhf.sourceSystemTime=time; -#endif - double B; - double AS; - bool hasBAndAS; - if (remoteSystemNeedsBAndAS) - { - congestionManager.OnSendAckGetBAndAS(time, &hasBAndAS,&B,&AS); - dhf.AS=(float)AS; - dhf.hasBAndAS=hasBAndAS; - } - else - dhf.hasBAndAS=false; -#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 - dhf.sourceSystemTime=nextAckTimeToSend; -#endif - // dhf.B=(float)B; - updateBitStream.Reset(); - dhf.Serialize(&updateBitStream); - CC_DEBUG_PRINTF_1("AckSnd "); - acknowlegements.Serialize(&updateBitStream, maxDatagramPayload, true); - SendBitStream( s, systemAddress, &updateBitStream, rnr, time ); - congestionManager.OnSendAck(time,updateBitStream.GetNumberOfBytesUsed()); - - // I think this is causing a bug where if the estimated bandwidth is very low for the recipient, only acks ever get sent - // congestionManager.OnSendBytes(time,UDP_HEADER_SIZE+updateBitStream.GetNumberOfBytesUsed()); - } -} -/* -//------------------------------------------------------------------------------------------------------- -ReliabilityLayer::DatagramMessageIDList* ReliabilityLayer::AllocateFromDatagramMessageIDPool(void) -{ -DatagramMessageIDList*s; -s=datagramMessageIDPool.Allocate( _FILE_AND_LINE_ ); -// Call new operator, memoryPool doesn't do this -s = new ((void*)s) DatagramMessageIDList; -return s; -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::ReleaseToDatagramMessageIDPool(DatagramMessageIDList* d) -{ -d->~DatagramMessageIDList(); -datagramMessageIDPool.Release(d); -} -*/ -//------------------------------------------------------------------------------------------------------- -InternalPacket* ReliabilityLayer::AllocateFromInternalPacketPool(void) -{ - InternalPacket *ip = internalPacketPool.Allocate( _FILE_AND_LINE_ ); - ip->reliableMessageNumber = (MessageNumberType) (const uint32_t)-1; - ip->messageNumberAssigned=false; - ip->nextActionTime = 0; - ip->splitPacketCount = 0; - ip->splitPacketIndex = 0; - ip->splitPacketId = 0; - ip->allocationScheme=InternalPacket::NORMAL; - ip->data=0; - ip->timesSent=0; - return ip; -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::ReleaseToInternalPacketPool(InternalPacket *ip) -{ - internalPacketPool.Release(ip, _FILE_AND_LINE_); -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::RemoveFromUnreliableLinkedList(InternalPacket *internalPacket) -{ - if (internalPacket->reliability==MafiaNet::Reliability::Unreliable || - internalPacket->reliability==MafiaNet::Reliability::UnreliableSequenced || - internalPacket->reliability==MafiaNet::Reliability::UnreliableWithAckReceipt -// || -// internalPacket->reliability==UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT - ) - { - InternalPacket *newPosition; - internalPacket->unreliablePrev->unreliableNext = internalPacket->unreliableNext; - internalPacket->unreliableNext->unreliablePrev = internalPacket->unreliablePrev; - newPosition = internalPacket->unreliableNext; - if ( internalPacket == unreliableLinkedListHead ) - unreliableLinkedListHead = newPosition; - if (unreliableLinkedListHead==internalPacket) - unreliableLinkedListHead=0; - } -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::AddToUnreliableLinkedList(InternalPacket *internalPacket) -{ - if (internalPacket->reliability==MafiaNet::Reliability::Unreliable || - internalPacket->reliability==MafiaNet::Reliability::UnreliableSequenced || - internalPacket->reliability==MafiaNet::Reliability::UnreliableWithAckReceipt -// || -// internalPacket->reliability==UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT - ) - { - if (unreliableLinkedListHead==0) - { - internalPacket->unreliableNext=internalPacket; - internalPacket->unreliablePrev=internalPacket; - unreliableLinkedListHead=internalPacket; - return; - } - internalPacket->unreliableNext=unreliableLinkedListHead; - internalPacket->unreliablePrev=unreliableLinkedListHead->unreliablePrev; - internalPacket->unreliablePrev->unreliableNext=internalPacket; - unreliableLinkedListHead->unreliablePrev=internalPacket; - } -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::ValidateResendList(void) const -{ -// unsigned int count1=0, count2=0; -// for (unsigned int i=0; i < RESEND_BUFFER_ARRAY_LENGTH; i++) -// if (resendBuffer[i]) -// count1++; -// -// if (resendLinkedListHead) -// { -// InternalPacket *internalPacket = resendLinkedListHead; -// do -// { -// count2++; -// internalPacket=internalPacket->resendNext; -// } while (internalPacket!=resendLinkedListHead); -// } -// RakAssert(count1==count2); -// RakAssert(count2<=RESEND_BUFFER_ARRAY_LENGTH); -} -//------------------------------------------------------------------------------------------------------- -bool ReliabilityLayer::ResendBufferOverflow(void) const -{ - int index1 = sendReliableMessageNumberIndex & (uint32_t) RESEND_BUFFER_ARRAY_MASK; - // int index2 = (sendReliableMessageNumberIndex+(uint32_t)1) & (uint32_t) RESEND_BUFFER_ARRAY_MASK; - RakAssert(index1= datagramHistory.Size()) - return nullptr; - - *timeSent=datagramHistory[offsetIntoList].timeSent; - return datagramHistory[offsetIntoList].head; -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::RemoveFromDatagramHistory(DatagramSequenceNumberType index) -{ - DatagramSequenceNumberType offsetIntoList = index - datagramHistoryPopCount; - MessageNumberNode *mnm = datagramHistory[offsetIntoList].head; - MessageNumberNode *next; - while (mnm) - { - next=mnm->next; - datagramHistoryMessagePool.Release(mnm, _FILE_AND_LINE_); - mnm=next; - } - datagramHistory[offsetIntoList].head=0; -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::AddFirstToDatagramHistory(DatagramSequenceNumberType datagramNumber, CCTimeType timeSent) -{ - (void) datagramNumber; - if (datagramHistory.Size()>DATAGRAM_MESSAGE_ID_ARRAY_LENGTH) - { - RemoveFromDatagramHistory(datagramHistoryPopCount); - datagramHistory.Pop(); - datagramHistoryPopCount++; - } - - datagramHistory.Push(DatagramHistoryNode(0, timeSent), _FILE_AND_LINE_); - // printf("%p Pushed empty DatagramHistoryNode to datagram history at index %i\n", this, datagramHistory.Size()-1); -} -//------------------------------------------------------------------------------------------------------- -ReliabilityLayer::MessageNumberNode* ReliabilityLayer::AddFirstToDatagramHistory(DatagramSequenceNumberType datagramNumber, DatagramSequenceNumberType messageNumber, CCTimeType timeSent) -{ - (void) datagramNumber; -// RakAssert(datagramHistoryPopCount+(unsigned int) datagramHistory.Size()==datagramNumber); - if (datagramHistory.Size()>DATAGRAM_MESSAGE_ID_ARRAY_LENGTH) - { - RemoveFromDatagramHistory(datagramHistoryPopCount); - datagramHistory.Pop(); - datagramHistoryPopCount++; - } - - MessageNumberNode *mnm = datagramHistoryMessagePool.Allocate(_FILE_AND_LINE_); - mnm->next=0; - mnm->messageNumber=messageNumber; - datagramHistory.Push(DatagramHistoryNode(mnm, timeSent), _FILE_AND_LINE_); - // printf("%p Pushed message %i to DatagramHistoryNode to datagram history at index %i\n", this, messageNumber.val, datagramHistory.Size()-1); - return mnm; -} -//------------------------------------------------------------------------------------------------------- -ReliabilityLayer::MessageNumberNode* ReliabilityLayer::AddSubsequentToDatagramHistory(MessageNumberNode *messageNumberNode, DatagramSequenceNumberType messageNumber) -{ - messageNumberNode->next=datagramHistoryMessagePool.Allocate(_FILE_AND_LINE_); - messageNumberNode->next->messageNumber=messageNumber; - messageNumberNode->next->next=0; - return messageNumberNode->next; -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::AllocInternalPacketData(InternalPacket *internalPacket, InternalPacketRefCountedData **refCounter, unsigned char *externallyAllocatedPtr, unsigned char *ourOffset) -{ - internalPacket->allocationScheme=InternalPacket::REF_COUNTED; - internalPacket->data=ourOffset; - if (*refCounter==0) - { - *refCounter = refCountedDataPool.Allocate(_FILE_AND_LINE_); - // *refCounter = MafiaNet::OP_NEW(_FILE_AND_LINE_); - (*refCounter)->refCount=1; - (*refCounter)->sharedDataBlock=externallyAllocatedPtr; - } - else - (*refCounter)->refCount++; - internalPacket->refCountedData=(*refCounter); -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::AllocInternalPacketData(InternalPacket *internalPacket, unsigned char *externallyAllocatedPtr) -{ - internalPacket->allocationScheme=InternalPacket::NORMAL; - internalPacket->data=externallyAllocatedPtr; -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::AllocInternalPacketData(InternalPacket *internalPacket, unsigned int numBytes, bool allowStack, const char *file, unsigned int line) -{ - if (allowStack && numBytes <= sizeof(internalPacket->stackData)) - { - internalPacket->allocationScheme=InternalPacket::STACK; - internalPacket->data=internalPacket->stackData; - } - else - { - internalPacket->allocationScheme=InternalPacket::NORMAL; - internalPacket->data=(unsigned char*) rakMalloc_Ex(numBytes,file,line); - } -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::FreeInternalPacketData(InternalPacket *internalPacket, const char *file, unsigned int line) -{ - if (internalPacket==0) - return; - - if (internalPacket->allocationScheme==InternalPacket::REF_COUNTED) - { - if (internalPacket->refCountedData==0) - return; - - internalPacket->refCountedData->refCount--; - if (internalPacket->refCountedData->refCount==0) - { - rakFree_Ex(internalPacket->refCountedData->sharedDataBlock, file, line ); - internalPacket->refCountedData->sharedDataBlock=0; - // MafiaNet::OP_DELETE(internalPacket->refCountedData,file, line); - refCountedDataPool.Release(internalPacket->refCountedData,file, line); - internalPacket->refCountedData=0; - } - } - else if (internalPacket->allocationScheme==InternalPacket::NORMAL) - { - if (internalPacket->data==0) - return; - - rakFree_Ex(internalPacket->data, file, line ); - internalPacket->data=0; - } - else - { - // Data was on stack - internalPacket->data=0; - } -} -//------------------------------------------------------------------------------------------------------- -unsigned int ReliabilityLayer::GetMaxDatagramSizeExcludingMessageHeaderBytes(void) -{ - unsigned int val = congestionManager.GetMTU() - DatagramHeaderFormat::GetDataHeaderByteLength(); - -#if LIBCAT_SECURITY==1 - if (useSecurity) - val -= cat::AuthenticatedEncryption::OVERHEAD_BYTES; -#endif - - return val; -} -//------------------------------------------------------------------------------------------------------- -BitSize_t ReliabilityLayer::GetMaxDatagramSizeExcludingMessageHeaderBits(void) -{ - return BYTES_TO_BITS(GetMaxDatagramSizeExcludingMessageHeaderBytes()); -} -//------------------------------------------------------------------------------------------------------- -void ReliabilityLayer::InitHeapWeights(void) -{ - for (int priorityLevel=0; priorityLevel < MafiaNet::NUMBER_OF_PRIORITIES; priorityLevel++) - outgoingPacketBufferNextWeights[priorityLevel]=(1<0) - { - int peekPL = (int)outgoingPacketBuffer.Peek()->priority; - reliabilityHeapWeightType weight = outgoingPacketBuffer.PeekWeight(); - reliabilityHeapWeightType min = weight - (1<GetNetworkID() < data->replica->GetNetworkID()) - return -1; - if (replica3->GetNetworkID() > data->replica->GetNetworkID()) - return 1; - */ - - // 7/28/2013 - If GetNetworkID chagned during runtime, the list would be out of order and lookup would always fail or go out of bounds - // I remember before that I could not directly compare - if (replica3->referenceIndex < data->replica->referenceIndex) - return -1; - if (replica3->referenceIndex > data->replica->referenceIndex) - return 1; - return 0; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -LastSerializationResult::LastSerializationResult() -{ - replica=0; - lastSerializationResultBS=0; - whenLastSerialized = MafiaNet::GetTime(); -} -LastSerializationResult::~LastSerializationResult() -{ - if (lastSerializationResultBS) - MafiaNet::OP_DELETE(lastSerializationResultBS,_FILE_AND_LINE_); -} -void LastSerializationResult::AllocBS(void) -{ - if (lastSerializationResultBS==0) - { - lastSerializationResultBS= MafiaNet::OP_NEW(_FILE_AND_LINE_); - } -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -ReplicaManager3::ReplicaManager3() -{ - defaultSendParameters.orderingChannel=0; - defaultSendParameters.priority=MafiaNet::Priority::High; - defaultSendParameters.reliability=MafiaNet::Reliability::ReliableOrdered; - defaultSendParameters.sendReceipt=0; - autoSerializeInterval=30; - lastAutoSerializeOccurance=0; - autoCreateConnections=true; - autoDestroyConnections=true; - currentlyDeallocatingReplica=0; - - for (unsigned int i=0; i < 255; i++) - worldsArray[i]=0; - - AddWorld(0); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -ReplicaManager3::~ReplicaManager3() -{ - if (autoDestroyConnections) - { - m_WorldListMutex.Lock(); - for (unsigned int i=0; i < worldsList.Size(); i++) - { - RakAssert(worldsList[i]->connectionList.Size()==0); - } - m_WorldListMutex.Unlock(); - } - Clear(true); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::SetAutoManageConnections(bool autoCreate, bool autoDestroy) -{ - autoCreateConnections=autoCreate; - autoDestroyConnections=autoDestroy; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool ReplicaManager3::GetAutoCreateConnections(void) const -{ - return autoCreateConnections; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool ReplicaManager3::GetAutoDestroyConnections(void) const -{ - return autoDestroyConnections; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::AutoCreateConnectionList( - DataStructures::List &participantListIn, - DataStructures::List &participantListOut, - WorldId worldId) -{ - for (unsigned int index=0; index < participantListIn.Size(); index++) - { - if (GetConnectionByGUID(participantListIn[index], worldId)== nullptr) - { - Connection_RM3 *connection = AllocConnection(rakPeerInterface->GetSystemAddressFromGuid(participantListIn[index]), participantListIn[index]); - if (connection) - { - PushConnection(connection); - participantListOut.Push(connection, _FILE_AND_LINE_); - } - } - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool ReplicaManager3::PushConnection(MafiaNet::Connection_RM3 *newConnection, WorldId worldId) -{ - if (newConnection==0) - return false; - if (GetConnectionByGUID(newConnection->GetRakNetGUID(), worldId)) - return false; - // Was this intended? - RakAssert(newConnection->GetRakNetGUID()!=rakPeerInterface->GetMyGUID()); - - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - unsigned int index = world->connectionList.GetIndexOf(newConnection); - if (index==(unsigned int)-1) - { - world->connectionList.Push(newConnection,_FILE_AND_LINE_); - - // Send message to validate the connection - newConnection->SendValidation(rakPeerInterface, worldId); - - Connection_RM3::ConstructionMode constructionMode = newConnection->QueryConstructionMode(); - if (constructionMode==Connection_RM3::QUERY_REPLICA_FOR_CONSTRUCTION || constructionMode==Connection_RM3::QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION) - { - unsigned int pushIdx; - for (pushIdx=0; pushIdx < world->userReplicaList.Size(); pushIdx++) - newConnection->OnLocalReference(world->userReplicaList[pushIdx], this); - } - } - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::DeallocReplicaNoBroadcastDestruction(MafiaNet::Connection_RM3 *connection, MafiaNet::Replica3 *replica3) -{ - currentlyDeallocatingReplica=replica3; - replica3->DeallocReplica(connection); - currentlyDeallocatingReplica=0; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -MafiaNet::Connection_RM3 * ReplicaManager3::PopConnection(unsigned int index, WorldId worldId) -{ - DataStructures::List replicaList; - DataStructures::List destructionList; - DataStructures::List broadcastList; - MafiaNet::Connection_RM3 *connection; - unsigned int index2; - RM3ActionOnPopConnection action; - - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - connection=world->connectionList[index]; - - // Clear out downloadGroup - connection->ClearDownloadGroup(rakPeerInterface); - - RakNetGUID guid = connection->GetRakNetGUID(); - // This might be wrong, I am relying on the variable creatingSystemGuid which is transmitted - // automatically from the first system to reference the object. However, if an object changes - // owners then it is not going to be returned here, and therefore QueryActionOnPopConnection() - // will not be called for the new owner. - GetReplicasCreatedByGuid(guid, replicaList); - - for (index2=0; index2 < replicaList.Size(); index2++) - { - action = replicaList[index2]->QueryActionOnPopConnection(connection); - replicaList[index2]->OnPoppedConnection(connection); - if (action==RM3AOPC_DELETE_REPLICA) - { - if (replicaList[index2]->GetNetworkIDManager()) - destructionList.Push( replicaList[index2]->GetNetworkID(), _FILE_AND_LINE_ ); - } - else if (action==RM3AOPC_DELETE_REPLICA_AND_BROADCAST_DESTRUCTION) - { - if (replicaList[index2]->GetNetworkIDManager()) - destructionList.Push( replicaList[index2]->GetNetworkID(), _FILE_AND_LINE_ ); - - broadcastList.Push( replicaList[index2], _FILE_AND_LINE_ ); - } - else if (action==RM3AOPC_DO_NOTHING) - { - for (unsigned int index3 = 0; index3 < connection->queryToSerializeReplicaList.Size(); index3++) - { - LastSerializationResult *lsr = connection->queryToSerializeReplicaList[index3]; - lsr->whenLastSerialized=0; - if (lsr->lastSerializationResultBS) - { - for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) - lsr->lastSerializationResultBS->bitStream[z].Reset(); - } - } - } - } - - BroadcastDestructionList(broadcastList, connection->GetSystemAddress()); - for (index2=0; index2 < destructionList.Size(); index2++) - { - // Do lookup in case DeallocReplica destroyed one of of the later Replica3 instances in the list - Replica3* replicaToDestroy = world->networkIDManager->GET_OBJECT_FROM_ID(destructionList[index2]); - if (replicaToDestroy) - { - replicaToDestroy->PreDestruction(connection); - replicaToDestroy->DeallocReplica(connection); - } - } - - world->connectionList.RemoveAtIndex(index); - return connection; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -MafiaNet::Connection_RM3 * ReplicaManager3::PopConnection(RakNetGUID guid, WorldId worldId) -{ - unsigned int index; - - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - for (index=0; index < world->connectionList.Size(); index++) - { - if (world->connectionList[index]->GetRakNetGUID()==guid) - { - return PopConnection(index, worldId); - } - } - return 0; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::Reference(MafiaNet::Replica3 *replica3, WorldId worldId) -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - unsigned int index = ReferenceInternal(replica3, worldId); - - if (index!=(unsigned int)-1) - { - unsigned int pushIdx; - for (pushIdx=0; pushIdx < world->connectionList.Size(); pushIdx++) - { - Connection_RM3::ConstructionMode constructionMode = world->connectionList[pushIdx]->QueryConstructionMode(); - if (constructionMode==Connection_RM3::QUERY_REPLICA_FOR_CONSTRUCTION || constructionMode==Connection_RM3::QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION) - { - world->connectionList[pushIdx]->OnLocalReference(replica3, this); - } - } - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned int ReplicaManager3::ReferenceInternal(MafiaNet::Replica3 *replica3, WorldId worldId) -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - unsigned int index; - index = world->userReplicaList.GetIndexOf(replica3); - if (index==(unsigned int)-1) - { - RakAssert(world->networkIDManager); - replica3->SetNetworkIDManager(world->networkIDManager); - // If it crashes on rakPeerInterface==0 then you didn't call RakPeerInterface::AttachPlugin() - if (replica3->creatingSystemGUID==UNASSIGNED_RAKNET_GUID) - replica3->creatingSystemGUID=rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); - replica3->replicaManager=this; - if (replica3->referenceIndex==(uint32_t)-1) - { - replica3->referenceIndex=nextReferenceIndex++; - } - world->userReplicaList.Push(replica3,_FILE_AND_LINE_); - return world->userReplicaList.Size()-1; - } - return (unsigned int) -1; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::Dereference(MafiaNet::Replica3 *replica3, WorldId worldId) -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - unsigned int index, index2; - for (index=0; index < world->userReplicaList.Size(); index++) - { - if (world->userReplicaList[index]==replica3) - { - world->userReplicaList.RemoveAtIndex(index); - break; - } - } - - // Remove from all connections - for (index2=0; index2 < world->connectionList.Size(); index2++) - { - world->connectionList[index2]->OnDereference(replica3, this); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::DereferenceList(DataStructures::List &replicaListIn, WorldId worldId) -{ - unsigned int index; - for (index=0; index < replicaListIn.Size(); index++) - Dereference(replicaListIn[index], worldId); -} - - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::GetReplicasCreatedByMe(DataStructures::List &replicaListOut, WorldId worldId) -{ - //RakNetGUID myGuid = rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); - GetReplicasCreatedByGuid(rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS), replicaListOut, worldId); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::GetReferencedReplicaList(DataStructures::List &replicaListOut, WorldId worldId) -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - replicaListOut=world->userReplicaList; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::GetReplicasCreatedByGuid(RakNetGUID guid, DataStructures::List &replicaListOut, WorldId worldId) -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - replicaListOut.Clear(false,_FILE_AND_LINE_); - unsigned int index; - for (index=0; index < world->userReplicaList.Size(); index++) - { - if (world->userReplicaList[index]->creatingSystemGUID==guid) - replicaListOut.Push(world->userReplicaList[index],_FILE_AND_LINE_); - } -} - - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned ReplicaManager3::GetReplicaCount(WorldId worldId) const -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - return world->userReplicaList.Size(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -Replica3 *ReplicaManager3::GetReplicaAtIndex(unsigned index, WorldId worldId) const -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - return world->userReplicaList[index]; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned int ReplicaManager3::GetConnectionCount(WorldId worldId) const -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - return world->connectionList.Size(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -Connection_RM3* ReplicaManager3::GetConnectionAtIndex(unsigned index, WorldId worldId) const -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - return world->connectionList[index]; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -Connection_RM3* ReplicaManager3::GetConnectionBySystemAddress(const SystemAddress &sa, WorldId worldId) const -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - unsigned int index; - for (index=0; index < world->connectionList.Size(); index++) - { - if (world->connectionList[index]->GetSystemAddress()==sa) - { - return world->connectionList[index]; - } - } - return 0; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -Connection_RM3* ReplicaManager3::GetConnectionByGUID(RakNetGUID guid, WorldId worldId) const -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - unsigned int index; - for (index=0; index < world->connectionList.Size(); index++) - { - if (world->connectionList[index]->GetRakNetGUID()==guid) - { - return world->connectionList[index]; - } - } - return 0; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::GetConnectionsInVirtualWorld(VirtualWorldId virtualWorld, DataStructures::List &connectionsOut, bool includeGlobal, WorldId worldId) const -{ - connectionsOut.Clear(true, _FILE_AND_LINE_); - - // Two distinct layers: the heavyweight RM3 world (worldId, default 0) is the - // container that actually holds the connection list; the virtual world is a - // lightweight per-connection tag we filter that list by. We are not switching - // RM3 worlds here -- we look up the RM3 world only to get its connections, - // then keep the ones whose virtual world matches. (Most setups only ever use - // the auto-created RM3 world 0.) See VirtualWorld.h. - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - unsigned int index; - for (index=0; index < world->connectionList.Size(); index++) - { - Connection_RM3 *connection = world->connectionList[index]; - VirtualWorldId connVirtualWorld = connection->GetVirtualWorld(); - // Membership test (not a symmetric visibility check): the connection is in - // this virtual world, plus -- when includeGlobal -- any global observer. - // Using VirtualWorldsCanSee here would make a GLOBAL *query* match every - // connection, which is not what "connections in virtual world N" means. - bool matches = (connVirtualWorld==virtualWorld) || - (includeGlobal && connVirtualWorld==VIRTUAL_WORLD_GLOBAL); - if (matches) - connectionsOut.Push(connection, _FILE_AND_LINE_); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::GetGuidsInVirtualWorld(VirtualWorldId virtualWorld, DataStructures::List &guidsOut, bool includeGlobal, WorldId worldId) const -{ - guidsOut.Clear(true, _FILE_AND_LINE_); - DataStructures::List connections; - GetConnectionsInVirtualWorld(virtualWorld, connections, includeGlobal, worldId); - - unsigned int index; - for (index=0; index < connections.Size(); index++) - guidsOut.Push(connections[index]->GetRakNetGUID(), _FILE_AND_LINE_); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::SetPlayerVirtualWorld(Connection_RM3 *connection, VirtualWorldReplica3 *avatar, VirtualWorldId virtualWorld) -{ - if (connection) - connection->SetVirtualWorld(virtualWorld); - if (avatar) - avatar->SetVirtualWorld(virtualWorld); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::SetDefaultOrderingChannel(char def) -{ - defaultSendParameters.orderingChannel=def; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::SetDefaultPacketPriority(MafiaNet::Priority def) -{ - defaultSendParameters.priority=def; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::SetDefaultPacketReliability(MafiaNet::Reliability def) -{ - defaultSendParameters.reliability=def; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::SetAutoSerializeInterval(MafiaNet::Time intervalMS) -{ - autoSerializeInterval=intervalMS; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::GetConnectionsThatHaveReplicaConstructed(Replica3 *replica, DataStructures::List &connectionsThatHaveConstructedThisReplica, WorldId worldId) -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - connectionsThatHaveConstructedThisReplica.Clear(false,_FILE_AND_LINE_); - unsigned int index; - for (index=0; index < world->connectionList.Size(); index++) - { - if (world->connectionList[index]->HasReplicaConstructed(replica)) - connectionsThatHaveConstructedThisReplica.Push(world->connectionList[index],_FILE_AND_LINE_); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool ReplicaManager3::GetAllConnectionDownloadsCompleted(WorldId worldId) const -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - unsigned int index; - for (index=0; index < world->connectionList.Size(); index++) - { - if (world->connectionList[index]->GetDownloadWasCompleted()==false) - return false; - } - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::Clear(bool deleteWorlds) -{ - m_WorldListMutex.Lock(); - for (unsigned int i=0; i < worldsList.Size(); i++) - { - worldsList[i]->Clear(this); - if (deleteWorlds) - { - worldsArray[worldsList[i]->worldId]=0; - MafiaNet::OP_DELETE(worldsList[i], _FILE_AND_LINE_); - } - } - if (deleteWorlds) - worldsList.Clear(false, _FILE_AND_LINE_); - m_WorldListMutex.Unlock(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -ReplicaManager3::RM3World::RM3World() -{ - networkIDManager=0; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::RM3World::Clear(ReplicaManager3 *replicaManager3) -{ - if (replicaManager3->GetAutoDestroyConnections()) - { - for (unsigned int i=0; i < connectionList.Size(); i++) - replicaManager3->DeallocConnection(connectionList[i]); - } - else - { - // Clear out downloadGroup even if not auto destroying the connection, since the packets need to go back to RakPeer - for (unsigned int i=0; i < connectionList.Size(); i++) - connectionList[i]->ClearDownloadGroup(replicaManager3->GetRakPeerInterface()); - } - - for (unsigned int i=0; i < userReplicaList.Size(); i++) - { - userReplicaList[i]->replicaManager=0; - userReplicaList[i]->SetNetworkIDManager(0); - } - connectionList.Clear(true,_FILE_AND_LINE_); - userReplicaList.Clear(true,_FILE_AND_LINE_); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -PRO ReplicaManager3::GetDefaultSendParameters(void) const -{ - return defaultSendParameters; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::AddWorld(WorldId worldId) -{ - RakAssert(worldsArray[worldId]==0 && "World already in use"); - - RM3World *newWorld = MafiaNet::OP_NEW(_FILE_AND_LINE_); - newWorld->worldId=worldId; - worldsArray[worldId]=newWorld; - m_WorldListMutex.Lock(); - worldsList.Push(newWorld,_FILE_AND_LINE_); - m_WorldListMutex.Unlock(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::RemoveWorld(WorldId worldId) -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - for (unsigned int i=0; i < worldsList.Size(); i++) - { - if (worldsList[i]==worldsArray[worldId]) - { - MafiaNet::OP_DELETE(worldsList[i],_FILE_AND_LINE_); - worldsList.RemoveAtIndexFast(i); - break; - } - } - worldsArray[worldId]=0; - -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -NetworkIDManager *ReplicaManager3::GetNetworkIDManager(WorldId worldId) const -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - return world->networkIDManager; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::SetNetworkIDManager(NetworkIDManager *_networkIDManager, WorldId worldId) -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - world->networkIDManager=_networkIDManager; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -PluginReceiveResult ReplicaManager3::OnReceive(Packet *packet) -{ - if (packet->length<2) - return RR_CONTINUE_PROCESSING; - - WorldId incomingWorldId; - - MafiaNet::Time timestamp=0; - unsigned char packetIdentifier, packetDataOffset; - if ( ( unsigned char ) packet->data[ 0 ] == ID_TIMESTAMP ) - { - if ( packet->length > sizeof( unsigned char ) + sizeof(MafiaNet::Time ) ) - { - packetIdentifier = ( unsigned char ) packet->data[ sizeof( unsigned char ) + sizeof(MafiaNet::Time ) ]; - // Required for proper endian swapping - MafiaNet::BitStream tsBs(packet->data+sizeof(MessageID),packet->length-1,false); - tsBs.Read(timestamp); - // Next line assumes worldId is only 1 byte - RakAssert(sizeof(WorldId)==1); - incomingWorldId=packet->data[sizeof( unsigned char )*2 + sizeof(MafiaNet::Time )]; - packetDataOffset=sizeof( unsigned char )*3 + sizeof(MafiaNet::Time ); - } - else - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - else - { - packetIdentifier = ( unsigned char ) packet->data[ 0 ]; - // Next line assumes worldId is only 1 byte - RakAssert(sizeof(WorldId)==1); - incomingWorldId=packet->data[sizeof( unsigned char )]; - packetDataOffset=sizeof( unsigned char )*2; - } - - if (worldsArray[incomingWorldId]==0) - return RR_CONTINUE_PROCESSING; - - switch (packetIdentifier) - { - case ID_REPLICA_MANAGER_CONSTRUCTION: - return OnConstruction(packet, packet->data, packet->length, packet->guid, packetDataOffset, incomingWorldId); - case ID_REPLICA_MANAGER_SERIALIZE: - return OnSerialize(packet, packet->data, packet->length, packet->guid, timestamp, packetDataOffset, incomingWorldId); - case ID_REPLICA_MANAGER_DOWNLOAD_STARTED: - if (packet->wasGeneratedLocally==false) - { - return OnDownloadStarted(packet, packet->data, packet->length, packet->guid, packetDataOffset, incomingWorldId); - } - else - break; - case ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE: - if (packet->wasGeneratedLocally==false) - { - return OnDownloadComplete(packet, packet->data, packet->length, packet->guid, packetDataOffset, incomingWorldId); - } - else - break; - case ID_REPLICA_MANAGER_SCOPE_CHANGE: - { - Connection_RM3 *connection = GetConnectionByGUID(packet->guid, incomingWorldId); - if (connection && connection->isValidated==false) - { - // This connection is now confirmed bidirectional - connection->isValidated=true; - // Reply back on validation - connection->SendValidation(rakPeerInterface,incomingWorldId); - } - } - } - - return RR_CONTINUE_PROCESSING; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::AutoConstructByQuery(ReplicaManager3 *replicaManager3, WorldId worldId) -{ - ValidateLists(replicaManager3); - - ConstructionMode curConstructionMode = QueryConstructionMode(); - - unsigned int index; - RM3ConstructionState constructionState; - LastSerializationResult *lsr; - index=0; - - constructedReplicasCulled.Clear(false,_FILE_AND_LINE_); - destroyedReplicasCulled.Clear(false,_FILE_AND_LINE_); - - if (curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION) - { - while (index < queryToConstructReplicaList.Size()) - { - lsr=queryToConstructReplicaList[index]; - constructionState=lsr->replica->QueryConstruction(this, replicaManager3); - if (constructionState==RM3CS_ALREADY_EXISTS_REMOTELY || constructionState==RM3CS_ALREADY_EXISTS_REMOTELY_DO_NOT_CONSTRUCT) - { - OnReplicaAlreadyExists(index, replicaManager3); - if (constructionState==RM3CS_ALREADY_EXISTS_REMOTELY) - constructedReplicasCulled.Push(lsr->replica,_FILE_AND_LINE_); - - /* - if (constructionState==RM3CS_ALREADY_EXISTS_REMOTELY) - { - // Serialize construction data to this connection - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_REPLICA_MANAGER_3_SERIALIZE_CONSTRUCTION_EXISTING); - bsOut.Write(replicaManager3->GetWorldID()); - NetworkID networkId; - networkId=lsr->replica->GetNetworkID(); - bsOut.Write(networkId); - BitSize_t bitsWritten = bsOut.GetNumberOfBitsUsed(); - lsr->replica->SerializeConstructionExisting(&bsOut, this); - if (bsOut.GetNumberOfBitsUsed()!=bitsWritten) - replicaManager3->SendUnified(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,GetSystemAddress(), false); - } - - // Serialize first serialization to this connection. - // This is done here, as it isn't done in PushConstruction - SerializeParameters sp; - MafiaNet::BitStream emptyBs; - for (index=0; index < (unsigned int) RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; index++) - { - sp.lastSentBitstream[index]=&emptyBs; - sp.pro[index]=replicaManager3->GetDefaultSendParameters(); - } - sp.bitsWrittenSoFar=0; - sp.destinationConnection=this; - sp.messageTimestamp=0; - sp.whenLastSerialized=0; - - MafiaNet::Replica3 *replica = lsr->replica; - - RM3SerializationResult res = replica->Serialize(&sp); - if (res!=RM3SR_NEVER_SERIALIZE_FOR_THIS_CONNECTION && - res!=RM3SR_DO_NOT_SERIALIZE && - res!=RM3SR_SERIALIZED_UNIQUELY) - { - bool allIndices[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; - for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) - { - sp.bitsWrittenSoFar+=sp.outputBitstream[z].GetNumberOfBitsUsed(); - allIndices[z]=true; - } - if (SendSerialize(replica, allIndices, sp.outputBitstream, sp.messageTimestamp, sp.pro, replicaManager3->GetRakPeerInterface(), replicaManager3->GetWorldID())==SSICR_SENT_DATA) - lsr->replica->whenLastSerialized=MafiaNet::GetTimeMS(); - } - */ - } - else if (constructionState==RM3CS_SEND_CONSTRUCTION) - { - OnConstructToThisConnection(index, replicaManager3); - RakAssert(lsr->replica); - constructedReplicasCulled.Push(lsr->replica,_FILE_AND_LINE_); - } - else if (constructionState==RM3CS_NEVER_CONSTRUCT) - { - OnNeverConstruct(index, replicaManager3); - } - else// if (constructionState==RM3CS_NO_ACTION) - { - // Do nothing - index++; - } - } - - if (curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION) - { - RM3DestructionState destructionState; - index=0; - while (index < queryToDestructReplicaList.Size()) - { - lsr=queryToDestructReplicaList[index]; - destructionState=lsr->replica->QueryDestruction(this, replicaManager3); - if (destructionState==RM3DS_SEND_DESTRUCTION) - { - OnSendDestructionFromQuery(index, replicaManager3); - destroyedReplicasCulled.Push(lsr->replica,_FILE_AND_LINE_); - } - else if (destructionState==RM3DS_DO_NOT_QUERY_DESTRUCTION) - { - OnDoNotQueryDestruction(index, replicaManager3); - } - else// if (destructionState==RM3CS_NO_ACTION) - { - // Do nothing - index++; - } - } - } - } - else if (curConstructionMode==QUERY_CONNECTION_FOR_REPLICA_LIST) - { - QueryReplicaList(constructedReplicasCulled,destroyedReplicasCulled); - - unsigned int idx1, idx2; - - // Create new - for (idx2=0; idx2 < constructedReplicasCulled.Size(); idx2++) - OnConstructToThisConnection(constructedReplicasCulled[idx2], replicaManager3); - - bool exists; - for (idx2=0; idx2 < destroyedReplicasCulled.Size(); idx2++) - { - exists=false; - bool objectExists; - idx1=constructedReplicaList.GetIndexFromKey(destroyedReplicasCulled[idx2], &objectExists); - if (objectExists) - { - constructedReplicaList.RemoveAtIndex(idx1); - - unsigned int j; - for (j=0; j < queryToSerializeReplicaList.Size(); j++) - { - if (queryToSerializeReplicaList[j]->replica==destroyedReplicasCulled[idx2] ) - { - queryToSerializeReplicaList.RemoveAtIndex(j); - break; - } - } - } - } - } - - SendConstruction(constructedReplicasCulled,destroyedReplicasCulled,replicaManager3->defaultSendParameters,replicaManager3->rakPeerInterface,worldId,replicaManager3); -} -void ReplicaManager3::Update(void) -{ - unsigned int index,index2,index3; - - WorldId worldId; - RM3World *world; - MafiaNet::Time time = MafiaNet::GetTime(); - - m_WorldListMutex.Lock(); - for (index3=0; index3 < worldsList.Size(); index3++) - { - world = worldsList[index3]; - worldId = world->worldId; - - for (index=0; index < world->connectionList.Size(); index++) - { - if (world->connectionList[index]->isValidated==false) - continue; - world->connectionList[index]->AutoConstructByQuery(this, worldId); - } - } - - if (time - lastAutoSerializeOccurance >= autoSerializeInterval) - { - for (index3=0; index3 < worldsList.Size(); index3++) - { - world = worldsList[index3]; - worldId = world->worldId; - - for (index=0; index < world->userReplicaList.Size(); index++) - { - world->userReplicaList[index]->forceSendUntilNextUpdate=false; - world->userReplicaList[index]->OnUserReplicaPreSerializeTick(); - } - - SerializeParameters sp; - sp.curTime=time; - Connection_RM3 *connection; - SendSerializeIfChangedResult ssicr; - LastSerializationResult *lsr; - - sp.messageTimestamp=0; - for (int i=0; i < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; i++) - sp.pro[i]=defaultSendParameters; - index2=0; - for (index=0; index < world->connectionList.Size(); index++) - { - connection = world->connectionList[index]; - sp.bitsWrittenSoFar=0; - index2=0; - sp.destinationConnection=connection; - - DataStructures::List replicasToSerialize; - replicasToSerialize.Clear(true, _FILE_AND_LINE_); - if (connection->QuerySerializationList(replicasToSerialize)) - { - // Update replica->lsr so we can lookup in the next block - // lsr is per connection / per replica - while (index2 < connection->queryToSerializeReplicaList.Size()) - { - connection->queryToSerializeReplicaList[index2]->replica->lsr=connection->queryToSerializeReplicaList[index2]; - index2++; - } - - - // User is manually specifying list of replicas to serialize - index2=0; - while (index2 < replicasToSerialize.Size()) - { - lsr=replicasToSerialize[index2]->lsr; - RakAssert(lsr->replica==replicasToSerialize[index2]); - - sp.whenLastSerialized=lsr->whenLastSerialized; - ssicr=connection->SendSerializeIfChanged(lsr, &sp, GetRakPeerInterface(), worldId, this, time); - if (ssicr==SSICR_SENT_DATA) - lsr->whenLastSerialized=time; - index2++; - } - } - else - { - while (index2 < connection->queryToSerializeReplicaList.Size()) - { - lsr=connection->queryToSerializeReplicaList[index2]; - - sp.destinationConnection=connection; - sp.whenLastSerialized=lsr->whenLastSerialized; - ssicr=connection->SendSerializeIfChanged(lsr, &sp, GetRakPeerInterface(), worldId, this, time); - if (ssicr==SSICR_SENT_DATA) - { - lsr->whenLastSerialized=time; - index2++; - } - else if (ssicr==SSICR_NEVER_SERIALIZE) - { - // Removed from the middle of the list - } - else - index2++; - } - } - } - } - - lastAutoSerializeOccurance=time; - } - m_WorldListMutex.Unlock(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) lostConnectionReason; - (void) systemAddress; - if (autoDestroyConnections) - { - Connection_RM3 *connection = PopConnection(rakNetGUID); - if (connection) - DeallocConnection(connection); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) -{ - (void) isIncoming; - if (autoCreateConnections) - { - Connection_RM3 *connection = AllocConnection(systemAddress, rakNetGUID); - if (connection) - PushConnection(connection); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::OnRakPeerShutdown(void) -{ - if (autoDestroyConnections) - { - RM3World *world; - unsigned int index3; - m_WorldListMutex.Lock(); - for (index3=0; index3 < worldsList.Size(); index3++) - { - world = worldsList[index3]; - - while (world->connectionList.Size()) - { - Connection_RM3 *connection = PopConnection(world->connectionList.Size()-1, world->worldId); - if (connection) - DeallocConnection(connection); - } - } - m_WorldListMutex.Unlock(); - } - - - Clear(false); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void ReplicaManager3::OnDetach(void) -{ - OnRakPeerShutdown(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -PluginReceiveResult ReplicaManager3::OnConstruction(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, unsigned char packetDataOffset, WorldId worldId) -{ - RM3World *world = worldsArray[worldId]; - - Connection_RM3 *connection = GetConnectionByGUID(senderGuid, worldId); - if (connection==0) - { - // Almost certainly a bug - RakAssert("Got OnConstruction but no connection yet" && 0); - return RR_CONTINUE_PROCESSING; - } - if (connection->groupConstructionAndSerialize) - { - connection->downloadGroup.Push(packet, __FILE__, __LINE__); - return RR_STOP_PROCESSING; - } - - MafiaNet::BitStream bsIn(packetData,packetDataLength,false); - bsIn.IgnoreBytes(packetDataOffset); - uint16_t constructionObjectListSize, destructionObjectListSize, index, index2; - BitSize_t streamEnd, writeAllocationIDEnd; - Replica3 *replica; - NetworkID networkId; - RakNetGUID creatingSystemGuid; - bool actuallyCreateObject=false; - - DataStructures::List actuallyCreateObjectList; - DataStructures::List constructionTickStack; - - RakAssert(world->networkIDManager); - - bsIn.Read(constructionObjectListSize); - for (index=0; index < constructionObjectListSize; index++) - { - bsIn.Read(streamEnd); - bsIn.Read(networkId); - Replica3* existingReplica = world->networkIDManager->GET_OBJECT_FROM_ID(networkId); - bsIn.Read(actuallyCreateObject); - actuallyCreateObjectList.Push(actuallyCreateObject, _FILE_AND_LINE_); - bsIn.AlignReadToByteBoundary(); - - if (actuallyCreateObject) - { - bsIn.Read(creatingSystemGuid); - bsIn.Read(writeAllocationIDEnd); - - //printf("OnConstruction: %i\n",networkId.guid.g); // Removeme - if (existingReplica) - { - existingReplica->replicaManager=this; - - // Network ID already in use - connection->OnDownloadExisting(existingReplica, this); - - constructionTickStack.Push(0, _FILE_AND_LINE_); - bsIn.SetReadOffset(streamEnd); - continue; - } - - bsIn.AlignReadToByteBoundary(); - replica = connection->AllocReplica(&bsIn, this); - if (replica==0) - { - constructionTickStack.Push(0, _FILE_AND_LINE_); - bsIn.SetReadOffset(streamEnd); - continue; - } - - // Go past the bitStream written to with WriteAllocationID(). Necessary in case the user didn't read out the bitStream the same way it was written - // bitOffset2 is already aligned - bsIn.SetReadOffset(writeAllocationIDEnd); - - replica->SetNetworkIDManager(world->networkIDManager); - replica->SetNetworkID(networkId); - - replica->replicaManager=this; - replica->creatingSystemGUID=creatingSystemGuid; - - if (!replica->QueryRemoteConstruction(connection) || - !replica->DeserializeConstruction(&bsIn, connection)) - { - DeallocReplicaNoBroadcastDestruction(connection, replica); - bsIn.SetReadOffset(streamEnd); - constructionTickStack.Push(0, _FILE_AND_LINE_); - continue; - } - - constructionTickStack.Push(replica, _FILE_AND_LINE_); - - // Register the replica - ReferenceInternal(replica, worldId); - } - else - { - if (existingReplica) - { - existingReplica->DeserializeConstructionExisting(&bsIn, connection); - constructionTickStack.Push(existingReplica, _FILE_AND_LINE_); - } - else - { - constructionTickStack.Push(0, _FILE_AND_LINE_); - } - } - - - bsIn.SetReadOffset(streamEnd); - bsIn.AlignReadToByteBoundary(); - } - - RakAssert(constructionTickStack.Size()==constructionObjectListSize); - RakAssert(actuallyCreateObjectList.Size()==constructionObjectListSize); - - MafiaNet::BitStream empty; - for (index=0; index < constructionObjectListSize; index++) - { - bool pdcWritten=false; - bsIn.Read(pdcWritten); - if (pdcWritten) - { - bsIn.AlignReadToByteBoundary(); - bsIn.Read(streamEnd); - bsIn.Read(networkId); - if (constructionTickStack[index]!=0) - { - bsIn.AlignReadToByteBoundary(); - if (actuallyCreateObjectList[index]) - constructionTickStack[index]->PostDeserializeConstruction(&bsIn, connection); - else - constructionTickStack[index]->PostDeserializeConstructionExisting(&bsIn, connection); - } - bsIn.SetReadOffset(streamEnd); - } - else - { - if (constructionTickStack[index]!=0) - { - if (actuallyCreateObjectList[index]) - constructionTickStack[index]->PostDeserializeConstruction(&empty, connection); - else - constructionTickStack[index]->PostDeserializeConstructionExisting(&empty, connection); - } - } - } - bsIn.AlignReadToByteBoundary(); - - for (index=0; index < constructionObjectListSize; index++) - { - if (constructionTickStack[index]!=0) - { - if (actuallyCreateObjectList[index]) - { - // Tell the connection(s) that this object exists since they just sent it to us - connection->OnDownloadFromThisSystem(constructionTickStack[index], this); - - for (index2=0; index2 < world->connectionList.Size(); index2++) - { - if (world->connectionList[index2]!=connection) - world->connectionList[index2]->OnDownloadFromOtherSystem(constructionTickStack[index], this); - } - } - } - } - - // Destructions - bool b = bsIn.Read(destructionObjectListSize); - (void) b; - RakAssert(b); - for (index=0; index < destructionObjectListSize; index++) - { - bsIn.Read(networkId); - bsIn.Read(streamEnd); - replica = world->networkIDManager->GET_OBJECT_FROM_ID(networkId); - if (replica==0) - { - // Unknown object - bsIn.SetReadOffset(streamEnd); - continue; - } - bsIn.Read(replica->deletingSystemGUID); - if (replica->DeserializeDestruction(&bsIn,connection)) - { - // Make sure it wasn't deleted in DeserializeDestruction - if (world->networkIDManager->GET_OBJECT_FROM_ID(networkId)) - { - replica->PreDestruction(connection); - - // Forward deletion by remote system - if (replica->QueryRelayDestruction(connection)) - BroadcastDestruction(replica,connection->GetSystemAddress()); - Dereference(replica); - DeallocReplicaNoBroadcastDestruction(connection, replica); - } - } - else - { - replica->PreDestruction(connection); - connection->OnDereference(replica, this); - } - - bsIn.AlignReadToByteBoundary(); - } - return RR_CONTINUE_PROCESSING; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -PluginReceiveResult ReplicaManager3::OnSerialize(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, MafiaNet::Time timestamp, unsigned char packetDataOffset, WorldId worldId) -{ - Connection_RM3 *connection = GetConnectionByGUID(senderGuid, worldId); - if (connection==0) - return RR_CONTINUE_PROCESSING; - if (connection->groupConstructionAndSerialize) - { - connection->downloadGroup.Push(packet, __FILE__, __LINE__); - return RR_STOP_PROCESSING; - } - - RM3World *world = worldsArray[worldId]; - RakAssert(world->networkIDManager); - MafiaNet::BitStream bsIn(packetData,packetDataLength,false); - bsIn.IgnoreBytes(packetDataOffset); - - struct DeserializeParameters ds; - ds.timeStamp=timestamp; - ds.sourceConnection=connection; - - Replica3 *replica; - NetworkID networkId; - BitSize_t bitsUsed; - bsIn.Read(networkId); - //printf("OnSerialize: %i\n",networkId.guid.g); // Removeme - replica = world->networkIDManager->GET_OBJECT_FROM_ID(networkId); - if (replica) - { - for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) - { - bsIn.Read(ds.bitstreamWrittenTo[z]); - if (ds.bitstreamWrittenTo[z]) - { - bsIn.ReadCompressed(bitsUsed); - bsIn.AlignReadToByteBoundary(); - bsIn.Read(ds.serializationBitstream[z], bitsUsed); - } - } - replica->Deserialize(&ds); - } - return RR_CONTINUE_PROCESSING; -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -PluginReceiveResult ReplicaManager3::OnDownloadStarted(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, unsigned char packetDataOffset, WorldId worldId) -{ - Connection_RM3 *connection = GetConnectionByGUID(senderGuid, worldId); - if (connection==0) - return RR_CONTINUE_PROCESSING; - if (connection->QueryGroupDownloadMessages() && - // ID_DOWNLOAD_STARTED will be processed twice, being processed the second time once ID_DOWNLOAD_COMPLETE arrives. - // However, the second time groupConstructionAndSerialize will be set to true so it won't be processed a third time - connection->groupConstructionAndSerialize==false - ) - { - // These messages will be held by the plugin and returned when the download is complete - connection->groupConstructionAndSerialize=true; - RakAssert(connection->downloadGroup.Size()==0); - connection->downloadGroup.Push(packet, __FILE__, __LINE__); - return RR_STOP_PROCESSING; - } - - connection->groupConstructionAndSerialize=false; - MafiaNet::BitStream bsIn(packetData,packetDataLength,false); - bsIn.IgnoreBytes(packetDataOffset); - connection->DeserializeOnDownloadStarted(&bsIn); - return RR_CONTINUE_PROCESSING; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -PluginReceiveResult ReplicaManager3::OnDownloadComplete(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, unsigned char packetDataOffset, WorldId worldId) -{ - Connection_RM3 *connection = GetConnectionByGUID(senderGuid, worldId); - if (connection==0) - return RR_CONTINUE_PROCESSING; - - if (connection->groupConstructionAndSerialize==true && connection->downloadGroup.Size()>0) - { - // Push back buffered packets in front of this one - unsigned int i; - for (i=0; i < connection->downloadGroup.Size(); i++) - rakPeerInterface->PushBackPacket(connection->downloadGroup[i],false); - - // Push this one to be last too. It will be processed again, but the second time - // groupConstructionAndSerialize will be false and downloadGroup will be empty, so it will go past this block - connection->downloadGroup.Clear(__FILE__,__LINE__); - rakPeerInterface->PushBackPacket(packet,false); - - return RR_STOP_PROCESSING; - } - - MafiaNet::BitStream bsIn(packetData,packetDataLength,false); - bsIn.IgnoreBytes(packetDataOffset); - connection->gotDownloadComplete=true; - connection->DeserializeOnDownloadComplete(&bsIn); - return RR_CONTINUE_PROCESSING; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -Replica3* ReplicaManager3::GetReplicaByNetworkID(NetworkID networkId, WorldId worldId) -{ - RM3World *world = worldsArray[worldId]; - - unsigned int i; - for (i=0; i < world->userReplicaList.Size(); i++) - { - if (world->userReplicaList[i]->GetNetworkID()==networkId) - return world->userReplicaList[i]; - } - return 0; -} - - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - -void ReplicaManager3::BroadcastDestructionList(DataStructures::List &replicaListSource, const SystemAddress &exclusionAddress, WorldId worldId) -{ - MafiaNet::BitStream bsOut; - unsigned int i,j; - - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - RM3World *world = worldsArray[worldId]; - - DataStructures::List replicaList; - - for (i=0; i < replicaListSource.Size(); i++) - { - if (replicaListSource[i]==currentlyDeallocatingReplica) - continue; - replicaList.Push(replicaListSource[i], __FILE__, __LINE__); - } - - if (replicaList.Size()==0) - return; - - for (i=0; i < replicaList.Size(); i++) - { - if (replicaList[i]->deletingSystemGUID==UNASSIGNED_RAKNET_GUID) - replicaList[i]->deletingSystemGUID=GetRakPeerInterface()->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); - } - - for (j=0; j < world->connectionList.Size(); j++) - { - if (world->connectionList[j]->GetSystemAddress()==exclusionAddress) - continue; - - bsOut.Reset(); - bsOut.Write((MessageID)ID_REPLICA_MANAGER_CONSTRUCTION); - bsOut.Write(worldId); - uint16_t cnt=0; - bsOut.Write(cnt); // No construction - cnt=(uint16_t) replicaList.Size(); - BitSize_t cntOffset=bsOut.GetWriteOffset();; - bsOut.Write(cnt); // Overwritten at send call - cnt=0; - - for (i=0; i < replicaList.Size(); i++) - { - if (world->connectionList[j]->HasReplicaConstructed(replicaList[i])==false) - continue; - cnt++; - - NetworkID networkId; - networkId=replicaList[i]->GetNetworkID(); - bsOut.Write(networkId); - BitSize_t offsetStart, offsetEnd; - offsetStart=bsOut.GetWriteOffset(); - bsOut.Write(offsetStart); - bsOut.Write(replicaList[i]->deletingSystemGUID); - replicaList[i]->SerializeDestruction(&bsOut, world->connectionList[j]); - bsOut.AlignWriteToByteBoundary(); - offsetEnd=bsOut.GetWriteOffset(); - bsOut.SetWriteOffset(offsetStart); - bsOut.Write(offsetEnd); - bsOut.SetWriteOffset(offsetEnd); - } - - if (cnt>0) - { - BitSize_t curOffset=bsOut.GetWriteOffset(); - bsOut.SetWriteOffset(cntOffset); - bsOut.Write(cnt); - bsOut.SetWriteOffset(curOffset); - rakPeerInterface->Send(&bsOut,defaultSendParameters.priority,defaultSendParameters.reliability,defaultSendParameters.orderingChannel,world->connectionList[j]->GetSystemAddress(),false, defaultSendParameters.sendReceipt); - } - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - -void ReplicaManager3::BroadcastDestruction(Replica3 *replica, const SystemAddress &exclusionAddress) -{ - DataStructures::List replicaList; - replicaList.Push(replica, _FILE_AND_LINE_ ); - BroadcastDestructionList(replicaList,exclusionAddress); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -Connection_RM3::Connection_RM3(const SystemAddress &_systemAddress, RakNetGUID _guid) -: systemAddress(_systemAddress), guid(_guid) -{ - isValidated=false; - isFirstConstruction=true; - groupConstructionAndSerialize=false; - gotDownloadComplete=false; - virtualWorld=VIRTUAL_WORLD_DEFAULT; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -Connection_RM3::~Connection_RM3() -{ - unsigned int i; - for (i=0; i < constructedReplicaList.Size(); i++) - MafiaNet::OP_DELETE(constructedReplicaList[i], _FILE_AND_LINE_); - for (i=0; i < queryToConstructReplicaList.Size(); i++) - MafiaNet::OP_DELETE(queryToConstructReplicaList[i], _FILE_AND_LINE_); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::GetConstructedReplicas(DataStructures::List &objectsTheyDoHave) -{ - objectsTheyDoHave.Clear(true,_FILE_AND_LINE_); - for (unsigned int idx=0; idx < constructedReplicaList.Size(); idx++) - { - objectsTheyDoHave.Push(constructedReplicaList[idx]->replica, _FILE_AND_LINE_ ); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool Connection_RM3::HasReplicaConstructed(MafiaNet::Replica3 *replica) -{ - bool objectExists; - constructedReplicaList.GetIndexFromKey(replica, &objectExists); - return objectExists; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void Connection_RM3::SendSerializeHeader(MafiaNet::Replica3 *replica, MafiaNet::Time timestamp, MafiaNet::BitStream *bs, WorldId worldId) -{ - bs->Reset(); - - if (timestamp!=0) - { - bs->Write((MessageID)ID_TIMESTAMP); - bs->Write(timestamp); - } - bs->Write((MessageID)ID_REPLICA_MANAGER_SERIALIZE); - bs->Write(worldId); - bs->Write(replica->GetNetworkID()); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void Connection_RM3::ClearDownloadGroup(RakPeerInterface *rakPeerInterface) -{ - unsigned int i; - for (i=0; i < downloadGroup.Size(); i++) - rakPeerInterface->DeallocatePacket(downloadGroup[i]); - downloadGroup.Clear(__FILE__,__LINE__); -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -SendSerializeIfChangedResult Connection_RM3::SendSerialize(MafiaNet::Replica3 *replica, bool indicesToSend[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], MafiaNet::BitStream serializationData[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], MafiaNet::Time timestamp, PRO sendParameters[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], RakPeerInterface *rakPeer, unsigned char worldId, MafiaNet::Time curTime) -{ - bool channelHasData; - BitSize_t sum=0; - for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) - { - if (indicesToSend[z]) - sum+=serializationData[z].GetNumberOfBitsUsed(); - } - - MafiaNet::BitStream out; - BitSize_t bitsPerChannel[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; - - if (sum==0) - { - memset(bitsPerChannel, 0, sizeof(bitsPerChannel)); - replica->OnSerializeTransmission(&out, this, bitsPerChannel, curTime); - return SSICR_DID_NOT_SEND_DATA; - } - - RakAssert(replica->GetNetworkID()!=UNASSIGNED_NETWORK_ID); - - BitSize_t bitsUsed; - - int channelIndex; - PRO lastPro=sendParameters[0]; - - for (channelIndex=0; channelIndex < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; channelIndex++) - { - if (channelIndex==0) - { - SendSerializeHeader(replica, timestamp, &out, worldId); - } - else if (lastPro!=sendParameters[channelIndex]) - { - // Write out remainder - for (int channelIndex2=channelIndex; channelIndex2 < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; channelIndex2++) - { - bitsPerChannel[channelIndex2]=0; - out.Write(false); - } - - // Send remainder - replica->OnSerializeTransmission(&out, this, bitsPerChannel, curTime); - rakPeer->Send(&out,lastPro.priority,lastPro.reliability,lastPro.orderingChannel,systemAddress,false,lastPro.sendReceipt); - - // If no data left to send, quit out - bool anyData=false; - for (int channelIndex2=channelIndex; channelIndex2 < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; channelIndex2++) - { - if (serializationData[channelIndex2].GetNumberOfBitsUsed()>0) - { - anyData=true; - break; - } - } - if (anyData==false) - return SSICR_SENT_DATA; - - // Restart stream - SendSerializeHeader(replica, timestamp, &out, worldId); - - for (int channelIndex2=0; channelIndex2 < channelIndex; channelIndex2++) - { - bitsPerChannel[channelIndex2]=0; - out.Write(false); - } - lastPro=sendParameters[channelIndex]; - } - - bitsUsed=serializationData[channelIndex].GetNumberOfBitsUsed(); - channelHasData = indicesToSend[channelIndex]==true && bitsUsed>0; - out.Write(channelHasData); - if (channelHasData) - { - bitsPerChannel[channelIndex] = bitsUsed; - out.WriteCompressed(bitsUsed); - out.AlignWriteToByteBoundary(); - out.Write(serializationData[channelIndex]); - // Crap, forgot this line, was a huge bug in that I'd only send to the first 3 systems - serializationData[channelIndex].ResetReadPointer(); - } - else - { - bitsPerChannel[channelIndex] = 0; - } - } - replica->OnSerializeTransmission(&out, this, bitsPerChannel, curTime); - rakPeer->Send(&out,lastPro.priority,lastPro.reliability,lastPro.orderingChannel,systemAddress,false,lastPro.sendReceipt); - return SSICR_SENT_DATA; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -SendSerializeIfChangedResult Connection_RM3::SendSerializeIfChanged(LastSerializationResult *lsr, SerializeParameters *sp, MafiaNet::RakPeerInterface *rakPeer, unsigned char worldId, ReplicaManager3 *replicaManager, MafiaNet::Time curTime) -{ - MafiaNet::Replica3 *replica = lsr->replica; - - if (replica->GetNetworkID()==UNASSIGNED_NETWORK_ID) - return SSICR_DID_NOT_SEND_DATA; - - RM3QuerySerializationResult rm3qsr = replica->QuerySerialization(this); - if (rm3qsr==RM3QSR_NEVER_CALL_SERIALIZE) - { - // Never again for this connection and replica pair - OnNeverSerialize(lsr, replicaManager); - return SSICR_NEVER_SERIALIZE; - } - - if (rm3qsr==RM3QSR_DO_NOT_CALL_SERIALIZE) - return SSICR_DID_NOT_SEND_DATA; - - if (replica->forceSendUntilNextUpdate) - { - for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) - { - if (replica->lastSentSerialization.indicesToSend[z]) - sp->bitsWrittenSoFar+=replica->lastSentSerialization.bitStream[z].GetNumberOfBitsUsed(); - } - return SendSerialize(replica, replica->lastSentSerialization.indicesToSend, replica->lastSentSerialization.bitStream, sp->messageTimestamp, sp->pro, rakPeer, worldId, curTime); - } - - for (int i=0; i < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; i++) - { - sp->outputBitstream[i].Reset(); - if (lsr->lastSerializationResultBS) - sp->lastSentBitstream[i]=&lsr->lastSerializationResultBS->bitStream[i]; - else - sp->lastSentBitstream[i]=&replica->lastSentSerialization.bitStream[i]; - } - - RM3SerializationResult serializationResult = replica->Serialize(sp); - - if (serializationResult==RM3SR_NEVER_SERIALIZE_FOR_THIS_CONNECTION) - { - // Never again for this connection and replica pair - OnNeverSerialize(lsr, replicaManager); - return SSICR_NEVER_SERIALIZE; - } - - if (serializationResult==RM3SR_DO_NOT_SERIALIZE) - { - // Don't serialize this tick only - return SSICR_DID_NOT_SEND_DATA; - } - - // This is necessary in case the user in the Serialize() function for some reason read the bitstream they also wrote - // WIthout this code, the Write calls to another bitstream would not write the entire bitstream - BitSize_t sum=0; - for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) - { - sp->outputBitstream[z].ResetReadPointer(); - sum+=sp->outputBitstream[z].GetNumberOfBitsUsed(); - } - - if (sum==0) - { - // Don't serialize this tick only - return SSICR_DID_NOT_SEND_DATA; - } - - if (serializationResult==RM3SR_SERIALIZED_ALWAYS) - { - bool allIndices[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; - for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) - { - sp->bitsWrittenSoFar+=sp->outputBitstream[z].GetNumberOfBitsUsed(); - allIndices[z]=true; - - lsr->AllocBS(); - lsr->lastSerializationResultBS->bitStream[z].Reset(); - lsr->lastSerializationResultBS->bitStream[z].Write(&sp->outputBitstream[z]); - sp->outputBitstream[z].ResetReadPointer(); - } - return SendSerialize(replica, allIndices, sp->outputBitstream, sp->messageTimestamp, sp->pro, rakPeer, worldId, curTime); - } - - if (serializationResult==RM3SR_SERIALIZED_ALWAYS_IDENTICALLY) - { - for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) - { - replica->lastSentSerialization.indicesToSend[z]=sp->outputBitstream[z].GetNumberOfBitsUsed()>0; - sp->bitsWrittenSoFar+=sp->outputBitstream[z].GetNumberOfBitsUsed(); - replica->lastSentSerialization.bitStream[z].Reset(); - replica->lastSentSerialization.bitStream[z].Write(&sp->outputBitstream[z]); - sp->outputBitstream[z].ResetReadPointer(); - replica->forceSendUntilNextUpdate=true; - } - return SendSerialize(replica, replica->lastSentSerialization.indicesToSend, sp->outputBitstream, sp->messageTimestamp, sp->pro, rakPeer, worldId, curTime); - } - - bool indicesToSend[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; - if (serializationResult==RM3SR_BROADCAST_IDENTICALLY || serializationResult==RM3SR_BROADCAST_IDENTICALLY_FORCE_SERIALIZATION) - { - for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) - { - if (sp->outputBitstream[z].GetNumberOfBitsUsed() > 0 && - (serializationResult==RM3SR_BROADCAST_IDENTICALLY_FORCE_SERIALIZATION || - ((sp->outputBitstream[z].GetNumberOfBitsUsed()!=replica->lastSentSerialization.bitStream[z].GetNumberOfBitsUsed() || - memcmp(sp->outputBitstream[z].GetData(), replica->lastSentSerialization.bitStream[z].GetData(), sp->outputBitstream[z].GetNumberOfBytesUsed())!=0)))) - { - indicesToSend[z]=true; - replica->lastSentSerialization.indicesToSend[z]=true; - sp->bitsWrittenSoFar+=sp->outputBitstream[z].GetNumberOfBitsUsed(); - replica->lastSentSerialization.bitStream[z].Reset(); - replica->lastSentSerialization.bitStream[z].Write(&sp->outputBitstream[z]); - sp->outputBitstream[z].ResetReadPointer(); - replica->forceSendUntilNextUpdate=true; - } - else - { - indicesToSend[z]=false; - replica->lastSentSerialization.indicesToSend[z]=false; - } - } - } - else - { - lsr->AllocBS(); - - // RM3SR_SERIALIZED_UNIQUELY - for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) - { - if (sp->outputBitstream[z].GetNumberOfBitsUsed() > 0 && - (sp->outputBitstream[z].GetNumberOfBitsUsed()!=lsr->lastSerializationResultBS->bitStream[z].GetNumberOfBitsUsed() || - memcmp(sp->outputBitstream[z].GetData(), lsr->lastSerializationResultBS->bitStream[z].GetData(), sp->outputBitstream[z].GetNumberOfBytesUsed())!=0) - ) - { - indicesToSend[z]=true; - sp->bitsWrittenSoFar+=sp->outputBitstream[z].GetNumberOfBitsUsed(); - lsr->lastSerializationResultBS->bitStream[z].Reset(); - lsr->lastSerializationResultBS->bitStream[z].Write(&sp->outputBitstream[z]); - sp->outputBitstream[z].ResetReadPointer(); - } - else - { - indicesToSend[z]=false; - } - } - } - - - if (serializationResult==RM3SR_BROADCAST_IDENTICALLY || serializationResult==RM3SR_BROADCAST_IDENTICALLY_FORCE_SERIALIZATION) - replica->forceSendUntilNextUpdate=true; - - // Send out the data - return SendSerialize(replica, indicesToSend, sp->outputBitstream, sp->messageTimestamp, sp->pro, rakPeer, worldId, curTime); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -void Connection_RM3::OnLocalReference(Replica3* replica3, ReplicaManager3 *replicaManager) -{ - ConstructionMode curConstructionMode = QueryConstructionMode(); - RakAssert(curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION); - RakAssert(replica3); - (void) replicaManager; - (void) curConstructionMode; - -#ifdef _DEBUG - for (unsigned int i=0; i < queryToConstructReplicaList.Size(); i++) - { - if (queryToConstructReplicaList[i]->replica==replica3) - { - RakAssert("replica added twice to queryToConstructReplicaList" && 0); - } - } - - if (constructedReplicaList.HasData(replica3)==true) - { - RakAssert("replica added to queryToConstructReplicaList when already in constructedReplicaList" && 0); - } -#endif - - LastSerializationResult* lsr= MafiaNet::OP_NEW(_FILE_AND_LINE_); - lsr->replica=replica3; - queryToConstructReplicaList.Push(lsr,_FILE_AND_LINE_); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::OnDereference(Replica3* replica3, ReplicaManager3 *replicaManager) -{ - ValidateLists(replicaManager); - - if (replica3->GetNetworkIDManager() == 0) - return; - - LastSerializationResult* lsr=0; - unsigned int idx; - - bool objectExists; - idx=constructedReplicaList.GetIndexFromKey(replica3, &objectExists); - if (objectExists) - { - lsr=constructedReplicaList[idx]; - constructedReplicaList.RemoveAtIndex(idx); - } - - for (idx=0; idx < queryToConstructReplicaList.Size(); idx++) - { - if (queryToConstructReplicaList[idx]->replica==replica3) - { - lsr=queryToConstructReplicaList[idx]; - queryToConstructReplicaList.RemoveAtIndex(idx); - break; - } - } - - for (idx=0; idx < queryToSerializeReplicaList.Size(); idx++) - { - if (queryToSerializeReplicaList[idx]->replica==replica3) - { - lsr=queryToSerializeReplicaList[idx]; - queryToSerializeReplicaList.RemoveAtIndex(idx); - break; - } - } - - for (idx=0; idx < queryToDestructReplicaList.Size(); idx++) - { - if (queryToDestructReplicaList[idx]->replica==replica3) - { - lsr=queryToDestructReplicaList[idx]; - queryToDestructReplicaList.RemoveAtIndex(idx); - break; - } - } - - ValidateLists(replicaManager); - - if (lsr) - MafiaNet::OP_DELETE(lsr,_FILE_AND_LINE_); - - ValidateLists(replicaManager); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::OnDownloadFromThisSystem(Replica3* replica3, ReplicaManager3 *replicaManager) -{ - RakAssert(replica3); - - ValidateLists(replicaManager); - LastSerializationResult* lsr= MafiaNet::OP_NEW(_FILE_AND_LINE_); - lsr->replica=replica3; - - ConstructionMode curConstructionMode = QueryConstructionMode(); - if (curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION) - { - unsigned int j; - for (j=0; j < queryToConstructReplicaList.Size(); j++) - { - if (queryToConstructReplicaList[j]->replica==replica3 ) - { - queryToConstructReplicaList.RemoveAtIndex(j); - break; - } - } - - queryToDestructReplicaList.Push(lsr,_FILE_AND_LINE_); - } - - if (constructedReplicaList.Insert(lsr->replica, lsr, true, _FILE_AND_LINE_) != (unsigned) -1) - { - //assert(queryToSerializeReplicaList.GetIndexOf(replica3)==(unsigned int)-1); - queryToSerializeReplicaList.Push(lsr,_FILE_AND_LINE_); - } - - ValidateLists(replicaManager); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::OnDownloadFromOtherSystem(Replica3* replica3, ReplicaManager3 *replicaManager) -{ - ConstructionMode curConstructionMode = QueryConstructionMode(); - if (curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION) - { - unsigned int j; - for (j=0; j < queryToConstructReplicaList.Size(); j++) - { - if (queryToConstructReplicaList[j]->replica==replica3 ) - { - return; - } - } - - OnLocalReference(replica3, replicaManager); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::OnNeverConstruct(unsigned int queryToConstructIdx, ReplicaManager3 *replicaManager) -{ - ConstructionMode curConstructionMode = QueryConstructionMode(); - RakAssert(curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION); - (void) curConstructionMode; - - ValidateLists(replicaManager); - LastSerializationResult* lsr = queryToConstructReplicaList[queryToConstructIdx]; - queryToConstructReplicaList.RemoveAtIndex(queryToConstructIdx); - MafiaNet::OP_DELETE(lsr,_FILE_AND_LINE_); - ValidateLists(replicaManager); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::OnConstructToThisConnection(unsigned int queryToConstructIdx, ReplicaManager3 *replicaManager) -{ - ConstructionMode curConstructionMode = QueryConstructionMode(); - RakAssert(curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION); - (void) curConstructionMode; - - ValidateLists(replicaManager); - LastSerializationResult* lsr = queryToConstructReplicaList[queryToConstructIdx]; - queryToConstructReplicaList.RemoveAtIndex(queryToConstructIdx); - //assert(constructedReplicaList.GetIndexOf(lsr->replica)==(unsigned int)-1); - constructedReplicaList.Insert(lsr->replica,lsr,true,_FILE_AND_LINE_); - //assert(queryToDestructReplicaList.GetIndexOf(lsr->replica)==(unsigned int)-1); - queryToDestructReplicaList.Push(lsr,_FILE_AND_LINE_); - //assert(queryToSerializeReplicaList.GetIndexOf(lsr->replica)==(unsigned int)-1); - queryToSerializeReplicaList.Push(lsr,_FILE_AND_LINE_); - ValidateLists(replicaManager); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::OnConstructToThisConnection(Replica3 *replica, ReplicaManager3 *replicaManager) -{ - RakAssert(replica); - RakAssert(QueryConstructionMode()==QUERY_CONNECTION_FOR_REPLICA_LIST); - (void) replicaManager; - - LastSerializationResult* lsr= MafiaNet::OP_NEW(_FILE_AND_LINE_); - lsr->replica=replica; - constructedReplicaList.Insert(replica,lsr,true,_FILE_AND_LINE_); - queryToSerializeReplicaList.Push(lsr,_FILE_AND_LINE_); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::OnNeverSerialize(LastSerializationResult *lsr, ReplicaManager3 *replicaManager) -{ - ValidateLists(replicaManager); - - unsigned int j; - for (j=0; j < queryToSerializeReplicaList.Size(); j++) - { - if (queryToSerializeReplicaList[j]==lsr ) - { - queryToSerializeReplicaList.RemoveAtIndex(j); - break; - } - } - - ValidateLists(replicaManager); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::OnReplicaAlreadyExists(unsigned int queryToConstructIdx, ReplicaManager3 *replicaManager) -{ - ConstructionMode curConstructionMode = QueryConstructionMode(); - RakAssert(curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION); - (void) curConstructionMode; - - ValidateLists(replicaManager); - LastSerializationResult* lsr = queryToConstructReplicaList[queryToConstructIdx]; - queryToConstructReplicaList.RemoveAtIndex(queryToConstructIdx); - //assert(constructedReplicaList.GetIndexOf(lsr->replica)==(unsigned int)-1); - constructedReplicaList.Insert(lsr->replica,lsr,true,_FILE_AND_LINE_); - //assert(queryToDestructReplicaList.GetIndexOf(lsr->replica)==(unsigned int)-1); - queryToDestructReplicaList.Push(lsr,_FILE_AND_LINE_); - //assert(queryToSerializeReplicaList.GetIndexOf(lsr->replica)==(unsigned int)-1); - queryToSerializeReplicaList.Push(lsr,_FILE_AND_LINE_); - ValidateLists(replicaManager); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::OnDownloadExisting(Replica3* replica3, ReplicaManager3 *replicaManager) -{ - ValidateLists(replicaManager); - - ConstructionMode curConstructionMode = QueryConstructionMode(); - if (curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION) - { - unsigned int idx; - for (idx=0; idx < queryToConstructReplicaList.Size(); idx++) - { - if (queryToConstructReplicaList[idx]->replica==replica3) - { - OnConstructToThisConnection(idx, replicaManager); - return; - } - } - } - else - { - OnConstructToThisConnection(replica3, replicaManager); - } -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::OnSendDestructionFromQuery(unsigned int queryToDestructIdx, ReplicaManager3 *replicaManager) -{ - ConstructionMode curConstructionMode = QueryConstructionMode(); - RakAssert(curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || curConstructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION); - (void) curConstructionMode; - - ValidateLists(replicaManager); - LastSerializationResult* lsr = queryToDestructReplicaList[queryToDestructIdx]; - queryToDestructReplicaList.RemoveAtIndex(queryToDestructIdx); - unsigned int j; - for (j=0; j < queryToSerializeReplicaList.Size(); j++) - { - if (queryToSerializeReplicaList[j]->replica==lsr->replica ) - { - queryToSerializeReplicaList.RemoveAtIndex(j); - break; - } - } - for (j=0; j < constructedReplicaList.Size(); j++) - { - if (constructedReplicaList[j]->replica==lsr->replica ) - { - constructedReplicaList.RemoveAtIndex(j); - break; - } - } - //assert(queryToConstructReplicaList.GetIndexOf(lsr->replica)==(unsigned int)-1); - queryToConstructReplicaList.Push(lsr,_FILE_AND_LINE_); - ValidateLists(replicaManager); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::OnDoNotQueryDestruction(unsigned int queryToDestructIdx, ReplicaManager3 *replicaManager) -{ - ValidateLists(replicaManager); - queryToDestructReplicaList.RemoveAtIndex(queryToDestructIdx); - ValidateLists(replicaManager); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::ValidateLists(ReplicaManager3 *replicaManager) const -{ - (void) replicaManager; - /* -#ifdef _DEBUG - // Each object should exist only once in either constructedReplicaList or queryToConstructReplicaList - // replicaPointer from LastSerializationResult should be same among all lists - unsigned int idx, idx2; - for (idx=0; idx < constructedReplicaList.Size(); idx++) - { - idx2=queryToConstructReplicaList.GetIndexOf(constructedReplicaList[idx]->replica); - if (idx2!=(unsigned int)-1) - { - int a=5; - assert(a==0); - int *b=0; - *b=5; - } - } - - for (idx=0; idx < queryToConstructReplicaList.Size(); idx++) - { - idx2=constructedReplicaList.GetIndexOf(queryToConstructReplicaList[idx]->replica); - if (idx2!=(unsigned int)-1) - { - int a=5; - assert(a==0); - int *b=0; - *b=5; - } - } - - LastSerializationResult *lsr, *lsr2; - for (idx=0; idx < constructedReplicaList.Size(); idx++) - { - lsr=constructedReplicaList[idx]; - - idx2=queryToSerializeReplicaList.GetIndexOf(lsr->replica); - if (idx2!=(unsigned int)-1) - { - lsr2=queryToSerializeReplicaList[idx2]; - if (lsr2!=lsr) - { - int a=5; - assert(a==0); - int *b=0; - *b=5; - } - } - - idx2=queryToDestructReplicaList.GetIndexOf(lsr->replica); - if (idx2!=(unsigned int)-1) - { - lsr2=queryToDestructReplicaList[idx2]; - if (lsr2!=lsr) - { - int a=5; - assert(a==0); - int *b=0; - *b=5; - } - } - } - for (idx=0; idx < queryToConstructReplicaList.Size(); idx++) - { - lsr=queryToConstructReplicaList[idx]; - - idx2=queryToSerializeReplicaList.GetIndexOf(lsr->replica); - if (idx2!=(unsigned int)-1) - { - lsr2=queryToSerializeReplicaList[idx2]; - if (lsr2!=lsr) - { - int a=5; - assert(a==0); - int *b=0; - *b=5; - } - } - - idx2=queryToDestructReplicaList.GetIndexOf(lsr->replica); - if (idx2!=(unsigned int)-1) - { - lsr2=queryToDestructReplicaList[idx2]; - if (lsr2!=lsr) - { - int a=5; - assert(a==0); - int *b=0; - *b=5; - } - } - } - - // Verify pointer integrity - for (idx=0; idx < constructedReplicaList.Size(); idx++) - { - if (constructedReplicaList[idx]->replica->replicaManager!=replicaManager) - { - int a=5; - assert(a==0); - int *b=0; - *b=5; - } - } - - // Verify pointer integrity - for (idx=0; idx < queryToConstructReplicaList.Size(); idx++) - { - if (queryToConstructReplicaList[idx]->replica->replicaManager!=replicaManager) - { - int a=5; - assert(a==0); - int *b=0; - *b=5; - } - } -#endif - */ -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::SendConstruction(DataStructures::List &newObjects, DataStructures::List &deletedObjects, PRO sendParameters, MafiaNet::RakPeerInterface *rakPeer, unsigned char worldId, ReplicaManager3 *replicaManager3) -{ - if (newObjects.Size()==0 && deletedObjects.Size()==0) - return; - - // All construction and destruction takes place in the same network message - // Otherwise, if objects rely on each other being created the same tick to be valid, this won't always be true - // DataStructures::List serializedObjects; - BitSize_t offsetStart, offsetStart2, offsetEnd; - unsigned int newListIndex, oldListIndex; - MafiaNet::BitStream bsOut; - NetworkID networkId; - if (isFirstConstruction) - { - bsOut.Write((MessageID)ID_REPLICA_MANAGER_DOWNLOAD_STARTED); - bsOut.Write(worldId); - SerializeOnDownloadStarted(&bsOut); - rakPeer->Send(&bsOut,sendParameters.priority,MafiaNet::Reliability::ReliableOrdered,sendParameters.orderingChannel,systemAddress,false,sendParameters.sendReceipt); - } - - // LastSerializationResult* lsr; - bsOut.Reset(); - bsOut.Write((MessageID)ID_REPLICA_MANAGER_CONSTRUCTION); - bsOut.Write(worldId); - uint16_t objectSize = (uint16_t) newObjects.Size(); - bsOut.Write(objectSize); - - // Construction - for (newListIndex=0; newListIndex < newObjects.Size(); newListIndex++) - { - offsetStart=bsOut.GetWriteOffset(); - bsOut.Write(offsetStart); // overwritten to point to the end of the stream - networkId=newObjects[newListIndex]->GetNetworkID(); - bsOut.Write(networkId); - - RM3ConstructionState cs = newObjects[newListIndex]->QueryConstruction(this, replicaManager3); - bool actuallyCreateObject = cs==RM3CS_SEND_CONSTRUCTION; - bsOut.Write(actuallyCreateObject); - bsOut.AlignWriteToByteBoundary(); - - if (actuallyCreateObject) - { - // Actually create the object - bsOut.Write(newObjects[newListIndex]->creatingSystemGUID); - offsetStart2=bsOut.GetWriteOffset(); - bsOut.Write(offsetStart2); // overwritten to point to after the call to WriteAllocationID - bsOut.AlignWriteToByteBoundary(); // Give the user an aligned bitStream in case they use memcpy - newObjects[newListIndex]->WriteAllocationID(this, &bsOut); - bsOut.AlignWriteToByteBoundary(); // Give the user an aligned bitStream in case they use memcpy - offsetEnd=bsOut.GetWriteOffset(); - bsOut.SetWriteOffset(offsetStart2); - bsOut.Write(offsetEnd); - bsOut.SetWriteOffset(offsetEnd); - newObjects[newListIndex]->SerializeConstruction(&bsOut, this); - } - else - { - newObjects[newListIndex]->SerializeConstructionExisting(&bsOut, this); - } - - bsOut.AlignWriteToByteBoundary(); - offsetEnd=bsOut.GetWriteOffset(); - bsOut.SetWriteOffset(offsetStart); - bsOut.Write(offsetEnd); - bsOut.SetWriteOffset(offsetEnd); - } - - MafiaNet::BitStream bsOut2; - for (newListIndex=0; newListIndex < newObjects.Size(); newListIndex++) - { - bsOut2.Reset(); - RM3ConstructionState cs = newObjects[newListIndex]->QueryConstruction(this, replicaManager3); - if (cs==RM3CS_SEND_CONSTRUCTION) - { - newObjects[newListIndex]->PostSerializeConstruction(&bsOut2, this); - } - else - { - RakAssert(cs==RM3CS_ALREADY_EXISTS_REMOTELY); - newObjects[newListIndex]->PostSerializeConstructionExisting(&bsOut2, this); - } - if (bsOut2.GetNumberOfBitsUsed()>0) - { - bsOut.Write(true); - bsOut.AlignWriteToByteBoundary(); - offsetStart=bsOut.GetWriteOffset(); - bsOut.Write(offsetStart); // overwritten to point to the end of the stream - networkId=newObjects[newListIndex]->GetNetworkID(); - bsOut.Write(networkId); - bsOut.AlignWriteToByteBoundary(); // Give the user an aligned bitStream in case they use memcpy - bsOut.Write(&bsOut2); - bsOut.AlignWriteToByteBoundary(); // Give the user an aligned bitStream in case they use memcpy - offsetEnd=bsOut.GetWriteOffset(); - bsOut.SetWriteOffset(offsetStart); - bsOut.Write(offsetEnd); - bsOut.SetWriteOffset(offsetEnd); - } - else - bsOut.Write(false); - } - bsOut.AlignWriteToByteBoundary(); - - // Destruction - objectSize = (uint16_t) deletedObjects.Size(); - bsOut.Write(objectSize); - for (oldListIndex=0; oldListIndex < deletedObjects.Size(); oldListIndex++) - { - networkId=deletedObjects[oldListIndex]->GetNetworkID(); - bsOut.Write(networkId); - offsetStart=bsOut.GetWriteOffset(); - bsOut.Write(offsetStart); - deletedObjects[oldListIndex]->deletingSystemGUID=rakPeer->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); - bsOut.Write(deletedObjects[oldListIndex]->deletingSystemGUID); - deletedObjects[oldListIndex]->SerializeDestruction(&bsOut, this); - bsOut.AlignWriteToByteBoundary(); - offsetEnd=bsOut.GetWriteOffset(); - bsOut.SetWriteOffset(offsetStart); - bsOut.Write(offsetEnd); - bsOut.SetWriteOffset(offsetEnd); - } - rakPeer->Send(&bsOut,sendParameters.priority,MafiaNet::Reliability::ReliableOrdered,sendParameters.orderingChannel,systemAddress,false,sendParameters.sendReceipt); - - // TODO - shouldn't this be part of construction? - - // Initial Download serialize to a new system - // Immediately send serialize after construction if the replica object already has saved data - // If the object was serialized identically, and does not change later on, then the new connection never gets the data - SerializeParameters sp; - sp.whenLastSerialized=0; - MafiaNet::BitStream emptyBs; - for (int index=0; index < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; index++) - { - sp.lastSentBitstream[index]=&emptyBs; - sp.pro[index]=sendParameters; - sp.pro[index].reliability=MafiaNet::Reliability::ReliableOrdered; - } - - sp.bitsWrittenSoFar=0; -// MafiaNet::Time t = MafiaNet::GetTimeMS(); - for (newListIndex=0; newListIndex < newObjects.Size(); newListIndex++) - { - sp.destinationConnection=this; - sp.messageTimestamp=0; - MafiaNet::Replica3 *replica = newObjects[newListIndex]; - // 8/22/09 Forgot ResetWritePointer - for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) - { - sp.outputBitstream[z].ResetWritePointer(); - } - - RM3SerializationResult res = replica->Serialize(&sp); - if (res!=RM3SR_NEVER_SERIALIZE_FOR_THIS_CONNECTION && - res!=RM3SR_DO_NOT_SERIALIZE && - res!=RM3SR_SERIALIZED_UNIQUELY) - { - bool allIndices[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; - for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) - { - sp.bitsWrittenSoFar+=sp.outputBitstream[z].GetNumberOfBitsUsed(); - allIndices[z]=true; - } - SendSerialize(replica, allIndices, sp.outputBitstream, sp.messageTimestamp, sp.pro, rakPeer, worldId, GetTime()); -/// newObjects[newListIndex]->whenLastSerialized=t; - - } - // else wait for construction request accepted before serializing - } - - if (isFirstConstruction) - { - bsOut.Reset(); - bsOut.Write((MessageID)ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE); - bsOut.Write(worldId); - SerializeOnDownloadComplete(&bsOut); - rakPeer->Send(&bsOut,sendParameters.priority,MafiaNet::Reliability::ReliableOrdered,sendParameters.orderingChannel,systemAddress,false,sendParameters.sendReceipt); - } - - isFirstConstruction=false; - -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Connection_RM3::SendValidation(MafiaNet::RakPeerInterface *rakPeer, WorldId worldId) -{ - // Hijack to mean sendValidation - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_REPLICA_MANAGER_SCOPE_CHANGE); - bsOut.Write(worldId); - rakPeer->Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,systemAddress,false); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -Replica3::Replica3() -{ - creatingSystemGUID=UNASSIGNED_RAKNET_GUID; - deletingSystemGUID=UNASSIGNED_RAKNET_GUID; - replicaManager=0; - forceSendUntilNextUpdate=false; - lsr=0; - referenceIndex = (uint32_t)-1; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -Replica3::~Replica3() -{ - if (replicaManager) - { - replicaManager->Dereference(this); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void Replica3::BroadcastDestruction(void) -{ - replicaManager->BroadcastDestruction(this,UNASSIGNED_SYSTEM_ADDRESS); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -RakNetGUID Replica3::GetCreatingSystemGUID(void) const -{ - return creatingSystemGUID; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -RM3ConstructionState Replica3::QueryConstruction_ClientConstruction(MafiaNet::Connection_RM3 *destinationConnection, bool isThisTheServer) -{ - (void) destinationConnection; - if (creatingSystemGUID==replicaManager->GetRakPeerInterface()->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)) - return RM3CS_SEND_CONSTRUCTION; - // Send back to the owner client too, because they couldn't assign the network ID - if (isThisTheServer) - return RM3CS_SEND_CONSTRUCTION; - return RM3CS_NEVER_CONSTRUCT; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool Replica3::QueryRemoteConstruction_ClientConstruction(MafiaNet::Connection_RM3 *sourceConnection, bool isThisTheServer) -{ - (void) sourceConnection; - (void) isThisTheServer; - - // OK to create - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -RM3ConstructionState Replica3::QueryConstruction_ServerConstruction(MafiaNet::Connection_RM3 *destinationConnection, bool isThisTheServer) -{ - (void) destinationConnection; - - if (isThisTheServer) - return RM3CS_SEND_CONSTRUCTION; - return RM3CS_NEVER_CONSTRUCT; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool Replica3::QueryRemoteConstruction_ServerConstruction(MafiaNet::Connection_RM3 *sourceConnection, bool isThisTheServer) -{ - (void) sourceConnection; - if (isThisTheServer) - return false; - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -RM3ConstructionState Replica3::QueryConstruction_PeerToPeer(MafiaNet::Connection_RM3 *destinationConnection, Replica3P2PMode p2pMode) -{ - (void) destinationConnection; - - if (p2pMode==R3P2PM_SINGLE_OWNER) - { - // We send to all, others do nothing - if (creatingSystemGUID==replicaManager->GetRakPeerInterface()->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)) - return RM3CS_SEND_CONSTRUCTION; - - // RM3CS_NEVER_CONSTRUCT will not send the object, and will not Serialize() it - return RM3CS_NEVER_CONSTRUCT; - } - else if (p2pMode==R3P2PM_MULTI_OWNER_CURRENTLY_AUTHORITATIVE) - { - return RM3CS_SEND_CONSTRUCTION; - } - else if (p2pMode==R3P2PM_STATIC_OBJECT_CURRENTLY_AUTHORITATIVE) - { - return RM3CS_ALREADY_EXISTS_REMOTELY; - } - else if (p2pMode==R3P2PM_STATIC_OBJECT_NOT_CURRENTLY_AUTHORITATIVE) - { - return RM3CS_ALREADY_EXISTS_REMOTELY_DO_NOT_CONSTRUCT; - } - else - { - RakAssert(p2pMode==R3P2PM_MULTI_OWNER_NOT_CURRENTLY_AUTHORITATIVE); - - // RM3CS_ALREADY_EXISTS_REMOTELY will not send the object, but WILL call QuerySerialization() and Serialize() on it. - return RM3CS_ALREADY_EXISTS_REMOTELY; - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool Replica3::QueryRemoteConstruction_PeerToPeer(MafiaNet::Connection_RM3 *sourceConnection) -{ - (void) sourceConnection; - - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -RM3QuerySerializationResult Replica3::QuerySerialization_ClientSerializable(MafiaNet::Connection_RM3 *destinationConnection, bool isThisTheServer) -{ - // Owner client sends to all - if (creatingSystemGUID==replicaManager->GetRakPeerInterface()->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)) - return RM3QSR_CALL_SERIALIZE; - // Server sends to all but owner client - if (isThisTheServer && destinationConnection->GetRakNetGUID()!=creatingSystemGUID) - return RM3QSR_CALL_SERIALIZE; - // Remote clients do not send - return RM3QSR_NEVER_CALL_SERIALIZE; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -RM3QuerySerializationResult Replica3::QuerySerialization_ServerSerializable(MafiaNet::Connection_RM3 *destinationConnection, bool isThisTheServer) -{ - (void) destinationConnection; - // Server sends to all - if (isThisTheServer) - return RM3QSR_CALL_SERIALIZE; - - // Clients do not send - return RM3QSR_NEVER_CALL_SERIALIZE; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -RM3QuerySerializationResult Replica3::QuerySerialization_PeerToPeer(MafiaNet::Connection_RM3 *destinationConnection, Replica3P2PMode p2pMode) -{ - (void) destinationConnection; - - if (p2pMode==R3P2PM_SINGLE_OWNER) - { - // Owner peer sends to all - if (creatingSystemGUID==replicaManager->GetRakPeerInterface()->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)) - return RM3QSR_CALL_SERIALIZE; - - // Remote peers do not send - return RM3QSR_NEVER_CALL_SERIALIZE; - } - else if (p2pMode==R3P2PM_MULTI_OWNER_CURRENTLY_AUTHORITATIVE) - { - return RM3QSR_CALL_SERIALIZE; - } - else if (p2pMode==R3P2PM_STATIC_OBJECT_CURRENTLY_AUTHORITATIVE) - { - return RM3QSR_CALL_SERIALIZE; - } - else if (p2pMode==R3P2PM_STATIC_OBJECT_NOT_CURRENTLY_AUTHORITATIVE) - { - return RM3QSR_DO_NOT_CALL_SERIALIZE; - } - else - { - RakAssert(p2pMode==R3P2PM_MULTI_OWNER_NOT_CURRENTLY_AUTHORITATIVE); - return RM3QSR_DO_NOT_CALL_SERIALIZE; - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -RM3ActionOnPopConnection Replica3::QueryActionOnPopConnection_Client(MafiaNet::Connection_RM3 *droppedConnection) const -{ - (void) droppedConnection; - return RM3AOPC_DELETE_REPLICA; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -RM3ActionOnPopConnection Replica3::QueryActionOnPopConnection_Server(MafiaNet::Connection_RM3 *droppedConnection) const -{ - (void) droppedConnection; - return RM3AOPC_DELETE_REPLICA_AND_BROADCAST_DESTRUCTION; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -RM3ActionOnPopConnection Replica3::QueryActionOnPopConnection_PeerToPeer(MafiaNet::Connection_RM3 *droppedConnection) const -{ - (void) droppedConnection; - return RM3AOPC_DELETE_REPLICA; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/Router2.cpp b/vendors/mafianet/Source/src/Router2.cpp deleted file mode 100644 index 43772edf4..000000000 --- a/vendors/mafianet/Source/src/Router2.cpp +++ /dev/null @@ -1,1373 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_Router2==1 && _RAKNET_SUPPORT_UDPForwarder==1 - -#include "mafianet/Router2.h" -#include "mafianet/peerinterface.h" -#include "mafianet/BitStream.h" -#include "mafianet/time.h" -#include "mafianet/GetTime.h" -#include "mafianet/DS_OrderedList.h" -#include "mafianet/SocketLayer.h" -#include "mafianet/FormatString.h" -#include "mafianet/SocketDefines.h" - -using namespace MafiaNet; - -#ifndef INVALID_SOCKET -#define INVALID_SOCKET -1 -#endif - -/* -Algorithm: - -1. Sender calls ConnectInternal(). A ConnnectRequest structure is allocated and stored in the connectionRequests list, containing a list of every system we are connected to. ID_ROUTER_2_QUERY_FORWARDING is sent to all connected systems. - -2. Upon the router getting ID_ROUTER_2_QUERY_FORWARDING, ID_ROUTER_2_REPLY_FORWARDING is sent to the sender indicating if that router is connected to the endpoint, along with the ping from the router to the endpoint. - -3. Upon the sender getting ID_ROUTER_2_REPLY_FORWARDING, the connection request structure is looked up in Router2::UpdateForwarding. The ping is stored in that structure. Once all systems have replied, the system continues to the next state. If every system in step 1 has been exhausted, and routing has occured at least once, then ID_CONNECTION_LOST is returned. If every system in step 1 has been exhausted and routing has never occured, then ID_ROUTER_2_FORWARDING_NO_PATH is returned. Otherwise, the router with the lowest ping is chosen, and RequestForwarding() is called with that system, which sends ID_ROUTER_2_REQUEST_FORWARDING to the router. - -4. When the router gets ID_ROUTER_2_REQUEST_FORWARDING, a MiniPunchRequest structure is allocated and stored in the miniPunchesInProgress list. The function SendOOBMessages() sends ID_ROUTER_2_REPLY_TO_SENDER_PORT from the routing sockets to both the sender and endpoint. It also sends ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT through the regular RakNet connection. - -5. The sender and endpoint should get ID_ROUTER_2_REPLY_TO_SENDER_PORT and/or ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT depending on what type of router they have. If ID_ROUTER_2_REPLY_TO_SENDER_PORT arrives, then this will reply back to the routing socket directly. If ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT arrives, then the reply port is modified to be the port specified by the router system. In both cases, ID_ROUTER_2_MINI_PUNCH_REPLY is sent. As the router has already setup the forwarding, ID_ROUTER_2_MINI_PUNCH_REPLY will actually arrive to the endpoint from the sender, and from the sender to the endpoint. - -6. When ID_ROUTER_2_MINI_PUNCH_REPLY arrives, ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE will be sent to the router. This is to tell the router that the forwarding has succeeded. - -7. When ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE arrives on the router, the router will find the two systems in the miniPunchesInProgress list, which was added in step 4 (See OnMiniPunchReplyBounce()). gotReplyFromSource or gotReplyFromEndpoint will be set to true, depending on the sender. When both gotReplyFromSource and gotReplyFromEndpoint have replied, then ID_ROUTER_2_REROUTE is sent to the endpoint, and ID_ROUTER_2_FORWARDING_ESTABLISHED is sent to the sender. - -8. When the endpoint gets ID_ROUTER_2_REROUTE, the system address is updated for the guid of the sender using RakPeer::ChangeSystemAddress(). This happens in OnRerouted(). - -9. When the sender gets ID_ROUTER_2_FORWARDING_ESTABLISHED, then in OnForwardingSuccess() the endpoint is removed from the connectionRequest list and moved to the forwardedConnectionList. - -10. In OnClosedConnection(), for the sender, if the closed connection is the endpoint, then the endpoint is removed from the forwardedConnectionList (this is a graceful disconnect). If the connection was instead lost to the router, then ConnectInternal() gets called, which goes back to step 1. If instead this was a connection requset in progress, then UpdateForwarding() gets called, which goes back to step 3. - -11. When the user connects the endpoint and sender, then the sender will get ID_CONNECTION_REQUEST_ACCEPTED. The sender will look up the endpoint in the forwardedConnectionList, and send ID_ROUTER_2_INCREASE_TIMEOUT to the endpoint. This message will call SetTimeoutTime() on the endpoint, so that if the router disconnects, enough time is available for the reroute to complete. -*/ - -#define MIN_MINIPUNCH_TIMEOUT 5000 - - - - -void Router2DebugInterface::ShowFailure(const char *message) -{ - printf("%s", message); -} -void Router2DebugInterface::ShowDiagnostic(const char *message) -{ - printf("%s", message); -} - -enum Router2MessageIdentifiers -{ - ID_ROUTER_2_QUERY_FORWARDING, - ID_ROUTER_2_REPLY_FORWARDING, - ID_ROUTER_2_REQUEST_FORWARDING, - ID_ROUTER_2_INCREASE_TIMEOUT, -}; -Router2::ConnnectRequest::ConnnectRequest() -{ - -} -Router2::ConnnectRequest::~ConnnectRequest() -{ - -} - -STATIC_FACTORY_DEFINITIONS(Router2,Router2); - -Router2::Router2() -{ - udpForwarder=0; - maximumForwardingRequests=0; - debugInterface=0; - socketFamily=AF_INET; -} -Router2::~Router2() -{ - ClearAll(); - - if (udpForwarder) - { - udpForwarder->Shutdown(); - MafiaNet::OP_DELETE(udpForwarder,_FILE_AND_LINE_); - } -} -void Router2::ClearMinipunches(void) -{ - miniPunchesInProgressMutex.Lock(); - miniPunchesInProgress.Clear(false,_FILE_AND_LINE_); - miniPunchesInProgressMutex.Unlock(); -} -void Router2::ClearConnectionRequests(void) -{ - connectionRequestsMutex.Lock(); - for (unsigned int i=0; i < connectionRequests.Size(); i++) - { - MafiaNet::OP_DELETE(connectionRequests[i],_FILE_AND_LINE_); - } - connectionRequests.Clear(false,_FILE_AND_LINE_); - connectionRequestsMutex.Unlock(); -} -bool Router2::ConnectInternal(RakNetGUID endpointGuid, bool returnConnectionLostOnFailure) -{ - int largestPing = GetLargestPingAmongConnectedSystems(); - if (largestPing<0) - { - char buff[512]; - if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2: ConnectInternal(%I64d) failed at %s:%i\n", endpointGuid.g, __FILE__, __LINE__)); - - // Not connected to anyone - return false; - } - - // ALready in progress? - connectionRequestsMutex.Lock(); - if (GetConnectionRequestIndex(endpointGuid)!=(unsigned int)-1) - { - connectionRequestsMutex.Unlock(); - char buff[512]; - if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2: ConnectInternal(%I64d) failed at %s:%i\n", endpointGuid.g, __FILE__, __LINE__)); - - return false; - } - connectionRequestsMutex.Unlock(); - - // StoreRequest(endpointGuid, Largest(ping*2), systemsSentTo). Set state REQUEST_STATE_QUERY_FORWARDING - Router2::ConnnectRequest *cr = MafiaNet::OP_NEW(_FILE_AND_LINE_); - DataStructures::List addresses; - DataStructures::List guids; - rakPeerInterface->GetSystemList(addresses, guids); - if (guids.Size()==0) - { - char buff[512]; - if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed at %s:%i\n", _FILE_AND_LINE_)); - - return false; - } - cr->requestState=R2RS_REQUEST_STATE_QUERY_FORWARDING; - cr->pingTimeout= MafiaNet::GetTimeMS()+largestPing*2+1000; - cr->endpointGuid=endpointGuid; - cr->returnConnectionLostOnFailure=returnConnectionLostOnFailure; - for (unsigned int i=0; i < guids.Size(); i++) - { - ConnectionRequestSystem crs; - if (guids[i]!=endpointGuid) - { - crs.guid=guids[i]; - crs.pingToEndpoint=-1; - cr->connectionRequestSystemsMutex.Lock(); - cr->connectionRequestSystems.Push(crs,_FILE_AND_LINE_); - cr->connectionRequestSystemsMutex.Unlock(); - - // Broadcast(ID_ROUTER_2_QUERY_FORWARDING, endpointGuid); - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_ROUTER_2_INTERNAL); - bsOut.Write((unsigned char) ID_ROUTER_2_QUERY_FORWARDING); - bsOut.Write(endpointGuid); - uint32_t pack_id = rakPeerInterface->Send(&bsOut,MafiaNet::Priority::Medium,MafiaNet::Reliability::ReliableOrdered,0,crs.guid,false); - - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Router2::ConnectInternal: at %s:%i, pack_id = %d", __FILE__, __LINE__,pack_id)); - } - - } - else - { - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Router2::ConnectInternal: at %s:%i [else ..].: %I64d==%I64d", __FILE__, __LINE__, - guids[i].g,endpointGuid.g)); - } - } - } - connectionRequestsMutex.Lock(); - connectionRequests.Push(cr,_FILE_AND_LINE_); - connectionRequestsMutex.Unlock(); - - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Broadcasting ID_ROUTER_2_QUERY_FORWARDING to %I64d at %s:%i\n", endpointGuid.g , __FILE__, __LINE__)); - } - - return true; -} -void Router2::SetSocketFamily(unsigned short _socketFamily) -{ - socketFamily=_socketFamily; -} -void Router2::EstablishRouting(RakNetGUID endpointGuid) -{ - ConnectionState cs = rakPeerInterface->GetConnectionState(endpointGuid); - if (cs!=IS_DISCONNECTED && cs!=IS_NOT_CONNECTED) - { - char buff[512]; - if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed at %s:%i " - "(already connected to the %I64d)\n", __FILE__, __LINE__, endpointGuid.g )); - return; - } - - ConnectInternal(endpointGuid,false); -} -void Router2::SetMaximumForwardingRequests(int max) -{ - if (max>0 && maximumForwardingRequests<=0) - { - udpForwarder = MafiaNet::OP_NEW(_FILE_AND_LINE_); - udpForwarder->Startup(); - } - else if (max<=0 && maximumForwardingRequests>0) - { - udpForwarder->Shutdown(); - MafiaNet::OP_DELETE(udpForwarder,_FILE_AND_LINE_); - udpForwarder=0; - } - - maximumForwardingRequests=max; -} -PluginReceiveResult Router2::OnReceive(Packet *packet) -{ - SystemAddress sa; - MafiaNet::BitStream bs(packet->data,packet->length,false); - if (packet->data[0]==ID_ROUTER_2_INTERNAL) - { - switch (packet->data[1]) - { - case ID_ROUTER_2_QUERY_FORWARDING: - { - OnQueryForwarding(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - case ID_ROUTER_2_REPLY_FORWARDING: - { - OnQueryForwardingReply(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - case ID_ROUTER_2_REQUEST_FORWARDING: - { - - if (debugInterface) - { - char buff[512]; - char buff2[32]; - packet->systemAddress.ToString(true,buff2,static_cast(32)); - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REQUEST_FORWARDING on ip %s from %I64d, ", - buff2,packet->guid.g)); - } - - OnRequestForwarding(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - case ID_ROUTER_2_INCREASE_TIMEOUT: - { - /// The routed system wants more time to stay alive on no communication, in case the router drops or crashes - rakPeerInterface->SetTimeoutTime(rakPeerInterface->GetTimeoutTime(packet->systemAddress)+10000, packet->systemAddress); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - } - } - else if (packet->data[0]==ID_OUT_OF_BAND_INTERNAL && packet->length>=2) - { - switch (packet->data[1]) - { - case ID_ROUTER_2_REPLY_TO_SENDER_PORT: - { - MafiaNet::BitStream bsOut; - bsOut.Write(packet->guid); - SendOOBFromRakNetPort(ID_ROUTER_2_MINI_PUNCH_REPLY, &bsOut, packet->systemAddress); - - if (debugInterface) - { - char buff[512]; - char buff2[32]; - sa.ToString(false,buff2,static_cast(32)); - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REPLY_TO_SENDER_PORT %i on address %s, replying with ID_ROUTER_2_MINI_PUNCH_REPLY at %s:%i\n", sa.GetPort(), buff2, _FILE_AND_LINE_)); - -// packet->systemAddress.ToString(true,buff2); -// debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REPLY_TO_SENDER_PORT on address %s (%I64d), " -// "replying with ID_ROUTER_2_MINI_PUNCH_REPLY at %s:%i\n", buff2,packet->guid.g, __FILE__, __LINE__)); - } - - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - case ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT: - { - MafiaNet::BitStream bsOut; - bsOut.Write(packet->guid); - bs.IgnoreBytes(2); - sa=packet->systemAddress; - unsigned short port; - bs.Read(port); - sa.SetPortHostOrder(port); - RakAssert(sa.GetPort()!=0); - SendOOBFromRakNetPort(ID_ROUTER_2_MINI_PUNCH_REPLY, &bsOut, sa); - - if (debugInterface) - { - char buff[512]; - char buff2[32]; - sa.ToString(false,buff2,static_cast(32)); - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT %i on address %s, " - "replying with ID_ROUTER_2_MINI_PUNCH_REPLY at %s:%i\n", sa.GetPort(), buff2, __FILE__, __LINE__)); - } - - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - case ID_ROUTER_2_MINI_PUNCH_REPLY: - OnMiniPunchReply(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE: - OnMiniPunchReplyBounce(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - } - else if (packet->data[0]==ID_ROUTER_2_FORWARDING_ESTABLISHED) - { -// printf("Got ID_ROUTER_2_FORWARDING_ESTABLISHED\n"); - if (OnForwardingSuccess(packet)==false) - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - else if (packet->data[0]==ID_ROUTER_2_REROUTED) - { - OnRerouted(packet); - } - else if (packet->data[0]==ID_CONNECTION_REQUEST_ACCEPTED) - { - unsigned int forwardingIndex; - forwardedConnectionListMutex.Lock(); - for (forwardingIndex=0; forwardingIndex < forwardedConnectionList.Size(); forwardingIndex++) - { - if (forwardedConnectionList[forwardingIndex].endpointGuid==packet->guid && forwardedConnectionList[forwardingIndex].weInitiatedForwarding) - break; - } - - if (forwardingIndexSend(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::Reliable,0,packet->guid,false); - - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_CONNECTION_REQUEST_ACCEPTED, " - "sending ID_ROUTER_2_INCREASE_TIMEOUT to the %I64d at %s:%i\n", packet->guid.g, __FILE__, __LINE__)); - } - - // Also take longer ourselves - rakPeerInterface->SetTimeoutTime(rakPeerInterface->GetTimeoutTime(packet->systemAddress)+10000, packet->systemAddress); - } - else { - // ~Gwynn: Fix for Receive hanging up problem on Windows XP - // See http://blog.delphi-jedi.net/2008/04/23/the-case-of-the-unexplained-dead-lock-in-a-single-thread/ for details - forwardedConnectionListMutex.Unlock(); - } - } - else if (packet->data[0]==ID_ROUTER_2_FORWARDING_NO_PATH) - { - if (packet->wasGeneratedLocally==false) - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - - return RR_CONTINUE_PROCESSING; -} -void Router2::Update(void) -{ - MafiaNet::TimeMS curTime = MafiaNet::GetTimeMS(); - unsigned int connectionRequestIndex=0; - connectionRequestsMutex.Lock(); - while (connectionRequestIndex < connectionRequests.Size()) - { - ConnnectRequest* connectionRequest = connectionRequests[connectionRequestIndex]; - - // pingTimeout is only used with R2RS_REQUEST_STATE_QUERY_FORWARDING - if (connectionRequest->requestState==R2RS_REQUEST_STATE_QUERY_FORWARDING && - connectionRequest->pingTimeout < curTime) - { - bool anyRemoved=false; - unsigned int connectionRequestGuidIndex=0; - connectionRequest->connectionRequestSystemsMutex.Lock(); - while (connectionRequestGuidIndex < connectionRequest->connectionRequestSystems.Size()) - { - if (connectionRequest->connectionRequestSystems[connectionRequestGuidIndex].pingToEndpoint<0) - { - anyRemoved=true; - connectionRequest->connectionRequestSystems.RemoveAtIndexFast(connectionRequestGuidIndex); - } - else - { - connectionRequestGuidIndex++; - } - } - connectionRequest->connectionRequestSystemsMutex.Unlock(); - - if (anyRemoved) - { - if (connectionRequestIndex!=(unsigned int)-1) - { - // connectionRequestsMutex should be locked before calling this function - if (UpdateForwarding(connectionRequest)==false) - { - RemoveConnectionRequest(connectionRequestIndex); - } - else - { - connectionRequestIndex++; - } - } - else - { - connectionRequestIndex++; - } - } - else - { - connectionRequestIndex++; - } - } - else - { - connectionRequestIndex++; - } - } - connectionRequestsMutex.Unlock(); - - unsigned int i=0; - miniPunchesInProgressMutex.Lock(); - while (i < miniPunchesInProgress.Size()) - { - if (miniPunchesInProgress[i].timeoutminiPunchesInProgress[i].nextAction) - { - miniPunchesInProgress[i].nextAction=curTime+100; - SendOOBMessages(&miniPunchesInProgress[i]); - } - else - i++; - } - miniPunchesInProgressMutex.Unlock(); - -} -void Router2::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) lostConnectionReason; - (void) systemAddress; - - - unsigned int forwardedConnectionIndex=0; - forwardedConnectionListMutex.Lock(); - while (forwardedConnectionIndexShowDiagnostic(FormatStringTS(buff,"Closed connection to the %I64d, removing forwarding from list at %s:%i\n", rakNetGUID.g, __FILE__, __LINE__)); - } - - // No longer need forwarding - forwardedConnectionList.RemoveAtIndexFast(forwardedConnectionIndex); - } - else if (forwardedConnectionList[forwardedConnectionIndex].intermediaryGuid==rakNetGUID && forwardedConnectionList[forwardedConnectionIndex].weInitiatedForwarding) - { - // Lost connection to intermediary. Restart process to connect to endpoint. If failed, push ID_CONNECTION_LOST. Also remove connection request if it already is in the list, to restart it - connectionRequestsMutex.Lock(); - unsigned int pos = GetConnectionRequestIndex(forwardedConnectionList[forwardedConnectionIndex].endpointGuid); - if((unsigned int)-1 != pos) { MafiaNet::OP_DELETE(connectionRequests[pos], __FILE__, __LINE__); connectionRequests.RemoveAtIndexFast(pos);} - connectionRequestsMutex.Unlock(); - - ConnectInternal(forwardedConnectionList[forwardedConnectionIndex].endpointGuid, true); - - forwardedConnectionIndex++; - - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Closed connection %I64d, restarting forwarding at %s:%i\n",rakNetGUID.g, __FILE__, __LINE__)); - } - - // This should not be removed - the connection is still forwarded, but perhaps through another system -// forwardedConnectionList.RemoveAtIndexFast(forwardedConnectionIndex); - } - else - forwardedConnectionIndex++; - } - forwardedConnectionListMutex.Unlock(); - - unsigned int connectionRequestIndex=0; - connectionRequestsMutex.Lock(); - while (connectionRequestIndex < connectionRequests.Size()) - { - ConnnectRequest *cr = connectionRequests[connectionRequestIndex]; - cr->connectionRequestSystemsMutex.Lock(); - unsigned int connectionRequestGuidIndex = cr->GetGuidIndex(rakNetGUID); - if (connectionRequestGuidIndex!=(unsigned int)-1) - { - cr->connectionRequestSystems.RemoveAtIndexFast(connectionRequestGuidIndex); - cr->connectionRequestSystemsMutex.Unlock(); - if (UpdateForwarding(cr)==false) // If returns false, no connection request systems left - { - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Aborted connection to the %I64d, aborted forwarding at %s:%i\n", rakNetGUID.g, __FILE__, __LINE__)); - } - - RemoveConnectionRequest(connectionRequestIndex); - } - else // Else a system in the connection request list dropped. If cr->requestState==R2RS_REQUEST_STATE_QUERY_FORWARDING then we are still waiting for other systems to respond. - { - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Aborted connection attempt to %I64d, restarting forwarding to %I64d at %s:%i\n", rakNetGUID.g,cr->endpointGuid.g,__FILE__, __LINE__)); - } -// if(volatile bool is_my_fix_a_truth = true) { // A system in the list of potential systems to try routing to dropped. There is no need to restart the whole process. -// connectionRequestsMutex.Lock(); -// connectionRequests.RemoveAtIndexFast(connectionRequestIndex); -// connectionRequestsMutex.Unlock(); -// -// if(false == ConnectInternal(cr->endpointGuid,cr->returnConnectionLostOnFailure)) -// if (debugInterface) -// { -// char buff[512]; -// debugInterface->ShowDiagnostic(FormatStringTS(buff,"ConnectInternal(cr->endpointGuid,cr->returnConnectionLostOnFailure) is false. at %s:%i\n", __FILE__, __LINE__)); -// } -// } - - connectionRequestIndex++; - } - } - else - { - cr->connectionRequestSystemsMutex.Unlock(); - connectionRequestIndex++; - } - } - connectionRequestsMutex.Unlock(); - - - unsigned int i=0; - miniPunchesInProgressMutex.Lock(); - while (i < miniPunchesInProgress.Size()) - { - if (miniPunchesInProgress[i].sourceGuid==rakNetGUID || miniPunchesInProgress[i].endpointGuid==rakNetGUID) - { - if (miniPunchesInProgress[i].sourceGuid!=rakNetGUID) - { - SendFailureOnCannotForward(miniPunchesInProgress[i].sourceGuid, miniPunchesInProgress[i].endpointGuid); - } - miniPunchesInProgress.RemoveAtIndexFast(i); - } - else - i++; - } - miniPunchesInProgressMutex.Unlock(); -} -void Router2::OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason) -{ - (void) failedConnectionAttemptReason; - (void) packet; - - unsigned int forwardedConnectionIndex=0; - forwardedConnectionListMutex.Lock(); - while (forwardedConnectionIndexsystemAddress) - { - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Failed connection attempt to forwarded system (%I64d : %s) at %s:%i\n", - forwardedConnectionList[forwardedConnectionIndex].endpointGuid.g, packet->systemAddress.ToString(true), __FILE__, __LINE__)); - } - - packet->guid=forwardedConnectionList[forwardedConnectionIndex].endpointGuid; - forwardedConnectionList.RemoveAtIndexFast(forwardedConnectionIndex); - } - else - forwardedConnectionIndex++; - } - forwardedConnectionListMutex.Unlock(); -} -void Router2::OnRakPeerShutdown(void) -{ - ClearAll(); -} -// connectionRequestsMutex should already be locked -bool Router2::UpdateForwarding(ConnnectRequest* connectionRequest) -{ - connectionRequest->connectionRequestSystemsMutex.Lock(); - - // RAKNET_DEBUG_PRINTF(__FUNCTION__": connectionRequest->connectionRequestSystems.Size = %d", connectionRequest->connectionRequestSystems.Size()); - - if (connectionRequest->connectionRequestSystems.Size()==0) - { - connectionRequest->connectionRequestSystemsMutex.Unlock(); - - // printf("Router2 failed at %s:%i\n", __FILE__, __LINE__); - if (connectionRequest->returnConnectionLostOnFailure) { - ReturnToUser(ID_CONNECTION_LOST, connectionRequest->endpointGuid, UNASSIGNED_SYSTEM_ADDRESS, true); // This is a connection which was previously established. Rerouting is not possible. -// bool sendDisconnectionNotification = false; -// rakPeerInterface->CloseConnection(rakPeerInterface->GetSystemAddressFromGuid(connectionRequest->endpointGuid), sendDisconnectionNotification); -// RAKNET_DEBUG_PRINTF(__FUNCTION__": call rakPeerInterface->CloseConnection(%I64d)" , connectionRequest->endpointGuid.g); - } - else - ReturnToUser(ID_ROUTER_2_FORWARDING_NO_PATH, connectionRequest->endpointGuid, UNASSIGNED_SYSTEM_ADDRESS, false); - - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Forwarding failed, no remaining systems at %s:%i\n", _FILE_AND_LINE_)); - } - - forwardedConnectionListMutex.Lock(); - - for (unsigned int forwardedConnectionIndex=0; forwardedConnectionIndex < forwardedConnectionList.Size(); forwardedConnectionIndex++) - { - if (forwardedConnectionList[forwardedConnectionIndex].endpointGuid==connectionRequest->endpointGuid && forwardedConnectionList[forwardedConnectionIndex].weInitiatedForwarding) - { - forwardedConnectionList.RemoveAtIndexFast(forwardedConnectionIndex); - break; - } - } - forwardedConnectionListMutex.Unlock(); - - return false; - } - connectionRequest->connectionRequestSystemsMutex.Unlock(); - - if (connectionRequest->requestState==R2RS_REQUEST_STATE_QUERY_FORWARDING) - { - connectionRequest->connectionRequestSystemsMutex.Lock(); - - for (unsigned int i=0; i < connectionRequest->connectionRequestSystems.Size(); i++) - { - if (connectionRequest->connectionRequestSystems[i].pingToEndpoint<0) - { - connectionRequest->connectionRequestSystemsMutex.Unlock(); - return true; // Forward query still in progress, just return - } - } - connectionRequest->connectionRequestSystemsMutex.Unlock(); - - RequestForwarding(connectionRequest); - } -// else if (connectionRequest->requestState==REQUEST_STATE_REQUEST_FORWARDING) -// { -// RequestForwarding(connectionRequestIndex); -// } - - return true; -} -// connectionRequestsMutex should already be locked -void Router2::RemoveConnectionRequest(unsigned int connectionRequestIndex) -{ - MafiaNet::OP_DELETE(connectionRequests[connectionRequestIndex],_FILE_AND_LINE_); - connectionRequests.RemoveAtIndexFast(connectionRequestIndex); -} -int ConnectionRequestSystemComp( const Router2::ConnectionRequestSystem & key, const Router2::ConnectionRequestSystem &data ) -{ - if (key.pingToEndpoint * (key.usedForwardingEntries+1) < data.pingToEndpoint * (data.usedForwardingEntries+1)) - return -1; - if (key.pingToEndpoint * (key.usedForwardingEntries+1) == data.pingToEndpoint * (data.usedForwardingEntries+1)) - return 1; - if (key.guid < data.guid) - return -1; - if (key.guid > data.guid) - return -1; - return 0; -} -// connectionRequestsMutex should already be locked -void Router2::RequestForwarding(ConnnectRequest* connectionRequest) -{ - RakAssert(connectionRequest->requestState==R2RS_REQUEST_STATE_QUERY_FORWARDING); - connectionRequest->requestState=REQUEST_STATE_REQUEST_FORWARDING; - - if (connectionRequest->GetGuidIndex(connectionRequest->lastRequestedForwardingSystem)!=(unsigned int)-1) - { - char buff[512]; - if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed at %s:%i\n", _FILE_AND_LINE_)); - return; - } - - // Prioritize systems to request forwarding - DataStructures::OrderedList commandList; - unsigned int connectionRequestGuidIndex; - connectionRequest->connectionRequestSystemsMutex.Lock(); - for (connectionRequestGuidIndex=0; connectionRequestGuidIndex < connectionRequest->connectionRequestSystems.Size(); connectionRequestGuidIndex++) - { - RakAssert(connectionRequest->connectionRequestSystems[connectionRequestGuidIndex].pingToEndpoint>=0); - commandList.Insert(connectionRequest->connectionRequestSystems[connectionRequestGuidIndex], - connectionRequest->connectionRequestSystems[connectionRequestGuidIndex], - true, - _FILE_AND_LINE_); - } - connectionRequest->connectionRequestSystemsMutex.Unlock(); - - connectionRequest->lastRequestedForwardingSystem=commandList[0].guid; - - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_ROUTER_2_INTERNAL); - bsOut.Write((unsigned char) ID_ROUTER_2_REQUEST_FORWARDING); - bsOut.Write(connectionRequest->endpointGuid); - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::Medium,MafiaNet::Reliability::ReliableOrdered,0,connectionRequest->lastRequestedForwardingSystem,false); - - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Sending ID_ROUTER_2_REQUEST_FORWARDING " - "(connectionRequest->lastRequestedForwardingSystem = %I64d, connectionRequest->endpointGuid = %I64d) at %s:%i\n", - connectionRequest->lastRequestedForwardingSystem.g,connectionRequest->endpointGuid.g, __FILE__, __LINE__)); - } -} -void Router2::SendFailureOnCannotForward(RakNetGUID sourceGuid, RakNetGUID endpointGuid) -{ - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_ROUTER_2_INTERNAL); - bsOut.Write((unsigned char) ID_ROUTER_2_REPLY_FORWARDING); - bsOut.Write(endpointGuid); - bsOut.Write(false); - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::Medium,MafiaNet::Reliability::ReliableOrdered,0,sourceGuid,false); -} -int Router2::ReturnFailureOnCannotForward(RakNetGUID sourceGuid, RakNetGUID endpointGuid) -{ - // If the number of systems we are currently forwarding>=maxForwarding, return ID_ROUTER_2_REPLY_FORWARDING,endpointGuid,false - if (udpForwarder==0 || udpForwarder->GetUsedForwardEntries()/2>maximumForwardingRequests) - { - char buff[512]; - if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed (%I64d -> %I64d) at %s:%i\n", - sourceGuid.g, endpointGuid.g,__FILE__, __LINE__)); - SendFailureOnCannotForward(sourceGuid,endpointGuid); - return -1; - } - - // We cannot forward connections which are themselves forwarded. Return fail in that case - forwardedConnectionListMutex.Lock(); - for (unsigned int i=0; i < forwardedConnectionList.Size(); i++) - { - if ((forwardedConnectionList[i].endpointGuid==endpointGuid) - || (forwardedConnectionList[i].endpointGuid==sourceGuid)) // sourceGuid is here so you do not respond to routing requests from systems you are already routing through. - { - forwardedConnectionListMutex.Unlock(); - - char buff[512]; - if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed at %s:%i\n", __FILE__, __LINE__)); - SendFailureOnCannotForward(sourceGuid,endpointGuid); - return -1; - } - } - forwardedConnectionListMutex.Unlock(); - - int pingToEndpoint; - pingToEndpoint = rakPeerInterface->GetAveragePing(endpointGuid); - if (pingToEndpoint==-1) - { - char buff[512]; - if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed (%I64d -> %I64d) at %s:%i\n", - sourceGuid.g, endpointGuid.g,__FILE__, __LINE__)); - - SendFailureOnCannotForward(sourceGuid,endpointGuid); - return -1; - } - return pingToEndpoint; -} -void Router2::OnQueryForwarding(Packet *packet) -{ - MafiaNet::BitStream bs(packet->data, packet->length, false); - bs.IgnoreBytes(sizeof(MessageID) + sizeof(unsigned char)); - RakNetGUID endpointGuid; - // Read endpointGuid - bs.Read(endpointGuid); - - int pingToEndpoint = ReturnFailureOnCannotForward(packet->guid, endpointGuid); - if (pingToEndpoint==-1) - { - char buff[512]; - if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed (%I64d) at %s:%i\n", packet->guid.g, __FILE__, __LINE__)); - return; - } - - // If we are connected to endpointGuid, reply ID_ROUTER_2_REPLY_FORWARDING,endpointGuid,true,ping,numCurrentlyForwarding - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_ROUTER_2_INTERNAL); - bsOut.Write((unsigned char) ID_ROUTER_2_REPLY_FORWARDING); - bsOut.Write(endpointGuid); - bsOut.Write(true); - bsOut.Write((unsigned short) pingToEndpoint); - bsOut.Write((unsigned short) udpForwarder->GetUsedForwardEntries()/2); - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::Medium,MafiaNet::Reliability::ReliableOrdered,0,packet->guid,false); - - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Sending ID_ROUTER_2_REPLY_FORWARDING to the %I64d at %s:%i\n", packet->guid.g, __FILE__, __LINE__)); - } -} -void Router2::OnQueryForwardingReply(Packet *packet) -{ - MafiaNet::BitStream bs(packet->data, packet->length, false); - bs.IgnoreBytes(sizeof(MessageID) + sizeof(unsigned char)); - RakNetGUID endpointGuid; - bs.Read(endpointGuid); - // Find endpointGuid among stored requests - bool canForward=false; - bs.Read(canForward); - - - connectionRequestsMutex.Lock(); - unsigned int connectionRequestIndex = GetConnectionRequestIndex(endpointGuid); - if (connectionRequestIndex==(unsigned int)-1) - { - connectionRequestsMutex.Unlock(); - char buff[512]; - if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed (%I64d) at %s:%i\n", endpointGuid.g, __FILE__, __LINE__)); - return; - } - - connectionRequests[connectionRequestIndex]->connectionRequestSystemsMutex.Lock(); - unsigned int connectionRequestGuidIndex = connectionRequests[connectionRequestIndex]->GetGuidIndex(packet->guid); - if (connectionRequestGuidIndex==(unsigned int)-1) - { - connectionRequests[connectionRequestIndex]->connectionRequestSystemsMutex.Unlock(); - connectionRequestsMutex.Unlock(); - char buff[512]; - if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed (%I64d) at %s:%i\n", endpointGuid.g, __FILE__, __LINE__)); - return; - } - - if (debugInterface) - { - char buff[512]; - char buff2[512]; - packet->systemAddress.ToString(true,buff2,static_cast(512)); - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REPLY_FORWARDING on address %s(%I64d -> %I64d) canForward=%i at %s:%i\n", - buff2, packet->guid.g, endpointGuid.g, canForward, __FILE__, __LINE__)); - } - - if (canForward) - { - unsigned short pingToEndpoint; - unsigned short usedEntries; - bs.Read(pingToEndpoint); - bs.Read(usedEntries); - connectionRequests[connectionRequestIndex]->connectionRequestSystems[connectionRequestGuidIndex].usedForwardingEntries=usedEntries; - connectionRequests[connectionRequestIndex]->connectionRequestSystems[connectionRequestGuidIndex].pingToEndpoint=rakPeerInterface->GetAveragePing(packet->guid)+pingToEndpoint; - } - else - { - connectionRequests[connectionRequestIndex]->connectionRequestSystems.RemoveAtIndex(connectionRequestGuidIndex); - } - connectionRequests[connectionRequestIndex]->connectionRequestSystemsMutex.Unlock(); - - if (UpdateForwarding(connectionRequests[connectionRequestIndex])==false) - { - RemoveConnectionRequest(connectionRequestIndex); - } - connectionRequestsMutex.Unlock(); -} -void Router2::SendForwardingSuccess(MessageID messageId, RakNetGUID sourceGuid, RakNetGUID endpointGuid, unsigned short sourceToDstPort) -{ - MafiaNet::BitStream bsOut; - bsOut.Write(messageId); - bsOut.Write(endpointGuid); - bsOut.Write(sourceToDstPort); - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::Medium,MafiaNet::Reliability::ReliableOrdered,0,sourceGuid,false); - - if (debugInterface) - { - char buff[512]; - if (messageId==ID_ROUTER_2_FORWARDING_ESTABLISHED) - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Sending ID_ROUTER_2_FORWARDING_ESTABLISHED at %s:%i\n", _FILE_AND_LINE_ )); - else - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Sending ID_ROUTER_2_REROUTED at %s:%i\n", _FILE_AND_LINE_ )); - } -} -void Router2::SendOOBFromRakNetPort(OutOfBandIdentifiers oob, BitStream *extraData, SystemAddress sa) -{ - MafiaNet::BitStream oobBs; - oobBs.Write((unsigned char)oob); - if (extraData) - { - extraData->ResetReadPointer(); - oobBs.Write(*extraData); - } - char ipAddressString[32]; - sa.ToString(false, ipAddressString,static_cast(32)); - rakPeerInterface->SendOutOfBand((const char*) ipAddressString,sa.GetPort(),(const char*) oobBs.GetData(),oobBs.GetNumberOfBytesUsed()); -} -void Router2::SendOOBFromSpecifiedSocket(OutOfBandIdentifiers oob, SystemAddress sa, __UDPSOCKET__ socket) -{ - MafiaNet::BitStream bs; - rakPeerInterface->WriteOutOfBandHeader(&bs); - bs.Write((unsigned char) oob); - // SocketLayer::SendTo_PC( socket, (const char*) bs.GetData(), bs.GetNumberOfBytesUsed(), sa, __FILE__, __LINE__ ); - - - if (sa.address.addr4.sin_family==AF_INET) - { - sendto__( socket, (const char*) bs.GetData(), bs.GetNumberOfBytesUsed(), 0, ( const sockaddr* ) & sa.address.addr4, sizeof( sockaddr_in ) ); - } - else - { - #if RAKNET_SUPPORT_IPV6==1 - sendto__( socket, (const char*) bs.GetData(), bs.GetNumberOfBytesUsed(), 0, ( const sockaddr* ) & sa.address.addr6, sizeof( sockaddr_in6 ) ); - #endif - } - - - - - - - - - - - - -} -void Router2::SendOOBMessages(Router2::MiniPunchRequest *mpr) -{ - // Mini NAT punch - // Send from srcToDestPort to packet->systemAddress (source). If the message arrives, the remote system should reply. - SendOOBFromSpecifiedSocket(ID_ROUTER_2_REPLY_TO_SENDER_PORT, mpr->sourceAddress, mpr->forwardingSocket); - - // Send from destToSourcePort to endpointSystemAddress (destination). If the message arrives, the remote system should reply. - SendOOBFromSpecifiedSocket(ID_ROUTER_2_REPLY_TO_SENDER_PORT, mpr->endpointAddress, mpr->forwardingSocket); - - - if (debugInterface) { - char buff [512]; - - char buff2[128]; - - mpr->sourceAddress .ToString(true,buff2,static_cast(128)); - - debugInterface->ShowDiagnostic(FormatStringTS(buff,"call SendOOBFromSpecifiedSocket(...,%s,...)", buff2)); - - mpr->endpointAddress .ToString(true,buff2,static_cast(128)); - - debugInterface->ShowDiagnostic(FormatStringTS(buff,"call SendOOBFromSpecifiedSocket(...,%s,...)", buff2)); - } - - // Tell source to send to forwardingPort - MafiaNet::BitStream extraData; - extraData.Write(mpr->forwardingPort); - RakAssert(mpr->forwardingPort!=0); - SendOOBFromRakNetPort(ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT, &extraData, mpr->sourceAddress); - - // Tell destination to send to forwardingPort - extraData.Reset(); - extraData.Write(mpr->forwardingPort); - RakAssert(mpr->forwardingPort); - SendOOBFromRakNetPort(ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT, &extraData, mpr->endpointAddress); -} -void Router2::OnRequestForwarding(Packet *packet) -{ - MafiaNet::BitStream bs(packet->data, packet->length, false); - bs.IgnoreBytes(sizeof(MessageID) + sizeof(unsigned char)); - RakNetGUID endpointGuid; - bs.Read(endpointGuid); - - int pingToEndpoint = ReturnFailureOnCannotForward(packet->guid, endpointGuid); - if (pingToEndpoint==-1) - { - char buff[512]; - if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed (packet->guid =%I64d, endpointGuid = %I64d) at %s:%i\n", - packet->guid.g, endpointGuid.g, __FILE__, __LINE__)); - return; - } - - unsigned short forwardingPort=0; - __UDPSOCKET__ forwardingSocket=INVALID_SOCKET; - SystemAddress endpointSystemAddress = rakPeerInterface->GetSystemAddressFromGuid(endpointGuid); - UDPForwarderResult result = udpForwarder->StartForwarding( - packet->systemAddress, endpointSystemAddress, 30000, 0, socketFamily, - &forwardingPort, &forwardingSocket); - - if (result==UDPFORWARDER_FORWARDING_ALREADY_EXISTS) - { - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REQUEST_FORWARDING, result=UDPFORWARDER_FORWARDING_ALREADY_EXISTS " - "(packet->guid =%I64d, endpointGuid = %I64d) at %s:%i\n", - packet->guid.g, endpointGuid.g,__FILE__, __LINE__)); - } - - SendForwardingSuccess(ID_ROUTER_2_FORWARDING_ESTABLISHED, packet->guid, endpointGuid, forwardingPort); - } - else if (result==UDPFORWARDER_NO_SOCKETS) - { - char buff[512]; - char buff2[64]; - char buff3[64]; - packet->systemAddress.ToString(true,buff2,static_cast(64)); - endpointSystemAddress.ToString(true,buff3,static_cast(64)); - if (debugInterface) - debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed at %s:%i with UDPFORWARDER_NO_SOCKETS, packet->systemAddress=%s, endpointSystemAddress=%s, forwardingPort=%i, forwardingSocket=%i\n", - __FILE__, __LINE__, buff2, buff3, forwardingPort, forwardingSocket)); - SendFailureOnCannotForward(packet->guid, endpointGuid); - } - else if (result==UDPFORWARDER_INVALID_PARAMETERS) - { - char buff[512]; - char buff2[64]; - char buff3[64]; - packet->systemAddress.ToString(true,buff2,static_cast(64)); - endpointSystemAddress.ToString(true,buff3,static_cast(64)); - if (debugInterface) - debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed at %s:%i with UDPFORWARDER_INVALID_PARAMETERS, packet->systemAddress=%s, endpointSystemAddress=%s, forwardingPort=%i, forwardingSocket=%i\n", - __FILE__, __LINE__, buff2, buff3, forwardingPort, forwardingSocket)); - SendFailureOnCannotForward(packet->guid, endpointGuid); - } - else if (result==UDPFORWARDER_BIND_FAILED) - { - char buff[512]; - char buff2[64]; - char buff3[64]; - packet->systemAddress.ToString(true,buff2,static_cast(64)); - endpointSystemAddress.ToString(true,buff3,static_cast(64)); - if (debugInterface) - debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed at %s:%i with UDPFORWARDER_BIND_FAILED, packet->systemAddress=%s, endpointSystemAddress=%s, forwardingPort=%i, forwardingSocket=%i\n", - __FILE__, __LINE__, buff2, buff3, forwardingPort, forwardingSocket)); - SendFailureOnCannotForward(packet->guid, endpointGuid); - } - else - { - if (debugInterface) - { - char buff2[32]; - char buff3[32]; - endpointSystemAddress.ToString(true,buff2,static_cast(32)); - packet->systemAddress.ToString(true,buff3,static_cast(32)); - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REQUEST_FORWARDING.\n" - "endpointAddress=%s\nsourceAddress=%s\nforwardingPort=%i\n " - "calling SendOOBMessages at %s:%i\n", buff2,buff3,forwardingPort,_FILE_AND_LINE_)); - } - - // Store the punch request - MiniPunchRequest miniPunchRequest; - miniPunchRequest.endpointAddress=endpointSystemAddress; - miniPunchRequest.endpointGuid=endpointGuid; - miniPunchRequest.gotReplyFromEndpoint=false; - miniPunchRequest.gotReplyFromSource=false; - miniPunchRequest.sourceGuid=packet->guid; - miniPunchRequest.sourceAddress=packet->systemAddress; - miniPunchRequest.forwardingPort=forwardingPort; - miniPunchRequest.forwardingSocket=forwardingSocket; - int ping1 = rakPeerInterface->GetAveragePing(packet->guid); - int ping2 = rakPeerInterface->GetAveragePing(endpointGuid); - if (ping1>ping2) - miniPunchRequest.timeout= MafiaNet::GetTimeMS() + ping1*8+300; - else - miniPunchRequest.timeout= MafiaNet::GetTimeMS() + ping2*8+300; - miniPunchRequest.nextAction= MafiaNet::GetTimeMS()+100; - SendOOBMessages(&miniPunchRequest); - miniPunchesInProgressMutex.Lock(); - miniPunchesInProgress.Push(miniPunchRequest,_FILE_AND_LINE_); - miniPunchesInProgressMutex.Unlock(); - } -} -void Router2::OnMiniPunchReplyBounce(Packet *packet) -{ - // Find stored punch request - unsigned int i=0; - - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE from guid=%I64d (miniPunchesInProgress.Size() = %d)", - packet->guid.g, miniPunchesInProgress.Size())); - } - - miniPunchesInProgressMutex.Lock(); - while (i < miniPunchesInProgress.Size()) - { - if (miniPunchesInProgress[i].sourceGuid==packet->guid || miniPunchesInProgress[i].endpointGuid==packet->guid) - { - if (miniPunchesInProgress[i].sourceGuid==packet->guid) - miniPunchesInProgress[i].gotReplyFromSource=true; - if (miniPunchesInProgress[i].endpointGuid==packet->guid) - miniPunchesInProgress[i].gotReplyFromEndpoint=true; - - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Processing ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE, gotReplyFromSource=%i gotReplyFromEndpoint=%i at %s:%i\n", miniPunchesInProgress[i].gotReplyFromSource, miniPunchesInProgress[i].gotReplyFromEndpoint, __FILE__, __LINE__)); - } - - if (miniPunchesInProgress[i].gotReplyFromEndpoint==true && - miniPunchesInProgress[i].gotReplyFromSource==true) - { - SendForwardingSuccess(ID_ROUTER_2_REROUTED, miniPunchesInProgress[i].endpointGuid, miniPunchesInProgress[i].sourceGuid, miniPunchesInProgress[i].forwardingPort); - SendForwardingSuccess(ID_ROUTER_2_FORWARDING_ESTABLISHED, miniPunchesInProgress[i].sourceGuid, miniPunchesInProgress[i].endpointGuid, miniPunchesInProgress[i].forwardingPort); - miniPunchesInProgress.RemoveAtIndexFast(i); - } - else - { - i++; - } - } - else - i++; - } - miniPunchesInProgressMutex.Unlock(); -} -void Router2::OnMiniPunchReply(Packet *packet) -{ - MafiaNet::BitStream bs(packet->data, packet->length, false); - bs.IgnoreBytes(sizeof(MessageID) + sizeof(unsigned char)); - RakNetGUID routerGuid; - bs.Read(routerGuid); - SendOOBFromRakNetPort(ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE, 0, rakPeerInterface->GetSystemAddressFromGuid(routerGuid)); - - if (debugInterface) - { - char buff[512]; - - char buff2[512]; - - rakPeerInterface->GetSystemAddressFromGuid(routerGuid).ToString(true,buff2,static_cast(512)); - - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Sending ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE (%s) at %s:%i\n", buff2, __FILE__, __LINE__)); - } -} -void Router2::OnRerouted(Packet *packet) -{ - MafiaNet::BitStream bs(packet->data, packet->length, false); - bs.IgnoreBytes(sizeof(MessageID)); - RakNetGUID endpointGuid; - bs.Read(endpointGuid); - unsigned short sourceToDestPort; - bs.Read(sourceToDestPort); - - // Return rerouted notice - SystemAddress intermediaryAddress=packet->systemAddress; - intermediaryAddress.SetPortHostOrder(sourceToDestPort); - rakPeerInterface->ChangeSystemAddress(endpointGuid, intermediaryAddress); - - unsigned int forwardingIndex; - forwardedConnectionListMutex.Lock(); - for (forwardingIndex=0; forwardingIndex < forwardedConnectionList.Size(); forwardingIndex++) - { - if (forwardedConnectionList[forwardingIndex].endpointGuid==endpointGuid) - break; - } - - if (forwardingIndexsystemAddress; - ref_fc.intermediaryAddress.SetPortHostOrder(sourceToDestPort); - ref_fc.intermediaryGuid = packet->guid; - - rakPeerInterface->ChangeSystemAddress(endpointGuid, intermediaryAddress); - - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"FIX: Got ID_ROUTER_2_REROUTE, returning ID_ROUTER_2_REROUTED," - " Calling RakPeer::ChangeSystemAddress(%I64d, %s) at %s:%i\n",endpointGuid.g, intermediaryAddress.ToString(true), __FILE__, __LINE__)); - } - } - else - { - ForwardedConnection fc; - fc.endpointGuid=endpointGuid; - fc.intermediaryAddress=packet->systemAddress; - fc.intermediaryAddress.SetPortHostOrder(sourceToDestPort); - fc.intermediaryGuid=packet->guid; - fc.weInitiatedForwarding=false; - // add to forwarding list. This is only here to avoid reporting direct connections in Router2::ReturnFailureOnCannotForward - forwardedConnectionList.Push (fc,__FILE__, __LINE__); - forwardedConnectionListMutex.Unlock(); - - rakPeerInterface->ChangeSystemAddress(endpointGuid, intermediaryAddress); - - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REROUTE, returning ID_ROUTER_2_REROUTED, Calling RakPeer::ChangeSystemAddress at %s:%i\n", __FILE__, __LINE__)); - } - } - -} -bool Router2::OnForwardingSuccess(Packet *packet) -{ - MafiaNet::BitStream bs(packet->data, packet->length, false); - bs.IgnoreBytes(sizeof(MessageID)); - RakNetGUID endpointGuid; - bs.Read(endpointGuid); - unsigned short sourceToDestPort; - bs.Read(sourceToDestPort); - - unsigned int forwardingIndex; - forwardedConnectionListMutex.Lock(); - for (forwardingIndex=0; forwardingIndex < forwardedConnectionList.Size(); forwardingIndex++) - { - if (forwardedConnectionList[forwardingIndex].endpointGuid==endpointGuid) - break; - } - - if (forwardingIndexsystemAddress; - intermediaryAddress.SetPortHostOrder(sourceToDestPort); - rakPeerInterface->ChangeSystemAddress(endpointGuid, intermediaryAddress); - - //////////////////////////////////////////////////////////////////////////// - ForwardedConnection& ref_fc = forwardedConnectionList[forwardingIndex]; - ref_fc.intermediaryAddress = packet->systemAddress; - ref_fc.intermediaryAddress.SetPortHostOrder(sourceToDestPort); - ref_fc.intermediaryGuid = packet->guid; - //////////////////////////////////////////////////////////////////////////// - - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_FORWARDING_ESTABLISHED, returning ID_ROUTER_2_REROUTED, Calling RakPeer::ChangeSystemAddress at %s:%i\n", _FILE_AND_LINE_)); - } - - packet->data[0]=ID_ROUTER_2_REROUTED; - - forwardedConnectionListMutex.Unlock(); - return true; // Return packet to user - } - else - { - forwardedConnectionListMutex.Unlock(); - - // removeFrom connectionRequests; - ForwardedConnection fc; - connectionRequestsMutex.Lock(); - unsigned int connectionRequestIndex = GetConnectionRequestIndex(endpointGuid); - fc.returnConnectionLostOnFailure=connectionRequests[connectionRequestIndex]->returnConnectionLostOnFailure; - connectionRequests.RemoveAtIndexFast(connectionRequestIndex); - connectionRequestsMutex.Unlock(); - fc.endpointGuid=endpointGuid; - fc.intermediaryAddress=packet->systemAddress; - fc.intermediaryAddress.SetPortHostOrder(sourceToDestPort); - fc.intermediaryGuid=packet->guid; - fc.weInitiatedForwarding=true; - - // add to forwarding list - forwardedConnectionListMutex.Lock(); - forwardedConnectionList.Push (fc,_FILE_AND_LINE_); - forwardedConnectionListMutex.Unlock(); - - if (debugInterface) - { - char buff[512]; - debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got and returning to user ID_ROUTER_2_FORWARDING_ESTABLISHED at %s:%i\n", _FILE_AND_LINE_)); - } - - } - return true; // Return packet to user -} -int Router2::GetLargestPingAmongConnectedSystems(void) const -{ - int avePing; - int largestPing=-1; - unsigned int maxPeers = rakPeerInterface->GetMaximumNumberOfPeers(); - if (maxPeers==0) - return 9999; - unsigned int index; - for (index=0; index < rakPeerInterface->GetMaximumNumberOfPeers(); index++) - { - RakNetGUID g = rakPeerInterface->GetGUIDFromIndex(index); - if (g!=UNASSIGNED_RAKNET_GUID) - { - avePing=rakPeerInterface->GetAveragePing(rakPeerInterface->GetGUIDFromIndex(index)); - if (avePing>largestPing) - largestPing=avePing; - } - } - return largestPing; -} - -unsigned int Router2::GetConnectionRequestIndex(RakNetGUID endpointGuid) -{ - unsigned int i; - for (i=0; i < connectionRequests.Size(); i++) - { - if (connectionRequests[i]->endpointGuid==endpointGuid) - return i; - } - return (unsigned int) -1; -} -unsigned int Router2::ConnnectRequest::GetGuidIndex(RakNetGUID guid) -{ - unsigned int i; - for (i=0; i < connectionRequestSystems.Size(); i++) - { - if (connectionRequestSystems[i].guid==guid) - return i; - } - return (unsigned int) -1; -} -void Router2::ReturnToUser(MessageID messageId, RakNetGUID endpointGuid, const SystemAddress &systemAddress, bool wasGeneratedLocally) -{ - Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(unsigned char)); - p->data[0]=messageId; - p->systemAddress=systemAddress; - p->systemAddress.systemIndex=(SystemIndex)-1; - p->guid=endpointGuid; - p->wasGeneratedLocally=wasGeneratedLocally; - rakPeerInterface->PushBackPacket(p, true); -} -void Router2::ClearForwardedConnections(void) -{ - forwardedConnectionListMutex.Lock(); - forwardedConnectionList.Clear(false,_FILE_AND_LINE_); - forwardedConnectionListMutex.Unlock(); -} -void Router2::ClearAll(void) -{ - ClearConnectionRequests(); - ClearMinipunches(); - ClearForwardedConnections(); -} -void Router2::SetDebugInterface(Router2DebugInterface *_debugInterface) -{ - debugInterface=_debugInterface; -} -Router2DebugInterface *Router2::GetDebugInterface(void) const -{ - return debugInterface; -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/SecureHandshake.cpp b/vendors/mafianet/Source/src/SecureHandshake.cpp deleted file mode 100644 index 54a04c816..000000000 --- a/vendors/mafianet/Source/src/SecureHandshake.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// - - -#include "mafianet/NativeFeatureIncludes.h" - -#if LIBCAT_SECURITY==1 - -// If building a MafiaNet DLL, be sure to tweak the CAT_EXPORT macro meaning -#if !defined(_MAFIANET_LIB) && defined(_MAFIANET_DLL) -# define CAT_BUILD_DLL -#else -# define CAT_NEUTER_EXPORT -#endif - -#include "cat/src/port/EndianNeutral.cpp" -#include "cat/src/port/AlignedAlloc.cpp" -#include "cat/src/time/Clock.cpp" -#include "cat/src/threads/Mutex.cpp" -#include "cat/src/threads/Thread.cpp" -#include "cat/src/threads/WaitableFlag.cpp" -#include "cat/src/hash/MurmurHash2.cpp" -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4706) // assignment within conditional expression -#endif -#include "cat/src/lang/Strings.cpp" -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4706) // assignment within conditional expression -#endif -#include "cat/src/math/BigRTL.cpp" -#ifdef _MSC_VER -#pragma warning(pop) -#endif -#include "cat/src/math/BigPseudoMersenne.cpp" -#include "cat/src/math/BigTwistedEdwards.cpp" - -#include "cat/src/crypt/SecureCompare.cpp" -#include "cat/src/crypt/cookie/CookieJar.cpp" -#include "cat/src/crypt/hash/HMAC_MD5.cpp" -#include "cat/src/crypt/privatekey/ChaCha.cpp" -#include "cat/src/crypt/hash/Skein.cpp" -#include "cat/src/crypt/hash/Skein256.cpp" -#include "cat/src/crypt/hash/Skein512.cpp" -#include "cat/src/crypt/pass/Passwords.cpp" - -#include "cat/src/crypt/rand/EntropyWindows.cpp" -#include "cat/src/crypt/rand/EntropyLinux.cpp" -#include "cat/src/crypt/rand/EntropyWindowsCE.cpp" -#include "cat/src/crypt/rand/EntropyGeneric.cpp" -#ifdef _M_X64 -#pragma warning(push) -#pragma warning(disable:4838) -#endif -#include "cat/src/crypt/rand/Fortuna.cpp" -#ifdef _M_X64 -#pragma warning(pop) -#endif - -#include "cat/src/crypt/tunnel/KeyAgreement.cpp" -#include "cat/src/crypt/tunnel/AuthenticatedEncryption.cpp" -#include "cat/src/crypt/tunnel/KeyAgreementInitiator.cpp" -#include "cat/src/crypt/tunnel/KeyAgreementResponder.cpp" -#include "cat/src/crypt/tunnel/KeyMaker.cpp" - -#include "cat/src/crypt/tunnel/EasyHandshake.cpp" - -#endif // LIBCAT_SECURITY diff --git a/vendors/mafianet/Source/src/SendToThread.cpp b/vendors/mafianet/Source/src/SendToThread.cpp deleted file mode 100644 index 12a5808ec..000000000 --- a/vendors/mafianet/Source/src/SendToThread.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/SendToThread.h" -#ifdef USE_THREADED_SEND -#include "mafianet/thread.h" -#include "mafianet/InternalPacket.h" -#include "mafianet/GetTime.h" - -#if USE_SLIDING_WINDOW_CONGESTION_CONTROL!=1 -#include "mafianet/CCRakNetUDT.h" -#else -#include "mafianet/CCRakNetSlidingWindow.h" -#endif - -using namespace MafiaNet; - -int SendToThread::refCount=0; -DataStructures::ThreadsafeAllocatingQueue SendToThread::objectQueue; -ThreadPool SendToThread::threadPool; - -SendToThread::SendToThreadBlock* SendToWorkerThread(SendToThread::SendToThreadBlock* input, bool *returnOutput, void* perThreadData) -{ - (void) perThreadData; - *returnOutput=false; -// MafiaNet::TimeUS *mostRecentTime=(MafiaNet::TimeUS *)input->data; -// *mostRecentTime=MafiaNet::GetTimeUS(); - SocketLayer::SendTo(input->s, input->data, input->dataWriteOffset, input->systemAddress, _FILE_AND_LINE_); - SendToThread::objectQueue.Push(input); - return 0; -} -SendToThread::SendToThread() -{ -} -SendToThread::~SendToThread() -{ - -} -void SendToThread::AddRef(void) -{ - if (++refCount==1) - { - threadPool.StartThreads(1,0); - } -} -void SendToThread::Deref(void) -{ - if (refCount>0) - { - if (--refCount==0) - { - threadPool.StopThreads(); - RakAssert(threadPool.NumThreadsWorking()==0); - - unsigned i; - SendToThreadBlock* info; - for (i=0; i < threadPool.InputSize(); i++) - { - info = threadPool.GetInputAtIndex(i); - objectQueue.Push(info); - } - threadPool.ClearInput(); - objectQueue.Clear(_FILE_AND_LINE_); - } - } -} -SendToThread::SendToThreadBlock* SendToThread::AllocateBlock(void) -{ - SendToThread::SendToThreadBlock *b; - b=objectQueue.Pop(); - if (b==0) - b=objectQueue.Allocate(_FILE_AND_LINE_); - return b; -} -void SendToThread::ProcessBlock(SendToThread::SendToThreadBlock* threadedSend) -{ - RakAssert(threadedSend->dataWriteOffset>0 && threadedSend->dataWriteOffset<=MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE); - threadPool.AddInput(SendToWorkerThread,threadedSend); -} -#endif diff --git a/vendors/mafianet/Source/src/SignaledEvent.cpp b/vendors/mafianet/Source/src/SignaledEvent.cpp deleted file mode 100644 index 5e4c2b9e2..000000000 --- a/vendors/mafianet/Source/src/SignaledEvent.cpp +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/SignaledEvent.h" -#include "mafianet/assert.h" -#include "mafianet/sleep.h" - -#if defined(__GNUC__) -#include -#include -#endif - -using namespace MafiaNet; - - - - - -SignaledEvent::SignaledEvent() -{ -#ifdef _WIN32 - eventList=INVALID_HANDLE_VALUE; - - -#else - isSignaled=false; -#endif -} -SignaledEvent::~SignaledEvent() -{ - // Intentionally do not close event, so it doesn't close twice on linux -} - -void SignaledEvent::InitEvent(void) -{ -#if defined(_WIN32) - eventList=CreateEvent(0, false, false, 0); -#else - -#if !defined(ANDROID) - pthread_condattr_init( &condAttr ); - pthread_cond_init(&eventList, &condAttr); -#else - pthread_cond_init(&eventList, 0); -#endif - pthread_mutexattr_init( &mutexAttr ); - pthread_mutex_init(&hMutex, &mutexAttr); -#endif -} - -void SignaledEvent::CloseEvent(void) -{ -#ifdef _WIN32 - if (eventList!=INVALID_HANDLE_VALUE) - { - CloseHandle(eventList); - eventList=INVALID_HANDLE_VALUE; - } - - - - - - - - - -#else - pthread_cond_destroy(&eventList); - pthread_mutex_destroy(&hMutex); -#if !defined(ANDROID) - pthread_condattr_destroy( &condAttr ); -#endif - pthread_mutexattr_destroy( &mutexAttr ); -#endif -} - -void SignaledEvent::SetEvent(void) -{ -#ifdef _WIN32 - ::SetEvent(eventList); - - - - - - - - - - -#else - // Different from SetEvent which stays signaled. - // We have to record manually that the event was signaled - isSignaledMutex.Lock(); - isSignaled=true; - isSignaledMutex.Unlock(); - - // Unblock waiting threads - pthread_cond_broadcast(&eventList); -#endif -} - -void SignaledEvent::WaitOnEvent(int timeoutMs) -{ -#ifdef _WIN32 -// WaitForMultipleObjects( -// 2, -// eventList, -// false, -// timeoutMs); - WaitForSingleObjectEx(eventList,timeoutMs,FALSE); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#else - - // If was previously set signaled, just unset and return - isSignaledMutex.Lock(); - if (isSignaled==true) - { - isSignaled=false; - isSignaledMutex.Unlock(); - return; - } - isSignaledMutex.Unlock(); - - - - //struct timespec ts; - - // Else wait for SetEvent to be called - - - - - - - - - - - - - - - - - - struct timespec ts; - - int rc; - struct timeval tp; - rc = gettimeofday(&tp, nullptr); - ts.tv_sec = tp.tv_sec; - ts.tv_nsec = tp.tv_usec * 1000; -// #endif - - while (timeoutMs > 30) - { - // Wait 30 milliseconds for the signal, then check again. - // This is in case we missed the signal between the top of this function and pthread_cond_timedwait, or after the end of the loop and pthread_cond_timedwait - ts.tv_nsec += 30*1000000; - if (ts.tv_nsec >= 1000000000) - { - ts.tv_nsec -= 1000000000; - ts.tv_sec++; - } - - // [SBC] added mutex lock/unlock around cond_timedwait. - // this prevents airplay from generating a whole much of errors. - // not sure how this works on other platforms since according to - // the docs you are suppost to hold the lock before you wait - // on the cond. - pthread_mutex_lock(&hMutex); - pthread_cond_timedwait(&eventList, &hMutex, &ts); - pthread_mutex_unlock(&hMutex); - - timeoutMs-=30; - - isSignaledMutex.Lock(); - if (isSignaled==true) - { - isSignaled=false; - isSignaledMutex.Unlock(); - return; - } - isSignaledMutex.Unlock(); - } - - // Wait the remaining time, and turn off the signal in case it was set - ts.tv_nsec += timeoutMs*1000000; - if (ts.tv_nsec >= 1000000000) - { - ts.tv_nsec -= 1000000000; - ts.tv_sec++; - } - - pthread_mutex_lock(&hMutex); - pthread_cond_timedwait(&eventList, &hMutex, &ts); - pthread_mutex_unlock(&hMutex); - - isSignaledMutex.Lock(); - isSignaled=false; - isSignaledMutex.Unlock(); - -#endif -} diff --git a/vendors/mafianet/Source/src/SimpleMutex.cpp b/vendors/mafianet/Source/src/SimpleMutex.cpp deleted file mode 100644 index 063f7243e..000000000 --- a/vendors/mafianet/Source/src/SimpleMutex.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// - - - -#include "mafianet/SimpleMutex.h" -#include "mafianet/assert.h" - -using namespace MafiaNet; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -SimpleMutex::SimpleMutex() //: isInitialized(false) -{ - - - - - - - - // Prior implementation of Initializing in Lock() was not threadsafe - Init(); -} - -SimpleMutex::~SimpleMutex() -{ -// if (isInitialized==false) -// return; -#ifdef _WIN32 - // CloseHandle(hMutex); - DeleteCriticalSection(&criticalSection); - - - - - - -#else - pthread_mutex_destroy(&hMutex); -#endif - - - - - - - -} - -#ifdef _WIN32 -#ifdef _DEBUG -#include -#endif -#endif - -void SimpleMutex::Lock(void) -{ -// if (isInitialized==false) -// Init(); - -#ifdef _WIN32 - /* - DWORD d = WaitForSingleObject(hMutex, INFINITE); - #ifdef _DEBUG - if (d==WAIT_FAILED) - { - LPVOID messageBuffer; - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language - (LPTSTR) &messageBuffer, - 0, - nullptr - ); - // Process any inserts in messageBuffer. - // ... - // Display the string. - //MessageBox( nullptr, (LPCTSTR)messageBuffer, "Error", MB_OK | MB_ICONINFORMATION ); - RAKNET_DEBUG_PRINTF("SimpleMutex error: %s", messageBuffer); - // Free the buffer. - LocalFree( messageBuffer ); - - } - - RakAssert(d==WAIT_OBJECT_0); - */ - EnterCriticalSection(&criticalSection); - - - - - - -#else - int error = pthread_mutex_lock(&hMutex); - (void) error; - RakAssert(error==0); -#endif -} - -void SimpleMutex::Unlock(void) -{ -// if (isInitialized==false) -// return; -#ifdef _WIN32 - // ReleaseMutex(hMutex); - LeaveCriticalSection(&criticalSection); -#else - int error = pthread_mutex_unlock(&hMutex); - (void) error; - RakAssert(error==0); -#endif -} - -void SimpleMutex::Init(void) -{ -#if defined(_WIN32) - // hMutex = CreateMutex(nullptr, FALSE, 0); - // RakAssert(hMutex); - InitializeCriticalSection(&criticalSection); -#else - int error = pthread_mutex_init(&hMutex, 0); - (void) error; - RakAssert(error==0); -#endif -// isInitialized=true; -} diff --git a/vendors/mafianet/Source/src/SocketLayer.cpp b/vendors/mafianet/Source/src/SocketLayer.cpp deleted file mode 100644 index 44bd2d0eb..000000000 --- a/vendors/mafianet/Source/src/SocketLayer.cpp +++ /dev/null @@ -1,491 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// \brief SocketLayer class implementation -/// - -#include "mafianet/SocketLayer.h" -#include "mafianet/assert.h" -#include "mafianet/types.h" -#include "mafianet/peer.h" -#include "mafianet/GetTime.h" -#include "mafianet/LinuxStrings.h" -#include "mafianet/SocketDefines.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" -#if (defined(__GNUC__) || defined(__GCCXML__)) && !defined(__WIN32__) -#include -#endif - -#ifdef _WIN32 -#include -#else -#ifndef _T -#define _T(x) (x) -#endif -#endif - -using namespace MafiaNet; - -/* -#if defined(__native_client__) -using namespace pp; -#endif -*/ - -#if USE_SLIDING_WINDOW_CONGESTION_CONTROL!=1 -#include "mafianet/CCRakNetUDT.h" -#else -#include "mafianet/CCRakNetSlidingWindow.h" -#endif - -//SocketLayerOverride *SocketLayer::slo=0; - -#ifdef _WIN32 - -#include "mafianet/WSAStartupSingleton.h" -#include "mafianet/WindowsIncludes.h" - -#else - -#include // memcpy -#include -#include -#include -#include // error numbers -#include // RAKNET_DEBUG_PRINTF -#if !defined(ANDROID) -#include -#endif -#include -#include -#include -#include -#include - -#endif - -#include "mafianet/sleep.h" -#include -#include "mafianet/Itoa.h" - -namespace MafiaNet -{ - extern void ProcessNetworkPacket( const SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, MafiaNet::TimeUS timeRead ); - //extern void ProcessNetworkPacket( const SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNetSocket* rakNetSocket, MafiaNet::TimeUS timeRead ); -} - -// http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#ip4to6 -// http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#getaddrinfo - -#if RAKNET_SUPPORT_IPV6==1 -void PrepareAddrInfoHints(addrinfo *hints) -{ - memset(hints, 0, sizeof (addrinfo)); // make sure the struct is empty - hints->ai_socktype = SOCK_DGRAM; // UDP sockets - hints->ai_flags = AI_PASSIVE; // fill in my IP for me -} -#endif - -void SocketLayer::SetSocketOptions( __UDPSOCKET__ listenSocket, bool blockingSocket, bool setBroadcast) -{ -#ifdef __native_client__ - (void) listenSocket; -#else - int sock_opt = 1; - - // This doubles the max throughput rate - sock_opt=1024*256; - setsockopt__(listenSocket, SOL_SOCKET, SO_RCVBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) ); - - // Immediate hard close. Don't linger the socket, or recreating the socket quickly on Vista fails. - // Fail with voice and xbox - - sock_opt=0; - setsockopt__(listenSocket, SOL_SOCKET, SO_LINGER, ( char * ) & sock_opt, sizeof ( sock_opt ) ); - - // This doesn't make much difference: 10% maybe - // Not supported on console 2 - sock_opt=1024*16; - setsockopt__(listenSocket, SOL_SOCKET, SO_SNDBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) ); - - if (blockingSocket==false) - { -#ifdef _WIN32 - unsigned long nonblocking = 1; - ioctlsocket__(listenSocket, FIONBIO, &nonblocking ); -#else - fcntl( listenSocket, F_SETFL, O_NONBLOCK ); -#endif - } - if (setBroadcast) - { - // Note: Fails with VDP but not xbox - // Set broadcast capable - sock_opt=1; - if ( setsockopt__(listenSocket, SOL_SOCKET, SO_BROADCAST, ( char * ) & sock_opt, sizeof( sock_opt ) ) == -1 ) - { -#if defined(_WIN32) && defined(_DEBUG) - DWORD dwIOError = GetLastError(); - // On Vista, can get WSAEACCESS (10013) - // See http://support.microsoft.com/kb/819124 - // http://blogs.msdn.com/wndp/archive/2007/03/19/winsock-so-exclusiveaddruse-on-vista.aspx - // http://msdn.microsoft.com/en-us/library/ms740621(VS.85).aspx - LPTSTR messageBuffer; - FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language - ( LPTSTR ) & messageBuffer, 0, nullptr); - // something has gone wrong here... - RAKNET_DEBUG_TPRINTF( _T("setsockopt__(SO_BROADCAST) failed:Error code - %lu\n%s"), dwIOError, messageBuffer ); - //Free the buffer. - LocalFree( messageBuffer ); -#endif - } - } -#endif -} - -MafiaNet::RakString SocketLayer::GetSubNetForSocketAndIp(__UDPSOCKET__ inSock, MafiaNet::RakString inIpString) -{ - MafiaNet::RakString netMaskString; - MafiaNet::RakString ipString; - -#if defined(_WIN32) - INTERFACE_INFO InterfaceList[20]; - unsigned long nBytesReturned; - if (WSAIoctl(inSock, SIO_GET_INTERFACE_LIST, 0, 0, &InterfaceList, - sizeof(InterfaceList), &nBytesReturned, 0, 0) == SOCKET_ERROR) { - return ""; - } - - int nNumInterfaces = nBytesReturned / sizeof(INTERFACE_INFO); - - for (int i = 0; i < nNumInterfaces; ++i) - { - sockaddr_in *pAddress; - pAddress = (sockaddr_in *) & (InterfaceList[i].iiAddress); - char ip[65]; - inet_ntop(pAddress->sin_family, &pAddress->sin_addr, ip, 65); - ipString = ip; - - if (inIpString==ipString) - { - pAddress = (sockaddr_in *) & (InterfaceList[i].iiNetmask); - char netmaskIP[65]; - inet_ntop(pAddress->sin_family, &pAddress->sin_addr, netmaskIP, 65); - netMaskString=netmaskIP; - return netMaskString; - } - } - return ""; -#else - - int fd,fd2; - fd2 = socket__(AF_INET, SOCK_DGRAM, 0); - - if(fd2 < 0) - { - return ""; - } - - struct ifconf ifc; - char buf[1999]; - ifc.ifc_len = sizeof(buf); - ifc.ifc_buf = buf; - if(ioctl(fd2, SIOCGIFCONF, &ifc) < 0) - { - close(fd2); - return ""; - } - - struct ifreq *ifr; - ifr = ifc.ifc_req; - int intNum = ifc.ifc_len / sizeof(struct ifreq); - for(int i = 0; i < intNum; i++) - { - char ip[65]; - inet_ntop(AF_INET, &((struct sockaddr_in *)&ifr[i].ifr_addr)->sin_addr, ip, 65); - ipString = ip; - - if (inIpString==ipString) - { - struct ifreq ifr2; - fd = socket__(AF_INET, SOCK_DGRAM, 0); - if(fd < 0) - { - return ""; - } - ifr2.ifr_addr.sa_family = AF_INET; - - strncpy_s(ifr2.ifr_name, IFNAMSIZ, ifr[i].ifr_name, IFNAMSIZ-1); - - ioctl(fd, SIOCGIFNETMASK, &ifr2); - - close(fd); - close(fd2); - inet_ntop(AF_INET, &((struct sockaddr_in *)&ifr2.ifr_addr)->sin_addr, ip, 65); - netMaskString=ip; - - return netMaskString; - } - } - - close(fd2); - return ""; -#endif -} - -void GetMyIP_Win32( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) -{ - int idx=0; - idx=0; - char ac[ 80 ]; - if ( gethostname( ac, sizeof( ac ) ) == -1 ) - { - #if defined(_WIN32) - DWORD dwIOError = GetLastError(); - LPTSTR messageBuffer; - FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language - ( LPTSTR ) & messageBuffer, 0, nullptr); - // something has gone wrong here... - RAKNET_DEBUG_TPRINTF( _T("gethostname failed:Error code - %lu\n%s"), dwIOError, messageBuffer ); - //Free the buffer. - LocalFree( messageBuffer ); - #endif - return ; - } - -#if RAKNET_SUPPORT_IPV6==1 - struct addrinfo hints; - struct addrinfo *servinfo=0, *aip; // will point to the results - PrepareAddrInfoHints(&hints); - getaddrinfo(ac, "", &hints, &servinfo); - - for (idx=0, aip = servinfo; aip != nullptr && idx < MAXIMUM_NUMBER_OF_INTERNAL_IDS; aip = aip->ai_next, idx++) - { - if (aip->ai_family == AF_INET) - { - struct sockaddr_in *ipv4 = (struct sockaddr_in *)aip->ai_addr; - memcpy(&addresses[idx].address.addr4,ipv4,sizeof(sockaddr_in)); - } - else - { - struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)aip->ai_addr; - memcpy(&addresses[idx].address.addr4,ipv6,sizeof(sockaddr_in6)); - } - } - - freeaddrinfo(servinfo); // free the linked-list -#else - struct addrinfo *curAddress = nullptr; - int err = getaddrinfo(ac, nullptr, nullptr, &curAddress); - - if ( err != 0 ) - { - #if defined(_WIN32) - int wsaError = WSAGetLastError(); - LPTSTR messageBuffer; - FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, wsaError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language - ( LPTSTR ) & messageBuffer, 0, nullptr); - // something has gone wrong here... - RAKNET_DEBUG_TPRINTF( _T("getaddrinfo failed:Error code - %d\n%s"), wsaError, messageBuffer ); - - //Free the buffer. - LocalFree( messageBuffer ); - #endif - return; - } - while (curAddress != nullptr && idx < MAXIMUM_NUMBER_OF_INTERNAL_IDS) - { - if (curAddress->ai_family == AF_INET) { - addresses[idx].address.addr4 = *((struct sockaddr_in *)curAddress->ai_addr); - ++idx; - } - curAddress = curAddress->ai_next; - } - -#endif // else RAKNET_SUPPORT_IPV6==1 - - while (idx < MAXIMUM_NUMBER_OF_INTERNAL_IDS) - { - addresses[idx]=UNASSIGNED_SYSTEM_ADDRESS; - idx++; - } -} - -void SocketLayer::GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) -{ -#if defined(_WIN32) - GetMyIP_Win32(addresses); -#else -// GetMyIP_Linux(addresses); - GetMyIP_Win32(addresses); -#endif -} - -/* -unsigned short SocketLayer::GetLocalPort(RakNetSocket *s) -{ - SystemAddress sa; - GetSystemAddress(s,&sa); - return sa.GetPort(); -} -*/ - -unsigned short SocketLayer::GetLocalPort(__UDPSOCKET__ s) -{ - SystemAddress sa; - GetSystemAddress(s,&sa); - return sa.GetPort(); -} -void SocketLayer::GetSystemAddress_Old ( __UDPSOCKET__ s, SystemAddress *systemAddressOut ) -{ -#if defined(__native_client__) - *systemAddressOut = UNASSIGNED_SYSTEM_ADDRESS; -#else - sockaddr_in sa; - memset(&sa,0,sizeof(sockaddr_in)); - socklen_t len = sizeof(sa); - if (getsockname__(s, (sockaddr*)&sa, &len)!=0) - { -#if defined(_WIN32) && defined(_DEBUG) - DWORD dwIOError = GetLastError(); - LPTSTR messageBuffer; - FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language - ( LPTSTR ) & messageBuffer, 0, nullptr); - // something has gone wrong here... - RAKNET_DEBUG_TPRINTF( _T("getsockname failed:Error code - %lu\n%s"), dwIOError, messageBuffer ); - - //Free the buffer. - LocalFree( messageBuffer ); -#endif - *systemAddressOut = UNASSIGNED_SYSTEM_ADDRESS; - return; - } - - systemAddressOut->SetPortNetworkOrder(sa.sin_port); - systemAddressOut->address.addr4.sin_addr.s_addr=sa.sin_addr.s_addr; -#endif -} - -/* -void SocketLayer::GetSystemAddress_Old ( RakNetSocket *s, SystemAddress *systemAddressOut ) -{ - return GetSystemAddress_Old(s->s, systemAddressOut); -} -*/ - -void SocketLayer::GetSystemAddress ( __UDPSOCKET__ s, SystemAddress *systemAddressOut ) -{ -#if RAKNET_SUPPORT_IPV6!=1 - GetSystemAddress_Old(s, systemAddressOut); -#else - socklen_t slen; - sockaddr_storage ss; - slen = sizeof(ss); - - if (getsockname__(s, (struct sockaddr *)&ss, &slen)!=0) - { -#if defined(_WIN32) && defined(_DEBUG) - DWORD dwIOError = GetLastError(); - LPVOID messageBuffer; - FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language - ( LPTSTR ) & messageBuffer, 0, nullptr); - // something has gone wrong here... - RAKNET_DEBUG_TPRINTF( _T("getsockname failed:Error code - %d\n%s"), dwIOError, static_cast(messageBuffer)); - - //Free the buffer. - LocalFree( messageBuffer ); -#endif - systemAddressOut->FromString(0); - return; - } - - if (ss.ss_family==AF_INET) - { - memcpy(&systemAddressOut->address.addr4,(sockaddr_in *)&ss,sizeof(sockaddr_in)); - systemAddressOut->debugPort=ntohs(systemAddressOut->address.addr4.sin_port); - - uint32_t zero = 0; - if (memcmp(&systemAddressOut->address.addr4.sin_addr.s_addr, &zero, sizeof(zero))==0) - systemAddressOut->SetToLoopback(4); - // systemAddressOut->address.addr4.sin_port=ntohs(systemAddressOut->address.addr4.sin_port); - } - else - { - memcpy(&systemAddressOut->address.addr6,(sockaddr_in6 *)&ss,sizeof(sockaddr_in6)); - systemAddressOut->debugPort=ntohs(systemAddressOut->address.addr6.sin6_port); - - char zero[16]; - memset(zero,0,sizeof(zero)); - if (memcmp(&systemAddressOut->address.addr4.sin_addr.s_addr, &zero, sizeof(zero))==0) - systemAddressOut->SetToLoopback(6); - - // systemAddressOut->address.addr6.sin6_port=ntohs(systemAddressOut->address.addr6.sin6_port); - } -#endif // #if RAKNET_SUPPORT_IPV6!=1 -} - -/* -void SocketLayer::GetSystemAddress ( RakNetSocket *s, SystemAddress *systemAddressOut ) -{ - return GetSystemAddress(s->s, systemAddressOut); -} -*/ - -// void SocketLayer::SetSocketLayerOverride(SocketLayerOverride *_slo) -// { -// slo=_slo; -// } - -bool SocketLayer::GetFirstBindableIP(char firstBindable[128], int ipProto) -{ - SystemAddress ipList[ MAXIMUM_NUMBER_OF_INTERNAL_IDS ]; - SocketLayer::GetMyIP( ipList ); - - if (ipProto==AF_UNSPEC) - { - ipList[0].ToString(false,firstBindable,static_cast(128)); - return true; - } - - // Find the first valid host address - unsigned int l; - for (l=0; l < MAXIMUM_NUMBER_OF_INTERNAL_IDS; l++) - { - if (ipList[l]==UNASSIGNED_SYSTEM_ADDRESS) - break; - if (ipList[l].GetIPVersion()==4 && ipProto==AF_INET) - break; - if (ipList[l].GetIPVersion()==6 && ipProto==AF_INET6) - break; - } - - if (l==MAXIMUM_NUMBER_OF_INTERNAL_IDS || ipList[l]==UNASSIGNED_SYSTEM_ADDRESS) - return false; -// RAKNET_DEBUG_PRINTF("%i %i %i %i\n", -// ((char*)(&ipList[l].address.addr4.sin_addr.s_addr))[0], -// ((char*)(&ipList[l].address.addr4.sin_addr.s_addr))[1], -// ((char*)(&ipList[l].address.addr4.sin_addr.s_addr))[2], -// ((char*)(&ipList[l].address.addr4.sin_addr.s_addr))[3] -// ); - ipList[l].ToString(false,firstBindable,static_cast(128)); - return true; -} diff --git a/vendors/mafianet/Source/src/StatisticsHistory.cpp b/vendors/mafianet/Source/src/StatisticsHistory.cpp deleted file mode 100644 index 08176b43e..000000000 --- a/vendors/mafianet/Source/src/StatisticsHistory.cpp +++ /dev/null @@ -1,832 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_StatisticsHistory==1 - -#include "mafianet/StatisticsHistory.h" -#include "mafianet/GetTime.h" -#include "mafianet/statistics.h" -#include "mafianet/peerinterface.h" - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(StatisticsHistory,StatisticsHistory); -STATIC_FACTORY_DEFINITIONS(StatisticsHistoryPlugin,StatisticsHistoryPlugin); - -int StatisticsHistory::TrackedObjectComp( const uint64_t &key, StatisticsHistory::TrackedObject* const &data ) -{ - if (key < data->trackedObjectData.objectId) - return -1; - if (key == data->trackedObjectData.objectId) - return 0; - return 1; -} - -int TimeAndValueQueueCompAsc( StatisticsHistory::TimeAndValueQueue* const &key, StatisticsHistory::TimeAndValueQueue* const &data ) -{ - if (key->sortValue < data->sortValue) - return -1; - if (key->sortValue > data->sortValue) - return 1; - if (key->key < data->key) - return -1; - if (key->key > data->key) - return 1; - return 0; -} - -int TimeAndValueQueueCompDesc( StatisticsHistory::TimeAndValueQueue* const &key, StatisticsHistory::TimeAndValueQueue* const &data ) -{ - if (key->sortValue > data->sortValue) - return -1; - if (key->sortValue < data->sortValue) - return 1; - if (key->key > data->key) - return -1; - if (key->key < data->key) - return 1; - return 0; -} -StatisticsHistory::TrackedObjectData::TrackedObjectData() {} -StatisticsHistory::TrackedObjectData::TrackedObjectData(uint64_t _objectId, int _objectType, void *_userData) -{ - objectId=_objectId; - objectType=_objectType; - userData=_userData; -} -StatisticsHistory::StatisticsHistory() {timeToTrack = 30000;} -StatisticsHistory::~StatisticsHistory() -{ - Clear(); -} -void StatisticsHistory::SetDefaultTimeToTrack(Time defaultTimeToTrack) {timeToTrack = defaultTimeToTrack;} -Time StatisticsHistory::GetDefaultTimeToTrack(void) const {return timeToTrack;} -bool StatisticsHistory::AddObject(TrackedObjectData tod) -{ - bool objectExists; - unsigned int idx = objects.GetIndexFromKey(tod.objectId, &objectExists); - if (objectExists) - return false; - TrackedObject *to = MafiaNet::OP_NEW(_FILE_AND_LINE_); - to->trackedObjectData=tod; - objects.InsertAtIndex(to,idx,_FILE_AND_LINE_); - return true; -} -bool StatisticsHistory::RemoveObject(uint64_t objectId, void **userData) -{ - unsigned int idx = GetObjectIndex(objectId); - if (idx == (unsigned int) -1) - return false; - if (userData) - *userData = objects[idx]->trackedObjectData.userData; - RemoveObjectAtIndex(idx); - return true; -} -void StatisticsHistory::RemoveObjectAtIndex(unsigned int index) -{ - TrackedObject *to = objects[index]; - objects.RemoveAtIndex(index); - MafiaNet::OP_DELETE(to, _FILE_AND_LINE_); -} -void StatisticsHistory::Clear(void) -{ - for (unsigned int idx=0; idx < objects.Size(); idx++) - { - MafiaNet::OP_DELETE(objects[idx], _FILE_AND_LINE_); - } - objects.Clear(false, _FILE_AND_LINE_); -} -unsigned int StatisticsHistory::GetObjectCount(void) const {return objects.Size();} -StatisticsHistory::TrackedObjectData * StatisticsHistory::GetObjectAtIndex(unsigned int index) const {return &objects[index]->trackedObjectData;} -bool StatisticsHistory::AddValueByObjectID(uint64_t objectId, RakString key, SHValueType val, Time curTime, bool combineEqualTimes) -{ - unsigned int idx = GetObjectIndex(objectId); - if (idx == (unsigned int) -1) - return false; - AddValueByIndex(idx, key, val, curTime, combineEqualTimes); - return true; -} -void StatisticsHistory::AddValueByIndex(unsigned int index, RakString key, SHValueType val, Time curTime, bool combineEqualTimes) -{ - TimeAndValueQueue *queue; - TrackedObject *to = objects[index]; - DataStructures::HashIndex hi = to->dataQueues.GetIndexOf(key); - if (hi.IsInvalid()) - { - queue = MafiaNet::OP_NEW(_FILE_AND_LINE_); - queue->key=key; - queue->timeToTrackValues = timeToTrack; - to->dataQueues.Push(key, queue, _FILE_AND_LINE_); - } - else - { - queue = to->dataQueues.ItemAtIndex(hi); - } - - TimeAndValue tav; - if (combineEqualTimes==true && queue->values.Size()>0 && queue->values.PeekTail().time==curTime) - { - tav = queue->values.PopTail(); - - queue->recentSum -= tav.val; - queue->recentSumOfSquares -= tav.val * tav.val; - queue->longTermSum -= tav.val; - queue->longTermCount = queue->longTermCount - 1; - } - else - { - tav.val=0.0; - tav.time=curTime; - } - - tav.val+=val; - queue->values.Push(tav, _FILE_AND_LINE_); - - queue->recentSum += tav.val; - queue->recentSumOfSquares += tav.val * tav.val; - queue->longTermSum += tav.val; - queue->longTermCount = queue->longTermCount + 1; - if (queue->longTermLowest > tav.val) - queue->longTermLowest = tav.val; - if (queue->longTermHighest < tav.val) - queue->longTermHighest = tav.val; -} -StatisticsHistory::SHErrorCode StatisticsHistory::GetHistoryForKey(uint64_t objectId, RakString key, StatisticsHistory::TimeAndValueQueue **values, Time curTime) const -{ - if (values == 0) - return SH_INVALID_PARAMETER; - - unsigned int idx = GetObjectIndex(objectId); - if (idx == (unsigned int) -1) - return SH_UKNOWN_OBJECT; - TrackedObject *to = objects[idx]; - DataStructures::HashIndex hi = to->dataQueues.GetIndexOf(key); - if (hi.IsInvalid()) - return SH_UKNOWN_KEY; - *values = to->dataQueues.ItemAtIndex(hi); - (*values)->CullExpiredValues(curTime); - return SH_OK; -} -bool StatisticsHistory::GetHistorySorted(uint64_t objectId, SHSortOperation sortType, DataStructures::List &values) const -{ - unsigned int idx = GetObjectIndex(objectId); - if (idx == (unsigned int) -1) - return false; - TrackedObject *to = objects[idx]; - DataStructures::List itemList; - DataStructures::List keyList; - to->dataQueues.GetAsList(itemList,keyList,_FILE_AND_LINE_); - Time curTime = GetTime(); - - DataStructures::OrderedList sortedQueues; - for (unsigned int i=0; i < itemList.Size(); i++) - { - TimeAndValueQueue *tavq = itemList[i]; - tavq->CullExpiredValues(curTime); - - if (sortType == SH_SORT_BY_RECENT_SUM_ASCENDING || sortType == SH_SORT_BY_RECENT_SUM_DESCENDING) - tavq->sortValue = tavq->GetRecentSum(); - else if (sortType == SH_SORT_BY_LONG_TERM_SUM_ASCENDING || sortType == SH_SORT_BY_LONG_TERM_SUM_DESCENDING) - tavq->sortValue = tavq->GetLongTermSum(); - else if (sortType == SH_SORT_BY_RECENT_SUM_OF_SQUARES_ASCENDING || sortType == SH_SORT_BY_RECENT_SUM_OF_SQUARES_DESCENDING) - tavq->sortValue = tavq->GetRecentSumOfSquares(); - else if (sortType == SH_SORT_BY_RECENT_AVERAGE_ASCENDING || sortType == SH_SORT_BY_RECENT_AVERAGE_DESCENDING) - tavq->sortValue = tavq->GetRecentAverage(); - else if (sortType == SH_SORT_BY_LONG_TERM_AVERAGE_ASCENDING || sortType == SH_SORT_BY_LONG_TERM_AVERAGE_DESCENDING) - tavq->sortValue = tavq->GetLongTermAverage(); - else if (sortType == SH_SORT_BY_RECENT_HIGHEST_ASCENDING || sortType == SH_SORT_BY_RECENT_HIGHEST_DESCENDING) - tavq->sortValue = tavq->GetRecentHighest(); - else if (sortType == SH_SORT_BY_RECENT_LOWEST_ASCENDING || sortType == SH_SORT_BY_RECENT_LOWEST_DESCENDING) - tavq->sortValue = tavq->GetRecentLowest(); - else if (sortType == SH_SORT_BY_LONG_TERM_HIGHEST_ASCENDING || sortType == SH_SORT_BY_LONG_TERM_HIGHEST_DESCENDING) - tavq->sortValue = tavq->GetLongTermHighest(); - else - tavq->sortValue = tavq->GetLongTermLowest(); - - if ( - sortType == SH_SORT_BY_RECENT_SUM_ASCENDING || - sortType == SH_SORT_BY_LONG_TERM_SUM_ASCENDING || - sortType == SH_SORT_BY_RECENT_SUM_OF_SQUARES_ASCENDING || - sortType == SH_SORT_BY_RECENT_AVERAGE_ASCENDING || - sortType == SH_SORT_BY_LONG_TERM_AVERAGE_ASCENDING || - sortType == SH_SORT_BY_RECENT_HIGHEST_ASCENDING || - sortType == SH_SORT_BY_RECENT_LOWEST_ASCENDING || - sortType == SH_SORT_BY_LONG_TERM_HIGHEST_ASCENDING || - sortType == SH_SORT_BY_LONG_TERM_LOWEST_ASCENDING) - sortedQueues.Insert(tavq, tavq, false, _FILE_AND_LINE_, TimeAndValueQueueCompAsc); - else - sortedQueues.Insert(tavq, tavq, false, _FILE_AND_LINE_, TimeAndValueQueueCompDesc); - } - - for (unsigned int i=0; i < sortedQueues.Size(); i++) - values.Push(sortedQueues[i], _FILE_AND_LINE_); - return true; -} -void StatisticsHistory::MergeAllObjectsOnKey(RakString key, TimeAndValueQueue *tavqOutput, SHDataCategory dataCategory) const -{ - tavqOutput->Clear(); - - Time curTime = GetTime(); - - // Find every object with this key - for (unsigned int idx=0; idx < objects.Size(); idx++) - { - TrackedObject *to = objects[idx]; - DataStructures::HashIndex hi = to->dataQueues.GetIndexOf(key); - if (hi.IsInvalid()==false) - { - TimeAndValueQueue *tavqInput = to->dataQueues.ItemAtIndex(hi); - tavqInput->CullExpiredValues(curTime); - TimeAndValueQueue::MergeSets(tavqOutput, dataCategory, tavqInput, dataCategory, tavqOutput); - } - } -} -void StatisticsHistory::GetUniqueKeyList(DataStructures::List &keys) -{ - keys.Clear(true, _FILE_AND_LINE_); - - for (unsigned int idx=0; idx < objects.Size(); idx++) - { - TrackedObject *to = objects[idx]; - DataStructures::List itemList; - DataStructures::List keyList; - to->dataQueues.GetAsList(itemList, keyList, _FILE_AND_LINE_); - for (unsigned int k=0; k < keyList.Size(); k++) - { - bool hasKey=false; - for (unsigned int j=0; j < keys.Size(); j++) - { - if (keys[j]==keyList[k]) - { - hasKey=true; - break; - } - } - - if (hasKey==false) - keys.Push(keyList[k], _FILE_AND_LINE_); - } - } -} -StatisticsHistory::TimeAndValueQueue::TimeAndValueQueue() -{ - Clear(); -} -StatisticsHistory::TimeAndValueQueue::~TimeAndValueQueue(){} -void StatisticsHistory::TimeAndValueQueue::SetTimeToTrackValues(Time t) -{ - timeToTrackValues = t; -} -Time StatisticsHistory::TimeAndValueQueue::GetTimeToTrackValues(void) const {return timeToTrackValues;} -SHValueType StatisticsHistory::TimeAndValueQueue::GetRecentSum(void) const {return recentSum;} -SHValueType StatisticsHistory::TimeAndValueQueue::GetRecentSumOfSquares(void) const {return recentSumOfSquares;} -SHValueType StatisticsHistory::TimeAndValueQueue::GetLongTermSum(void) const {return longTermSum;} -SHValueType StatisticsHistory::TimeAndValueQueue::GetRecentAverage(void) const -{ - if (values.Size() > 0) - return recentSum / (SHValueType) values.Size(); - else - return 0; -} -SHValueType StatisticsHistory::TimeAndValueQueue::GetRecentLowest(void) const -{ - SHValueType out = SH_TYPE_MAX; - for (unsigned int idx=0; idx < values.Size(); idx++) - { - if (values[idx].val < out) - out = values[idx].val; - } - return out; -} -SHValueType StatisticsHistory::TimeAndValueQueue::GetRecentHighest(void) const -{ - SHValueType out = -SH_TYPE_MAX; - for (unsigned int idx=0; idx < values.Size(); idx++) - { - if (values[idx].val > out) - out = values[idx].val; - } - return out; -} -SHValueType StatisticsHistory::TimeAndValueQueue::GetRecentStandardDeviation(void) const -{ - if (values.Size()==0) - return 0; - - SHValueType recentMean= GetRecentAverage(); - SHValueType squareOfMean = recentMean * recentMean; - SHValueType meanOfSquares = GetRecentSumOfSquares() / (SHValueType) values.Size(); - return meanOfSquares - squareOfMean; -} -SHValueType StatisticsHistory::TimeAndValueQueue::GetLongTermAverage(void) const -{ - if (longTermCount == 0) - return 0; - return longTermSum / longTermCount; -} -SHValueType StatisticsHistory::TimeAndValueQueue::GetLongTermLowest(void) const {return longTermLowest;} -SHValueType StatisticsHistory::TimeAndValueQueue::GetLongTermHighest(void) const {return longTermHighest;} -Time StatisticsHistory::TimeAndValueQueue::GetTimeRange(void) const -{ - if (values.Size()<2) - return 0; - return values[values.Size()-1].time - values[0].time; -} -SHValueType StatisticsHistory::TimeAndValueQueue::GetSumSinceTime(Time t) const -{ - SHValueType sum = 0; - for (int i=values.Size(); i > 0; --i) - { - if (values[i-1].time>=t) - sum+=values[i-1].val; - } - return sum; -} -void StatisticsHistory::TimeAndValueQueue::MergeSets( const TimeAndValueQueue *lhs, SHDataCategory lhsDataCategory, const TimeAndValueQueue *rhs, SHDataCategory rhsDataCategory, TimeAndValueQueue *output ) -{ - // Two ways to merge: - // 1. Treat rhs as just more data points. - // 1A. Sums are just added. If two values have the same time, just put in queue twice - // 1B. longTermLowest and longTermHighest are the lowest and highest of the two sets - // - // 2. Add by time. If time for the other set is missing, calculate slope to extrapolate - // 2A. Have to recalculate recentSum, recentSumOfSquares. - // 2B. longTermSum, longTermCount, longTermLowest, longTermHighest are unknown - - if (lhs!=output) - { - output->key = lhs->key; - output->timeToTrackValues = lhs->timeToTrackValues; - } - else - { - output->key = rhs->key; - output->timeToTrackValues = rhs->timeToTrackValues; - } - - unsigned int lhsIndex, rhsIndex; - lhsIndex=0; - rhsIndex=0; - - // I use local valuesOutput in case lhs==output || rhs==output - DataStructures::Queue valuesOutput; - - if (lhsDataCategory==StatisticsHistory::DC_DISCRETE && rhsDataCategory==StatisticsHistory::DC_DISCRETE) - { - while (rhsIndex < rhs->values.Size() && lhsIndex < lhs->values.Size()) - { - if (rhs->values[rhsIndex].time < lhs->values[lhsIndex].time) - { - valuesOutput.Push(rhs->values[rhsIndex], _FILE_AND_LINE_ ); - rhsIndex++; - } - else if (rhs->values[rhsIndex].time > lhs->values[lhsIndex].time) - { - valuesOutput.Push(lhs->values[rhsIndex], _FILE_AND_LINE_ ); - lhsIndex++; - } - else - { - valuesOutput.Push(rhs->values[rhsIndex], _FILE_AND_LINE_ ); - rhsIndex++; - valuesOutput.Push(lhs->values[rhsIndex], _FILE_AND_LINE_ ); - lhsIndex++; - } - } - - while (rhsIndex < rhs->values.Size()) - { - valuesOutput.Push(rhs->values[rhsIndex], _FILE_AND_LINE_ ); - rhsIndex++; - } - while (lhsIndex < lhs->values.Size()) - { - valuesOutput.Push(lhs->values[lhsIndex], _FILE_AND_LINE_ ); - lhsIndex++; - } - - output->recentSum = lhs->recentSum + rhs->recentSum; - output->recentSumOfSquares = lhs->recentSumOfSquares + rhs->recentSumOfSquares; - output->longTermSum = lhs->longTermSum + rhs->longTermSum; - output->longTermCount = lhs->longTermCount + rhs->longTermCount; - if (lhs->longTermLowest < rhs->longTermLowest) - output->longTermLowest = lhs->longTermLowest; - else - output->longTermLowest = rhs->longTermLowest; - if (lhs->longTermHighest > rhs->longTermHighest) - output->longTermHighest = lhs->longTermHighest; - else - output->longTermHighest = rhs->longTermHighest; - } - else - { - TimeAndValue lastTimeAndValueLhs, lastTimeAndValueRhs; - lastTimeAndValueLhs.time=0; - lastTimeAndValueLhs.val=0; - lastTimeAndValueRhs.time=0; - lastTimeAndValueRhs.val=0; - SHValueType lastSlopeLhs=0; - SHValueType lastSlopeRhs=0; - Time timeSinceOppositeValue; - - TimeAndValue newTimeAndValue; - - while (rhsIndex < rhs->values.Size() && lhsIndex < lhs->values.Size()) - { - if (rhs->values[rhsIndex].time < lhs->values[lhsIndex].time) - { - timeSinceOppositeValue = rhs->values[rhsIndex].time - lastTimeAndValueLhs.time; - newTimeAndValue.val = rhs->values[rhsIndex].val + lastTimeAndValueLhs.val + lastSlopeLhs * timeSinceOppositeValue; - newTimeAndValue.time = rhs->values[rhsIndex].time; - lastTimeAndValueRhs = rhs->values[rhsIndex]; - if (rhsIndex>0 && rhs->values[rhsIndex].time != rhs->values[rhsIndex-1].time && rhsDataCategory==StatisticsHistory::DC_CONTINUOUS) - lastSlopeRhs = (rhs->values[rhsIndex].val - rhs->values[rhsIndex-1].val) / (SHValueType) (rhs->values[rhsIndex].time - rhs->values[rhsIndex-1].time); - rhsIndex++; - } - else if (lhs->values[lhsIndex].time < rhs->values[rhsIndex].time) - { - timeSinceOppositeValue = lhs->values[lhsIndex].time - lastTimeAndValueRhs.time; - newTimeAndValue.val = lhs->values[lhsIndex].val + lastTimeAndValueRhs.val + lastSlopeRhs * timeSinceOppositeValue; - newTimeAndValue.time = lhs->values[lhsIndex].time; - lastTimeAndValueLhs = lhs->values[lhsIndex]; - if (lhsIndex>0 && lhs->values[lhsIndex].time != lhs->values[lhsIndex-1].time && lhsDataCategory==StatisticsHistory::DC_CONTINUOUS) - lastSlopeLhs = (lhs->values[lhsIndex].val - lhs->values[lhsIndex-1].val) / (SHValueType) (lhs->values[lhsIndex].time - lhs->values[lhsIndex-1].time); - lhsIndex++; - } - else - { - newTimeAndValue.val = lhs->values[lhsIndex].val + rhs->values[rhsIndex].val; - newTimeAndValue.time = lhs->values[lhsIndex].time; - lastTimeAndValueRhs = rhs->values[rhsIndex]; - lastTimeAndValueLhs = lhs->values[lhsIndex]; - if (rhsIndex>0 && rhs->values[rhsIndex].time != rhs->values[rhsIndex-1].time && rhsDataCategory==StatisticsHistory::DC_CONTINUOUS) - lastSlopeRhs = (rhs->values[rhsIndex].val - rhs->values[rhsIndex-1].val) / (SHValueType) (rhs->values[rhsIndex].time - rhs->values[rhsIndex-1].time); - if (lhsIndex>0 && lhs->values[lhsIndex].time != lhs->values[lhsIndex-1].time && lhsDataCategory==StatisticsHistory::DC_CONTINUOUS) - lastSlopeLhs = (lhs->values[lhsIndex].val - lhs->values[lhsIndex-1].val) / (SHValueType) (lhs->values[lhsIndex].time - lhs->values[lhsIndex-1].time); - lhsIndex++; - rhsIndex++; - } - - valuesOutput.Push(newTimeAndValue, _FILE_AND_LINE_ ); - } - - while (rhsIndex < rhs->values.Size()) - { - timeSinceOppositeValue = rhs->values[rhsIndex].time - lastTimeAndValueLhs.time; - newTimeAndValue.val = rhs->values[rhsIndex].val + lastTimeAndValueLhs.val + lastSlopeLhs * timeSinceOppositeValue; - newTimeAndValue.time = rhs->values[rhsIndex].time; - valuesOutput.Push(newTimeAndValue, _FILE_AND_LINE_ ); - rhsIndex++; - } - while (lhsIndex < lhs->values.Size()) - { - timeSinceOppositeValue = lhs->values[lhsIndex].time - lastTimeAndValueRhs.time; - newTimeAndValue.val = lhs->values[lhsIndex].val + lastTimeAndValueRhs.val + lastSlopeRhs * timeSinceOppositeValue; - newTimeAndValue.time = lhs->values[lhsIndex].time; - valuesOutput.Push(newTimeAndValue, _FILE_AND_LINE_ ); - lhsIndex++; - } - - output->recentSum = 0; - output->recentSumOfSquares = 0; - for (unsigned int i=0; i < valuesOutput.Size(); i++) - { - output->recentSum += valuesOutput[i].val; - output->recentSumOfSquares += valuesOutput[i].val * valuesOutput[i].val; - } - } - - output->values = valuesOutput; -} -void StatisticsHistory::TimeAndValueQueue::ResizeSampleSet( int maxSamples, DataStructures::Queue &histogram, SHDataCategory dataCategory, Time timeClipStart, Time timeClipEnd ) -{ - histogram.Clear(_FILE_AND_LINE_); - if (maxSamples==0) - return; - Time timeRange = GetTimeRange(); - if (timeRange==0) - return; - if (maxSamples==1) - { - StatisticsHistory::TimeAndValue tav; - tav.time = timeRange; - tav.val = GetRecentSum(); - histogram.Push(tav, _FILE_AND_LINE_); - return; - } - Time interval = timeRange / maxSamples; - if (interval==0) - interval=1; - unsigned int dataIndex; - Time timeBoundary; - StatisticsHistory::TimeAndValue currentSum; - Time currentTime; - SHValueType numSamples; - Time endTime; - - numSamples=0; - endTime = values[values.Size()-1].time; - dataIndex=0; - currentTime=values[0].time; - currentSum.val=0; - currentSum.time=values[0].time + interval / 2; - timeBoundary = values[0].time + interval; - while (timeBoundary <= endTime) - { - while (dataIndex < values.Size() && values[dataIndex].time <= timeBoundary) - { - currentSum.val += values[dataIndex].val; - dataIndex++; - numSamples++; - } - - if (dataCategory==DC_CONTINUOUS) - { - if (dataIndex > 0 && - dataIndex < values.Size() && - values[dataIndex-1].time < timeBoundary && - values[dataIndex].time > timeBoundary) - { - SHValueType interpolatedValue = Interpolate(values[dataIndex-1], values[dataIndex], timeBoundary); - currentSum.val+=interpolatedValue; - numSamples++; - } - - if (numSamples > 1) - { - currentSum.val /= numSamples; - } - } - - histogram.Push(currentSum, _FILE_AND_LINE_); - currentSum.time=timeBoundary + interval / 2; - timeBoundary += interval; - currentSum.val=0; - numSamples=0; - } - - - if ( timeClipStart!=0 && histogram.Size()>=1) - { - timeClipStart = histogram.Peek().time+timeClipStart; - if (histogram.PeekTail().time < timeClipStart) - { - histogram.Clear(_FILE_AND_LINE_); - } - else if (histogram.Size()>=2 && histogram.Peek().time < timeClipStart) - { - StatisticsHistory::TimeAndValue tav; - - do - { - tav = histogram.Pop(); - - if (histogram.Peek().time == timeClipStart) - { - break; - } - else if (histogram.Peek().time > timeClipStart) - { - StatisticsHistory::TimeAndValue tav2; - tav2.val = StatisticsHistory::TimeAndValueQueue::Interpolate(tav, histogram.Peek(), timeClipStart); - tav2.time=timeClipStart; - histogram.PushAtHead(tav2, 0, _FILE_AND_LINE_); - break; - } - } while (histogram.Size()>=2); - } - } - - if ( timeClipEnd!=0 && histogram.Size()>=1) - { - timeClipEnd = histogram.PeekTail().time-timeClipEnd; - if (histogram.Peek().time > timeClipEnd) - { - histogram.Clear(_FILE_AND_LINE_); - } - else if (histogram.Size()>=2 && histogram.PeekTail().time > timeClipEnd) - { - StatisticsHistory::TimeAndValue tav; - - do - { - tav = histogram.PopTail(); - - if (histogram.PeekTail().time == timeClipEnd) - { - break; - } - else if (histogram.PeekTail().time < timeClipEnd) - { - StatisticsHistory::TimeAndValue tav2; - tav2.val = StatisticsHistory::TimeAndValueQueue::Interpolate(tav, histogram.PeekTail(), timeClipEnd); - tav2.time=timeClipEnd; - histogram.Push(tav2, _FILE_AND_LINE_); - break; - } - } while (histogram.Size()>=2); - } - } -} -void StatisticsHistory::TimeAndValueQueue::CullExpiredValues(Time curTime) -{ - while (values.Size()) - { - StatisticsHistory::TimeAndValue tav = values.Peek(); - if (curTime - tav.time > timeToTrackValues) - { - recentSum -= tav.val; - recentSumOfSquares -= tav.val * tav.val; - values.Pop(); - } - else - { - break; - } - } -} -SHValueType StatisticsHistory::TimeAndValueQueue::Interpolate(StatisticsHistory::TimeAndValue t1, StatisticsHistory::TimeAndValue t2, Time time) -{ - if (t2.time==t1.time) - return (t1.val + t2.val) / 2; -// if (t2.time > t1.time) -// { - SHValueType slope = (t2.val - t1.val) / ((SHValueType) t2.time - (SHValueType) t1.time); - return t1.val + slope * ((SHValueType) time - (SHValueType) t1.time); -// } -// else -// { -// SHValueType slope = (t1.val - t2.val) / (SHValueType) (t1.time - t2.time); -// return t2.val + slope * (SHValueType) (time - t2.time); -// } -} -void StatisticsHistory::TimeAndValueQueue::Clear(void) -{ - recentSum = 0; - recentSumOfSquares = 0; - longTermSum = 0; - longTermCount = 0; - longTermLowest = SH_TYPE_MAX; - longTermHighest = -SH_TYPE_MAX; - values.Clear(_FILE_AND_LINE_); -} -StatisticsHistory::TimeAndValueQueue& StatisticsHistory::TimeAndValueQueue::operator = ( const TimeAndValueQueue& input ) -{ - values=input.values; - timeToTrackValues=input.timeToTrackValues; - key=input.key; - recentSum=input.recentSum; - recentSumOfSquares=input.recentSumOfSquares; - longTermSum=input.longTermSum; - longTermCount=input.longTermCount; - longTermLowest=input.longTermLowest; - longTermHighest=input.longTermHighest; - return *this; -} -StatisticsHistory::TrackedObject::TrackedObject() {} -StatisticsHistory::TrackedObject::~TrackedObject() -{ - DataStructures::List itemList; - DataStructures::List keyList; - for (unsigned int idx=0; idx < itemList.Size(); idx++) - MafiaNet::OP_DELETE(itemList[idx], _FILE_AND_LINE_); -} -unsigned int StatisticsHistory::GetObjectIndex(uint64_t objectId) const -{ - bool objectExists; - unsigned int idx = objects.GetIndexFromKey(objectId, &objectExists); - if (objectExists) - return idx; - return (unsigned int) -1; -} -StatisticsHistoryPlugin::StatisticsHistoryPlugin() -{ - addNewConnections = true; - removeLostConnections = true; - newConnectionsObjectType = 0; -} -StatisticsHistoryPlugin::~StatisticsHistoryPlugin() -{ -} -void StatisticsHistoryPlugin::SetTrackConnections(bool _addNewConnections, int _newConnectionsObjectType, bool _removeLostConnections) -{ - addNewConnections = _addNewConnections; - removeLostConnections = _removeLostConnections; - newConnectionsObjectType = _newConnectionsObjectType; -} -void StatisticsHistoryPlugin::Update(void) -{ - DataStructures::List addresses; - DataStructures::List guids; - DataStructures::List stats; - rakPeerInterface->GetStatisticsList(addresses, guids, stats); - - Time curTime = GetTime(); - for (unsigned int idx = 0; idx < guids.Size(); idx++) - { - unsigned int objectIndex = statistics.GetObjectIndex(guids[idx].g); - if (objectIndex!=(unsigned int)-1) - { - statistics.AddValueByIndex(objectIndex, - "RN_ACTUAL_BYTES_SENT", - (SHValueType) stats[idx].valueOverLastSecond[ACTUAL_BYTES_SENT], - curTime, false); - - statistics.AddValueByIndex(objectIndex, - "RN_USER_MESSAGE_BYTES_RESENT", - (SHValueType) stats[idx].valueOverLastSecond[USER_MESSAGE_BYTES_RESENT], - curTime, false); - - statistics.AddValueByIndex(objectIndex, - "RN_ACTUAL_BYTES_RECEIVED", - (SHValueType) stats[idx].valueOverLastSecond[ACTUAL_BYTES_RECEIVED], - curTime, false); - - statistics.AddValueByIndex(objectIndex, - "RN_USER_MESSAGE_BYTES_PUSHED", - (SHValueType) stats[idx].valueOverLastSecond[USER_MESSAGE_BYTES_PUSHED], - curTime, false); - - statistics.AddValueByIndex(objectIndex, - "RN_USER_MESSAGE_BYTES_RECEIVED_PROCESSED", - (SHValueType) stats[idx].valueOverLastSecond[USER_MESSAGE_BYTES_RECEIVED_PROCESSED], - curTime, false); - - statistics.AddValueByIndex(objectIndex, - "RN_lastPing", - (SHValueType) rakPeerInterface->GetLastPing(guids[idx]), - curTime, false); - - statistics.AddValueByIndex(objectIndex, - "RN_bytesInResendBuffer", - (SHValueType) stats[idx].bytesInResendBuffer, - curTime, false); - - statistics.AddValueByIndex(objectIndex, - "RN_packetlossLastSecond", - (SHValueType) stats[idx].packetlossLastSecond, - curTime, false); - } - - } - - /* - RakNetStatistics rns; - DataStructures::List addresses; - DataStructures::List guids; - rakPeerInterface->GetSystemList(addresses, guids); - for (unsigned int idx = 0; idx < guids.Size(); idx++) - { - rakPeerInterface->GetStatistics(remoteSystems[idx], &rns); - statistics.AddValue(); - - bool AddValue(uint64_t objectId, RakString key, SHValueType val, Time curTime); - - } - */ -} -/* -void StatisticsHistoryPlugin::OnDirectSocketSend(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) -{ - // Would have to use GetGuidFromSystemAddress for every send -} -void StatisticsHistoryPlugin::OnDirectSocketReceive(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) -{ -} -*/ -void StatisticsHistoryPlugin::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) lostConnectionReason; - (void) systemAddress; - - if (removeLostConnections) - { - statistics.RemoveObject(rakNetGUID.g, 0); - } -} -void StatisticsHistoryPlugin::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) -{ - (void) systemAddress; - (void) isIncoming; - - if (addNewConnections) - { - statistics.AddObject(StatisticsHistory::TrackedObjectData(rakNetGUID.g, newConnectionsObjectType, 0)); - } -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -#endif // _RAKNET_SUPPORT_StatisticsHistory==1 diff --git a/vendors/mafianet/Source/src/StringCompressor.cpp b/vendors/mafianet/Source/src/StringCompressor.cpp deleted file mode 100644 index 3153aae8a..000000000 --- a/vendors/mafianet/Source/src/StringCompressor.cpp +++ /dev/null @@ -1,514 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/// \file -/// - - - -#include "mafianet/StringCompressor.h" -#include "mafianet/DS_HuffmanEncodingTree.h" -#include "mafianet/BitStream.h" -#include "mafianet/string.h" -#include "mafianet/assert.h" -#include - -#include - - - - - - - -using namespace MafiaNet; - -StringCompressor* StringCompressor::instance=0; -int StringCompressor::referenceCount=0; - -void StringCompressor::AddReference(void) -{ - if (++referenceCount==1) - { - instance = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - } -} -void StringCompressor::RemoveReference(void) -{ - RakAssert(referenceCount > 0); - - if (referenceCount > 0) - { - if (--referenceCount==0) - { - MafiaNet::OP_DELETE(instance, _FILE_AND_LINE_); - instance=0; - } - } -} - -StringCompressor* StringCompressor::Instance(void) -{ - return instance; -} - -unsigned int englishCharacterFrequencies[ 256 ] = -{ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 722, - 0, - 0, - 2, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 11084, - 58, - 63, - 1, - 0, - 31, - 0, - 317, - 64, - 64, - 44, - 0, - 695, - 62, - 980, - 266, - 69, - 67, - 56, - 7, - 73, - 3, - 14, - 2, - 69, - 1, - 167, - 9, - 1, - 2, - 25, - 94, - 0, - 195, - 139, - 34, - 96, - 48, - 103, - 56, - 125, - 653, - 21, - 5, - 23, - 64, - 85, - 44, - 34, - 7, - 92, - 76, - 147, - 12, - 14, - 57, - 15, - 39, - 15, - 1, - 1, - 1, - 2, - 3, - 0, - 3611, - 845, - 1077, - 1884, - 5870, - 841, - 1057, - 2501, - 3212, - 164, - 531, - 2019, - 1330, - 3056, - 4037, - 848, - 47, - 2586, - 2919, - 4771, - 1707, - 535, - 1106, - 152, - 1243, - 100, - 0, - 2, - 0, - 10, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 -}; - -StringCompressor::StringCompressor() -{ - DataStructures::Map::IMPLEMENT_DEFAULT_COMPARISON(); - - // Make a default tree immediately, since this is used for RPC possibly from multiple threads at the same time - HuffmanEncodingTree *huffmanEncodingTree = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - huffmanEncodingTree->GenerateFromFrequencyTable( englishCharacterFrequencies ); - - huffmanEncodingTrees.Set(0, huffmanEncodingTree); -} -void StringCompressor::GenerateTreeFromStrings( unsigned char *input, unsigned inputLength, uint8_t languageId ) -{ - HuffmanEncodingTree *huffmanEncodingTree; - if (huffmanEncodingTrees.Has(languageId)) - { - huffmanEncodingTree = huffmanEncodingTrees.Get(languageId); - MafiaNet::OP_DELETE(huffmanEncodingTree, _FILE_AND_LINE_); - } - - unsigned index; - unsigned int frequencyTable[ 256 ]; - - if ( inputLength == 0 ) - return ; - - // Zero out the frequency table - memset( frequencyTable, 0, sizeof( frequencyTable ) ); - - // Generate the frequency table from the strings - for ( index = 0; index < inputLength; index++ ) - frequencyTable[ input[ index ] ] ++; - - // Build the tree - huffmanEncodingTree = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - huffmanEncodingTree->GenerateFromFrequencyTable( frequencyTable ); - huffmanEncodingTrees.Set(languageId, huffmanEncodingTree); -} - -StringCompressor::~StringCompressor() -{ - for (unsigned i=0; i < huffmanEncodingTrees.Size(); i++) - MafiaNet::OP_DELETE(huffmanEncodingTrees[i], _FILE_AND_LINE_); -} - -void StringCompressor::EncodeString( const char *input, int maxCharsToWrite, MafiaNet::BitStream *output, uint8_t languageId ) -{ - HuffmanEncodingTree *huffmanEncodingTree; - if (huffmanEncodingTrees.Has(languageId)==false) - return; - huffmanEncodingTree=huffmanEncodingTrees.Get(languageId); - - if ( input == 0 ) - { - output->WriteCompressed( (uint32_t) 0 ); - return ; - } - - MafiaNet::BitStream encodedBitStream; - - uint32_t stringBitLength; - - int charsToWrite; - - if ( maxCharsToWrite<=0 || ( int ) strlen( input ) < maxCharsToWrite ) - charsToWrite = ( int ) strlen( input ); - else - charsToWrite = maxCharsToWrite - 1; - - huffmanEncodingTree->EncodeArray( ( unsigned char* ) input, charsToWrite, &encodedBitStream ); - - stringBitLength = (uint32_t) encodedBitStream.GetNumberOfBitsUsed(); - - output->WriteCompressed( stringBitLength ); - - output->WriteBits( encodedBitStream.GetData(), stringBitLength ); -} - -bool StringCompressor::DecodeString( char *output, int maxCharsToWrite, MafiaNet::BitStream *input, uint8_t languageId ) -{ - HuffmanEncodingTree *huffmanEncodingTree; - if (huffmanEncodingTrees.Has(languageId)==false) - return false; - if (maxCharsToWrite<=0) - return false; - huffmanEncodingTree=huffmanEncodingTrees.Get(languageId); - - uint32_t stringBitLength; - int bytesInStream; - - output[ 0 ] = 0; - - if ( input->ReadCompressed( stringBitLength ) == false ) - return false; - - if ( (unsigned) input->GetNumberOfUnreadBits() < stringBitLength ) - return false; - - bytesInStream = huffmanEncodingTree->DecodeArray( input, stringBitLength, maxCharsToWrite, ( unsigned char* ) output ); - - if ( bytesInStream < maxCharsToWrite ) - output[ bytesInStream ] = 0; - else - output[ maxCharsToWrite - 1 ] = 0; - - return true; -} -#ifdef _CSTRING_COMPRESSOR -void StringCompressor::EncodeString( const CString &input, int maxCharsToWrite, MafiaNet::BitStream *output ) -{ - LPTSTR p = input; - EncodeString(p, maxCharsToWrite*sizeof(TCHAR), output, languageID); -} -bool StringCompressor::DecodeString( CString &output, int maxCharsToWrite, MafiaNet::BitStream *input, uint8_t languageId ) -{ - LPSTR p = output.GetBuffer(maxCharsToWrite*sizeof(TCHAR)); - DecodeString(p,maxCharsToWrite*sizeof(TCHAR), input, languageID); - output.ReleaseBuffer(0) - -} -#endif -#ifdef _STD_STRING_COMPRESSOR -void StringCompressor::EncodeString( const std::string &input, int maxCharsToWrite, MafiaNet::BitStream *output, uint8_t languageId ) -{ - EncodeString(input.c_str(), maxCharsToWrite, output, languageId); -} -bool StringCompressor::DecodeString( std::string *output, int maxCharsToWrite, MafiaNet::BitStream *input, uint8_t languageId ) -{ - if (maxCharsToWrite <= 0) - { - output->clear(); - return true; - } - - char *destinationBlock; - bool out; - -#if USE_ALLOCA==1 - if (maxCharsToWrite < MAX_ALLOCA_STACK_ALLOCATION) - { - destinationBlock = (char*) alloca(maxCharsToWrite); - out=DecodeString(destinationBlock, maxCharsToWrite, input, languageId); - *output=destinationBlock; - } - else -#endif - { - destinationBlock = (char*) rakMalloc_Ex( maxCharsToWrite, _FILE_AND_LINE_ ); - out=DecodeString(destinationBlock, maxCharsToWrite, input, languageId); - *output=destinationBlock; - rakFree_Ex(destinationBlock, _FILE_AND_LINE_ ); - } - - return out; -} -#endif -void StringCompressor::EncodeString( const RakString *input, int maxCharsToWrite, MafiaNet::BitStream *output, uint8_t languageId ) -{ - EncodeString(input->C_String(), maxCharsToWrite, output, languageId); -} -bool StringCompressor::DecodeString( RakString *output, int maxCharsToWrite, MafiaNet::BitStream *input, uint8_t languageId ) -{ - if (maxCharsToWrite <= 0) - { - output->Clear(); - return true; - } - - char *destinationBlock; - bool out; - -#if USE_ALLOCA==1 - if (maxCharsToWrite < MAX_ALLOCA_STACK_ALLOCATION) - { - destinationBlock = (char*) alloca(maxCharsToWrite); - out=DecodeString(destinationBlock, maxCharsToWrite, input, languageId); - *output=destinationBlock; - } - else -#endif - { - destinationBlock = (char*) rakMalloc_Ex( maxCharsToWrite, _FILE_AND_LINE_ ); - out=DecodeString(destinationBlock, maxCharsToWrite, input, languageId); - *output=destinationBlock; - rakFree_Ex(destinationBlock, _FILE_AND_LINE_ ); - } - - return out; -} diff --git a/vendors/mafianet/Source/src/StringTable.cpp b/vendors/mafianet/Source/src/StringTable.cpp deleted file mode 100644 index 101ae1da7..000000000 --- a/vendors/mafianet/Source/src/StringTable.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/StringTable.h" -#include -#include "mafianet/assert.h" -#include -#include "mafianet/BitStream.h" -#include "mafianet/StringCompressor.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" -using namespace MafiaNet; - -StringTable* StringTable::instance=0; -int StringTable::referenceCount=0; - - -int MafiaNet::StrAndBoolComp( char *const &key, const StrAndBool &data ) -{ - return strcmp(key,(const char*)data.str); -} - -StringTable::StringTable() -{ - -} - -StringTable::~StringTable() -{ - unsigned i; - for (i=0; i < orderedStringList.Size(); i++) - { - if (orderedStringList[i].b) - rakFree_Ex(orderedStringList[i].str, _FILE_AND_LINE_ ); - } -} - -void StringTable::AddReference(void) -{ - if (++referenceCount==1) - { - instance = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - } -} -void StringTable::RemoveReference(void) -{ - RakAssert(referenceCount > 0); - - if (referenceCount > 0) - { - if (--referenceCount==0) - { - MafiaNet::OP_DELETE(instance, _FILE_AND_LINE_); - instance=0; - } - } -} - -StringTable* StringTable::Instance(void) -{ - return instance; -} - -void StringTable::AddString(const char *str, bool copyString) -{ - StrAndBool sab; - sab.b=copyString; - if (copyString) - { - sab.str = (char*) rakMalloc_Ex( strlen(str)+1, _FILE_AND_LINE_ ); - strcpy_s(sab.str, strlen(str)+1, str); - } - else - { - sab.str=(char*)str; - } - - // If it asserts inside here you are adding duplicate strings. - orderedStringList.Insert(sab.str,sab, true, _FILE_AND_LINE_); - - // If this assert hits you need to increase the range of StringTableType - RakAssert(orderedStringList.Size() < (StringTableType)-1); - -} -void StringTable::EncodeString( const char *input, int maxCharsToWrite, MafiaNet::BitStream *output ) -{ - unsigned index; - bool objectExists; - // This is fast because the list is kept ordered. - index=orderedStringList.GetIndexFromKey((char*)input, &objectExists); - if (objectExists) - { - output->Write(true); - output->Write((StringTableType)index); - } - else - { - LogStringNotFound(input); - output->Write(false); - StringCompressor::Instance()->EncodeString(input, maxCharsToWrite, output); - } -} - -bool StringTable::DecodeString( char *output, int maxCharsToWrite, MafiaNet::BitStream *input ) -{ - bool hasIndex=false; - RakAssert(maxCharsToWrite>0); - - if (maxCharsToWrite==0) - return false; - if (!input->Read(hasIndex)) - return false; - if (hasIndex==false) - { - StringCompressor::Instance()->DecodeString(output, maxCharsToWrite, input); - } - else - { - StringTableType index; - if (!input->Read(index)) - return false; - if (index >= orderedStringList.Size()) - { -#ifdef _DEBUG - // Critical error - got a string index out of range, which means AddString was called more times on the remote system than on this system. - // All systems must call AddString the same number of types, with the same strings in the same order. - RakAssert(0); -#endif - return false; - } - - strncpy_s(output, maxCharsToWrite, orderedStringList[index].str, maxCharsToWrite); - output[maxCharsToWrite-1]=0; - } - - return true; -} -void StringTable::LogStringNotFound(const char *strName) -{ - (void) strName; - -#ifdef _DEBUG - RAKNET_DEBUG_PRINTF("Efficiency Warning! Unregistered String %s sent to StringTable.\n", strName); -#endif -} diff --git a/vendors/mafianet/Source/src/SuperFastHash.cpp b/vendors/mafianet/Source/src/SuperFastHash.cpp deleted file mode 100644 index 730b25244..000000000 --- a/vendors/mafianet/Source/src/SuperFastHash.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/SuperFastHash.h" -#include "mafianet/NativeTypes.h" -#include - -#if !defined(_WIN32) -#include -#endif -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -#undef get16bits - -#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ - || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) -#define get16bits(d) (*((const uint16_t *) (d))) -#else -#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\ - +(uint32_t)(((const uint8_t *)(d))[0]) ) -#endif - -static const int INCREMENTAL_READ_BLOCK=65536; - -uint32_t SuperFastHash (const char * data, int length) -{ - // All this is necessary or the hash does not match SuperFastHashIncremental - int bytesRemaining=length; - unsigned int lastHash = length; - int offset=0; - while (bytesRemaining>=INCREMENTAL_READ_BLOCK) - { - lastHash=SuperFastHashIncremental (data+offset, INCREMENTAL_READ_BLOCK, lastHash ); - bytesRemaining-=INCREMENTAL_READ_BLOCK; - offset+=INCREMENTAL_READ_BLOCK; - } - if (bytesRemaining>0) - { - lastHash=SuperFastHashIncremental (data+offset, bytesRemaining, lastHash ); - } - return lastHash; - -// return SuperFastHashIncremental(data,len,len); -} -uint32_t SuperFastHashIncremental (const char * data, int len, unsigned int lastHash ) -{ - uint32_t hash = (uint32_t) lastHash; - uint32_t tmp; - int rem; - - if (len <= 0 || data == nullptr) return 0; - - rem = len & 3; - len >>= 2; - - /* Main loop */ - for (;len > 0; len--) { - hash += get16bits (data); - tmp = (get16bits (data+2) << 11) ^ hash; - hash = (hash << 16) ^ tmp; - data += 2*sizeof (uint16_t); - hash += hash >> 11; - } - - /* Handle end cases */ - switch (rem) { - case 3: hash += get16bits (data); - hash ^= hash << 16; - hash ^= data[sizeof (uint16_t)] << 18; - hash += hash >> 11; - break; - case 2: hash += get16bits (data); - hash ^= hash << 11; - hash += hash >> 17; - break; - case 1: hash += *data; - hash ^= hash << 10; - hash += hash >> 1; - } - - /* Force "avalanching" of final 127 bits */ - hash ^= hash << 3; - hash += hash >> 5; - hash ^= hash << 4; - hash += hash >> 17; - hash ^= hash << 25; - hash += hash >> 6; - - return (uint32_t) hash; - -} - -uint32_t SuperFastHashFile (const char * filename) -{ - FILE *fp; - if (fopen_s(&fp, filename, "rb")!=0) - return 0; - uint32_t hash = SuperFastHashFilePtr(fp); - fclose(fp); - return hash; -} - -uint32_t SuperFastHashFilePtr (FILE *fp) -{ - fseek(fp, 0, SEEK_END); - int length = ftell(fp); - fseek(fp, 0, SEEK_SET); - int bytesRemaining=length; - unsigned int lastHash = length; - char readBlock[INCREMENTAL_READ_BLOCK]; - while (bytesRemaining>=(int) sizeof(readBlock)) - { - fread(readBlock, sizeof(readBlock), 1, fp); - lastHash=SuperFastHashIncremental (readBlock, (int) sizeof(readBlock), lastHash ); - bytesRemaining-=(int) sizeof(readBlock); - } - if (bytesRemaining>0) - { - fread(readBlock, bytesRemaining, 1, fp); - lastHash=SuperFastHashIncremental (readBlock, bytesRemaining, lastHash ); - } - return lastHash; -} diff --git a/vendors/mafianet/Source/src/TCPInterface.cpp b/vendors/mafianet/Source/src/TCPInterface.cpp deleted file mode 100644 index eeb61bbe4..000000000 --- a/vendors/mafianet/Source/src/TCPInterface.cpp +++ /dev/null @@ -1,1440 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_TCPInterface==1 - -/// \file -/// \brief A simple TCP based server allowing sends and receives. Can be connected to by a telnet client. -/// - - - -#include "mafianet/TCPInterface.h" -#ifdef _WIN32 - typedef int socklen_t; -#else -#include -#include -#include -#endif -#include -#include "mafianet/assert.h" -#include -#include "mafianet/assert.h" -#include "mafianet/sleep.h" -#include "mafianet/StringCompressor.h" -#include "mafianet/StringTable.h" -#include "mafianet/Itoa.h" -#include "mafianet/SocketLayer.h" -#include "mafianet/SocketDefines.h" -#if (defined(__GNUC__) || defined(__GCCXML__)) && !defined(__WIN32__) -#include -#endif - -#ifdef _DO_PRINTF -#endif - -#ifdef _WIN32 -#include "mafianet/WSAStartupSingleton.h" -#endif -namespace MafiaNet -{ -RAK_THREAD_DECLARATION(UpdateTCPInterfaceLoop); -RAK_THREAD_DECLARATION(ConnectionAttemptLoop); -} -#ifdef _MSC_VER -#pragma warning( push ) -#endif -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(TCPInterface,TCPInterface); - -TCPInterface::TCPInterface() -{ - listenSocket=0; - remoteClients=0; - remoteClientsLength=0; - - StringCompressor::AddReference(); - MafiaNet::StringTable::AddReference(); - -#if OPEN_SSL_CLIENT_SUPPORT==1 - ctx=0; - meth=0; -#endif - -#ifdef _WIN32 - WSAStartupSingleton::AddRef(); -#endif -} -TCPInterface::~TCPInterface() -{ - Stop(); -#ifdef _WIN32 - WSAStartupSingleton::Deref(); -#endif - - MafiaNet::OP_DELETE_ARRAY(remoteClients,_FILE_AND_LINE_); - - StringCompressor::RemoveReference(); - MafiaNet::StringTable::RemoveReference(); -} - -bool TCPInterface::CreateListenSocket(unsigned short port, unsigned short maxIncomingConnections, unsigned short socketFamily, const char *bindAddress) -{ - (void) maxIncomingConnections; - (void) socketFamily; -#if RAKNET_SUPPORT_IPV6!=1 - listenSocket = socket__(AF_INET, SOCK_STREAM, 0); - if ((int)listenSocket ==-1) - return false; - - struct sockaddr_in serverAddress; - memset(&serverAddress,0,sizeof(sockaddr_in)); - serverAddress.sin_family = AF_INET; - if ( bindAddress && bindAddress[0] ) - { - - - - - - inet_pton(AF_INET, bindAddress, &serverAddress.sin_addr.s_addr); - - } - else - serverAddress.sin_addr.s_addr = INADDR_ANY; - - serverAddress.sin_port = htons(port); - - SocketLayer::SetSocketOptions(listenSocket, false, false); - - if (bind__(listenSocket,(struct sockaddr *) &serverAddress,sizeof(serverAddress)) < 0) - return false; - - listen__(listenSocket, maxIncomingConnections); -#else - (void)bindAddress; - struct addrinfo hints; - memset(&hints, 0, sizeof (addrinfo)); // make sure the struct is empty - hints.ai_family = socketFamily; // don't care IPv4 or IPv6 - hints.ai_socktype = SOCK_STREAM; // TCP sockets - hints.ai_flags = AI_PASSIVE; // fill in my IP for me - struct addrinfo *servinfo=0, *aip; // will point to the results - char portStr[32]; - Itoa(port,portStr,10); - - getaddrinfo(0, portStr, &hints, &servinfo); - for (aip = servinfo; aip != nullptr; aip = aip->ai_next) - { - // Open socket. The address type depends on what - // getaddrinfo() gave us. - listenSocket = socket__(aip->ai_family, aip->ai_socktype, aip->ai_protocol); - if (listenSocket != 0) - { - int ret = bind__( listenSocket, aip->ai_addr, (int) aip->ai_addrlen ); - if (ret>=0) - { - break; - } - else - { - closesocket__(listenSocket); - listenSocket=0; - } - } - } - - if (listenSocket==0) - return false; - - SocketLayer::SetSocketOptions(listenSocket, false, false); - - listen__(listenSocket, maxIncomingConnections); -#endif // #if RAKNET_SUPPORT_IPV6!=1 - - return true; -} - -bool TCPInterface::Start(unsigned short port, unsigned short maxIncomingConnections, unsigned short maxConnections, int _threadPriority, unsigned short socketFamily, const char *bindAddress) -{ -#ifdef __native_client__ - return false; -#else - (void) socketFamily; - - if (isStarted.GetValue()>0) - return false; - - threadPriority=_threadPriority; - - if (threadPriority==-99999) - { - - -#if defined(_WIN32) - threadPriority=0; - - -#else - threadPriority=1000; -#endif - } - - isStarted.Increment(); - if (maxConnections==0) - maxConnections=maxIncomingConnections; - if (maxConnections==0) - maxConnections=1; - remoteClientsLength=maxConnections; - remoteClients= MafiaNet::OP_NEW_ARRAY(maxConnections,_FILE_AND_LINE_); - - - listenSocket=0; - if (maxIncomingConnections>0) - { - CreateListenSocket(port, maxIncomingConnections, socketFamily, bindAddress); - } - - - // Start the update thread - int errorCode; - - - - - - errorCode = MafiaNet::RakThread::Create(UpdateTCPInterfaceLoop, this, threadPriority); - - - if (errorCode!=0) - return false; - - while (threadRunning.GetValue()==0) - RakSleep(0); - - unsigned int i; - for (i=0; i < messageHandlerList.Size(); i++) - messageHandlerList[i]->OnRakPeerStartup(); - - return true; -#endif // __native_client__ -} -void TCPInterface::Stop(void) -{ - unsigned int i; - for (i=0; i < messageHandlerList.Size(); i++) - messageHandlerList[i]->OnRakPeerShutdown(); - -#ifndef __native_client__ - if (isStarted.GetValue()==0) - return; - -#if OPEN_SSL_CLIENT_SUPPORT==1 - for (i=0; i < remoteClientsLength; i++) - remoteClients[i].DisconnectSSL(); -#endif - - isStarted.Decrement(); - - if (listenSocket!=0) - { -#ifdef _WIN32 - shutdown__(listenSocket, SD_BOTH); - -#else - shutdown__(listenSocket, SHUT_RDWR); -#endif - closesocket__(listenSocket); - } - - // Abort waiting connect calls - blockingSocketListMutex.Lock(); - for (i=0; i < blockingSocketList.Size(); i++) - { - closesocket__(blockingSocketList[i]); - } - blockingSocketListMutex.Unlock(); - - // Wait for the thread to stop - while ( threadRunning.GetValue()>0 ) - RakSleep(15); - - RakSleep(100); - - listenSocket=0; - - // Stuff from here on to the end of the function is not threadsafe - for (i=0; i < remoteClientsLength; i++) - { - closesocket__(remoteClients[i].socket); -#if OPEN_SSL_CLIENT_SUPPORT==1 - remoteClients[i].FreeSSL(); -#endif - } - remoteClientsLength=0; - MafiaNet::OP_DELETE_ARRAY(remoteClients,_FILE_AND_LINE_); - remoteClients=0; - - // #low review whether we'd rather use PopInaccurate() here (i.e. check whether related threads accessing the queue terminated already) - // consider even adding a dtor to Packet which would then clear its data (at this point drop this explicit packet deallocation here) - MafiaNet::Packet* packet = incomingMessages.Pop(); - while (packet != nullptr) { - DeallocatePacket(packet); - packet = incomingMessages.Pop(); - } - incomingMessages.Clear(_FILE_AND_LINE_); - newIncomingConnections.Clear(_FILE_AND_LINE_); - newRemoteClients.Clear(_FILE_AND_LINE_); - lostConnections.Clear(_FILE_AND_LINE_); - requestedCloseConnections.Clear(_FILE_AND_LINE_); - failedConnectionAttempts.Clear(_FILE_AND_LINE_); - completedConnectionAttempts.Clear(_FILE_AND_LINE_); - failedConnectionAttempts.Clear(_FILE_AND_LINE_); - for (i=0; i < headPush.Size(); i++) - DeallocatePacket(headPush[i]); - headPush.Clear(_FILE_AND_LINE_); - for (i=0; i < tailPush.Size(); i++) - DeallocatePacket(tailPush[i]); - tailPush.Clear(_FILE_AND_LINE_); - -#if OPEN_SSL_CLIENT_SUPPORT==1 - SSL_CTX_free (ctx); - startSSL.Clear(_FILE_AND_LINE_); - activeSSLConnections.Clear(false, _FILE_AND_LINE_); -#endif - - - - - -#endif // __native_client__ -} -SystemAddress TCPInterface::Connect(const char* host, unsigned short remotePort, bool block, unsigned short socketFamily, const char *bindAddress) -{ - if (threadRunning.GetValue()==0) - return UNASSIGNED_SYSTEM_ADDRESS; - - int newRemoteClientIndex=-1; - for (newRemoteClientIndex=0; newRemoteClientIndex < remoteClientsLength; newRemoteClientIndex++) - { - remoteClients[newRemoteClientIndex].isActiveMutex.Lock(); - if (remoteClients[newRemoteClientIndex].isActive==false) - { - remoteClients[newRemoteClientIndex].SetActive(true); - remoteClients[newRemoteClientIndex].isActiveMutex.Unlock(); - break; - } - remoteClients[newRemoteClientIndex].isActiveMutex.Unlock(); - } - if (newRemoteClientIndex==-1) - return UNASSIGNED_SYSTEM_ADDRESS; - - if (block) - { - SystemAddress systemAddress; - // #med - call should be changed to ...FromString(host, '\0') so to not try to extract an optional port (which is overwritten with the removePort directly afterwards) - systemAddress.FromString(host); - systemAddress.SetPortHostOrder(remotePort); - systemAddress.systemIndex=(SystemIndex) newRemoteClientIndex; - char buffout[128]; - systemAddress.ToString(false,buffout, static_cast(128)); - - __TCPSOCKET__ sockfd = SocketConnect(buffout, remotePort, socketFamily, bindAddress); - if (sockfd==0) - { - remoteClients[newRemoteClientIndex].isActiveMutex.Lock(); - remoteClients[newRemoteClientIndex].SetActive(false); - remoteClients[newRemoteClientIndex].isActiveMutex.Unlock(); - - failedConnectionAttemptMutex.Lock(); - failedConnectionAttempts.Push(systemAddress, _FILE_AND_LINE_ ); - failedConnectionAttemptMutex.Unlock(); - - return UNASSIGNED_SYSTEM_ADDRESS; - } - - remoteClients[newRemoteClientIndex].socket=sockfd; - remoteClients[newRemoteClientIndex].systemAddress=systemAddress; - - completedConnectionAttemptMutex.Lock(); - completedConnectionAttempts.Push(remoteClients[newRemoteClientIndex].systemAddress, _FILE_AND_LINE_ ); - completedConnectionAttemptMutex.Unlock(); - - return remoteClients[newRemoteClientIndex].systemAddress; - } - else - { - ThisPtrPlusSysAddr *s = MafiaNet::OP_NEW( _FILE_AND_LINE_ ); - s->systemAddress.FromStringExplicitPort(host,remotePort); - s->systemAddress.systemIndex=(SystemIndex) newRemoteClientIndex; - if (bindAddress) - strcpy_s(s->bindAddress, bindAddress); - else - s->bindAddress[0]=0; - s->tcpInterface=this; - s->socketFamily=socketFamily; - - // Start the connection thread - int errorCode; - - - - - errorCode = MafiaNet::RakThread::Create(ConnectionAttemptLoop, s, threadPriority); - - if (errorCode!=0) - { - MafiaNet::OP_DELETE(s, _FILE_AND_LINE_); - failedConnectionAttempts.Push(s->systemAddress, _FILE_AND_LINE_ ); - } - return UNASSIGNED_SYSTEM_ADDRESS; - } -} -#if OPEN_SSL_CLIENT_SUPPORT==1 -void TCPInterface::StartSSLClient(SystemAddress systemAddress) -{ - if (ctx==0) - { - sharedSslMutex.Lock(); - meth = TLS_client_method(); - ctx = SSL_CTX_new (meth); - RakAssert(ctx!=0); - sharedSslMutex.Unlock(); - } - - SystemAddress *id = startSSL.Allocate( _FILE_AND_LINE_ ); - *id=systemAddress; - startSSL.Push(id); - unsigned index = activeSSLConnections.GetIndexOf(systemAddress); - if (index==(unsigned)-1) - activeSSLConnections.Insert(systemAddress,_FILE_AND_LINE_); -} -bool TCPInterface::IsSSLActive(SystemAddress systemAddress) -{ - return activeSSLConnections.GetIndexOf(systemAddress)!=-1; -} -#endif -void TCPInterface::Send( const char *data, unsigned length, const SystemAddress &systemAddress, bool broadcast ) -{ - SendList( &data, &length, 1, systemAddress,broadcast ); -} -bool TCPInterface::SendList( const char **data, const unsigned int *lengths, const int numParameters, const SystemAddress &systemAddress, bool broadcast ) -{ - if (isStarted.GetValue()==0) - return false; - if (data==0) - return false; - if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS && broadcast==false) - return false; - unsigned int totalLength=0; - int i; - for (i=0; i < numParameters; i++) - { - if (lengths[i]>0) - totalLength+=lengths[i]; - } - if (totalLength==0) - return false; - - if (broadcast) - { - // Send to all, possible exception system - for (i=0; i < remoteClientsLength; i++) - { - if (remoteClients[i].systemAddress!=systemAddress) - { - remoteClients[i].SendOrBuffer(data, lengths, numParameters); - } - } - } - else - { - // Send to this player - if (systemAddress.systemIndexUpdate(); - - Packet* outgoingPacket = ReceiveInt(); - - if (outgoingPacket) - { - PluginReceiveResult pluginResult; - for (i=0; i < messageHandlerList.Size(); i++) - { - pluginResult=messageHandlerList[i]->OnReceive(outgoingPacket); - if (pluginResult==RR_STOP_PROCESSING_AND_DEALLOCATE) - { - DeallocatePacket( outgoingPacket ); - outgoingPacket=0; // Will do the loop again and get another packet - break; // break out of the enclosing for - } - else if (pluginResult==RR_STOP_PROCESSING) - { - outgoingPacket=0; - break; - } - } - } - - - return outgoingPacket; -} -Packet* TCPInterface::ReceiveInt( void ) -{ - if (isStarted.GetValue()==0) - return 0; - if (headPush.IsEmpty()==false) - return headPush.Pop(); - Packet *p = incomingMessages.PopInaccurate(); - if (p) - return p; - if (tailPush.IsEmpty()==false) - return tailPush.Pop(); - return 0; -} - - -void TCPInterface::AttachPlugin( PluginInterface2 *plugin ) -{ - if (messageHandlerList.GetIndexOf(plugin)==MAX_UNSIGNED_LONG) - { - messageHandlerList.Insert(plugin, _FILE_AND_LINE_); - plugin->SetTCPInterface(this); - plugin->OnAttach(); - } -} -void TCPInterface::DetachPlugin( PluginInterface2 *plugin ) -{ - if (plugin==0) - return; - - unsigned int index; - index = messageHandlerList.GetIndexOf(plugin); - if (index!=MAX_UNSIGNED_LONG) - { - messageHandlerList[index]->OnDetach(); - // Unordered list so delete from end for speed - messageHandlerList[index]=messageHandlerList[messageHandlerList.Size()-1]; - messageHandlerList.RemoveFromEnd(); - plugin->SetTCPInterface(0); - } -} -void TCPInterface::CloseConnection( SystemAddress systemAddress ) -{ - if (isStarted.GetValue()==0) - return; - if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS) - return; - - unsigned int i; - for (i=0; i < messageHandlerList.Size(); i++) - messageHandlerList[i]->OnClosedConnection(systemAddress, UNASSIGNED_RAKNET_GUID, LCR_CLOSED_BY_USER); - - if (systemAddress.systemIndexdeleteData) - { - rakFree_Ex(packet->data, _FILE_AND_LINE_ ); - incomingMessages.Deallocate(packet, _FILE_AND_LINE_); - } - else - { - // Came from userspace AllocatePacket - rakFree_Ex(packet->data, _FILE_AND_LINE_ ); - MafiaNet::OP_DELETE(packet, _FILE_AND_LINE_); - } -} -Packet* TCPInterface::AllocatePacket(unsigned dataSize) -{ - Packet*p = MafiaNet::OP_NEW(_FILE_AND_LINE_); - p->data=(unsigned char*) rakMalloc_Ex(dataSize,_FILE_AND_LINE_); - p->length=dataSize; - p->bitSize=BYTES_TO_BITS(dataSize); - p->deleteData=false; - p->guid=UNASSIGNED_RAKNET_GUID; - p->systemAddress=UNASSIGNED_SYSTEM_ADDRESS; - p->systemAddress.systemIndex=(SystemIndex)-1; - return p; -} -void TCPInterface::PushBackPacket( Packet *packet, bool pushAtHead ) -{ - if (pushAtHead) - headPush.Push(packet, _FILE_AND_LINE_ ); - else - tailPush.Push(packet, _FILE_AND_LINE_ ); -} -bool TCPInterface::WasStarted(void) const -{ - return threadRunning.GetValue()>0; -} -SystemAddress TCPInterface::HasCompletedConnectionAttempt(void) -{ - SystemAddress sysAddr=UNASSIGNED_SYSTEM_ADDRESS; - completedConnectionAttemptMutex.Lock(); - if (completedConnectionAttempts.IsEmpty()==false) - sysAddr=completedConnectionAttempts.Pop(); - completedConnectionAttemptMutex.Unlock(); - - if (sysAddr!=UNASSIGNED_SYSTEM_ADDRESS) - { - unsigned int i; - for (i=0; i < messageHandlerList.Size(); i++) - messageHandlerList[i]->OnNewConnection(sysAddr, UNASSIGNED_RAKNET_GUID, true); - } - - return sysAddr; -} -SystemAddress TCPInterface::HasFailedConnectionAttempt(void) -{ - SystemAddress sysAddr=UNASSIGNED_SYSTEM_ADDRESS; - failedConnectionAttemptMutex.Lock(); - if (failedConnectionAttempts.IsEmpty()==false) - sysAddr=failedConnectionAttempts.Pop(); - failedConnectionAttemptMutex.Unlock(); - - if (sysAddr!=UNASSIGNED_SYSTEM_ADDRESS) - { - unsigned int i; - for (i=0; i < messageHandlerList.Size(); i++) - { - Packet p; - p.systemAddress=sysAddr; - p.data=0; - p.length=0; - p.bitSize=0; - messageHandlerList[i]->OnFailedConnectionAttempt(&p, FCAR_CONNECTION_ATTEMPT_FAILED); - } - } - - return sysAddr; -} -SystemAddress TCPInterface::HasNewIncomingConnection(void) -{ - SystemAddress *out, out2; - out = newIncomingConnections.PopInaccurate(); - if (out) - { - out2=*out; - newIncomingConnections.Deallocate(out, _FILE_AND_LINE_); - - unsigned int i; - for (i=0; i < messageHandlerList.Size(); i++) - messageHandlerList[i]->OnNewConnection(out2, UNASSIGNED_RAKNET_GUID, true); - - return *out; - } - else - { - return UNASSIGNED_SYSTEM_ADDRESS; - } -} -SystemAddress TCPInterface::HasLostConnection(void) -{ - SystemAddress *out, out2; - out = lostConnections.PopInaccurate(); - if (out) - { - out2=*out; - lostConnections.Deallocate(out, _FILE_AND_LINE_); - - unsigned int i; - for (i=0; i < messageHandlerList.Size(); i++) - messageHandlerList[i]->OnClosedConnection(out2, UNASSIGNED_RAKNET_GUID, LCR_DISCONNECTION_NOTIFICATION); - - return *out; - } - else - { - return UNASSIGNED_SYSTEM_ADDRESS; - } -} -void TCPInterface::GetConnectionList( SystemAddress *remoteSystems, unsigned short *numberOfSystems ) const -{ - unsigned short systemCount=0; - unsigned short maxToWrite=*numberOfSystems; - for (int i=0; i < remoteClientsLength; i++) - { - if (remoteClients[i].isActive) - { - if (systemCount < maxToWrite) - remoteSystems[systemCount]=remoteClients[i].systemAddress; - systemCount++; - } - } - *numberOfSystems=systemCount; -} -unsigned short TCPInterface::GetConnectionCount(void) const -{ - unsigned short systemCount=0; - for (int i=0; i < remoteClientsLength; i++) - { - if (remoteClients[i].isActive) - systemCount++; - } - return systemCount; -} - -unsigned int TCPInterface::GetOutgoingDataBufferSize(SystemAddress systemAddress) const -{ - unsigned bytesWritten=0; - if (systemAddress.systemIndexai_family == AF_INET) { - break; // found an IPv4 address - } - curAddress = curAddress->ai_next; - } - - if (curAddress == nullptr) - return 0; - - if (err != 0) - return 0; - - - __TCPSOCKET__ sockfd = socket__(AF_INET, SOCK_STREAM, 0); - if (sockfd < 0) - return 0; - - memset(&serverAddress, 0, sizeof(serverAddress)); - serverAddress.sin_family = AF_INET; - serverAddress.sin_port = htons( remotePort ); - - - if ( bindAddress && bindAddress[0] ) - { - - - - - - inet_pton(AF_INET, bindAddress, &serverAddress.sin_addr.s_addr); - - } - else - serverAddress.sin_addr.s_addr = INADDR_ANY; - - int sock_opt=1024*256; - setsockopt__(sockfd, SOL_SOCKET, SO_RCVBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) ); - - serverAddress.sin_addr = ((struct sockaddr_in *)curAddress->ai_addr)->sin_addr; - - - - - - - - - - - blockingSocketListMutex.Lock(); - blockingSocketList.Insert(sockfd, _FILE_AND_LINE_); - blockingSocketListMutex.Unlock(); - - // This is blocking - connectResult = connect__( sockfd, ( struct sockaddr * ) &serverAddress, sizeof( struct sockaddr ) ); - -#else - - (void)bindAddress; - struct addrinfo hints, *res; - __TCPSOCKET__ sockfd; - memset(&hints, 0, sizeof hints); - hints.ai_family = socketFamily; - hints.ai_socktype = SOCK_STREAM; - char portStr[32]; - Itoa(remotePort,portStr,10); - getaddrinfo(host, portStr, &hints, &res); - sockfd = socket__(res->ai_family, res->ai_socktype, res->ai_protocol); - blockingSocketListMutex.Lock(); - blockingSocketList.Insert(sockfd, _FILE_AND_LINE_); - blockingSocketListMutex.Unlock(); - // #low - review usage of static cast here - connectResult=connect__(sockfd, res->ai_addr, static_cast(res->ai_addrlen)); - freeaddrinfo(res); // free the linked-list - -#endif // #if RAKNET_SUPPORT_IPV6!=1 - - if (connectResult==-1) - { - unsigned sockfdIndex; - blockingSocketListMutex.Lock(); - sockfdIndex=blockingSocketList.GetIndexOf(sockfd); - if (sockfdIndex!=(unsigned)-1) - blockingSocketList.RemoveAtIndexFast(sockfdIndex); - blockingSocketListMutex.Unlock(); - - closesocket__(sockfd); - return 0; - } - - return sockfd; -#endif // __native_client__ -} - -RAK_THREAD_DECLARATION(MafiaNet::ConnectionAttemptLoop) -{ - - - - TCPInterface::ThisPtrPlusSysAddr *s = (TCPInterface::ThisPtrPlusSysAddr *) arguments; - - - - SystemAddress systemAddress = s->systemAddress; - TCPInterface *tcpInterface = s->tcpInterface; - int newRemoteClientIndex=systemAddress.systemIndex; - unsigned short socketFamily = s->socketFamily; - MafiaNet::OP_DELETE(s, _FILE_AND_LINE_); - - char str1[64]; - systemAddress.ToString(false, str1, static_cast(64)); - __TCPSOCKET__ sockfd = tcpInterface->SocketConnect(str1, systemAddress.GetPort(), socketFamily, s->bindAddress); - if (sockfd==0) - { - tcpInterface->remoteClients[newRemoteClientIndex].isActiveMutex.Lock(); - tcpInterface->remoteClients[newRemoteClientIndex].SetActive(false); - tcpInterface->remoteClients[newRemoteClientIndex].isActiveMutex.Unlock(); - - tcpInterface->failedConnectionAttemptMutex.Lock(); - tcpInterface->failedConnectionAttempts.Push(systemAddress, _FILE_AND_LINE_ ); - tcpInterface->failedConnectionAttemptMutex.Unlock(); - return 0; - } - - tcpInterface->remoteClients[newRemoteClientIndex].socket=sockfd; - tcpInterface->remoteClients[newRemoteClientIndex].systemAddress=systemAddress; - - // Notify user that the connection attempt has completed. - if (tcpInterface->threadRunning.GetValue()>0) - { - tcpInterface->completedConnectionAttemptMutex.Lock(); - tcpInterface->completedConnectionAttempts.Push(systemAddress, _FILE_AND_LINE_ ); - tcpInterface->completedConnectionAttemptMutex.Unlock(); - } - - - - - return 0; - -} - -RAK_THREAD_DECLARATION(MafiaNet::UpdateTCPInterfaceLoop) -{ - - - - TCPInterface * sts = ( TCPInterface * ) arguments; - - -// const int BUFF_SIZE=8096; - const unsigned int BUFF_SIZE=1048576; - //char data[ BUFF_SIZE ]; - char * data = (char*) rakMalloc_Ex(BUFF_SIZE,_FILE_AND_LINE_); - Packet *incomingMessage; - fd_set readFD, exceptionFD, writeFD; - sts->threadRunning.Increment(); - -#if RAKNET_SUPPORT_IPV6!=1 - sockaddr_in sockAddr; - int sockAddrSize = sizeof(sockAddr); -#else - struct sockaddr_storage sockAddr; - socklen_t sockAddrSize = sizeof(sockAddr); -#endif - - int len; - __TCPSOCKET__ newSock; - int selectResult; - - - timeval tv; - tv.tv_sec=0; - tv.tv_usec=30000; - - - while (sts->isStarted.GetValue()>0) - { -#if OPEN_SSL_CLIENT_SUPPORT==1 - SystemAddress *sslSystemAddress; - sslSystemAddress = sts->startSSL.PopInaccurate(); - if (sslSystemAddress) - { - if (sslSystemAddress->systemIndex>=0 && - sslSystemAddress->systemIndexremoteClientsLength && - sts->remoteClients[sslSystemAddress->systemIndex].systemAddress==*sslSystemAddress) - { - sts->remoteClients[sslSystemAddress->systemIndex].InitSSL(sts->ctx,sts->meth); - } - else - { - for (int i=0; i < sts->remoteClientsLength; i++) - { - sts->remoteClients[i].isActiveMutex.Lock(); - if (sts->remoteClients[i].isActive && sts->remoteClients[i].systemAddress==*sslSystemAddress) - { - if (sts->remoteClients[i].ssl==0) - sts->remoteClients[i].InitSSL(sts->ctx,sts->meth); - } - sts->remoteClients[i].isActiveMutex.Unlock(); - } - } - sts->startSSL.Deallocate(sslSystemAddress,_FILE_AND_LINE_); - } -#endif - - - __TCPSOCKET__ largestDescriptor=0; // see select__()'s first parameter's documentation under linux - - - // Linux' select__() implementation changes the timeout - - tv.tv_sec=0; - tv.tv_usec=30000; - - -#ifdef _MSC_VER -#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant -#endif - for(;;) - { - // Reset readFD, writeFD, and exceptionFD since select seems to clear it - FD_ZERO(&readFD); - FD_ZERO(&exceptionFD); - FD_ZERO(&writeFD); - largestDescriptor=0; - if (sts->listenSocket!=0) - { - FD_SET(sts->listenSocket, &readFD); - FD_SET(sts->listenSocket, &exceptionFD); - largestDescriptor = sts->listenSocket; // @see largestDescriptor def - } - - unsigned i; - for (i=0; i < sts->remoteClientsLength; i++) - { - sts->remoteClients[i].isActiveMutex.Lock(); - if (sts->remoteClients[i].isActive) - { - // calling FD_ISSET with -1 as socket (that’s what 0 is set to) produces a bus error under Linux 64-Bit - __TCPSOCKET__ socketCopy = sts->remoteClients[i].socket; - if (socketCopy != 0) - { - FD_SET(socketCopy, &readFD); - FD_SET(socketCopy, &exceptionFD); - if (sts->remoteClients[i].outgoingData.GetBytesWritten()>0) - FD_SET(socketCopy, &writeFD); - if(socketCopy > largestDescriptor) // @see largestDescriptorDef - largestDescriptor = socketCopy; - } - } - sts->remoteClients[i].isActiveMutex.Unlock(); - } - -#ifdef _MSC_VER -#pragma warning( disable : 4244 ) // warning C4127: conditional expression is constant -#endif - - - selectResult=(int) select__(largestDescriptor+1, &readFD, &writeFD, &exceptionFD, &tv); - - - - - if (selectResult<=0) - break; - - if (sts->listenSocket!=0 && FD_ISSET(sts->listenSocket, &readFD)) - { - newSock = accept__(sts->listenSocket, (sockaddr*)&sockAddr, (socklen_t*)&sockAddrSize); - - if (newSock != 0) - { - int newRemoteClientIndex=-1; - for (newRemoteClientIndex=0; newRemoteClientIndex < sts->remoteClientsLength; newRemoteClientIndex++) - { - sts->remoteClients[newRemoteClientIndex].isActiveMutex.Lock(); - if (sts->remoteClients[newRemoteClientIndex].isActive==false) - { - sts->remoteClients[newRemoteClientIndex].socket=newSock; - -#if RAKNET_SUPPORT_IPV6!=1 - sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr4.sin_addr.s_addr=sockAddr.sin_addr.s_addr; - sts->remoteClients[newRemoteClientIndex].systemAddress.SetPortNetworkOrder( sockAddr.sin_port); - sts->remoteClients[newRemoteClientIndex].systemAddress.systemIndex=newRemoteClientIndex; -#else - if (sockAddr.ss_family==AF_INET) - { - memcpy(&sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr4,(sockaddr_in *)&sockAddr,sizeof(sockaddr_in)); - // sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr4.sin_port=ntohs( sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr4.sin_port ); - } - else - { - memcpy(&sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr6,(sockaddr_in6 *)&sockAddr,sizeof(sockaddr_in6)); - // sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr6.sin6_port=ntohs( sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr6.sin6_port ); - } - -#endif // #if RAKNET_SUPPORT_IPV6!=1 - sts->remoteClients[newRemoteClientIndex].SetActive(true); - sts->remoteClients[newRemoteClientIndex].isActiveMutex.Unlock(); - - - SystemAddress *newConnectionSystemAddress=sts->newIncomingConnections.Allocate( _FILE_AND_LINE_ ); - *newConnectionSystemAddress=sts->remoteClients[newRemoteClientIndex].systemAddress; - sts->newIncomingConnections.Push(newConnectionSystemAddress); - - break; - } - sts->remoteClients[newRemoteClientIndex].isActiveMutex.Unlock(); - } - if (newRemoteClientIndex==-1) - { - closesocket__(sts->listenSocket); - } - } - else - { -#ifdef _DO_PRINTF - RAKNET_DEBUG_PRINTF("Error: connection failed\n"); -#endif - } - } - else if (sts->listenSocket!=0 && FD_ISSET(sts->listenSocket, &exceptionFD)) - { -#ifdef _DO_PRINTF - int err; - int errlen = sizeof(err); - getsockopt__(sts->listenSocket, SOL_SOCKET, SO_ERROR,(char*)&err, &errlen); - RAKNET_DEBUG_PRINTF("Socket error %s on listening socket\n", err); -#endif - } - - { - i=0; - while (i < sts->remoteClientsLength) - { - if (sts->remoteClients[i].isActive==false) - { - i++; - continue; - } - // calling FD_ISSET with -1 as socket (that’s what 0 is set to) produces a bus error under Linux 64-Bit - __TCPSOCKET__ socketCopy = sts->remoteClients[i].socket; - if (socketCopy == 0) - { - i++; - continue; - } - - if (FD_ISSET(socketCopy, &exceptionFD)) - { -// #ifdef _DO_PRINTF -// if (sts->listenSocket!=-1) -// { -// int err; -// int errlen = sizeof(err); -// getsockopt__(sts->listenSocket, SOL_SOCKET, SO_ERROR,(char*)&err, &errlen); -// in_addr in; -// in.s_addr = sts->remoteClients[i].systemAddress.binaryAddress; -// char ip[65]; -// inet_ntop(sts->remoteClients[i].systemAddress.address.addr4.sin_family, &in, ip, 65); -// RAKNET_DEBUG_PRINTF("Socket error %i on %s:%i\n", err,ip, sts->remoteClients[i].systemAddress.GetPort() ); -// } -// -// #endif - // Connection lost abruptly - SystemAddress *lostConnectionSystemAddress=sts->lostConnections.Allocate( _FILE_AND_LINE_ ); - *lostConnectionSystemAddress=sts->remoteClients[i].systemAddress; - sts->lostConnections.Push(lostConnectionSystemAddress); - sts->remoteClients[i].isActiveMutex.Lock(); - sts->remoteClients[i].SetActive(false); - sts->remoteClients[i].isActiveMutex.Unlock(); - } - else - { - if (FD_ISSET(socketCopy, &readFD)) - { - // if recv returns 0 this was a graceful close - len = sts->remoteClients[i].Recv(data,BUFF_SIZE); - - - // removeme -// data[len]=0; -// printf(data); - - if (len>0) - { - incomingMessage=sts->incomingMessages.Allocate( _FILE_AND_LINE_ ); - incomingMessage->data = (unsigned char*) rakMalloc_Ex( len+1, _FILE_AND_LINE_ ); - memcpy(incomingMessage->data, data, len); - incomingMessage->data[len]=0; // Null terminate this so we can print it out as regular strings. This is different from RakNet which does not do this. - // printf("RECV: %s\n",incomingMessage->data); - /* - if (1) - { - static FILE *fp=0; - if (fp==0) - { - fopen_s(&fp, "tcpRcv.txt", "wb"); - } - fwrite(data,1,len,fp); - } - */ - incomingMessage->length=len; - incomingMessage->deleteData=true; // actually means came from SPSC, rather than AllocatePacket - incomingMessage->systemAddress=sts->remoteClients[i].systemAddress; - sts->incomingMessages.Push(incomingMessage); - } - else - { - // Connection lost gracefully - SystemAddress *lostConnectionSystemAddress=sts->lostConnections.Allocate( _FILE_AND_LINE_ ); - *lostConnectionSystemAddress=sts->remoteClients[i].systemAddress; - sts->lostConnections.Push(lostConnectionSystemAddress); - sts->remoteClients[i].isActiveMutex.Lock(); - sts->remoteClients[i].SetActive(false); - sts->remoteClients[i].isActiveMutex.Unlock(); - continue; - } - } - if (FD_ISSET(socketCopy, &writeFD)) - { - RemoteClient *rc = &sts->remoteClients[i]; - unsigned int bytesInBuffer; - int bytesAvailable; - int bytesSent; - rc->outgoingDataMutex.Lock(); - bytesInBuffer=rc->outgoingData.GetBytesWritten(); - if (bytesInBuffer>0) - { - unsigned int contiguousLength; - char* contiguousBytesPointer = rc->outgoingData.PeekContiguousBytes(&contiguousLength); - if (contiguousLength < (unsigned int) BUFF_SIZE && contiguousLength BUFF_SIZE) - bytesAvailable=BUFF_SIZE; - else - bytesAvailable=bytesInBuffer; - rc->outgoingData.ReadBytes(data,bytesAvailable,true); - bytesSent=rc->Send(data,bytesAvailable); - } - else - { - bytesSent=rc->Send(contiguousBytesPointer,contiguousLength); - } - - if (bytesSent>0) - rc->outgoingData.IncrementReadOffset(bytesSent); - bytesInBuffer=rc->outgoingData.GetBytesWritten(); - } - rc->outgoingDataMutex.Unlock(); - } - - i++; // Nothing deleted so increment the index - } - } - } - } - - // Sleep 0 on Linux monopolizes the CPU - RakSleep(30); - } - sts->threadRunning.Decrement(); - - rakFree_Ex(data,_FILE_AND_LINE_); - - - - - return 0; - -} - -void RemoteClient::SetActive(bool a) -{ - if (isActive != a) - { - isActive=a; - Reset(); - if (isActive==false && socket!=0) - { - closesocket__(socket); - socket=0; - } - } -} -void RemoteClient::SendOrBuffer(const char **data, const unsigned int *lengths, const int numParameters) -{ - // True can save memory and buffer copies, but gives worse performance overall - // Do not use true for the XBOX, as it just locks up - const bool ALLOW_SEND_FROM_USER_THREAD=false; - - int parameterIndex; - if (isActive==false) - return; - parameterIndex=0; - for (; parameterIndex < numParameters; parameterIndex++) - { - outgoingDataMutex.Lock(); - if (ALLOW_SEND_FROM_USER_THREAD && outgoingData.GetBytesWritten()==0) - { - outgoingDataMutex.Unlock(); - int bytesSent = Send(data[parameterIndex],lengths[parameterIndex]); - if (bytesSent<(int) lengths[parameterIndex]) - { - // Push remainder - outgoingDataMutex.Lock(); - outgoingData.WriteBytes(data[parameterIndex]+bytesSent,lengths[parameterIndex]-bytesSent,_FILE_AND_LINE_); - outgoingDataMutex.Unlock(); - } - } - else - { - outgoingData.WriteBytes(data[parameterIndex],lengths[parameterIndex],_FILE_AND_LINE_); - outgoingDataMutex.Unlock(); - } - } -} -#if OPEN_SSL_CLIENT_SUPPORT==1 -bool RemoteClient::InitSSL(SSL_CTX* ctx, SSL_METHOD *meth) -{ - (void) meth; - - ssl = SSL_new (ctx); - RakAssert(ssl); - int res; - res = SSL_set_fd (ssl, socket); - if (res!=1) - { - printf("SSL_set_fd error: %s\n", ERR_reason_error_string(ERR_get_error())); - SSL_free(ssl); - ssl=0; - return false; - } - RakAssert(res==1); - res = SSL_connect (ssl); - if (res<0) - { - unsigned long err = ERR_get_error(); - printf("SSL_connect error: %s\n", ERR_reason_error_string(err)); - SSL_free(ssl); - ssl=0; - return false; - } - else if (res==0) - { - // The TLS/SSL handshake was not successful but was shut down controlled and by the specifications of the TLS/SSL protocol. Call SSL_get_error() with the return value ret to find out the reason. - int err = SSL_get_error(ssl, res); - switch (err) - { - case SSL_ERROR_NONE: - printf("SSL_ERROR_NONE\n"); - break; - case SSL_ERROR_ZERO_RETURN: - printf("SSL_ERROR_ZERO_RETURN\n"); - break; - case SSL_ERROR_WANT_READ: - printf("SSL_ERROR_WANT_READ\n"); - break; - case SSL_ERROR_WANT_WRITE: - printf("SSL_ERROR_WANT_WRITE\n"); - break; - case SSL_ERROR_WANT_CONNECT: - printf("SSL_ERROR_WANT_CONNECT\n"); - break; - case SSL_ERROR_WANT_ACCEPT: - printf("SSL_ERROR_WANT_ACCEPT\n"); - break; - case SSL_ERROR_WANT_X509_LOOKUP: - printf("SSL_ERROR_WANT_X509_LOOKUP\n"); - break; - case SSL_ERROR_SYSCALL: - { - // http://www.openssl.org/docs/ssl/SSL_get_error.html - char buff[1024]; - unsigned long ege = ERR_get_error(); - if (ege==0 && res==0) - printf("SSL_ERROR_SYSCALL EOF in violation of the protocol\n"); - else if (ege==0 && res==-1) { - strerror_s(buff, errno); - printf("SSL_ERROR_SYSCALL %s\n", buff); - } - else - printf("SSL_ERROR_SYSCALL %s\n", ERR_error_string(ege, buff)); - } - break; - case SSL_ERROR_SSL: - printf("SSL_ERROR_SSL\n"); - break; - } - - } - - if (res!=1) - { - SSL_free(ssl); - ssl=0; - return false; - } - return true; -} -void RemoteClient::DisconnectSSL(void) -{ - if (ssl) - SSL_shutdown (ssl); /* send SSL/TLS close_notify */ -} -void RemoteClient::FreeSSL(void) -{ - if (ssl) - SSL_free (ssl); -} -int RemoteClient::Send(const char *data, unsigned int length) -{ - if (ssl) - return SSL_write (ssl, data, length); - else - return send__(socket, data, length, 0); -} -int RemoteClient::Recv(char *data, const int dataSize) -{ - if (ssl) - return SSL_read (ssl, data, dataSize); - else - return recv__(socket, data, dataSize, 0); -} -#else -int RemoteClient::Send(const char *data, unsigned int length) -{ -#ifdef __native_client__ - return -1; -#else - return send__(socket, data, length, 0); -#endif -} -int RemoteClient::Recv(char *data, const int dataSize) -{ -#ifdef __native_client__ - return -1; -#else - return recv__(socket, data, dataSize, 0); -#endif -} -#endif - -#ifdef _MSC_VER -#pragma warning( pop ) -#endif - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/TableSerializer.cpp b/vendors/mafianet/Source/src/TableSerializer.cpp deleted file mode 100644 index 62956f749..000000000 --- a/vendors/mafianet/Source/src/TableSerializer.cpp +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/TableSerializer.h" -#include "mafianet/DS_Table.h" -#include "mafianet/BitStream.h" -#include "mafianet/StringCompressor.h" -#include "mafianet/assert.h" - -using namespace MafiaNet; - -void TableSerializer::SerializeTable(DataStructures::Table *in, MafiaNet::BitStream *out) -{ - DataStructures::Page *cur = in->GetRows().GetListHead(); - const DataStructures::List &columns=in->GetColumns(); - SerializeColumns(in, out); - out->Write((unsigned)in->GetRows().Size()); - unsigned rowIndex; - while (cur) - { - for (rowIndex=0; rowIndex < (unsigned)cur->size; rowIndex++) - { - SerializeRow(cur->data[rowIndex], cur->keys[rowIndex], columns, out); - } - cur=cur->next; - } -} -void TableSerializer::SerializeColumns(DataStructures::Table *in, MafiaNet::BitStream *out) -{ - const DataStructures::List &columns=in->GetColumns(); - out->Write((unsigned)columns.Size()); - unsigned i; - for (i=0; iEncodeString(columns[i].columnName, _TABLE_MAX_COLUMN_NAME_LENGTH, out); - out->Write((unsigned char)columns[i].columnType); - } -} -void TableSerializer::SerializeColumns(DataStructures::Table *in, MafiaNet::BitStream *out, DataStructures::List &skipColumnIndices) -{ - const DataStructures::List &columns=in->GetColumns(); - out->Write((unsigned)columns.Size()-skipColumnIndices.Size()); - unsigned i; - for (i=0; iEncodeString(columns[i].columnName, _TABLE_MAX_COLUMN_NAME_LENGTH, out); - out->Write((unsigned char)columns[i].columnType); - } - } -} -bool TableSerializer::DeserializeTable(unsigned char *serializedTable, unsigned int dataLength, DataStructures::Table *out) -{ - MafiaNet::BitStream in((unsigned char*) serializedTable, dataLength, false); - return DeserializeTable(&in, out); -} -bool TableSerializer::DeserializeTable(MafiaNet::BitStream *in, DataStructures::Table *out) -{ - unsigned rowSize; - DeserializeColumns(in,out); - if (in->Read(rowSize)==false || rowSize>100000) - { - RakAssert(0); - return false; // Hacker crash prevention - } - - unsigned rowIndex; - for (rowIndex=0; rowIndex < rowSize; rowIndex++) - { - if (DeserializeRow(in, out)==false) - return false; - } - return true; -} -bool TableSerializer::DeserializeColumns(MafiaNet::BitStream *in, DataStructures::Table *out) -{ - unsigned columnSize; - unsigned char columnType; - char columnName[_TABLE_MAX_COLUMN_NAME_LENGTH]; - if (in->Read(columnSize)==false || columnSize > 10000) - return false; // Hacker crash prevention - - out->Clear(); - unsigned i; - for (i=0; iDecodeString(columnName, 32, in); - in->Read(columnType); - out->AddColumn(columnName, (DataStructures::Table::ColumnType)columnType); - } - return true; -} -void TableSerializer::SerializeRow(DataStructures::Table::Row *in, unsigned keyIn, const DataStructures::List &columns, MafiaNet::BitStream *out) -{ - unsigned cellIndex; - out->Write(keyIn); - unsigned int columnsSize = columns.Size(); - out->Write(columnsSize); - for (cellIndex=0; cellIndexWrite(cellIndex); - SerializeCell(out, in->cells[cellIndex], columns[cellIndex].columnType); - } -} -void TableSerializer::SerializeRow(DataStructures::Table::Row *in, unsigned keyIn, const DataStructures::List &columns, MafiaNet::BitStream *out, DataStructures::List &skipColumnIndices) -{ - unsigned cellIndex; - out->Write(keyIn); - unsigned int numEntries=0; - for (cellIndex=0; cellIndexWrite(numEntries); - - for (cellIndex=0; cellIndexWrite(cellIndex); - SerializeCell(out, in->cells[cellIndex], columns[cellIndex].columnType); - } - } -} -bool TableSerializer::DeserializeRow(MafiaNet::BitStream *in, DataStructures::Table *out) -{ - const DataStructures::List &columns=out->GetColumns(); - unsigned numEntries; - DataStructures::Table::Row *row; - unsigned key; - if (in->Read(key)==false) - return false; - row=out->AddRow(key); - unsigned int cnt; - in->Read(numEntries); - for (cnt=0; cntRead(cellIndex); - if (DeserializeCell(in, row->cells[cellIndex], columns[cellIndex].columnType)==false) - { - out->RemoveRow(key); - return false; - } - } - return true; -} -void TableSerializer::SerializeCell(MafiaNet::BitStream *out, DataStructures::Table::Cell *cell, DataStructures::Table::ColumnType columnType) -{ - out->Write(cell->isEmpty); - if (cell->isEmpty==false) - { - if (columnType==DataStructures::Table::NUMERIC) - { - out->Write(cell->i); - } - else if (columnType==DataStructures::Table::STRING) - { - StringCompressor::Instance()->EncodeString(cell->c, 65535, out); - } - else if (columnType==DataStructures::Table::POINTER) - { - out->Write(cell->ptr); - } - else - { - // Binary - RakAssert(columnType==DataStructures::Table::BINARY); - RakAssert(cell->i>0); - unsigned binaryLength; - binaryLength=(unsigned)cell->i; - out->Write(binaryLength); - out->WriteAlignedBytes((const unsigned char*) cell->c, (const unsigned int) cell->i); - } - } -} -bool TableSerializer::DeserializeCell(MafiaNet::BitStream *in, DataStructures::Table::Cell *cell, DataStructures::Table::ColumnType columnType) -{ - bool isEmpty=false; - double value; - void *ptr; - char tempString[65535]; - cell->Clear(); - - if (in->Read(isEmpty)==false) - return false; - if (isEmpty==false) - { - if (columnType==DataStructures::Table::NUMERIC) - { - if (in->Read(value)==false) - return false; - cell->Set(value); - } - else if (columnType==DataStructures::Table::STRING) - { - if (StringCompressor::Instance()->DecodeString(tempString, 65535, in)==false) - return false; - cell->Set(tempString); - } - else if (columnType==DataStructures::Table::POINTER) - { - if (in->Read(ptr)==false) - return false; - cell->SetPtr(ptr); - } - else - { - unsigned binaryLength; - // Binary - RakAssert(columnType==DataStructures::Table::BINARY); - if (in->Read(binaryLength)==false || binaryLength > 10000000) - return false; // Sanity check to max binary cell of 10 megabytes - in->AlignReadToByteBoundary(); - if (BITS_TO_BYTES(in->GetNumberOfUnreadBits())<(BitSize_t)binaryLength) - return false; - cell->Set((char*) in->GetData()+BITS_TO_BYTES(in->GetReadOffset()), (int) binaryLength); - in->IgnoreBits(BYTES_TO_BITS((int) binaryLength)); - } - } - return true; -} -void TableSerializer::SerializeFilterQuery(MafiaNet::BitStream *in, DataStructures::Table::FilterQuery *query) -{ - StringCompressor::Instance()->EncodeString(query->columnName,_TABLE_MAX_COLUMN_NAME_LENGTH,in,0); - in->WriteCompressed(query->columnIndex); - in->Write((unsigned char) query->operation); - in->Write(query->cellValue->isEmpty); - if (query->cellValue->isEmpty==false) - { - in->Write(query->cellValue->i); - in->WriteAlignedBytesSafe((const char*)query->cellValue->c,(const unsigned int)query->cellValue->i,10000000); // Sanity check to max binary cell of 10 megabytes - in->Write(query->cellValue->ptr); - - } -} -bool TableSerializer::DeserializeFilterQuery(MafiaNet::BitStream *out, DataStructures::Table::FilterQuery *query) -{ - bool b; - RakAssert(query->cellValue); - StringCompressor::Instance()->DecodeString(query->columnName,_TABLE_MAX_COLUMN_NAME_LENGTH,out,0); - out->ReadCompressed(query->columnIndex); - unsigned char op; - out->Read(op); - query->operation=(DataStructures::Table::FilterQueryType) op; - query->cellValue->Clear(); - b=out->Read(query->cellValue->isEmpty); - if (query->cellValue->isEmpty==false) - { - // HACK - cellValue->i is used for integer, character, and binary data. However, for character and binary c will be 0. So use that to determine if the data was integer or not. - out->Read(query->cellValue->i); - unsigned int inputLength; - out->ReadAlignedBytesSafeAlloc(&query->cellValue->c,inputLength,10000000); // Sanity check to max binary cell of 10 megabytes - if (query->cellValue->c) - query->cellValue->i=inputLength; - b=out->Read(query->cellValue->ptr); - } - return b; -} -void TableSerializer::SerializeFilterQueryList(MafiaNet::BitStream *in, DataStructures::Table::FilterQuery *query, unsigned int numQueries, unsigned int maxQueries) -{ - (void) maxQueries; - in->Write((bool)(query && numQueries>0)); - if (query==0 || numQueries<=0) - return; - - RakAssert(numQueries<=maxQueries); - in->WriteCompressed(numQueries); - unsigned i; - for (i=0; i < numQueries; i++) - { - SerializeFilterQuery(in, query); - } -} -bool TableSerializer::DeserializeFilterQueryList(MafiaNet::BitStream *out, DataStructures::Table::FilterQuery **query, unsigned int *numQueries, unsigned int maxQueries, int allocateExtraQueries) -{ - bool b, anyQueries=false; - out->Read(anyQueries); - if (anyQueries==false) - { - if (allocateExtraQueries<=0) - *query=0; - else - *query=new DataStructures::Table::FilterQuery[allocateExtraQueries]; - - *numQueries=0; - return true; - } - b=out->ReadCompressed(*numQueries); - if (*numQueries>maxQueries) - { - RakAssert(0); - *numQueries=maxQueries; - } - if (*numQueries==0) - return b; - - *query=new DataStructures::Table::FilterQuery[*numQueries+allocateExtraQueries]; - DataStructures::Table::FilterQuery *queryPtr = *query; - - unsigned i; - for (i=0; i < *numQueries; i++) - { - queryPtr[i].cellValue=new DataStructures::Table::Cell; - b=DeserializeFilterQuery(out, queryPtr+i); - } - - return b; -} -void TableSerializer::DeallocateQueryList(DataStructures::Table::FilterQuery *query, unsigned int numQueries) -{ - if (query==0 || numQueries==0) - return; - - unsigned i; - for (i=0; i < numQueries; i++) - MafiaNet::OP_DELETE(query[i].cellValue, _FILE_AND_LINE_); - MafiaNet::OP_DELETE_ARRAY(query, _FILE_AND_LINE_); -} diff --git a/vendors/mafianet/Source/src/TeamBalancer.cpp b/vendors/mafianet/Source/src/TeamBalancer.cpp deleted file mode 100644 index 31a08e0b1..000000000 --- a/vendors/mafianet/Source/src/TeamBalancer.cpp +++ /dev/null @@ -1,890 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_TeamBalancer==1 - -#include "mafianet/TeamBalancer.h" -#include "mafianet/BitStream.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/peerinterface.h" -#include "mafianet/Rand.h" - -using namespace MafiaNet; - -enum TeamBalancerOperations -{ - ID_STATUS_UPDATE_TO_NEW_HOST, - ID_CANCEL_TEAM_REQUEST, - ID_REQUEST_ANY_TEAM, - ID_REQUEST_SPECIFIC_TEAM -}; - -STATIC_FACTORY_DEFINITIONS(TeamBalancer,TeamBalancer); - -TeamBalancer::TeamBalancer() -{ - defaultAssigmentAlgorithm=SMALLEST_TEAM; - forceTeamsToBeEven=false; - lockTeams=false; - hostGuid=UNASSIGNED_RAKNET_GUID; -} -TeamBalancer::~TeamBalancer() -{ - -} -void TeamBalancer::SetTeamSizeLimit(TeamId team, unsigned short limit) -{ - teamLimits.Replace(limit,0,team,_FILE_AND_LINE_); - if (teamLimits.Size() > teamMemberCounts.Size()) - teamMemberCounts.Replace(0,0,teamLimits.Size()-1,_FILE_AND_LINE_); -} -void TeamBalancer::SetDefaultAssignmentAlgorithm(DefaultAssigmentAlgorithm daa) -{ - // Just update the default. Currently active teams are not affected. - defaultAssigmentAlgorithm=daa; -} -void TeamBalancer::SetForceEvenTeams(bool force) -{ - // Set flag to indicate that teams should be even. - forceTeamsToBeEven=force; - - // If teams are locked, just return. - if (lockTeams==true) - return; - - if (forceTeamsToBeEven==true) - { - // Run the even team algorithm - EvenTeams(); - } -} -void TeamBalancer::SetLockTeams(bool lock) -{ - if (lock==lockTeams) - return; - - // Set flag to indicate that teams can no longer be changed. - lockTeams=lock; - - // If lock is false, and teams were set to be forced as even, then run through the even team algorithm - if (lockTeams==false) - { - // Process even swaps - TeamId i,j; - for (i=0; i < teamMembers.Size(); i++) - { - if (teamMembers[i].requestedTeam!=UNASSIGNED_TEAM_ID) - { - for (j=i+1; j < teamMembers.Size(); j++) - { - if (teamMembers[j].requestedTeam==teamMembers[i].currentTeam && - teamMembers[i].requestedTeam==teamMembers[j].currentTeam) - { - SwapTeamMembersByRequest(i,j); - NotifyTeamAssigment(i); - NotifyTeamAssigment(j); - } - } - } - } - - if (forceTeamsToBeEven==true) - { - EvenTeams(); - } - else - { - // Process requested team changes - // Process movement while not full - for (i=0; i < teamMembers.Size(); i++) - { - TeamId requestedTeam = teamMembers[i].requestedTeam; - if (requestedTeam!=UNASSIGNED_TEAM_ID) - { - if (teamMemberCounts[requestedTeam]Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,hostGuid,false); -} -void TeamBalancer::CancelRequestSpecificTeam(NetworkID memberId) -{ - for (unsigned int i=0; i < myTeamMembers.Size(); i++) - { - if (myTeamMembers[i].memberId==memberId) - { - myTeamMembers[i].requestedTeam=UNASSIGNED_TEAM_ID; - - // Send packet to the host to remove our request flag. - BitStream bsOut; - bsOut.Write((MessageID)ID_TEAM_BALANCER_INTERNAL); - bsOut.Write((MessageID)ID_CANCEL_TEAM_REQUEST); - bsOut.Write(memberId); - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,hostGuid,false); - - return; - } - } -} -void TeamBalancer::RequestAnyTeam(NetworkID memberId) -{ - bool foundMatch=false; - - for (unsigned int i=0; i < myTeamMembers.Size(); i++) - { - if (myTeamMembers[i].memberId==memberId) - { - foundMatch=true; - if (myTeamMembers[i].currentTeam!=UNASSIGNED_TEAM_ID) - return; - else - myTeamMembers[i].requestedTeam=UNASSIGNED_TEAM_ID; - break; - } - } - - if (foundMatch==false) - { - MyTeamMembers mtm; - mtm.currentTeam=UNASSIGNED_TEAM_ID; - mtm.memberId=memberId; - mtm.requestedTeam=UNASSIGNED_TEAM_ID; - myTeamMembers.Push(mtm, _FILE_AND_LINE_); - } - - // Else send to the current host that we need a team. - BitStream bsOut; - bsOut.Write((MessageID)ID_TEAM_BALANCER_INTERNAL); - bsOut.Write((MessageID)ID_REQUEST_ANY_TEAM); - bsOut.Write(memberId); - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,hostGuid,false); -} -TeamId TeamBalancer::GetMyTeam(NetworkID memberId) const -{ - // Return team returned by last ID_TEAM_BALANCER_TEAM_ASSIGNED packet - for (unsigned int i=0; i < myTeamMembers.Size(); i++) - { - if (myTeamMembers[i].memberId==memberId) - { - return myTeamMembers[i].currentTeam; - } - } - - return UNASSIGNED_TEAM_ID; -} -void TeamBalancer::DeleteMember(NetworkID memberId) -{ - for (unsigned int i=0; i < myTeamMembers.Size(); i++) - { - if (myTeamMembers[i].memberId==memberId) - { - myTeamMembers.RemoveAtIndexFast(i); - break; - } - } - - for (unsigned int i=0; i < teamMembers.Size(); i++) - { - if (teamMembers[i].memberId==memberId) - { - RemoveTeamMember(i); - break; - } - } -} -PluginReceiveResult TeamBalancer::OnReceive(Packet *packet) -{ - switch (packet->data[0]) - { - case ID_FCM2_NEW_HOST: - { - hostGuid=packet->guid; - - if (myTeamMembers.Size()>0) - { - BitStream bsOut; - bsOut.Write((MessageID)ID_TEAM_BALANCER_INTERNAL); - bsOut.Write((MessageID)ID_STATUS_UPDATE_TO_NEW_HOST); - - bsOut.WriteCasted(myTeamMembers.Size()); - for (unsigned int i=0; i < myTeamMembers.Size(); i++) - { - bsOut.Write(myTeamMembers[i].memberId); - bsOut.Write(myTeamMembers[i].currentTeam); - bsOut.Write(myTeamMembers[i].requestedTeam); - } - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,hostGuid,false); - } - } - break; - case ID_TEAM_BALANCER_INTERNAL: - { - if (packet->length>=2) - { - switch (packet->data[1]) - { - case ID_STATUS_UPDATE_TO_NEW_HOST: - OnStatusUpdateToNewHost(packet); - break; - case ID_CANCEL_TEAM_REQUEST: - OnCancelTeamRequest(packet); - break; - case ID_REQUEST_ANY_TEAM: - OnRequestAnyTeam(packet); - break; - case ID_REQUEST_SPECIFIC_TEAM: - OnRequestSpecificTeam(packet); - break; - } - } - } - return RR_STOP_PROCESSING_AND_DEALLOCATE; - - case ID_TEAM_BALANCER_TEAM_ASSIGNED: - { - return OnTeamAssigned(packet); - } - - case ID_TEAM_BALANCER_REQUESTED_TEAM_FULL: - { - return OnRequestedTeamChangePending(packet); - } - - case ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED: - { - return OnTeamsLocked(packet); - } - } - - // Got RequestSpecificTeam - // If teams are locked - // - If this user already has a team, return ID_TEAM_BALANCER_TEAMS_LOCKED - // - This user does not already have a team. Assign a team as if the user called RequestAnyTeam(), with a preference for the requested team. Return ID_TEAM_BALANCER_TEAM_ASSIGNED once the team has been assigned. - // If teams are not locked - // - If even team balancing is on, only assign this user if this would not cause teams to be unbalanced. If teams WOULD be unbalanced, then flag this user as wanting to join this team. Return ID_TEAM_BALANCER_REQUESTED_TEAM_CHANGE_PENDING - // - If the destination team is full, flag this user as wanting to join this team. Return ID_TEAM_BALANCER_REQUESTED_TEAM_CHANGE_PENDING - // - Else, join this team. Return ID_TEAM_BALANCER_TEAM_ASSIGNED - - // Got RequestAnyTeam - // Put user on a team following the algorithm. No team is set as preferred. - - return RR_CONTINUE_PROCESSING; -} -void TeamBalancer::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) systemAddress; - (void) lostConnectionReason; - - RemoveByGuid(rakNetGUID); -} -void TeamBalancer::OnAttach(void) -{ - hostGuid = rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); -} -void TeamBalancer::RemoveByGuid(RakNetGUID rakNetGUID) -{ - // If we are the host, and the closed connection has a team, and teams are not locked: - if (WeAreHost()) - { - unsigned int droppedMemberIndex=0; - while (droppedMemberIndex < teamMembers.Size()) - { - if (teamMembers[droppedMemberIndex].memberGuid==rakNetGUID) - { - TeamId droppedTeam = teamMembers[droppedMemberIndex].currentTeam; - RemoveTeamMember(droppedMemberIndex); - if (lockTeams==false) - { - if (forceTeamsToBeEven) - { - // - teams were forced to be even, then run the even team algorithm - EvenTeams(); - } - else - { - // - teams were NOT forced to be even, and the team the dropped player on was full, then move users wanting to join that team (if any) - if (teamMemberCounts[ droppedTeam ]==teamLimits[ droppedTeam ]-1) - { - MoveMemberThatWantsToJoinTeam(droppedTeam); - } - } - } - } - else - { - droppedMemberIndex++; - } - } - } -} -void TeamBalancer::OnStatusUpdateToNewHost(Packet *packet) -{ - if (WeAreHost()==false) - return; - - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2); - uint8_t requestedTeamChangeListSize; - bsIn.Read(requestedTeamChangeListSize); - TeamMember tm; - tm.memberGuid=packet->guid; - for (uint8_t i=0; i < requestedTeamChangeListSize; i++) - { - bsIn.Read(tm.memberId); - bsIn.Read(tm.currentTeam); - bsIn.Read(tm.requestedTeam); - - if (tm.currentTeam!=UNASSIGNED_TEAM_ID && tm.currentTeam>teamLimits.Size()) - { - RakAssert("Current team out of range in TeamBalancer::OnStatusUpdateToNewHost" && 0); - return; - } - - if (tm.requestedTeam!=UNASSIGNED_TEAM_ID && tm.requestedTeam>teamLimits.Size()) - { - RakAssert("Requested team out of range in TeamBalancer::OnStatusUpdateToNewHost" && 0); - return; - } - - if (tm.currentTeam==UNASSIGNED_TEAM_ID && tm.requestedTeam==UNASSIGNED_TEAM_ID) - return; - - unsigned int memberIndex = GetMemberIndex(tm.memberId, packet->guid); - if (memberIndex==(unsigned int) -1) - { - // Add this system (by GUID) to the list of members if he is not already there - // Also update his requested team flag. - // Do not process balancing on requested teams, since we don't necessarily have all data from all systems yet and hopefully the state during the host migration was stable. - if (tm.currentTeam==UNASSIGNED_TEAM_ID) - { - // Assign a default team, then add team member - if (tm.requestedTeam==UNASSIGNED_TEAM_ID) - { - // Assign a default team - tm.currentTeam=GetNextDefaultTeam(); - } - else - { - // Assign to requested team if possible. Otherwise, assign to a default team - if (TeamWouldBeOverpopulatedOnAddition(tm.requestedTeam, teamMembers.Size())==false) - { - tm.currentTeam=tm.requestedTeam; - } - else - { - tm.currentTeam=GetNextDefaultTeam(); - } - } - } - - if (tm.currentTeam==UNASSIGNED_TEAM_ID) - { - RakAssert("Too many members asking for teams!" && 0); - return; - } - NotifyTeamAssigment(AddTeamMember(tm)); - } - } -} -void TeamBalancer::OnCancelTeamRequest(Packet *packet) -{ - if (WeAreHost()==false) - return; - - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2); - NetworkID memberId; - bsIn.Read(memberId); - - unsigned int memberIndex = GetMemberIndex(memberId, packet->guid); - if (memberIndex!=(unsigned int)-1) - teamMembers[memberIndex].requestedTeam=UNASSIGNED_TEAM_ID; -} -void TeamBalancer::OnRequestAnyTeam(Packet *packet) -{ - if (WeAreHost()==false) - return; - - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2); - NetworkID memberId; - bsIn.Read(memberId); - - unsigned int memberIndex = GetMemberIndex(memberId, packet->guid); - if (memberIndex==(unsigned int)-1) - { - TeamMember tm; - tm.currentTeam=GetNextDefaultTeam(); - tm.requestedTeam=UNASSIGNED_TEAM_ID; - tm.memberGuid=packet->guid; - tm.memberId=memberId; - if (tm.currentTeam==UNASSIGNED_TEAM_ID) - { - RakAssert("Too many members asking for teams!" && 0); - return; - } - NotifyTeamAssigment(AddTeamMember(tm)); - } -} -void TeamBalancer::OnRequestSpecificTeam(Packet *packet) -{ - if (WeAreHost()==false) - return; - - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2); - TeamMember tm; - bsIn.Read(tm.memberId); - bsIn.Read(tm.requestedTeam); - - unsigned int memberIndex = GetMemberIndex(tm.memberId, packet->guid); - if (tm.requestedTeam==UNASSIGNED_TEAM_ID) - { - NotifyNoTeam(tm.memberId, packet->guid); - if (memberIndex != (unsigned int) -1) - RemoveTeamMember(memberIndex); - return; - } - - if (tm.requestedTeam>teamLimits.Size()) - { - RakAssert("Requested team out of range in TeamBalancer::OnRequestSpecificTeam" && 0); - return; - } - if (memberIndex==(unsigned int) -1) - { - tm.memberGuid=packet->guid; - - // Assign to requested team if possible. Otherwise, assign to a default team - if (TeamWouldBeOverpopulatedOnAddition(tm.requestedTeam, teamMembers.Size())==false) - { - tm.currentTeam=tm.requestedTeam; - tm.requestedTeam=UNASSIGNED_TEAM_ID; - } - else - { - tm.currentTeam=GetNextDefaultTeam(); - } - if (tm.currentTeam==UNASSIGNED_TEAM_ID) - { - RakAssert("Too many members asking for teams!" && 0); - return; - } - NotifyTeamAssigment(AddTeamMember(tm)); - } - else - { - teamMembers[memberIndex].requestedTeam=tm.requestedTeam; - TeamId oldTeamThisUserWasOn = teamMembers[memberIndex].currentTeam; - - if (lockTeams) - { - NotifyTeamsLocked(packet->guid, tm.requestedTeam); - return; - } - - // Assign to requested team if possible. Otherwise, assign to a default team - if (TeamsWouldBeEvenOnSwitch(tm.requestedTeam,oldTeamThisUserWasOn)==true) - { - SwitchMemberTeam(memberIndex,tm.requestedTeam); - NotifyTeamAssigment(memberIndex); - } - else - { - // If someone wants to join this user's old team, and we want to join their team, they can swap - unsigned int swappableMemberIndex; - for (swappableMemberIndex=0; swappableMemberIndex < teamMembers.Size(); swappableMemberIndex++) - { - if (teamMembers[swappableMemberIndex].currentTeam==tm.requestedTeam && teamMembers[swappableMemberIndex].requestedTeam==oldTeamThisUserWasOn) - break; - } - - if (swappableMemberIndex!=teamMembers.Size()) - { - SwapTeamMembersByRequest(memberIndex,swappableMemberIndex); - NotifyTeamAssigment(memberIndex); - NotifyTeamAssigment(swappableMemberIndex); - } - else - { - // Full or would not be even - NotifyTeamSwitchPending(packet->guid, tm.requestedTeam, tm.memberId); - } - } - } -} -unsigned int TeamBalancer::GetMemberIndex(NetworkID memberId, RakNetGUID guid) const -{ - for (unsigned int i=0; i < teamMembers.Size(); i++) - { - if (teamMembers[i].memberGuid==guid && teamMembers[i].memberId==memberId) - return i; - } - return (unsigned int) -1; -} -unsigned int TeamBalancer::AddTeamMember(const TeamMember &tm) -{ - if (tm.currentTeam>teamLimits.Size()) - { - RakAssert("TeamBalancer::AddTeamMember team index out of bounds" && 0); - return (unsigned int) -1; - } - - RakAssert(tm.currentTeam!=UNASSIGNED_TEAM_ID); - - teamMembers.Push(tm,_FILE_AND_LINE_); - if (teamMemberCounts.Size() overpopulatedTeams; - TeamId teamMemberCountsIndex; - unsigned int memberIndexToSwitch; - for (teamMemberCountsIndex=0; teamMemberCountsIndex0); - memberIndexToSwitch=GetMemberIndexToSwitchTeams(overpopulatedTeams,teamMemberCountsIndex); - RakAssert(memberIndexToSwitch!=(unsigned int)-1); - SwitchMemberTeam(memberIndexToSwitch,teamMemberCountsIndex); - // Tell this member he switched teams - NotifyTeamAssigment(memberIndexToSwitch); - } - } -} -unsigned int TeamBalancer::GetMemberIndexToSwitchTeams(const DataStructures::List &sourceTeamNumbers, TeamId targetTeamNumber) -{ - DataStructures::List preferredSwapIndices; - DataStructures::List potentialSwapIndices; - unsigned int i,j; - for (j=0; j < sourceTeamNumbers.Size(); j++) - { - RakAssert(sourceTeamNumbers[j]!=targetTeamNumber); - for (i=0; i < teamMembers.Size(); i++) - { - if (teamMembers[i].currentTeam==sourceTeamNumbers[j]) - { - if (teamMembers[i].requestedTeam==targetTeamNumber) - preferredSwapIndices.Push(i,_FILE_AND_LINE_); - else - potentialSwapIndices.Push(i,_FILE_AND_LINE_); - } - } - } - - if (preferredSwapIndices.Size()>0) - { - return preferredSwapIndices[ randomMT() % preferredSwapIndices.Size() ]; - } - else if (potentialSwapIndices.Size()>0) - { - return potentialSwapIndices[ randomMT() % potentialSwapIndices.Size() ]; - } - else - { - return (unsigned int) -1; - } -} -void TeamBalancer::SwitchMemberTeam(unsigned int teamMemberIndex, TeamId destinationTeam) -{ - teamMemberCounts[ teamMembers[teamMemberIndex].currentTeam ]=teamMemberCounts[ teamMembers[teamMemberIndex].currentTeam ]-1; - teamMemberCounts[ destinationTeam ]=teamMemberCounts[ destinationTeam ]+1; - teamMembers[teamMemberIndex].currentTeam=destinationTeam; - if (teamMembers[teamMemberIndex].requestedTeam==destinationTeam) - teamMembers[teamMemberIndex].requestedTeam=UNASSIGNED_TEAM_ID; -} -void TeamBalancer::GetOverpopulatedTeams(DataStructures::List &overpopulatedTeams, int maxTeamSize) -{ - overpopulatedTeams.Clear(true,_FILE_AND_LINE_); - for (TeamId i=0; i < teamMemberCounts.Size(); i++) - { - if (teamMemberCounts[i]>=maxTeamSize) - overpopulatedTeams.Push(i,_FILE_AND_LINE_); - } -} -void TeamBalancer::NotifyTeamAssigment(unsigned int teamMemberIndex) -{ - RakAssert(teamMemberIndex < teamMembers.Size()); - if (teamMemberIndex>=teamMembers.Size()) - return; - - BitStream bsOut; - bsOut.Write((MessageID)ID_TEAM_BALANCER_TEAM_ASSIGNED); - bsOut.Write(teamMembers[teamMemberIndex].currentTeam); - bsOut.Write(teamMembers[teamMemberIndex].memberId); - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,teamMembers[teamMemberIndex].memberGuid,false); -} -bool TeamBalancer::WeAreHost(void) const -{ - return hostGuid==rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); -} -PluginReceiveResult TeamBalancer::OnTeamAssigned(Packet *packet) -{ - if (packet->guid!=hostGuid) - return RR_STOP_PROCESSING_AND_DEALLOCATE; - - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(1); - - MyTeamMembers mtm; - bsIn.Read(mtm.currentTeam); - bsIn.Read(mtm.memberId); - mtm.requestedTeam=UNASSIGNED_TEAM_ID; - - bool foundMatch=false; - for (unsigned int i=0; i < myTeamMembers.Size(); i++) - { - if (myTeamMembers[i].memberId==mtm.memberId) - { - foundMatch=true; - if (myTeamMembers[i].requestedTeam==mtm.currentTeam) - myTeamMembers[i].requestedTeam=UNASSIGNED_TEAM_ID; - myTeamMembers[i].currentTeam=mtm.currentTeam; - break; - } - } - - if (foundMatch==false) - { - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - - return RR_CONTINUE_PROCESSING; -} -PluginReceiveResult TeamBalancer::OnRequestedTeamChangePending(Packet *packet) -{ - if (packet->guid!=hostGuid) - return RR_STOP_PROCESSING_AND_DEALLOCATE; - - return RR_CONTINUE_PROCESSING; -} -PluginReceiveResult TeamBalancer::OnTeamsLocked(Packet *packet) -{ - if (packet->guid!=hostGuid) - return RR_STOP_PROCESSING_AND_DEALLOCATE; - - return RR_CONTINUE_PROCESSING; -} -TeamId TeamBalancer::GetNextDefaultTeam(void) -{ - // Accounting for team balancing and team limits, get the team a player should be placed on - switch (defaultAssigmentAlgorithm) - { - case SMALLEST_TEAM: - { - return GetSmallestNonFullTeam(); - } - - case FILL_IN_ORDER: - { - return GetFirstNonFullTeam(); - } - - default: - { - RakAssert("TeamBalancer::GetNextDefaultTeam unknown algorithm enumeration" && 0); - return UNASSIGNED_TEAM_ID; - } - } -} -bool TeamBalancer::TeamWouldBeOverpopulatedOnAddition(TeamId teamId, unsigned int teamMemberSize) -{ - // Accounting for team balancing and team limits, would this team be overpopulated if a member was added to it? - if (teamMemberCounts[teamId]>=teamLimits[teamId]) - { - return true; - } - - if (forceTeamsToBeEven) - { - int allowedLimit = teamMemberSize/teamLimits.Size() + 1; - return teamMemberCounts[teamId]>=allowedLimit; - } - - return false; -} -bool TeamBalancer::TeamWouldBeUnderpopulatedOnLeave(TeamId teamId, unsigned int teamMemberSize) -{ - if (forceTeamsToBeEven) - { - unsigned int minMembersOnASingleTeam = (teamMemberSize-1)/teamLimits.Size(); - return teamMemberCounts[teamId]<=minMembersOnASingleTeam; - } - return false; -} -TeamId TeamBalancer::GetSmallestNonFullTeam(void) const -{ - TeamId idx; - unsigned long smallestTeamCount=MAX_UNSIGNED_LONG; - TeamId smallestTeamIndex = UNASSIGNED_TEAM_ID; - for (idx=0; idx < teamMemberCounts.Size(); idx++) - { - if (teamMemberCounts[idx] membersThatWantToJoinTheTeam; - for (TeamId i=0; i < teamMembers.Size(); i++) - { - if (teamMembers[i].requestedTeam==teamId) - membersThatWantToJoinTheTeam.Push(i,_FILE_AND_LINE_); - } - - if (membersThatWantToJoinTheTeam.Size()>0) - { - TeamId oldTeam; - unsigned int swappedMemberIndex = membersThatWantToJoinTheTeam[ randomMT() % membersThatWantToJoinTheTeam.Size() ]; - oldTeam=teamMembers[swappedMemberIndex].currentTeam; - SwitchMemberTeam(swappedMemberIndex,teamId); - NotifyTeamAssigment(swappedMemberIndex); - return oldTeam; - } - return UNASSIGNED_TEAM_ID; -} -void TeamBalancer::NotifyTeamsLocked(RakNetGUID target, TeamId requestedTeam) -{ - BitStream bsOut; - bsOut.Write((MessageID)ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED); - bsOut.Write(requestedTeam); - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,target,false); -} -void TeamBalancer::NotifyTeamSwitchPending(RakNetGUID target, TeamId requestedTeam, NetworkID memberId) -{ - BitStream bsOut; - bsOut.Write((MessageID)ID_TEAM_BALANCER_REQUESTED_TEAM_FULL); - bsOut.Write(requestedTeam); - bsOut.Write(memberId); - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,target,false); -} -void TeamBalancer::SwapTeamMembersByRequest(unsigned int memberIndex1, unsigned int memberIndex2) -{ - TeamId index1Team = teamMembers[memberIndex1].currentTeam; - teamMembers[memberIndex1].currentTeam=teamMembers[memberIndex2].currentTeam; - teamMembers[memberIndex2].currentTeam=index1Team; - teamMembers[memberIndex1].requestedTeam=UNASSIGNED_TEAM_ID; - teamMembers[memberIndex2].requestedTeam=UNASSIGNED_TEAM_ID; -} -void TeamBalancer::NotifyNoTeam(NetworkID memberId, RakNetGUID target) -{ - BitStream bsOut; - bsOut.Write((MessageID)ID_TEAM_BALANCER_TEAM_ASSIGNED); - bsOut.Write((unsigned char)UNASSIGNED_TEAM_ID); - bsOut.Write(memberId); - rakPeerInterface->Send(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,target,false); -} -bool TeamBalancer::TeamsWouldBeEvenOnSwitch(TeamId t1, TeamId t2) -{ - RakAssert(teamMembers.Size()!=0); - return TeamWouldBeOverpopulatedOnAddition(t1, teamMembers.Size()-1)==false && - TeamWouldBeUnderpopulatedOnLeave(t2, teamMembers.Size()-1)==false; -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/TeamManager.cpp b/vendors/mafianet/Source/src/TeamManager.cpp deleted file mode 100644 index d197a74c2..000000000 --- a/vendors/mafianet/Source/src/TeamManager.cpp +++ /dev/null @@ -1,2858 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_TeamManager==1 - -#include "mafianet/TeamManager.h" -#include "mafianet/BitStream.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/GetTime.h" - -using namespace MafiaNet; - - -enum TeamManagerOperations -{ - ID_RUN_UpdateListsToNoTeam, - ID_RUN_UpdateTeamsRequestedToAny, - ID_RUN_JoinAnyTeam, - ID_RUN_JoinRequestedTeam, - ID_RUN_UpdateTeamsRequestedToNoneAndAddTeam, - ID_RUN_RemoveFromTeamsRequestedAndAddTeam, - ID_RUN_AddToRequestedTeams, - ID_RUN_LeaveTeam, - ID_RUN_SetMemberLimit, - ID_RUN_SetJoinPermissions, - ID_RUN_SetBalanceTeams, - ID_RUN_SetBalanceTeamsInitial, - ID_RUN_SerializeWorld, -}; - -STATIC_FACTORY_DEFINITIONS(TM_TeamMember,TM_TeamMember); -STATIC_FACTORY_DEFINITIONS(TM_Team,TM_Team); -STATIC_FACTORY_DEFINITIONS(TeamManager,TeamManager); - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -int TM_World::JoinRequestHelperComp(const TM_World::JoinRequestHelper &key, const TM_World::JoinRequestHelper &data) -{ - if (key.whenRequestMade < data.whenRequestMade) - return -1; - if (key.whenRequestMade > data.whenRequestMade) - return 1; - if (key.requestIndex < data.requestIndex) - return -1; - if (key.requestIndex > data.requestIndex) - return 1; - return 0; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TeamSelection::TeamSelection() {} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TeamSelection::TeamSelection(JoinTeamType itt) : joinTeamType(itt) {} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TeamSelection::TeamSelection(JoinTeamType itt, TM_Team *param) : joinTeamType(itt) {teamParameter.specificTeamToJoin=param;} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TeamSelection::TeamSelection(JoinTeamType itt, NoTeamId param) : joinTeamType(itt) {teamParameter.noTeamSubcategory=param;} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TeamSelection TeamSelection::AnyAvailable(void) {return TeamSelection(JOIN_ANY_AVAILABLE_TEAM);} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TeamSelection TeamSelection::SpecificTeam(TM_Team *specificTeamToJoin) {return TeamSelection(JOIN_SPECIFIC_TEAM, specificTeamToJoin);} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TeamSelection TeamSelection::NoTeam(NoTeamId noTeamSubcategory) {return TeamSelection(JOIN_NO_TEAM, noTeamSubcategory);} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_TeamMember::TM_TeamMember() -{ - networkId=0; - world=0; - joinTeamType=JOIN_NO_TEAM; - noTeamSubcategory=0; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_TeamMember::~TM_TeamMember() -{ - if (world) - { - world->DereferenceTeamMember(this); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_TeamMember::RequestTeam(TeamSelection teamSelection) -{ - if (teamSelection.joinTeamType==JOIN_NO_TEAM) - { - // If joining no team: - // - If already no team, and no team category is the same, return false. - // - Execute JoinNoTeam() locally. Return ID_TEAM_BALANCER_TEAM_ASSIGNED locally. - // - If we are host, broadcast event. Done. - // - Send to remote host event to call JoinNoTeam() - // - remote Host executes JoinNoTeam() and broadcasts event. This may cause may cause rebalance if team balancing is on. - // - - JoinNoTeam(): Remove from all current and requested teams. Set no-team category. - - if (teams.Size()==0 && noTeamSubcategory==teamSelection.teamParameter.noTeamSubcategory) - { - // No change - return false; - } - - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_UpdateListsToNoTeam); - bsOut.Write(world->GetWorldId()); - bsOut.Write(networkId); - bsOut.Write(teamSelection.teamParameter.noTeamSubcategory); - world->BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); - - StoreLastTeams(); - - UpdateListsToNoTeam(teamSelection.teamParameter.noTeamSubcategory); - - world->GetTeamManager()->PushTeamAssigned(this); - if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()) - { - world->FillRequestedSlots(); - world->EnforceTeamBalance(teamSelection.teamParameter.noTeamSubcategory); - } - } - else if (teamSelection.joinTeamType==JOIN_ANY_AVAILABLE_TEAM) - { - // If joining any team - // Execute JoinAnyTeamCheck() - // - JoinAnyTeamCheck(): - // - - If already on a team, return false - // - - If any team is already in requested teams, return false. - // On local, call UpdateTeamsRequestedToAny(). Send event to also execute this to remote host - // If we are host, execute JoinAnyTeam(myguid). - // - JoinAnyTeam(requesterGuid): Attempt to join any team immediately. If fails, send to all except requestGuid UpdateTeamsRequestedToAny(). Else sends out new team, including to caller. - // On remote host, execute JoinAnyTeamCheck(). If fails, this was because you were added to a team simultaneously on host. This is OK, just ignore the call. - // Assuming JoinAnyTeamCheck() passed on remote host, call UpdateTeamsRequestedToAny() for this player. execute JoinAnyTeam(packet->guid). - - if (JoinAnyTeamCheck()==false) - return false; - - UpdateTeamsRequestedToAny(); - - // Send request to host to execute JoinAnyTeam() - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_JoinAnyTeam); - bsOut.Write(world->GetWorldId()); - bsOut.Write(networkId); - world->GetTeamManager()->SendUnified(&bsOut,MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, world->GetHost(), false); - } - else - { - RakAssert(teamSelection.joinTeamType==JOIN_SPECIFIC_TEAM); - - // If joining specific team - // Execute JoinSpecificTeamCheck() - // JoinSpecificTeamCheck(): - // - If already on specific team, return false - // - If specific team is in requested list, return false - // On local, call AddToRequestedTeams(). Send event to also execute this to remote host - // If we are host, execute JoinSpecificTeam(myguid) - // - JoinSpecificTeam(requesterGuid): Attempt to join specific team immediately. If fails, send to all except requesterGuid to execute AddSpecificToRequested(). Else sends out new team, including to caller. - // On remote host, execute JoinSpecificTeamCheck(). If fails, just ignore. - // Assuming JoinSpecificTeamCheck() passed on host, call AddSpecificToRequestedList(). Execute JoinSpecificTeam(packet->guid) - - if (JoinSpecificTeamCheck(teamSelection.teamParameter.specificTeamToJoin,false)==false) - return false; - - AddToRequestedTeams(teamSelection.teamParameter.specificTeamToJoin); - - // Send request to host to execute JoinRequestedTeam() - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_JoinRequestedTeam); - bsOut.Write(world->GetWorldId()); - bsOut.Write(networkId); - bsOut.Write(teamSelection.teamParameter.specificTeamToJoin->GetNetworkID()); - bsOut.Write(false); - world->GetTeamManager()->SendUnified(&bsOut,MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, world->GetHost(), false); - } - - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_TeamMember::RequestTeamSwitch(TM_Team *teamToJoin, TM_Team *teamToLeave) -{ - if (SwitchSpecificTeamCheck(teamToJoin,teamToLeave,false)==false) - return false; - - AddToRequestedTeams(teamToJoin, teamToLeave); - - // Send request to host to execute JoinRequestedTeam() - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_JoinRequestedTeam); - bsOut.Write(world->GetWorldId()); - bsOut.Write(networkId); - bsOut.Write(teamToJoin->GetNetworkID()); - bsOut.Write(true); - if (teamToLeave) - { - bsOut.Write(true); - bsOut.Write(teamToLeave->GetNetworkID()); - } - else - { - bsOut.Write(false); - } - world->GetTeamManager()->SendUnified(&bsOut,MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, world->GetHost(), false); - - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TeamSelection TM_TeamMember::GetRequestedTeam(void) const -{ - if (teamsRequested.Size()>0) - return TeamSelection::SpecificTeam(teamsRequested[0].requested); - else if (joinTeamType==JOIN_NO_TEAM) - return TeamSelection::NoTeam(noTeamSubcategory); - else - return TeamSelection::AnyAvailable(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_TeamMember::GetRequestedSpecificTeams(DataStructures::List &requestedTeams) const -{ - requestedTeams.Clear(true, _FILE_AND_LINE_); - for (unsigned int i=0; i < teamsRequested.Size(); i++) - requestedTeams.Push(teamsRequested[i].requested, _FILE_AND_LINE_); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_TeamMember::HasRequestedTeam(TM_Team *team) const -{ - unsigned int i = GetRequestedTeamIndex(team); - if (i==(unsigned int)-1) - return false; - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned int TM_TeamMember::GetRequestedTeamIndex(TM_Team *team) const -{ - unsigned int i; - for (i=0; i < teamsRequested.Size(); i++) - { - if (teamsRequested[i].requested==team) - return i; - } - return (unsigned int) -1; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned int TM_TeamMember::GetRequestedTeamCount(void) const -{ - return teamsRequested.Size(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_TeamMember::CancelTeamRequest(TM_Team *specificTeamToCancel) -{ - if (RemoveFromRequestedTeams(specificTeamToCancel)==false) - return false; - - // Send request to host to execute JoinRequestedTeam() - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED); - bsOut.Write(world->GetWorldId()); - bsOut.Write(networkId); - if (specificTeamToCancel) - { - bsOut.Write(true); - bsOut.Write(specificTeamToCancel->GetNetworkID()); - } - else - { - bsOut.Write(false); - } - world->BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); - - world->GetTeamManager()->PushBitStream(&bsOut); - - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_TeamMember::LeaveTeam(TM_Team* team, NoTeamId _noTeamSubcategory) -{ - if (LeaveTeamCheck(team)==false) - return false; - - RemoveFromSpecificTeamInternal(team); - if (teams.Size()==0) - { - noTeamSubcategory=_noTeamSubcategory; - joinTeamType=JOIN_NO_TEAM; - } - - // Execute LeaveTeamCheck() - // - LeaveTeamCheck(): - // - - If not on this team, return false - // On local, call RemoteFromTeamsList(). Send event to also execute this to remote host - // If we are host, execute OnLeaveTeamEvent(myGuid) - // - OnLeaveTeamEvent(requesterGuid): - // - - If rebalancing is active, rebalance - // - - If someone else wants to join this team, let them. - // - - Send leave team event notification to all except requesterGuid- - // On remote host, execute LeaveTeamCheck(). If fails, ignore. - // On remote host, execute RemoteFromTeamsList() followed by OnLeaveTeamEvent(packet->guid) - - // Pattern: - // Execute local check, if fails return false - // Locally execute non-host guaranteed changes - // If local system is also host, execute host changes. Relay to all but local - // On remote host, execute check. If check passes, execute non-host changes, followed by host changes. Relay to all but sender. - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_LeaveTeam); - bsOut.Write(world->GetWorldId()); - bsOut.Write(networkId); - bsOut.Write(team->GetNetworkID()); - bsOut.Write(noTeamSubcategory); - world->BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); - - if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()) - { - // Rebalance teams - world->FillRequestedSlots(); - world->EnforceTeamBalance(noTeamSubcategory); - } - - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_TeamMember::LeaveAllTeams(NoTeamId inNoTeamSubcategory) -{ - return RequestTeam(TeamSelection::NoTeam(inNoTeamSubcategory)); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_Team* TM_TeamMember::GetCurrentTeam(void) const -{ - if (teams.Size()>0) - return teams[0]; - return 0; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned int TM_TeamMember::GetCurrentTeamCount(void) const -{ - return teams.Size(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_Team* TM_TeamMember::GetCurrentTeamByIndex(unsigned int index) -{ - return teams[index]; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_TeamMember::GetCurrentTeams(DataStructures::List &_teams) const -{ - _teams=teams; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_TeamMember::GetLastTeams(DataStructures::List &_teams) const -{ - _teams=lastTeams; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_TeamMember::IsOnTeam(TM_Team *team) const -{ - unsigned int i; - for (i=0; i < teams.Size(); i++) - { - if (teams[i]==team) - return true; - } - return false; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -NetworkID TM_TeamMember::GetNetworkID(void) const -{ - return networkId; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_World* TM_TeamMember::GetTM_World(void) const -{ - return world; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_TeamMember::SerializeConstruction(BitStream *constructionBitstream) -{ - // Write requested teams - constructionBitstream->Write(world->GetWorldId()); - constructionBitstream->Write(networkId); - constructionBitstream->WriteCasted(teamsRequested.Size()); - for (unsigned int i=0; i < teamsRequested.Size(); i++) - { - constructionBitstream->Write(teamsRequested[i].isTeamSwitch); - if (teamsRequested[i].teamToLeave) - { - constructionBitstream->Write(true); - constructionBitstream->Write(teamsRequested[i].teamToLeave->GetNetworkID()); - } - else - { - constructionBitstream->Write(false); - } - if (teamsRequested[i].requested) - { - constructionBitstream->Write(true); - constructionBitstream->Write(teamsRequested[i].requested->GetNetworkID()); - } - else - { - constructionBitstream->Write(false); - } - } - - world->teamManager->EncodeTeamAssigned(constructionBitstream, this); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_TeamMember::DeserializeConstruction(TeamManager *teamManager, BitStream *constructionBitstream) -{ - // Read requested teams - bool success; - uint16_t teamsRequestedSize; - - WorldId worldId; - constructionBitstream->Read(worldId); - TM_World *curWorld = teamManager->GetWorldWithId(worldId); - RakAssert(curWorld); - constructionBitstream->Read(networkId); - curWorld->ReferenceTeamMember(this,networkId); - - success=constructionBitstream->Read(teamsRequestedSize); - for (unsigned int i=0; i < teamsRequestedSize; i++) - { - RequestedTeam rt; - rt.isTeamSwitch=false; - rt.requested=0; - rt.whenRequested=0; - constructionBitstream->Read(rt.isTeamSwitch); - bool hasTeamToLeave=false; - constructionBitstream->Read(hasTeamToLeave); - NetworkID teamToLeaveId; - if (hasTeamToLeave) - { - constructionBitstream->Read(teamToLeaveId); - rt.teamToLeave = curWorld->GetTeamByNetworkID(teamToLeaveId); - RakAssert(rt.teamToLeave); - } - else - rt.teamToLeave=0; - bool hasTeamRequested=false; - success=constructionBitstream->Read(hasTeamRequested); - NetworkID teamRequestedId; - if (hasTeamRequested) - { - success=constructionBitstream->Read(teamRequestedId); - rt.requested = curWorld->GetTeamByNetworkID(teamRequestedId); - RakAssert(rt.requested); - } - rt.whenRequested= MafiaNet::GetTime(); - rt.requestIndex= curWorld->teamRequestIndex++; // In case whenRequested is the same between two teams when sorting team requests - if ( - (hasTeamToLeave==false || (hasTeamToLeave==true && rt.teamToLeave!=0)) && - (hasTeamRequested==false || (hasTeamRequested==true && rt.requested!=0)) - ) - { - teamsRequested.Push(rt, _FILE_AND_LINE_); - } - } - - - if (success) - curWorld->teamManager->ProcessTeamAssigned(constructionBitstream); - return success; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void *TM_TeamMember::GetOwner(void) const -{ - return owner; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_TeamMember::SetOwner(void *o) -{ - owner=o; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -NoTeamId TM_TeamMember::GetNoTeamId(void) const -{ - return noTeamSubcategory; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned int TM_TeamMember::GetWorldIndex(void) const -{ - return world->GetTeamMemberIndex(this); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned long TM_TeamMember::ToUint32( const NetworkID &g ) -{ - return g & 0xFFFFFFFF; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_TeamMember::UpdateListsToNoTeam(NoTeamId nti) -{ - teamsRequested.Clear(true, _FILE_AND_LINE_ ); - for (unsigned int i=0; i < teams.Size(); i++) - { - teams[i]->RemoveFromTeamMemberList(this); - } - teams.Clear(true, _FILE_AND_LINE_ ); - noTeamSubcategory=nti; - joinTeamType=JOIN_NO_TEAM; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_TeamMember::JoinAnyTeamCheck(void) const -{ - // - - If already on a team, return false - if (teams.Size() > 0) - return false; - - // - - If any team is already in requested teams, return false. - if (teamsRequested.Size()==0 && joinTeamType==JOIN_ANY_AVAILABLE_TEAM) - return false; - - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_TeamMember::JoinSpecificTeamCheck(TM_Team *specificTeamToJoin, bool ignoreRequested) const -{ - // - If already on specific team, return false - if (IsOnTeam(specificTeamToJoin)) - return false; - - if (ignoreRequested) - return true; - - unsigned int i; - for (i=0; i < teamsRequested.Size(); i++) - { - if (teamsRequested[i].requested==specificTeamToJoin) - { - if (teamsRequested[i].isTeamSwitch==true) - return true; // Turn off team switch - - // Same thing - return false; - } - } - - // Not in teams requested - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_TeamMember::SwitchSpecificTeamCheck(TM_Team *teamToJoin, TM_Team *teamToLeave, bool ignoreRequested) const -{ - RakAssert(teamToJoin!=0); - - // - If already on specific team, return false - if (IsOnTeam(teamToJoin)) - return false; - - if (teamToLeave!=0 && IsOnTeam(teamToLeave)==false) - return false; - - if (teamToJoin==teamToLeave) - return false; - - if (ignoreRequested) - return true; - - unsigned int i; - for (i=0; i < teamsRequested.Size(); i++) - { - if (teamsRequested[i].requested==teamToJoin) - { - if (teamsRequested[i].isTeamSwitch==false) - return true; // Different - leave team was off, turn on - - if (teamsRequested[i].teamToLeave==teamToLeave) - return false; // Same thing - leave all or a specific team - - // Change leave team - return true; - } - } - - // Not in teams requested - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_TeamMember::LeaveTeamCheck(TM_Team *team) const -{ - if (IsOnTeam(team)==false) - return false; - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_TeamMember::UpdateTeamsRequestedToAny(void) -{ - teamsRequested.Clear(true, _FILE_AND_LINE_); - joinTeamType=JOIN_ANY_AVAILABLE_TEAM; - whenJoinAnyRequested= MafiaNet::GetTime(); - joinAnyRequestIndex=world->teamRequestIndex++; // In case whenRequested is the same between two teams when sorting team requests -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_TeamMember::UpdateTeamsRequestedToNone(void) -{ - teamsRequested.Clear(true, _FILE_AND_LINE_); - joinTeamType=JOIN_NO_TEAM; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_TeamMember::AddToRequestedTeams(TM_Team *teamToJoin) -{ - RemoveFromRequestedTeams(teamToJoin); - - RequestedTeam rt; - rt.isTeamSwitch=false; - rt.requested=teamToJoin; - rt.teamToLeave=0; - rt.whenRequested= MafiaNet::GetTime(); - rt.requestIndex=world->teamRequestIndex++; // In case whenRequested is the same between two teams when sorting team requests - teamsRequested.Push(rt, _FILE_AND_LINE_ ); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_TeamMember::AddToRequestedTeams(TM_Team *teamToJoin, TM_Team *teamToLeave) -{ - RemoveFromRequestedTeams(teamToJoin); - - RequestedTeam rt; - rt.isTeamSwitch=true; - rt.requested=teamToJoin; - rt.teamToLeave=teamToLeave; - rt.whenRequested= MafiaNet::GetTime(); - rt.requestIndex=world->teamRequestIndex++; // In case whenRequested is the same between two teams when sorting team requests - teamsRequested.Push(rt, _FILE_AND_LINE_ ); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_TeamMember::RemoveFromRequestedTeams(TM_Team *team) -{ - if (team==0) - { - teamsRequested.Clear(true, _FILE_AND_LINE_); - joinTeamType=JOIN_NO_TEAM; - return true; - } - else - { - unsigned int i; - for (i=0; i < teamsRequested.Size(); i++) - { - if (teamsRequested[i].requested==team) - { - teamsRequested.RemoveAtIndex(i); - if (teamsRequested.Size()==0) - { - joinTeamType=JOIN_NO_TEAM; - } - return true; - } - } - } - return false; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_TeamMember::AddToTeamList(TM_Team *team) -{ - team->teamMembers.Push(this, _FILE_AND_LINE_ ); - teams.Push(team, _FILE_AND_LINE_ ); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_TeamMember::RemoveFromSpecificTeamInternal(TM_Team *team) -{ - unsigned int i,j; - for (i=0; i < teams.Size(); i++) - { - if (teams[i]==team) - { - for (j=0; j < team->teamMembers.Size(); j++) - { - if (team->teamMembers[j]==this) - { - team->teamMembers.RemoveAtIndex(j); - break; - } - } - teams.RemoveAtIndex(i); - break; - } - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_TeamMember::RemoveFromAllTeamsInternal(void) -{ - TM_Team *team; - unsigned int i,j; - for (i=0; i < teams.Size(); i++) - { - team = teams[i]; - - for (j=0; j < team->teamMembers.Size(); j++) - { - if (team->teamMembers[j]==this) - { - team->teamMembers.RemoveAtIndex(j); - break; - } - } - } - teams.Clear(true, _FILE_AND_LINE_); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_TeamMember::StoreLastTeams(void) -{ - lastTeams=teams; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_Team::TM_Team() -{ - ID=0; - world=0; - joinPermissions=ALLOW_JOIN_ANY_AVAILABLE_TEAM|ALLOW_JOIN_SPECIFIC_TEAM|ALLOW_JOIN_REBALANCING; - balancingApplies=true; - teamMemberLimit=65535; - owner=0; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_Team::~TM_Team() -{ - if (world) - world->DereferenceTeam(this, 0); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_Team::SetMemberLimit(TeamMemberLimit _teamMemberLimit, NoTeamId noTeamId) -{ - if (teamMemberLimit==_teamMemberLimit) - return false; - - teamMemberLimit=_teamMemberLimit; - // Network this as request to host - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_SetMemberLimit); - bsOut.Write(world->GetWorldId()); - bsOut.Write(GetNetworkID()); - bsOut.Write(teamMemberLimit); - bsOut.Write(noTeamId); - world->GetTeamManager()->Send(&bsOut, world->GetHost(), false); - - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TeamMemberLimit TM_Team::GetMemberLimit(void) const -{ - if (world->GetBalanceTeams()==false) - { - return teamMemberLimit; - } - else - { - TeamMemberLimit limitWithBalancing=world->GetBalancedTeamLimit(); - if (limitWithBalancing < teamMemberLimit) - return limitWithBalancing; - return teamMemberLimit; - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TeamMemberLimit TM_Team::GetMemberLimitSetting(void) const -{ - return teamMemberLimit; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_Team::SetJoinPermissions(JoinPermissions _joinPermissions) -{ - if (joinPermissions==_joinPermissions) - return false; - - joinPermissions=_joinPermissions; - - // Network this as request to host - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_SetJoinPermissions); - bsOut.Write(world->GetWorldId()); - bsOut.Write(GetNetworkID()); - bsOut.Write(_joinPermissions); - world->GetTeamManager()->Send(&bsOut,world->GetHost(), false); - - return true; - - -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -JoinPermissions TM_Team::GetJoinPermissions(void) const -{ - return joinPermissions; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_Team::LeaveTeam(TM_TeamMember* teamMember, NoTeamId noTeamSubcategory) -{ - teamMember->LeaveTeam(this, noTeamSubcategory); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_Team::GetBalancingApplies(void) const -{ - return balancingApplies; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_Team::GetTeamMembers(DataStructures::List &_teamMembers) const -{ - _teamMembers=teamMembers; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned int TM_Team::GetTeamMembersCount(void) const -{ - return teamMembers.Size(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_TeamMember *TM_Team::GetTeamMemberByIndex(unsigned int index) const -{ - return teamMembers[index]; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -NetworkID TM_Team::GetNetworkID(void) const -{ - return ID; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_World* TM_Team::GetTM_World(void) const -{ - return world; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_Team::SerializeConstruction(BitStream *constructionBitstream) -{ - // Do not need to serialize member lists, the team members do this - constructionBitstream->Write(world->GetWorldId()); - constructionBitstream->Write(ID); - constructionBitstream->Write(joinPermissions); - constructionBitstream->Write(balancingApplies); - constructionBitstream->Write(teamMemberLimit); - -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_Team::DeserializeConstruction(TeamManager *teamManager, BitStream *constructionBitstream) -{ - WorldId worldId; - constructionBitstream->Read(worldId); - TM_World *curWorld = teamManager->GetWorldWithId(worldId); - RakAssert(curWorld); - constructionBitstream->Read(ID); - constructionBitstream->Read(joinPermissions); - constructionBitstream->Read(balancingApplies); - bool b = constructionBitstream->Read(teamMemberLimit); - RakAssert(b); - if (b) - { - curWorld->ReferenceTeam(this,ID,balancingApplies); - } - return b; -} - - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned long TM_Team::ToUint32( const NetworkID &g ) -{ - return g & 0xFFFFFFFF; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void *TM_Team::GetOwner(void) const -{ - return owner; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - -unsigned int TM_Team::GetWorldIndex(void) const -{ - return world->GetTeamIndex(this); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_Team::SetOwner(void *o) -{ - owner=o; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_Team::RemoveFromTeamMemberList(TM_TeamMember *teamMember) -{ - unsigned int index = teamMembers.GetIndexOf(teamMember); - RakAssert(index != (unsigned int) -1); - teamMembers.RemoveAtIndex(index); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned int TM_Team::GetMemberWithRequestedSingleTeamSwitch(TM_Team *team) -{ - unsigned int i; - for (i=0; i < teamMembers.Size(); i++) - { - if (teamMembers[i]->GetCurrentTeamCount()==1) - { - unsigned int j = teamMembers[i]->GetRequestedTeamIndex(team); - if (j!=(unsigned int)-1) - { - if (teamMembers[i]->teamsRequested[j].isTeamSwitch && - (teamMembers[i]->teamsRequested[j].teamToLeave==0 || - teamMembers[i]->teamsRequested[j].teamToLeave==teamMembers[i]->teams[0]) - ) - return i; - } - } - } - return (unsigned int) -1; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_World::TM_World() -{ - teamManager=0; - balanceTeamsIsActive=false; - hostGuid=UNASSIGNED_RAKNET_GUID; - worldId=0; - autoAddParticipants=true; - teamRequestIndex=0; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_World::~TM_World() -{ - Clear(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TeamManager *TM_World::GetTeamManager(void) const -{ - return teamManager; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::AddParticipant(RakNetGUID rakNetGUID) -{ - participants.Push(rakNetGUID, _FILE_AND_LINE_ ); - - // Send to remote system status of balanceTeamsIsActive - - if (GetTeamManager()->GetMyGUIDUnified()==GetHost()) - { - // Actually just transmitting initial value of balanceTeamsIsActive - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_SetBalanceTeamsInitial); - bsOut.Write(GetWorldId()); - bsOut.Write(balanceTeamsIsActive); - teamManager->SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0,rakNetGUID, false); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::RemoveParticipant(RakNetGUID rakNetGUID) -{ - unsigned int i; - i = participants.GetIndexOf(rakNetGUID); - if (i!=(unsigned int)-1) - participants.RemoveAtIndex(i); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::SetAutoManageConnections(bool autoAdd) -{ - autoAddParticipants=autoAdd; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::GetParticipantList(DataStructures::List &participantList) -{ - participantList = participants; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::ReferenceTeam(TM_Team *team, NetworkID networkId, bool applyBalancing) -{ - unsigned int i; - for (i=0; i < teams.Size(); i++) - { - if (teams[i]==team) - return; - } - - team->ID=networkId; - team->balancingApplies=applyBalancing; - team->world=this; - - // Add this team to the list of teams - teams.Push(team, _FILE_AND_LINE_); - - teamsHash.Push(networkId,team,_FILE_AND_LINE_); - - // If autobalancing is on, and the team lock state supports it, then call EnforceTeamBalancing() - if (applyBalancing && balanceTeamsIsActive) - { - EnforceTeamBalance(0); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::DereferenceTeam(TM_Team *team, NoTeamId noTeamSubcategory) -{ - unsigned int i; - for (i=0; i < teams.Size(); i++) - { - if (teams[i]==team) - { - TM_Team *curTeam = teams[i]; - while (curTeam->teamMembers.Size()) - { - curTeam->teamMembers[curTeam->teamMembers.Size()-1]->LeaveTeam(curTeam, noTeamSubcategory); - } - teams.RemoveAtIndex(i); - - teamsHash.Remove(curTeam->GetNetworkID(),_FILE_AND_LINE_); - - break; - } - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned int TM_World::GetTeamCount(void) const -{ - return teams.Size(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_Team *TM_World::GetTeamByIndex(unsigned int index) const -{ - return teams[index]; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_Team *TM_World::GetTeamByNetworkID(NetworkID teamId) -{ - DataStructures::HashIndex hi = teamsHash.GetIndexOf(teamId); - if (hi.IsInvalid()) - return 0; - return teamsHash.ItemAtIndex(hi); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned int TM_World::GetTeamIndex(const TM_Team *team) const -{ - unsigned int i; - for (i=0; i < teams.Size(); i++) - { - if (teams[i]==team) - return i; - } - return (unsigned int) -1; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::ReferenceTeamMember(TM_TeamMember *teamMember, NetworkID networkId) -{ - unsigned int i; - for (i=0; i < teamMembers.Size(); i++) - { - if (teamMembers[i]==teamMember) - return; - } - - teamMember->world=this; - teamMember->networkId=networkId; - - teamMembers.Push(teamMember, _FILE_AND_LINE_); - - teamMembersHash.Push(networkId,teamMember,_FILE_AND_LINE_); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::DereferenceTeamMember(TM_TeamMember *teamMember) -{ - unsigned int i; - for (i=0; i < teamMembers.Size(); i++) - { - if (teamMembers[i]==teamMember) - { - teamMembers[i]->UpdateListsToNoTeam(0); - teamMembersHash.Remove(teamMembers[i]->GetNetworkID(),_FILE_AND_LINE_); - teamMembers.RemoveAtIndex(i); - break; - } - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned int TM_World::GetTeamMemberCount(void) const -{ - return teamMembers.Size(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_TeamMember *TM_World::GetTeamMemberByIndex(unsigned int index) const -{ - return teamMembers[index]; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -NetworkID TM_World::GetTeamMemberIDByIndex(unsigned int index) const -{ - return teamMembers[index]->GetNetworkID(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_TeamMember *TM_World::GetTeamMemberByNetworkID(NetworkID teamMemberId) -{ - DataStructures::HashIndex hi = teamMembersHash.GetIndexOf(teamMemberId); - if (hi.IsInvalid()) - return 0; - return teamMembersHash.ItemAtIndex(hi); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned int TM_World::GetTeamMemberIndex(const TM_TeamMember *teamMember) const -{ - unsigned int i; - for (i=0; i < teamMembers.Size(); i++) - { - if (teamMembers[i]==teamMember) - return i; - } - return (unsigned int) -1; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_World::SetBalanceTeams(bool balanceTeams, NoTeamId noTeamId) -{ - if (balanceTeams==balanceTeamsIsActive) - return false; - - balanceTeamsIsActive=balanceTeams; - - // Network this as request to host - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_SetBalanceTeams); - bsOut.Write(GetWorldId()); - bsOut.Write(balanceTeams); - bsOut.Write(noTeamId); - GetTeamManager()->SendUnified(&bsOut,MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, GetHost(), false); - - return true; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TM_World::GetBalanceTeams(void) const -{ - return balanceTeamsIsActive; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::SetHost(RakNetGUID _hostGuid) -{ - if (hostGuid==_hostGuid) - return; - - RakAssert(_hostGuid!=UNASSIGNED_RAKNET_GUID); - - hostGuid=_hostGuid; - - if (GetHost()==GetTeamManager()->GetMyGUIDUnified()) - FillRequestedSlots(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -RakNetGUID TM_World::GetHost(void) const -{ - return hostGuid; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -WorldId TM_World::GetWorldId(void) const -{ - return worldId; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::Clear(void) -{ - for (unsigned int i=0; i < teams.Size(); i++) - { - teams[i]->world=0; - } - for (unsigned int i=0; i < teamMembers.Size(); i++) - { - teamMembers[i]->world=0; - } - participants.Clear(true, _FILE_AND_LINE_); - teams.Clear(true, _FILE_AND_LINE_); - teamMembers.Clear(true, _FILE_AND_LINE_); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) lostConnectionReason; - (void) systemAddress; - - RemoveParticipant(rakNetGUID); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) -{ - (void) isIncoming; - (void) systemAddress; - - if (autoAddParticipants) - AddParticipant(rakNetGUID); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::EnforceTeamBalance(NoTeamId noTeamId) -{ - // Host only function - RakAssert(GetHost()==GetTeamManager()->GetMyGUIDUnified()); - - KickExcessMembers(noTeamId); -} - - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::KickExcessMembers(NoTeamId noTeamId) -{ - // Host only function - RakAssert(GetHost()==GetTeamManager()->GetMyGUIDUnified()); - - // For each team that applies balancing, if the team is overfull, put on a team that is not overfull if the team has ALLOW_JOIN_REBALANCING set - // If cannot move the player to another team, just take the player off the team and set to noTeamId if they have no team at that point - - TeamMemberLimit balancedTeamLimit; - if (balanceTeamsIsActive) - balancedTeamLimit = GetBalancedTeamLimit(); - else - balancedTeamLimit = (TeamMemberLimit) -1; - - TM_Team *team, *teamToJoin; - unsigned int i, teamIndex; - for (i=0; i < teams.Size(); i++) - { - team = teams[i]; - while (team->GetMemberLimitSetting() < team->GetTeamMembersCount() || - (balancedTeamLimit < team->GetTeamMembersCount() && team->GetBalancingApplies()) ) - { - TM_TeamMember *teamMember = team->teamMembers[team->teamMembers.Size()-1]; - - teamIndex = GetAvailableTeamIndexWithFewestMembers(balancedTeamLimit, ALLOW_JOIN_REBALANCING); - if (teamIndex == (unsigned int)-1) - { - // Move this member to no team - teamMember->LeaveTeam(team, noTeamId); - teamManager->PushTeamAssigned(teamMember); - } - else - { - teamToJoin = teams[teamIndex]; - - // Move this member - teamMember->StoreLastTeams(); - teamManager->RemoveFromTeamsRequestedAndAddTeam(teamMember, teamToJoin, true, team); - - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_RemoveFromTeamsRequestedAndAddTeam); - bsOut.Write(GetWorldId()); - bsOut.Write(teamMember->GetNetworkID()); - bsOut.Write(teamToJoin->GetNetworkID()); - bsOut.Write(true); - bsOut.Write(true); - bsOut.Write(team->GetNetworkID()); - BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); - } - - } - } -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::FillRequestedSlots(void) -{ - // Host only function - RakAssert(GetHost()==GetTeamManager()->GetMyGUIDUnified()); - - - TeamMemberLimit balancedTeamLimit; - if (balanceTeamsIsActive) - balancedTeamLimit = GetBalancedTeamLimit(); - else - balancedTeamLimit = (TeamMemberLimit) -1; - - unsigned int teamIndex, indexIntoTeamsRequested = (unsigned int)-1; - TM_Team *team; - TM_TeamMember *teamMember; - DataStructures::OrderedList joinRequests; - GetSortedJoinRequests(joinRequests); - unsigned int joinRequestIndex; - - for (joinRequestIndex=0; joinRequestIndex < joinRequests.Size(); joinRequestIndex++) - { - teamMember = teamMembers[joinRequests[joinRequestIndex].teamMemberIndex]; - if (teamMember->teamsRequested.Size()==0) - { - if (teamMember->joinTeamType==JOIN_ANY_AVAILABLE_TEAM) - teamIndex = GetAvailableTeamIndexWithFewestMembers(balancedTeamLimit, ALLOW_JOIN_ANY_AVAILABLE_TEAM); - else - teamIndex=(unsigned int)-1; - } - else - { - indexIntoTeamsRequested = joinRequests[joinRequestIndex].indexIntoTeamsRequested; - - team = teamMember->teamsRequested[indexIntoTeamsRequested].requested; - if (team->GetTeamMembersCount() < balancedTeamLimit && - team->GetTeamMembersCount() < team->GetMemberLimitSetting() && - (ALLOW_JOIN_SPECIFIC_TEAM & team->GetJoinPermissions())!=0) - { - teamIndex=teams.GetIndexOf(team); - } - else - { - teamIndex=(unsigned int)-1; - } - } - - if (teamIndex != (unsigned int)-1) - { - team = teams[teamIndex]; - - if (teamMember->teamsRequested.Size()==0) - { - if (teamMember->joinTeamType==JOIN_ANY_AVAILABLE_TEAM) - { - // Join any - teamMember->StoreLastTeams(); - teamMember->UpdateTeamsRequestedToNone(); - teamMember->AddToTeamList(teams[teamIndex]); - teamManager->PushTeamAssigned(teamMember); - - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_UpdateTeamsRequestedToNoneAndAddTeam); - bsOut.Write(GetWorldId()); - bsOut.Write(teamMember->GetNetworkID()); - bsOut.Write(team->GetNetworkID()); - BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); - } - } - else - { - // Switch or join specific - DataStructures::List teamsWeAreLeaving; - bool isSwitch = teamMember->teamsRequested[indexIntoTeamsRequested].isTeamSwitch; - TM_Team *teamToLeave; - if (isSwitch) - { - teamToLeave=teamMember->teamsRequested[indexIntoTeamsRequested].teamToLeave; - if (teamToLeave) - { - if (teamMember->IsOnTeam(teamToLeave)) - { - teamsWeAreLeaving.Push(teamToLeave, _FILE_AND_LINE_); - } - else - { - teamToLeave=0; - isSwitch=false; - } - } - else - { - teamsWeAreLeaving=teamMember->teams; - } - } - else - teamToLeave=0; - - int teamJoined = JoinSpecificTeam(teamMember, team, isSwitch, teamToLeave, teamsWeAreLeaving); - - if (teamJoined==1) - { - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_RemoveFromTeamsRequestedAndAddTeam); - bsOut.Write(GetWorldId()); - bsOut.Write(teamMember->GetNetworkID()); - bsOut.Write(team->GetNetworkID()); - bsOut.Write(isSwitch); - if (teamToLeave!=0) - { - bsOut.Write(true); - bsOut.Write(teamToLeave->GetNetworkID()); - } - else - bsOut.Write(false); - BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); - } - } - } - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned int TM_World::GetAvailableTeamIndexWithFewestMembers(TeamMemberLimit secondaryLimit, JoinPermissions joinPermissions) -{ - unsigned int teamIndex; - - unsigned int lowestTeamMembers = (unsigned int) -1; - unsigned int lowestIndex = (unsigned int) -1; - - for (teamIndex=0; teamIndex < teams.Size(); teamIndex++) - { - if (teams[teamIndex]->GetTeamMembersCount() < secondaryLimit && - teams[teamIndex]->GetTeamMembersCount() < teams[teamIndex]->GetMemberLimitSetting() && - teams[teamIndex]->GetTeamMembersCount() < lowestTeamMembers && - (joinPermissions & teams[teamIndex]->GetJoinPermissions())!=0) - { - lowestTeamMembers = teams[teamIndex]->GetTeamMembersCount(); - lowestIndex = teamIndex; - } - } - - return lowestIndex; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::GetSortedJoinRequests(DataStructures::OrderedList &joinRequests) -{ - unsigned int i; - - for (i=0; i < teamMembers.Size(); i++) - { - TM_TeamMember *teamMember = teamMembers[i]; - if (teamMember->teamsRequested.Size()==0) - { - if (teamMember->joinTeamType==JOIN_ANY_AVAILABLE_TEAM) - { - TM_World::JoinRequestHelper jrh; - jrh.whenRequestMade=teamMember->whenJoinAnyRequested; - jrh.teamMemberIndex=i; - jrh.requestIndex=teamMember->joinAnyRequestIndex; - joinRequests.Insert(jrh, jrh, true, _FILE_AND_LINE_); - } - } - else - { - unsigned int j; - for (j=0; j < teamMember->teamsRequested.Size(); j++) - { - TM_World::JoinRequestHelper jrh; - jrh.whenRequestMade=teamMember->teamsRequested[j].whenRequested; - jrh.teamMemberIndex=i; - jrh.indexIntoTeamsRequested=j; - jrh.requestIndex=teamMember->teamsRequested[j].requestIndex; - joinRequests.Insert(jrh, jrh, true, _FILE_AND_LINE_); - } - - } - } -} -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::BroadcastToParticipants(MafiaNet::BitStream *bsOut, RakNetGUID exclusionGuid) -{ - for (unsigned int i=0; i < participants.Size(); i++) - { - if (participants[i]==exclusionGuid) - continue; - teamManager->SendUnified(bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, participants[i], false); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TM_World::BroadcastToParticipants(unsigned char *data, const int length, RakNetGUID exclusionGuid) -{ - for (unsigned int i=0; i < participants.Size(); i++) - { - if (participants[i]==exclusionGuid) - continue; - teamManager->SendUnified((const char*) data, length, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, participants[i], false); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_Team* TM_World::JoinAnyTeam(TM_TeamMember *teamMember, int *resultCode) -{ - TeamMemberLimit balancedLimit = GetBalancedTeamLimit(); - - unsigned int idx = GetAvailableTeamIndexWithFewestMembers(balancedLimit, ALLOW_JOIN_ANY_AVAILABLE_TEAM); - if (idx == (unsigned int ) -1) - { - // If any team is joinable but full, return full. Otherwise return locked - for (idx=0; idx < teams.Size(); idx++) - { - if ((teams[idx]->GetTeamMembersCount() >= balancedLimit || - teams[idx]->GetTeamMembersCount() >= teams[idx]->GetMemberLimitSetting()) && - teams[idx]->GetMemberLimitSetting() != 0 && - (ALLOW_JOIN_ANY_AVAILABLE_TEAM & teams[idx]->GetJoinPermissions())!=0) - { - // Full - *resultCode=-2; - return teams[idx]; - } - } - - // Locked - *resultCode=-1; - return 0; - } - - TM_Team* lowestMemberTeam = teams[idx]; - - teamMember->StoreLastTeams(); - teamMember->UpdateTeamsRequestedToNone(); - teamMember->AddToTeamList(lowestMemberTeam); - teamManager->PushTeamAssigned(teamMember); - - *resultCode=1; - return lowestMemberTeam; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -int TM_World::JoinSpecificTeam(TM_TeamMember *teamMember, TM_Team *team, bool isTeamSwitch, TM_Team *teamToLeave, DataStructures::List &teamsWeAreLeaving) -{ - if (team->GetJoinPermissions() & ALLOW_JOIN_SPECIFIC_TEAM) - { - if (balanceTeamsIsActive==false || teamsWeAreLeaving.Size()==0) - { - if (team->GetMemberLimit() > team->GetTeamMembersCount()) - { - // Can join normally - teamMember->StoreLastTeams(); - teamManager->RemoveFromTeamsRequestedAndAddTeam(teamMember, team, isTeamSwitch, teamToLeave); - return 1; - } - else - { - // Full - return -2; - } - } - else - { - // Note: balanceTeamsIsActive==true && isTeamSwitch==true - - // Do limited team swap - // We must be on one team, target must be on one team, and we want to exchange teams - if (teamsWeAreLeaving.Size()==1) - { - unsigned int j = team->GetMemberWithRequestedSingleTeamSwitch(teamsWeAreLeaving[0]); - if (j!=(unsigned int)-1) - { - TM_TeamMember *swappingMember = team->teamMembers[j]; - teamMember->StoreLastTeams(); - swappingMember->StoreLastTeams(); - teamManager->RemoveFromTeamsRequestedAndAddTeam(teamMember, team, true, 0); - teamManager->RemoveFromTeamsRequestedAndAddTeam(swappingMember, teamsWeAreLeaving[0], true, 0); - - // Send ID_TEAM_BALANCER_TEAM_ASSIGNED to all, for swapped member - // Calling function sends ID_RUN_RemoveFromTeamsRequestedAndAddTeam which pushes ID_TEAM_BALANCER_TEAM_ASSIGNED for teamMember - MafiaNet::BitStream bitStream; - bitStream.WriteCasted(ID_TEAM_BALANCER_TEAM_ASSIGNED); - teamManager->EncodeTeamAssigned(&bitStream, swappingMember); - BroadcastToParticipants(&bitStream, UNASSIGNED_RAKNET_GUID); - - return 1; - } - } - - // Full - return -2; - } - } - else - { - // Locked - return -1; - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TeamMemberLimit TM_World::GetBalancedTeamLimit(void) const -{ - if (teams.Size()==0) - return 0; - - if (balanceTeamsIsActive==false) - return (TeamMemberLimit) -1; - - unsigned int i; - bool additionalTeamsExcluded; - TeamMemberLimit balancedLimit; - unsigned int teamsCount=teams.Size(); - unsigned int membersCount=teamMembers.Size(); - DataStructures::List consideredTeams = teams; - - do - { - additionalTeamsExcluded=false; - balancedLimit = (TeamMemberLimit) ((membersCount+(teamsCount-1))/(teamsCount)); - i=0; - while (i < consideredTeams.Size()) - { - if (consideredTeams[i]->GetMemberLimitSetting() < balancedLimit) - { - additionalTeamsExcluded=true; - membersCount-=consideredTeams[i]->GetMemberLimitSetting(); - teamsCount--; - consideredTeams.RemoveAtIndexFast(i); - } - else - { - i++; - } - } - - } while (additionalTeamsExcluded==true && teamsCount>0); - - return balancedLimit; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TeamManager::TeamManager() -{ - for (unsigned int i=0; i < 255; i++) - worldsArray[i]=0; - autoAddParticipants=true; - topology=TM_PEER_TO_PEER; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TeamManager::~TeamManager() -{ - Clear(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_World* TeamManager::AddWorld(WorldId worldId) -{ - RakAssert(worldsArray[worldId]==0 && "World already in use"); - - TM_World *newWorld = MafiaNet::OP_NEW(_FILE_AND_LINE_); - newWorld->worldId=worldId; - newWorld->teamManager=this; - newWorld->hostGuid=GetMyGUIDUnified(); - worldsArray[worldId]=newWorld; - worldsList.Push(newWorld,_FILE_AND_LINE_); - return newWorld; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::RemoveWorld(WorldId worldId) -{ - RakAssert(worldsArray[worldId]!=0 && "World not in use"); - for (unsigned int i=0; i < worldsList.Size(); i++) - { - if (worldsList[i]==worldsArray[worldId]) - { - MafiaNet::OP_DELETE(worldsList[i],_FILE_AND_LINE_); - worldsList.RemoveAtIndexFast(i); - break; - } - } - worldsArray[worldId]=0; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -unsigned int TeamManager::GetWorldCount(void) const -{ - return worldsList.Size(); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_World* TeamManager::GetWorldAtIndex(unsigned int index) const -{ - return worldsList[index]; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -TM_World* TeamManager::GetWorldWithId(WorldId worldId) const -{ - return worldsArray[worldId]; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::SetAutoManageConnections(bool autoAdd) -{ - autoAddParticipants=autoAdd; - - for (unsigned int i=0; i < worldsList.Size(); i++) - { - worldsList[i]->SetAutoManageConnections(autoAdd); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::SetTopology(TMTopology _topology) -{ - topology=_topology; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::EncodeTeamFull(MafiaNet::BitStream *bitStream, TM_TeamMember *teamMember, TM_Team *team) -{ - bitStream->WriteCasted(ID_TEAM_BALANCER_REQUESTED_TEAM_FULL); - EncodeTeamFullOrLocked(bitStream, teamMember, team); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::DecomposeTeamFull(Packet *packet, - TM_World **world, TM_TeamMember **teamMember, TM_Team **team, - uint16_t ¤tMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions) -{ - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(sizeof(MessageID)); - DecomposeTeamFullOrLocked(&bsIn, world, teamMember, team, currentMembers, memberLimitIncludingBalancing, balancingIsActive, joinPermissions); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::EncodeTeamLocked(MafiaNet::BitStream *bitStream, TM_TeamMember *teamMember, TM_Team *team) -{ - bitStream->WriteCasted(ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED); - EncodeTeamFullOrLocked(bitStream, teamMember, team); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::EncodeTeamFullOrLocked(MafiaNet::BitStream *bitStream, TM_TeamMember *teamMember, TM_Team *team) -{ - bitStream->Write(teamMember->world->GetWorldId()); - bitStream->Write(teamMember->GetNetworkID()); - bitStream->Write(team->GetNetworkID()); - bitStream->WriteCasted(team->GetTeamMembersCount()); - bitStream->Write(team->GetMemberLimit()); - bitStream->Write(team->GetBalancingApplies()); - bitStream->Write(team->GetJoinPermissions()); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::DecomposeTeamFullOrLocked(MafiaNet::BitStream *bsIn, TM_World **world, TM_TeamMember **teamMember, TM_Team **team, - uint16_t ¤tMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions) -{ - WorldId worldId; - NetworkID teamMemberId; - NetworkID teamId; - - *teamMember=0; - *team=0; - *world=0; - - bsIn->Read(worldId); - bsIn->Read(teamMemberId); - bsIn->Read(teamId); - bsIn->Read(currentMembers); - bsIn->Read(memberLimitIncludingBalancing); - bsIn->Read(balancingIsActive); - bsIn->Read(joinPermissions); - - *world = GetWorldWithId(worldId); - if (*world) - { - *teamMember = (*world)->GetTeamMemberByNetworkID(teamMemberId); - *team = (*world)->GetTeamByNetworkID(teamId); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::DecomposeTeamLocked(Packet *packet, - TM_World **world, TM_TeamMember **teamMember, TM_Team **team, - uint16_t ¤tMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions) -{ - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(sizeof(MessageID)); - DecomposeTeamFullOrLocked(&bsIn, world, teamMember, team, currentMembers, memberLimitIncludingBalancing, balancingIsActive, joinPermissions); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::EncodeTeamAssigned(MafiaNet::BitStream *bitStream, TM_TeamMember *teamMember) -{ - bitStream->Write(teamMember->world->GetWorldId()); - bitStream->Write(teamMember->GetNetworkID()); - bitStream->WriteCasted(teamMember->teams.Size()); - for (unsigned int i=0; i < teamMember->teams.Size(); i++) - { - bitStream->Write(teamMember->teams[i]->GetNetworkID()); - } - bitStream->Write(teamMember->noTeamSubcategory); - bitStream->Write(teamMember->joinTeamType); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::ProcessTeamAssigned(MafiaNet::BitStream *bsIn) -{ - TM_World *world; - TM_TeamMember *teamMember; - NoTeamId noTeamId; - JoinTeamType joinTeamType; - DataStructures::List newTeam; - DataStructures::List teamsLeft; - DataStructures::List teamsJoined; - DecodeTeamAssigned(bsIn, &world, &teamMember, noTeamId, joinTeamType, newTeam, teamsLeft, teamsJoined); - if (teamMember) - { - teamMember->StoreLastTeams(); - for (unsigned int i=0; i < teamsLeft.Size(); i++) - { - teamMember->RemoveFromSpecificTeamInternal(teamsLeft[i]); - } - for (unsigned int i=0; i < teamsJoined.Size(); i++) - { - if (teamMember->IsOnTeam(teamsJoined[i])==false) - { - teamMember->RemoveFromRequestedTeams(teamsJoined[i]); - teamMember->AddToTeamList(teamsJoined[i]); - } - } - teamMember->noTeamSubcategory=noTeamId; - teamMember->joinTeamType=joinTeamType; - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::DecodeTeamAssigned(Packet *packet, TM_World **world, TM_TeamMember **teamMember) -{ - WorldId worldId; - NetworkID teamMemberId; - - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)); - bsIn.Read(worldId); - bsIn.Read(teamMemberId); - *world = GetWorldWithId(worldId); - if (*world) - { - *teamMember = (*world)->GetTeamMemberByNetworkID(teamMemberId); - } - else - { - *teamMember=0; - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::DecodeTeamCancelled(Packet *packet, TM_World **world, TM_TeamMember **teamMember, TM_Team **teamCancelled) -{ - WorldId worldId; - NetworkID teamMemberId; - - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)); - bsIn.Read(worldId); - bsIn.Read(teamMemberId); - bool sp=false; - *world = GetWorldWithId(worldId); - if (*world) - { - *teamMember = (*world)->GetTeamMemberByNetworkID(teamMemberId); - } - else - { - *teamMember=0; - } - - bsIn.Read(sp); - if (sp) - { - NetworkID nid; - bsIn.Read(nid); - *teamCancelled = (*world)->GetTeamByNetworkID(nid); - } - else - { - *teamCancelled = 0; - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::DecodeTeamAssigned(BitStream *bsIn, TM_World **world, TM_TeamMember **teamMember, NoTeamId &noTeamId, - JoinTeamType &joinTeamType, DataStructures::List &newTeam, - DataStructures::List &teamsLeft, DataStructures::List &teamsJoined - ) -{ - newTeam.Clear(true, _FILE_AND_LINE_); - teamsLeft.Clear(true, _FILE_AND_LINE_); - teamsJoined.Clear(true, _FILE_AND_LINE_); - - WorldId worldId; - NetworkID teamMemberId; - NetworkID teamId; - - bsIn->Read(worldId); - bsIn->Read(teamMemberId); - *world = GetWorldWithId(worldId); - if (*world) - { - *teamMember = (*world)->GetTeamMemberByNetworkID(teamMemberId); - uint16_t teamsCount; - bsIn->Read(teamsCount); - - for (unsigned int i=0; i < teamsCount; i++) - { - bsIn->Read(teamId); - TM_Team * team = (*world)->GetTeamByNetworkID(teamId); - RakAssert(team); - if (team) - newTeam.Push(team, _FILE_AND_LINE_); - // else probably didn't reference team first - } - - if (*teamMember) - { - for (unsigned int i=0; i < (*teamMember)->teams.Size(); i++) - { - TM_Team *team = (*teamMember)->teams[i]; - if (newTeam.GetIndexOf(team)==(unsigned int)-1) - teamsLeft.Push(team, _FILE_AND_LINE_); - } - } - - for (unsigned int i=0; i < newTeam.Size(); i++) - { - TM_Team *team = newTeam[i]; - if ((*teamMember)->teams.GetIndexOf(team)==(unsigned int)-1) - teamsJoined.Push(team, _FILE_AND_LINE_); - } - - bsIn->Read(noTeamId); - bsIn->Read(joinTeamType); - } - else - { - *teamMember=0; - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::Clear(void) -{ - for (unsigned int i=0; i < worldsList.Size(); i++) - { - worldsArray[worldsList[i]->worldId]=0; - worldsList[i]->Clear(); - MafiaNet::OP_DELETE(worldsList[i], _FILE_AND_LINE_); - } - worldsList.Clear(false, _FILE_AND_LINE_); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::Update(void) -{ -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -PluginReceiveResult TeamManager::OnReceive(Packet *packet) -{ - switch (packet->data[0]) - { - case ID_FCM2_NEW_HOST: - { - unsigned int i; - for (i=0; i < worldsList.Size(); i++) - worldsList[i]->SetHost(packet->guid); - } - break; - case ID_TEAM_BALANCER_TEAM_ASSIGNED: - { - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(sizeof(MessageID)); - - ProcessTeamAssigned(&bsIn); - } - break; - case ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED: - { - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(1); - WorldId worldId; - bsIn.Read(worldId); - TM_World *world = GetWorldWithId(worldId); - if (world==0) - return RR_STOP_PROCESSING_AND_DEALLOCATE; - bool validPacket = OnRemoveFromRequestedTeams(packet, world); - if (validPacket==false) - return RR_STOP_PROCESSING_AND_DEALLOCATE; - break; - } - case ID_TEAM_BALANCER_INTERNAL: - { - if (packet->length>=2) - { - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2); - WorldId worldId; - bsIn.Read(worldId); - TM_World *world = GetWorldWithId(worldId); - if (world==0) - return RR_STOP_PROCESSING_AND_DEALLOCATE; - - switch (packet->data[1]) - { - case ID_RUN_UpdateListsToNoTeam: - OnUpdateListsToNoTeam(packet, world); - break; - case ID_RUN_UpdateTeamsRequestedToAny: - OnUpdateTeamsRequestedToAny(packet, world); - break; - case ID_RUN_JoinAnyTeam: - OnJoinAnyTeam(packet, world); - break; - case ID_RUN_JoinRequestedTeam: - OnJoinRequestedTeam(packet, world); - break; - case ID_RUN_UpdateTeamsRequestedToNoneAndAddTeam: - OnUpdateTeamsRequestedToNoneAndAddTeam(packet, world); - break; - case ID_RUN_RemoveFromTeamsRequestedAndAddTeam: - OnRemoveFromTeamsRequestedAndAddTeam(packet, world); - break; - case ID_RUN_AddToRequestedTeams: - OnAddToRequestedTeams(packet, world); - break; - case ID_RUN_LeaveTeam: - OnLeaveTeam(packet, world); - break; - case ID_RUN_SetMemberLimit: - OnSetMemberLimit(packet, world); - break; - case ID_RUN_SetJoinPermissions: - OnSetJoinPermissions(packet, world); - break; - case ID_RUN_SetBalanceTeams: - OnSetBalanceTeams(packet, world); - break; - case ID_RUN_SetBalanceTeamsInitial: - OnSetBalanceTeamsInitial(packet, world); - break; - } - } - } - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - - return RR_CONTINUE_PROCESSING; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - for (unsigned int i=0; i < worldsList.Size(); i++) - { - worldsList[i]->OnClosedConnection(systemAddress, rakNetGUID, lostConnectionReason); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) -{ - for (unsigned int i=0; i < worldsList.Size(); i++) - { - worldsList[i]->OnNewConnection(systemAddress, rakNetGUID, isIncoming); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::Send( const MafiaNet::BitStream * bitStream, const AddressOrGUID systemIdentifier, bool broadcast ) -{ - SendUnified(bitStream,MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, systemIdentifier, broadcast); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::RemoveFromTeamsRequestedAndAddTeam(TM_TeamMember *teamMember, TM_Team *team, bool isTeamSwitch, TM_Team *teamToLeave) -{ - teamMember->RemoveFromRequestedTeams(team); - if (isTeamSwitch) - { - if (teamToLeave==0) - { - // Leave all teams - teamMember->RemoveFromAllTeamsInternal(); - } - else - { - // Leave specific team if it exists - teamMember->RemoveFromSpecificTeamInternal(teamToLeave); - } - } - teamMember->AddToTeamList(team); - PushTeamAssigned(teamMember); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::PushTeamAssigned(TM_TeamMember *teamMember) -{ - // Push ID_TEAM_BALANCER_TEAM_ASSIGNED locally - MafiaNet::BitStream bitStream; - bitStream.WriteCasted(ID_TEAM_BALANCER_TEAM_ASSIGNED); - EncodeTeamAssigned(&bitStream, teamMember); - - PushBitStream(&bitStream); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::PushBitStream(MafiaNet::BitStream *bitStream) -{ - Packet *p = AllocatePacketUnified(bitStream->GetNumberOfBytesUsed()); - memcpy(p->data, bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); - p->systemAddress=UNASSIGNED_SYSTEM_ADDRESS; - p->systemAddress.systemIndex=(SystemIndex)-1; - p->guid=UNASSIGNED_RAKNET_GUID; - p->wasGeneratedLocally=true; - PushBackPacketUnified(p, true); -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::OnUpdateListsToNoTeam(Packet *packet, TM_World *world) -{ - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2+sizeof(WorldId)); - NetworkID networkId; - bsIn.Read(networkId); - TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); - NoTeamId noTeamId; - bsIn.Read(noTeamId); - if (teamMember) - { - teamMember->StoreLastTeams(); - teamMember->UpdateListsToNoTeam(noTeamId); - PushTeamAssigned(teamMember); - - if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()) - { - world->FillRequestedSlots(); - world->EnforceTeamBalance(noTeamId); - - if (topology==TM_CLIENT_SERVER) - { - // Relay - world->BroadcastToParticipants(packet->data, packet->length, packet->guid); - } - } - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::OnUpdateTeamsRequestedToAny(Packet *packet, TM_World *world) -{ - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2+sizeof(WorldId)); - NetworkID networkId; - bsIn.Read(networkId); - TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); - if (teamMember) - { - teamMember->UpdateTeamsRequestedToAny(); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::OnJoinAnyTeam(Packet *packet, TM_World *world) -{ - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2+sizeof(WorldId)); - NetworkID networkId; - bsIn.Read(networkId); - TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); - if (teamMember) - { - // This is a host-only operation - RakAssert(world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()); - - teamMember->UpdateTeamsRequestedToAny(); - - int resultCode; - TM_Team *newTeam = world->JoinAnyTeam(teamMember, &resultCode); - - if (resultCode==1) - { - // Broadcast packet - remote systems should clear requested teams to none, and add the team we joined. - // Broadcast includes non-host sender (all participants) - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_UpdateTeamsRequestedToNoneAndAddTeam); - bsOut.Write(world->GetWorldId()); - bsOut.Write(networkId); - bsOut.Write(newTeam->GetNetworkID()); - world->BroadcastToParticipants(&bsOut, packet->guid); - - // Send to sender ID_TEAM_BALANCER_TEAM_ASSIGNED - if (packet->guid!=GetMyGUIDUnified()) - { - MafiaNet::BitStream bitStream; - bitStream.WriteCasted(ID_TEAM_BALANCER_TEAM_ASSIGNED); - EncodeTeamAssigned(&bitStream, teamMember); - SendUnified(&bitStream, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, packet->guid, false); - } - } - else - { - // Relay packet to set requested teams to any - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_UpdateTeamsRequestedToAny); - bsOut.Write(world->GetWorldId()); - bsOut.Write(networkId); - world->BroadcastToParticipants(&bsOut, packet->guid); - - bsOut.Reset(); - if (resultCode==-2) - { - EncodeTeamFull(&bsOut, teamMember, newTeam); - } - else if (resultCode==-1) - { - EncodeTeamLocked(&bsOut, teamMember, newTeam); - } - // SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, packet->guid, false); - world->BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); - if (packet->guid!=GetMyGUIDUnified()) - PushBitStream(&bsOut); - } - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::OnJoinRequestedTeam(Packet *packet, TM_World *world) -{ - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2+sizeof(WorldId)); - NetworkID networkId; - bsIn.Read(networkId); - TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); - NetworkID teamToJoinNetworkId; - bsIn.Read(teamToJoinNetworkId); - TM_Team *teamToJoin = world->GetTeamByNetworkID(teamToJoinNetworkId); - bool isTeamSwitch=false; - bool switchSpecificTeam=false; - NetworkID teamToLeaveNetworkId=UNASSIGNED_NETWORK_ID; - TM_Team *teamToLeave=0; - bsIn.Read(isTeamSwitch); - if (isTeamSwitch) - { - bsIn.Read(switchSpecificTeam); - if (switchSpecificTeam) - { - bsIn.Read(teamToLeaveNetworkId); - teamToLeave = world->GetTeamByNetworkID(teamToLeaveNetworkId); - if (teamToLeave==0) - isTeamSwitch=false; - } - } - if (teamToJoin && teamMember) - { - if (isTeamSwitch) - { - if (teamMember->SwitchSpecificTeamCheck(teamToJoin, teamToLeave, packet->guid==GetMyGUIDUnified())==false) - return; - - teamMember->AddToRequestedTeams(teamToJoin, teamToLeave); - } - else - { - if (teamMember->JoinSpecificTeamCheck(teamToJoin, packet->guid==GetMyGUIDUnified())==false) - return; - - teamMember->AddToRequestedTeams(teamToJoin); - } - - DataStructures::List teamsWeAreLeaving; - if (isTeamSwitch) - { - if (teamToLeave==0) - { - teamsWeAreLeaving=teamMember->teams; - } - else - { - if (teamMember->IsOnTeam(teamToLeave)) - teamsWeAreLeaving.Push(teamToLeave, _FILE_AND_LINE_); - } - - if (teamsWeAreLeaving.Size()==0) - isTeamSwitch=false; - } - - int resultCode = world->JoinSpecificTeam(teamMember, teamToJoin, isTeamSwitch, teamToLeave, teamsWeAreLeaving); - - if (resultCode==1) - { - // Broadcast packet - remote systems should remove from requested teams and add the team we joined. - // Broadcast includes non-host sender (all participants) - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_RemoveFromTeamsRequestedAndAddTeam); - bsOut.Write(world->GetWorldId()); - bsOut.Write(networkId); - bsOut.Write(teamToJoin->GetNetworkID()); - bsOut.Write(isTeamSwitch); - if (isTeamSwitch) - { - bsOut.Write(switchSpecificTeam); - if (switchSpecificTeam) - bsOut.Write(teamToLeaveNetworkId); - } - world->BroadcastToParticipants(&bsOut, packet->guid); - - // Send to sender ID_TEAM_BALANCER_TEAM_ASSIGNED - if (packet->guid!=GetMyGUIDUnified()) - { - MafiaNet::BitStream bitStream; - bitStream.WriteCasted(ID_TEAM_BALANCER_TEAM_ASSIGNED); - EncodeTeamAssigned(&bitStream, teamMember); - SendUnified(&bitStream, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, packet->guid, false); - } - } - else - { - // Relay packet to set requested teams to any - BitStream bsOut; - bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); - bsOut.WriteCasted(ID_RUN_AddToRequestedTeams); - bsOut.Write(world->GetWorldId()); - bsOut.Write(networkId); - bsOut.Write(teamToJoin->GetNetworkID()); - bsOut.Write(isTeamSwitch); - if (isTeamSwitch) - { - bsOut.Write(switchSpecificTeam); - if (switchSpecificTeam) - bsOut.Write(teamToLeaveNetworkId); - } - world->BroadcastToParticipants(&bsOut, packet->guid); - - bsOut.Reset(); - if (resultCode==-2) - { - EncodeTeamFull(&bsOut, teamMember, teamToJoin); - } - else if (resultCode==-1) - { - EncodeTeamLocked(&bsOut, teamMember, teamToJoin); - } - // SendUnified(&bsOut, MafiaNet::Priority::High, MafiaNet::Reliability::ReliableOrdered, 0, packet->guid, false); - - world->BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); - if (packet->guid!=GetMyGUIDUnified()) - PushBitStream(&bsOut); - } - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::OnUpdateTeamsRequestedToNoneAndAddTeam(Packet *packet, TM_World *world) -{ - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2+sizeof(WorldId)); - NetworkID networkId; - bsIn.Read(networkId); - TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); - NetworkID teamNetworkId; - bsIn.Read(teamNetworkId); - TM_Team *team = world->GetTeamByNetworkID(teamNetworkId); - - if (team && teamMember) - { - teamMember->StoreLastTeams(); - teamMember->UpdateTeamsRequestedToNone(); - teamMember->AddToTeamList(team); - world->GetTeamManager()->PushTeamAssigned(teamMember); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::OnRemoveFromTeamsRequestedAndAddTeam(Packet *packet, TM_World *world) -{ - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2+sizeof(WorldId)); - NetworkID networkId; - bsIn.Read(networkId); - TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); - NetworkID teamNetworkId; - bsIn.Read(teamNetworkId); - bool isTeamSwitch=false, switchSpecificTeam=false; - NetworkID teamToLeaveNetworkId; - TM_Team *teamToLeave=0; - bsIn.Read(isTeamSwitch); - if (isTeamSwitch) - { - bsIn.Read(switchSpecificTeam); - if (switchSpecificTeam) - { - bsIn.Read(teamToLeaveNetworkId); - teamToLeave = world->GetTeamByNetworkID(teamToLeaveNetworkId); - } - } - - TM_Team *team = world->GetTeamByNetworkID(teamNetworkId); - if (team && teamMember) - { - teamMember->StoreLastTeams(); - if (teamToLeave) - teamMember->RemoveFromSpecificTeamInternal(teamToLeave); - else if (isTeamSwitch==true && switchSpecificTeam==false) - teamMember->RemoveFromAllTeamsInternal(); - RemoveFromTeamsRequestedAndAddTeam(teamMember, team, false, 0); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::OnAddToRequestedTeams(Packet *packet, TM_World *world) -{ - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2+sizeof(WorldId)); - NetworkID networkId; - bsIn.Read(networkId); - TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); - NetworkID teamNetworkId; - bsIn.Read(teamNetworkId); - TM_Team *team = world->GetTeamByNetworkID(teamNetworkId); - - bool isTeamSwitch=false; - bool switchSpecificTeam=false; - NetworkID teamToLeaveNetworkId=UNASSIGNED_NETWORK_ID; - TM_Team *teamToLeave=0; - bsIn.Read(isTeamSwitch); - if (isTeamSwitch) - { - bsIn.Read(switchSpecificTeam); - if (switchSpecificTeam) - { - bsIn.Read(teamToLeaveNetworkId); - teamToLeave = world->GetTeamByNetworkID(teamToLeaveNetworkId); - if (teamToLeave==0) - isTeamSwitch=false; - } - } - - if (team && teamMember) - { - if (isTeamSwitch) - teamMember->AddToRequestedTeams(team, teamToLeave); - else - teamMember->AddToRequestedTeams(team); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -bool TeamManager::OnRemoveFromRequestedTeams(Packet *packet, TM_World *world) -{ - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(1+sizeof(WorldId)); - NetworkID networkId; - bsIn.Read(networkId); - TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); - bool hasSpecificTeam=false; - NetworkID teamNetworkId; - TM_Team *team; - bsIn.Read(hasSpecificTeam); - if (hasSpecificTeam) - { - bsIn.Read(teamNetworkId); - team = world->GetTeamByNetworkID(teamNetworkId); - if (team==0) - return false; - } - else - { - team=0; - } - - if (teamMember) - { - teamMember->RemoveFromRequestedTeams(team); - - // Relay as host - if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified() && topology==TM_CLIENT_SERVER) - { - world->BroadcastToParticipants(packet->data, packet->length, packet->guid); - } - return true; - } - else - { - return false; - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::OnLeaveTeam(Packet *packet, TM_World *world) -{ - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2+sizeof(WorldId)); - NetworkID networkId; - bsIn.Read(networkId); - TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); - NetworkID teamNetworkId; - bsIn.Read(teamNetworkId); - TM_Team *team = world->GetTeamByNetworkID(teamNetworkId); - NoTeamId noTeamId; - bsIn.Read(noTeamId); - - if (team && teamMember) - { - if (teamMember->LeaveTeamCheck(team)==false) - return; - - teamMember->StoreLastTeams(); - teamMember->RemoveFromSpecificTeamInternal(team); - if (teamMember->GetCurrentTeamCount()==0) - { - teamMember->noTeamSubcategory=noTeamId; - teamMember->joinTeamType=JOIN_NO_TEAM; - } - PushTeamAssigned(teamMember); - - if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()) - { - // Rebalance teams - world->FillRequestedSlots(); - world->EnforceTeamBalance(noTeamId); - - // Relay as host - if (topology==TM_CLIENT_SERVER) - world->BroadcastToParticipants(packet->data, packet->length, packet->guid); - } - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::OnSetMemberLimit(Packet *packet, TM_World *world) -{ - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2+sizeof(WorldId)); - NetworkID teamNetworkId; - bsIn.Read(teamNetworkId); - TeamMemberLimit teamMemberLimit; - NoTeamId noTeamId; - bsIn.Read(teamMemberLimit); - bsIn.Read(noTeamId); - - TM_Team *team = world->GetTeamByNetworkID(teamNetworkId); - if (team) - { - team->teamMemberLimit=teamMemberLimit; - - if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()) - { - if (packet->guid==GetMyGUIDUnified()) - world->BroadcastToParticipants(packet->data, packet->length, packet->guid); - else - world->BroadcastToParticipants(packet->data, packet->length, UNASSIGNED_RAKNET_GUID); - world->FillRequestedSlots(); - world->KickExcessMembers(noTeamId); - } - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::OnSetJoinPermissions(Packet *packet, TM_World *world) -{ - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2+sizeof(WorldId)); - NetworkID teamNetworkId; - bsIn.Read(teamNetworkId); - JoinPermissions joinPermissions; - bsIn.Read(joinPermissions); - - TM_Team *team = world->GetTeamByNetworkID(teamNetworkId); - if (team) - { - team->joinPermissions=joinPermissions; - - if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()) - { - if (packet->guid==GetMyGUIDUnified()) - world->BroadcastToParticipants(packet->data, packet->length, packet->guid); - else - world->BroadcastToParticipants(packet->data, packet->length, UNASSIGNED_RAKNET_GUID); - world->FillRequestedSlots(); - } - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::OnSetBalanceTeams(Packet *packet, TM_World *world) -{ - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2+sizeof(WorldId)); - bool balanceTeams=false; - bsIn.Read(balanceTeams); - NoTeamId noTeamId; - bsIn.Read(noTeamId); - - world->balanceTeamsIsActive=balanceTeams; - if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()) - { - if (packet->guid==GetMyGUIDUnified()) - world->BroadcastToParticipants(packet->data, packet->length, packet->guid); - else - world->BroadcastToParticipants(packet->data, packet->length, UNASSIGNED_RAKNET_GUID); - - if (balanceTeams) - world->EnforceTeamBalance(noTeamId); - else - world->FillRequestedSlots(); - } -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -void TeamManager::OnSetBalanceTeamsInitial(Packet *packet, TM_World *world) -{ - BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(2+sizeof(WorldId)); - bool balanceTeams=false; - bsIn.Read(balanceTeams); - world->balanceTeamsIsActive=balanceTeams; -} - -// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -#endif // _RAKNET_SUPPORT_TeamManager==1 - diff --git a/vendors/mafianet/Source/src/TelnetTransport.cpp b/vendors/mafianet/Source/src/TelnetTransport.cpp deleted file mode 100644 index 1caea68e1..000000000 --- a/vendors/mafianet/Source/src/TelnetTransport.cpp +++ /dev/null @@ -1,372 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_TelnetTransport==1 && _RAKNET_SUPPORT_TCPInterface==1 - -#include "mafianet/TelnetTransport.h" -#include "mafianet/TCPInterface.h" -#include -#include -#include -#include "mafianet/LinuxStrings.h" -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -// #define _PRINTF_DEBUG - -#define ECHO_INPUT - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(TelnetTransport,TelnetTransport); - -TelnetTransport::TelnetTransport() -{ - tcpInterface=0; - sendSuffix=0; - sendPrefix=0; -} -TelnetTransport::~TelnetTransport() -{ - Stop(); - if (sendSuffix) - rakFree_Ex(sendSuffix, _FILE_AND_LINE_ ); - if (sendPrefix) - rakFree_Ex(sendPrefix, _FILE_AND_LINE_ ); -} -bool TelnetTransport::Start(unsigned short port, bool serverMode) -{ - (void) serverMode; - AutoAllocate(); - RakAssert(serverMode); - return tcpInterface->Start(port, 64); -} -void TelnetTransport::Stop(void) -{ - if (tcpInterface==0) return; - tcpInterface->Stop(); - unsigned i; - for (i=0; i < remoteClients.Size(); i++) - MafiaNet::OP_DELETE(remoteClients[i], _FILE_AND_LINE_); - remoteClients.Clear(false, _FILE_AND_LINE_); - MafiaNet::OP_DELETE(tcpInterface, _FILE_AND_LINE_); - tcpInterface=0; -} -void TelnetTransport::Send( SystemAddress systemAddress, const char *data,... ) -{ - if (tcpInterface==0) return; - - if (data==0 || data[0]==0) - return; - - char text[REMOTE_MAX_TEXT_INPUT]; - size_t prefixLength; - if (sendPrefix) - { - strcpy_s(text, sendPrefix); - prefixLength = strlen(sendPrefix); - } - else - { - text[0]=0; - prefixLength=0; - } - va_list ap; - va_start(ap, data); - vsnprintf_s(text+prefixLength, REMOTE_MAX_TEXT_INPUT-prefixLength, REMOTE_MAX_TEXT_INPUT-prefixLength-1, data, ap); - va_end(ap); - - if (sendSuffix) - { - size_t length = strlen(text); - size_t availableChars = REMOTE_MAX_TEXT_INPUT-length-1; - strncat_s(text, sendSuffix, availableChars); - } - - tcpInterface->Send(text, (unsigned int) strlen(text), systemAddress, false); -} -void TelnetTransport::CloseConnection( SystemAddress systemAddress ) -{ - tcpInterface->CloseConnection(systemAddress); -} -Packet* TelnetTransport::Receive( void ) -{ - if (tcpInterface==0) return 0; - Packet *p = tcpInterface->Receive(); - if (p==0) - return 0; - - /* - if (p->data[0]==255) - { - unsigned i; - for (i=0; i < p->length; i++) - { - RAKNET_DEBUG_PRINTF("%i ", p->data[i]); - } - RAKNET_DEBUG_PRINTF("\n"); - tcpInterface->DeallocatePacket(p); - return 0; - } - */ - - // Get this guy's cursor buffer. This is real bullcrap that I have to do this. - unsigned i; - TelnetClient *remoteClient=0; - for (i=0; i < remoteClients.Size(); i++) - { - if (remoteClients[i]->systemAddress==p->systemAddress) - remoteClient=remoteClients[i]; - } - //RakAssert(remoteClient); - if (remoteClient==0) - { - tcpInterface->DeallocatePacket(p); - return 0; - } - - - if (p->length==3 && p->data[0]==27 && p->data[1]==91 && p->data[2]==65) - { - if (remoteClient->lastSentTextInput[0]) - { - // Up arrow, return last string - for (i=0; remoteClient->textInput[i]; i++) - remoteClient->textInput[i]=8; - strcat_s(remoteClient->textInput, remoteClient->lastSentTextInput); - tcpInterface->Send((const char *)remoteClient->textInput, (unsigned int) strlen(remoteClient->textInput), p->systemAddress, false); - strcpy_s(remoteClient->textInput,remoteClient->lastSentTextInput); - remoteClient->cursorPosition=(unsigned int) strlen(remoteClient->textInput); - } - - return 0; - } - - - // 127 is delete - ignore that - // 9 is tab - // 27 is escape - if (p->data[0]>=127 || p->data[0]==9 || p->data[0]==27) - { - tcpInterface->DeallocatePacket(p); - return 0; - } - - // Hack - I don't know what the hell this is about but cursor keys send 3 characters at a time. I can block these - //Up=27,91,65 - //Down=27,91,66 - //Right=27,91,67 - //Left=27,91,68 - if (p->length==3 && p->data[0]==27 && p->data[1]==91 && p->data[2]>=65 && p->data[2]<=68) - { - tcpInterface->DeallocatePacket(p); - return 0; - } - - - - // Echo -#ifdef ECHO_INPUT - tcpInterface->Send((const char *)p->data, p->length, p->systemAddress, false); -#endif - - bool gotLine; - // Process each character in turn - for (i=0; i < p->length; i++) - { - -#ifdef ECHO_INPUT - if (p->data[i]==8) - { - char spaceThenBack[2]; - spaceThenBack[0]=' '; - spaceThenBack[1]=8; - tcpInterface->Send((const char *)spaceThenBack, 2, p->systemAddress, false); - } -#endif - - gotLine=ReassembleLine(remoteClient, p->data[i]); - if (gotLine && remoteClient->textInput[0]) - { - - Packet *reassembledLine = (Packet*) rakMalloc_Ex(sizeof(Packet), _FILE_AND_LINE_); - reassembledLine->length=(unsigned int) strlen(remoteClient->textInput); - memcpy(remoteClient->lastSentTextInput, remoteClient->textInput, reassembledLine->length+1); - RakAssert(reassembledLine->length < REMOTE_MAX_TEXT_INPUT); - reassembledLine->data= (unsigned char*) rakMalloc_Ex( reassembledLine->length+1, _FILE_AND_LINE_ ); - memcpy(reassembledLine->data, remoteClient->textInput, reassembledLine->length); -#ifdef _PRINTF_DEBUG - memset(remoteClient->textInput, 0, REMOTE_MAX_TEXT_INPUT); -#endif - reassembledLine->data[reassembledLine->length]=0; - reassembledLine->systemAddress=p->systemAddress; - tcpInterface->DeallocatePacket(p); - return reassembledLine; - } - } - - tcpInterface->DeallocatePacket(p); - return 0; -} -void TelnetTransport::DeallocatePacket( Packet *packet ) -{ - if (tcpInterface==0) return; - rakFree_Ex(packet->data, _FILE_AND_LINE_ ); - rakFree_Ex(packet, _FILE_AND_LINE_ ); -} -SystemAddress TelnetTransport::HasNewIncomingConnection(void) -{ - unsigned i; - SystemAddress newConnection; - newConnection = tcpInterface->HasNewIncomingConnection(); - // 03/16/06 Can't force the stupid windows telnet to use line mode or local echo so now I have to track all the remote players and their - // input buffer - if (newConnection != UNASSIGNED_SYSTEM_ADDRESS) - { - unsigned char command[10]; - // http://www.pcmicro.com/netfoss/RFC857.html - // IAC WON'T ECHO - command[0]=255; // IAC - //command[1]=253; // WON'T - command[1]=251; // WILL - command[2]=1; // ECHO - tcpInterface->Send((const char*)command, 3, newConnection, false); - - /* - // Tell the other side to use line mode - // http://www.faqs.org/rfcs/rfc1184.html - // IAC DO LINEMODE - // command[0]=255; // IAC - // command[1]=252; // DO - // command[2]=34; // LINEMODE - // tcpInterface->Send((const char*)command, 3, newConnection); - - */ - - TelnetClient *remoteClient=0; - for (i=0; i < remoteClients.Size(); i++) - { - if (remoteClients[i]->systemAddress==newConnection) - { - remoteClient=remoteClients[i]; - remoteClient->cursorPosition=0; - } - } - - if (remoteClient==0) - { - remoteClient=new TelnetClient; - remoteClient->lastSentTextInput[0]=0; - remoteClient->cursorPosition=0; - remoteClient->systemAddress=newConnection; -#ifdef _PRINTF_DEBUG - memset(remoteClient->textInput, 0, REMOTE_MAX_TEXT_INPUT); -#endif - } - - remoteClients.Insert(remoteClient, _FILE_AND_LINE_); - } - return newConnection; -} -SystemAddress TelnetTransport::HasLostConnection(void) -{ - SystemAddress systemAddress; - unsigned i; - systemAddress=tcpInterface->HasLostConnection(); - if (systemAddress!=UNASSIGNED_SYSTEM_ADDRESS) - { - for (i=0; i < remoteClients.Size(); i++) - { - if (remoteClients[i]->systemAddress==systemAddress) - { - MafiaNet::OP_DELETE(remoteClients[i], _FILE_AND_LINE_); - remoteClients[i]=remoteClients[remoteClients.Size()-1]; - remoteClients.RemoveFromEnd(); - } - } - } - return systemAddress; -} -CommandParserInterface* TelnetTransport::GetCommandParser(void) -{ - return 0; -} -void TelnetTransport::SetSendSuffix(const char *suffix) -{ - if (sendSuffix) - { - rakFree_Ex(sendSuffix, _FILE_AND_LINE_ ); - sendSuffix=0; - } - if (suffix) - { - sendSuffix = (char*) rakMalloc_Ex(strlen(suffix)+1, _FILE_AND_LINE_); - strcpy_s(sendSuffix, strlen(suffix)+1, suffix); - } -} -void TelnetTransport::SetSendPrefix(const char *prefix) -{ - if (sendPrefix) - { - rakFree_Ex(sendPrefix, _FILE_AND_LINE_ ); - sendPrefix=0; - } - if (prefix) - { - sendPrefix = (char*) rakMalloc_Ex(strlen(prefix)+1, _FILE_AND_LINE_); - strcpy_s(sendPrefix, strlen(prefix)+1, prefix); - } -} -void TelnetTransport::AutoAllocate(void) -{ - if (tcpInterface==0) - tcpInterface=new TCPInterface; -} -bool TelnetTransport::ReassembleLine(TelnetTransport::TelnetClient* remoteClient, unsigned char c) -{ - if (c=='\n') - { - remoteClient->textInput[remoteClient->cursorPosition]=0; - remoteClient->cursorPosition=0; -#ifdef _PRINTF_DEBUG - RAKNET_DEBUG_PRINTF("[Done] %s\n", remoteClient->textInput); -#endif - return true; - } - else if (c==8) // backspace - { - if (remoteClient->cursorPosition>0) - { - remoteClient->textInput[--remoteClient->cursorPosition]=0; -#ifdef _PRINTF_DEBUG - RAKNET_DEBUG_PRINTF("[Back] %s\n", remoteClient->textInput); -#endif - } - } - else if (c>=32 && c <127) - { - if (remoteClient->cursorPosition < REMOTE_MAX_TEXT_INPUT) - { - remoteClient->textInput[remoteClient->cursorPosition++]=c; -#ifdef _PRINTF_DEBUG - RAKNET_DEBUG_PRINTF("[Norm] %s\n", remoteClient->textInput); -#endif - } - } - return false; -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/ThreadsafePacketLogger.cpp b/vendors/mafianet/Source/src/ThreadsafePacketLogger.cpp deleted file mode 100644 index f730d2165..000000000 --- a/vendors/mafianet/Source/src/ThreadsafePacketLogger.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_PacketLogger==1 - -#include "mafianet/ThreadsafePacketLogger.h" -#include -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - -using namespace MafiaNet; - -ThreadsafePacketLogger::ThreadsafePacketLogger() -{ - -} -ThreadsafePacketLogger::~ThreadsafePacketLogger() -{ - char **msg; - while ((msg = logMessages.ReadLock()) != 0) - { - rakFree_Ex((*msg), _FILE_AND_LINE_ ); - } -} -void ThreadsafePacketLogger::Update(void) -{ - char **msg; - while ((msg = logMessages.ReadLock()) != 0) - { - WriteLog(*msg); - rakFree_Ex((*msg), _FILE_AND_LINE_ ); - } -} -void ThreadsafePacketLogger::AddToLog(const char *str) -{ - char **msg = logMessages.WriteLock(); - *msg = (char*) rakMalloc_Ex( strlen(str)+1, _FILE_AND_LINE_ ); - strcpy_s(*msg, strlen(str)+1, str); - logMessages.WriteUnlock(); -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/TwoWayAuthentication.cpp b/vendors/mafianet/Source/src/TwoWayAuthentication.cpp deleted file mode 100644 index 3cae72f69..000000000 --- a/vendors/mafianet/Source/src/TwoWayAuthentication.cpp +++ /dev/null @@ -1,453 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_TwoWayAuthentication==1 - -#include "mafianet/TwoWayAuthentication.h" -#include "mafianet/Rand.h" -#include "mafianet/GetTime.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/BitStream.h" -#include "mafianet/peerinterface.h" - -#if LIBCAT_SECURITY==1 -static const int HASH_BITS = 256; -static const int HASH_BYTES = HASH_BITS / 8; -static const int STRENGTHENING_FACTOR = 256; - -// If building a MafiaNet DLL, be sure to tweak the CAT_EXPORT macro meaning -#if !defined(_MAFIANET_LIB) && defined(_MAFIANET_DLL) -# define CAT_BUILD_DLL -#else -# define CAT_NEUTER_EXPORT -#endif -#include -#endif - -using namespace MafiaNet; - -enum NegotiationIdentifiers -{ - ID_NONCE_REQUEST, - ID_NONCE_REPLY, - ID_HASHED_NONCE_AND_PASSWORD, -}; - -TwoWayAuthentication::NonceGenerator::NonceGenerator() {nextRequestId=0;} -TwoWayAuthentication::NonceGenerator::~NonceGenerator() -{ - Clear(); -} -void TwoWayAuthentication::NonceGenerator::GetNonce(char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH], unsigned short *requestId, MafiaNet::AddressOrGUID remoteSystem) -{ - TwoWayAuthentication::NonceAndRemoteSystemRequest *narsr = MafiaNet::OP_NEW(_FILE_AND_LINE_); - narsr->remoteSystem=remoteSystem; - GenerateNonce(narsr->nonce); - narsr->requestId=nextRequestId++; - *requestId=narsr->requestId; - memcpy(nonce,narsr->nonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); - narsr->whenGenerated= MafiaNet::GetTime(); - generatedNonces.Push(narsr,_FILE_AND_LINE_); -} -void TwoWayAuthentication::NonceGenerator::GenerateNonce(char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH]) -{ - fillBufferMT(nonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); -} -bool TwoWayAuthentication::NonceGenerator::GetNonceById(char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH], unsigned short requestId, MafiaNet::AddressOrGUID remoteSystem, bool popIfFound) -{ - unsigned int i; - for (i=0; i < generatedNonces.Size(); i++) - { - if (generatedNonces[i]->requestId==requestId) - { - if (remoteSystem==generatedNonces[i]->remoteSystem) - { - memcpy(nonce,generatedNonces[i]->nonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); - if (popIfFound) - { - MafiaNet::OP_DELETE(generatedNonces[i],_FILE_AND_LINE_); - generatedNonces.RemoveAtIndex(i); - } - return true; - } - else - { - return false; - } - } - } - return false; -} -void TwoWayAuthentication::NonceGenerator::Clear(void) -{ - unsigned int i; - for (i=0; i < generatedNonces.Size(); i++) - MafiaNet::OP_DELETE(generatedNonces[i],_FILE_AND_LINE_); - generatedNonces.Clear(true,_FILE_AND_LINE_); -} -void TwoWayAuthentication::NonceGenerator::ClearByAddress(MafiaNet::AddressOrGUID remoteSystem) -{ - unsigned int i=0; - while (i < generatedNonces.Size()) - { - if (generatedNonces[i]->remoteSystem==remoteSystem) - { - MafiaNet::OP_DELETE(generatedNonces[i],_FILE_AND_LINE_); - generatedNonces.RemoveAtIndex(i); - } - else - { - i++; - } - } -} -void TwoWayAuthentication::NonceGenerator::Update(MafiaNet::Time curTime) -{ - if (generatedNonces.Size()>0 && GreaterThan(curTime-5000, generatedNonces[0]->whenGenerated)) - { - MafiaNet::OP_DELETE(generatedNonces[0], _FILE_AND_LINE_); - generatedNonces.RemoveAtIndex(0); - } -} -TwoWayAuthentication::TwoWayAuthentication() -{ - whenLastTimeoutCheck= MafiaNet::GetTime(); - seedMT(MafiaNet::GetTimeMS()); -} -TwoWayAuthentication::~TwoWayAuthentication() -{ - Clear(); -} -bool TwoWayAuthentication::AddPassword(MafiaNet::RakString identifier, MafiaNet::RakString password) -{ - if (password.IsEmpty()) - return false; - - if (identifier.IsEmpty()) - return false; - - if (password==identifier) - return false; // Insecure - - if (passwords.GetIndexOf(identifier.C_String()).IsInvalid()==false) - return false; // This identifier already in use - - passwords.Push(identifier, password,_FILE_AND_LINE_); - return true; -} -bool TwoWayAuthentication::Challenge(MafiaNet::RakString identifier, AddressOrGUID remoteSystem) -{ - DataStructures::HashIndex skhi = passwords.GetIndexOf(identifier.C_String()); - if (skhi.IsInvalid()) - return false; - - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_TWO_WAY_AUTHENTICATION_NEGOTIATION); - bsOut.Write((MessageID)ID_NONCE_REQUEST); - SendUnified(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,remoteSystem,false); - - PendingChallenge pc; - pc.identifier=identifier; - pc.remoteSystem=remoteSystem; - pc.time= MafiaNet::GetTime(); - pc.sentHash=false; - outgoingChallenges.Push(pc,_FILE_AND_LINE_); - - return true; -} -void TwoWayAuthentication::Update(void) -{ - MafiaNet::Time curTime = MafiaNet::GetTime(); - nonceGenerator.Update(curTime); - if (GreaterThan(curTime - CHALLENGE_MINIMUM_TIMEOUT, whenLastTimeoutCheck)) - { - while (outgoingChallenges.Size() && GreaterThan(curTime - CHALLENGE_MINIMUM_TIMEOUT, outgoingChallenges.Peek().time)) - { - PendingChallenge pc = outgoingChallenges.Pop(); - - // Tell the user about the timeout - PushToUser(ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT, pc.identifier, pc.remoteSystem); - } - - whenLastTimeoutCheck=curTime+CHALLENGE_MINIMUM_TIMEOUT; - } -} -PluginReceiveResult TwoWayAuthentication::OnReceive(Packet *packet) -{ - switch (packet->data[0]) - { - case ID_TWO_WAY_AUTHENTICATION_NEGOTIATION: - { - if (packet->length>=sizeof(MessageID)*2) - { - switch (packet->data[sizeof(MessageID)]) - { - case ID_NONCE_REQUEST: - { - OnNonceRequest(packet); - } - break; - case ID_NONCE_REPLY: - { - OnNonceReply(packet); - } - break; - case ID_HASHED_NONCE_AND_PASSWORD: - { - return OnHashedNonceAndPassword(packet); - } - break; - } - } - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - case ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_FAILURE: - case ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_SUCCESS: - { - if (packet->wasGeneratedLocally==false) - { - OnPasswordResult(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - else - break; - } - break; - // These should only be generated locally - case ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_SUCCESS: - case ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_FAILURE: - case ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT: - if (packet->wasGeneratedLocally==false) - return RR_STOP_PROCESSING_AND_DEALLOCATE; - break; - } - - return RR_CONTINUE_PROCESSING; -} -void TwoWayAuthentication::OnRakPeerShutdown(void) -{ - Clear(); -} -void TwoWayAuthentication::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) lostConnectionReason; - - // Remove from pending challenges - unsigned int i=0; - while (i < outgoingChallenges.Size()) - { - if ((rakNetGUID!=UNASSIGNED_RAKNET_GUID && outgoingChallenges[i].remoteSystem.rakNetGuid==rakNetGUID) || - (systemAddress!=UNASSIGNED_SYSTEM_ADDRESS && outgoingChallenges[i].remoteSystem.systemAddress==systemAddress)) - { - outgoingChallenges.RemoveAtIndex(i); - } - else - { - i++; - } - } - - if (rakNetGUID!=UNASSIGNED_RAKNET_GUID) - nonceGenerator.ClearByAddress(rakNetGUID); - else - nonceGenerator.ClearByAddress(systemAddress); -} -void TwoWayAuthentication::Clear(void) -{ - outgoingChallenges.Clear(_FILE_AND_LINE_); - passwords.Clear(_FILE_AND_LINE_); - nonceGenerator.Clear(); -} -void TwoWayAuthentication::PushToUser(MessageID messageId, MafiaNet::RakString password, MafiaNet::AddressOrGUID remoteSystem) -{ - MafiaNet::BitStream output; - output.Write(messageId); - if (password.IsEmpty()==false) - output.Write(password); - Packet *p = AllocatePacketUnified(output.GetNumberOfBytesUsed()); - p->systemAddress=remoteSystem.systemAddress; - p->systemAddress.systemIndex=(SystemIndex)-1; - p->guid=remoteSystem.rakNetGuid; - p->wasGeneratedLocally=true; - memcpy(p->data, output.GetData(), output.GetNumberOfBytesUsed()); - rakPeerInterface->PushBackPacket(p, true); -} -void TwoWayAuthentication::OnNonceRequest(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - - char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH]; - unsigned short requestId; - nonceGenerator.GetNonce(nonce,&requestId,packet); - - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_TWO_WAY_AUTHENTICATION_NEGOTIATION); - bsOut.Write((MessageID)ID_NONCE_REPLY); - bsOut.Write(requestId); - bsOut.WriteAlignedBytes((const unsigned char*) nonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); - SendUnified(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,packet,false); -} -void TwoWayAuthentication::OnNonceReply(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - - char thierNonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH]; - unsigned short requestId; - bsIn.Read(requestId); - bsIn.ReadAlignedBytes((unsigned char *) thierNonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); - - // Lookup one of the negotiations for this guid/system address - AddressOrGUID aog(packet); - unsigned int i; - for (i=0; i < outgoingChallenges.Size(); i++) - { - if (outgoingChallenges[i].remoteSystem==aog && outgoingChallenges[i].sentHash==false) - { - outgoingChallenges[i].sentHash=true; - - // Get the password for this identifier - DataStructures::HashIndex skhi = passwords.GetIndexOf(outgoingChallenges[i].identifier.C_String()); - if (skhi.IsInvalid()==false) - { - MafiaNet::RakString password = passwords.ItemAtIndex(skhi); - - // Hash their nonce with password and reply - char hashedNonceAndPw[HASHED_NONCE_AND_PW_LENGTH]; - Hash(thierNonce, password, hashedNonceAndPw); - - // Send - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_TWO_WAY_AUTHENTICATION_NEGOTIATION); - bsOut.Write((MessageID)ID_HASHED_NONCE_AND_PASSWORD); - bsOut.Write(requestId); - bsOut.Write(outgoingChallenges[i].identifier); // Identifier helps the other system lookup the password quickly. - bsOut.WriteAlignedBytes((const unsigned char*) hashedNonceAndPw,HASHED_NONCE_AND_PW_LENGTH); - SendUnified(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,packet,false); - } - - return; - } - } -} -PluginReceiveResult TwoWayAuthentication::OnHashedNonceAndPassword(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*2); - - char remoteHashedNonceAndPw[HASHED_NONCE_AND_PW_LENGTH]; - unsigned short requestId; - bsIn.Read(requestId); - MafiaNet::RakString passwordIdentifier; - bsIn.Read(passwordIdentifier); - bsIn.ReadAlignedBytes((unsigned char *) remoteHashedNonceAndPw,HASHED_NONCE_AND_PW_LENGTH); - - // Look up used nonce from requestId - char usedNonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH]; - if (nonceGenerator.GetNonceById(usedNonce, requestId, packet, true)==false) - return RR_STOP_PROCESSING_AND_DEALLOCATE; - - DataStructures::HashIndex skhi = passwords.GetIndexOf(passwordIdentifier.C_String()); - if (skhi.IsInvalid()==false) - { - char hashedThisNonceAndPw[HASHED_NONCE_AND_PW_LENGTH]; - Hash(usedNonce, passwords.ItemAtIndex(skhi), hashedThisNonceAndPw); - if (memcmp(hashedThisNonceAndPw, remoteHashedNonceAndPw,HASHED_NONCE_AND_PW_LENGTH)==0) - { - // Pass - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_SUCCESS); - bsOut.WriteAlignedBytes((const unsigned char*) usedNonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); - bsOut.WriteAlignedBytes((const unsigned char*) remoteHashedNonceAndPw,HASHED_NONCE_AND_PW_LENGTH); - bsOut.Write(passwordIdentifier); - SendUnified(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,packet,false); - - // Incoming success, modify packet header to tell user - PushToUser(ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_SUCCESS, passwordIdentifier, packet); - - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - } - - // Incoming failure, modify arrived packet header to tell user - packet->data[0]=(MessageID) ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_FAILURE; - - MafiaNet::BitStream bsOut; - bsOut.Write((MessageID)ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_FAILURE); - bsOut.WriteAlignedBytes((const unsigned char*) usedNonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); - bsOut.WriteAlignedBytes((const unsigned char*) remoteHashedNonceAndPw,HASHED_NONCE_AND_PW_LENGTH); - bsOut.Write(passwordIdentifier); - SendUnified(&bsOut,MafiaNet::Priority::High,MafiaNet::Reliability::ReliableOrdered,0,packet,false); - - return RR_CONTINUE_PROCESSING; -} -void TwoWayAuthentication::OnPasswordResult(Packet *packet) -{ - MafiaNet::BitStream bsIn(packet->data, packet->length, false); - bsIn.IgnoreBytes(sizeof(MessageID)*1); - char usedNonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH]; - bsIn.ReadAlignedBytes((unsigned char *)usedNonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); - char hashedNonceAndPw[HASHED_NONCE_AND_PW_LENGTH]; - bsIn.ReadAlignedBytes((unsigned char *)hashedNonceAndPw,HASHED_NONCE_AND_PW_LENGTH); - MafiaNet::RakString passwordIdentifier; - bsIn.Read(passwordIdentifier); - - DataStructures::HashIndex skhi = passwords.GetIndexOf(passwordIdentifier.C_String()); - if (skhi.IsInvalid()==false) - { - MafiaNet::RakString password = passwords.ItemAtIndex(skhi); - char testHash[HASHED_NONCE_AND_PW_LENGTH]; - Hash(usedNonce, password, testHash); - if (memcmp(testHash,hashedNonceAndPw,HASHED_NONCE_AND_PW_LENGTH)==0) - { - // Lookup the outgoing challenge and remove it from the list - unsigned int i; - AddressOrGUID aog(packet); - for (i=0; i < outgoingChallenges.Size(); i++) - { - if (outgoingChallenges[i].identifier==passwordIdentifier && - outgoingChallenges[i].remoteSystem==aog && - outgoingChallenges[i].sentHash==true) - { - outgoingChallenges.RemoveAtIndex(i); - - PushToUser(packet->data[0], passwordIdentifier, packet); - return; - } - } - } - } -} -void TwoWayAuthentication::Hash(char thierNonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH], MafiaNet::RakString password, char out[HASHED_NONCE_AND_PW_LENGTH]) -{ -#if LIBCAT_SECURITY==1 - cat::Skein hash; - if (!hash.BeginKey(HASH_BITS)) return; - hash.Crunch(thierNonce, TWO_WAY_AUTHENTICATION_NONCE_LENGTH); - hash.Crunch(password.C_String(), (int) password.GetLength()); - hash.End(); - hash.Generate(out, HASH_BYTES, STRENGTHENING_FACTOR); -#else - CSHA1 sha1; - sha1.Update((unsigned char *) thierNonce, TWO_WAY_AUTHENTICATION_NONCE_LENGTH); - sha1.Update((unsigned char *) password.C_String(), (unsigned int) password.GetLength()); - sha1.Final(); - sha1.GetHash((unsigned char *) out); -#endif -} - -#endif diff --git a/vendors/mafianet/Source/src/UDPForwarder.cpp b/vendors/mafianet/Source/src/UDPForwarder.cpp deleted file mode 100644 index 03dc1f08f..000000000 --- a/vendors/mafianet/Source/src/UDPForwarder.cpp +++ /dev/null @@ -1,650 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/UDPForwarder.h" - -#if _RAKNET_SUPPORT_UDPForwarder==1 - -#include "mafianet/GetTime.h" -#include "mafianet/MTUSize.h" -#include "mafianet/SocketLayer.h" -#include "mafianet/WSAStartupSingleton.h" -#include "mafianet/sleep.h" -#include "mafianet/DS_OrderedList.h" -#include "mafianet/LinuxStrings.h" -#include "mafianet/SocketDefines.h" -#include "mafianet/VitaIncludes.h" -#include "errno.h" - -#ifdef _WIN32 -#include -#else -#ifndef _T -#define _T(x) (x) -#endif -#include // used for getaddrinfo() -#include // used for getaddrinfo() -#include // used for getaddrinfo() -#endif - -#ifndef INVALID_SOCKET -#define INVALID_SOCKET -1 -#endif - -using namespace MafiaNet; -static const unsigned short DEFAULT_MAX_FORWARD_ENTRIES=64; - -namespace MafiaNet -{ - RAK_THREAD_DECLARATION(UpdateUDPForwarderGlobal); -} - -UDPForwarder::ForwardEntry::ForwardEntry() -{ - socket=INVALID_SOCKET; - timeLastDatagramForwarded= MafiaNet::GetTimeMS(); - addr1Confirmed=UNASSIGNED_SYSTEM_ADDRESS; - addr2Confirmed=UNASSIGNED_SYSTEM_ADDRESS; -} -UDPForwarder::ForwardEntry::~ForwardEntry() { - if (socket!=INVALID_SOCKET) - closesocket__(socket); -} - -UDPForwarder::UDPForwarder() -{ -#ifdef _WIN32 - WSAStartupSingleton::AddRef(); -#endif - - maxForwardEntries=DEFAULT_MAX_FORWARD_ENTRIES; - nextInputId=0; - startForwardingInput.SetPageSize(sizeof(StartForwardingInputStruct)*16); - stopForwardingCommands.SetPageSize(sizeof(StopForwardingStruct)*16); -} -UDPForwarder::~UDPForwarder() -{ - Shutdown(); - -#ifdef _WIN32 - WSAStartupSingleton::Deref(); -#endif -} -void UDPForwarder::Startup(void) -{ - if (isRunning.GetValue()>0) - return; - - isRunning.Increment(); - - int errorCode; - - - - errorCode = MafiaNet::RakThread::Create(UpdateUDPForwarderGlobal, this); - - if ( errorCode != 0 ) - { - RakAssert(0); - return; - } - - while (threadRunning.GetValue()==0) - RakSleep(30); -} -void UDPForwarder::Shutdown(void) -{ - if (isRunning.GetValue()==0) - return; - isRunning.Decrement(); - - while (threadRunning.GetValue()>0) - RakSleep(30); - - unsigned int j; - for (j=0; j < forwardListNotUpdated.Size(); j++) - MafiaNet::OP_DELETE(forwardListNotUpdated[j],_FILE_AND_LINE_); - forwardListNotUpdated.Clear(false, _FILE_AND_LINE_); -} -void UDPForwarder::SetMaxForwardEntries(unsigned short maxEntries) -{ - RakAssert(maxEntries>0 && maxEntries<65535/2); - maxForwardEntries=maxEntries; -} -int UDPForwarder::GetMaxForwardEntries(void) const -{ - return maxForwardEntries; -} -int UDPForwarder::GetUsedForwardEntries(void) const -{ - return (int) forwardListNotUpdated.Size(); -} -UDPForwarderResult UDPForwarder::StartForwarding(SystemAddress source, SystemAddress destination, MafiaNet::TimeMS timeoutOnNoDataMS, const char *forceHostAddress, unsigned short socketFamily, - unsigned short *forwardingPort, __UDPSOCKET__ *forwardingSocket) -{ - // Invalid parameters? - if (timeoutOnNoDataMS == 0 || timeoutOnNoDataMS > UDP_FORWARDER_MAXIMUM_TIMEOUT || source==UNASSIGNED_SYSTEM_ADDRESS || destination==UNASSIGNED_SYSTEM_ADDRESS) - return UDPFORWARDER_INVALID_PARAMETERS; - - if (isRunning.GetValue()==0) - return UDPFORWARDER_NOT_RUNNING; - - (void) socketFamily; - - unsigned int inputId = nextInputId++; - - StartForwardingInputStruct *sfis; - sfis = startForwardingInput.Allocate(_FILE_AND_LINE_); - sfis->source=source; - sfis->destination=destination; - sfis->timeoutOnNoDataMS=timeoutOnNoDataMS; - RakAssert(timeoutOnNoDataMS!=0); - if (forceHostAddress && forceHostAddress[0]) - sfis->forceHostAddress=forceHostAddress; - sfis->socketFamily=socketFamily; - sfis->inputId=inputId; - startForwardingInput.Push(sfis); - - for(;;) - { - RakSleep(0); - startForwardingOutputMutex.Lock(); - for (unsigned int i=0; i < startForwardingOutput.Size(); i++) - { - if (startForwardingOutput[i].inputId==inputId) - { - if (startForwardingOutput[i].result==UDPFORWARDER_SUCCESS) - { - if (forwardingPort) - *forwardingPort = startForwardingOutput[i].forwardingPort; - if (forwardingSocket) - *forwardingSocket = startForwardingOutput[i].forwardingSocket; - } - UDPForwarderResult res = startForwardingOutput[i].result; - startForwardingOutput.RemoveAtIndex(i); - startForwardingOutputMutex.Unlock(); - return res; - } - } - startForwardingOutputMutex.Unlock(); - } -} -void UDPForwarder::StopForwarding(SystemAddress source, SystemAddress destination) -{ - StopForwardingStruct *sfs; - sfs = stopForwardingCommands.Allocate(_FILE_AND_LINE_); - sfs->destination=destination; - sfs->source=source; - stopForwardingCommands.Push(sfs); -} -void UDPForwarder::RecvFrom(MafiaNet::TimeMS curTime, ForwardEntry *forwardEntry) -{ -#ifndef __native_client__ - char data[ MAXIMUM_MTU_SIZE ]; - -#if RAKNET_SUPPORT_IPV6==1 - sockaddr_storage their_addr; - memset(&their_addr,0,sizeof(their_addr)); - sockaddr* sockAddrPtr; - socklen_t sockLen; - socklen_t* socketlenPtr=(socklen_t*) &sockLen; - sockaddr_in *sockAddrIn; - sockaddr_in6 *sockAddrIn6; - sockLen=sizeof(their_addr); - sockAddrPtr=(sockaddr*) &their_addr; -#else - sockaddr_in sockAddrIn; - memset(&sockAddrIn,0,sizeof(sockaddr_in)); - socklen_t len2; - len2 = sizeof( sockAddrIn ); - sockAddrIn.sin_family = AF_INET; -#endif - -#if defined(__GNUC__) - #if defined(MSG_DONTWAIT) - const int flag=MSG_DONTWAIT; - #else - const int flag=0x40; - #endif -#else - const int flag=0; -#endif - - int receivedDataLen, len=0; - //unsigned short portnum=0; - -#if RAKNET_SUPPORT_IPV6==1 - receivedDataLen = recvfrom__( forwardEntry->socket, data, MAXIMUM_MTU_SIZE, flag, sockAddrPtr, socketlenPtr ); -#else - receivedDataLen = recvfrom__( forwardEntry->socket, data, MAXIMUM_MTU_SIZE, flag, ( sockaddr* ) & sockAddrIn, ( socklen_t* ) & len2 ); -#endif - - if (receivedDataLen<0) - { -#if defined(_WIN32) && defined(_DEBUG) - DWORD dwIOError = WSAGetLastError(); - - if (dwIOError!=WSAECONNRESET && dwIOError!=WSAEINTR && dwIOError!=WSAETIMEDOUT && dwIOError!=WSAEWOULDBLOCK) - { - LPTSTR messageBuffer; - FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language - ( LPTSTR ) & messageBuffer, 0, nullptr); - // something has gone wrong here... - RAKNET_DEBUG_TPRINTF( _T("recvfrom failed:Error code - %lu\n%s"), dwIOError, messageBuffer ); - - //Free the buffer. - LocalFree( messageBuffer ); - } -#else - if (errno!=EAGAIN - && errno!=0 -#if defined(__GNUC__) - && errno!=EWOULDBLOCK -#endif - ) - { - printf("errno=%i\n", errno); - } -#endif - - - } - - if (receivedDataLen<=0) - return; - - SystemAddress receivedAddr; -#if RAKNET_SUPPORT_IPV6==1 - if (their_addr.ss_family==AF_INET) - { - sockAddrIn=(sockaddr_in *)&their_addr; - sockAddrIn6=0; - memcpy(&receivedAddr.address.addr4,sockAddrIn,sizeof(sockaddr_in)); - } - else - { - sockAddrIn=0; - sockAddrIn6=(sockaddr_in6 *)&their_addr; - memcpy(&receivedAddr.address.addr6,sockAddrIn6,sizeof(sockaddr_in6)); - } -#else - memcpy(&receivedAddr.address.addr4,&sockAddrIn,sizeof(sockaddr_in)); -#endif - //portnum=receivedAddr.GetPort(); - - SystemAddress forwardTarget; - - bool confirmed1 = forwardEntry->addr1Confirmed!=UNASSIGNED_SYSTEM_ADDRESS; - bool confirmed2 = forwardEntry->addr2Confirmed!=UNASSIGNED_SYSTEM_ADDRESS; - bool matchConfirmed1 = - confirmed1 && - forwardEntry->addr1Confirmed==receivedAddr; - bool matchConfirmed2 = - confirmed2 && - forwardEntry->addr2Confirmed==receivedAddr; - bool matchUnconfirmed1 = forwardEntry->addr1Unconfirmed.EqualsExcludingPort(receivedAddr); - bool matchUnconfirmed2 = forwardEntry->addr2Unconfirmed.EqualsExcludingPort(receivedAddr); - - if (matchConfirmed1==true || (matchConfirmed2==false && confirmed1==false && matchUnconfirmed1==true)) - { - // Forward to addr2 - if (forwardEntry->addr1Confirmed==UNASSIGNED_SYSTEM_ADDRESS) - { - forwardEntry->addr1Confirmed=receivedAddr; - } - if (forwardEntry->addr2Confirmed!=UNASSIGNED_SYSTEM_ADDRESS) - forwardTarget=forwardEntry->addr2Confirmed; - else - forwardTarget=forwardEntry->addr2Unconfirmed; - } - else if (matchConfirmed2==true || (confirmed2==false && matchUnconfirmed2==true)) - { - // Forward to addr1 - if (forwardEntry->addr2Confirmed==UNASSIGNED_SYSTEM_ADDRESS) - { - forwardEntry->addr2Confirmed=receivedAddr; - } - if (forwardEntry->addr1Confirmed!=UNASSIGNED_SYSTEM_ADDRESS) - forwardTarget=forwardEntry->addr1Confirmed; - else - forwardTarget=forwardEntry->addr1Unconfirmed; - } - else - { - return; - } - - // Forward to dest - len=0; -// sockaddr_in saOut; -// saOut.sin_port = forwardTarget.GetPortNetworkOrder(); // User port -// saOut.sin_addr.s_addr = forwardTarget.address.addr4.sin_addr.s_addr; -// saOut.sin_family = AF_INET; - do - { - - - -#if RAKNET_SUPPORT_IPV6==1 - if (forwardTarget.address.addr4.sin_family==AF_INET) - { - do - { - len = sendto__( forwardEntry->socket, data, receivedDataLen, 0, ( const sockaddr* ) & forwardTarget.address.addr4, sizeof( sockaddr_in ) ); - } - while ( len == 0 ); - } - else - { - do - { - len = sendto__( forwardEntry->socket, data, receivedDataLen, 0, ( const sockaddr* ) & forwardTarget.address.addr6, sizeof( sockaddr_in6 ) ); - } - while ( len == 0 ); - } -#else - do - { - len = sendto__( forwardEntry->socket, data, receivedDataLen, 0, ( const sockaddr* ) & forwardTarget.address.addr4, sizeof( sockaddr_in ) ); - } - while ( len == 0 ); -#endif - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } - while ( len == 0 ); - - forwardEntry->timeLastDatagramForwarded=curTime; -#endif // __native_client__ -} -void UDPForwarder::UpdateUDPForwarder(void) -{ - /* -#if !defined(SN_TARGET_PSP2) - timeval tv; - tv.tv_sec=0; - tv.tv_usec=0; -#endif - */ - - MafiaNet::TimeMS curTime = MafiaNet::GetTimeMS(); - - StartForwardingInputStruct *sfis; - StartForwardingOutputStruct sfos; - sfos.forwardingSocket=INVALID_SOCKET; - sfos.forwardingPort=0; - sfos.inputId=0; - sfos.result=UDPFORWARDER_RESULT_COUNT; - - for(;;) - { - sfis = startForwardingInput.Pop(); - if (sfis==0) - break; - - if (GetUsedForwardEntries()>maxForwardEntries) - { - sfos.result=UDPFORWARDER_NO_SOCKETS; - } - else - { - sfos.result=UDPFORWARDER_RESULT_COUNT; - - for (unsigned int i=0; i < forwardListNotUpdated.Size(); i++) - { - if ( - (forwardListNotUpdated[i]->addr1Unconfirmed==sfis->source && - forwardListNotUpdated[i]->addr2Unconfirmed==sfis->destination) - || - (forwardListNotUpdated[i]->addr1Unconfirmed==sfis->destination && - forwardListNotUpdated[i]->addr2Unconfirmed==sfis->source) - ) - { - ForwardEntry *fe = forwardListNotUpdated[i]; - sfos.forwardingPort = SocketLayer::GetLocalPort ( fe->socket ); - sfos.forwardingSocket=fe->socket; - sfos.result=UDPFORWARDER_FORWARDING_ALREADY_EXISTS; - break; - } - } - - if (sfos.result==UDPFORWARDER_RESULT_COUNT) - { - int sock_opt; - sockaddr_in listenerSocketAddress; - listenerSocketAddress.sin_port = 0; - ForwardEntry *fe = MafiaNet::OP_NEW(_FILE_AND_LINE_); - fe->addr1Unconfirmed=sfis->source; - fe->addr2Unconfirmed=sfis->destination; - fe->timeoutOnNoDataMS=sfis->timeoutOnNoDataMS; - -#if RAKNET_SUPPORT_IPV6!=1 - fe->socket = socket__( AF_INET, SOCK_DGRAM, 0 ); - listenerSocketAddress.sin_family = AF_INET; - if (sfis->forceHostAddress.IsEmpty()==false) - { - - - - - inet_pton(AF_INET, sfis->forceHostAddress.C_String(), &listenerSocketAddress.sin_addr.s_addr); - - } - else - { - listenerSocketAddress.sin_addr.s_addr = INADDR_ANY; - } - int ret = bind__( fe->socket, ( struct sockaddr * ) & listenerSocketAddress, sizeof( listenerSocketAddress ) ); - if (ret==-1) - { - MafiaNet::OP_DELETE(fe,_FILE_AND_LINE_); - sfos.result=UDPFORWARDER_BIND_FAILED; - } - else - { - sfos.result=UDPFORWARDER_SUCCESS; - } - -#else // RAKNET_SUPPORT_IPV6==1 - struct addrinfo hints; - memset(&hints, 0, sizeof (addrinfo)); // make sure the struct is empty - hints.ai_family = sfis->socketFamily; - hints.ai_socktype = SOCK_DGRAM; // UDP sockets - hints.ai_flags = AI_PASSIVE; // fill in my IP for me - struct addrinfo *servinfo=0, *aip; // will point to the results - - if (sfis->forceHostAddress.IsEmpty() || sfis->forceHostAddress=="UNASSIGNED_SYSTEM_ADDRESS") - getaddrinfo(0, "0", &hints, &servinfo); - else - getaddrinfo(sfis->forceHostAddress.C_String(), "0", &hints, &servinfo); - - for (aip = servinfo; aip != nullptr; aip = aip->ai_next) - { - // Open socket. The address type depends on what - // getaddrinfo() gave us. - fe->socket = socket__(aip->ai_family, aip->ai_socktype, aip->ai_protocol); - if (fe->socket != INVALID_SOCKET) - { - int ret = bind__( fe->socket, aip->ai_addr, (int) aip->ai_addrlen ); - if (ret>=0) - { - break; - } - else - { - closesocket__(fe->socket); - fe->socket=INVALID_SOCKET; - } - } - } - - // Release address info after we have used it - freeaddrinfo(servinfo); - - if (fe->socket==INVALID_SOCKET) - sfos.result=UDPFORWARDER_BIND_FAILED; - else - sfos.result=UDPFORWARDER_SUCCESS; -#endif // RAKNET_SUPPORT_IPV6==1 - - if (sfos.result==UDPFORWARDER_SUCCESS) - { - sfos.forwardingPort = SocketLayer::GetLocalPort ( fe->socket ); - sfos.forwardingSocket=fe->socket; - - sock_opt=1024*256; - setsockopt__(fe->socket, SOL_SOCKET, SO_RCVBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) ); - sock_opt=0; - setsockopt__(fe->socket, SOL_SOCKET, SO_LINGER, ( char * ) & sock_opt, sizeof ( sock_opt ) ); -#ifdef _WIN32 - unsigned long nonblocking = 1; - ioctlsocket__( fe->socket, FIONBIO, &nonblocking ); - - - -#else - fcntl( fe->socket, F_SETFL, O_NONBLOCK ); -#endif - - forwardListNotUpdated.Insert(fe,_FILE_AND_LINE_); - } - } - } - - // Push result - sfos.inputId=sfis->inputId; - startForwardingOutputMutex.Lock(); - startForwardingOutput.Push(sfos,_FILE_AND_LINE_); - startForwardingOutputMutex.Unlock(); - - startForwardingInput.Deallocate(sfis, _FILE_AND_LINE_); - } - - StopForwardingStruct *sfs; - - for(;;) - { - sfs = stopForwardingCommands.Pop(); - if (sfs==0) - break; - - ForwardEntry *fe; - for (unsigned int i=0; i < forwardListNotUpdated.Size(); i++) - { - if ( - (forwardListNotUpdated[i]->addr1Unconfirmed==sfs->source && - forwardListNotUpdated[i]->addr2Unconfirmed==sfs->destination) - || - (forwardListNotUpdated[i]->addr1Unconfirmed==sfs->destination && - forwardListNotUpdated[i]->addr2Unconfirmed==sfs->source) - ) - { - fe = forwardListNotUpdated[i]; - forwardListNotUpdated.RemoveAtIndexFast(i); - MafiaNet::OP_DELETE(fe, _FILE_AND_LINE_); - break; - } - } - - stopForwardingCommands.Deallocate(sfs, _FILE_AND_LINE_); - } - - unsigned int i; - - i=0; - while (i < forwardListNotUpdated.Size()) - { - if (curTime > forwardListNotUpdated[i]->timeLastDatagramForwarded && // Account for timestamp wrap - curTime > forwardListNotUpdated[i]->timeLastDatagramForwarded+forwardListNotUpdated[i]->timeoutOnNoDataMS) - { - MafiaNet::OP_DELETE(forwardListNotUpdated[i],_FILE_AND_LINE_); - forwardListNotUpdated.RemoveAtIndex(i); - } - else - i++; - } - - ForwardEntry *forwardEntry; - for (i=0; i < forwardListNotUpdated.Size(); i++) - { - forwardEntry = forwardListNotUpdated[i]; - RecvFrom(curTime, forwardEntry); - } -} - -namespace MafiaNet { -RAK_THREAD_DECLARATION(UpdateUDPForwarderGlobal) -{ - - - - UDPForwarder * udpForwarder = ( UDPForwarder * ) arguments; - - - udpForwarder->threadRunning.Increment(); - while (udpForwarder->isRunning.GetValue()>0) - { - udpForwarder->UpdateUDPForwarder(); - - // 12/1/2010 Do not change from 0 - // See http://www.jenkinssoftware.com/forum/index.php?topic=4033.0;topicseen - // Avoid 100% reported CPU usage - if (udpForwarder->forwardListNotUpdated.Size()==0) - RakSleep(30); - else - RakSleep(0); - } - udpForwarder->threadRunning.Decrement(); - - - - - return 0; - - -} - -} // namespace MafiaNet - -#endif // #if _RAKNET_SUPPORT_FileOperations==1 diff --git a/vendors/mafianet/Source/src/UDPProxyClient.cpp b/vendors/mafianet/Source/src/UDPProxyClient.cpp deleted file mode 100644 index a65d73a24..000000000 --- a/vendors/mafianet/Source/src/UDPProxyClient.cpp +++ /dev/null @@ -1,322 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_UDPProxyClient==1 - -#include "mafianet/UDPProxyClient.h" -#include "mafianet/BitStream.h" -#include "mafianet/UDPProxyCommon.h" -#include "mafianet/peerinterface.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/GetTime.h" - -using namespace MafiaNet; -static const int DEFAULT_UNRESPONSIVE_PING_TIME_COORDINATOR=1000; - -// bool operator<( const DataStructures::MLKeyRef &inputKey, const UDPProxyClient::ServerWithPing &cls ) {return inputKey.Get().serverAddress < cls.serverAddress;} -// bool operator>( const DataStructures::MLKeyRef &inputKey, const UDPProxyClient::ServerWithPing &cls ) {return inputKey.Get().serverAddress > cls.serverAddress;} -// bool operator==( const DataStructures::MLKeyRef &inputKey, const UDPProxyClient::ServerWithPing &cls ) {return inputKey.Get().serverAddress == cls.serverAddress;} - -STATIC_FACTORY_DEFINITIONS(UDPProxyClient,UDPProxyClient); - -UDPProxyClient::UDPProxyClient() -{ - resultHandler=0; -} -UDPProxyClient::~UDPProxyClient() -{ - Clear(); -} -void UDPProxyClient::SetResultHandler(UDPProxyClientResultHandler *rh) -{ - resultHandler=rh; -} -bool UDPProxyClient::RequestForwarding(SystemAddress proxyCoordinator, SystemAddress sourceAddress, RakNetGUID targetGuid, MafiaNet::TimeMS timeoutOnNoDataMS, MafiaNet::BitStream *serverSelectionBitstream) -{ - // Return false if not connected - ConnectionState cs = rakPeerInterface->GetConnectionState(proxyCoordinator); - if (cs!=IS_CONNECTED) - return false; - - // Pretty much a bug not to set the result handler, as otherwise you won't know if the operation succeeed or not - RakAssert(resultHandler!=0); - if (resultHandler==0) - return false; - - BitStream outgoingBs; - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_FORWARDING_REQUEST_FROM_CLIENT_TO_COORDINATOR); - outgoingBs.Write(sourceAddress); - outgoingBs.Write(false); - outgoingBs.Write(targetGuid); - outgoingBs.Write(timeoutOnNoDataMS); - if (serverSelectionBitstream && serverSelectionBitstream->GetNumberOfBitsUsed()>0) - { - outgoingBs.Write(true); - outgoingBs.Write(serverSelectionBitstream); - } - else - { - outgoingBs.Write(false); - } - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, proxyCoordinator, false); - - return true; -} -bool UDPProxyClient::RequestForwarding(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddressAsSeenFromCoordinator, MafiaNet::TimeMS timeoutOnNoDataMS, MafiaNet::BitStream *serverSelectionBitstream) -{ - // Return false if not connected - ConnectionState cs = rakPeerInterface->GetConnectionState(proxyCoordinator); - if (cs!=IS_CONNECTED) - return false; - - // Pretty much a bug not to set the result handler, as otherwise you won't know if the operation succeeed or not - RakAssert(resultHandler!=0); - if (resultHandler==0) - return false; - - BitStream outgoingBs; - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_FORWARDING_REQUEST_FROM_CLIENT_TO_COORDINATOR); - outgoingBs.Write(sourceAddress); - outgoingBs.Write(true); - outgoingBs.Write(targetAddressAsSeenFromCoordinator); - outgoingBs.Write(timeoutOnNoDataMS); - if (serverSelectionBitstream && serverSelectionBitstream->GetNumberOfBitsUsed()>0) - { - outgoingBs.Write(true); - outgoingBs.Write(serverSelectionBitstream); - } - else - { - outgoingBs.Write(false); - } - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, proxyCoordinator, false); - - return true; -} -void UDPProxyClient::Update(void) -{ - unsigned int idx1=0; - while (idx1 < pingServerGroups.Size()) - { - PingServerGroup *psg = pingServerGroups[idx1]; - - if (psg->serversToPing.Size() > 0 && - MafiaNet::GetTimeMS() > psg->startPingTime+DEFAULT_UNRESPONSIVE_PING_TIME_COORDINATOR) - { - // If they didn't reply within DEFAULT_UNRESPONSIVE_PING_TIME_COORDINATOR, just give up on them - psg->SendPingedServersToCoordinator(rakPeerInterface); - - MafiaNet::OP_DELETE(psg,_FILE_AND_LINE_); - pingServerGroups.RemoveAtIndex(idx1); - } - else - idx1++; - } - -} -PluginReceiveResult UDPProxyClient::OnReceive(Packet *packet) -{ - if (packet->data[0]==ID_UNCONNECTED_PONG) - { - unsigned int idx1, idx2; - PingServerGroup *psg; - for (idx1=0; idx1 < pingServerGroups.Size(); idx1++) - { - psg = pingServerGroups[idx1]; - for (idx2=0; idx2 < psg->serversToPing.Size(); idx2++) - { - if (psg->serversToPing[idx2].serverAddress==packet->systemAddress) - { - MafiaNet::BitStream bsIn(packet->data,packet->length,false); - bsIn.IgnoreBytes(sizeof(MessageID)); - MafiaNet::TimeMS sentTime; - bsIn.Read(sentTime); - MafiaNet::TimeMS curTime = MafiaNet::GetTimeMS(); - int ping; - if (curTime>sentTime) - ping=(int) (curTime-sentTime); - else - ping=0; - psg->serversToPing[idx2].ping=(unsigned short) ping; - - // If all servers to ping are now pinged, reply to coordinator - if (psg->AreAllServersPinged()) - { - psg->SendPingedServersToCoordinator(rakPeerInterface); - MafiaNet::OP_DELETE(psg,_FILE_AND_LINE_); - pingServerGroups.RemoveAtIndex(idx1); - } - - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - } - - } - } - else if (packet->data[0]==ID_UDP_PROXY_GENERAL && packet->length>1) - { - switch (packet->data[1]) - { - case ID_UDP_PROXY_PING_SERVERS_FROM_COORDINATOR_TO_CLIENT: - { - OnPingServers(packet); - } - break; - case ID_UDP_PROXY_FORWARDING_SUCCEEDED: - case ID_UDP_PROXY_ALL_SERVERS_BUSY: - case ID_UDP_PROXY_IN_PROGRESS: - case ID_UDP_PROXY_NO_SERVERS_ONLINE: - case ID_UDP_PROXY_RECIPIENT_GUID_NOT_CONNECTED_TO_COORDINATOR: - case ID_UDP_PROXY_FORWARDING_NOTIFICATION: - { - RakNetGUID targetGuid; - SystemAddress senderAddress, targetAddress; - MafiaNet::BitStream incomingBs(packet->data, packet->length, false); - incomingBs.IgnoreBytes(sizeof(MessageID)*2); - incomingBs.Read(senderAddress); - incomingBs.Read(targetAddress); - incomingBs.Read(targetGuid); - - switch (packet->data[1]) - { - case ID_UDP_PROXY_FORWARDING_NOTIFICATION: - case ID_UDP_PROXY_FORWARDING_SUCCEEDED: - case ID_UDP_PROXY_IN_PROGRESS: - { - unsigned short forwardingPort; - MafiaNet::RakString serverIP; - incomingBs.Read(serverIP); - incomingBs.Read(forwardingPort); - if (packet->data[1]==ID_UDP_PROXY_FORWARDING_SUCCEEDED) - { - if (resultHandler) - resultHandler->OnForwardingSuccess(serverIP.C_String(), forwardingPort, packet->systemAddress, senderAddress, targetAddress, targetGuid, this); - } - else if (packet->data[1]==ID_UDP_PROXY_IN_PROGRESS) - { - if (resultHandler) - resultHandler->OnForwardingInProgress(serverIP.C_String(), forwardingPort, packet->systemAddress, senderAddress, targetAddress, targetGuid, this); - } - else - { - // Send a datagram to the proxy, so if we are behind a router, that router adds an entry to the routing table. - // Otherwise the router would block the incoming datagrams from source - // It doesn't matter if the message actually arrives as long as it goes through the router - rakPeerInterface->Ping(serverIP.C_String(), forwardingPort, false); - - if (resultHandler) - resultHandler->OnForwardingNotification(serverIP.C_String(), forwardingPort, packet->systemAddress, senderAddress, targetAddress, targetGuid, this); - } - } - break; - case ID_UDP_PROXY_ALL_SERVERS_BUSY: - if (resultHandler) - resultHandler->OnAllServersBusy(packet->systemAddress, senderAddress, targetAddress, targetGuid, this); - break; - case ID_UDP_PROXY_NO_SERVERS_ONLINE: - if (resultHandler) - resultHandler->OnNoServersOnline(packet->systemAddress, senderAddress, targetAddress, targetGuid, this); - break; - case ID_UDP_PROXY_RECIPIENT_GUID_NOT_CONNECTED_TO_COORDINATOR: - { - if (resultHandler) - resultHandler->OnRecipientNotConnected(packet->systemAddress, senderAddress, targetAddress, targetGuid, this); - break; - } - } - - } - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - } - return RR_CONTINUE_PROCESSING; -} -void UDPProxyClient::OnRakPeerShutdown(void) -{ - Clear(); -} -void UDPProxyClient::OnPingServers(Packet *packet) -{ - MafiaNet::BitStream incomingBs(packet->data, packet->length, false); - incomingBs.IgnoreBytes(2); - - PingServerGroup *psg = MafiaNet::OP_NEW(_FILE_AND_LINE_); - - ServerWithPing swp; - incomingBs.Read(psg->sata.senderClientAddress); - incomingBs.Read(psg->sata.targetClientAddress); - // #med - might be possible to drop - see pull request 35 - however kept as is to ensure ABI - // compatibility to RakNet in MaxNet 0.x - see #39 - RakNetGUID targetGuid; - incomingBs.Read(targetGuid); - psg->startPingTime= MafiaNet::GetTimeMS(); - psg->coordinatorAddressForPings=packet->systemAddress; - unsigned short serverListSize; - incomingBs.Read(serverListSize); - SystemAddress serverAddress; - unsigned short serverListIndex; - char ipStr[64]; - for (serverListIndex=0; serverListIndexserversToPing.Push(swp, _FILE_AND_LINE_ ); - swp.serverAddress.ToString(false,ipStr,static_cast(64)); - rakPeerInterface->Ping(ipStr,swp.serverAddress.GetPort(),false,0); - } - pingServerGroups.Push(psg,_FILE_AND_LINE_); -} - -bool UDPProxyClient::PingServerGroup::AreAllServersPinged(void) const -{ - unsigned int serversToPingIndex; - for (serversToPingIndex=0; serversToPingIndex < serversToPing.Size(); serversToPingIndex++) - { - if (serversToPing[serversToPingIndex].ping==DEFAULT_UNRESPONSIVE_PING_TIME_COORDINATOR) - return false; - } - return true; -} - -void UDPProxyClient::PingServerGroup::SendPingedServersToCoordinator(RakPeerInterface *rakPeer) -{ - BitStream outgoingBs; - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_PING_SERVERS_REPLY_FROM_CLIENT_TO_COORDINATOR); - outgoingBs.Write(sata.senderClientAddress); - outgoingBs.Write(sata.targetClientAddress); - unsigned short serversToPingSize = (unsigned short) serversToPing.Size(); - outgoingBs.Write(serversToPingSize); - unsigned int serversToPingIndex; - for (serversToPingIndex=0; serversToPingIndex < serversToPingSize; serversToPingIndex++) - { - outgoingBs.Write(serversToPing[serversToPingIndex].serverAddress); - outgoingBs.Write(serversToPing[serversToPingIndex].ping); - } - rakPeer->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, coordinatorAddressForPings, false); -} -void UDPProxyClient::Clear(void) -{ - for (unsigned int i=0; i < pingServerGroups.Size(); i++) - MafiaNet::OP_DELETE(pingServerGroups[i],_FILE_AND_LINE_); - pingServerGroups.Clear(false, _FILE_AND_LINE_); -} - - -#endif // _RAKNET_SUPPORT_* - diff --git a/vendors/mafianet/Source/src/UDPProxyCoordinator.cpp b/vendors/mafianet/Source/src/UDPProxyCoordinator.cpp deleted file mode 100644 index dab4277b5..000000000 --- a/vendors/mafianet/Source/src/UDPProxyCoordinator.cpp +++ /dev/null @@ -1,573 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2018, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_UDPProxyCoordinator==1 && _RAKNET_SUPPORT_UDPForwarder==1 - -#include "mafianet/UDPProxyCoordinator.h" -#include "mafianet/BitStream.h" -#include "mafianet/UDPProxyCommon.h" -#include "mafianet/peerinterface.h" -#include "mafianet/MessageIdentifiers.h" -#include "mafianet/Rand.h" -#include "mafianet/GetTime.h" -#include "mafianet/UDPForwarder.h" - -// Larger than the client version -static const int DEFAULT_CLIENT_UNRESPONSIVE_PING_TIME=2000; -static const int DEFAULT_UNRESPONSIVE_PING_TIME_COORDINATOR=DEFAULT_CLIENT_UNRESPONSIVE_PING_TIME+1000; - -using namespace MafiaNet; - -// bool operator<( const DataStructures::MLKeyRef &inputKey, const UDPProxyCoordinator::ServerWithPing &cls ) {return inputKey.Get() < cls.ping;} -// bool operator>( const DataStructures::MLKeyRef &inputKey, const UDPProxyCoordinator::ServerWithPing &cls ) {return inputKey.Get() > cls.ping;} -// bool operator==( const DataStructures::MLKeyRef &inputKey, const UDPProxyCoordinator::ServerWithPing &cls ) {return inputKey.Get() == cls.ping;} - -int UDPProxyCoordinator::ServerWithPingComp( const unsigned short &key, const UDPProxyCoordinator::ServerWithPing &data ) -{ - if (key < data.ping) - return -1; - if (key > data.ping) - return 1; - return 0; -} - -int UDPProxyCoordinator::ForwardingRequestComp( const SenderAndTargetAddress &key, ForwardingRequest* const &data) -{ - if (key.senderClientAddress < data->sata.senderClientAddress ) - return -1; - if (key.senderClientAddress > data->sata.senderClientAddress ) - return 1; - if (key.targetClientAddress < data->sata.targetClientAddress ) - return -1; - if (key.targetClientAddress > data->sata.targetClientAddress ) - return 1; - return 0; -} -// -// bool operator<( const DataStructures::MLKeyRef &inputKey, const UDPProxyCoordinator::ForwardingRequest *cls ) -// { -// return inputKey.Get().senderClientAddress < cls->sata.senderClientAddress || -// (inputKey.Get().senderClientAddress == cls->sata.senderClientAddress && inputKey.Get().targetClientAddress < cls->sata.targetClientAddress); -// } -// bool operator>( const DataStructures::MLKeyRef &inputKey, const UDPProxyCoordinator::ForwardingRequest *cls ) -// { -// return inputKey.Get().senderClientAddress > cls->sata.senderClientAddress || -// (inputKey.Get().senderClientAddress == cls->sata.senderClientAddress && inputKey.Get().targetClientAddress > cls->sata.targetClientAddress); -// } -// bool operator==( const DataStructures::MLKeyRef &inputKey, const UDPProxyCoordinator::ForwardingRequest *cls ) -// { -// return inputKey.Get().senderClientAddress == cls->sata.senderClientAddress && inputKey.Get().targetClientAddress == cls->sata.targetClientAddress; -// } - -STATIC_FACTORY_DEFINITIONS(UDPProxyCoordinator,UDPProxyCoordinator); - -UDPProxyCoordinator::UDPProxyCoordinator() -{ - -} -UDPProxyCoordinator::~UDPProxyCoordinator() -{ - Clear(); -} -void UDPProxyCoordinator::SetRemoteLoginPassword(MafiaNet::RakString password) -{ - remoteLoginPassword=password; -} -void UDPProxyCoordinator::Update(void) -{ - unsigned int idx; - MafiaNet::TimeMS curTime = MafiaNet::GetTimeMS(); - ForwardingRequest *fw; - idx=0; - while (idx < forwardingRequestList.Size()) - { - fw=forwardingRequestList[idx]; - if (fw->timeRequestedPings!=0 && - curTime > fw->timeRequestedPings + DEFAULT_UNRESPONSIVE_PING_TIME_COORDINATOR) - { - fw->OrderRemainingServersToTry(); - fw->timeRequestedPings=0; - TryNextServer(fw->sata, fw); - idx++; - } - else if (fw->timeoutAfterSuccess!=0 && - curTime > fw->timeoutAfterSuccess) - { - // Forwarding request succeeded, we waited a bit to prevent duplicates. Can forget about the entry now. - MafiaNet::OP_DELETE(fw,_FILE_AND_LINE_); - forwardingRequestList.RemoveAtIndex(idx); - } - else - idx++; - } -} -PluginReceiveResult UDPProxyCoordinator::OnReceive(Packet *packet) -{ - if (packet->data[0]==ID_UDP_PROXY_GENERAL && packet->length>1) - { - switch (packet->data[1]) - { - case ID_UDP_PROXY_FORWARDING_REQUEST_FROM_CLIENT_TO_COORDINATOR: - OnForwardingRequestFromClientToCoordinator(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_UDP_PROXY_LOGIN_REQUEST_FROM_SERVER_TO_COORDINATOR: - OnLoginRequestFromServerToCoordinator(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_UDP_PROXY_FORWARDING_REPLY_FROM_SERVER_TO_COORDINATOR: - OnForwardingReplyFromServerToCoordinator(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - case ID_UDP_PROXY_PING_SERVERS_REPLY_FROM_CLIENT_TO_COORDINATOR: - OnPingServersReplyFromClientToCoordinator(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - } - return RR_CONTINUE_PROCESSING; -} -void UDPProxyCoordinator::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) lostConnectionReason; - (void) rakNetGUID; - - unsigned int idx, idx2; - - idx=0; - while (idx < forwardingRequestList.Size()) - { - if (forwardingRequestList[idx]->requestingAddress==systemAddress) - { - // Guy disconnected before the attempt completed - MafiaNet::OP_DELETE(forwardingRequestList[idx], _FILE_AND_LINE_); - forwardingRequestList.RemoveAtIndex(idx ); - } - else - idx++; - } - - idx = serverList.GetIndexOf(systemAddress); - if (idx!=(unsigned int)-1) - { - ForwardingRequest *fw; - // For each pending client for this server, choose from remaining servers. - for (idx2=0; idx2 < forwardingRequestList.Size(); idx2++) - { - fw = forwardingRequestList[idx2]; - if (fw->currentlyAttemptedServerAddress==systemAddress) - { - // Try the next server - TryNextServer(fw->sata, fw); - } - } - - // Remove dead server - serverList.RemoveAtIndexFast(idx); - } -} -void UDPProxyCoordinator::OnForwardingRequestFromClientToCoordinator(Packet *packet) -{ - MafiaNet::BitStream incomingBs(packet->data, packet->length, false); - incomingBs.IgnoreBytes(2); - SystemAddress sourceAddress; - incomingBs.Read(sourceAddress); - if (sourceAddress==UNASSIGNED_SYSTEM_ADDRESS) - sourceAddress=packet->systemAddress; - SystemAddress targetAddress; - RakNetGUID targetGuid; - bool usesAddress=false; - incomingBs.Read(usesAddress); - if (usesAddress) - { - incomingBs.Read(targetAddress); - targetGuid=rakPeerInterface->GetGuidFromSystemAddress(targetAddress); - } - else - { - incomingBs.Read(targetGuid); - targetAddress=rakPeerInterface->GetSystemAddressFromGuid(targetGuid); - } - ForwardingRequest *fw = MafiaNet::OP_NEW(_FILE_AND_LINE_); - fw->timeoutAfterSuccess=0; - incomingBs.Read(fw->timeoutOnNoDataMS); - bool hasServerSelectionBitstream=false; - incomingBs.Read(hasServerSelectionBitstream); - if (hasServerSelectionBitstream) - incomingBs.Read(&(fw->serverSelectionBitstream)); - - MafiaNet::BitStream outgoingBs; - SenderAndTargetAddress sata; - sata.senderClientAddress=sourceAddress; - sata.targetClientAddress=targetAddress; - sata.targetClientGuid=targetGuid; - sata.senderClientGuid=rakPeerInterface->GetGuidFromSystemAddress(sourceAddress); - SenderAndTargetAddress sataReversed; - sataReversed.senderClientAddress=targetAddress; - sataReversed.targetClientAddress=sourceAddress; - sataReversed.senderClientGuid=sata.targetClientGuid; - sataReversed.targetClientGuid=sata.senderClientGuid; - - unsigned int insertionIndex; - bool objectExists1, objectExists2; - insertionIndex=forwardingRequestList.GetIndexFromKey(sata, &objectExists1); - forwardingRequestList.GetIndexFromKey(sataReversed, &objectExists2); - - if (objectExists1 || objectExists2) - { - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_IN_PROGRESS); - outgoingBs.Write(sata.senderClientAddress); - outgoingBs.Write(targetAddress); - outgoingBs.Write(targetGuid); - // Request in progress, not completed - unsigned short forwardingPort=0; - RakString serverPublicIp; - outgoingBs.Write(serverPublicIp); - outgoingBs.Write(forwardingPort); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, packet->systemAddress, false); - MafiaNet::OP_DELETE(fw, _FILE_AND_LINE_); - return; - } - - if (serverList.Size()==0) - { - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_NO_SERVERS_ONLINE); - outgoingBs.Write(sata.senderClientAddress); - outgoingBs.Write(targetAddress); - outgoingBs.Write(targetGuid); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, packet->systemAddress, false); - MafiaNet::OP_DELETE(fw, _FILE_AND_LINE_); - return; - } - - if (rakPeerInterface->GetConnectionState(targetAddress)!=IS_CONNECTED && usesAddress==false) - { - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_RECIPIENT_GUID_NOT_CONNECTED_TO_COORDINATOR); - outgoingBs.Write(sata.senderClientAddress); - outgoingBs.Write(targetAddress); - outgoingBs.Write(targetGuid); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, packet->systemAddress, false); - MafiaNet::OP_DELETE(fw, _FILE_AND_LINE_); - return; - } - - fw->sata=sata; - fw->requestingAddress=packet->systemAddress; - - if (serverList.Size()>1) - { - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_PING_SERVERS_FROM_COORDINATOR_TO_CLIENT); - outgoingBs.Write(sourceAddress); - outgoingBs.Write(targetAddress); - outgoingBs.Write(targetGuid); - unsigned short serverListSize = (unsigned short) serverList.Size(); - outgoingBs.Write(serverListSize); - unsigned int idx; - for (idx=0; idx < serverList.Size(); idx++) - outgoingBs.Write(serverList[idx]); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, sourceAddress, false); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, targetAddress, false); - fw->timeRequestedPings= MafiaNet::GetTimeMS(); - unsigned int copyIndex; - for (copyIndex=0; copyIndex < serverList.Size(); copyIndex++) - fw->remainingServersToTry.Push(serverList[copyIndex], _FILE_AND_LINE_ ); - forwardingRequestList.InsertAtIndex(fw, insertionIndex, _FILE_AND_LINE_ ); - } - else - { - fw->timeRequestedPings=0; - fw->currentlyAttemptedServerAddress=serverList[0]; - forwardingRequestList.InsertAtIndex(fw, insertionIndex, _FILE_AND_LINE_ ); - SendForwardingRequest(sourceAddress, targetAddress, fw->currentlyAttemptedServerAddress, fw->timeoutOnNoDataMS); - } -} - -void UDPProxyCoordinator::SendForwardingRequest(SystemAddress sourceAddress, SystemAddress targetAddress, SystemAddress serverAddress, MafiaNet::TimeMS timeoutOnNoDataMS) -{ - MafiaNet::BitStream outgoingBs; - // Send request to desired server - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_FORWARDING_REQUEST_FROM_COORDINATOR_TO_SERVER); - outgoingBs.Write(sourceAddress); - outgoingBs.Write(targetAddress); - outgoingBs.Write(timeoutOnNoDataMS); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, serverAddress, false); -} -void UDPProxyCoordinator::OnLoginRequestFromServerToCoordinator(Packet *packet) -{ - MafiaNet::BitStream incomingBs(packet->data, packet->length, false); - incomingBs.IgnoreBytes(2); - MafiaNet::RakString password; - incomingBs.Read(password); - MafiaNet::BitStream outgoingBs; - - if (remoteLoginPassword.IsEmpty()) - { - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_NO_PASSWORD_SET_FROM_COORDINATOR_TO_SERVER); - outgoingBs.Write(password); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, packet->systemAddress, false); - return; - } - - if (remoteLoginPassword!=password) - { - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_WRONG_PASSWORD_FROM_COORDINATOR_TO_SERVER); - outgoingBs.Write(password); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, packet->systemAddress, false); - return; - } - - unsigned int insertionIndex; - insertionIndex=serverList.GetIndexOf(packet->systemAddress); - if (insertionIndex!=(unsigned int)-1) - { - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_ALREADY_LOGGED_IN_FROM_COORDINATOR_TO_SERVER); - outgoingBs.Write(password); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, packet->systemAddress, false); - return; - } - serverList.Push(packet->systemAddress, _FILE_AND_LINE_ ); - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_LOGIN_SUCCESS_FROM_COORDINATOR_TO_SERVER); - outgoingBs.Write(password); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, packet->systemAddress, false); -} -void UDPProxyCoordinator::OnForwardingReplyFromServerToCoordinator(Packet *packet) -{ - MafiaNet::BitStream incomingBs(packet->data, packet->length, false); - incomingBs.IgnoreBytes(2); - SenderAndTargetAddress sata; - incomingBs.Read(sata.senderClientAddress); - incomingBs.Read(sata.targetClientAddress); - bool objectExists; - unsigned int index = forwardingRequestList.GetIndexFromKey(sata, &objectExists); - if (objectExists==false) - { - // The guy disconnected before the request finished - return; - } - ForwardingRequest *fw = forwardingRequestList[index]; - sata.senderClientGuid = fw->sata.senderClientGuid; - sata.targetClientGuid = fw->sata.targetClientGuid; - - RakString serverPublicIp; - incomingBs.Read(serverPublicIp); - - if (serverPublicIp.IsEmpty()) - { - char serverIP[64]; - packet->systemAddress.ToString(false,serverIP,static_cast(64)); - serverPublicIp=serverIP; - } - - UDPForwarderResult success; - unsigned char c; - incomingBs.Read(c); - success=(UDPForwarderResult)c; - - unsigned short forwardingPort; - incomingBs.Read(forwardingPort); - - MafiaNet::BitStream outgoingBs; - if (success==UDPFORWARDER_SUCCESS) - { - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_FORWARDING_SUCCEEDED); - outgoingBs.Write(sata.senderClientAddress); - outgoingBs.Write(sata.targetClientAddress); - outgoingBs.Write(sata.targetClientGuid); - outgoingBs.Write(serverPublicIp); - outgoingBs.Write(forwardingPort); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, fw->requestingAddress, false); - - outgoingBs.Reset(); - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_FORWARDING_NOTIFICATION); - outgoingBs.Write(sata.senderClientAddress); - outgoingBs.Write(sata.targetClientAddress); - outgoingBs.Write(sata.targetClientGuid); - outgoingBs.Write(serverPublicIp); - outgoingBs.Write(forwardingPort); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, sata.targetClientAddress, false); - - // 05/18/09 Keep the entry around for some time after success, so duplicates are reported if attempting forwarding from the target system before notification of success - fw->timeoutAfterSuccess= MafiaNet::GetTimeMS()+fw->timeoutOnNoDataMS; - // forwardingRequestList.RemoveAtIndex(index); - // MafiaNet::OP_DELETE(fw,_FILE_AND_LINE_); - - return; - } - else if (success==UDPFORWARDER_NO_SOCKETS) - { - // Try next server - TryNextServer(sata, fw); - } - else - { - RakAssert(success==UDPFORWARDER_FORWARDING_ALREADY_EXISTS); - - // Return in progress - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_IN_PROGRESS); - outgoingBs.Write(sata.senderClientAddress); - outgoingBs.Write(sata.targetClientAddress); - outgoingBs.Write(sata.targetClientGuid); - outgoingBs.Write(serverPublicIp); - outgoingBs.Write(forwardingPort); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, fw->requestingAddress, false); - forwardingRequestList.RemoveAtIndex(index); - MafiaNet::OP_DELETE(fw,_FILE_AND_LINE_); - } -} -void UDPProxyCoordinator::OnPingServersReplyFromClientToCoordinator(Packet *packet) -{ - MafiaNet::BitStream incomingBs(packet->data, packet->length, false); - incomingBs.IgnoreBytes(2); - unsigned short serversToPingSize; - SystemAddress serverAddress; - SenderAndTargetAddress sata; - incomingBs.Read(sata.senderClientAddress); - incomingBs.Read(sata.targetClientAddress); - bool objectExists; - unsigned int index = forwardingRequestList.GetIndexFromKey(sata, &objectExists); - if (objectExists==false) - return; - unsigned short idx; - ServerWithPing swp; - ForwardingRequest *fw = forwardingRequestList[index]; - if (fw->timeRequestedPings==0) - return; - - incomingBs.Read(serversToPingSize); - if (packet->systemAddress==sata.senderClientAddress) - { - for (idx=0; idx < serversToPingSize; idx++) - { - incomingBs.Read(swp.serverAddress); - incomingBs.Read(swp.ping); - unsigned int index2; - for (index2=0; index2 < fw->sourceServerPings.Size(); index2++) - { - if (fw->sourceServerPings[index2].ping >= swp.ping ) - break; - } - fw->sourceServerPings.Insert(swp, index2, _FILE_AND_LINE_); - } - } - else - { - for (idx=0; idx < serversToPingSize; idx++) - { - incomingBs.Read(swp.serverAddress); - incomingBs.Read(swp.ping); - - unsigned int index2; - for (index2=0; index2 < fw->targetServerPings.Size(); index2++) - { - if (fw->targetServerPings[index2].ping >= swp.ping ) - break; - } - fw->sourceServerPings.Insert(swp, index2, _FILE_AND_LINE_); - } - } - - // Both systems have to give us pings to progress here. Otherwise will timeout in Update() - if (fw->sourceServerPings.Size()>0 && - fw->targetServerPings.Size()>0) - { - fw->OrderRemainingServersToTry(); - fw->timeRequestedPings=0; - TryNextServer(fw->sata, fw); - } -} -void UDPProxyCoordinator::TryNextServer(SenderAndTargetAddress sata, ForwardingRequest *fw) -{ - bool pickedGoodServer=false; - while(fw->remainingServersToTry.Size()>0) - { - fw->currentlyAttemptedServerAddress=fw->remainingServersToTry.Pop(); - if (serverList.GetIndexOf(fw->currentlyAttemptedServerAddress)!=(unsigned int)-1) - { - pickedGoodServer=true; - break; - } - } - - if (pickedGoodServer==false) - { - SendAllBusy(sata.senderClientAddress, sata.targetClientAddress, sata.targetClientGuid, fw->requestingAddress); - forwardingRequestList.Remove(sata); - MafiaNet::OP_DELETE(fw,_FILE_AND_LINE_); - return; - } - - SendForwardingRequest(sata.senderClientAddress, sata.targetClientAddress, fw->currentlyAttemptedServerAddress, fw->timeoutOnNoDataMS); -} -void UDPProxyCoordinator::SendAllBusy(SystemAddress senderClientAddress, SystemAddress targetClientAddress, RakNetGUID targetClientGuid, SystemAddress requestingAddress) -{ - MafiaNet::BitStream outgoingBs; - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_ALL_SERVERS_BUSY); - outgoingBs.Write(senderClientAddress); - outgoingBs.Write(targetClientAddress); - outgoingBs.Write(targetClientGuid); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, requestingAddress, false); -} -void UDPProxyCoordinator::Clear(void) -{ - serverList.Clear(true, _FILE_AND_LINE_); - for (unsigned int i=0; i < forwardingRequestList.Size(); i++) - { - MafiaNet::OP_DELETE(forwardingRequestList[i],_FILE_AND_LINE_); - } - forwardingRequestList.Clear(false, _FILE_AND_LINE_); -} -void UDPProxyCoordinator::ForwardingRequest::OrderRemainingServersToTry(void) -{ - //DataStructures::Multilist swpList; - DataStructures::OrderedList swpList; - // swpList.SetSortOrder(true); - - if (sourceServerPings.Size()==0 && targetServerPings.Size()==0) - return; - - unsigned int idx; - UDPProxyCoordinator::ServerWithPing swp; - for (idx=0; idx < remainingServersToTry.Size(); idx++) - { - swp.serverAddress=remainingServersToTry[idx]; - swp.ping=0; - if (sourceServerPings.Size()) - swp.ping+=(unsigned short) (sourceServerPings[idx].ping); - else - swp.ping+=(unsigned short) (DEFAULT_CLIENT_UNRESPONSIVE_PING_TIME); - if (targetServerPings.Size()) - swp.ping+=(unsigned short) (targetServerPings[idx].ping); - else - swp.ping+=(unsigned short) (DEFAULT_CLIENT_UNRESPONSIVE_PING_TIME); - swpList.Insert(swp.ping, swp, false, _FILE_AND_LINE_); - } - remainingServersToTry.Clear(_FILE_AND_LINE_ ); - for (idx=0; idx < swpList.Size(); idx++) - { - remainingServersToTry.Push(swpList[idx].serverAddress, _FILE_AND_LINE_ ); - } -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/UDPProxyServer.cpp b/vendors/mafianet/Source/src/UDPProxyServer.cpp deleted file mode 100644 index 28c8d0108..000000000 --- a/vendors/mafianet/Source/src/UDPProxyServer.cpp +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/NativeFeatureIncludes.h" -#if _RAKNET_SUPPORT_UDPProxyServer==1 && _RAKNET_SUPPORT_UDPForwarder==1 - -#include "mafianet/UDPProxyServer.h" -#include "mafianet/BitStream.h" -#include "mafianet/UDPProxyCommon.h" -#include "mafianet/peerinterface.h" -#include "mafianet/MessageIdentifiers.h" - -using namespace MafiaNet; - -STATIC_FACTORY_DEFINITIONS(UDPProxyServer,UDPProxyServer); - -UDPProxyServer::UDPProxyServer() -{ - resultHandler=0; - socketFamily=AF_INET; -} -UDPProxyServer::~UDPProxyServer() -{ - -} -void UDPProxyServer::SetSocketFamily(unsigned short _socketFamily) -{ - socketFamily=_socketFamily; -} -void UDPProxyServer::SetResultHandler(UDPProxyServerResultHandler *rh) -{ - resultHandler=rh; -} -bool UDPProxyServer::LoginToCoordinator(MafiaNet::RakString password, SystemAddress coordinatorAddress) -{ - unsigned int insertionIndex; - bool objectExists; - insertionIndex=loggingInCoordinators.GetIndexFromKey(coordinatorAddress,&objectExists); - if (objectExists==true) - return false; - loggedInCoordinators.GetIndexFromKey(coordinatorAddress,&objectExists); - if (objectExists==true) - return false; - MafiaNet::BitStream outgoingBs; - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_LOGIN_REQUEST_FROM_SERVER_TO_COORDINATOR); - outgoingBs.Write(password); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, coordinatorAddress, false); - loggingInCoordinators.InsertAtIndex(coordinatorAddress, insertionIndex, _FILE_AND_LINE_ ); - return true; -} -void UDPProxyServer::SetServerPublicIP(RakString ip) -{ - serverPublicIp = ip; -} -void UDPProxyServer::Update(void) -{ -} -PluginReceiveResult UDPProxyServer::OnReceive(Packet *packet) -{ - // Make sure incoming messages from from UDPProxyCoordinator - - if (packet->data[0]==ID_UDP_PROXY_GENERAL && packet->length>1) - { - bool objectExists; - - switch (packet->data[1]) - { - case ID_UDP_PROXY_FORWARDING_REQUEST_FROM_COORDINATOR_TO_SERVER: - if (loggedInCoordinators.GetIndexFromKey(packet->systemAddress, &objectExists)!=(unsigned int)-1) - { - OnForwardingRequestFromCoordinatorToServer(packet); - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - break; - case ID_UDP_PROXY_NO_PASSWORD_SET_FROM_COORDINATOR_TO_SERVER: - case ID_UDP_PROXY_WRONG_PASSWORD_FROM_COORDINATOR_TO_SERVER: - case ID_UDP_PROXY_ALREADY_LOGGED_IN_FROM_COORDINATOR_TO_SERVER: - case ID_UDP_PROXY_LOGIN_SUCCESS_FROM_COORDINATOR_TO_SERVER: - { - unsigned int removalIndex = loggingInCoordinators.GetIndexFromKey(packet->systemAddress, &objectExists); - if (objectExists) - { - loggingInCoordinators.RemoveAtIndex(removalIndex); - - MafiaNet::BitStream incomingBs(packet->data, packet->length, false); - incomingBs.IgnoreBytes(2); - MafiaNet::RakString password; - incomingBs.Read(password); - switch (packet->data[1]) - { - case ID_UDP_PROXY_NO_PASSWORD_SET_FROM_COORDINATOR_TO_SERVER: - if (resultHandler) - resultHandler->OnNoPasswordSet(password, this); - break; - case ID_UDP_PROXY_WRONG_PASSWORD_FROM_COORDINATOR_TO_SERVER: - if (resultHandler) - resultHandler->OnWrongPassword(password, this); - break; - case ID_UDP_PROXY_ALREADY_LOGGED_IN_FROM_COORDINATOR_TO_SERVER: - if (resultHandler) - resultHandler->OnAlreadyLoggedIn(password, this); - break; - case ID_UDP_PROXY_LOGIN_SUCCESS_FROM_COORDINATOR_TO_SERVER: - // RakAssert(loggedInCoordinators.GetIndexOf(packet->systemAddress)==(unsigned int)-1); - loggedInCoordinators.Insert(packet->systemAddress, packet->systemAddress, true, _FILE_AND_LINE_); - if (resultHandler) - resultHandler->OnLoginSuccess(password, this); - break; - } - } - - - return RR_STOP_PROCESSING_AND_DEALLOCATE; - } - } - } - return RR_CONTINUE_PROCESSING; -} -void UDPProxyServer::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) -{ - (void) lostConnectionReason; - (void) rakNetGUID; - - loggingInCoordinators.RemoveIfExists(systemAddress); - loggedInCoordinators.RemoveIfExists(systemAddress); -} -void UDPProxyServer::OnRakPeerStartup(void) -{ - udpForwarder.Startup(); -} -void UDPProxyServer::OnRakPeerShutdown(void) -{ - udpForwarder.Shutdown(); - loggingInCoordinators.Clear(true,_FILE_AND_LINE_); - loggedInCoordinators.Clear(true,_FILE_AND_LINE_); -} -void UDPProxyServer::OnAttach(void) -{ - if (rakPeerInterface->IsActive()) - OnRakPeerStartup(); -} -void UDPProxyServer::OnDetach(void) -{ - OnRakPeerShutdown(); -} -void UDPProxyServer::OnForwardingRequestFromCoordinatorToServer(Packet *packet) -{ - SystemAddress sourceAddress, targetAddress; - MafiaNet::BitStream incomingBs(packet->data, packet->length, false); - incomingBs.IgnoreBytes(2); - incomingBs.Read(sourceAddress); - incomingBs.Read(targetAddress); - MafiaNet::TimeMS timeoutOnNoDataMS; - incomingBs.Read(timeoutOnNoDataMS); - RakAssert(timeoutOnNoDataMS > 0 && timeoutOnNoDataMS <= UDP_FORWARDER_MAXIMUM_TIMEOUT); - - unsigned short forwardingPort=0; - UDPForwarderResult success = udpForwarder.StartForwarding(sourceAddress, targetAddress, timeoutOnNoDataMS, 0, socketFamily, &forwardingPort, 0); - MafiaNet::BitStream outgoingBs; - outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); - outgoingBs.Write((MessageID)ID_UDP_PROXY_FORWARDING_REPLY_FROM_SERVER_TO_COORDINATOR); - outgoingBs.Write(sourceAddress); - outgoingBs.Write(targetAddress); - outgoingBs.Write(serverPublicIp); - outgoingBs.Write((unsigned char) success); - outgoingBs.Write(forwardingPort); - rakPeerInterface->Send(&outgoingBs, MafiaNet::Priority::Medium, MafiaNet::Reliability::ReliableOrdered, 0, packet->systemAddress, false); -} - -#endif // _RAKNET_SUPPORT_* diff --git a/vendors/mafianet/Source/src/VariableDeltaSerializer.cpp b/vendors/mafianet/Source/src/VariableDeltaSerializer.cpp deleted file mode 100644 index d3781df3f..000000000 --- a/vendors/mafianet/Source/src/VariableDeltaSerializer.cpp +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/VariableDeltaSerializer.h" - -using namespace MafiaNet; - -VariableDeltaSerializer::VariableDeltaSerializer() {didComparisonThisTick=false;} -VariableDeltaSerializer::~VariableDeltaSerializer() {RemoveRemoteSystemVariableHistory();} - -VariableDeltaSerializer::SerializationContext::SerializationContext() {variableHistoryIdentical=0; variableHistoryUnique=0;} -VariableDeltaSerializer::SerializationContext::~SerializationContext() {} - -void VariableDeltaSerializer::OnMessageReceipt(RakNetGUID guid, uint32_t receiptId, bool messageArrived) -{ - // Module? - if (messageArrived) - FreeVarsAssociatedWithReceipt(guid, receiptId); - else - DirtyAndFreeVarsAssociatedWithReceipt(guid, receiptId); - -} - -void VariableDeltaSerializer::BeginUnreliableAckedSerialize(SerializationContext *context, RakNetGUID _guid, BitStream *_bitStream, uint32_t _sendReceipt) -{ - RakAssert(_guid!=UNASSIGNED_RAKNET_GUID); - context->anyVariablesWritten=false; - context->guid=_guid; - context->bitStream=_bitStream; - if (context->variableHistoryUnique==0) - context->variableHistoryUnique=StartVariableHistoryWrite(_guid); - context->variableHistory=context->variableHistoryUnique; - context->sendReceipt=_sendReceipt; - context->changedVariables = AllocChangedVariablesList(); - context->newSystemSend=false; - context->serializationMode=MafiaNet::Reliability::UnreliableWithAckReceipt; -} - -void VariableDeltaSerializer::BeginUniqueSerialize(SerializationContext *context, RakNetGUID _guid, BitStream *_bitStream) -{ - RakAssert(_guid!=UNASSIGNED_RAKNET_GUID); - context->anyVariablesWritten=false; - context->guid=_guid; - context->bitStream=_bitStream; - if (context->variableHistoryUnique==0) - context->variableHistoryUnique=StartVariableHistoryWrite(_guid); - context->variableHistory=context->variableHistoryUnique; - context->newSystemSend=false; - - context->serializationMode=MafiaNet::Reliability::Reliable; -} - - -void VariableDeltaSerializer::BeginIdenticalSerialize(SerializationContext *context, bool _isFirstSendToRemoteSystem, BitStream *_bitStream) -{ - context->anyVariablesWritten=false; - context->guid=UNASSIGNED_RAKNET_GUID; - context->bitStream=_bitStream; - context->serializationMode=MafiaNet::Reliability::Reliable; - if (context->variableHistoryIdentical==0) - context->variableHistoryIdentical=StartVariableHistoryWrite(UNASSIGNED_RAKNET_GUID); - context->variableHistory=context->variableHistoryIdentical; - context->newSystemSend=_isFirstSendToRemoteSystem; -} - -void VariableDeltaSerializer::EndSerialize(SerializationContext *context) -{ - if (context->serializationMode==MafiaNet::Reliability::UnreliableWithAckReceipt) - { - if (context->anyVariablesWritten==false) - { - context->bitStream->Reset(); - FreeChangedVariablesList(context->changedVariables); - return; - } - - StoreChangedVariablesList(context->variableHistory, context->changedVariables, context->sendReceipt); - } - else - { - if (context->variableHistoryIdentical) - { - if (didComparisonThisTick==false) - { - didComparisonThisTick=true; - identicalSerializationBs.Reset(); - - if (context->anyVariablesWritten==false) - { - context->bitStream->Reset(); - return; - } - - identicalSerializationBs.Write(context->bitStream); - context->bitStream->ResetReadPointer(); - } - else - { - context->bitStream->Write(&identicalSerializationBs); - identicalSerializationBs.ResetReadPointer(); - } - } - else if (context->anyVariablesWritten==false) - { - context->bitStream->Reset(); - return; - } - } -} - -void VariableDeltaSerializer::BeginDeserialize(DeserializationContext *context, BitStream *_bitStream) -{ - context->bitStream=_bitStream; -} - -void VariableDeltaSerializer::EndDeserialize(DeserializationContext *context) -{ - (void) context; -} - -void VariableDeltaSerializer::AddRemoteSystemVariableHistory(RakNetGUID guid) -{ - (void) guid; -} - -void VariableDeltaSerializer::RemoveRemoteSystemVariableHistory(RakNetGUID guid) -{ - unsigned int idx,idx2; - idx = GetVarsWrittenPerRemoteSystemListIndex(guid); - if (idx==(unsigned int)-1) - return; - - if (remoteSystemVariableHistoryList[idx]->guid==guid) - { - // Memory pool doesn't call destructor - for (idx2=0; idx2 < remoteSystemVariableHistoryList[idx]->updatedVariablesHistory.Size(); idx2++) - { - FreeChangedVariablesList(remoteSystemVariableHistoryList[idx]->updatedVariablesHistory[idx2]); - } - - delete remoteSystemVariableHistoryList[idx]; - remoteSystemVariableHistoryList.RemoveAtIndexFast(idx); - return; - } -} - -int MafiaNet::VariableDeltaSerializer::UpdatedVariablesListPtrComp( const uint32_t &key, ChangedVariablesList* const &data ) -{ - if (keysendReceipt) - return -1; - if (key==data->sendReceipt) - return 0; - return 1; -} - -void VariableDeltaSerializer::FreeVarsAssociatedWithReceipt(RakNetGUID guid, uint32_t receiptId) -{ - unsigned int idx, idx2; - idx = GetVarsWrittenPerRemoteSystemListIndex(guid); - if (idx==(unsigned int)-1) - return; - - RemoteSystemVariableHistory* vprs = remoteSystemVariableHistoryList[idx]; - bool objectExists; - idx2=vprs->updatedVariablesHistory.GetIndexFromKey(receiptId,&objectExists); - if (objectExists) - { - // Free this history node - FreeChangedVariablesList(vprs->updatedVariablesHistory[idx2]); - vprs->updatedVariablesHistory.RemoveAtIndex(idx2); - } -} - -void VariableDeltaSerializer::DirtyAndFreeVarsAssociatedWithReceipt(RakNetGUID guid, uint32_t receiptId) -{ - unsigned int idx, idx2; - idx = GetVarsWrittenPerRemoteSystemListIndex(guid); - if (idx==(unsigned int)-1) - return; - - RemoteSystemVariableHistory* vprs = remoteSystemVariableHistoryList[idx]; - bool objectExists; - idx2=vprs->updatedVariablesHistory.GetIndexFromKey(receiptId,&objectExists); - if (objectExists) - { - // 'Dirty' all variables sent this update, meaning they will be resent the next time Serialize() is called - vprs->variableListDeltaTracker.FlagDirtyFromBitArray(vprs->updatedVariablesHistory[idx2]->bitField); - - // Free this history node - FreeChangedVariablesList(vprs->updatedVariablesHistory[idx2]); - vprs->updatedVariablesHistory.RemoveAtIndex(idx2); - } -} -unsigned int VariableDeltaSerializer::GetVarsWrittenPerRemoteSystemListIndex(RakNetGUID guid) -{ - unsigned int idx; - for (idx=0; idx < remoteSystemVariableHistoryList.Size(); idx++) - { - if (remoteSystemVariableHistoryList[idx]->guid==guid) - return idx; - } - return (unsigned int) -1; -} -void VariableDeltaSerializer::RemoveRemoteSystemVariableHistory(void) -{ - unsigned int idx,idx2; - for (idx=0; idx < remoteSystemVariableHistoryList.Size(); idx++) - { - for (idx2=0; idx2 < remoteSystemVariableHistoryList[idx]->updatedVariablesHistory.Size(); idx2++) - { - FreeChangedVariablesList(remoteSystemVariableHistoryList[idx]->updatedVariablesHistory[idx2]); - } - - delete remoteSystemVariableHistoryList[idx]; - } - remoteSystemVariableHistoryList.Clear(false,_FILE_AND_LINE_); -} - -VariableDeltaSerializer::RemoteSystemVariableHistory* VariableDeltaSerializer::GetRemoteSystemVariableHistory(RakNetGUID guid) -{ - unsigned int rshli = GetRemoteSystemHistoryListIndex(guid); - return remoteSystemVariableHistoryList[rshli]; -} - -VariableDeltaSerializer::ChangedVariablesList *VariableDeltaSerializer::AllocChangedVariablesList(void) -{ - VariableDeltaSerializer::ChangedVariablesList *p = updatedVariablesMemoryPool.Allocate(_FILE_AND_LINE_); - p->bitWriteIndex=0; - p->bitField[0]=0; - return p; -} -void VariableDeltaSerializer::FreeChangedVariablesList(ChangedVariablesList *changedVariables) -{ - updatedVariablesMemoryPool.Release(changedVariables, _FILE_AND_LINE_); -} -void VariableDeltaSerializer::StoreChangedVariablesList(RemoteSystemVariableHistory *variableHistory, ChangedVariablesList *changedVariables, uint32_t sendReceipt) -{ - changedVariables->sendReceipt=sendReceipt; - variableHistory->updatedVariablesHistory.Insert(changedVariables->sendReceipt,changedVariables,true,_FILE_AND_LINE_); -} - -VariableDeltaSerializer::RemoteSystemVariableHistory *VariableDeltaSerializer::StartVariableHistoryWrite(RakNetGUID guid) -{ - RemoteSystemVariableHistory *variableHistory; - - unsigned int rshli = GetRemoteSystemHistoryListIndex(guid); - if (rshli==(unsigned int) -1) - { - variableHistory = new RemoteSystemVariableHistory; - variableHistory->guid=guid; - remoteSystemVariableHistoryList.Push(variableHistory,_FILE_AND_LINE_); - } - else - { - variableHistory=remoteSystemVariableHistoryList[rshli]; - } - - variableHistory->variableListDeltaTracker.StartWrite(); - return variableHistory; -} -unsigned int VariableDeltaSerializer::GetRemoteSystemHistoryListIndex(RakNetGUID guid) -{ - // Find the variable tracker for the target system - unsigned int idx; - for (idx=0; idx < remoteSystemVariableHistoryList.Size(); idx++) - { - if (remoteSystemVariableHistoryList[idx]->guid==guid) - { - return idx; - } - } - return (unsigned int) -1; -} - -void VariableDeltaSerializer::OnPreSerializeTick(void) -{ - didComparisonThisTick=false; -} diff --git a/vendors/mafianet/Source/src/VariableListDeltaTracker.cpp b/vendors/mafianet/Source/src/VariableListDeltaTracker.cpp deleted file mode 100644 index 01f7412c5..000000000 --- a/vendors/mafianet/Source/src/VariableListDeltaTracker.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/VariableListDeltaTracker.h" - -using namespace MafiaNet; - -VariableListDeltaTracker::VariableListDeltaTracker() {nextWriteIndex=0;} -VariableListDeltaTracker::~VariableListDeltaTracker() -{ - unsigned int i; - for (i=0; i < variableList.Size(); i++) - rakFree_Ex(variableList[i].lastData,_FILE_AND_LINE_); -} - -// Call before using a series of WriteVar -void VariableListDeltaTracker::StartWrite(void) {nextWriteIndex=0;} - -void VariableListDeltaTracker::FlagDirtyFromBitArray(unsigned char *bArray) -{ - unsigned short readOffset=0; - for (readOffset=0; readOffset < variableList.Size(); readOffset++) - { - bool result = ( bArray[ readOffset >> 3 ] & ( 0x80 >> ( readOffset & 7 ) ) ) !=0; - - if (result==true) - variableList[readOffset].isDirty=true; - } -} -VariableListDeltaTracker::VariableLastValueNode::VariableLastValueNode() -{ - lastData=0; -} -VariableListDeltaTracker::VariableLastValueNode::VariableLastValueNode(const unsigned char *data, int _byteLength) -{ - lastData=(char*) rakMalloc_Ex(_byteLength,_FILE_AND_LINE_); - memcpy(lastData,data,_byteLength); - byteLength=_byteLength; - isDirty=false; -} -VariableListDeltaTracker::VariableLastValueNode::~VariableLastValueNode() -{ -} diff --git a/vendors/mafianet/Source/src/VariadicSQLParser.cpp b/vendors/mafianet/Source/src/VariadicSQLParser.cpp deleted file mode 100644 index 0b5348aa9..000000000 --- a/vendors/mafianet/Source/src/VariadicSQLParser.cpp +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/VariadicSQLParser.h" -#include "mafianet/BitStream.h" -#include - -using namespace VariadicSQLParser; - -struct TypeMapping -{ - char inputType; - const char *type; -}; -const int NUM_TYPE_MAPPINGS=7; -TypeMapping typeMappings[NUM_TYPE_MAPPINGS] = -{ - {'i', "int"}, - {'d', "int"}, - {'s', "text"}, - {'b', "bool"}, - {'f', "numeric"}, - {'g', "double precision"}, - {'a', "bytea"}, -}; -unsigned int GetTypeMappingIndex(char c) -{ - unsigned int i; - for (i=0; i < (unsigned int) NUM_TYPE_MAPPINGS; i++ ) - if (typeMappings[i].inputType==c) - return i; - return (unsigned int)-1; -} -const char* VariadicSQLParser::GetTypeMappingAtIndex(int i) -{ - return typeMappings[i].type; -} -void VariadicSQLParser::GetTypeMappingIndices( const char *format, DataStructures::List &indices ) -{ - bool previousCharWasPercentSign; - unsigned int i; - unsigned int typeMappingIndex; - indices.Clear(false, _FILE_AND_LINE_); - unsigned int len = (unsigned int) strlen(format); - previousCharWasPercentSign=false; - for (i=0; i < len; i++) - { - if (previousCharWasPercentSign==true ) - { - typeMappingIndex = GetTypeMappingIndex(format[i]); - if (typeMappingIndex!=(unsigned int) -1) - { - IndexAndType iat; - iat.strIndex=i-1; - iat.typeMappingIndex=typeMappingIndex; - indices.Insert(iat, _FILE_AND_LINE_ ); - } - } - - previousCharWasPercentSign=format[i]=='%'; - } -} -void VariadicSQLParser::ExtractArguments( va_list argptr, const DataStructures::List &indices, char ***argumentBinary, int **argumentLengths ) -{ - if (indices.Size()==0) - return; - - unsigned int i; - *argumentBinary= MafiaNet::OP_NEW_ARRAY(indices.Size(), _FILE_AND_LINE_); - *argumentLengths= MafiaNet::OP_NEW_ARRAY(indices.Size(), _FILE_AND_LINE_); - - char **paramData=*argumentBinary; - int *paramLength=*argumentLengths; - - int variadicArgIndex; - for (variadicArgIndex=0, i=0; i < indices.Size(); i++, variadicArgIndex++) - { - switch (typeMappings[indices[i].typeMappingIndex].inputType) - { - case 'i': - case 'd': - { - int val = va_arg( argptr, int ); - paramLength[i]=sizeof(val); - paramData[i]=(char*) rakMalloc_Ex(paramLength[i], _FILE_AND_LINE_); - memcpy(paramData[i], &val, paramLength[i]); - if (MafiaNet::BitStream::IsNetworkOrder()==false) MafiaNet::BitStream::ReverseBytesInPlace((unsigned char*) paramData[i], paramLength[i]); - } - break; - case 's': - { - char* val = va_arg( argptr, char* ); - paramLength[i]=(int) strlen(val); - paramData[i]=(char*) rakMalloc_Ex(paramLength[i]+1, _FILE_AND_LINE_); - memcpy(paramData[i], val, paramLength[i]+1); - } - break; - case 'b': - { - bool val = (va_arg( argptr, int )!=0); - paramLength[i]=sizeof(val); - paramData[i]=(char*) rakMalloc_Ex(paramLength[i], _FILE_AND_LINE_); - memcpy(paramData[i], &val, paramLength[i]); - if (MafiaNet::BitStream::IsNetworkOrder()==false) MafiaNet::BitStream::ReverseBytesInPlace((unsigned char*) paramData[i], paramLength[i]); - } - break; - /* - case 'f': - { - // On MSVC at least, this only works with double as the 2nd param - float val = (float) va_arg( argptr, double ); - //float val = va_arg( argptr, float ); - paramLength[i]=sizeof(val); - paramData[i]=(char*) rakMalloc_Ex(paramLength[i], _FILE_AND_LINE_); - memcpy(paramData[i], &val, paramLength[i]); - if (MafiaNet::BitStream::IsNetworkOrder()==false) MafiaNet::BitStream::ReverseBytesInPlace((unsigned char*) paramData[i], paramLength[i]); - } - break; - */ - // On MSVC at least, this only works with double as the 2nd param - case 'f': - case 'g': - { - double val = va_arg( argptr, double ); - paramLength[i]=sizeof(val); - paramData[i]=(char*) rakMalloc_Ex(paramLength[i], _FILE_AND_LINE_); - memcpy(paramData[i], &val, paramLength[i]); - if (MafiaNet::BitStream::IsNetworkOrder()==false) MafiaNet::BitStream::ReverseBytesInPlace((unsigned char*) paramData[i], paramLength[i]); - } - break; - case 'a': - { - char* val = va_arg( argptr, char* ); - paramLength[i]=va_arg( argptr, unsigned int ); - paramData[i]=(char*) rakMalloc_Ex(paramLength[i], _FILE_AND_LINE_); - memcpy(paramData[i], val, paramLength[i]); - } - break; - } - } - -} -void VariadicSQLParser::FreeArguments(const DataStructures::List &indices, char **argumentBinary, int *argumentLengths) -{ - if (indices.Size()==0) - return; - - unsigned int i; - for (i=0; i < indices.Size(); i++) - rakFree_Ex(argumentBinary[i],_FILE_AND_LINE_); - MafiaNet::OP_DELETE_ARRAY(argumentBinary,_FILE_AND_LINE_); - MafiaNet::OP_DELETE_ARRAY(argumentLengths,_FILE_AND_LINE_); -} diff --git a/vendors/mafianet/Source/src/VitaIncludes.cpp b/vendors/mafianet/Source/src/VitaIncludes.cpp deleted file mode 100644 index 610dcab6c..000000000 --- a/vendors/mafianet/Source/src/VitaIncludes.cpp +++ /dev/null @@ -1,175 +0,0 @@ -/* - * This file was taken from RakNet 4.082. - * Please see licenses/RakNet license.txt for the underlying license and related copyright. - * - * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/EmptyHeader.h" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/vendors/mafianet/Source/src/WSAStartupSingleton.cpp b/vendors/mafianet/Source/src/WSAStartupSingleton.cpp deleted file mode 100644 index 586871474..000000000 --- a/vendors/mafianet/Source/src/WSAStartupSingleton.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#include "mafianet/WSAStartupSingleton.h" - - - - - -#if defined(_WIN32) -#include -#include - - - - - -#endif -#include "mafianet/defines.h" -#include - -#ifdef _WIN32 -#include -#else -#ifndef _T -#define _T(x) (x) -#endif -#endif - -int WSAStartupSingleton::refCount=0; - -WSAStartupSingleton::WSAStartupSingleton() {} -WSAStartupSingleton::~WSAStartupSingleton() {} -void WSAStartupSingleton::AddRef(void) -{ -#if defined(_WIN32) - - refCount++; - - if (refCount!=1) - return; - - - - - - WSADATA winsockInfo; - if ( WSAStartup( MAKEWORD( 2, 2 ), &winsockInfo ) != 0 ) - { -#if defined(_DEBUG) - DWORD dwIOError = GetLastError(); - LPTSTR messageBuffer; - FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language - ( LPTSTR ) & messageBuffer, 0, nullptr); - // something has gone wrong here... - RAKNET_DEBUG_TPRINTF( _T("WSAStartup failed:Error code - %lu\n%s"), dwIOError, messageBuffer ); - //Free the buffer. - LocalFree( messageBuffer ); -#endif - } - -#endif -} -void WSAStartupSingleton::Deref(void) -{ -#if defined(_WIN32) - if (refCount==0) - return; - - if (refCount>1) - { - refCount--; - return; - } - - WSACleanup(); - - - - - - - refCount=0; -#endif -} diff --git a/vendors/mafianet/Source/src/_FindFirst.cpp b/vendors/mafianet/Source/src/_FindFirst.cpp deleted file mode 100644 index 569b989b1..000000000 --- a/vendors/mafianet/Source/src/_FindFirst.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* - * This file was taken from RakNet 4.082. - * Please see licenses/RakNet license.txt for the underlying license and related copyright. - * - * Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -/** -* Original file by the_viking, fixed by Rv¥mulo Fernandes, fixed by Emmanuel Nars -* Should emulate windows finddata structure -*/ -#if (defined(__GNUC__) || defined(__GCCXML__)) && !defined(_WIN32) -#include "mafianet/_FindFirst.h" -#include "mafianet/DS_List.h" - -#include - -#include -#include "mafianet/linux_adapter.h" -#include "mafianet/osx_adapter.h" - - -static DataStructures::List< _findinfo_t* > fileInfo; - -#include "mafianet/memoryoverride.h" -#include "mafianet/assert.h" - -/** -* _findfirst - equivalent -*/ -long _findfirst(const char *name, _finddata_t *f) -{ - MafiaNet::RakString nameCopy = name; - MafiaNet::RakString filter; - - // This is linux only, so don't bother with '\' - const char* lastSep = strrchr(name,'/'); - if(!lastSep) - { - // filter pattern only is given, search current directory. - filter = nameCopy; - nameCopy = "."; - } else - { - // strip filter pattern from directory name, leave - // trailing '/' intact. - filter = lastSep+1; - unsigned sepIndex = lastSep - name; - nameCopy.Erase(sepIndex+1, nameCopy.GetLength() - sepIndex-1); - } - - DIR* dir = opendir(nameCopy); - - if(!dir) return -1; - - _findinfo_t* fi = MafiaNet::OP_NEW<_findinfo_t>( _FILE_AND_LINE_ ); - fi->filter = filter; - fi->dirName = nameCopy; // we need to remember this for stat() - fi->openedDir = dir; - fileInfo.Insert(fi, _FILE_AND_LINE_); - - long ret = fileInfo.Size()-1; - - // Retrieve the first file. We cannot rely on the first item - // being '.' - if (_findnext(ret, f) == -1) return -1; - else return ret; -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -int _findnext(long h, _finddata_t *f) -{ - RakAssert(h >= 0 && h < (long)fileInfo.Size()); - if (h < 0 || h >= (long)fileInfo.Size()) return -1; - - _findinfo_t* fi = fileInfo[h]; - - while(true) - { - dirent* entry = readdir(fi->openedDir); - if(entry == 0) return -1; - - // Only report stuff matching our filter - if (fnmatch(fi->filter, entry->d_name, FNM_PATHNAME) != 0) continue; - - // To reliably determine the entry's type, we must do - // a stat... don't rely on entry->d_type, as this - // might be unavailable! - struct stat filestat; - MafiaNet::RakString fullPath = fi->dirName + entry->d_name; - if (stat(fullPath, &filestat) != 0) - { - RAKNET_DEBUG_PRINTF("Cannot stat %s\n", fullPath.C_String()); - continue; - } - - if (S_ISREG(filestat.st_mode)) - { - f->attrib = _A_NORMAL; - } else if (S_ISDIR(filestat.st_mode)) - { - f->attrib = _A_SUBDIR; - } else continue; // We are interested in files and - // directories only. Links currently - // are not supported. - - f->size = filestat.st_size; - strncpy_s(f->name, entry->d_name, STRING_BUFFER_SIZE); - - return 0; - } - - return -1; -} - - - - - -/** - * _findclose - equivalent - */ -int _findclose(long h) -{ - if (h==-1) return 0; - - if (h < 0 || h >= (long)fileInfo.Size()) - { - RakAssert(false); - return -1; - } - - _findinfo_t* fi = fileInfo[h]; - closedir(fi->openedDir); - fileInfo.RemoveAtIndex(h); - MafiaNet::OP_DELETE(fi, _FILE_AND_LINE_); - return 0; -} -#endif diff --git a/vendors/mafianet/Source/src/crypto/cryptomanager.cpp b/vendors/mafianet/Source/src/crypto/cryptomanager.cpp deleted file mode 100644 index 76acb1fa2..000000000 --- a/vendors/mafianet/Source/src/crypto/cryptomanager.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/* -* Copyright (c) 2019, SLikeSoft UG (haftungsbeschr�nkt) -* -* This source code is licensed under the MIT-style license found in the license.txt -* file in the root directory of this source tree. -*/ -#include "mafianet/crypto/cryptomanager.h" - -#include "mafianet/assert.h" // used for RakAssert -#include // used for std::numeric_limits<> - -// prevent max/min macros getting defined (breaking numeric_limits<>::max() / ::min() usage) through the indirect windows.h include in the OpenSSL includes -#ifdef _WIN32 -#define NOMINMAX -#endif - -#include // used for ERR_xxxx -#include // used for EVP_xxxx, OpenSSL_add_all_algorithms() -#include // used for RAND_xxxx - -namespace MafiaNet -{ - namespace Experimental - { - namespace Crypto - { - bool CCryptoManager::Initialize() - { - if (m_Initialized) { - return true; // already initialized - } - - ERR_load_crypto_strings(); - OpenSSL_add_all_algorithms(); - - // Note: Modern OpenSSL (1.1.0+) provides proper entropy on all platforms. - // RAND_bytes() below will automatically seed the PRNG if needed. - - if (RAND_bytes(m_sessionKey, EVP_MAX_KEY_LENGTH) != 1) { - return false; // failed to initialize the random session key - } - if (RAND_bytes(m_initializationVector, EVP_MAX_IV_LENGTH) != 1) { - return false; // failed to initialize the initialization vector - } - - // Initialize the contexts - if (!m_decryptionContext) { - m_decryptionContext = EVP_CIPHER_CTX_new(); - if (!m_decryptionContext) { - return false; - } - } - if (!m_encryptionContext) { - m_encryptionContext = EVP_CIPHER_CTX_new(); - if (!m_encryptionContext) { - EVP_CIPHER_CTX_free(m_decryptionContext); - m_decryptionContext = nullptr; - return false; - } - } - - m_Initialized = true; - return true; - } - - void CCryptoManager::Shutdown() - { - if (m_decryptionContext) { - EVP_CIPHER_CTX_free(m_decryptionContext); - m_decryptionContext = nullptr; - } - if (m_encryptionContext) { - EVP_CIPHER_CTX_free(m_encryptionContext); - m_encryptionContext = nullptr; - } - m_Initialized = false; - } - - bool CCryptoManager::EncryptSessionData(const unsigned char* plaintext, size_t dataLength, unsigned char* outBuffer, size_t& inOutBufferSize) - { - if (!Initialize()) { - return false; // CryptoManager failed to initialize - } - - size_t requiredBufferSize = dataLength; - if (!GetRequiredEncryptionBufferSize(requiredBufferSize)) { - return false; // dataLength too large (integer overflow) - } - if (inOutBufferSize < requiredBufferSize) { - return false; // out buffer (potentially) too small - } - - // #high - review usage of the CBC mode here --- not the best nowadays - // #med - add engine support to use HW-acceleration - if (EVP_EncryptInit_ex(m_encryptionContext, EVP_aes_256_cbc(), nullptr, m_sessionKey, m_initializationVector) == 0) { - return false; // failed to initialize the encryption context - } - - int bytesWritten1; - // note: static_cast<> safe here, since GetRequiredEncrpytionBufferSize()-check ensured dataLength is <= int::max() - if (EVP_EncryptUpdate(m_encryptionContext, outBuffer, &bytesWritten1, plaintext, static_cast(dataLength)) == 0) { - return false; // encryption failed - } - RakAssert(static_cast(bytesWritten1) <= inOutBufferSize); - int bytesWritten2; - if (EVP_EncryptFinal_ex(m_encryptionContext, outBuffer + bytesWritten1, &bytesWritten2) == 0) { - return false; // failed final encryption step - } - RakAssert(static_cast(bytesWritten1) + static_cast(bytesWritten2) <= inOutBufferSize); - - inOutBufferSize = static_cast(bytesWritten1) + static_cast(bytesWritten2); - return true; - } - - bool CCryptoManager::DecryptSessionData(const unsigned char* encryptedtext, size_t dataLength, unsigned char* outBuffer, size_t& inOutBufferSize) - { - if (!Initialize()) { - return false; // CryptoManager failed to initialize - } - - // #med - extend support for inOutBufferSize > int::max() - if (inOutBufferSize > static_cast(std::numeric_limits::max())) { - // note: We check the inOutBufferSize here rather than the dataLength due to the indirect size limitation due to the EVP_DecryptUpdate()/EVP_DecryptFinal_ex() calls - // being limited to int::max() through their returned written bytes values. Due to the next check (inOutBufferSize < dataLength) it's implicitly ensured that - // dataLength doesn't exceed the limit either. - return false; // specified length exceeds max supported size - } - - if (inOutBufferSize < dataLength) { - // prevent potential buffer overflow, even though it's possible that the encryptedtext is padded and hence the effectively required - // inOutBufferSize is less than the provided dataLength, since we cannot determine this before running the actual decryption - so consider - // this an invalid call, if the provided inOutBufferSize is smaller than the incoming encrypted text's length - return false; - } - - // #high - review usage of the CBC mode here --- not the best nowadays - // #med - add engine support to use HW-acceleration - if (EVP_DecryptInit_ex(m_decryptionContext, EVP_aes_256_cbc(), nullptr, m_sessionKey, m_initializationVector) == 0) { - return false; // failed to initialize the decryption context - } - - int bytesWritten1; - // static cast safe due to size-check above - if (EVP_DecryptUpdate(m_decryptionContext, outBuffer, &bytesWritten1, encryptedtext, static_cast(dataLength)) == 0) { - return false; // decryption failed - } - RakAssert(static_cast(bytesWritten1) <= inOutBufferSize); - int bytesWritten2; - if (EVP_DecryptFinal_ex(m_decryptionContext, outBuffer + bytesWritten1, &bytesWritten2) == 0) { - return false; // failed final decryption step - } - RakAssert(static_cast(bytesWritten1) + static_cast(bytesWritten2) <= inOutBufferSize); - - inOutBufferSize = static_cast(bytesWritten1) + static_cast(bytesWritten2); - return true; - } - - bool CCryptoManager::GetRequiredEncryptionBufferSize(size_t& encryptionDataByteLength) - { - // note: not using EVP_CIPHER_CTX_block_size() here, since otherwise we would have to make sure that the encryption context was initialized already - const int blockSize = EVP_CIPHER_block_size(EVP_aes_256_cbc()); - - // EVP_EncryptUpdate() can write up to dataLength + blockSize - 1. The final EVP_EncryptFinal_ex() call can write up to blockSize. (reference: OpenSSL 1.0.2 documentation) - // Hence, by definition the required encryption buffer size is dataLength + blockSize*2 -1. - // Note: Practically the limit should actually never exceed dataLength + blockSize due to the encryption we use (AES 256 / CBC). However, we want to be safe - // on the design level to prevent possible incompatibilities with future OpenSSL changes. - - if (encryptionDataByteLength + blockSize * 2 - 1 < encryptionDataByteLength) { - return false; // prevent integer overflow - } - - encryptionDataByteLength = encryptionDataByteLength + blockSize * 2 - 1; - - // #med - extend support for datalength > int::max() - // verify that the specified length doesn't exceed the max supported data length - return encryptionDataByteLength <= static_cast(std::numeric_limits::max()); - } - - void* CCryptoManager::AllocateSecureMemory(size_t size) - { - // #high - route through memory manager (aka: same as OP_NEW_ARRAY) - return OPENSSL_malloc(size); - } - - void CCryptoManager::FreeSecureMemory(void* pointer, size_t size) - { - // make sure the memory is cleared before it's freed again - SecureClearMemory(pointer, size); - - // #high - route through memory manager (aka: same as OP_NEW_ARRAY) - return OPENSSL_free(pointer); - } - - void CCryptoManager::SecureClearMemory(void* pointer, size_t size) - { - OPENSSL_cleanse(pointer, size); - } - - // initialization list - EVP_CIPHER_CTX* CCryptoManager::m_decryptionContext = nullptr; - EVP_CIPHER_CTX* CCryptoManager::m_encryptionContext = nullptr; - unsigned char CCryptoManager::m_sessionKey[EVP_MAX_KEY_LENGTH]; - unsigned char CCryptoManager::m_initializationVector[EVP_MAX_IV_LENGTH]; - bool CCryptoManager::m_Initialized = false; - } - } -} \ No newline at end of file diff --git a/vendors/mafianet/Source/src/crypto/factory.cpp b/vendors/mafianet/Source/src/crypto/factory.cpp deleted file mode 100644 index b4e0ceeb5..000000000 --- a/vendors/mafianet/Source/src/crypto/factory.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2018-2019, SLikeSoft UG (haftungsbeschraenkt) - * - * This source code is licensed under the MIT-style license found in the license.txt - * file in the root directory of this source tree. - */ -#include "mafianet/crypto/factory.h" - -// includes for concrete classes -#include "mafianet/crypto/fileencrypter.h" // used for CFileEncrypter - -namespace MafiaNet -{ - namespace Experimental - { - namespace Crypto - { - IFileEncrypter* Factory::ConstructFileEncrypter(const char *publicKey, size_t publicKeyLength) - { - return new CFileEncrypter(publicKey, publicKeyLength); - } - - // #high - change interface --- use RakString? - // #high - reconsider non-const CSecureString (for private key) - IFileEncrypter* Factory::ConstructFileEncrypter(const char *publicKey, size_t publicKeyLength, const char *privateKey, size_t privateKeyLength, CSecureString& privateKeyPassword) - { - return new CFileEncrypter(publicKey, publicKeyLength, privateKey, privateKeyLength, privateKeyPassword); - } - } - } -} \ No newline at end of file diff --git a/vendors/mafianet/Source/src/crypto/fileencrypter.cpp b/vendors/mafianet/Source/src/crypto/fileencrypter.cpp deleted file mode 100644 index a7272907f..000000000 --- a/vendors/mafianet/Source/src/crypto/fileencrypter.cpp +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Copyright (c) 2018-2019, SLikeSoft UG (haftungsbeschr�nkt) - * - * This source code is licensed under the MIT-style license found in the license.txt - * file in the root directory of this source tree. - */ -#include "mafianet/crypto/fileencrypter.h" - -#include // used for strlen, strcpy_s - -#include // used for ERR_xxxx -#include // used for EVP_xxx -#include // used for PEM_read_bio_RSAPrivateKey, PEM_read_bio_RSA_PUBKEY, BIO_xxx -#include // used for RSA_xxxx - -#include "mafianet/crypto/cryptomanager.h" // used for MafiaNet::Experimental::Crypto::CCryptoManager -#include "mafianet/assert.h" // used for RakAssert - -#include "mafianet/linux_adapter.h" // used for strcpy_s -#include "mafianet/osx_adapter.h" // used for strcpy_s - -namespace MafiaNet -{ - namespace Experimental - { - namespace Crypto - { - CFileEncrypter::CFileEncrypter() : - m_privatePKey(nullptr), - m_publicPKey(nullptr) - { - CCryptoManager::Initialize(); - } - - CFileEncrypter::CFileEncrypter(const char *publicKey, size_t publicKeyLength) : - m_privatePKey(nullptr), - m_publicPKey(nullptr) - { - CCryptoManager::Initialize(); - - // #high - error / exception handling - (void)SetPublicKey(publicKey, publicKeyLength); - } - - CFileEncrypter::CFileEncrypter(const char *publicKey, size_t publicKeyLength, const char *privateKey, size_t privateKeyLength, CSecureString &password) : - m_privatePKey(nullptr), - m_publicPKey(nullptr) - { - CCryptoManager::Initialize(); - - // #high - error / exception handling - (void)SetPrivateKey(privateKey, privateKeyLength, password); - (void)SetPublicKey(publicKey, publicKeyLength); - } - - CFileEncrypter::~CFileEncrypter() - { - // ensure that either both key elements are null or both are non-null - RakAssert(m_publicPKey == nullptr); - RakAssert(m_privatePKey == nullptr); - - if (m_publicPKey != nullptr) { - EVP_PKEY_free(m_publicPKey); // implicitly frees the linked m_publicKey - } - - if (m_privatePKey != nullptr) { - EVP_PKEY_free(m_privatePKey); // implicitly frees the linked m_privateKey - } - } - - const unsigned char* CFileEncrypter::SignData(const unsigned char *data, const size_t dataLength) - { - if (m_privatePKey == nullptr) { - // #high - error/exception handling - return nullptr; - } - - EVP_MD_CTX *const rsaSigningContext = EVP_MD_CTX_new(); - // #med - double check this - it's not documented whether EVP_MD_CTX_new() can actually fail (and return null) - if (rsaSigningContext == nullptr) { - // #high - error/exception handling - return nullptr; - } - - if (EVP_SignInit_ex(rsaSigningContext, EVP_sha512(), nullptr) == 0) { - // #high - error/exception handling - EVP_MD_CTX_free(rsaSigningContext); - return nullptr; - } - - if (EVP_SignUpdate(rsaSigningContext, data, dataLength) == 0) { - // #high - error/exception handling - EVP_MD_CTX_free(rsaSigningContext); - return nullptr; - } - - // #med - use ArraySize<>()? - unsigned int bufferSize = 1024; - // #high - verify returned bufferSize... - const bool success = (EVP_SignFinal(rsaSigningContext, m_sigBuffer, &bufferSize, m_privatePKey) != 0); - - // note: EVP_MD_CTX_destroy handles cleanup - EVP_MD_CTX_free(rsaSigningContext); - - return success ? m_sigBuffer : nullptr; - } - - const char* CFileEncrypter::SignDataBase64(const unsigned char *data, const size_t dataLength) - { - const unsigned char* signature = SignData(data, dataLength); - if (signature == nullptr) { - // #high - error reporting - return nullptr; - } - - // #high - const_cast... / reinterpret_cast - // 1024 binary -> 1368 base64-encoded (excluding the written null-terminator) - if (EVP_EncodeBlock(reinterpret_cast(m_sigBufferBase64), const_cast(signature), 1024) != 1368) { - // #high - error reporting - return nullptr; - } - return m_sigBufferBase64; - } - - // #med - consider dropping signatureLength and replace it with a fixed size unsigned char array - // since the signature must be 1024 chars long - bool CFileEncrypter::VerifyData(const unsigned char *data, const size_t dataLength, const unsigned char *signature, const size_t signatureLength) - { - EVP_MD_CTX *const rsaVerifyContext = EVP_MD_CTX_new(); - // #med - double check this - it's not documented whether EVP_MD_CTX_new() can actually fail (and return null) - if (rsaVerifyContext == nullptr) { - // #high - error/exception handling - return false; - } - - // missing EVP_PKEY_free() call --- actually this will also destroy the RSA_KEY!!!! - if (EVP_DigestVerifyInit(rsaVerifyContext, nullptr, EVP_sha512(), nullptr, m_publicPKey) <= 0) { - // #high - error/exception handling - EVP_MD_CTX_free(rsaVerifyContext); - return false; - } - - if (EVP_DigestVerifyUpdate(rsaVerifyContext, data, dataLength) <= 0) { - // #high - error/exception handling - EVP_MD_CTX_free(rsaVerifyContext); - return false; - } - - // #high - review const_cast / also code simplifications - const int authenticStatus = EVP_DigestVerifyFinal(rsaVerifyContext, const_cast(signature), signatureLength); - // note: EVP_MD_CTX_destroy handles cleanup - EVP_MD_CTX_free(rsaVerifyContext); - - if (authenticStatus == 1) { - return true; - } - - // #high - add error logging/reporting - return false; - } - - bool CFileEncrypter::VerifyDataBase64(const unsigned char *data, const size_t dataLength, const char *signature, const size_t signatureLength) - { - if (signatureLength != 1368) { - // #high error reporting - return false; // signature has an incorrect size (1024 binary -> 1368 Base64) - } - - // #high - casts... / signatureLength should be 1026 (1024 plus 2 padding bytes) - if (EVP_DecodeBlock(m_sigBuffer, reinterpret_cast(signature), static_cast(signatureLength)) != 1026) { - // #high error reporting - return false; - } - - // 1026 minus two padding bytes -> 1024 - return VerifyData(data, dataLength, m_sigBuffer, 1024); - } - - int CFileEncrypter::PasswordCallback(char *buffer, int bufferSize, int, void *password) - { - CSecureString *securePassword = reinterpret_cast(password); - const char *decryptedPassword = securePassword->Decrypt(); - const size_t passwordLength = strlen(decryptedPassword); - if (passwordLength >= (size_t)bufferSize) { - securePassword->FlushUnencryptedData(); - return -1; - } - strcpy_s(buffer, bufferSize, decryptedPassword); - securePassword->FlushUnencryptedData(); - // note: static cast safe here --- already ensured that it's < bufferSize and bufferSize is of type int - return static_cast(passwordLength); - } - - const char* CFileEncrypter::SetPrivateKey(const char *privateKey, size_t privateKeyLength, CSecureString &password) - { - const char *error = ""; - - if (m_privatePKey != nullptr) { - EVP_PKEY_free(m_privatePKey); - m_privatePKey = nullptr; - // note: m_privateKey will be set below - } - - // #med - review interface handling (const cast...) - // #high - size_t -> int cast... - BIO *const keyBIO = BIO_new_mem_buf(const_cast(privateKey), static_cast(privateKeyLength)); - - // #high - error/exception handling - m_privatePKey = PEM_read_bio_PrivateKey(keyBIO, nullptr, &PasswordCallback, &password); - if (m_privatePKey == nullptr) { - error = ERR_error_string(ERR_get_error(), nullptr); - } - - // #high - add error check/handling if BIO_free() fails - BIO_free(keyBIO); - - if (m_privatePKey == nullptr) { - return error; // failed to load the private key - } - - return error; - } - - const char* CFileEncrypter::SetPublicKey(const char* publicKey, size_t publicKeyLength) - { - const char *error = ""; - - if (m_publicPKey != nullptr) { - EVP_PKEY_free(m_publicPKey); - m_publicPKey = nullptr; - // note: m_publicKey will be set below - } - - // #med - review interface handling (const cast...) - // #high - size_t -> int cast... - BIO *const keyBIO = BIO_new_mem_buf(const_cast(publicKey), static_cast(publicKeyLength)); - - // #high - error/exception handling - // #high - review &m_publicKey - m_publicPKey = PEM_read_bio_PUBKEY(keyBIO, nullptr, nullptr, nullptr); - if (m_publicPKey == nullptr) { - error = ERR_error_string(ERR_get_error(), nullptr); - } - - // #high - add error check/handling if BIO_free() fails - BIO_free(keyBIO); - - if (m_publicPKey == nullptr) { - return error; // failed to load the public key - } - return error; - } - } - } -} \ No newline at end of file diff --git a/vendors/mafianet/Source/src/crypto/securestring.cpp b/vendors/mafianet/Source/src/crypto/securestring.cpp deleted file mode 100644 index a014df590..000000000 --- a/vendors/mafianet/Source/src/crypto/securestring.cpp +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (c) 2018-2019, SLikeSoft UG (haftungsbeschraenkt) - * - * This source code is licensed under the MIT-style license found in the license.txt - * file in the root directory of this source tree. - */ -#include "mafianet/crypto/securestring.h" - -// #med - review the include order - defines.h defines SLNET_VERIFY but doesn't enforce including assert.h which it honestly should -#include "mafianet/crypto/cryptomanager.h" // used for CCryptoManager -#include "mafianet/assert.h" // used for assert() (via SLNET_VERIFY) -#include "mafianet/memoryoverride.h" // used for OP_NEW_ARRAY - -#include // used for std::memcpy -#include // used for std::numeric_limits - -namespace MafiaNet -{ - namespace Experimental - { - namespace Crypto - { - // #high - review UTF-8 mode handling --- quick and dirty addition atm - should use distinct UTF8 char-class? - CSecureString::CSecureString(const size_t maxBufferSize, const bool utf8Mode) : - m_UTF8Mode(utf8Mode), - m_wasFlushed(false), - m_numBufferSize(maxBufferSize), - m_numBufferUsed(0), - m_numEncryptedBufferUsed(0) - { - // #high - add proper handling for char sizes ~= 1 byte! - - // #med - add missing size_t overflow check if maxBufferSize == size_t::max() - // #high - raise exception upon failure to retrieve the proper size - // note: we don't encrypt the trailing null-terminator -> only requiring maxBufferSize amount of data here - m_EncryptedBufferSize = maxBufferSize; - SLNET_VERIFY(CCryptoManager::GetRequiredEncryptionBufferSize(m_EncryptedBufferSize)); - - // note: we must set the unencrypted buffer size to the size required for the encrypted buffer (which is ensured to be >= maxBufferSize) since the - // CCryptoManager::DecryptSessionData() requires the unencrypted buffer size to be at least the size of the encrypted buffer (in order to prevent potential buffer overruns) - m_UnencryptedBufferSize = m_EncryptedBufferSize + 1; // +1 for trailing '\0'-char (which is not part of the encrypted data) - - // #high - raise exception upon failure to allocate - m_EncryptedMemory = static_cast(CCryptoManager::AllocateSecureMemory(m_EncryptedBufferSize)); - // note: also keep the unencrypted buffer in the secure memory space, so any memory specific security features (f.e. privilege or enclave - // restrictions) also apply for the unencrypted data - m_UnencryptedBuffer = static_cast(CCryptoManager::AllocateSecureMemory(m_UnencryptedBufferSize)); - } - - CSecureString::~CSecureString() - { - // make sure that no data is leaked which could hint to the content of the secure string (i.e. the used size) after the object - // was destroyed - CCryptoManager::SecureClearMemory(&m_numBufferUsed, sizeof(size_t)); - - CCryptoManager::FreeSecureMemory(m_EncryptedMemory, m_EncryptedBufferSize); - m_EncryptedMemory = nullptr; - - CCryptoManager::FreeSecureMemory(m_UnencryptedBuffer, m_UnencryptedBufferSize); - m_UnencryptedBuffer = nullptr; - } - - size_t CSecureString::AddChar(char* character) - { - // #med skip or error out if '\0'? since this would just be pointless as the trailing null-terminator is written implicitly upon decryption... - if (character == nullptr) { - // #high - add error output - return 0; - } - - size_t charSize = 1; - if (m_UTF8Mode) { - // calculate char size - if (static_cast(character[0]) >= 0xF0) { - charSize = 4; - } - else if(static_cast(character[0]) >= 0xE0) { - charSize = 3; - } - else if (static_cast(character[0]) >= 0xC0) { - charSize = 2; - } - else if (static_cast(character[0]) >= 0x80) { - // invalid encoding - // #high - add error output - // note: not nulling, since obviously the input data is wrong (not a UTF8-char) - return 0; - } - // else single byte char - - // validate the 10-prefixes for bytes 2ff. - for (size_t i = 1; i < charSize; ++i) { - if (static_cast(character[i]) < 0x80) { - // #high - add error output - // note: not nulling, since obviously the input data is wrong (not a UTF8-char) - return 0; - } - } - } - - if (m_numBufferUsed + charSize > m_numBufferSize) { - // out of memory / ensure source data was cleared regardless - // #high - add error output - CCryptoManager::SecureClearMemory(character, charSize); - return 0; - } - - // decrypt, add, and re-encrypt the data - // note: do not decrypting the memory if it wasn't encrypted yet - if (m_numBufferUsed > 0) { - RakAssert(m_numEncryptedBufferUsed > 0); - size_t bufferSize = (m_UnencryptedBufferSize - 1); - // #high - add error output - if (!CCryptoManager::DecryptSessionData(m_EncryptedMemory, m_numEncryptedBufferUsed, reinterpret_cast(m_UnencryptedBuffer), bufferSize)) { - // error decrypting the encrypted memory / ensure source data was cleared regardless - CCryptoManager::SecureClearMemory(character, charSize); - return 0; - } - } - memcpy(m_UnencryptedBuffer + m_numBufferUsed, character, charSize); - m_numBufferUsed += charSize; - - // clear the source data - CCryptoManager::SecureClearMemory(character, charSize); - - // #high - add error handling - size_t bufferSize = m_EncryptedBufferSize; - // note: we always encrypt the entire buffer rather than just the used portion of it, so to not leak any information about the encrypted string (i.e. its length) - // note: correct to use m_numBufferSize here which is the actual max data-length for the secure string - const bool success = CCryptoManager::EncryptSessionData(reinterpret_cast(m_UnencryptedBuffer), m_numBufferSize, m_EncryptedMemory, bufferSize); - if (success) { - m_numEncryptedBufferUsed = bufferSize; - } - - // clear the unencrypted buffer after it got reencrypted (to be safe, clear the full buffer, not just the m_numBufferSize portion / this also prevents leaking the - // null-terminator in the buffer) - CCryptoManager::SecureClearMemory(m_UnencryptedBuffer, m_UnencryptedBufferSize); - - return success ? charSize : 0; - } - - bool CSecureString::RemoveLastChar() - { - if (m_numBufferUsed == 0) { - return false; // empty buffer - nothing to remove - } - - size_t numCharsToRemove = 0; - if (m_UTF8Mode && (m_numBufferUsed >= 1)) { - // note: if we are in UTF8-mode and only have a single encoded UTF8-byte left to remove, there's no need to decrypt and check the string - // adding a check here would be redundant with the check we do in AddChar(), which already ensures that there are no invalid UTF-8 encoded strings in the encrypted secure - // string buffer - - size_t bufferSize = (m_UnencryptedBufferSize - 1); - if (!CCryptoManager::DecryptSessionData(m_EncryptedMemory, m_numEncryptedBufferUsed, reinterpret_cast(m_UnencryptedBuffer), bufferSize)) { - // error decrypting the encrypted memory - return false; - } - - // iterate backwards over the UTF-8 encoded chars, to find the starting char (which will have a different encoding than 10xxxxxx) - while ((static_cast(m_UnencryptedBuffer[m_numBufferUsed - numCharsToRemove - 1]) & 0xC0) == 0x80) { - ++numCharsToRemove; - RakAssert(m_numBufferUsed >= numCharsToRemove); - } - - // clear the unencrypted buffer after it got reencrypted - CCryptoManager::SecureClearMemory(m_UnencryptedBuffer, m_UnencryptedBufferSize); - } - ++numCharsToRemove; // either remove a single char (in ASCII mode) or the first character before the continuing chars which were removed in the while-loop above - RakAssert(numCharsToRemove <= 4); - RakAssert(m_numBufferUsed >= numCharsToRemove); - - // note: no need to remove the character from the encrypted string - just act as if it was removed and clear the data the next time we decrypt the data - m_numBufferUsed -= numCharsToRemove; - // #high - add this handling - //m_numCharsToClear += numCharsToClear; - return true; - } - - void CSecureString::Reset() - { - // resetting the memory buffer also explicitly resets any not-yet flushed unencrypted buffer - FlushUnencryptedData(); - - // also clear the encrypted data so to not leave behind any residues of the old data (even if only in encrypted form) - CCryptoManager::SecureClearMemory(m_EncryptedMemory, m_EncryptedBufferSize); - - m_numBufferUsed = 0; - m_numEncryptedBufferUsed = 0; - } - - const char* CSecureString::Decrypt() - { - // #high - add mutex to prevent threading issues - - if (m_numBufferUsed == 0) { - return ""; // no encrypted data (prevent decrypting non-encrypted data - i.e. if never any data was added) - } - - // flushing the data here to safeguard against the user having forgotten to flush existing unencrypted data of some old encrypted data - // (which then would remain in memory if the new data's length is smaller than the old ones) - // note: since we flush the data, we don't need to write a trailing null-terminator lateron (i.e. entire memory is zeroed here) - FlushUnencryptedData(); - - size_t bufferSize = (m_UnencryptedBufferSize - 1); - if (!CCryptoManager::DecryptSessionData(m_EncryptedMemory, m_numEncryptedBufferUsed, reinterpret_cast(m_UnencryptedBuffer), bufferSize)) { - // error decrypting the encrypted memory - // #high - add error handling - return ""; - } - - // write trailing null-terminator (which is not part of the encrypted data) - m_UnencryptedBuffer[m_numBufferUsed] = '\0'; - m_wasFlushed = false; - return m_UnencryptedBuffer; - } - - void CSecureString::FlushUnencryptedData() - { - if (!m_wasFlushed) { - CCryptoManager::SecureClearMemory(m_UnencryptedBuffer, m_UnencryptedBufferSize); - m_wasFlushed = true; - } - } - } - } -} \ No newline at end of file diff --git a/vendors/mafianet/Source/src/gettimeofday.cpp b/vendors/mafianet/Source/src/gettimeofday.cpp deleted file mode 100644 index 324d283a1..000000000 --- a/vendors/mafianet/Source/src/gettimeofday.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Original work: Copyright (c) 2014, Oculus VR, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * RakNet License.txt file in the licenses directory of this source tree. An additional grant - * of patent rights can be found in the RakNet Patents.txt file in the same directory. - * - * - * Modified work: Copyright (c) 2016-2020, SLikeSoft UG (haftungsbeschränkt) - * - * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style - * license found in the license.txt file in the root directory of this source tree. - */ - -#if defined(_WIN32) && !defined(__GNUC__) &&!defined(__GCCXML__) - -#include "mafianet/gettimeofday.h" - -// From http://www.openasthra.com/c-tidbits/gettimeofday-function-for-windows/ - -#include "mafianet/WindowsIncludes.h" - -#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) - #define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64 -#else - #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL -#endif - -int gettimeofday(struct timeval *tv, struct timezone *tz) -{ - FILETIME ft; - unsigned __int64 tmpres = 0; - static int tzflag; - - if (nullptr != tv) - { - GetSystemTimeAsFileTime(&ft); - - tmpres |= ft.dwHighDateTime; - tmpres <<= 32; - tmpres |= ft.dwLowDateTime; - - /*converting file time to unix epoch*/ - tmpres /= 10; /*convert into microseconds*/ - tmpres -= DELTA_EPOCH_IN_MICROSECS; - tv->tv_sec = (long)(tmpres / 1000000UL); - tv->tv_usec = (long)(tmpres % 1000000UL); - } - - if (nullptr != tz) - { - if (!tzflag) - { - _tzset(); - tzflag++; - } - long seconds; - _get_timezone(&seconds); - tz->tz_minuteswest = seconds / 60; - _get_daylight(&(tz->tz_dsttime)); - } - return 0; -} - -#endif - diff --git a/vendors/mafianet/Source/src/guid_util.cpp b/vendors/mafianet/Source/src/guid_util.cpp deleted file mode 100644 index 62ac484c1..000000000 --- a/vendors/mafianet/Source/src/guid_util.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2024, MafiaHub - * - * This source code is licensed under the MIT-style license found in the - * license.txt file in the root directory of this source tree. - */ - -#include "mafianet/guid_util.h" - -namespace MafiaNet { - -std::string to_string(const RakNetGUID& g) -{ - // The longest possible output is "UNASSIGNED_RAKNET_GUID" (22 chars) or a - // 64-bit decimal (20 chars); 64 bytes matches the legacy buffer size and - // leaves ample headroom. Buffer is local, so this is thread-safe. - char buffer[64]; - g.ToString(buffer, sizeof(buffer)); - return std::string(buffer); -} - -std::optional connected_address(RakPeerInterface& peer, const RakNetGUID& g) -{ - const SystemAddress address = peer.GetSystemAddressFromGuid(g); - if (address == UNASSIGNED_SYSTEM_ADDRESS) - return std::nullopt; - return address; -} - -} // namespace MafiaNet diff --git a/vendors/mafianet/Source/src/linux_adapter.cpp b/vendors/mafianet/Source/src/linux_adapter.cpp deleted file mode 100644 index cdb054815..000000000 --- a/vendors/mafianet/Source/src/linux_adapter.cpp +++ /dev/null @@ -1,328 +0,0 @@ -/* - * Copyright (c) 2016-2019, SLikeSoft UG (haftungsbeschränkt) - * - * This source code is licensed under the MIT-style license found in the - * license.txt file in the root directory of this source tree. - * - * - * This file defines adapters for all MS-specific functions used throughout MafiaNet. - */ - -#ifdef __linux__ -#include "mafianet/linux_adapter.h" - -#include // for std::max, std::min -#include // for errno -#include // for FILE, fopen, vsnprintf -#include // for mbstowcs -#include // for strcat, strcpy, strerror, strncat, strncpy -#include // for va_start, va_end, va_list -#include // for localtime, time_t -#include // for wcscat, wcscpy, wcslen - -errno_t fopen_s(FILE **pfile, const char *filename, const char *mode) -{ - if ((pfile == nullptr) || (filename == nullptr) || (mode == nullptr)) { - return 22; // error: EINVAL - } - - FILE *file = fopen(filename, mode); - if (file == nullptr) { - return errno; - } - - *pfile = file; - return 0; -} - -errno_t localtime_s(struct tm *_tm, const time_t *time) -{ - // #med - should actually also check for _*time > _MAX_TIME64_T according to MSDN, but can't seem to find the - // definition of _MAX_TIME64_T - if ((_tm == nullptr) || (time == nullptr) || (*time == 0)) { - if (_tm != nullptr) { - _tm->tm_hour = -1; - _tm->tm_isdst = -1; - _tm->tm_mday = -1; - _tm->tm_min = -1; - _tm->tm_mon = -1; - _tm->tm_sec = -1; - _tm->tm_wday = -1; - _tm->tm_yday = -1; - _tm->tm_year = -1; - } - return 22; // error: EINVAL - } - - struct tm *curTime = localtime(time); - *_tm = *curTime; - - return 0; -} - -errno_t mbstowcs_s(size_t *pReturnValue, wchar_t *wcstr, size_t sizeInWords, const char *mbstr, size_t count) -{ - if ((mbstr == nullptr) || ((wcstr == nullptr) && (sizeInWords > 0)) || ((wcstr != nullptr) && (sizeInWords != 0))) { - if (wcstr != nullptr) { - wcstr[0] = L'\0'; // ensure 0-termination - } - return 22; // error: EINVAL - } - - size_t numMaxChars = sizeInWords; - if (count != _TRUNCATE) { - numMaxChars = std::min(numMaxChars, count); - } - - size_t numCharsWritten = mbstowcs(wcstr, mbstr, numMaxChars); - if (numCharsWritten == (size_t)-1) { - // invalid multibyte character encountered - if (pReturnValue != nullptr) { - *pReturnValue = 0; - } - if (wcstr != nullptr) { - wcstr[0] = L'\0'; // ensure 0-termination - } - return 42; // error: EILSEQ - } - - if (numCharsWritten == numMaxChars) { - if (wcstr != nullptr) { - wcstr[0] = L'\0'; // ensure 0-termination - } - return 34; // error: ERANGE - } - - if (pReturnValue != nullptr) { - *pReturnValue = numCharsWritten + 1; // chars written, including terminating null character - } - - // ensure we write a terminating null character (in case there was none in the original converted string) - if (wcstr != nullptr) { - wcstr[numCharsWritten] = L'\0'; // ensure 0-termination - } - - return 0; -} - -int sprintf_s(char *buffer, size_t sizeOfBuffer, const char *format, ...) -{ - if ((buffer == nullptr) || (sizeOfBuffer == 0) || (format == nullptr)) { - return -1; - } - - va_list arglist; - va_start(arglist, format); - int numCharsWritten = vsnprintf(buffer, sizeOfBuffer, format, arglist); - va_end(arglist); - - if (numCharsWritten == -1) { - buffer[0] = '\0'; // error occurred ensure terminating \0-character - return -1; - } - - if (numCharsWritten >= sizeOfBuffer) { - buffer[0] = '\0'; // buffer too small, write empty string to ensure terminating \0-char - } - - return numCharsWritten; -} - -errno_t strcat_s(char *strDestination, size_t numberOfElements, const char *strSource) -{ - if ((strDestination == nullptr) || (strSource == nullptr)) { - if (strDestination != nullptr) { - strDestination[0] = '\0'; // ensure trailing \0 is written - } - return 22; // error: EINVAL - } - - if (numberOfElements == 0) { - strDestination[0] = '\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - - const size_t destLen = strlen(strDestination); - const size_t sourceLen = strlen(strSource); - if ((destLen > numberOfElements - 1) || ((sourceLen > 0) && (destLen == numberOfElements - 1)) || (sourceLen > numberOfElements - destLen - 1)) { - strDestination[0] = '\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - - (void)strcat(strDestination, strSource); - return 0; -} - -errno_t strcpy_s(char* strDestination, size_t numberOfElements, const char *strSource) -{ - if ((strDestination == nullptr) || (strSource == nullptr)) { - if (strDestination != nullptr) { - strDestination[0] = '\0'; // ensure trailing \0 is written - } - return 22; // error: EINVAL - } - - if ((numberOfElements == 0) || (strlen(strSource) >= numberOfElements)) { - strDestination[0] = '\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - - (void)strcpy(strDestination, strSource); - return 0; -} - -errno_t strerror_s(char* buffer, size_t numberOfElements, int errnum) -{ - // check valid parameters - if ((buffer == nullptr) || (numberOfElements == 0)) { - return 22; // error: EINVAL - } - - const char *errorMessage = strerror(errnum); - return strcpy_s(buffer, numberOfElements, errorMessage); -} - -errno_t strncat_s(char *strDest, size_t numberOfElements, const char *strSource, size_t count) -{ - // check valid parameters - if ((strDest == nullptr) || (strSource == nullptr)) { - return 22; // error: EINVAL - } - - if (numberOfElements == 0) { - return 34; // error: ERANGE - } - - size_t charsToWrite; - const size_t sourceLen = strlen(strSource); - if (count == _TRUNCATE) { - charsToWrite = sourceLen; - } - else { - charsToWrite = std::min(count, sourceLen); - } - - const size_t destLen = strlen(strDest); - const size_t sizeLeft = numberOfElements - destLen; - - if (((count != _TRUNCATE) && (charsToWrite > sizeLeft - 1)) || ((sourceLen > 0) && (destLen == numberOfElements - 1))) { - strDest[0] = '\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - - (void)strncat(strDest, strSource, charsToWrite); - return 0; -} - -errno_t strncpy_s(char *strDest, size_t numberOfElements, const char *strSource, size_t count) -{ - // check valid parameters - if ((numberOfElements == 0) || (strDest == nullptr) || (strSource == nullptr)) { - if (strDest != nullptr) { - strDest[0] = '\0'; // ensure trailing \0 is written - } - return 22; // error: EINVAL - } - - size_t numChars; - bool truncated = false; - if (count == _TRUNCATE) { - // if count == _TRUNCATE use the length of the source string - numChars = strlen(strSource); - - // ensure we are not exceeding numberOfElements - if (numChars >= numberOfElements) { - numChars = numberOfElements - 1; - truncated = true; // we are going to truncate the copied string - } - } - else { - // otherwise we use count, but have to check that the destination buffer is of sufficient size - if ((count > numberOfElements) || ((count == numberOfElements) && (strSource[count] != '\0'))) { - strDest[0] = '\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - numChars = count; - } - - (void)strncpy(strDest, strSource, numChars); - - // enforce the trailing \0 - strDest[numChars] = '\0'; - - return truncated ? 80 : 0; // STRUNCATE, if we truncated the string, 0 otherwise -} - -int vsnprintf_s(char *buffer, size_t sizeOfBuffer, size_t count, const char *format, va_list argptr) -{ - if ((buffer == nullptr) || (format == nullptr) || (sizeOfBuffer == 0)) { - return -1; - } - - size_t maxChars = sizeOfBuffer; - if (count != _TRUNCATE) { - if (count >= sizeOfBuffer) { - buffer[0] = '\0'; // ensure trailing \0 is written - return -1; - } - maxChars = count; - } - - int numCharsWritten = vsnprintf(buffer, maxChars, format, argptr); - if (numCharsWritten >= maxChars) { - if (count != _TRUNCATE) { - buffer[0] = '\0'; // buffer set to empty string - return -1; - } - - // truncation occurred, add terminating \0 - buffer[sizeOfBuffer] = '\0'; - } - - return numCharsWritten; -} - -errno_t wcscat_s(wchar_t *strDestination, size_t numberOfElements, const wchar_t *strSource) -{ - if ((strDestination == nullptr) || (strSource == nullptr)) { - if (strDestination != nullptr) { - strDestination[0] = L'\0'; // ensure trailing \0 is written - } - return 22; // error: EINVAL - } - - if (numberOfElements == 0) { - strDestination[0] = L'\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - - const size_t destLen = wcslen(strDestination); - const size_t sourceLen = wcslen(strSource); - if ((destLen > numberOfElements - 1) || ((sourceLen > 0) && (destLen == numberOfElements)) || (sourceLen > numberOfElements - destLen - 1)) { - strDestination[0] = L'\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - - (void)wcscat(strDestination, strSource); - return 0; -} - -errno_t wcscpy_s(wchar_t* strDestination, size_t numberOfElements, const wchar_t *strSource) -{ - if ((strDestination == nullptr) || (strSource == nullptr)) { - if (strDestination != nullptr) { - strDestination[0] = L'\0'; // ensure trailing \0 is written - } - return 22; // error: EINVAL - } - - if ((numberOfElements == 0) || (wcslen(strSource) >= numberOfElements)) { - strDestination[0] = L'\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - - (void)wcscpy(strDestination, strSource); - return 0; -} - -#endif diff --git a/vendors/mafianet/Source/src/osx_adapter.cpp b/vendors/mafianet/Source/src/osx_adapter.cpp deleted file mode 100644 index ad52e429d..000000000 --- a/vendors/mafianet/Source/src/osx_adapter.cpp +++ /dev/null @@ -1,343 +0,0 @@ -/* - * Copyright (c) 2016-2019, SLikeSoft UG (haftungsbeschränkt) - * - * This source code is licensed under the MIT-style license found in the - * license.txt file in the root directory of this source tree. - * - * - * This file defines adapters for all MS-specific functions used throughout MafiaNet. - */ - -#ifdef __APPLE__ -#include "mafianet/osx_adapter.h" - -#include // for std::max, std::min -#include // for errno -#include // for FILE, fopen, vsnprintf -#include // for mbstowcs -#include // for strcat, strcpy, strerror, strncat, strncpy -#include // for va_start, va_end, va_list -#include // for localtime, time_t -#include // for wcscat, wcscpy, wcslen -#include // for tolower - -char *_strlwr(char *str) -{ - if (str == nullptr) { - return nullptr; - } - - char *p = str; - while (*p) { - *p = static_cast(tolower(static_cast(*p))); - ++p; - } - return str; -} - -errno_t fopen_s(FILE **pfile, const char *filename, const char *mode) -{ - if ((pfile == nullptr) || (filename == nullptr) || (mode == nullptr)) { - return 22; // error: EINVAL - } - - FILE *file = fopen(filename, mode); - if (file == nullptr) { - return errno; - } - - *pfile = file; - return 0; -} - -errno_t localtime_s(struct tm *_tm, const time_t *time) -{ - // #med - should actually also check for _*time > _MAX_TIME64_T according to MSDN, but can't seem to find the - // definition of _MAX_TIME64_T - if ((_tm == nullptr) || (time == nullptr) || (*time == 0)) { - if (_tm != nullptr) { - _tm->tm_hour = -1; - _tm->tm_isdst = -1; - _tm->tm_mday = -1; - _tm->tm_min = -1; - _tm->tm_mon = -1; - _tm->tm_sec = -1; - _tm->tm_wday = -1; - _tm->tm_yday = -1; - _tm->tm_year = -1; - } - return 22; // error: EINVAL - } - - struct tm *curTime = localtime(time); - *_tm = *curTime; - - return 0; -} - -errno_t mbstowcs_s(size_t *pReturnValue, wchar_t *wcstr, size_t sizeInWords, const char *mbstr, size_t count) -{ - if ((mbstr == nullptr) || ((wcstr == nullptr) && (sizeInWords > 0)) || ((wcstr != nullptr) && (sizeInWords != 0))) { - if (wcstr != nullptr) { - wcstr[0] = L'\0'; // ensure 0-termination - } - return 22; // error: EINVAL - } - - size_t numMaxChars = sizeInWords; - if (count != _TRUNCATE) { - numMaxChars = std::min(numMaxChars, count); - } - - size_t numCharsWritten = mbstowcs(wcstr, mbstr, numMaxChars); - if (numCharsWritten == (size_t)-1) { - // invalid multibyte character encountered - if (pReturnValue != nullptr) { - *pReturnValue = 0; - } - if (wcstr != nullptr) { - wcstr[0] = L'\0'; // ensure 0-termination - } - return 42; // error: EILSEQ - } - - if (numCharsWritten == numMaxChars) { - if (wcstr != nullptr) { - wcstr[0] = L'\0'; // ensure 0-termination - } - return 34; // error: ERANGE - } - - if (pReturnValue != nullptr) { - *pReturnValue = numCharsWritten + 1; // chars written, including terminating null character - } - - // ensure we write a terminating null character (in case there was none in the original converted string) - if (wcstr != nullptr) { - wcstr[numCharsWritten] = L'\0'; // ensure 0-termination - } - - return 0; -} - -int sprintf_s(char *buffer, size_t sizeOfBuffer, const char *format, ...) -{ - if ((buffer == nullptr) || (sizeOfBuffer == 0) || (format == nullptr)) { - return -1; - } - - va_list arglist; - va_start(arglist, format); - int numCharsWritten = vsnprintf(buffer, sizeOfBuffer, format, arglist); - va_end(arglist); - - if (numCharsWritten == -1) { - buffer[0] = '\0'; // error occurred ensure terminating \0-character - return -1; - } - - if (numCharsWritten >= sizeOfBuffer) { - buffer[0] = '\0'; // buffer too small, write empty string to ensure terminating \0-char - } - - return numCharsWritten; -} - -errno_t strcat_s(char *strDestination, size_t numberOfElements, const char *strSource) -{ - if ((strDestination == nullptr) || (strSource == nullptr)) { - if (strDestination != nullptr) { - strDestination[0] = '\0'; // ensure trailing \0 is written - } - return 22; // error: EINVAL - } - - if (numberOfElements == 0) { - strDestination[0] = '\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - - const size_t destLen = strlen(strDestination); - const size_t sourceLen = strlen(strSource); - if ((destLen > numberOfElements - 1) || ((sourceLen > 0) && (destLen == numberOfElements - 1)) || (sourceLen > numberOfElements - destLen - 1)) { - strDestination[0] = '\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - - (void)strcat(strDestination, strSource); - return 0; -} - -errno_t strcpy_s(char* strDestination, size_t numberOfElements, const char *strSource) -{ - if ((strDestination == nullptr) || (strSource == nullptr)) { - if (strDestination != nullptr) { - strDestination[0] = '\0'; // ensure trailing \0 is written - } - return 22; // error: EINVAL - } - - if ((numberOfElements == 0) || (strlen(strSource) >= numberOfElements)) { - strDestination[0] = '\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - - (void)strcpy(strDestination, strSource); - return 0; -} - -errno_t strerror_s(char* buffer, size_t numberOfElements, int errnum) -{ - // check valid parameters - if ((buffer == nullptr) || (numberOfElements == 0)) { - return 22; // error: EINVAL - } - - const char *errorMessage = strerror(errnum); - return strcpy_s(buffer, numberOfElements, errorMessage); -} - -errno_t strncat_s(char *strDest, size_t numberOfElements, const char *strSource, size_t count) -{ - // check valid parameters - if ((strDest == nullptr) || (strSource == nullptr)) { - return 22; // error: EINVAL - } - - if (numberOfElements == 0) { - return 34; // error: ERANGE - } - - size_t charsToWrite; - const size_t sourceLen = strlen(strSource); - if (count == _TRUNCATE) { - charsToWrite = sourceLen; - } - else { - charsToWrite = std::min(count, sourceLen); - } - - const size_t destLen = strlen(strDest); - const size_t sizeLeft = numberOfElements - destLen; - - if (((count != _TRUNCATE) && (charsToWrite > sizeLeft - 1)) || ((sourceLen > 0) && (destLen == numberOfElements - 1))) { - strDest[0] = '\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - - (void)strncat(strDest, strSource, charsToWrite); - return 0; -} - -errno_t strncpy_s(char *strDest, size_t numberOfElements, const char *strSource, size_t count) -{ - // check valid parameters - if ((numberOfElements == 0) || (strDest == nullptr) || (strSource == nullptr)) { - if (strDest != nullptr) { - strDest[0] = '\0'; // ensure trailing \0 is written - } - return 22; // error: EINVAL - } - - size_t numChars; - bool truncated = false; - if (count == _TRUNCATE) { - // if count == _TRUNCATE use the length of the source string - numChars = strlen(strSource); - - // ensure we are not exceeding numberOfElements - if (numChars >= numberOfElements) { - numChars = numberOfElements - 1; - truncated = true; // we are going to truncate the copied string - } - } - else { - // otherwise we use count, but have to check that the destination buffer is of sufficient size - if ((count > numberOfElements) || ((count == numberOfElements) && (strSource[count] != '\0'))) { - strDest[0] = '\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - numChars = count; - } - - (void)strncpy(strDest, strSource, numChars); - - // enforce the trailing \0 - strDest[numChars] = '\0'; - - return truncated ? 80 : 0; // STRUNCATE, if we truncated the string, 0 otherwise -} - -int vsnprintf_s(char *buffer, size_t sizeOfBuffer, size_t count, const char *format, va_list argptr) -{ - if ((buffer == nullptr) || (format == nullptr) || (sizeOfBuffer == 0)) { - return -1; - } - - size_t maxChars = sizeOfBuffer; - if (count != _TRUNCATE) { - if (count >= sizeOfBuffer) { - buffer[0] = '\0'; // ensure trailing \0 is written - return -1; - } - maxChars = count; - } - - int numCharsWritten = vsnprintf(buffer, maxChars, format, argptr); - if (numCharsWritten >= maxChars) { - if (count != _TRUNCATE) { - buffer[0] = '\0'; // buffer set to empty string - return -1; - } - - // truncation occurred, add terminating \0 - buffer[sizeOfBuffer] = '\0'; - } - - return numCharsWritten; -} - -errno_t wcscat_s(wchar_t *strDestination, size_t numberOfElements, const wchar_t *strSource) -{ - if ((strDestination == nullptr) || (strSource == nullptr)) { - if (strDestination != nullptr) { - strDestination[0] = L'\0'; // ensure trailing \0 is written - } - return 22; // error: EINVAL - } - - if (numberOfElements == 0) { - strDestination[0] = L'\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - - const size_t destLen = wcslen(strDestination); - const size_t sourceLen = wcslen(strSource); - if ((destLen > numberOfElements - 1) || ((sourceLen > 0) && (destLen == numberOfElements)) || (sourceLen > numberOfElements - destLen - 1)) { - strDestination[0] = L'\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - - (void)wcscat(strDestination, strSource); - return 0; -} - -errno_t wcscpy_s(wchar_t* strDestination, size_t numberOfElements, const wchar_t *strSource) -{ - if ((strDestination == nullptr) || (strSource == nullptr)) { - if (strDestination != nullptr) { - strDestination[0] = L'\0'; // ensure trailing \0 is written - } - return 22; // error: EINVAL - } - - if ((numberOfElements == 0) || (wcslen(strSource) >= numberOfElements)) { - strDestination[0] = L'\0'; // ensure trailing \0 is written - return 34; // error: ERANGE - } - - (void)wcscpy(strDestination, strSource); - return 0; -} - -#endif diff --git a/vendors/mafianet/VERSION.txt b/vendors/mafianet/VERSION.txt deleted file mode 100644 index 5f8787125..000000000 --- a/vendors/mafianet/VERSION.txt +++ /dev/null @@ -1,2 +0,0 @@ -MafiaNet vendored from https://github.com/MafiaHub/MafiaNet -Pinned: tag v0.10.0 (commit 0ab32ce519398443c122afb99597e1af1fb7fbd9)