Compare commits

...

39 Commits
v1.2.3 ... main

Author SHA1 Message Date
fd452f6643 Merge pull request 'NetChannels' (#19) from NetChannels into main
Reviewed-on: #19
2025-03-28 23:11:54 -07:00
c437a39e1d Added missing dependency on Windows.
All checks were successful
Build & Release / Windows-AMD64-Build (push) Successful in 4m45s
Build & Release / Linux-AMD64-Build (push) Successful in 14m40s
Build & Release / Linux-AARCH64-Build (push) Successful in 43m39s
2025-03-28 21:47:47 -07:00
8b53b6e4d1 Implemented ICMPv6 on Windows.
Some checks failed
Build & Release / Windows-AMD64-Build (push) Failing after 3m34s
Build & Release / Linux-AMD64-Build (push) Successful in 14m39s
Build & Release / Linux-AARCH64-Build (push) Successful in 43m40s
2025-03-28 21:24:13 -07:00
ff42dfd3a4 Added ICMPv6 support to Linux.
Some checks failed
Build & Release / Windows-AMD64-Build (push) Failing after 3m31s
Build & Release / Linux-AMD64-Build (push) Successful in 14m40s
Build & Release / Linux-AARCH64-Build (push) Successful in 43m42s
2025-03-28 20:53:48 -07:00
d8c5327180 Added ICMPv6 support to Windows.
Some checks failed
Build & Release / Linux-AMD64-Build (push) Has been cancelled
Build & Release / Linux-AARCH64-Build (push) Has been cancelled
Build & Release / Windows-AMD64-Build (push) Has been cancelled
2025-03-28 20:47:46 -07:00
42b26045a6 Added ICMPv6 support to Linux. 2025-03-27 00:15:02 -07:00
d41f71f17d Added IPv4 ICMP support to Windows.
All checks were successful
Build & Release / Windows-AMD64-Build (push) Successful in 4m57s
Build & Release / Linux-AMD64-Build (push) Successful in 14m40s
Build & Release / Linux-AARCH64-Build (push) Successful in 43m36s
2025-03-26 11:45:54 -07:00
c19c0bc80b Renamed member variables and parameters.
All checks were successful
Build & Release / Windows-AMD64-Build (push) Successful in 4m10s
Build & Release / Linux-AMD64-Build (push) Successful in 14m40s
Build & Release / Linux-AARCH64-Build (push) Successful in 43m37s
2025-03-26 10:42:29 -07:00
86149d246a Renamed member variables and parameters.
Some checks failed
Build & Release / Linux-AMD64-Build (push) Failing after 10s
Build & Release / Linux-AARCH64-Build (push) Failing after 14s
Build & Release / Windows-AMD64-Build (push) Successful in 4m16s
2025-03-26 10:29:20 -07:00
1e55b11eed Fixed CMakeLists.
All checks were successful
Build & Release / Windows-AMD64-Build (push) Successful in 4m23s
Build & Release / Linux-AMD64-Build (push) Successful in 14m40s
Build & Release / Linux-AARCH64-Build (push) Successful in 43m36s
2025-03-25 19:43:42 -07:00
ce225b2888 Fixed CMakeLists and BaseICMP.cpp.
Some checks failed
Build & Release / Linux-AMD64-Build (push) Has been cancelled
Build & Release / Linux-AARCH64-Build (push) Has been cancelled
Build & Release / Windows-AMD64-Build (push) Has been cancelled
2025-03-25 19:42:40 -07:00
eb3d345c5a Fixed gitea workflow.
Some checks failed
Build & Release / Windows-AMD64-Build (push) Failing after 9m49s
Build & Release / Linux-AMD64-Build (push) Successful in 14m41s
Build & Release / Linux-AARCH64-Build (push) Successful in 43m37s
2025-03-25 19:26:10 -07:00
6cf4977a6c Fixed gitea workflow.
Some checks failed
Build & Release / Linux-AMD64-Build (push) Has been cancelled
Build & Release / Linux-AARCH64-Build (push) Has been cancelled
Build & Release / Windows-AMD64-Build (push) Has been cancelled
2025-03-25 19:22:08 -07:00
ae226c9a84 Fixed gitea workflow.
Some checks failed
Build & Release / Windows-AMD64-Build (push) Failing after 15s
Build & Release / Linux-AMD64-Build (push) Successful in 14m41s
Build & Release / Linux-AARCH64-Build (push) Successful in 43m37s
2025-03-25 19:20:24 -07:00
bf3b063e96 Fixed gitea workflow.
Some checks failed
Build & Release / Windows-AMD64-Build (push) Failing after 19s
Build & Release / Linux-AMD64-Build (push) Successful in 14m39s
Build & Release / Linux-AARCH64-Build (push) Successful in 43m36s
2025-03-25 19:17:53 -07:00
e071877045 Fixed gitea workflow.
Some checks failed
Build & Release / Windows-AMD64-Build (push) Failing after 14s
Build & Release / Linux-AMD64-Build (push) Successful in 14m40s
Build & Release / Linux-AARCH64-Build (push) Successful in 43m37s
2025-03-25 19:15:32 -07:00
af90f90156 Fixed gitea workflow.
Some checks failed
Build & Release / Windows-AMD64-Build (push) Failing after 14s
Build & Release / Linux-AMD64-Build (push) Successful in 14m39s
Build & Release / Linux-AARCH64-Build (push) Successful in 43m37s
2025-03-25 18:49:14 -07:00
389fa61fba Merge pull request 'Fixed gitea workflow.' (#18) from NetChannels into main
Reviewed-on: #18
2025-03-25 18:43:47 -07:00
16ef5bbb74 Fixed gitea workflow.
Some checks failed
Build & Release / Linux-AMD64-Build (push) Successful in 14m41s
Build & Release / Windows-AMD64-Build (push) Failing after 23s
Build & Release / Linux-AARCH64-Build (push) Successful in 43m36s
2025-03-25 18:42:56 -07:00
a67197766e Merge pull request 'Fixed gitea workflow.' (#17) from NetChannels into main
Some checks failed
Build & Release / Windows-AMD64-Build (push) Failing after 25s
Build & Release / Linux-AMD64-Build (push) Failing after 11m42s
Build & Release / Linux-AARCH64-Build (push) Successful in 43m39s
Reviewed-on: #17
2025-03-25 18:37:27 -07:00
6cba7d6698 Fixed gitea workflow. 2025-03-25 18:35:52 -07:00
ae414c5c99 Merge pull request 'Added CPU::GetCacheLineSize() definition for Windows.' (#16) from NetChannels into main
Reviewed-on: #16
2025-03-25 16:50:40 -07:00
9ab62d0545 Added CPU::GetCacheLineSize() definition for Windows.
Some checks failed
Build & Release / Windows-AMD64-Build (push) Failing after 25s
Build & Release / Linux-AMD64-Build (push) Failing after 13m28s
Build & Release / Linux-AARCH64-Build (push) Failing after 1m0s
2025-03-25 16:45:18 -07:00
b44e55a92c Merge pull request 'NetChannels' (#15) from NetChannels into main
Reviewed-on: EventHorizonStudio/EHS#15
2025-03-23 03:22:41 -07:00
53d86eb539 Merge remote-tracking branch 'origin/NetChannels' into NetChannels
Some checks failed
Build & Release / Windows-AMD64-Build (push) Failing after 9m34s
Build & Release / Linux-AMD64-Build (push) Failing after 1m58s
Build & Release / Linux-AARCH64-Build (push) Failing after 5m21s
2025-03-23 03:11:24 -07:00
352b4d612f First commit for ICMP capabilities, added CPU::GetCacheLineSize(), and removed BaseObj from containers. 2025-03-23 03:10:35 -07:00
89925fe820 Renamed member variables and parameters. 2025-01-30 13:01:01 -08:00
16b56a7084 Made NetChannel methods public in EHC. 2025-01-30 12:32:52 -08:00
62f8a662a0 Backup. 2025-01-29 16:21:11 -08:00
39bbcd0d56 Added missing constructor for NetChannel in NetServerCh. 2025-01-28 04:28:55 -08:00
981b40d3b1 Finished implementing, now for the testing phase. 2025-01-26 21:43:17 -08:00
7bc4b9977d Merge pull request 'Added the capability for custom encryption's to be added to EHC.' (#14) from fix into main
All checks were successful
Build & Release / Windows-AMD64-Build (push) Successful in 6m24s
Build & Release / Linux-AMD64-Build (push) Successful in 13m7s
Build & Release / Linux-AARCH64-Build (push) Successful in 39m52s
Reviewed-on: EventHorizonStudio/EHS#14
2024-10-06 23:20:53 -07:00
79860c7d39 Added the capability for custom encryption's to be added to EHC.
Some checks failed
Build & Release / Windows-AMD64-Build (push) Waiting to run
Build & Release / Linux-AARCH64-Build (push) Has been cancelled
Build & Release / Linux-AMD64-Build (push) Has been cancelled
2024-10-06 23:19:42 -07:00
99bab4a6ef Merge pull request 'New Audio and EHC PR' (#13) from audio into main
Some checks failed
Build & Release / Linux-AMD64-Build (push) Failing after 3m34s
Build & Release / Windows-AMD64-Build (push) Successful in 6m44s
Build & Release / Linux-AARCH64-Build (push) Has been cancelled
Reviewed-on: EventHorizonStudio/EHS#13
2024-10-06 23:00:31 -07:00
8b01ee3c46 Added the capability for custom encryption's to be added to EHC. 2024-10-06 22:54:29 -07:00
1feff0a25c Moved the Event Horizon Communications to this project. 2024-10-06 20:08:22 -07:00
9b42ad6d74 Simplified audio playback & capturing significantly. 2024-10-06 17:24:32 -07:00
9639329df3 Updated readme. 2024-10-06 01:16:04 -07:00
6cd686a17e Updated readme. 2024-10-06 01:14:14 -07:00
68 changed files with 4683 additions and 294 deletions

View File

@ -22,10 +22,9 @@ jobs:
- name: Building/Compiling/Installing Project - name: Building/Compiling/Installing Project
run: | run: |
cd ${{ gitea.workspace }} cd ${{ gitea.workspace }}
vcpkg install
mkdir build mkdir build
cd build cd build
cmake -A x64 -DCMAKE_BUILD_TYPE=Release .. cmake -A x64 -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE="$env:VCPKG_ROOT\scripts\buildsystems\vcpkg.cmake" ..
cmake --build . --config Release cmake --build . --config Release
cmake --install . cmake --install .
@ -56,6 +55,7 @@ jobs:
files: |- files: |-
ehs-windows-amd64.zip ehs-windows-amd64.zip
api_key: '${{secrets.RELEASE_TOKEN}}' api_key: '${{secrets.RELEASE_TOKEN}}'
pre_release: false
Linux-AMD64-Build: Linux-AMD64-Build:
runs-on: linux-x86_64 runs-on: linux-x86_64
@ -101,6 +101,7 @@ jobs:
files: |- files: |-
ehs-linux-amd64.zip ehs-linux-amd64.zip
api_key: '${{secrets.RELEASE_TOKEN}}' api_key: '${{secrets.RELEASE_TOKEN}}'
pre_release: false
Linux-AARCH64-Build: Linux-AARCH64-Build:
runs-on: linux-aarch64 runs-on: linux-aarch64
@ -144,4 +145,5 @@ jobs:
with: with:
files: |- files: |-
ehs-linux-aarch64.zip ehs-linux-aarch64.zip
api_key: '${{secrets.RELEASE_TOKEN}}' api_key: '${{secrets.RELEASE_TOKEN}}'
pre_release: false

View File

@ -121,20 +121,27 @@ set(EHS_SOURCES
include/ehs/io/FileMonitor.h include/ehs/io/FileMonitor.h
include/ehs/io/Window.h include/ehs/io/Window.h
include/ehs/io/socket/Socket.h
src/io/socket/Request.cpp include/ehs/io/socket/Request.h src/io/socket/Request.cpp include/ehs/io/socket/Request.h
src/io/socket/Response.cpp include/ehs/io/socket/Response.h src/io/socket/Response.cpp include/ehs/io/socket/Response.h
src/io/socket/BaseDNS.cpp include/ehs/io/socket/BaseDNS.h src/io/socket/BaseDNS.cpp include/ehs/io/socket/BaseDNS.h
include/ehs/io/socket/DNS.h
src/io/socket/BaseUDP.cpp include/ehs/io/socket/BaseUDP.h src/io/socket/BaseUDP.cpp include/ehs/io/socket/BaseUDP.h
include/ehs/io/socket/UDP.h
src/io/socket/BaseTCP.cpp include/ehs/io/socket/BaseTCP.h src/io/socket/BaseTCP.cpp include/ehs/io/socket/BaseTCP.h
include/ehs/io/socket/TCP.h
src/io/socket/SSL.cpp include/ehs/io/socket/SSL.h src/io/socket/SSL.cpp include/ehs/io/socket/SSL.h
include/ehs/io/socket/ehc/NetUtils.h
src/io/socket/EHC.cpp include/ehs/io/socket/EHC.h
src/io/socket/ehc/NetFrag.cpp include/ehs/io/socket/ehc/NetFrag.h
src/io/socket/ehc/NetEnd.cpp include/ehs/io/socket/ehc/NetEnd.h
src/io/socket/ehc/NetSys.cpp include/ehs/io/socket/ehc/NetSys.h
src/io/socket/ehc/NetOp.cpp include/ehs/io/socket/ehc/NetOp.h
src/io/socket/rest/Twitch.cpp include/ehs/io/socket/rest/Twitch.h src/io/socket/rest/Twitch.cpp include/ehs/io/socket/rest/Twitch.h
src/io/socket/rest/TwitchChat.cpp include/ehs/io/socket/rest/TwitchChat.h src/io/socket/rest/TwitchChat.cpp include/ehs/io/socket/rest/TwitchChat.h
src/io/socket/rest/Spotify.cpp include/ehs/io/socket/rest/Spotify.h src/io/socket/rest/Spotify.cpp include/ehs/io/socket/rest/Spotify.h
include/ehs/io/socket/Socket.h
include/ehs/io/socket/TCP.h
include/ehs/io/socket/UDP.h
include/ehs/io/socket/DNS.h
src/io/audio/Audio.cpp include/ehs/io/audio/Audio.h src/io/audio/Audio.cpp include/ehs/io/audio/Audio.h
src/io/audio/BaseAudioDevice.cpp include/ehs/io/audio/BaseAudioDevice.h src/io/audio/BaseAudioDevice.cpp include/ehs/io/audio/BaseAudioDevice.h
@ -178,6 +185,17 @@ set(EHS_SOURCES
include/ehs/io/BaseDirectory.h include/ehs/io/BaseDirectory.h
src/io/BaseDirectory.cpp src/io/BaseDirectory.cpp
include/ehs/io/Directory.h include/ehs/io/Directory.h
include/ehs/io/socket/ehc/NetEnc.h
src/io/socket/ehc/NetEnc.cpp
include/ehs/io/socket/ehc/NetChannel.h
src/io/socket/ehc/NetChannel.cpp
include/ehs/io/socket/ehc/NetServerCh.h
include/ehs/io/socket/ehc/NetClientCh.h
src/io/socket/ehc/NetClientCh.cpp
src/io/socket/ehc/NetServerCh.cpp
src/io/socket/ehc/NetUtils.cpp
include/ehs/io/socket/BaseICMP.h src/io/socket/BaseICMP.cpp
include/ehs/io/socket/ICMP.h
) )
if (IS_OS_WINDOWS) if (IS_OS_WINDOWS)
@ -196,7 +214,9 @@ if (IS_OS_WINDOWS)
src/io/COM.cpp include/ehs/io/COM.h src/io/COM.cpp include/ehs/io/COM.h
src/system/CPU_MSVC_AMD64.asm src/HRNG_MSVC.asm src/Math_MSVC_AMD64.asm src/system/CPU_MSVC_AMD64.asm src/HRNG_MSVC.asm src/Math_MSVC_AMD64.asm
src/io/Directory_W32.cpp include/ehs/io/Directory_W32.h src/io/Directory_W32.cpp include/ehs/io/Directory_W32.h
include/ehs/io/socket/ICMP_W32.h src/io/socket/ICMP_W32.cpp
) )
elseif (IS_OS_LINUX) elseif (IS_OS_LINUX)
list(APPEND EHS_SOURCES list(APPEND EHS_SOURCES
src/io/socket/UDP_BSD.cpp include/ehs/io/socket/UDP_BSD.h src/io/socket/UDP_BSD.cpp include/ehs/io/socket/UDP_BSD.h
@ -213,6 +233,7 @@ elseif (IS_OS_LINUX)
src/system/User.cpp include/ehs/system/User.h src/system/User.cpp include/ehs/system/User.h
src/io/Directory_LNX.cpp include/ehs/io/Directory_LNX.h src/io/Directory_LNX.cpp include/ehs/io/Directory_LNX.h
src/io/Usb_LNX.cpp include/ehs/io/Usb_LNX.h src/io/Usb_LNX.cpp include/ehs/io/Usb_LNX.h
include/ehs/io/socket/ICMP_LNX.h src/io/socket/ICMP_LNX.cpp
) )
#set(LINUX_WINDOW_SYSTEM "Wayland" CACHE STRING "Linux Window System") #set(LINUX_WINDOW_SYSTEM "Wayland" CACHE STRING "Linux Window System")
@ -291,7 +312,7 @@ target_link_libraries(EHS_Dyn OpenSSL::SSL OpenSSL::Crypto ZLIB::ZLIB)
target_link_libraries(StrToHash OpenSSL::SSL OpenSSL::Crypto ZLIB::ZLIB) target_link_libraries(StrToHash OpenSSL::SSL OpenSSL::Crypto ZLIB::ZLIB)
if (IS_OS_WINDOWS) if (IS_OS_WINDOWS)
target_link_libraries(EHS_Dyn avrt ws2_32) target_link_libraries(EHS_Dyn avrt ws2_32 IPHLPAPI)
target_link_libraries(StrToHash ws2_32 avrt EHS_Stc) target_link_libraries(StrToHash ws2_32 avrt EHS_Stc)
elseif (IS_OS_LINUX) elseif (IS_OS_LINUX)
if (LINUX_WINDOW_SYSTEM STREQUAL "Wayland") if (LINUX_WINDOW_SYSTEM STREQUAL "Wayland")

View File

@ -22,6 +22,7 @@ This project does not fully follow the C++ standard.
- Semaphores - Semaphores
- CPU information and features at runtime - CPU information and features at runtime
- HTTP(S) Socket Layer - HTTP(S) Socket Layer
- ICMP & ICMPv6 Socket
- TCP Socket - TCP Socket
- UDP Socket - UDP Socket
- COM (Serial) IO - COM (Serial) IO
@ -73,6 +74,8 @@ Wayland Window System. Wayland support is currently not fully supported yet, use
- [CMake](https://cmake.org/) - [CMake](https://cmake.org/)
- [vcpkg](https://learn.microsoft.com/en-us/vcpkg/get_started/get-started?pivots=shell-cmd) - [vcpkg](https://learn.microsoft.com/en-us/vcpkg/get_started/get-started?pivots=shell-cmd)
`vcpkg install` - Use this command in the directory where `vcpkg.json` is located to download/install dependencies.
### Building ### Building
`cmake -A x64 -DCMAKE_BUILD_TYPE=Release /path/to/source` `cmake -A x64 -DCMAKE_BUILD_TYPE=Release /path/to/source`
@ -101,7 +104,7 @@ int main()
if (!response.IsNum()) if (!response.IsNum())
{ {
ehs::Console::Clear(); // Clear the console's buffer. ehs::Console::Clear(); // Clear the console's buffer.
return Main(appName, appVerId, appVer); // Repeat process if given response is not a number. return main(); // Repeat process if given response is not a number.
} }
ehs::UInt_8 age = response.ToDecimal<ehs::UInt_8>(); // Converts the string number into a number based primitive. ehs::UInt_8 age = response.ToDecimal<ehs::UInt_8>(); // Converts the string number into a number based primitive.

View File

@ -12,7 +12,7 @@ namespace ehs
/// @tparam T Array data type to use. /// @tparam T Array data type to use.
/// @tparam N Number data type to use. /// @tparam N Number data type to use.
template<typename T, typename N = UInt_64> template<typename T, typename N = UInt_64>
class Array : public BaseObj class Array
{ {
protected: protected:
T* data; T* data;
@ -20,7 +20,7 @@ namespace ehs
public: public:
/// Frees any data created on the heap. /// Frees any data created on the heap.
~Array() override ~Array()
{ {
delete[] data; delete[] data;
} }
@ -29,7 +29,6 @@ namespace ehs
Array() Array()
: data(nullptr), size(0) : data(nullptr), size(0)
{ {
AddType("Array");
} }
/// Initializes an empty array with the given size. /// Initializes an empty array with the given size.
@ -37,7 +36,6 @@ namespace ehs
explicit Array(const N size) explicit Array(const N size)
: data(new T[size]), size(size) : data(new T[size]), size(size)
{ {
AddType("Array");
} }
/// Initializes this array with an initializer list object. /// Initializes this array with an initializer list object.
@ -45,8 +43,6 @@ namespace ehs
Array(std::initializer_list<T> list) Array(std::initializer_list<T> list)
: data(new T[list.size()]), size(list.size()) : data(new T[list.size()]), size(list.size())
{ {
AddType("Array");
N i = 0; N i = 0;
for (auto v = list.begin(); v != list.end(); ++v) for (auto v = list.begin(); v != list.end(); ++v)
data[i++] = std::move(*v); data[i++] = std::move(*v);
@ -58,14 +54,12 @@ namespace ehs
Array(const T* const data, const N size) Array(const T* const data, const N size)
: data(new T[size]), size(size) : data(new T[size]), size(size)
{ {
AddType("Array");
for (N i = 0; i < size; ++i) for (N i = 0; i < size; ++i)
this->data[i] = data[i]; this->data[i] = data[i];
} }
Array(Array&& array) noexcept Array(Array&& array) noexcept
: BaseObj(array), data(array.data), size(array.size) : data(array.data), size(array.size)
{ {
array.data = nullptr; array.data = nullptr;
array.size = 0; array.size = 0;
@ -74,7 +68,7 @@ namespace ehs
/// Copies all members from the given array object. /// Copies all members from the given array object.
/// @param [in] array The array object to copy from. /// @param [in] array The array object to copy from.
Array(const Array& array) Array(const Array& array)
: BaseObj((BaseObj&&)array), data(new T[array.size]), size(array.size) : data(new T[array.size]), size(array.size)
{ {
for (N i = 0; i < size; ++i) for (N i = 0; i < size; ++i)
data[i] = array.data[i]; data[i] = array.data[i];
@ -85,8 +79,6 @@ namespace ehs
if (this == &array) if (this == &array)
return *this; return *this;
BaseObj::operator=((BaseObj&&)array);
delete[] data; delete[] data;
data = array.data; data = array.data;
size = array.size; size = array.size;
@ -105,8 +97,6 @@ namespace ehs
if (this == &array) if (this == &array)
return *this; return *this;
BaseObj::operator=(array);
delete[] data; delete[] data;
data = new T[array.size]; data = new T[array.size];
for (N i = 0; i < array.size; ++i) for (N i = 0; i < array.size; ++i)

View File

@ -21,7 +21,7 @@
namespace ehs namespace ehs
{ {
template<typename N = UInt_64> template<typename N = UInt_64>
class Serializer : public BaseObj class Serializer
{ {
private: private:
Endianness endianness; Endianness endianness;
@ -30,7 +30,7 @@ namespace ehs
N offset; N offset;
public: public:
~Serializer() override ~Serializer()
{ {
delete[] data; delete[] data;
} }
@ -38,32 +38,27 @@ namespace ehs
Serializer() Serializer()
: endianness(Endianness::BE), data(nullptr), size(0), offset(0) : endianness(Endianness::BE), data(nullptr), size(0), offset(0)
{ {
AddType("Serializer");
} }
Serializer(const Endianness endianness) Serializer(const Endianness endianness)
: endianness(endianness), data(nullptr), size(0), offset(0) : endianness(endianness), data(nullptr), size(0), offset(0)
{ {
AddType("Serializer");
} }
Serializer(const Endianness endianness, const N size) Serializer(const Endianness endianness, const N size)
: endianness(endianness), data(new Byte[size]), size(size), offset(0) : endianness(endianness), data(new Byte[size]), size(size), offset(0)
{ {
AddType("Serializer");
} }
Serializer(const Endianness endianness, const Byte* const data, const N size, const N offset = 0) Serializer(const Endianness endianness, const Byte* const data, const N size, const N offset = 0)
: endianness(endianness), data(new Byte[size]), size(size), offset(offset) : endianness(endianness), data(new Byte[size]), size(size), offset(offset)
{ {
AddType("Serializer");
for (N i = 0; i < size; ++i) for (N i = 0; i < size; ++i)
this->data[i] = data[i]; this->data[i] = data[i];
} }
Serializer(Serializer&& serializer) noexcept Serializer(Serializer&& serializer) noexcept
: BaseObj((BaseObj&&)serializer), endianness(serializer.endianness), data(serializer.data), : endianness(serializer.endianness), data(serializer.data),
size(serializer.size), offset(serializer.offset) size(serializer.size), offset(serializer.offset)
{ {
serializer.data = nullptr; serializer.data = nullptr;
@ -72,7 +67,7 @@ namespace ehs
} }
Serializer(const Serializer& serializer) Serializer(const Serializer& serializer)
: BaseObj(serializer), endianness(serializer.endianness), data(new Byte[serializer.size]), : endianness(serializer.endianness), data(new Byte[serializer.size]),
size(serializer.size), offset(serializer.offset) size(serializer.size), offset(serializer.offset)
{ {
for (N i = 0; i < serializer.size; ++i) for (N i = 0; i < serializer.size; ++i)
@ -84,8 +79,6 @@ namespace ehs
if (this == &serializer) if (this == &serializer)
return *this; return *this;
BaseObj::operator=((Serializer&&)serializer);
endianness = serializer.endianness; endianness = serializer.endianness;
delete[] data; delete[] data;
data = serializer.data; data = serializer.data;
@ -104,8 +97,6 @@ namespace ehs
if (this == &serializer) if (this == &serializer)
return *this; return *this;
BaseObj::operator=(serializer);
endianness = serializer.endianness; endianness = serializer.endianness;
delete[] data; delete[] data;
@ -1228,7 +1219,7 @@ namespace ehs
void Resize(const N newSize) void Resize(const N newSize)
{ {
Byte* result = new Byte[newSize]; Byte* result = new Byte[newSize];
Util::Copy(result, data, size); Util::Copy(result, data, newSize >= size ? size : newSize);
delete[] data; delete[] data;
data = result; data = result;
size = newSize; size = newSize;

View File

@ -25,7 +25,7 @@ namespace ehs
/// @tparam T The character's data type to use. /// @tparam T The character's data type to use.
/// @tparam N The number data type to use. /// @tparam N The number data type to use.
template<typename T = Char_8, typename N = UInt_64> template<typename T = Char_8, typename N = UInt_64>
class Str : public BaseObj class Str
{ {
private: private:
N size; N size;
@ -33,7 +33,7 @@ namespace ehs
public: public:
/// Frees any data created on the heap. /// Frees any data created on the heap.
~Str() override ~Str()
{ {
delete[] data; delete[] data;
} }
@ -42,7 +42,6 @@ namespace ehs
Str() Str()
: size(0), data(nullptr) : size(0), data(nullptr)
{ {
AddType("Str");
} }
/// Initializes members with given C-style string. /// Initializes members with given C-style string.
@ -56,8 +55,6 @@ namespace ehs
Util::Copy(data, str, Size(true)); Util::Copy(data, str, Size(true));
data[this->size] = 0; data[this->size] = 0;
AddType("Str");
} }
/// Initializes members with given C-style string. /// Initializes members with given C-style string.
@ -70,8 +67,6 @@ namespace ehs
Util::Copy(data, str, Size(true)); Util::Copy(data, str, Size(true));
data[size] = 0; data[size] = 0;
AddType("Str");
} }
/// Initializes string with the given size. /// Initializes string with the given size.
@ -80,13 +75,11 @@ namespace ehs
: size(size), data(new T[size + 1]) : size(size), data(new T[size + 1])
{ {
data[size] = 0; data[size] = 0;
AddType("Str");
} }
/// A move constructor. /// A move constructor.
Str(Str&& str) noexcept Str(Str&& str) noexcept
: BaseObj((BaseObj&&)str), size(str.size), data(str.data) : size(str.size), data(str.data)
{ {
str.size = 0; str.size = 0;
str.data = nullptr; str.data = nullptr;
@ -95,7 +88,7 @@ namespace ehs
/// Copies all members from the given string object. /// Copies all members from the given string object.
/// @param [in] str The string object to copy from. /// @param [in] str The string object to copy from.
Str(const Str& str) Str(const Str& str)
: BaseObj(str), size(str.size), data(new T[size + 1]) : size(str.size), data(new T[size + 1])
{ {
Util::Copy(data, str.data, Size(true)); Util::Copy(data, str.data, Size(true));
@ -107,8 +100,6 @@ namespace ehs
if (this == &str) if (this == &str)
return *this; return *this;
BaseObj::operator=((BaseObj&&)str);
size = str.size; size = str.size;
delete[] data; delete[] data;
data = str.data; data = str.data;
@ -127,8 +118,6 @@ namespace ehs
if (&str == this) if (&str == this)
return *this; return *this;
BaseObj::operator=(str);
size = str.size; size = str.size;
delete[] data; delete[] data;

View File

@ -14,7 +14,7 @@ namespace ehs
/// @tparam N Number data type to use. /// @tparam N Number data type to use.
/// @note If extra memory is set to five then each time that memory is filled it will add five extra. /// @note If extra memory is set to five then each time that memory is filled it will add five extra.
template<typename T, typename N = UInt_64> template<typename T, typename N = UInt_64>
class Vector : public BaseObj class Vector
{ {
protected: protected:
N rawSize; N rawSize;
@ -24,7 +24,7 @@ namespace ehs
public: public:
/// Frees any data created on the heap. /// Frees any data created on the heap.
~Vector() override ~Vector()
{ {
delete[] data; delete[] data;
} }
@ -33,7 +33,6 @@ namespace ehs
Vector() Vector()
: rawSize(0), size(0), stride(5), data(nullptr) : rawSize(0), size(0), stride(5), data(nullptr)
{ {
AddType("Vector");
} }
/// Initializes members for pre-allocated memory to write to later. /// Initializes members for pre-allocated memory to write to later.
@ -42,7 +41,6 @@ namespace ehs
Vector(const N size, const N stride) Vector(const N size, const N stride)
: rawSize(size + stride), size(size), stride(stride), data(new T[rawSize]) : rawSize(size + stride), size(size), stride(stride), data(new T[rawSize])
{ {
AddType("Vector");
} }
/// Initializes this vector with an initializer list object. /// Initializes this vector with an initializer list object.
@ -51,8 +49,6 @@ namespace ehs
Vector(std::initializer_list<T> list, const N stride = 5) Vector(std::initializer_list<T> list, const N stride = 5)
: rawSize(0), size(list.size()), stride(stride), data(nullptr) : rawSize(0), size(list.size()), stride(stride), data(nullptr)
{ {
AddType("Vector");
if (stride) if (stride)
{ {
rawSize = list.size() / stride * stride; rawSize = list.size() / stride * stride;
@ -78,8 +74,6 @@ namespace ehs
Vector(const T* data, const N size, const N stride) Vector(const T* data, const N size, const N stride)
: rawSize(0), size(size), stride(stride), data(nullptr) : rawSize(0), size(size), stride(stride), data(nullptr)
{ {
AddType("Vector");
if (stride) if (stride)
{ {
rawSize = size / stride * stride; rawSize = size / stride * stride;
@ -100,14 +94,14 @@ namespace ehs
/// Copies all members from the given vector object. /// Copies all members from the given vector object.
/// @param [in] vec The vector object to copy from. /// @param [in] vec The vector object to copy from.
Vector(const Vector& vec) Vector(const Vector& vec)
: BaseObj(vec), rawSize(vec.rawSize), size(vec.size), stride(vec.stride), data(new T[rawSize]) : rawSize(vec.rawSize), size(vec.size), stride(vec.stride), data(new T[rawSize])
{ {
for (N i = 0; i < size; ++i) for (N i = 0; i < size; ++i)
data[i] = vec.data[i]; data[i] = vec.data[i];
} }
Vector(Vector&& vec) noexcept Vector(Vector&& vec) noexcept
: BaseObj((BaseObj&&)vec), rawSize(vec.rawSize), size(vec.size), stride(vec.stride), data(vec.data) : rawSize(vec.rawSize), size(vec.size), stride(vec.stride), data(vec.data)
{ {
vec.rawSize = 0; vec.rawSize = 0;
vec.size = 0; vec.size = 0;
@ -123,8 +117,6 @@ namespace ehs
if (this == &vec) if (this == &vec)
return *this; return *this;
BaseObj::operator=(vec);
rawSize = vec.rawSize; rawSize = vec.rawSize;
size = vec.size; size = vec.size;
stride = vec.stride; stride = vec.stride;
@ -143,8 +135,6 @@ namespace ehs
if (this == &vec) if (this == &vec)
return *this; return *this;
BaseObj::operator=((BaseObj&&)vec);
rawSize = vec.rawSize; rawSize = vec.rawSize;
size = vec.size; size = vec.size;
stride = vec.stride; stride = vec.stride;

View File

@ -81,10 +81,14 @@ namespace ehs
UInt_64 GetSampleCount() const; UInt_64 GetSampleCount() const;
UInt_8 GetFrameSize() const;
UInt_64 GetSize() const; UInt_64 GetSize() const;
float GetLength() const; float GetLength() const;
Byte* GetFrame(UInt_64 frameIndex) const;
Array<Byte> FrameAsMono(UInt_64 frameIndex) const; Array<Byte> FrameAsMono(UInt_64 frameIndex) const;
Array<Byte> FrameAsStereo(UInt_64 frameIndex) const; Array<Byte> FrameAsStereo(UInt_64 frameIndex) const;

View File

@ -52,7 +52,9 @@ namespace ehs
virtual UInt_64 ReceiveStream(void *data, UInt_64 size); virtual UInt_64 ReceiveStream(void *data, UInt_64 size);
void BridgeStreams(UInt_64 bufferSize); void BridgeStreams(BaseAudioDevice *input, UInt_64 frameBufferSize);
void BridgeStreams(UInt_64 frameBufferSize);
AudioDeviceType GetType() const; AudioDeviceType GetType() const;

View File

@ -8,7 +8,7 @@ namespace ehs
class EHS_LIB_IO BaseDNS class EHS_LIB_IO BaseDNS
{ {
public: public:
static Str_8 Resolve(AddrType type, const Str_8 &hostname); static Str_8 Resolve(IP type, const Str_8 &hostname);
/// Resolves a hostname to an ip address. /// Resolves a hostname to an ip address.
/// @param [in] hostname The given hostname to resolve. /// @param [in] hostname The given hostname to resolve.

View File

@ -0,0 +1,68 @@
#pragma once
#include "ehs/Serializer.h"
#include "ehs/Types.h"
#include "ehs/io/socket/Socket.h"
namespace ehs
{
struct ICMP_Header
{
UInt_8 type;
UInt_8 code;
UInt_16 checksum;
};
struct ICMP_EchoRequest
{
UInt_16 id;
UInt_16 sequence;
};
class BaseICMP
{
private:
IP version;
public:
virtual ~BaseICMP() = default;
BaseICMP();
BaseICMP(IP version);
BaseICMP(BaseICMP &&icmp) noexcept;
BaseICMP(const BaseICMP &icmp);
BaseICMP &operator=(BaseICMP &&icmp) noexcept;
BaseICMP &operator=(const BaseICMP &icmp);
virtual void Release();
UInt_64 Send(const Str_8 &address, ICMP_Header header, const Byte *data, UInt_64 size);
UInt_64 Receive(Str_8 &address, ICMP_Header &header, Serializer<UInt_64> &data);
void SendEchoRequest(const Str_8 &address, ICMP_EchoRequest er, const Byte *data, UInt_64 size);
virtual void SetReceiveTimeout(UInt_64 timeout);
IP GetVersion() const;
virtual bool IsValid() const;
protected:
static UInt_16 ComputeChecksumV4(UInt_16 *buffer, Size length);
private:
virtual UInt_64 SendV6(const Str_8 &address, ICMP_Header header, const Byte *data, UInt_64 size);
virtual UInt_64 SendV4(const Str_8 &address, ICMP_Header header, const Byte *data, UInt_64 size);
virtual UInt_64 ReceiveV6(Str_8 &address, ICMP_Header &header, Serializer<UInt_64> &data) const;
virtual UInt_64 ReceiveV4(Str_8 &address, ICMP_Header &header, Serializer<UInt_64> &data) const;
};
}

View File

@ -12,7 +12,7 @@ namespace ehs
class EHS_LIB_IO BaseTCP class EHS_LIB_IO BaseTCP
{ {
protected: protected:
AddrType addrType; IP ip;
Str_8 localAddr; Str_8 localAddr;
UInt_16 localPort; UInt_16 localPort;
Str_8 remoteHostName; Str_8 remoteHostName;
@ -35,7 +35,7 @@ namespace ehs
/// Properly initializes the socket. /// Properly initializes the socket.
/// @param [in] type The ip version to initialize the socket with. /// @param [in] type The ip version to initialize the socket with.
BaseTCP(AddrType addrType); BaseTCP(IP ip);
BaseTCP(BaseTCP&& tcp) noexcept; BaseTCP(BaseTCP&& tcp) noexcept;
@ -104,7 +104,7 @@ namespace ehs
/// Retrieves the sockets ip version. /// Retrieves the sockets ip version.
/// @returns The ip version. /// @returns The ip version.
AddrType GetAddressType() const; IP GetAddressType() const;
/// Retrieves the bound ip address. /// Retrieves the bound ip address.
/// @returns The ip address. /// @returns The ip address.

View File

@ -9,9 +9,7 @@ namespace ehs
class EHS_LIB_IO BaseUDP class EHS_LIB_IO BaseUDP
{ {
protected: protected:
AddrType type; Endpoint localEndpoint;
Str_8 address;
UInt_16 port;
bool bound; bool bound;
public: public:
@ -22,7 +20,7 @@ namespace ehs
/// Properly initializes the socket. /// Properly initializes the socket.
/// @param [in] type The ip version to initialize the socket with. /// @param [in] type The ip version to initialize the socket with.
BaseUDP(AddrType type); BaseUDP(IP version);
BaseUDP(BaseUDP&& udp) noexcept; BaseUDP(BaseUDP&& udp) noexcept;
@ -40,13 +38,13 @@ namespace ehs
/// @param [in] address The ip address to bind to. /// @param [in] address The ip address to bind to.
/// @param [in] port The port to bind to. /// @param [in] port The port to bind to.
/// @note Used for servers. /// @note Used for servers.
virtual void Bind(AddrType type, const Str_8& address, UInt_16 port) = 0; virtual void Bind(const Endpoint &endpoint) = 0;
/// Sends data to the endpoint. /// Sends data to the endpoint.
/// @param [in] type The ip version of the endpoint. /// @param [in] type The ip version of the endpoint.
/// @param [in] address The ip address of the endpoint. /// @param [in] address The ip address of the endpoint.
/// @param [in] port The port of the endpoint is bound to. /// @param [in] port The port of the endpoint is bound to.
virtual UInt_64 Send(AddrType type, const Str_8& address, UInt_16 port, const Byte* data, UInt_64 size) = 0; virtual UInt_64 Send(const Endpoint &endpoint, const Byte *data, UInt_64 size) = 0;
/// Receives data from the endpoint. /// Receives data from the endpoint.
/// @param [out] type The ip version of the endpoint. /// @param [out] type The ip version of the endpoint.
@ -55,7 +53,7 @@ namespace ehs
/// @param [out] data The incoming data from the endpoint. /// @param [out] data The incoming data from the endpoint.
/// @param [in] size The max size of the buffer in bytes to store the data. /// @param [in] size The max size of the buffer in bytes to store the data.
/// @returns The size of the incoming data in bytes. /// @returns The size of the incoming data in bytes.
virtual UInt_64 Receive(AddrType* type, Str_8* address, UInt_16* port, Byte* data, UInt_64 size) = 0; virtual UInt_64 Receive(Endpoint *endpoint, Byte *data, UInt_64 size) = 0;
/// Retrieves whether or not this socket is bound to an ip address and port. /// Retrieves whether or not this socket is bound to an ip address and port.
/// @returns The result. /// @returns The result.
@ -73,17 +71,7 @@ namespace ehs
virtual bool IsIPv6Only() const = 0; virtual bool IsIPv6Only() const = 0;
/// Retrieves the bound ip version. Endpoint GetLocalEndpoint() const;
/// @returns The result.
AddrType GetLocalAddressType() const;
/// Retrieves the bound ip address.
/// @returns The bound ip address.
Str_8 GetLocalAddress() const;
/// Retrieves the bound port.
/// @returns The bound port.
UInt_16 GetLocalPort() const;
/// Retrieves whether or not this socket was initialized. /// Retrieves whether or not this socket was initialized.
/// @returns The result. /// @returns The result.

View File

@ -10,7 +10,7 @@ namespace ehs
class EHS_LIB_IO DNS final : public BaseDNS class EHS_LIB_IO DNS final : public BaseDNS
{ {
public: public:
static Str_8 Resolve(AddrType type, const Str_8 &hostname); static Str_8 Resolve(IP type, const Str_8 &hostname);
static Str_8 Resolve(const Str_8 &hostname); static Str_8 Resolve(const Str_8 &hostname);
}; };

View File

@ -7,7 +7,7 @@ namespace ehs
class EHS_LIB_IO DNS final : public BaseDNS class EHS_LIB_IO DNS final : public BaseDNS
{ {
public: public:
static Str_8 Resolve(AddrType type, const Str_8 &hostname); static Str_8 Resolve(IP type, const Str_8 &hostname);
static Str_8 Resolve(const Str_8 &hostname); static Str_8 Resolve(const Str_8 &hostname);
}; };

View File

@ -0,0 +1,95 @@
#pragma once
#include "ehs/io/socket/ehc/NetEnc.h"
#include "ehs/Array.h"
#include "Socket.h"
#include "UDP.h"
namespace ehs
{
class NetServerCh;
class NetClientCh;
class NetEnd;
class EHC;
class EHC
{
private:
friend class NetEnc;
friend class NetChannel;
friend class NetServerCh;
friend class NetClientCh;
friend class NetEnd;
static const Version version;
UDP udp;
Byte* buffer;
UInt_32 bufferSize;
UInt_64 lastTSC;
float delta;
Array<NetEnc *> encryptions;
Array<NetServerCh *> servers;
Array<NetClientCh *> clients;
public:
~EHC();
EHC(IP version = IP::V6);
EHC(EHC &&sock) noexcept;
EHC(const EHC &sock);
EHC &operator=(EHC&& sock) noexcept;
EHC &operator=(const EHC &sock);
void Initialize();
void Release();
void Bind(const Endpoint &endpoint);
void Poll();
bool IsInitialized() const;
Endpoint GetLocalEndpoint() const;
bool IsBound() const;
static Version GetVersion();
bool AddEncryption(NetEnc *enc);
bool HasServer(UInt_64 serverId) const;
bool HasServer(const Str_8& serverName) const;
bool AddServer(NetServerCh *server);
NetServerCh *GetServer(UInt_64 serverId) const;
NetServerCh *GetServer(const Str_8& serverName) const;
bool HasClient(UInt_64 clientId) const;
bool HasClient(const Str_8& clientName) const;
bool AddClient(NetClientCh *channel);
NetClientCh *GetClient(UInt_64 clientId) const;
NetClientCh *GetClient(const Str_8& clientName) const;
private:
bool HasEncryption(UInt_64 encId) const;
bool HasEncryption(const Str_8& encName) const;
NetEnc* GetEncryption(UInt_64 encId) const;
NetEnc* GetEncryption(const Str_8& encName) const;
};
}

View File

@ -0,0 +1,9 @@
#pragma once
#include "ehs/system/OS.h"
#ifdef EHS_OS_WINDOWS
#include "ICMP_W32.h"
#else
#include "ICMP_LNX.h"
#endif

View File

@ -0,0 +1,60 @@
#pragma once
#include "BaseICMP.h"
#include <netinet/in.h>
namespace ehs
{
struct PseudoICMPv6_Header
{
sockaddr_in6 src;
sockaddr_in6 dst;
UInt_32 length;
};
class ICMP final : public BaseICMP
{
private:
Int_32 hdl;
sockaddr_in6 src;
public:
~ICMP() override;
ICMP();
ICMP(IP version);
ICMP(ICMP &&icmp) noexcept;
ICMP(const ICMP &icmp);
ICMP &operator=(ICMP &&icmp) noexcept;
ICMP &operator=(const ICMP &icmp);
void Release() override;
void SetReceiveTimeout(UInt_64 timeout) override;
bool IsValid() const override;
private:
static bool IsLinkLocal(const in6_addr &addr);
static sockaddr_in6 RetrieveSrcAddress();
static UInt_32 CalculatePseudoHeaderChecksum(const PseudoICMPv6_Header &header);
UInt_16 ComputeChecksumV6(UInt_16* buffer, Size length, const sockaddr_in6& dst);
UInt_64 SendV6(const Str_8 &address, ICMP_Header header, const Byte *data, UInt_64 size) override;
UInt_64 SendV4(const Str_8 &address, ICMP_Header header, const Byte *data, UInt_64 size) override;
UInt_64 ReceiveV6(Str_8 &address, ICMP_Header &header, Serializer<UInt_64> &data) const override;
UInt_64 ReceiveV4(Str_8 &address, ICMP_Header &header, Serializer<UInt_64> &data) const override;
};
}

View File

@ -0,0 +1,63 @@
#pragma once
#include "BaseICMP.h"
#include "ehs/System/OS.h"
#include <winsock2.h>
#include <WS2tcpip.h>
#include <iphlpapi.h>
namespace ehs
{
struct PseudoICMPv6_Header
{
sockaddr_in6 src;
sockaddr_in6 dst;
UInt_32 length;
};
class ICMP : public BaseICMP
{
private:
Socket hdl;
sockaddr_in6 src;
public:
~ICMP() override;
ICMP();
ICMP(IP version);
ICMP(ICMP &&icmp) noexcept;
ICMP(const ICMP &icmp);
ICMP &operator=(ICMP &&icmp) noexcept;
ICMP &operator=(const ICMP &icmp);
void Release() override;
void SetReceiveTimeout(UInt_64 timeout) override;
bool IsValid() const override;
private:
static bool IsLinkLocal(const in6_addr &addr);
static sockaddr_in6 RetrieveSrcAddress();
static UInt_32 CalculatePseudoHeaderChecksum(const PseudoICMPv6_Header &header);
UInt_16 ComputeChecksumV6(UInt_16* buffer, Size length, const sockaddr_in6& dst);
UInt_64 SendV6(const Str_8 &address, ICMP_Header header, const Byte *data, UInt_64 size) override;
UInt_64 SendV4(const Str_8 &address, ICMP_Header header, const Byte *data, UInt_64 size) override;
UInt_64 ReceiveV6(Str_8 &address, ICMP_Header &header, Serializer<UInt_64> &data) const override;
UInt_64 ReceiveV4(Str_8 &address, ICMP_Header &header, Serializer<UInt_64> &data) const override;
};
}

View File

@ -23,7 +23,7 @@ namespace ehs
SSL(); SSL();
SSL(const AddrType type); SSL(const IP type);
SSL(TCP&& tcp) noexcept; SSL(TCP&& tcp) noexcept;

View File

@ -1,7 +1,10 @@
#pragma once #pragma once
#include "ehs/Str.h"
#ifndef EHS_IPV4_HEADER #ifndef EHS_IPV4_HEADER
#define EHS_IPV4_HEADER 60 #define EHS_IPV4_HEADER 60
#include <string>
#endif #endif
#ifndef EHS_IPV6_HEADER #ifndef EHS_IPV6_HEADER
@ -22,10 +25,10 @@
namespace ehs namespace ehs
{ {
enum class AddrType enum class IP
{ {
IPV6, V4,
IPV4 V6
}; };
enum class ContentType enum class ContentType
@ -41,6 +44,13 @@ namespace ehs
NONE NONE
}; };
struct Endpoint
{
IP version = IP::V6;
Str_8 address;
UInt_16 port = 0;
};
#if defined(EHS_OS_WINDOWS) #if defined(EHS_OS_WINDOWS)
typedef UInt_64 Socket; typedef UInt_64 Socket;
#define EHS_INVALID_SOCKET EHS_UINT_64_MAX #define EHS_INVALID_SOCKET EHS_UINT_64_MAX

View File

@ -22,7 +22,7 @@ namespace ehs
/// Default members initialization. /// Default members initialization.
TCP(); TCP();
TCP(AddrType addrType); TCP(IP IP);
TCP(TCP&& tcp) noexcept; TCP(TCP&& tcp) noexcept;

View File

@ -22,7 +22,7 @@ namespace ehs
/// Default members initialization. /// Default members initialization.
TCP(); TCP();
TCP(AddrType addrType); TCP(IP IP);
TCP(TCP&& tcp) noexcept; TCP(TCP&& tcp) noexcept;

View File

@ -19,7 +19,7 @@ namespace ehs
UDP(); UDP();
/// Default members initialization. /// Default members initialization.
UDP(AddrType type); UDP(IP version);
UDP(UDP&& udp) noexcept; UDP(UDP&& udp) noexcept;
@ -41,7 +41,7 @@ namespace ehs
/// @param [in] address The local IPv4 or IPv6 address to bind to. Resolves domain names. The given address can be empty, "127.0.0.1", or "localhost" to automatically find the appropriate device. /// @param [in] address The local IPv4 or IPv6 address to bind to. Resolves domain names. The given address can be empty, "127.0.0.1", or "localhost" to automatically find the appropriate device.
/// @param [in] port The port to bind to. /// @param [in] port The port to bind to.
/// @note Requires the port given to be forwarded if this is called. /// @note Requires the port given to be forwarded if this is called.
void Bind(AddrType type, const Str_8& address, UInt_16 port) override; void Bind(const Endpoint &endpoint) override;
/// Sends data using a C-style byte array. /// Sends data using a C-style byte array.
/// @param [in] addr The remote Ipv4 or Ipv6 address to send to. Resolves domain names. The given address can be empty, "127.0.0.1", or "localhost" to automatically find the appropriate device. /// @param [in] addr The remote Ipv4 or Ipv6 address to send to. Resolves domain names. The given address can be empty, "127.0.0.1", or "localhost" to automatically find the appropriate device.
@ -49,7 +49,7 @@ namespace ehs
/// @param [in] data The C-style byte array to send. /// @param [in] data The C-style byte array to send.
/// @param [in] size The size of the C-style byte array. /// @param [in] size The size of the C-style byte array.
/// @note The size of data to be sent cannot exceed "UDP::maxPayloadIpv4" or "UDP::maxPayloadIpv6". /// @note The size of data to be sent cannot exceed "UDP::maxPayloadIpv4" or "UDP::maxPayloadIpv6".
UInt_64 Send(AddrType type, const Str_8& address, UInt_16 port, const Byte* data, UInt_64 size) override; UInt_64 Send(const Endpoint &endpoint, const Byte* data, UInt_64 size) override;
/// Receives data using the packet helper class. /// Receives data using the packet helper class.
/// @param [out] addr The Ipv4 or Ipv6 address of the sender. /// @param [out] addr The Ipv4 or Ipv6 address of the sender.
@ -58,7 +58,7 @@ namespace ehs
/// @param [in] size The size of the pre-allocated C-style byte array. /// @param [in] size The size of the pre-allocated C-style byte array.
/// @returns The size of the data received. /// @returns The size of the data received.
/// @warning The provided C-style byte array must be freed when finished using. /// @warning The provided C-style byte array must be freed when finished using.
UInt_64 Receive(AddrType* type, Str_8* address, UInt_16* port, Byte* data, UInt_64 size) override; UInt_64 Receive(Endpoint *endpoint, Byte* data, UInt_64 size) override;
/// Sets whether or not receiving data blocks the next task. /// Sets whether or not receiving data blocks the next task.
/// @param [in] blocking Whether or not to block. /// @param [in] blocking Whether or not to block.

View File

@ -19,7 +19,7 @@ namespace ehs
UDP(); UDP();
/// Default members initialization. /// Default members initialization.
UDP(const AddrType addrType); UDP(const IP IP);
UDP(UDP&& udp) noexcept; UDP(UDP&& udp) noexcept;
@ -41,7 +41,7 @@ namespace ehs
/// @param [in] address The local IPv4 or IPv6 address to bind to. Resolves domain names. The given address can be empty, "127.0.0.1", or "localhost" to automatically find the appropriate device. /// @param [in] address The local IPv4 or IPv6 address to bind to. Resolves domain names. The given address can be empty, "127.0.0.1", or "localhost" to automatically find the appropriate device.
/// @param [in] port The port to bind to. /// @param [in] port The port to bind to.
/// @note Requires the port given to be forwarded if this is called. /// @note Requires the port given to be forwarded if this is called.
void Bind(AddrType type, const Str_8& address, UInt_16 port) override; void Bind(const Endpoint &endpoint) override;
/// Sends data using a C-style byte array. /// Sends data using a C-style byte array.
/// @param [in] addr The remote Ipv4 or Ipv6 address to send to. Resolves domain names. The given address can be empty, "127.0.0.1", or "localhost" to automatically find the appropriate device. /// @param [in] addr The remote Ipv4 or Ipv6 address to send to. Resolves domain names. The given address can be empty, "127.0.0.1", or "localhost" to automatically find the appropriate device.
@ -49,7 +49,7 @@ namespace ehs
/// @param [in] data The C-style byte array to send. /// @param [in] data The C-style byte array to send.
/// @param [in] size The size of the C-style byte array. /// @param [in] size The size of the C-style byte array.
/// @note The size of data to be sent cannot exceed "UDP::maxPayloadIpv4" or "UDP::maxPayloadIpv6". /// @note The size of data to be sent cannot exceed "UDP::maxPayloadIpv4" or "UDP::maxPayloadIpv6".
UInt_64 Send(AddrType type, const Str_8& addr, UInt_16 port, const Byte* data, UInt_64 size) override; UInt_64 Send(const Endpoint &endpoint, const Byte* data, UInt_64 size) override;
/// Receives data using the packet helper class. /// Receives data using the packet helper class.
/// @param [out] addr The Ipv4 or Ipv6 address of the sender. /// @param [out] addr The Ipv4 or Ipv6 address of the sender.
@ -58,7 +58,7 @@ namespace ehs
/// @param [in] size The size of the pre-allocated C-style byte array. /// @param [in] size The size of the pre-allocated C-style byte array.
/// @returns The size of the data received. /// @returns The size of the data received.
/// @warning The provided C-style byte array must be freed when finished using. /// @warning The provided C-style byte array must be freed when finished using.
UInt_64 Receive(AddrType* type, Str_8* addr, UInt_16* port, Byte* data, UInt_64 size) override; UInt_64 Receive(Endpoint *endpoint, Byte* data, UInt_64 size) override;
/// Sets whether or not receiving data blocks the next task. /// Sets whether or not receiving data blocks the next task.
/// @param [in] blocking Whether or not to block. /// @param [in] blocking Whether or not to block.

View File

@ -0,0 +1,94 @@
#pragma once
#include "ehs/Str.h"
#include "ehs/Array.h"
#include "ehs/io/socket/Socket.h"
#include "NetUtils.h"
namespace ehs
{
class EHC;
class NetEnd;
class NetSys;
class NetChannel
{
protected:
static const UInt_64 internalSys;
static const UInt_64 connectOp;
static const UInt_64 connectedOp;
static const UInt_64 rejectedOp;
static const UInt_64 disconnectOp;
static const UInt_64 disconnectedOp;
static const UInt_64 statusUpdateOp;
static const UInt_64 pingOp;
static const UInt_64 pongOp;
static const UInt_64 latencyOp;
static const UInt_64 receivedOp;
private:
friend class EHC;
EHC *owner;
UInt_64 id;
Str_8 name;
Version version;
float maxTimeout;
float resendRate;
bool dropPackets;
Array<NetSys *> systems;
public:
virtual ~NetChannel();
NetChannel();
NetChannel(Str_8 name, const Version &version);
NetChannel(NetChannel &&channel) noexcept;
NetChannel(const NetChannel &channel);
NetChannel &operator=(NetChannel &&channel) noexcept;
NetChannel &operator=(const NetChannel &channel);
EHC *GetOwner() const;
UInt_64 GetId() const;
Str_8 GetName() const;
Version GetVersion() const;
void SetMaxTimeout(float seconds);
float GetMaxTimeout() const;
void SetResendRate(float seconds);
float GetResendRate() const;
void EnableDropPackets(bool enable);
bool IsDropPacketsEnabled() const;
bool AddSystem(NetSys *sys);
bool IsValid() const;
private:
virtual void Process(const float &delta, const Endpoint &endpoint, const Header &header, Serializer<UInt_64> &payload);
virtual void Poll(const float &delta);
protected:
bool HasSystem(UInt_64 sysId) const;
bool HasSystem(const Str_8& sysName) const;
NetSys* GetSystem(UInt_64 sysId) const;
NetSys* GetSystem(const Str_8& sysName) const;
};
}

View File

@ -0,0 +1,81 @@
#pragma once
#include "NetChannel.h"
#include "ehs/io/socket/Socket.h"
#include "ehs/io/socket/ehc/NetEnc.h"
#include "ehs/io/socket/ehc/NetFrag.h"
namespace ehs
{
class NetClientCh : public NetChannel
{
private:
friend class EHC;
Endpoint remoteEndpoint;
Char_8 token[64];
NetStatus status;
UInt_64 queueSlot;
float deltaDuration;
float deltaRate;
float lastPing;
float latency;
float timeout;
UInt_64 nextSendId;
Vector<Insurance> sent;
UInt_64 nextRecvId;
Vector<NetFrag> received;
public:
~NetClientCh();
NetClientCh();
NetClientCh(Str_8 name, const Version &version, Endpoint remoteEndpoint);
NetClientCh(NetClientCh &&client) noexcept;
NetClientCh(const NetClientCh &client);
NetClientCh &operator=(NetClientCh &&client) noexcept;
NetClientCh &operator=(const NetClientCh &client);
virtual void OnConnected(Serializer<UInt_64> data);
virtual void OnActive(Serializer<UInt_64> data);
virtual void OnQueueUpdate(Serializer<UInt_64> data);
virtual void OnDisconnected(Serializer<UInt_64> data);
virtual void OnRejected(Serializer<UInt_64> data);
virtual void OnTimeout(Serializer<UInt_64> data);
void Connect(const Endpoint &endpoint, const Serializer<UInt_64>& payload);
bool Disconnect(const Serializer<UInt_64>& payload);
void Send(bool deltaLocked, UInt_64 encId, bool ensure, UInt_64 sysId, UInt_64 opId, const Serializer<UInt_64>& payload);
void Send(bool deltaLocked, const Str_8 &encName, bool ensure, const Str_8& sysName, const Str_8& opName, const Serializer<UInt_64>& payload);
NetStatus GetStatus() const;
private:
void Process(const float &delta, const Endpoint &endpoint, const Header &header, Serializer<UInt_64> &payload) override;
void Poll(const float &delta) override;
NetFrag FragmentData(IP version, const Header& header, const Serializer<>& data);
void Send(NetEnc *enc, const Header& header, const Serializer<>& payload);
void Pong(float delta);
void RemoveInsurance(UInt_64 msgId, UInt_64 fragment);
void AddReceived(const Header& header, const Serializer<>& payload);
};
}

View File

@ -0,0 +1,44 @@
#pragma once
#include "ehs/Str.h"
#include "ehs/Version.h"
namespace ehs
{
class EHC;
class NetEnc
{
private:
friend class EHC;
UInt_64 id;
Str_8 name;
Version version;
public:
virtual ~NetEnc() = default;
NetEnc();
NetEnc(Str_8 name, const Version &version);
NetEnc(NetEnc &&enc) noexcept;
NetEnc(const NetEnc &enc);
NetEnc &operator=(NetEnc &&enc) noexcept;
NetEnc &operator=(const NetEnc &enc);
UInt_64 GetId() const;
Str_8 GetName() const;
Version GetVersion() const;
virtual void Encrypt(Byte *data, UInt_64 size) const;
virtual void Decrypt(Byte *data, UInt_64 size) const;
};
}

View File

@ -0,0 +1,122 @@
#pragma once
#include "NetUtils.h"
#include "NetFrag.h"
#include "ehs/Str.h"
#include "ehs/Vector.h"
#include "ehs/Serializer.h"
#include "ehs/io/socket/Socket.h"
namespace ehs
{
class NetServerCh;
class NetEnd
{
private:
friend class NetServerCh;
NetServerCh* owner;
UInt_64 id;
Str_8 name;
NetStatus status;
Char_8 token[64];
UInt_64 nextSendId;
Vector<Insurance> sent;
UInt_64 nextRecvId;
Vector<NetFrag> received;
Endpoint endpoint;
float deltaDuration;
float deltaRate;
float timeout;
float lastPing;
float oldLatency;
float latency;
UInt_64 queueSlot;
public:
NetEnd();
NetEnd(Str_8 id, Endpoint endpoint);
NetEnd(Endpoint endpoint);
NetEnd(NetEnd &&end) noexcept;
NetEnd(const NetEnd &end);
NetEnd &operator=(NetEnd &&end) noexcept;
NetEnd &operator=(const NetEnd &end);
UInt_64 GetId() const;
Str_8 GetName() const;
NetStatus GetStatus() const;
UInt_64 GetNextSendId() const;
/// Sends data to the remote endpoint.
/// @param [in] deltaLocked Whether or not to match the remote endpoint's delta time to prevent overloading the client. This will drop data if delta time does not match.
/// @param [in] encHashId The hash id of the encryption to use. Can be zero for none.
/// @param [in] ensure Whether or not to ensure the data was received by the remote endpoint.
/// @param [in] sys The system hash id to execute an operation from.
/// @param [in] op The operation hash id in the system to execute.
/// @param [in] payload Additional parameters and data to send to the remote endpoint.
void Send(bool deltaLocked, UInt_64 encId, bool ensure, UInt_64 sysId, UInt_64 opId, const Serializer<UInt_64>& payload);
/// Sends data to the remote endpoint.
/// @param [in] deltaLocked Whether or not to match the remote endpoint's delta time to prevent overloading the client. This will drop data if delta time does not match.
/// @param [in] encId The id of the encryption to use. Can be empty for none.
/// @param [in] ensure Whether or not to ensure the data was received by the remote endpoint.
/// @param [in] sys The system string id to execute an operation from.
/// @param [in] op The operation string id in the system to execute.
/// @param [in] payload Additional parameters and data to send to the remote endpoint.
void Send(bool deltaLocked, const Str_8 &encName, bool ensure, const Str_8& sysName, const Str_8& opName, const Serializer<UInt_64>& payload);
UInt_64 GetNextRecvId() const;
Endpoint GetEndpoint() const;
void SetDeltaRate(float newDeltaRate);
float GetDeltaRate() const;
float GetTimeout() const;
float GetLastPing() const;
void SendLatency();
float GetLatency() const;
UInt_64 GetQueueSlot() const;
private:
void Poll(float delta);
void SetStatus(NetStatus newStatus);
void RemoveInsurance(UInt_64 msgId, UInt_64 fragment);
void AddReceived(const Header& header, const Serializer<>& payload);
Vector<NetFrag>* GetReceived();
void Ping(float delta);
void SetLatency(float newLatency);
void SetQueueSlot(UInt_64 slot);
NetFrag FragmentData(const Header& header, const Serializer<>& data);
void Send(const Header& header, const Serializer<>& payload);
bool SortingNeeded() const;
void SortReceived();
};
}

View File

@ -0,0 +1,43 @@
#pragma once
#include "NetUtils.h"
#include <ehs/Serializer.h>
namespace ehs
{
class NetFrag
{
private:
Header header;
Serializer<UInt_64>* data;
UInt_64 size;
public:
~NetFrag();
NetFrag();
NetFrag(const Header &header, const Serializer<UInt_64> &payload);
NetFrag(const Header &header, UInt_64 size);
NetFrag(NetFrag &&frags) noexcept;
NetFrag(const NetFrag &frags);
NetFrag &operator=(NetFrag &&frags) noexcept;
NetFrag &operator=(const NetFrag &frags);
operator Serializer<UInt_64> *() const;
Header GetHeader() const;
UInt_64 Size() const;
bool IsComplete() const;
Packet Combine() const;
};
}

View File

@ -0,0 +1,42 @@
#pragma once
#include "ehs/Str.h"
#include "ehs/Serializer.h"
namespace ehs
{
class NetChannel;
class NetSys;
class NetEnd;
class NetOp
{
private:
friend class NetSys;
UInt_64 id;
Str_8 name;
public:
virtual ~NetOp() = default;
NetOp();
NetOp(Str_8 name);
NetOp(NetOp &&op) noexcept;
NetOp(const NetOp &op);
NetOp &operator=(NetOp &&op) noexcept;
NetOp &operator=(const NetOp &op);
UInt_64 GetId() const;
Str_8 GetName() const;
private:
virtual void Execute(NetChannel *channel, NetEnd *issuer, NetSys *sys, Serializer<UInt_64> &payload);
};
}

View File

@ -0,0 +1,105 @@
#pragma once
#include "NetChannel.h"
namespace ehs
{
class NetEnd;
class NetServerCh : public NetChannel
{
private:
friend class EHC;
Vector<NetEnd *> endpoints;
UInt_64 maxEndpoints;
public:
~NetServerCh() override;
NetServerCh();
NetServerCh(Str_8 name, const Version &version, UInt_64 maxEndpoints);
NetServerCh(NetServerCh &&server) noexcept;
NetServerCh(const NetServerCh &server);
NetServerCh &operator=(NetServerCh &&server) noexcept;
NetServerCh &operator=(const NetServerCh &server);
virtual bool OnEndpointConnect(NetEnd *endpoint, Serializer<UInt_64> payload);
virtual Serializer<UInt_64> OnEndpointAccepted(NetEnd *endpoint);
virtual void OnEndpointDisconnect(NetEnd *endpoint, Serializer<UInt_64> payload);
virtual void OnEndpointTimeout(NetEnd *endpoint);
virtual void OnEndpointActive(NetEnd *endpoint);
virtual Serializer<UInt_64> OnShutdown();
void Broadcast(NetStatus endStatus, bool deltaLocked, UInt_64 encHashId,
bool ensure, UInt_64 sysHashId, UInt_64 opHashId,
const Serializer<UInt_64> &payload);
void Broadcast(NetStatus endStatus, bool deltaLocked, const Str_8 &encId,
bool ensure, const Str_8 &sysId, const Str_8 &opId,
const Serializer<UInt_64> &payload);
bool HasEndpoint(NetStatus endStatus, const Char_8 token[64]) const;
bool HasEndpoint(NetStatus endStatus, UInt_64 hashId) const;
bool HasEndpoint(NetStatus endStatus, const Str_8 &id) const;
bool HasEndpoint(const Char_8 token[64]) const;
bool HasEndpoint(UInt_64 hashId) const;
bool HasEndpoint(const Str_8 &id) const;
bool HasEndpoint(const Endpoint &endpoint) const;
NetEnd *GetEndpoint(NetStatus endStatus, const Char_8 token[64]) const;
NetEnd *GetEndpoint(NetStatus endStatus, UInt_64 hashId) const;
NetEnd *GetEndpoint(NetStatus endStatus, const Str_8 &id) const;
NetEnd *GetEndpoint(const Char_8 token[64]) const;
NetEnd *GetEndpoint(UInt_64 hashId) const;
NetEnd *GetEndpoint(const Str_8 &id) const;
NetEnd *GetEndpoint(const Endpoint &endpoint) const;
Array<NetEnd *> GetEndpoints(NetStatus endStatus);
UInt_64 GetEndpointsCount(NetStatus endStatus);
UInt_64 GetMaxEndpoints() const;
private:
void Process(const float &delta, const Endpoint &endpoint, const Header &header, Serializer<UInt_64> &payload) override;
void GenerateToken(Char_8 in[64]);
void UpdateQueue(UInt_64 active);
void UpdateQueue();
bool RemoveEndpoint(const Char_8 token[64]);
bool RemoveEndpoint(const Endpoint &endpoint);
bool RemoveEndpoint(const NetEnd* end);
void Poll(const float &delta) override;
void Shutdown();
};
}

View File

@ -0,0 +1,50 @@
#pragma once
#include "ehs/Str.h"
#include "ehs/Array.h"
#include "ehs/Serializer.h"
namespace ehs
{
class NetChannel;
class NetEnd;
class NetOp;
class NetSys
{
private:
friend class NetChannel;
friend class NetServerCh;
friend class NetClientCh;
UInt_64 id;
Str_8 name;
Array<NetOp*> ops;
public:
virtual ~NetSys();
NetSys();
NetSys(Str_8 name);
NetSys(NetSys &&sys) noexcept;
NetSys(const NetSys &sys);
NetSys &operator=(NetSys &&sys) noexcept;
NetSys &operator=(const NetSys &sys);
UInt_64 GetId() const;
Str_8 GetName() const;
bool HasOperation(UInt_64 id) const;
bool AddOperation(NetOp *op);
private:
void Execute(NetChannel *channel, NetEnd *issuer, UInt_64 opId, Serializer<UInt_64> &payload);
};
}

View File

@ -0,0 +1,62 @@
#pragma once
#include "ehs/Serializer.h"
namespace ehs
{
enum class NetStatus : UInt_8
{
DISCONNECTED,
ACTIVE,
PENDING,
QUEUED
};
enum class NetChannelType : UInt_8
{
SERVER,
CLIENT
};
struct Header
{
Version version = {};
UInt_64 encId = 0;
Version encVer = {};
UInt_64 channelId = 0;
NetChannelType channelType = NetChannelType::SERVER;
Version channelVer = {};
UInt_64 id = 0;
UInt_64 fragmentCount = 0;
UInt_64 fragment = 0;
bool ensure = false;
Char_8 token[64] = {};
UInt_64 systemId = 0;
UInt_64 opId = 0;
};
void WriteHeader(const Header &header, Serializer<UInt_64> &data);
Header ReadHeader(Serializer<UInt_64> &data);
struct Packet
{
Header header;
Serializer<UInt_64> payload;
};
struct Insurance
{
Header header;
Serializer<UInt_64> payload;
float lastResend;
};
}
#ifndef EHC_IPV4_PAYLOAD
#define EHC_IPV4_PAYLOAD (EHS_IPV4_UDP_PAYLOAD - (UInt_16)sizeof(Header))
#endif
#ifndef EHC_IPV6_PAYLOAD
#define EHC_IPV6_PAYLOAD (EHS_IPV6_UDP_PAYLOAD - (UInt_16)sizeof(Header))
#endif

View File

@ -210,6 +210,8 @@ namespace ehs
/// @param[out] input A 48 byte character array representing the brand. /// @param[out] input A 48 byte character array representing the brand.
static void GetBrand(Char_8* input); static void GetBrand(Char_8* input);
static UInt_8 GetCacheLineSize();
//static Str_8 ToStr(); //static Str_8 ToStr();
private: private:

View File

@ -290,6 +290,11 @@ namespace ehs
return channels * frames; return channels * frames;
} }
UInt_8 Audio::GetFrameSize() const
{
return byteDepth * channels;
}
UInt_64 Audio::GetSize() const UInt_64 Audio::GetSize() const
{ {
return byteDepth * channels * frames; return byteDepth * channels * frames;
@ -300,6 +305,11 @@ namespace ehs
return length; return length;
} }
Byte* Audio::GetFrame(UInt_64 frameIndex) const
{
return &data[frameIndex * GetFrameSize()];
}
Array<Byte> Audio::FrameAsMono(const UInt_64 frameIndex) const Array<Byte> Audio::FrameAsMono(const UInt_64 frameIndex) const
{ {
Array<Byte> result(byteDepth); Array<Byte> result(byteDepth);
@ -1743,161 +1753,161 @@ namespace ehs
void Audio::SInt_16_to_SInt_8(Byte* newData, Byte* newPeak) const void Audio::SInt_16_to_SInt_8(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
newData[a] = (Byte)((float)((SInt_16*)data)[a] / (float)EHS_SINT_16_MAX * (float)EHS_SINT_8_MAX); newData[a] = (Byte)((double)((SInt_16*)data)[a] / (double)EHS_SINT_16_MAX * (double)EHS_SINT_8_MAX);
*(SInt_8*)newPeak = (SInt_8)((float)*(SInt_16*)peak / (float)EHS_SINT_16_MAX * (float)EHS_SINT_8_MAX); *(SInt_8*)newPeak = (SInt_8)((double)*(SInt_16*)peak / (double)EHS_SINT_16_MAX * (double)EHS_SINT_8_MAX);
} }
void Audio::Float_to_SInt_8(Byte* newData, Byte* newPeak) const void Audio::Float_to_SInt_8(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((SInt_8*)newData)[a] = (SInt_8)(((float*)data)[a] * (float)EHS_SINT_8_MAX); ((SInt_8*)newData)[a] = (SInt_8)((double)((float*)data)[a] * (double)EHS_SINT_8_MAX);
*(SInt_8*)newPeak = (SInt_8)(*(float*)peak * (float)EHS_SINT_8_MAX); *(SInt_8*)newPeak = (SInt_8)((double)(*(float*)peak) * (double)EHS_SINT_8_MAX);
} }
void Audio::SInt_32_to_SInt_8(Byte* newData, Byte* newPeak) const void Audio::SInt_32_to_SInt_8(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
newData[a] = (Byte)((float)((SInt_32*)data)[a] / (float)EHS_SINT_32_MAX * (float)EHS_SINT_8_MAX); newData[a] = (Byte)((double)((SInt_32*)data)[a] / (double)EHS_SINT_32_MAX * (double)EHS_SINT_8_MAX);
*(SInt_8*)newPeak = (SInt_8)((float)*(SInt_32*)peak / (float)EHS_SINT_32_MAX * (float)EHS_SINT_8_MAX); *(SInt_8*)newPeak = (SInt_8)((double)*(SInt_32*)peak / (double)EHS_SINT_32_MAX * (double)EHS_SINT_8_MAX);
} }
void Audio::SInt_64_to_SInt_8(Byte* newData, Byte* newPeak) const void Audio::SInt_64_to_SInt_8(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
newData[a] = (Byte)((float)((SInt_64*)data)[a] / (float)EHS_SINT_64_MAX * (float)EHS_SINT_8_MAX); newData[a] = (Byte)((double)((SInt_64*)data)[a] / (double)EHS_SINT_64_MAX * (double)EHS_SINT_8_MAX);
*(SInt_8*)newPeak = (SInt_8)((float)*(SInt_64*)peak / (float)EHS_SINT_64_MAX * (float)EHS_SINT_8_MAX); *(SInt_8*)newPeak = (SInt_8)((double)*(SInt_64*)peak / (double)EHS_SINT_64_MAX * (double)EHS_SINT_8_MAX);
} }
void Audio::SInt_8_to_SInt_16(Byte* newData, Byte* newPeak) const void Audio::SInt_8_to_SInt_16(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((SInt_16*)newData)[a] = (SInt_16)((float)(SInt_8)data[a] / (float)EHS_SINT_8_MAX * (float)EHS_SINT_16_MAX); ((SInt_16*)newData)[a] = (SInt_16)((double)(SInt_8)data[a] / (double)EHS_SINT_8_MAX * (double)EHS_SINT_16_MAX);
*(SInt_16*)newPeak = (SInt_16)((float)*(SInt_8*)peak / (float)EHS_SINT_8_MAX * (float)EHS_SINT_16_MAX); *(SInt_16*)newPeak = (SInt_16)((double)*(SInt_8*)peak / (double)EHS_SINT_8_MAX * (double)EHS_SINT_16_MAX);
} }
void Audio::Float_to_SInt_16(Byte* newData, Byte* newPeak) const void Audio::Float_to_SInt_16(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((SInt_16*)newData)[a] = (SInt_16)(((float*)data)[a] * (float)EHS_SINT_16_MAX); ((SInt_16*)newData)[a] = (SInt_16)((double)((float*)data)[a] * (double)EHS_SINT_16_MAX);
*(SInt_16*)newPeak = (SInt_16)(*(float*)peak * (float)EHS_SINT_16_MAX); *(SInt_16*)newPeak = (SInt_16)((double)(*(float*)peak) * (double)EHS_SINT_16_MAX);
} }
void Audio::SInt_32_to_SInt_16(Byte* newData, Byte* newPeak) const void Audio::SInt_32_to_SInt_16(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((SInt_16*)newData)[a] = (SInt_16)((float)((SInt_32*)data)[a] / (float)EHS_SINT_32_MAX * (float)EHS_SINT_16_MAX); ((SInt_16*)newData)[a] = (SInt_16)((double)((SInt_32*)data)[a] / (double)EHS_SINT_32_MAX * (double)EHS_SINT_16_MAX);
*(SInt_16*)newPeak = (SInt_16)((float)*(SInt_32*)peak / (float)EHS_SINT_32_MAX * (float)EHS_SINT_16_MAX); *(SInt_16*)newPeak = (SInt_16)((double)*(SInt_32*)peak / (double)EHS_SINT_32_MAX * (double)EHS_SINT_16_MAX);
} }
void Audio::SInt_64_to_SInt_16(Byte* newData, Byte* newPeak) const void Audio::SInt_64_to_SInt_16(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((SInt_16*)newData)[a] = (SInt_16)((float)((SInt_64*)data)[a] / (float)EHS_SINT_64_MAX * (float)EHS_SINT_16_MAX); ((SInt_16*)newData)[a] = (SInt_16)((double)((SInt_64*)data)[a] / (double)EHS_SINT_64_MAX * (double)EHS_SINT_16_MAX);
*(SInt_16*)newPeak = (SInt_16)((float)*(SInt_64*)peak / (float)EHS_SINT_64_MAX * (float)EHS_SINT_16_MAX); *(SInt_16*)newPeak = (SInt_16)((double)*(SInt_64*)peak / (double)EHS_SINT_64_MAX * (double)EHS_SINT_16_MAX);
} }
void Audio::SInt_8_to_Float(Byte* newData, Byte* newPeak) const void Audio::SInt_8_to_Float(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((float*)newData)[a] = (float)(((SInt_8*)data)[a]) / (float)EHS_SINT_8_MAX; ((float*)newData)[a] = (float)((double)(((SInt_8*)data)[a]) / (double)EHS_SINT_8_MAX);
*(float*)newPeak = (float)*(SInt_8*)peak / (float)EHS_SINT_8_MAX; *(float*)newPeak = (float)((double)*(SInt_8*)peak / (double)EHS_SINT_8_MAX);
} }
void Audio::SInt_16_to_Float(Byte* newData, Byte* newPeak) const void Audio::SInt_16_to_Float(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((float*)newData)[a] = (float)(((SInt_16*)data)[a]) / (float)EHS_SINT_16_MAX; ((float*)newData)[a] = (float)((double)(((SInt_16*)data)[a]) / (double)EHS_SINT_16_MAX);
*(float*)newPeak = (float)*(SInt_16*)peak / (float)EHS_SINT_16_MAX; *(float*)newPeak = (float)((double)*(SInt_16*)peak / (double)EHS_SINT_16_MAX);
} }
void Audio::SInt_32_to_Float(Byte* newData, Byte* newPeak) const void Audio::SInt_32_to_Float(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((float*)newData)[a] = (float)(((SInt_32*)data)[a]) / (float)EHS_SINT_32_MAX; ((float*)newData)[a] = (float)((double)(((SInt_32*)data)[a]) / (double)EHS_SINT_32_MAX);
*(float*)newPeak = (float)*(SInt_32*)peak / (float)EHS_SINT_32_MAX; *(float*)newPeak = (float)((double)*(SInt_32*)peak / (double)EHS_SINT_32_MAX);
} }
void Audio::SInt_64_to_Float(Byte* newData, Byte* newPeak) const void Audio::SInt_64_to_Float(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((float*)newData)[a] = (float)(((SInt_64*)data)[a]) / (float)EHS_SINT_64_MAX; ((float*)newData)[a] = (float)((double)(((SInt_64*)data)[a]) / (double)EHS_SINT_64_MAX);
*(float*)newPeak = (float)*(SInt_64*)peak / (float)EHS_SINT_64_MAX; *(float*)newPeak = (float)((double)*(SInt_64*)peak / (double)EHS_SINT_64_MAX);
} }
void Audio::SInt_8_to_SInt_32(Byte* newData, Byte* newPeak) const void Audio::SInt_8_to_SInt_32(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((SInt_32*)newData)[a] = (SInt_32)((float)(SInt_8)data[a] / (float)EHS_SINT_8_MAX * (float)EHS_SINT_32_MAX); ((SInt_32*)newData)[a] = (SInt_32)((double)(SInt_8)data[a] / (double)EHS_SINT_8_MAX * (double)EHS_SINT_32_MAX);
*(SInt_32*)newPeak = (SInt_32)((float)*(SInt_8*)peak / (float)EHS_SINT_8_MAX * (float)EHS_SINT_32_MAX); *(SInt_32*)newPeak = (SInt_32)((double)*(SInt_8*)peak / (double)EHS_SINT_8_MAX * (double)EHS_SINT_32_MAX);
} }
void Audio::SInt_16_to_SInt_32(Byte* newData, Byte* newPeak) const void Audio::SInt_16_to_SInt_32(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((SInt_32*)newData)[a] = (SInt_32)((float)((SInt_16*)data)[a] / (float)EHS_SINT_16_MAX * (float)EHS_SINT_32_MAX); ((SInt_32*)newData)[a] = (SInt_32)((double)((SInt_16*)data)[a] / (double)EHS_SINT_16_MAX * (double)EHS_SINT_32_MAX);
*(SInt_32*)newPeak = (SInt_32)((float)*(SInt_16*)peak / (float)EHS_SINT_16_MAX * (float)EHS_SINT_32_MAX); *(SInt_32*)newPeak = (SInt_32)((double)*(SInt_16*)peak / (double)EHS_SINT_16_MAX * (double)EHS_SINT_32_MAX);
} }
void Audio::Float_to_SInt_32(Byte* newData, Byte* newPeak) const void Audio::Float_to_SInt_32(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((SInt_32*)newData)[a] = (SInt_32)(((float*)data)[a] * (float)EHS_SINT_32_MAX); ((SInt_32*)newData)[a] = (SInt_32)(((double*)data)[a] * (double)EHS_SINT_32_MAX);
*(SInt_32*)newPeak = (SInt_32)(*(float*)peak * (float)EHS_SINT_32_MAX); *(SInt_32*)newPeak = (SInt_32)(*(double*)peak * (double)EHS_SINT_32_MAX);
} }
void Audio::SInt_64_to_SInt_32(Byte* newData, Byte* newPeak) const void Audio::SInt_64_to_SInt_32(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((SInt_32*)newData)[a] = (SInt_32)((float)((SInt_64*)data)[a] / (float)EHS_SINT_64_MAX * (float)EHS_SINT_32_MAX); ((SInt_32*)newData)[a] = (SInt_32)((double)((SInt_64*)data)[a] / (double)EHS_SINT_64_MAX * (double)EHS_SINT_32_MAX);
*(SInt_32*)newPeak = (SInt_32)((float)*(SInt_64*)peak / (float)EHS_SINT_64_MAX * (float)EHS_SINT_32_MAX); *(SInt_32*)newPeak = (SInt_32)((double)*(SInt_64*)peak / (double)EHS_SINT_64_MAX * (double)EHS_SINT_32_MAX);
} }
void Audio::SInt_8_to_SInt_64(Byte* newData, Byte* newPeak) const void Audio::SInt_8_to_SInt_64(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((SInt_64*)newData)[a] = (SInt_64)((float)(SInt_8)data[a] / (float)EHS_SINT_8_MAX * (float)EHS_SINT_64_MAX); ((SInt_64*)newData)[a] = (SInt_64)((double)(SInt_8)data[a] / (double)EHS_SINT_8_MAX * (double)EHS_SINT_64_MAX);
*(SInt_64*)newPeak = (SInt_64)((float)*(SInt_8*)peak / (float)EHS_SINT_8_MAX * (float)EHS_SINT_64_MAX); *(SInt_64*)newPeak = (SInt_64)((double)*(SInt_8*)peak / (double)EHS_SINT_8_MAX * (double)EHS_SINT_64_MAX);
} }
void Audio::SInt_16_to_SInt_64(Byte* newData, Byte* newPeak) const void Audio::SInt_16_to_SInt_64(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((SInt_64*)newData)[a] = (SInt_64)((float)((SInt_16*)data)[a] / (float)EHS_SINT_16_MAX * (float)EHS_SINT_64_MAX); ((SInt_64*)newData)[a] = (SInt_64)((double)((SInt_16*)data)[a] / (double)EHS_SINT_16_MAX * (double)EHS_SINT_64_MAX);
*(SInt_64*)newPeak = (SInt_64)((float)*(SInt_16*)peak / (float)EHS_SINT_16_MAX * (float)EHS_SINT_64_MAX); *(SInt_64*)newPeak = (SInt_64)((double)*(SInt_16*)peak / (double)EHS_SINT_16_MAX * (double)EHS_SINT_64_MAX);
} }
void Audio::Float_to_SInt_64(Byte* newData, Byte* newPeak) const void Audio::Float_to_SInt_64(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((SInt_64*)newData)[a] = (SInt_64)(((float*)data)[a] * (float)EHS_SINT_64_MAX); ((SInt_64*)newData)[a] = (SInt_64)(((double*)data)[a] * (double)EHS_SINT_64_MAX);
*(SInt_64*)newPeak = (SInt_64)(*(float*)peak * (float)EHS_SINT_64_MAX); *(SInt_64*)newPeak = (SInt_64)(*(double*)peak * (double)EHS_SINT_64_MAX);
} }
void Audio::SInt_32_to_SInt_64(Byte* newData, Byte* newPeak) const void Audio::SInt_32_to_SInt_64(Byte* newData, Byte* newPeak) const
{ {
for (UInt_64 a = 0; a < GetSampleCount(); ++a) for (UInt_64 a = 0; a < GetSampleCount(); ++a)
((SInt_64*)newData)[a] = (SInt_64)((float)((SInt_32*)data)[a] / (float)EHS_SINT_32_MAX * (float)EHS_SINT_64_MAX); ((SInt_64*)newData)[a] = (SInt_64)((double)((SInt_32*)data)[a] / (double)EHS_SINT_32_MAX * (double)EHS_SINT_64_MAX);
*(SInt_64*)newPeak = (SInt_64)((float)*(SInt_32*)peak / (float)EHS_SINT_32_MAX * (float)EHS_SINT_64_MAX); *(SInt_64*)newPeak = (SInt_64)((double)*(SInt_32*)peak / (double)EHS_SINT_32_MAX * (double)EHS_SINT_64_MAX);
} }
bool EncodeEHA(const ehs::AudioCodec* const codec, ehs::Serializer<ehs::UInt_64>& out, const ehs::Audio* const in) bool EncodeEHA(const ehs::AudioCodec* const codec, ehs::Serializer<ehs::UInt_64>& out, const ehs::Audio* const in)

View File

@ -341,6 +341,8 @@ namespace ehs
return 0; return 0;
} }
Util::Copy(buffer, data, frameSize * byteDepth * channels);
r = playbackClient->ReleaseBuffer(frameSize, 0); r = playbackClient->ReleaseBuffer(frameSize, 0);
if (r == AUDCLNT_E_DEVICE_INVALIDATED) if (r == AUDCLNT_E_DEVICE_INVALIDATED)
{ {

View File

@ -1,4 +1,5 @@
#include "ehs/io/audio/BaseAudioDevice.h" #include "ehs/io/audio/BaseAudioDevice.h"
#include "ehs/Log.h"
namespace ehs namespace ehs
{ {
@ -49,19 +50,48 @@ namespace ehs
return 0; return 0;
} }
void BaseAudioDevice::BridgeStreams(const UInt_64 bufferSize) void BaseAudioDevice::BridgeStreams(BaseAudioDevice* input, UInt_64 frameBufferSize)
{ {
Byte* buffer = new Byte[bufferSize]; if (type != AudioDeviceType::OUTPUT)
{
EHS_LOG_INT(LogType::WARN, 0, "The current audio device object is not an output device.");
return;
}
UInt_64 result = ReceiveStream(buffer, bufferSize); if (input->type != AudioDeviceType::INPUT)
while (result < bufferSize) {
result += ReceiveStream(&buffer[result], bufferSize - result); EHS_LOG_INT(LogType::WARN, 1, "The provided audio device is not an input device.");
return;
}
Byte* buffer = new Byte[frameBufferSize * GetFrameSize()];
UInt_64 result = 0;
while (result < frameBufferSize)
result += input->ReceiveStream(&buffer[result * GetFrameSize()], frameBufferSize - result);
result -= SendStream(buffer, result);
while (result) while (result)
result -= SendStream(&buffer[bufferSize - result], result); result -= SendStream(&buffer[(frameBufferSize - result) * GetFrameSize()], result);
delete[] buffer; delete[] buffer;
EHS_LOG_SUCCESS();
}
void BaseAudioDevice::BridgeStreams(const UInt_64 frameBufferSize)
{
Byte* buffer = new Byte[frameBufferSize * GetFrameSize()];
UInt_64 result = ReceiveStream(buffer, frameBufferSize);
while (result < frameBufferSize)
result += ReceiveStream(&buffer[result * GetFrameSize()], frameBufferSize - result);
while (result)
result -= SendStream(&buffer[(frameBufferSize - result) * GetFrameSize()], result);
delete[] buffer;
EHS_LOG_SUCCESS();
} }
AudioDeviceType BaseAudioDevice::GetType() const AudioDeviceType BaseAudioDevice::GetType() const

View File

@ -4,7 +4,7 @@
namespace ehs namespace ehs
{ {
Str_8 BaseDNS::Resolve(const AddrType type, const Str_8 &hostname) Str_8 BaseDNS::Resolve(const IP type, const Str_8 &hostname)
{ {
EHS_LOG_INT(LogType::ERR, 0, "Unsupported Operating System."); EHS_LOG_INT(LogType::ERR, 0, "Unsupported Operating System.");
return {}; return {};

145
src/io/socket/BaseICMP.cpp Normal file
View File

@ -0,0 +1,145 @@
#include "ehs/io/socket/BaseICMP.h"
#include "ehs/Serializer.h"
namespace ehs
{
BaseICMP::BaseICMP()
: version(IP::V6)
{
}
BaseICMP::BaseICMP(const IP version)
: version(version)
{
}
BaseICMP::BaseICMP(BaseICMP &&icmp) noexcept
: version(icmp.version)
{
}
BaseICMP::BaseICMP(const BaseICMP &icmp)
: version(icmp.version)
{
}
BaseICMP & BaseICMP::operator=(BaseICMP &&icmp) noexcept
{
if (this == &icmp)
return *this;
version = icmp.version;
return *this;
}
BaseICMP & BaseICMP::operator=(const BaseICMP &icmp)
{
if (this == &icmp)
return *this;
version = icmp.version;
return *this;
}
void BaseICMP::Release()
{
}
UInt_64 BaseICMP::Send(const Str_8 &address, ICMP_Header header, const Byte *data, UInt_64 size)
{
if (GetVersion() == IP::V6)
return SendV6(address, header, data, size);
return SendV4(address, header, data, size);
}
UInt_64 BaseICMP::Receive(Str_8 &address, ICMP_Header &header, Serializer<UInt_64> &data)
{
if (GetVersion() == IP::V6)
return ReceiveV6(address, header, data);
return ReceiveV4(address, header, data);
}
void BaseICMP::SendEchoRequest(const Str_8 &address, ICMP_EchoRequest er, const Byte *data, UInt_64 size)
{
if (!IsValid())
{
EHS_LOG_INT(LogType::WARN, 0, "Socket is not initialized.");
return;
}
ICMP_Header header = {
version == IP::V6 ? (UInt_8)128 : (UInt_8)8,
0,
0
};
Serializer<UInt_64> payload(Endianness::LE);
payload.Write(er);
payload.Resize(payload.Size() + size);
Util::Copy(&payload[payload.GetOffset()], data, size);
payload.SetOffset(payload.GetOffset() + size);
Send(address, header, &payload[0], payload.Size());
}
void BaseICMP::SetReceiveTimeout(UInt_64 timeout)
{
}
IP BaseICMP::GetVersion() const
{
return version;
}
bool BaseICMP::IsValid() const
{
return false;
}
UInt_16 BaseICMP::ComputeChecksumV4(UInt_16 *buffer, Size length)
{
Size sum = 0;
while (length > 1)
{
sum += *buffer++;
length -= sizeof(UInt_16);
}
if (length == 1)
sum += *(UInt_8 *)buffer;
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
return (UInt_16)~sum;
}
UInt_64 BaseICMP::SendV6(const Str_8 &address, ICMP_Header header, const Byte *data, UInt_64 size)
{
return 0;
}
UInt_64 BaseICMP::SendV4(const Str_8 &address, ICMP_Header header, const Byte *data, UInt_64 size)
{
return 0;
}
UInt_64 BaseICMP::ReceiveV6(Str_8 &address, ICMP_Header &header, Serializer<UInt_64> &data) const
{
return 0;
}
UInt_64 BaseICMP::ReceiveV4(Str_8 &address, ICMP_Header &header, Serializer<UInt_64> &data) const
{
return 0;
}
}

View File

@ -4,26 +4,26 @@
namespace ehs namespace ehs
{ {
BaseTCP::BaseTCP() BaseTCP::BaseTCP()
: addrType(AddrType::IPV6), localPort(0), remotePort(0), connection(false), bound(false), listening(false), : ip(IP::V6), localPort(0), remotePort(0), connection(false), bound(false), listening(false),
connected(false) connected(false)
{ {
} }
BaseTCP::BaseTCP(const AddrType addrType) BaseTCP::BaseTCP(const IP ip)
: addrType(addrType), localPort(0), remotePort(0), connection(false), bound(false), listening(false), : ip(ip), localPort(0), remotePort(0), connection(false), bound(false), listening(false),
connected(false) connected(false)
{ {
} }
BaseTCP::BaseTCP(BaseTCP&& tcp) noexcept BaseTCP::BaseTCP(BaseTCP&& tcp) noexcept
: addrType(tcp.addrType), localAddr(std::move(tcp.localAddr)), localPort(tcp.localPort), : ip(tcp.ip), localAddr(std::move(tcp.localAddr)), localPort(tcp.localPort),
remoteHostName(std::move(tcp.remoteHostName)), remoteAddr(std::move(tcp.remoteAddr)), remotePort(tcp.remotePort), remoteHostName(std::move(tcp.remoteHostName)), remoteAddr(std::move(tcp.remoteAddr)), remotePort(tcp.remotePort),
connection(tcp.connection), bound(tcp.bound), listening(tcp.listening), connected(tcp.connected) connection(tcp.connection), bound(tcp.bound), listening(tcp.listening), connected(tcp.connected)
{ {
} }
BaseTCP::BaseTCP(const BaseTCP& tcp) BaseTCP::BaseTCP(const BaseTCP& tcp)
: addrType(tcp.addrType), localPort(0), remotePort(0), connection(false), bound(false), listening(false), : ip(tcp.ip), localPort(0), remotePort(0), connection(false), bound(false), listening(false),
connected(false) connected(false)
{ {
} }
@ -33,7 +33,7 @@ namespace ehs
if (this == &tcp) if (this == &tcp)
return *this; return *this;
addrType = tcp.addrType; ip = tcp.ip;
localAddr = std::move(tcp.localAddr); localAddr = std::move(tcp.localAddr);
localPort = tcp.localPort; localPort = tcp.localPort;
remoteHostName = std::move(tcp.remoteHostName); remoteHostName = std::move(tcp.remoteHostName);
@ -44,7 +44,7 @@ namespace ehs
listening = tcp.listening; listening = tcp.listening;
connected = tcp.connected; connected = tcp.connected;
tcp.addrType = AddrType::IPV6; tcp.ip = IP::V6;
tcp.localPort = 0; tcp.localPort = 0;
tcp.remotePort = 0; tcp.remotePort = 0;
tcp.connection = false; tcp.connection = false;
@ -60,7 +60,7 @@ namespace ehs
if (this == &tcp) if (this == &tcp)
return *this; return *this;
addrType = tcp.addrType; ip = tcp.ip;
localAddr = Str_8(); localAddr = Str_8();
localPort = 0; localPort = 0;
remoteHostName = Str_8(); remoteHostName = Str_8();
@ -188,9 +188,9 @@ namespace ehs
return request; return request;
} }
AddrType BaseTCP::GetAddressType() const IP BaseTCP::GetAddressType() const
{ {
return addrType; return ip;
} }
Str_8 BaseTCP::GetLocalAddress() const Str_8 BaseTCP::GetLocalAddress() const

View File

@ -3,25 +3,23 @@
namespace ehs namespace ehs
{ {
BaseUDP::BaseUDP() BaseUDP::BaseUDP()
: type(AddrType::IPV6), port(0), bound(false) : bound(false)
{ {
} }
BaseUDP::BaseUDP(const AddrType type) BaseUDP::BaseUDP(const IP version)
: type(type), port(0), bound(false) : localEndpoint{version, "", 0}, bound(false)
{ {
} }
BaseUDP::BaseUDP(BaseUDP&& udp) noexcept BaseUDP::BaseUDP(BaseUDP&& udp) noexcept
: type(udp.type), address(std::move(udp.address)), port(udp.port), bound(true) : localEndpoint((Endpoint &&)udp.localEndpoint), bound(true)
{ {
udp.type = AddrType::IPV6;
udp.port = 0;
udp.bound = false; udp.bound = false;
} }
BaseUDP::BaseUDP(const BaseUDP& udp) BaseUDP::BaseUDP(const BaseUDP& udp)
: type(udp.type), address(udp.address), port(udp.port), bound(false) : localEndpoint(udp.localEndpoint), bound(false)
{ {
} }
@ -30,13 +28,9 @@ namespace ehs
if (this == &udp) if (this == &udp)
return *this; return *this;
type = udp.type; localEndpoint = (Endpoint &&)udp.localEndpoint;
address = std::move(udp.address);
port = udp.port;
bound = udp.bound; bound = udp.bound;
udp.type = AddrType::IPV6;
udp.port = 0;
udp.bound = false; udp.bound = false;
return *this; return *this;
@ -47,9 +41,7 @@ namespace ehs
if (this == &udp) if (this == &udp)
return *this; return *this;
type = udp.type; localEndpoint = udp.localEndpoint;
address = udp.address;
port = udp.port;
bound = false; bound = false;
return *this; return *this;
@ -60,18 +52,8 @@ namespace ehs
return bound; return bound;
} }
AddrType BaseUDP::GetLocalAddressType() const Endpoint BaseUDP::GetLocalEndpoint() const
{ {
return type; return localEndpoint;
}
Str_8 BaseUDP::GetLocalAddress() const
{
return address;
}
UInt_16 BaseUDP::GetLocalPort() const
{
return port;
} }
} }

View File

@ -7,14 +7,14 @@
namespace ehs namespace ehs
{ {
Str_8 DNS::Resolve(const AddrType type, const Str_8 &hostname) Str_8 DNS::Resolve(const IP type, const Str_8 &hostname)
{ {
addrinfo* result = nullptr; addrinfo* result = nullptr;
addrinfo req = {}; addrinfo req = {};
if (type == AddrType::IPV6) if (type == IP::V6)
req.ai_family = AF_INET6; req.ai_family = AF_INET6;
else if (type == AddrType::IPV4) else if (type == IP::V4)
req.ai_family = AF_INET; req.ai_family = AF_INET;
Int_32 code = getaddrinfo(hostname, nullptr, &req, &result); Int_32 code = getaddrinfo(hostname, nullptr, &req, &result);

View File

@ -6,7 +6,7 @@
namespace ehs namespace ehs
{ {
Str_8 DNS::Resolve(const AddrType type, const Str_8 &hostname) Str_8 DNS::Resolve(const IP type, const Str_8 &hostname)
{ {
WSADATA data = {}; WSADATA data = {};
@ -20,9 +20,9 @@ namespace ehs
addrinfo* result = nullptr; addrinfo* result = nullptr;
addrinfo req = {}; addrinfo req = {};
if (type == AddrType::IPV6) if (type == IP::V6)
req.ai_family = AF_INET6; req.ai_family = AF_INET6;
else if (type == AddrType::IPV4) else if (type == IP::V4)
req.ai_family = AF_INET; req.ai_family = AF_INET;
Int_32 code = getaddrinfo(hostname, nullptr, &req, &result); Int_32 code = getaddrinfo(hostname, nullptr, &req, &result);

380
src/io/socket/EHC.cpp Normal file
View File

@ -0,0 +1,380 @@
#include "ehs/io/socket/EHC.h"
#include "ehs/io/socket/ehc/NetEnc.h"
#include "ehs/io/socket/ehc/NetServerCh.h"
#include "ehs/io/socket/ehc/NetClientCh.h"
#include "ehs/io/socket/ehc/NetSys.h"
#include "ehs/io/socket/ehc/NetEnd.h"
#include "ehs/PRNG.h"
namespace ehs
{
const Version EHC::version(1, 0, 0);
EHC::~EHC()
{
Release();
}
EHC::EHC(const IP version)
: udp(version), buffer(nullptr), bufferSize(0), lastTSC(0), delta(0.0f)
{
}
EHC::EHC(EHC &&sock) noexcept
: udp((UDP&&)sock.udp), buffer(sock.buffer), bufferSize(sock.bufferSize), lastTSC(sock.lastTSC), delta(sock.delta),
encryptions((Array<NetEnc *> &&)sock.encryptions), servers((Array<NetServerCh *> &&)sock.servers),
clients((Array<NetClientCh *> &&)sock.clients)
{
for (UInt_64 i = 0; i < servers.Size(); i++)
servers[i]->owner = this;
for (UInt_64 i = 0; i < clients.Size(); i++)
clients[i]->owner = this;
sock.buffer = nullptr;
sock.bufferSize = 0;
sock.lastTSC = 0;
sock.delta = 0.0f;
}
EHC::EHC(const EHC &sock)
: udp(sock.udp), buffer(nullptr), bufferSize(0), lastTSC(CPU::GetTSC()), delta(0.0f),
encryptions(sock.encryptions), servers(sock.servers), clients(sock.clients)
{
for (UInt_64 i = 0; i < servers.Size(); i++)
servers[i]->owner = this;
for (UInt_64 i = 0; i < clients.Size(); i++)
clients[i]->owner = this;
Initialize();
}
EHC &EHC::operator=(EHC &&sock) noexcept
{
if (this == &sock)
return *this;
udp = (UDP &&)sock.udp;
delete[] buffer;
buffer = sock.buffer;
bufferSize = sock.bufferSize;
lastTSC = sock.lastTSC;
delta = sock.delta;
for (UInt_64 i = 0; i < encryptions.Size(); i++)
delete encryptions[i];
encryptions = (Array<NetEnc *> &&)sock.encryptions;
for (UInt_64 i = 0; i < servers.Size(); i++)
delete servers[i];
servers = (Array<NetServerCh *> &&)sock.servers;
for (UInt_64 i = 0; i < servers.Size(); i++)
servers[i]->owner = this;
for (UInt_64 i = 0; i < clients.Size(); i++)
delete clients[i];
clients = (Array<NetClientCh *> &&)sock.clients;
for (UInt_64 i = 0; i < clients.Size(); i++)
clients[i]->owner = this;
sock.buffer = nullptr;
sock.bufferSize = 0;
sock.lastTSC = 0;
sock.delta = 0.0f;
return *this;
}
EHC &EHC::operator=(const EHC &sock)
{
if (this == &sock)
return *this;
udp = sock.udp;
delete[] buffer;
buffer = nullptr;
bufferSize = 0;
lastTSC = 0;
delta = 0.0f;
for (UInt_64 i = 0; i < encryptions.Size(); i++)
delete encryptions[i];
encryptions = sock.encryptions;
for (UInt_64 i = 0; i < servers.Size(); i++)
delete servers[i];
servers = sock.servers;
for (UInt_64 i = 0; i < servers.Size(); i++)
servers[i]->owner = this;
for (UInt_64 i = 0; i < clients.Size(); i++)
delete clients[i];
clients = sock.clients;
for (UInt_64 i = 0; i < clients.Size(); i++)
clients[i]->owner = this;
Initialize();
return *this;
}
void EHC::Initialize()
{
if (!udp.IsValid())
return;
udp.SetBlocking(false);
if (udp.GetLocalEndpoint().version == IP::V4)
{
buffer = new Byte[EHS_IPV4_UDP_PAYLOAD];
bufferSize = EHS_IPV4_UDP_PAYLOAD;
}
else if (udp.GetLocalEndpoint().version == IP::V6)
{
buffer = new Byte[EHS_IPV6_UDP_PAYLOAD];
bufferSize = EHS_IPV6_UDP_PAYLOAD;
}
}
void EHC::Release()
{
if (!udp.IsValid())
return;
delete[] buffer;
buffer = nullptr;
bufferSize = 0;
for (UInt_64 i = 0; i < encryptions.Size(); i++)
delete encryptions[i];
encryptions.Clear();
for (UInt_64 i = 0; i < servers.Size(); i++)
delete servers[i];
servers.Clear();
for (UInt_64 i = 0; i < clients.Size(); i++)
delete clients[i];
clients.Clear();
udp.Release();
}
void EHC::Bind(const Endpoint &endpoint)
{
udp.Bind(endpoint);
}
void EHC::Poll()
{
if (!udp.IsValid())
return;
UInt_64 newTSC = CPU::GetTSC();
delta = (float)(newTSC - lastTSC) / (float)CPU::GetTSC_Freq();
lastTSC = newTSC;
Endpoint remoteEndpoint;
UInt_16 received;
while ((received = udp.Receive(&remoteEndpoint, buffer, bufferSize)))
{
Serializer<UInt_64> payload(Endianness::LE, buffer, received);
Version remoteVer = payload.ReadVersion();
if (remoteVer != version)
continue;
UInt_64 encId = payload.Read<UInt_64>();
if (encId)
{
Version remoteEncVersion = payload.ReadVersion();
NetEnc* enc = GetEncryption(encId);
if (!enc || enc->GetVersion() != remoteEncVersion)
continue;
enc->Decrypt(&payload[payload.GetOffset()], payload.Size() - payload.GetOffset());
}
payload.SetOffset(0);
Header header = ReadHeader(payload);
if (!header.channelId)
continue;
if (header.channelType == NetChannelType::SERVER)
{
NetServerCh *server = GetServer(header.channelId);
if (!server)
continue;
server->Process(delta, remoteEndpoint, header, payload);
}
else if (header.channelType == NetChannelType::CLIENT)
{
NetClientCh *client = GetClient(header.channelId);
if (!client)
continue;
client->Process(delta, remoteEndpoint, header, payload);
}
}
for (UInt_64 i = 0; i < servers.Size(); ++i)
servers[i]->Poll(delta);
for (UInt_64 i = 0; i < clients.Size(); ++i)
clients[i]->Poll(delta);
}
bool EHC::IsInitialized() const
{
return udp.IsValid();
}
Endpoint EHC::GetLocalEndpoint() const
{
return udp.GetLocalEndpoint();
}
bool EHC::IsBound() const
{
return udp.IsBound();
}
Version EHC::GetVersion()
{
return version;
}
bool EHC::AddEncryption(NetEnc* enc)
{
if (HasEncryption(enc->GetId()))
return false;
encryptions.Push(enc);
return true;
}
bool EHC::HasServer(const UInt_64 serverId) const
{
for (UInt_64 i = 0; i < servers.Size(); ++i)
if (servers[i]->GetId() == serverId)
return true;
return false;
}
bool EHC::HasServer(const Str_8 &serverName) const
{
return HasServer(serverName.Hash_64());
}
bool EHC::AddServer(NetServerCh *server)
{
if (HasServer(server->GetId()))
return false;
server->owner = this;
servers.Push(server);
return true;
}
NetServerCh *EHC::GetServer(const UInt_64 serverId) const
{
for (UInt_64 i = 0; i < servers.Size(); ++i)
if (servers[i]->GetId() == serverId)
return servers[i];
return nullptr;
}
NetServerCh *EHC::GetServer(const Str_8 &serverName) const
{
return GetServer(serverName.Hash_64());
}
bool EHC::HasClient(const UInt_64 clientId) const
{
for (UInt_64 i = 0; i < clients.Size(); ++i)
if (clients[i]->GetId() == clientId)
return true;
return false;
}
bool EHC::HasClient(const Str_8 &clientName) const
{
return HasClient(clientName.Hash_64());
}
bool EHC::AddClient(NetClientCh *client)
{
if (HasServer(client->GetId()))
return false;
client->owner = this;
clients.Push(client);
return true;
}
NetClientCh *EHC::GetClient(const UInt_64 clientId) const
{
for (UInt_64 i = 0; i < clients.Size(); ++i)
if (clients[i]->GetId() == clientId)
return clients[i];
return nullptr;
}
NetClientCh *EHC::GetClient(const Str_8 &clientName) const
{
return GetClient(clientName.Hash_64());
}
bool EHC::HasEncryption(UInt_64 encId) const
{
for (UInt_64 i = 0; i < encryptions.Size(); ++i)
if (encryptions[i]->GetId() == encId)
return true;
return false;
}
bool EHC::HasEncryption(const Str_8& encName) const
{
return HasEncryption(encName.Hash_64());
}
NetEnc* EHC::GetEncryption(UInt_64 encId) const
{
for (UInt_64 i = 0; i < encryptions.Size(); ++i)
if (encryptions[i]->GetId() == encId)
return encryptions[i];
return nullptr;
}
NetEnc* EHC::GetEncryption(const Str_8& encName) const
{
return GetEncryption(encName.Hash_64());
}
}

384
src/io/socket/ICMP_LNX.cpp Normal file
View File

@ -0,0 +1,384 @@
#include "ehs/io/socket/ICMP_LNX.h"
#include "ehs/Serializer.h"
#include "ehs/Log.h"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <ifaddrs.h>
#include <unistd.h>
namespace ehs
{
ICMP::~ICMP()
{
if (close(hdl) == -1)
EHS_LOG_INT(LogType::ERR, 0, "Failed to close socket.");
}
ICMP::ICMP()
: hdl(EHS_INVALID_SOCKET), src{}
{
}
ICMP::ICMP(const IP version)
: BaseICMP(version), src{}
{
if (version == IP::V6)
hdl = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
else
hdl = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (hdl < 0)
{
EHS_LOG_INT(LogType::ERR, 0, "Failed to create ICMP socket with error #" + Str_8::FromNum(errno) + ".");
return;
}
EHS_LOG_SUCCESS();
}
ICMP::ICMP(ICMP &&icmp) noexcept
: BaseICMP((BaseICMP &&)icmp), hdl(icmp.hdl), src(icmp.src)
{
icmp.hdl = EHS_INVALID_SOCKET;
icmp.src = {};
}
ICMP::ICMP(const ICMP &icmp)
: BaseICMP(icmp), hdl(icmp.hdl), src{}
{
}
ICMP & ICMP::operator=(ICMP &&icmp) noexcept
{
if (this == &icmp)
return *this;
BaseICMP::operator=((BaseICMP &&)icmp);
hdl = icmp.hdl;
src = icmp.src;
icmp.hdl = EHS_INVALID_SOCKET;
icmp.src = {};
return *this;
}
ICMP & ICMP::operator=(const ICMP &icmp)
{
if (this == &icmp)
return *this;
BaseICMP::operator=(icmp);
hdl = icmp.hdl;
src = {};
return *this;
}
void ICMP::Release()
{
if (close(hdl) == -1)
{
EHS_LOG_INT(LogType::ERR, 0, "Failed to close socket.");
return;
}
hdl = EHS_INVALID_SOCKET;
EHS_LOG_SUCCESS();
}
void ICMP::SetReceiveTimeout(const UInt_64 timeout)
{
timeval result = {};
result.tv_sec = (long)timeout;
result.tv_usec = 0;
if (setsockopt(hdl, SOL_SOCKET, SO_RCVTIMEO, &result, sizeof(result)) < 0)
{
EHS_LOG_INT(LogType::WARN, 0, "Failed to set receive timeout with error #" + Str_8::FromNum(errno) + ".");
return;
}
EHS_LOG_SUCCESS();
}
bool ICMP::IsValid() const
{
return hdl != EHS_INVALID_SOCKET;
}
bool ICMP::IsLinkLocal(const in6_addr &addr)
{
return addr.s6_addr[0] == 0xfe && (addr.s6_addr[1] & 0xc0) == 0x80;
}
sockaddr_in6 ICMP::RetrieveSrcAddress()
{
ifaddrs *ifaddr;
sockaddr_in6 addr = {};
if (getifaddrs(&ifaddr) == -1)
{
EHS_LOG_INT(LogType::ERR, 0, "Failed to retrieve public address with error #" + Str_8::FromNum(errno) + ".");
return addr;
}
for (ifaddrs *ifa = ifaddr; ifa; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == nullptr || ifa->ifa_addr->sa_family != AF_INET6)
continue;
addr = *(sockaddr_in6 *)ifa->ifa_addr;
if (!addr.sin6_addr.s6_addr32[0] || IsLinkLocal(addr.sin6_addr))
continue;
break;
}
freeifaddrs(ifaddr);
EHS_LOG_SUCCESS();
return addr;
}
UInt_32 ICMP::CalculatePseudoHeaderChecksum(const PseudoICMPv6_Header &header)
{
UInt_32 checksum = 0;
for (UInt_8 i = 0; i < 16; ++i)
checksum += header.src.sin6_addr.s6_addr[i];
for (UInt_8 i = 0; i < 16; ++i)
checksum += header.dst.sin6_addr.s6_addr[i];
checksum += 58;
checksum += htons(header.length);
checksum = (checksum >> 16) + (checksum & 0xFFFF);
checksum += (checksum >> 16);
return checksum;
}
UInt_16 ICMP::ComputeChecksumV6(UInt_16 *buffer, Size length, const sockaddr_in6 &dst)
{
UInt_32 checksum = 0;
if (!src.sin6_addr.s6_addr32[0])
{
src = RetrieveSrcAddress();
if (!src.sin6_addr.s6_addr32[0])
{
EHS_LOG_INT(LogType::ERR, 0, "Could not retrieve a suitable global address.");
return checksum;
}
}
checksum += CalculatePseudoHeaderChecksum({src, dst, (UInt_32)length});
while (length > 1)
{
checksum += *buffer++;
length -= sizeof(UInt_16);
}
if (length == 1)
checksum += *(UInt_8 *)buffer;
// Carry over any overflow from the 16-bit result
checksum = (checksum >> 16) + (checksum & 0xFFFF);
checksum += (checksum >> 16);
// Return the 16-bit complement
return ~checksum;
}
UInt_64 ICMP::SendV6(const Str_8 &address, ICMP_Header header, const Byte *data, UInt_64 size)
{
if (!IsValid())
{
EHS_LOG_INT(LogType::WARN, 0, "Socket is not initialized.");
return 0;
}
header.checksum = 0;
Serializer<UInt_64> payload(Endianness::LE);
payload.Write(header);
payload.Resize(payload.Size() + size);
Util::Copy(&payload[payload.GetOffset()], data, size);
payload.SetOffset(payload.GetOffset() + size);
sockaddr_in6 dst = {};
dst.sin6_family = AF_INET6;
inet_pton(AF_INET6, address, &(dst.sin6_addr));
header.checksum = ComputeChecksumV6((UInt_16 *)&payload[0], payload.Size(), dst);
payload.SetOffset(0);
payload.Write(header);
payload.SetOffset(payload.Size());
SInt_64 sent = sendto(hdl, payload, payload.Size(), 0, (sockaddr *)&dst, sizeof(sockaddr_in6));
if (sent < 0)
{
EHS_LOG_INT(LogType::ERR, 0, "Failed to send packet with error #" + Str_8::FromNum(errno) + ".");
return 0;
}
EHS_LOG_SUCCESS();
return sent;
}
UInt_64 ICMP::SendV4(const Str_8 &address, ICMP_Header header, const Byte *data, UInt_64 size)
{
if (!IsValid())
{
EHS_LOG_INT(LogType::WARN, 0, "Socket is not initialized.");
return 0;
}
header.checksum = 0;
Serializer<UInt_64> payload(Endianness::LE);
payload.Write(header);
payload.Resize(payload.Size() + size);
Util::Copy(&payload[payload.GetOffset()], data, size);
payload.SetOffset(payload.GetOffset() + size);
header.checksum = ComputeChecksumV4((UInt_16 *)&payload[0], payload.Size());
payload.SetOffset(0);
payload.Write(header);
payload.SetOffset(payload.Size());
sockaddr_in dst = {};
dst.sin_family = AF_INET;
inet_pton(AF_INET, address, &(dst.sin_addr));
SInt_64 sent = sendto(hdl, payload, payload.Size(), 0, (sockaddr *)&dst, sizeof(sockaddr_in));
if (sent < 0)
{
EHS_LOG_INT(LogType::ERR, 0, "Failed to send packet with error #" + Str_8::FromNum(errno) + ".");
return 0;
}
EHS_LOG_SUCCESS();
return sent;
}
UInt_64 ICMP::ReceiveV6(Str_8 &address, ICMP_Header &header, Serializer<UInt_64> &data) const
{
if (!IsValid())
{
EHS_LOG_INT(LogType::WARN, 0, "Socket is not initialized.");
return 0;
}
Serializer<UInt_64> payload(Endianness::LE);
payload.Resize(1500);
sockaddr_in6 remote = {};
socklen_t from_len = sizeof(remote);
SInt_64 recv = recvfrom(hdl, payload, 1500, 0, (sockaddr *)&remote, &from_len);
if (recv < 0)
{
int code = errno;
if (code == EAGAIN)
EHS_LOG_SUCCESS();
else
EHS_LOG_INT(LogType::ERR, 0, "Failed to receive packet with error #" + Str_8::FromNum(code) + ".");
return 0;
}
payload.Resize(recv);
char tmpAddr[INET6_ADDRSTRLEN];
if (!inet_ntop(remote.sin6_family, &remote.sin6_addr, tmpAddr, INET6_ADDRSTRLEN))
{
EHS_LOG_INT(LogType::ERR, 1, "Failed to convert IPv6 address with error #" + Str_8::FromNum(errno) + ".");
return recv;
}
address = tmpAddr;
header = payload.Read<ICMP_Header>();
data = Serializer<UInt_64>(payload.GetEndianness(), &payload[payload.GetOffset()], payload.Size() - payload.GetOffset());
EHS_LOG_SUCCESS();
return recv;
}
UInt_64 ICMP::ReceiveV4(Str_8 &address, ICMP_Header &header, Serializer<UInt_64> &data) const
{
if (!IsValid())
{
EHS_LOG_INT(LogType::WARN, 0, "Socket is not initialized.");
return 0;
}
Serializer<UInt_64> payload(Endianness::LE);
payload.Resize(1500);
sockaddr_in remote = {};
socklen_t from_len = sizeof(remote);
SInt_64 recv = recvfrom(hdl, payload, 1500, 0, (sockaddr *)&remote, &from_len);
if (recv < 0)
{
int code = errno;
if (code == EAGAIN)
EHS_LOG_SUCCESS();
else
EHS_LOG_INT(LogType::ERR, 0, "Failed to receive packet with error #" + Str_8::FromNum(code) + ".");
return 0;
}
payload.Resize(recv);
char tmpAddr[INET_ADDRSTRLEN];
if (!inet_ntop(remote.sin_family, &remote.sin_addr, tmpAddr, INET_ADDRSTRLEN))
{
EHS_LOG_INT(LogType::ERR, 1, "Failed to convert IPv4 address with error #" + Str_8::FromNum(errno) + ".");
return recv;
}
address = tmpAddr;
iphdr ipHeader = payload.Read<iphdr>();
header = payload.Read<ICMP_Header>();
data = Serializer<UInt_64>(payload.GetEndianness(), &payload[payload.GetOffset()], payload.Size() - payload.GetOffset());
EHS_LOG_SUCCESS();
return recv;
}
}

391
src/io/socket/ICMP_W32.cpp Normal file
View File

@ -0,0 +1,391 @@
#include "ehs/io/socket/ICMP_W32.h"
struct iphdr
{
u_char ip_hl:4, ip_v:4;
u_char ip_tos;
u_short ip_len;
u_short ip_id;
u_short ip_off;
u_char ip_ttl;
u_char ip_p;
u_short ip_sum;
in_addr ip_src, ip_dst;
};
namespace ehs
{
ICMP::~ICMP()
{
if (closesocket(hdl) == -1)
EHS_LOG_INT(LogType::ERR, 0, "Failed to close socket.");
}
ICMP::ICMP()
: hdl(EHS_INVALID_SOCKET)
{
}
ICMP::ICMP(const IP version)
: BaseICMP(version)
{
hdl = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (hdl < 0)
{
EHS_LOG_INT(LogType::ERR, 0, "Failed to create ICMP socket with error #" + Str_8::FromNum(errno) + ".");
return;
}
EHS_LOG_SUCCESS();
}
ICMP::ICMP(ICMP &&icmp) noexcept
: BaseICMP((BaseICMP &&)icmp), hdl(icmp.hdl)
{
icmp.hdl = EHS_INVALID_SOCKET;
}
ICMP::ICMP(const ICMP &icmp)
: BaseICMP(icmp), hdl(icmp.hdl)
{
}
ICMP & ICMP::operator=(ICMP &&icmp) noexcept
{
if (this == &icmp)
return *this;
BaseICMP::operator=((BaseICMP &&)icmp);
hdl = icmp.hdl;
icmp.hdl = EHS_INVALID_SOCKET;
return *this;
}
ICMP & ICMP::operator=(const ICMP &icmp)
{
if (this == &icmp)
return *this;
BaseICMP::operator=(icmp);
hdl = icmp.hdl;
return *this;
}
void ICMP::Release()
{
if (closesocket(hdl) == -1)
{
EHS_LOG_INT(LogType::ERR, 0, "Failed to close socket.");
return;
}
hdl = EHS_INVALID_SOCKET;
EHS_LOG_SUCCESS();
}
void ICMP::SetReceiveTimeout(UInt_64 timeout)
{
timeval result = {};
result.tv_sec = (long)timeout;
result.tv_usec = 0;
if (setsockopt(hdl, SOL_SOCKET, SO_RCVTIMEO, (const char *)&result, sizeof(result)) < 0)
{
EHS_LOG_INT(LogType::WARN, 0, "Failed to set receive timeout with error #" + Str_8::FromNum(errno) + ".");
return;
}
EHS_LOG_SUCCESS();
}
bool ICMP::IsValid() const
{
return hdl != EHS_INVALID_SOCKET;
}
bool ICMP::IsLinkLocal(const in6_addr &addr)
{
return addr.s6_addr[0] == 0xfe && (addr.s6_addr[1] & 0xc0) == 0x80;
}
sockaddr_in6 ICMP::RetrieveSrcAddress()
{
sockaddr_in6 addr = {};
UInt_32 outBufLen = 15000;
Array<Byte> buffer(outBufLen);
PIP_ADAPTER_ADDRESSES pAdapterAddresses = (PIP_ADAPTER_ADDRESSES)&buffer[0];
if (GetAdaptersAddresses(AF_INET6, GAA_FLAG_INCLUDE_PREFIX, nullptr, pAdapterAddresses, (PULONG)&outBufLen) == ERROR_BUFFER_OVERFLOW)
{
buffer.Resize(outBufLen);
pAdapterAddresses = (PIP_ADAPTER_ADDRESSES)&buffer[0];
}
if (GetAdaptersAddresses(AF_INET6, GAA_FLAG_INCLUDE_PREFIX, nullptr, pAdapterAddresses, (PULONG)&outBufLen) == NO_ERROR)
{
for (PIP_ADAPTER_ADDRESSES adapter = pAdapterAddresses; adapter != nullptr; adapter = adapter->Next)
{
for (PIP_ADAPTER_UNICAST_ADDRESS addrInfo = adapter->FirstUnicastAddress; addrInfo != nullptr; addrInfo = addrInfo->Next)
{
SOCKADDR *sa = addrInfo->Address.lpSockaddr;
if (sa->sa_family != AF_INET6)
continue;
sockaddr_in6 *ipv6Addr = (sockaddr_in6 *)sa;
// Skip link-local addresses
if (IN6_IS_ADDR_LINKLOCAL(&ipv6Addr->sin6_addr))
continue;
addr = *ipv6Addr;
return addr; // Return the first suitable address
}
}
}
EHS_LOG_SUCCESS();
return addr; // Return an empty sockaddr_in6 if no valid address was found
}
UInt_32 ICMP::CalculatePseudoHeaderChecksum(const PseudoICMPv6_Header &header)
{
UInt_32 checksum = 0;
for (UInt_8 i = 0; i < 16; ++i)
checksum += header.src.sin6_addr.s6_addr[i];
for (UInt_8 i = 0; i < 16; ++i)
checksum += header.dst.sin6_addr.s6_addr[i];
checksum += 58;
checksum += htons(header.length);
checksum = (checksum >> 16) + (checksum & 0xFFFF);
checksum += (checksum >> 16);
return checksum;
}
UInt_16 ICMP::ComputeChecksumV6(UInt_16 *buffer, Size length, const sockaddr_in6 &dst)
{
UInt_32 checksum = 0;
if (!src.sin6_addr.u.Word[0])
{
src = RetrieveSrcAddress();
if (!src.sin6_addr.u.Word[0])
{
EHS_LOG_INT(LogType::ERR, 0, "Could not retrieve a suitable global address.");
return checksum;
}
}
checksum += CalculatePseudoHeaderChecksum({src, dst, (UInt_32)length});
while (length > 1)
{
checksum += *buffer++;
length -= sizeof(UInt_16);
}
if (length == 1)
checksum += *(UInt_8 *)buffer;
// Carry over any overflow from the 16-bit result
checksum = (checksum >> 16) + (checksum & 0xFFFF);
checksum += (checksum >> 16);
// Return the 16-bit complement
return ~checksum;
}
UInt_64 ICMP::SendV6(const Str_8 &address, ICMP_Header header, const Byte *data, UInt_64 size)
{
if (!IsValid())
{
EHS_LOG_INT(LogType::WARN, 0, "Socket is not initialized.");
return 0;
}
header.checksum = 0;
Serializer<UInt_64> payload(Endianness::LE);
payload.Write(header);
payload.Resize(payload.Size() + size);
Util::Copy(&payload[payload.GetOffset()], data, size);
payload.SetOffset(payload.GetOffset() + size);
sockaddr_in6 dst = {};
dst.sin6_family = AF_INET6;
inet_pton(AF_INET6, address, &(dst.sin6_addr));
header.checksum = ComputeChecksumV6((UInt_16 *)&payload[0], payload.Size(), dst);
payload.SetOffset(0);
payload.Write(header);
payload.SetOffset(payload.Size());
SInt_64 sent = sendto(hdl, (const char *)&payload[0], payload.Size(), 0, (sockaddr *)&dst, sizeof(sockaddr_in6));
if (sent < 0)
{
EHS_LOG_INT(LogType::ERR, 0, "Failed to send packet with error #" + Str_8::FromNum(errno) + ".");
return 0;
}
EHS_LOG_SUCCESS();
return sent;
}
UInt_64 ICMP::SendV4(const Str_8 &address, ICMP_Header header, const Byte *data, UInt_64 size)
{
if (!IsValid())
{
EHS_LOG_INT(LogType::WARN, 0, "Socket is not initialized.");
return 0;
}
header.checksum = 0;
Serializer<UInt_64> payload(Endianness::LE);
payload.Write(header);
payload.Resize(payload.Size() + size);
Util::Copy(&payload[payload.GetOffset()], data, size);
payload.SetOffset(payload.GetOffset() + size);
header.checksum = ComputeChecksumV4((UInt_16 *)&payload[0], payload.Size());
payload.SetOffset(0);
payload.Write(header);
payload.SetOffset(payload.Size());
sockaddr_in dst_addr = {};
dst_addr.sin_family = AF_INET;
inet_pton(AF_INET, address, &(dst_addr.sin_addr));
SInt_64 sent = sendto(hdl, (const char *)&payload[0], payload.Size(), 0, (sockaddr *)&dst_addr, sizeof(dst_addr));
if (sent < 0)
{
EHS_LOG_INT(LogType::ERR, 0, "Failed to send packet with error #" + Str_8::FromNum(errno) + ".");
return 0;
}
EHS_LOG_SUCCESS();
return sent;
}
UInt_64 ICMP::ReceiveV6(Str_8 &address, ICMP_Header &header, Serializer<UInt_64> &data) const
{
if (!IsValid())
{
EHS_LOG_INT(LogType::WARN, 0, "Socket is not initialized.");
return 0;
}
Serializer<UInt_64> payload(Endianness::LE);
payload.Resize(1500);
sockaddr_in6 remote = {};
socklen_t from_len = sizeof(remote);
SInt_64 recv = recvfrom(hdl, (char *)&payload[0], 1500, 0, (sockaddr *)&remote, &from_len);
if (recv < 0)
{
int code = errno;
if (code == EAGAIN)
EHS_LOG_SUCCESS();
else
EHS_LOG_INT(LogType::ERR, 0, "Failed to receive packet with error #" + Str_8::FromNum(code) + ".");
return 0;
}
payload.Resize(recv);
char tmpAddr[INET6_ADDRSTRLEN];
if (!inet_ntop(remote.sin6_family, &remote.sin6_addr, tmpAddr, INET6_ADDRSTRLEN))
{
EHS_LOG_INT(LogType::ERR, 1, "Failed to convert IPv6 address with error #" + Str_8::FromNum(errno) + ".");
return recv;
}
address = tmpAddr;
header = payload.Read<ICMP_Header>();
data = Serializer<UInt_64>(payload.GetEndianness(), &payload[payload.GetOffset()], payload.Size() - payload.GetOffset());
EHS_LOG_SUCCESS();
return recv;
}
UInt_64 ICMP::ReceiveV4(Str_8 &address, ICMP_Header &header, Serializer<UInt_64> &data) const
{
if (!IsValid())
{
EHS_LOG_INT(LogType::WARN, 0, "Socket is not initialized.");
return 0;
}
Serializer<UInt_64> payload(Endianness::LE);
payload.Resize(1500);
sockaddr_in remote = {};
socklen_t from_len = sizeof(remote);
SInt_64 recv = recvfrom(hdl, (char *)&payload[0], 1500, 0, (sockaddr *)&remote, &from_len);
if (recv < 0)
{
int code = errno;
if (code == EAGAIN)
EHS_LOG_SUCCESS();
else
EHS_LOG_INT(LogType::ERR, 0, "Failed to receive packet with error #" + Str_8::FromNum(code) + ".");
return 0;
}
payload.Resize(recv);
char tmpAddr[INET_ADDRSTRLEN];
if (!inet_ntop(remote.sin_family, &remote.sin_addr, tmpAddr, INET_ADDRSTRLEN))
{
EHS_LOG_INT(LogType::ERR, 1, "Failed to convert IPv4 address with error #" + Str_8::FromNum(errno) + ".");
return recv;
}
address = tmpAddr;
iphdr ipHeader = payload.Read<iphdr>();
header = payload.Read<ICMP_Header>();
data = Serializer<UInt_64>(payload.GetEndianness(), &payload[payload.GetOffset()], payload.Size() - payload.GetOffset());
EHS_LOG_SUCCESS();
return recv;
}
}

View File

@ -29,7 +29,7 @@ namespace ehs
{ {
} }
SSL::SSL(const AddrType type) SSL::SSL(const IP type)
: TCP(type), ctx(nullptr), sslHdl(nullptr) : TCP(type), ctx(nullptr), sslHdl(nullptr)
{ {
SSL::Initialize(); SSL::Initialize();

View File

@ -38,7 +38,7 @@ namespace ehc
} }
Socket::Socket() Socket::Socket()
: hdl(EHS_INVALID_SOCKET), type(AddrType::IPV4), port(0), bound(false), appVer(0, 0, 0), : hdl(EHS_INVALID_SOCKET), type(IP::V4), port(0), bound(false), appVer(0, 0, 0),
disposition(Disposition::UNKNOWN), dropPackets(false), hashId(0), buffer(nullptr), bufferSize(0), disposition(Disposition::UNKNOWN), dropPackets(false), hashId(0), buffer(nullptr), bufferSize(0),
maxEndpoints(0), lastTSC(0), delta(0.0f), maxTimeout(5.0f), resendRate(0.5f), connectedCb(nullptr), maxEndpoints(0), lastTSC(0), delta(0.0f), maxTimeout(5.0f), resendRate(0.5f), connectedCb(nullptr),
activeCb(nullptr), disconnectedCb(nullptr) activeCb(nullptr), disconnectedCb(nullptr)
@ -47,7 +47,7 @@ namespace ehc
} }
Socket::Socket(const Version& ver, const Disposition disposition, const Str_8& id, const UInt_64 maxEndpoints) Socket::Socket(const Version& ver, const Disposition disposition, const Str_8& id, const UInt_64 maxEndpoints)
: hdl(EHS_INVALID_SOCKET), type(AddrType::IPV4), port(0), bound(false), appVer(ver), disposition(disposition), : hdl(EHS_INVALID_SOCKET), type(IP::V4), port(0), bound(false), appVer(ver), disposition(disposition),
dropPackets(false), id(id), hashId(id.Hash_32()), buffer(nullptr), bufferSize(0), dropPackets(false), id(id), hashId(id.Hash_32()), buffer(nullptr), bufferSize(0),
maxEndpoints(maxEndpoints), lastTSC(CPU::GetTSC()), delta(0.0f), maxTimeout(5.0f), resendRate(0.5f), maxEndpoints(maxEndpoints), lastTSC(CPU::GetTSC()), delta(0.0f), maxTimeout(5.0f), resendRate(0.5f),
connectedCb(nullptr), activeCb(nullptr), disconnectedCb(nullptr) connectedCb(nullptr), activeCb(nullptr), disconnectedCb(nullptr)
@ -113,9 +113,9 @@ namespace ehc
} }
#endif #endif
if (type == AddrType::IPV6) if (type == IP::V6)
hdl = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); hdl = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
else if (type == AddrType::IPV4) else if (type == IP::V4)
hdl = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); hdl = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
else else
return; return;
@ -140,12 +140,12 @@ namespace ehc
return; return;
} }
if (type == AddrType::IPV4) if (type == IP::V4)
{ {
buffer = new Byte[EHS_IPV4_UDP_PAYLOAD]; buffer = new Byte[EHS_IPV4_UDP_PAYLOAD];
bufferSize = EHS_IPV4_UDP_PAYLOAD; bufferSize = EHS_IPV4_UDP_PAYLOAD;
} }
else if (type == AddrType::IPV6) else if (type == IP::V6)
{ {
buffer = new Byte[EHS_IPV6_UDP_PAYLOAD]; buffer = new Byte[EHS_IPV6_UDP_PAYLOAD];
bufferSize = EHS_IPV6_UDP_PAYLOAD; bufferSize = EHS_IPV6_UDP_PAYLOAD;
@ -204,9 +204,9 @@ namespace ehc
if (hdl == EHS_INVALID_SOCKET || bound) if (hdl == EHS_INVALID_SOCKET || bound)
return; return;
if (type == AddrType::IPV6) if (type == IP::V6)
Bind_v6(newAddress, newPort); Bind_v6(newAddress, newPort);
else if (type == AddrType::IPV4) else if (type == IP::V4)
Bind_v4(newAddress, newPort); Bind_v4(newAddress, newPort);
address = newAddress; address = newAddress;
@ -580,7 +580,7 @@ namespace ehc
return hdl != EHS_INVALID_SOCKET; return hdl != EHS_INVALID_SOCKET;
} }
void Socket::SetAddressType(const AddrType newType) void Socket::SetAddressType(const IP newType)
{ {
if (hdl != EHS_INVALID_SOCKET) if (hdl != EHS_INVALID_SOCKET)
return; return;
@ -588,7 +588,7 @@ namespace ehc
type = newType; type = newType;
} }
AddrType Socket::GetAddressType() const IP Socket::GetAddressType() const
{ {
return type; return type;
} }
@ -1219,14 +1219,14 @@ namespace ehc
return 0; return 0;
} }
if (type == AddrType::IPV4 && size > EHS_IPV4_UDP_PAYLOAD) if (type == IP::V4 && size > EHS_IPV4_UDP_PAYLOAD)
{ {
EHS_LOG_INT(LogType::ERR, 1, "Attempted to receive with a buffer size of, \"" + Str_8::FromNum(size) EHS_LOG_INT(LogType::ERR, 1, "Attempted to receive with a buffer size of, \"" + Str_8::FromNum(size)
+ "\", that exceeds, \"" + Str_8::FromNum(EHS_IPV4_UDP_PAYLOAD) + "."); + "\", that exceeds, \"" + Str_8::FromNum(EHS_IPV4_UDP_PAYLOAD) + ".");
} }
sockaddr_in6 remote = {}; sockaddr_in6 remote = {};
UInt_32 addrLen = type == AddrType::IPV6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in); UInt_32 addrLen = type == IP::V6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in);
SInt_64 received = 0; SInt_64 received = 0;
#if defined(EHS_OS_WINDOWS) #if defined(EHS_OS_WINDOWS)

View File

@ -30,8 +30,8 @@ namespace ehs
{ {
} }
TCP::TCP(const AddrType addrType) TCP::TCP(const IP IP)
: BaseTCP(addrType), hdl(EHS_INVALID_SOCKET) : BaseTCP(IP), hdl(EHS_INVALID_SOCKET)
{ {
TCP::Initialize(); TCP::Initialize();
} }
@ -78,9 +78,9 @@ namespace ehs
if (IsValid()) if (IsValid())
return; return;
if (addrType == AddrType::IPV6) if (ip == IP::V6)
hdl = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP); hdl = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
else if (addrType == AddrType::IPV4) else if (ip == IP::V4)
hdl = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); hdl = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
else else
return; return;
@ -119,9 +119,9 @@ namespace ehs
if (!IsValid() || bound || connection) if (!IsValid() || bound || connection)
return; return;
if (addrType == AddrType::IPV6) if (ip == IP::V6)
Bind_v6(address, port); Bind_v6(address, port);
else if (addrType == AddrType::IPV4) else if (ip == IP::V4)
Bind_v4(address, port); Bind_v4(address, port);
this->localAddr = address; this->localAddr = address;
@ -155,7 +155,7 @@ namespace ehs
UInt_32 addrLen = sizeof(sockaddr_in6); UInt_32 addrLen = sizeof(sockaddr_in6);
TCP* client = new TCP(); TCP* client = new TCP();
client->addrType = addrType; client->ip = ip;
client->localAddr = localAddr; client->localAddr = localAddr;
client->localPort = localPort; client->localPort = localPort;
client->connection = true; client->connection = true;
@ -215,18 +215,18 @@ namespace ehs
remoteHostName = address; remoteHostName = address;
remotePort = port; remotePort = port;
if (addrType == AddrType::IPV6) if (ip == IP::V6)
{ {
if (IsIPv6Only()) if (IsIPv6Only())
remoteAddr = DNS::Resolve(AddrType::IPV6, address); remoteAddr = DNS::Resolve(IP::V6, address);
else else
remoteAddr = DNS::Resolve(address); remoteAddr = DNS::Resolve(address);
Connect_v6(remoteAddr, port); Connect_v6(remoteAddr, port);
} }
else if (addrType == AddrType::IPV4) else if (ip == IP::V4)
{ {
remoteAddr = DNS::Resolve(AddrType::IPV4, address); remoteAddr = DNS::Resolve(IP::V4, address);
Connect_v4(remoteAddr, port); Connect_v4(remoteAddr, port);
} }
@ -338,7 +338,7 @@ namespace ehs
void TCP::SetIPv6Only(const bool value) void TCP::SetIPv6Only(const bool value)
{ {
if (addrType != AddrType::IPV6) if (ip != IP::V6)
{ {
EHS_LOG_INT(LogType::WARN, 0, "Cannot set IPv6 only mode while socket is not using IPv6."); EHS_LOG_INT(LogType::WARN, 0, "Cannot set IPv6 only mode while socket is not using IPv6.");
return; return;
@ -362,7 +362,7 @@ namespace ehs
bool TCP::IsIPv6Only() const bool TCP::IsIPv6Only() const
{ {
if (addrType != AddrType::IPV6) if (ip != IP::V6)
return false; return false;
if (!IsValid()) if (!IsValid())

View File

@ -33,8 +33,8 @@ namespace ehs
{ {
} }
TCP::TCP(const AddrType addrType) TCP::TCP(const IP IP)
: BaseTCP(addrType), hdl(EHS_INVALID_SOCKET) : BaseTCP(IP), hdl(EHS_INVALID_SOCKET)
{ {
TCP::Initialize(); TCP::Initialize();
} }
@ -90,9 +90,9 @@ namespace ehs
return; return;
} }
if (addrType == AddrType::IPV6) if (ip == IP::V6)
hdl = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP); hdl = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
else if (addrType == AddrType::IPV4) else if (ip == IP::V4)
hdl = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); hdl = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
else else
return; return;
@ -142,9 +142,9 @@ namespace ehs
if (!IsValid() || bound || connection) if (!IsValid() || bound || connection)
return; return;
if (addrType == AddrType::IPV6) if (ip == IP::V6)
Bind_v6(address, port); Bind_v6(address, port);
else if (addrType == AddrType::IPV4) else if (ip == IP::V4)
Bind_v4(address, port); Bind_v4(address, port);
this->localAddr = address; this->localAddr = address;
@ -178,7 +178,7 @@ namespace ehs
UInt_32 addrLen = sizeof(sockaddr_in6); UInt_32 addrLen = sizeof(sockaddr_in6);
TCP* client = new TCP(); TCP* client = new TCP();
client->addrType = addrType; client->ip = ip;
client->localAddr = localAddr; client->localAddr = localAddr;
client->localPort = localPort; client->localPort = localPort;
client->connection = true; client->connection = true;
@ -244,18 +244,18 @@ namespace ehs
remoteHostName = address; remoteHostName = address;
remotePort = port; remotePort = port;
if (addrType == AddrType::IPV6) if (ip == IP::V6)
{ {
if (IsIPv6Only()) if (IsIPv6Only())
remoteAddr = DNS::Resolve(AddrType::IPV6, address); remoteAddr = DNS::Resolve(IP::V6, address);
else else
remoteAddr = DNS::Resolve(address); remoteAddr = DNS::Resolve(address);
Connect_v6(remoteAddr, port); Connect_v6(remoteAddr, port);
} }
else if (addrType == AddrType::IPV4) else if (ip == IP::V4)
{ {
remoteAddr = DNS::Resolve(AddrType::IPV4, address); remoteAddr = DNS::Resolve(IP::V4, address);
Connect_v4(remoteAddr, port); Connect_v4(remoteAddr, port);
} }
@ -359,7 +359,7 @@ namespace ehs
void TCP::SetIPv6Only(const bool value) void TCP::SetIPv6Only(const bool value)
{ {
if (addrType != AddrType::IPV6) if (ip != IP::V6)
{ {
EHS_LOG_INT(LogType::WARN, 0, "Cannot set IPv6 only mode while socket is not using IPv6."); EHS_LOG_INT(LogType::WARN, 0, "Cannot set IPv6 only mode while socket is not using IPv6.");
return; return;
@ -383,7 +383,7 @@ namespace ehs
bool TCP::IsIPv6Only() const bool TCP::IsIPv6Only() const
{ {
if (addrType != AddrType::IPV6) if (ip != IP::V6)
return false; return false;
if (!IsValid()) if (!IsValid())

View File

@ -25,12 +25,12 @@ namespace ehs
{ {
} }
UDP::UDP(const AddrType addrType) UDP::UDP(const IP version)
: BaseUDP(addrType), hdl(EHS_INVALID_SOCKET) : BaseUDP(version), hdl(EHS_INVALID_SOCKET)
{ {
if (addrType == AddrType::IPV6) if (version == IP::V6)
hdl = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); hdl = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
else if (addrType == AddrType::IPV4) else if (version == IP::V4)
hdl = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); hdl = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
else else
return; return;
@ -96,33 +96,32 @@ namespace ehs
bound = false; bound = false;
} }
void UDP::Bind(const AddrType type, const Str_8& address, const UInt_16 port) void UDP::Bind(const Endpoint &endpoint)
{ {
if (!IsValid() || bound) if (!IsValid() || bound)
return; return;
if (type == AddrType::IPV6) if (endpoint.version == IP::V6)
Bind_v6(address, port); Bind_v6(endpoint.address, endpoint.port);
else if (type == AddrType::IPV4) else if (endpoint.version == IP::V4)
Bind_v4(address, port); Bind_v4(endpoint.address, endpoint.port);
this->address = address; localEndpoint = endpoint;
this->port = port;
bound = true; bound = true;
} }
UInt_64 UDP::Send(const AddrType type, const Str_8& address, const UInt_16 port, const Byte *const data, const UInt_64 size) UInt_64 UDP::Send(const Endpoint &endpoint, const Byte *const data, const UInt_64 size)
{ {
if (type == AddrType::IPV6) if (endpoint.version == IP::V6)
return Send_v6(address, port, data, size); return Send_v6(endpoint.address, endpoint.port, data, size);
else if (type == AddrType::IPV4) else if (endpoint.version == IP::V4)
return Send_v4(address, port, data, size); return Send_v4(endpoint.address, endpoint.port, data, size);
return 0; return 0;
} }
UInt_64 UDP::Receive(AddrType* const type, Str_8* const address, UInt_16* const port, Byte* const data, const UInt_64 size) UInt_64 UDP::Receive(Endpoint *endpoint, Byte* const data, const UInt_64 size)
{ {
if (!IsValid()) if (!IsValid())
{ {
@ -161,9 +160,7 @@ namespace ehs
return received; return received;
} }
*type = AddrType::IPV6; *endpoint = {IP::V6, tmpAddr, remote.sin6_port};
*address = tmpAddr;
*port = ntohs(remote.sin6_port);
} }
else if (addrLen == sizeof(sockaddr_in)) else if (addrLen == sizeof(sockaddr_in))
{ {
@ -178,9 +175,7 @@ namespace ehs
return received; return received;
} }
*type = AddrType::IPV4; *endpoint = {IP::V4, tmpAddr, ntohs(((sockaddr_in*)&remote)->sin_port)};
*address = tmpAddr;
*port = ntohs(((sockaddr_in*)&remote)->sin_port);
} }
return received; return received;
@ -205,7 +200,7 @@ namespace ehs
void UDP::SetIPv6Only(const bool value) void UDP::SetIPv6Only(const bool value)
{ {
if (type != AddrType::IPV6) if (localEndpoint.version != IP::V6)
{ {
EHS_LOG_INT(LogType::WARN, 0, "Cannot set IPv6 only mode while socket is not using IPv6."); EHS_LOG_INT(LogType::WARN, 0, "Cannot set IPv6 only mode while socket is not using IPv6.");
return; return;
@ -229,7 +224,7 @@ namespace ehs
bool UDP::IsIPv6Only() const bool UDP::IsIPv6Only() const
{ {
if (type != AddrType::IPV6) if (localEndpoint.version != IP::V6)
return false; return false;
if (!IsValid()) if (!IsValid())

View File

@ -24,8 +24,8 @@ namespace ehs
{ {
} }
UDP::UDP(const AddrType addrType) UDP::UDP(const IP IP)
: BaseUDP(addrType), hdl(EHS_INVALID_SOCKET) : BaseUDP(IP), hdl(EHS_INVALID_SOCKET)
{ {
WSADATA data = {}; WSADATA data = {};
@ -36,9 +36,9 @@ namespace ehs
return; return;
} }
if (addrType == AddrType::IPV6) if (IP == IP::V6)
hdl = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); hdl = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
else if (addrType == AddrType::IPV4) else if (IP == IP::V4)
hdl = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); hdl = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
else else
return; return;
@ -110,33 +110,32 @@ namespace ehs
bound = false; bound = false;
} }
void UDP::Bind(const AddrType type, const Str_8& address, const UInt_16 port) void UDP::Bind(const Endpoint &endpoint)
{ {
if (!IsValid() || bound) if (!IsValid() || bound)
return; return;
if (type == AddrType::IPV6) if (endpoint.version == IP::V6)
Bind_v6(address, port); Bind_v6(endpoint.address, endpoint.port);
else if (type == AddrType::IPV4) else if (endpoint.version == IP::V4)
Bind_v4(address, port); Bind_v4(endpoint.address, endpoint.port);
this->address = address; localEndpoint = endpoint;
this->port = port;
bound = true; bound = true;
} }
UInt_64 UDP::Send(const AddrType type, const Str_8& address, const UInt_16 port, const Byte *const data, const UInt_64 size) UInt_64 UDP::Send(const Endpoint &endpoint, const Byte *const data, const UInt_64 size)
{ {
if (type == AddrType::IPV6) if (endpoint.version == IP::V6)
return Send_v6(address, port, data, size); return Send_v6(endpoint.address, endpoint.port, data, size);
else if (type == AddrType::IPV4) else if (endpoint.version == IP::V4)
return Send_v4(address, port, data, size); return Send_v4(endpoint.address, endpoint.port, data, size);
return 0; return 0;
} }
UInt_64 UDP::Receive(AddrType* type, Str_8* const address, UInt_16* const port, Byte* const data, const UInt_64 size) UInt_64 UDP::Receive(Endpoint *endpoint, Byte* const data, const UInt_64 size)
{ {
if (!IsValid()) if (!IsValid())
{ {
@ -174,9 +173,11 @@ namespace ehs
return received; return received;
} }
*type = AddrType::IPV6; *endpoint = {
*address = tmpAddr; IP::V6,
*port = ntohs(remote.sin6_port); tmpAddr,
ntohs(remote.sin6_port)
};
} }
else if (addrLen == sizeof(sockaddr_in)) else if (addrLen == sizeof(sockaddr_in))
{ {
@ -191,9 +192,11 @@ namespace ehs
return received; return received;
} }
*type = AddrType::IPV4; *endpoint = {
*address = tmpAddr; IP::V4,
*port = ntohs(((sockaddr_in*)&remote)->sin_port); tmpAddr,
ntohs(((sockaddr_in*)&remote)->sin_port)
};
} }
return received; return received;
@ -225,7 +228,7 @@ namespace ehs
void UDP::SetIPv6Only(const bool value) void UDP::SetIPv6Only(const bool value)
{ {
if (type != AddrType::IPV6) if (localEndpoint.version != IP::V6)
{ {
EHS_LOG_INT(LogType::WARN, 0, "Cannot set IPv6 only mode while socket is not using IPv6."); EHS_LOG_INT(LogType::WARN, 0, "Cannot set IPv6 only mode while socket is not using IPv6.");
return; return;
@ -249,7 +252,7 @@ namespace ehs
bool UDP::IsIPv6Only() const bool UDP::IsIPv6Only() const
{ {
if (type != AddrType::IPV6) if (localEndpoint.version != IP::V6)
return false; return false;
if (!IsValid()) if (!IsValid())
@ -362,7 +365,7 @@ namespace ehs
Int_32 code = inet_pton(AF_INET6, addr, &result.sin6_addr); Int_32 code = inet_pton(AF_INET6, addr, &result.sin6_addr);
if (!code) if (!code)
{ {
EHS_LOG_INT(LogType::ERR, 1, "The given address, \"" + address + "\" is not valid."); EHS_LOG_INT(LogType::ERR, 1, "The given address, \"" + addr + "\" is not valid.");
return 0; return 0;
} }
else if (code == -1) else if (code == -1)
@ -403,7 +406,7 @@ namespace ehs
int code = inet_pton(AF_INET, addr, &result.sin_addr); int code = inet_pton(AF_INET, addr, &result.sin_addr);
if (!code) if (!code)
{ {
EHS_LOG_INT(LogType::ERR, 1, "The given address, \"" + address + "\" is not valid."); EHS_LOG_INT(LogType::ERR, 1, "The given address, \"" + addr + "\" is not valid.");
return 0; return 0;
} }
else if (code == -1) else if (code == -1)

View File

@ -0,0 +1,193 @@
#include "ehs/io/socket/ehc/NetChannel.h"
#include "ehs/io/socket/ehc/NetEnd.h"
#include "ehs/io/socket/ehc/NetSys.h"
#include "ehs/io/socket/EHC.h"
#include "ehs/PRNG.h"
namespace ehs
{
const UInt_64 NetChannel::internalSys = Str_8::Hash_64("Internal");
const UInt_64 NetChannel::connectOp = Str_8::Hash_64("Connect");
const UInt_64 NetChannel::connectedOp = Str_8::Hash_64("Connected");
const UInt_64 NetChannel::rejectedOp = Str_8::Hash_64("Rejected");
const UInt_64 NetChannel::disconnectOp = Str_8::Hash_64("Disconnect");
const UInt_64 NetChannel::disconnectedOp = Str_8::Hash_64("Disconnected");
const UInt_64 NetChannel::statusUpdateOp = Str_8::Hash_64("StatusUpdate");
const UInt_64 NetChannel::pingOp = Str_8::Hash_64("Ping");
const UInt_64 NetChannel::pongOp = Str_8::Hash_64("Pong");
const UInt_64 NetChannel::latencyOp = Str_8::Hash_64("Latency");
const UInt_64 NetChannel::receivedOp = Str_8::Hash_64("Received");
NetChannel::~NetChannel()
{
}
NetChannel::NetChannel()
: owner(nullptr), id(0), maxTimeout(5.0f), resendRate(0.5f)
{
}
NetChannel::NetChannel(Str_8 name, const Version &version)
: owner(nullptr), id(name.Hash_64()), name((Str_8 &&)name), version(version), maxTimeout(5.0f),
resendRate(0.5f)
{
}
NetChannel::NetChannel(NetChannel &&channel) noexcept
: owner(channel.owner), id(channel.id), name((Str_8 &&)channel.name), version(channel.version),
maxTimeout(channel.maxTimeout), resendRate(channel.resendRate)
{
channel.owner = nullptr;
channel.id = 0;
channel.version = {};
channel.maxTimeout = 5.0f;
channel.resendRate = 0.5f;
}
NetChannel::NetChannel(const NetChannel &channel)
: owner(nullptr), id(channel.id), name(channel.name), version(channel.version),
maxTimeout(channel.maxTimeout), resendRate(channel.resendRate)
{
}
NetChannel &NetChannel::operator=(NetChannel &&channel) noexcept
{
if (this == &channel)
return *this;
owner = channel.owner;
id = channel.id;
name = (Str_8 &&)channel.name;
version = channel.version;
maxTimeout = channel.maxTimeout;
resendRate = channel.resendRate;
channel.owner = nullptr;
channel.id = 0;
channel.version = {};
channel.maxTimeout = 5.0f;
channel.resendRate = 0.5f;
return *this;
}
NetChannel &NetChannel::operator=(const NetChannel &channel)
{
if (this == &channel)
return *this;
owner = nullptr;
id = channel.id;
name = channel.name;
version = channel.version;
maxTimeout = channel.maxTimeout;
resendRate = channel.resendRate;
return *this;
}
EHC *NetChannel::GetOwner() const
{
return owner;
}
UInt_64 NetChannel::GetId() const
{
return id;
}
Str_8 NetChannel::GetName() const
{
return name;
}
Version NetChannel::GetVersion() const
{
return version;
}
void NetChannel::SetMaxTimeout(const float seconds)
{
maxTimeout = seconds;
}
float NetChannel::GetMaxTimeout() const
{
return maxTimeout;
}
void NetChannel::SetResendRate(const float seconds)
{
resendRate = seconds;
}
float NetChannel::GetResendRate() const
{
return resendRate;
}
void NetChannel::EnableDropPackets(const bool enable)
{
dropPackets = enable;
}
bool NetChannel::IsDropPacketsEnabled() const
{
return dropPackets;
}
bool NetChannel::AddSystem(NetSys *sys)
{
if (sys->GetId() == internalSys)
return false;
if (HasSystem(sys->GetId()))
return false;
systems.Push(sys);
return true;
}
bool NetChannel::IsValid() const
{
return owner && id;
}
void NetChannel::Process(const float &delta, const Endpoint &endpoint, const Header &header, Serializer<UInt_64> &payload)
{
}
void NetChannel::Poll(const float &delta)
{
}
bool NetChannel::HasSystem(const UInt_64 sysId) const
{
for (UInt_64 i = 0; i < systems.Size(); ++i)
if (systems[i]->GetId() == sysId)
return true;
return false;
}
bool NetChannel::HasSystem(const Str_8& sysName) const
{
return HasSystem(sysName.Hash_64());
}
NetSys* NetChannel::GetSystem(const UInt_64 sysId) const
{
for (UInt_64 i = 0; i < systems.Size(); ++i)
if (systems[i]->GetId() == sysId)
return systems[i];
return nullptr;
}
NetSys* NetChannel::GetSystem(const Str_8& sysName) const
{
return GetSystem(sysName.Hash_64());
}
}

View File

@ -0,0 +1,385 @@
#include "ehs/io/socket/ehc/NetClientCh.h"
#include "ehs/io/socket/EHC.h"
namespace ehs
{
NetClientCh::~NetClientCh()
{
}
NetClientCh::NetClientCh()
: token{}, status(NetStatus::DISCONNECTED), queueSlot(0), deltaDuration(0.0f), deltaRate(0.0f), lastPing(0.0f),
latency(0.0f), timeout(5.0f), nextSendId(0), nextRecvId(0)
{
}
NetClientCh::NetClientCh(Str_8 name, const Version &version, Endpoint remoteEndpoint)
: NetChannel((Str_8 &&)name, version), remoteEndpoint((Endpoint &&)remoteEndpoint), token{},
status(NetStatus::DISCONNECTED), queueSlot(0), deltaDuration(0.0f), deltaRate(0.0f), lastPing(0.0f),
latency(0.0f), timeout(0.0f), nextSendId(0), nextRecvId(0)
{
}
NetClientCh::NetClientCh(NetClientCh &&client) noexcept
: NetChannel((NetChannel &&)client), remoteEndpoint((Endpoint &&)client.remoteEndpoint), token{},
status(client.status), queueSlot(client.queueSlot), deltaDuration(0.0f), deltaRate(0.0f), lastPing(0.0f),
latency(0.0f), timeout(0.0f), nextSendId(0), sent((Vector<Insurance> &&)client.sent), nextRecvId(0),
received((Vector<NetFrag> &&)client.received)
{
Util::Copy(token, client.token, 64);
Util::Zero(client.token, 64);
client.status = NetStatus::DISCONNECTED;
client.queueSlot = 0;
client.deltaDuration = 0.0f;
client.deltaRate = 0.0f;
client.lastPing = 0.0f;
client.latency = 0.0f;
client.timeout = 0.0f;
client.nextSendId = 0;
client.nextRecvId = 0;
}
NetClientCh::NetClientCh(const NetClientCh &client)
: NetChannel(client), remoteEndpoint(client.remoteEndpoint), token{}, status(NetStatus::DISCONNECTED),
queueSlot(0), deltaDuration(0.0f), deltaRate(0.0f), lastPing(0.0f), latency(0.0f), timeout(0.0f), nextSendId(0),
nextRecvId(0)
{
}
NetClientCh & NetClientCh::operator=(NetClientCh &&client) noexcept
{
if (this == &client)
return *this;
NetChannel::operator=((NetChannel &&)client);
remoteEndpoint = (Endpoint &&)client.remoteEndpoint;
Util::Copy(token, client.token, 64);
status = client.status;
queueSlot = client.queueSlot;
deltaDuration = client.deltaDuration;
deltaRate = client.deltaRate;
lastPing = client.lastPing;
latency = client.latency;
timeout = client.timeout;
nextSendId = client.nextSendId;
sent = (Vector<Insurance> &&)client.sent;
nextRecvId = client.nextRecvId;
received = (Vector<NetFrag> &&)client.received;
Util::Zero(client.token, 64);
client.status = NetStatus::DISCONNECTED;
client.queueSlot = 0;
client.deltaDuration = 0.0f;
client.deltaRate = 0.0f;
client.lastPing = 0.0f;
client.latency = 0.0f;
client.timeout = 0.0f;
client.nextSendId = 0;
client.nextRecvId = 0;
return *this;
}
NetClientCh & NetClientCh::operator=(const NetClientCh &client)
{
if (this == &client)
return *this;
remoteEndpoint = client.remoteEndpoint;
Util::Zero(token, 64);
status = NetStatus::DISCONNECTED;
queueSlot = 0;
deltaDuration = 0.0f;
deltaRate = 0.0f;
lastPing = 0.0f;
latency = 0.0f;
timeout = 0.0f;
nextSendId = 0;
sent = {};
nextRecvId = 0;
received = {};
return *this;
}
void NetClientCh::OnConnected(Serializer<UInt_64> data)
{
}
void NetClientCh::OnActive(Serializer<UInt_64> data)
{
}
void NetClientCh::OnQueueUpdate(Serializer<UInt_64> data)
{
}
void NetClientCh::OnDisconnected(Serializer<UInt_64> data)
{
}
void NetClientCh::OnRejected(Serializer<UInt_64> data)
{
}
void NetClientCh::OnTimeout(Serializer<UInt_64> data)
{
}
void NetClientCh::Connect(const Endpoint &endpoint, const Serializer<UInt_64> &payload)
{
if (!GetOwner()->udp.IsValid())
return;
Send(false, true, false, internalSys, connectOp, payload);
status = NetStatus::PENDING;
}
bool NetClientCh::Disconnect(const Serializer<UInt_64> &payload)
{
if (!GetOwner()->udp.IsValid())
return false;
Send(false, true, false, internalSys, disconnectOp, payload);
return true;
}
void NetClientCh::Send(const bool deltaLocked, UInt_64 encId, const bool ensure, UInt_64 sysId, UInt_64 opId,
const Serializer<UInt_64> &payload)
{
if (!IsValid() || (deltaLocked && deltaDuration < deltaRate))
return;
const EHC *owner = GetOwner();
NetEnc *enc = owner->GetEncryption(encId);
if (!enc)
{
EHS_LOG_INT(LogType::WARN, 0, "Encryption with the Id, \"" + Str_8::FromNum(encId) + "\", does not exist.");
return;
}
Header header = {
EHC::GetVersion(),
encId,
enc->GetVersion(),
GetId(),
NetChannelType::SERVER,
GetVersion(),
nextSendId++,
1,
0,
ensure,
"",
sysId,
opId
};
Util::Copy(header.token, token, 64);
const Endpoint localEndpoint = owner->GetLocalEndpoint();
if ((localEndpoint.version == IP::V6 && payload.Size() > EHC_IPV6_PAYLOAD) || (localEndpoint.version == IP::V4 && payload.Size() > EHC_IPV4_PAYLOAD))
{
NetFrag frags = FragmentData(localEndpoint.version, header, payload);
for (UInt_64 i = 0; i < frags.Size(); ++i)
{
Header newHeader = frags.GetHeader();
newHeader.fragment = i;
Send(enc, newHeader, frags[i]);
}
}
else
{
Send(enc, header, payload);
}
}
void NetClientCh::Send(const bool deltaLocked, const Str_8 &encName, const bool ensure, const Str_8 &sysName,
const Str_8 &opName, const Serializer<UInt_64> &payload)
{
Send(deltaLocked, encName.Hash_64(), ensure, sysName.Hash_64(), opName.Hash_64(), payload);
}
NetStatus NetClientCh::GetStatus() const
{
return status;
}
void NetClientCh::Process(const float &delta, const Endpoint &endpoint, const Header &header, Serializer<UInt_64> &payload)
{
if (!Util::Compare(token, header.token, 64))
return;
if (!header.ensure && header.token[0] && header.systemId == internalSys && header.opId == connectedOp)
{
if (status != NetStatus::PENDING)
return;
Util::Copy(token, header.token, 64);
status = payload.Read<NetStatus>();
queueSlot = payload.Read<UInt_64>();
OnConnected({Endianness::LE, &payload[payload.GetOffset()], payload.Size() - payload.GetOffset()});
}
else if (!header.ensure && header.token[0] && header.systemId == internalSys && header.opId == disconnectedOp)
{
OnDisconnected({Endianness::LE, &payload[payload.GetOffset()], payload.Size() - payload.GetOffset()});
}
else if (!header.ensure && header.token[0] && header.systemId == internalSys && header.opId == rejectedOp)
{
OnRejected({Endianness::LE, &payload[payload.GetOffset()], payload.Size() - payload.GetOffset()});
}
else if (!header.ensure && header.token[0] && header.systemId == internalSys && header.opId == statusUpdateOp)
{
const NetStatus newStatus = payload.Read<NetStatus>();
queueSlot = payload.Read<UInt_64>();
if (status == NetStatus::ACTIVE)
OnActive({Endianness::LE, &payload[payload.GetOffset()], payload.Size() - payload.GetOffset()});
else if (status == NetStatus::QUEUED && newStatus == NetStatus::QUEUED)
OnQueueUpdate({Endianness::LE, &payload[payload.GetOffset()], payload.Size() - payload.GetOffset()});
status = newStatus;
}
else if (!header.ensure && header.token[0] && header.systemId == internalSys && header.opId == receivedOp)
{
const UInt_64 msgId = payload.Read<UInt_64>();
const UInt_64 fragment = payload.Read<UInt_64>();
RemoveInsurance(msgId, fragment);
}
else if (!header.ensure && header.token[0] && header.systemId == internalSys && header.opId == pingOp)
{
deltaRate = payload.Read<float>();
Pong(delta);
}
else if (!header.ensure && header.token[0] && header.systemId == internalSys && header.opId == latencyOp)
{
latency = payload.Read<float>();
}
}
void NetClientCh::Poll(const float &delta)
{
}
NetFrag NetClientCh::FragmentData(const IP version, const Header& header, const Serializer<>& data)
{
NetFrag result;
if (version == IP::V6)
{
UInt_64 frags = data.Size() / EHC_IPV6_PAYLOAD;
if (data.Size() % EHC_IPV6_PAYLOAD)
++frags;
result = NetFrag(header, frags);
UInt_64 size = EHC_IPV6_PAYLOAD;
for (UInt_64 i = 0; i < result.Size(); ++i)
{
size = EHC_IPV6_PAYLOAD;
if (i == result.Size() - 1)
size = data.Size() % EHC_IPV6_PAYLOAD;
result[i] = {data.GetEndianness(), &data[i * EHC_IPV6_PAYLOAD], size};
}
}
else if (version == IP::V4)
{
UInt_64 frags = data.Size() / EHC_IPV4_PAYLOAD;
if (data.Size() % EHC_IPV4_PAYLOAD)
++frags;
result = NetFrag(header, frags);
UInt_64 size = EHC_IPV4_PAYLOAD;
for (UInt_64 i = 0; i < result.Size(); ++i)
{
size = EHC_IPV4_PAYLOAD;
if (i == result.Size() - 1)
size = data.Size() % EHC_IPV4_PAYLOAD;
result[i] = {data.GetEndianness(), &data[i * EHC_IPV4_PAYLOAD], size};
}
}
return result;
}
void NetClientCh::Send(NetEnc *enc, const Header& header, const Serializer<UInt_64>& payload)
{
Serializer result(Endianness::LE);
result.Write(header);
result.WriteSer(payload);
enc->Encrypt(&result[sizeof(bool)], result.Size() - sizeof(bool));
if (header.ensure)
sent.Push({header, payload});
GetOwner()->udp.Send(remoteEndpoint, result, result.Size());
}
void NetClientCh::Pong(const float delta)
{
Serializer payload(Endianness::LE);
payload.Write(delta);
Send(false, true, false, internalSys, pongOp, payload);
timeout = 0.0f;
}
void NetClientCh::RemoveInsurance(const UInt_64 msgId, const UInt_64 fragment)
{
for (UInt_64 i = 0; i < sent.Size(); ++i)
{
if (sent[i].header.id == msgId && sent[i].header.fragment == fragment)
{
sent.Remove(i);
break;
}
}
timeout = 0.0f;
}
void NetClientCh::AddReceived(const Header& header, const Serializer<>& payload)
{
NetFrag* frags = nullptr;
for (UInt_64 i = 0; i < received.Size(); ++i)
{
if (received[i].GetHeader().id == header.id)
{
if (received[i][header.fragment].Size())
return;
frags = &received[i];
break;
}
}
if (header.id > nextRecvId)
nextRecvId = header.id + 1;
if (frags)
(*frags)[header.fragment] = payload;
else
received.Push({header, payload});
timeout = 0.0f;
}
}

View File

@ -0,0 +1,76 @@
#include "ehs/io/socket/ehc/NetEnc.h"
namespace ehs
{
NetEnc::NetEnc()
: id(0)
{
}
NetEnc::NetEnc(Str_8 name, const Version &version)
: id(name.Hash_64()), name((Str_8 &&)name), version(version)
{
}
NetEnc::NetEnc(NetEnc&& enc) noexcept
: id(enc.id), name((Str_8 &&)enc.name), version(enc.version)
{
enc.id = 0;
enc.version = {};
}
NetEnc::NetEnc(const NetEnc& enc)
: id(enc.id), name(enc.name), version(enc.version)
{
}
NetEnc& NetEnc::operator=(NetEnc&& enc) noexcept
{
if (this == &enc)
return *this;
id = enc.id;
name = (Str_8 &&)enc.name;
version = enc.version;
enc.id = 0;
enc.version = {};
return *this;
}
NetEnc& NetEnc::operator=(const NetEnc& enc)
{
if (this == &enc)
return *this;
id = enc.id;
name = enc.name;
version = enc.version;
return *this;
}
UInt_64 NetEnc::GetId() const
{
return id;
}
Str_8 NetEnc::GetName() const
{
return name;
}
Version NetEnc::GetVersion() const
{
return version;
}
void NetEnc::Encrypt(Byte *data, UInt_64 size) const
{
}
void NetEnc::Decrypt(Byte *data, UInt_64 size) const
{
}
}

View File

@ -0,0 +1,511 @@
#include "ehs/io/socket/ehc/NetEnd.h"
#include "ehs/io/socket/EHC.h"
#include "ehs/io/socket/ehc/NetEnc.h"
#include "ehs/io/socket/ehc/NetServerCh.h"
#include "ehs/system/CPU.h"
namespace ehs
{
NetEnd::NetEnd()
: owner(nullptr), id(0), status(NetStatus::PENDING), token{}, nextSendId(0), nextRecvId(0),
deltaDuration(0.0f), deltaRate(1.0f / 60.0f), timeout(0.0f), lastPing(0.0f), oldLatency(0.0f),
latency(0.0f), queueSlot(0)
{
}
NetEnd::NetEnd(Str_8 id, Endpoint endpoint)
: owner(nullptr), id(id.Hash_64()), name((Str_8&&)id), status(NetStatus::ACTIVE), token{}, nextSendId(0),
nextRecvId(0), endpoint((Endpoint &&)endpoint), deltaDuration(0.0f), deltaRate(1.0f / 60.0f),
timeout(0.0f), lastPing(0.0f), oldLatency(0.0f), latency(0.0f), queueSlot(0)
{
}
NetEnd::NetEnd(Endpoint endpoint)
: owner(nullptr), id(0), status(NetStatus::PENDING), token{}, nextSendId(0), nextRecvId(0),
endpoint((Endpoint &&)endpoint), deltaDuration(0.0f), deltaRate(1.0f / 60.0f), timeout(0.0f), lastPing(0.0f),
oldLatency(0.0f), latency(0.0f), queueSlot(0)
{
}
NetEnd::NetEnd(NetEnd &&end) noexcept
: owner(end.owner), id(end.id), name((Str_8&&)end.name), status(end.status), token{},
nextSendId(end.nextSendId), sent((Vector<Insurance>&&)end.sent), nextRecvId(end.nextRecvId),
received((Vector<NetFrag>&&)end.received), endpoint((Endpoint &&)end.endpoint),
deltaDuration(end.deltaDuration), deltaRate(end.deltaRate), timeout(end.timeout), lastPing(end.lastPing),
oldLatency(end.oldLatency), latency(end.latency), queueSlot(end.queueSlot)
{
end.owner = nullptr;
end.id = 0;
end.status = NetStatus::PENDING;
Util::Copy(token, end.token, 64);
Util::Zero(end.token, 64);
end.nextSendId = 0;
end.nextRecvId = 0;
end.deltaDuration = 0.0f;
end.deltaRate = 1.0f / 60.0f;
end.timeout = 0.0f;
end.lastPing = 0.0f;
end.oldLatency = 0.0f;
end.latency = 0.0f;
end.queueSlot = 0;
}
NetEnd::NetEnd(const NetEnd& end)
: owner(nullptr), id(end.id), name(end.name), status(NetStatus::PENDING), token{}, nextSendId(0),
nextRecvId(0), deltaDuration(0.0f), deltaRate(1.0f / 60.0f), timeout(0.0f), lastPing(0.0f), oldLatency(0.0f),
latency(0.0f), queueSlot(0)
{
}
NetEnd& NetEnd::operator=(NetEnd&& end) noexcept
{
if (this == &end)
return *this;
owner = end.owner;
id = end.id;
name = (Str_8&&)end.name;
status = end.status;
Util::Copy(token, end.token, 64);
nextSendId = end.nextSendId;
sent = (Vector<Insurance>&&)end.sent;
nextRecvId = end.nextRecvId;
received = (Vector<NetFrag>&&)end.received;
endpoint = (Endpoint &&)end.endpoint;
deltaDuration = end.deltaDuration;
deltaRate = end.deltaRate;
timeout = end.timeout;
lastPing = end.lastPing;
oldLatency = end.oldLatency;
latency = end.latency;
queueSlot = end.queueSlot;
end.owner = nullptr;
end.id = 0;
end.status = NetStatus::PENDING;
Util::Zero(end.token, 64);
end.nextSendId = 0;
end.nextRecvId = 0;
end.deltaDuration = 0.0f;
end.deltaRate = 1.0f / 60.0f;
end.timeout = 0.0f;
end.lastPing = 0.0f;
end.oldLatency = 0.0f;
end.latency = 0.0f;
end.queueSlot = 0;
return *this;
}
NetEnd &NetEnd::operator=(const NetEnd &end)
{
if (this == &end)
return *this;
owner = nullptr;
id = end.id;
name = end.name;
status = NetStatus::PENDING;
Util::Zero(token, 64);
nextSendId = 0;
sent = {};
nextRecvId = 0;
received = {};
endpoint = {};
deltaDuration = 0.0f;
deltaRate = 1.0f / 60.0f;
timeout = 0.0f;
lastPing = 0.0f;
oldLatency = 0.0f;
latency = 0.0f;
queueSlot = 0;
return *this;
}
UInt_64 NetEnd::GetId() const
{
return id;
}
Str_8 NetEnd::GetName() const
{
return name;
}
NetStatus NetEnd::GetStatus() const
{
return status;
}
UInt_64 NetEnd::GetNextSendId() const
{
return nextSendId;
}
void NetEnd::Send(const bool deltaLocked, const UInt_64 encId, const bool ensure, const UInt_64 sysId,
const UInt_64 opId, const Serializer<UInt_64> &payload)
{
if (!owner || !owner->GetOwner() || (deltaLocked && deltaDuration < deltaRate))
return;
EHC *ehc = owner->GetOwner();
NetEnc *enc = ehc->GetEncryption(encId);
if (!enc)
{
EHS_LOG_INT(LogType::WARN, 0, "Encryption with the Id, \"" + Str_8::FromNum(encId) + "\", does not exist.");
return;
}
Header header = {
EHC::GetVersion(),
encId,
enc->GetVersion(),
GetId(),
NetChannelType::SERVER,
GetVersion(),
nextSendId++,
1,
0,
ensure,
"",
sysId,
opId
};
Util::Copy(header.token, token, 64);
if ((ehc->GetLocalEndpoint().version == IP::V6 && payload.Size() > EHC_IPV6_PAYLOAD) ||
(ehc->GetLocalEndpoint().version == IP::V4 && payload.Size() > EHC_IPV4_PAYLOAD))
{
NetFrag frags = FragmentData(header, payload);
for (UInt_64 i = 0; i < frags.Size(); ++i)
{
Header newHeader = frags.GetHeader();
newHeader.fragment = i;
Send(newHeader, frags[i]);
}
}
else
{
Send(header, payload);
}
}
void NetEnd::Send(const bool deltaLocked, const Str_8 &encName, const bool ensure, const Str_8& sysName,
const Str_8& opName, const Serializer<>& payload)
{
Send(deltaLocked, encName.Hash_64(), ensure, sysName.Hash_64(), opName.Hash_64(), payload);
}
UInt_64 NetEnd::GetNextRecvId() const
{
return nextRecvId;
}
Endpoint NetEnd::GetEndpoint() const
{
return endpoint;
}
float NetEnd::GetDeltaRate() const
{
return deltaRate;
}
float NetEnd::GetTimeout() const
{
return timeout;
}
float NetEnd::GetLastPing() const
{
return lastPing;
}
float NetEnd::GetLatency() const
{
return oldLatency;
}
UInt_64 NetEnd::GetQueueSlot() const
{
return queueSlot;
}
void NetEnd::Poll(const float delta)
{
SortReceived();
if (deltaDuration >= deltaRate)
deltaDuration = Math::Mod(deltaDuration, deltaRate);
deltaDuration += delta;
timeout += delta;
latency += delta;
if (sent.Size())
{
for (UInt_64 i = 0; i < sent.Size(); ++i)
{
sent[i].lastResend += delta;
if (sent[i].lastResend >= owner->GetResendRate())
{
EHC *ehc = owner->GetOwner();
Serializer result(Endianness::LE);
result.Write(sent[i].header);
result.WriteSer(sent[i].payload);
if (sent[i].header.encId)
{
NetEnc *enc = ehc->GetEncryption(sent[i].header.encId);
if (!enc)
{
EHS_LOG_INT(LogType::WARN, 0, "The network encryption with the hash id " +
Str_8::FromNum(sent[i].header.encId) + ", does not exist.");
continue;
}
enc->Encrypt(&result[sizeof(bool)], result.Size() - sizeof(bool));
}
ehc->udp.Send(endpoint, result, result.Size());
sent[i].lastResend = Math::Mod(sent[i].lastResend, owner->GetResendRate());
}
}
}
lastPing += delta;
if (lastPing >= 1.0f)
Ping(delta);
EHS_LOG_SUCCESS();
}
void NetEnd::SetStatus(const NetStatus newStatus)
{
status = newStatus;
}
void NetEnd::RemoveInsurance(const UInt_64 msgId, const UInt_64 fragment)
{
for (UInt_64 i = 0; i < sent.Size(); ++i)
{
if (sent[i].header.id == msgId && sent[i].header.fragment == fragment)
{
sent.Remove(i);
break;
}
}
timeout = 0.0f;
}
void NetEnd::AddReceived(const Header& header, const Serializer<>& payload)
{
NetFrag* frags = nullptr;
for (UInt_64 i = 0; i < received.Size(); ++i)
{
if (received[i].GetHeader().id == header.id)
{
if (received[i][header.fragment].Size())
return;
frags = &received[i];
break;
}
}
if (header.id > nextRecvId)
nextRecvId = header.id + 1;
if (frags)
(*frags)[header.fragment] = payload;
else
received.Push({header, payload});
timeout = 0.0f;
}
Vector<NetFrag>* NetEnd::GetReceived()
{
return &received;
}
void NetEnd::SetDeltaRate(const float newDeltaRate)
{
deltaRate = newDeltaRate;
}
void NetEnd::Ping(const float delta)
{
Serializer payload(Endianness::LE);
payload.Write(delta);
Send(false, true, false, "Internal", "Ping", payload);
lastPing = 0.0f;
latency = 0.0f;
}
void NetEnd::SendLatency()
{
oldLatency = latency * 1000;
Serializer sPayload(Endianness::LE);
sPayload.Write(oldLatency);
Send(false, true, false, "Internal", "Latency", sPayload);
latency = 0.0f;
timeout = 0.0f;
}
void NetEnd::SetLatency(const float newLatency)
{
oldLatency = newLatency;
}
void NetEnd::SetQueueSlot(const UInt_64 slot)
{
queueSlot = slot;
}
NetFrag NetEnd::FragmentData(const Header& header, const Serializer<>& data)
{
NetFrag result;
EHC *ehc = owner->GetOwner();
if (ehc->GetLocalEndpoint().version == IP::V6)
{
UInt_64 frags = data.Size() / EHC_IPV6_PAYLOAD;
if (data.Size() % EHC_IPV6_PAYLOAD)
++frags;
result = NetFrag(header, frags);
UInt_64 size = EHC_IPV6_PAYLOAD;
for (UInt_64 i = 0; i < result.Size(); ++i)
{
size = EHC_IPV6_PAYLOAD;
if (i == result.Size() - 1)
size = data.Size() % EHC_IPV6_PAYLOAD;
result[i] = {data.GetEndianness(), &data[i * EHC_IPV6_PAYLOAD], size};
}
}
else if (ehc->GetLocalEndpoint().version == IP::V4)
{
UInt_64 frags = data.Size() / EHC_IPV4_PAYLOAD;
if (data.Size() % EHC_IPV4_PAYLOAD)
++frags;
result = NetFrag(header, frags);
UInt_64 size = EHC_IPV4_PAYLOAD;
for (UInt_64 i = 0; i < result.Size(); ++i)
{
size = EHC_IPV4_PAYLOAD;
if (i == result.Size() - 1)
size = data.Size() % EHC_IPV4_PAYLOAD;
result[i] = {data.GetEndianness(), &data[i * EHC_IPV4_PAYLOAD], size};
}
}
return result;
}
void NetEnd::Send(const Header& header, const Serializer<UInt_64>& payload)
{
EHC *ehc = owner->GetOwner();
Serializer result(Endianness::LE);
result.Write(header);
result.WriteSer(payload);
if (header.encId)
{
NetEnc *enc = ehc->GetEncryption(header.encId);
if (!enc)
{
EHS_LOG_INT(LogType::WARN, 0, "The network encryption with the hash id " +
Str_8::FromNum(header.encId) + ", does not exist.");
return;
}
enc->Encrypt(&result[sizeof(bool)], result.Size() - sizeof(bool));
}
if (header.ensure)
sent.Push({header, payload});
ehc->udp.Send(endpoint, result, result.Size());
}
bool NetEnd::SortingNeeded() const
{
UInt_64 lastPacket = 0;
for (UInt_64 i = 0; i < received.Size(); ++i)
{
if (received[i].GetHeader().id < lastPacket)
return true;
else
lastPacket = received[i].GetHeader().id;
}
return false;
}
void NetEnd::SortReceived()
{
if (!SortingNeeded())
return;
Vector<NetFrag> sorted(0, received.Stride());
for (UInt_64 a = 0; a < received.Size(); ++a)
{
if (sorted.Size())
{
for (UInt_64 b = sorted.Size(); b; --b)
{
if (received[a].GetHeader().id > sorted[b - 1].GetHeader().id)
{
if (b == sorted.Size())
sorted.Push(received[a]);
else
sorted.Insert(b, received[a]);
break;
}
else
{
sorted.Insert(b - 1, received[a]);
break;
}
}
}
else
{
sorted.Push(received[a]);
}
}
received = sorted;
}
}

View File

@ -0,0 +1,122 @@
#include "ehs/io/socket/ehc/NetFrag.h"
namespace ehs
{
NetFrag::~NetFrag()
{
delete[] data;
}
NetFrag::NetFrag()
: data(nullptr), size(0)
{
}
NetFrag::NetFrag(const Header &header, const Serializer<UInt_64> &payload)
: header(header), data(new Serializer<UInt_64>[header.fragmentCount]), size(header.fragmentCount)
{
this->header.fragment = 0;
data[header.fragment] = payload;
}
NetFrag::NetFrag(const Header &header, const UInt_64 size)
: header(header), data(new Serializer<UInt_64>[size]), size(size)
{
this->header.fragmentCount = size;
this->header.fragment = 0;
}
NetFrag::NetFrag(NetFrag &&frags) noexcept
: header(frags.header), data(frags.data), size(frags.size)
{
frags.header = {};
frags.data = nullptr;
frags.size = 0;
}
NetFrag::NetFrag(const NetFrag &frags)
: header(frags.header), data(new Serializer<UInt_64>[frags.size]), size(frags.size)
{
for (UInt_64 i = 0; i < size; ++i)
data[i] = frags.data[i];
}
NetFrag &NetFrag::operator=(NetFrag &&frags) noexcept
{
if (this == &frags)
return *this;
header = frags.header;
delete[] data;
data = frags.data;
size = frags.size;
frags.header = {};
frags.data = nullptr;
frags.size = 0;
return *this;
}
NetFrag &NetFrag::operator=(const NetFrag &frags)
{
if (this == &frags)
return *this;
header = frags.header;
delete[] data;
data = new Serializer<UInt_64>[frags.size];
for (UInt_64 i = 0; i < frags.size; ++i)
data[i] = frags.data[i];
size = frags.size;
return *this;
}
NetFrag::operator Serializer<UInt_64> *() const
{
return data;
}
Header NetFrag::GetHeader() const
{
return header;
}
UInt_64 NetFrag::Size() const
{
return size;
}
bool NetFrag::IsComplete() const
{
for (UInt_64 i = 0; i < size; ++i)
if (!data[i].Size())
return false;
return true;
}
Packet NetFrag::Combine() const
{
UInt_64 rSize = 0;
for (UInt_64 i = 0; i < size; ++i)
rSize += data[i].Size();
Packet result =
{
header,
{Endianness::LE, rSize}
};
result.header.fragmentCount = 0;
for (UInt_64 i = 0; i < size; ++i)
result.payload.WriteSer(data[i]);
result.payload.SetOffset(0);
return result;
}
}

View File

@ -0,0 +1,65 @@
#include "ehs/io/socket/ehc/NetOp.h"
#include "ehs/io/socket/EHC.h"
#include "ehs/io/socket/ehc/NetEnd.h"
namespace ehs
{
NetOp::NetOp()
: id(0)
{
}
NetOp::NetOp(Str_8 name)
: id(name.Hash_64()), name((Str_8 &&)name)
{
}
NetOp::NetOp(NetOp&& op) noexcept
: id(op.id), name((Str_8 &&)op.name)
{
op.id = 0;
}
NetOp::NetOp(const NetOp &op)
: id(op.id), name(op.name)
{
}
NetOp& NetOp::operator=(NetOp&& op) noexcept
{
if (this == &op)
return *this;
id = op.id;
name = (Str_8 &&)op.name;
op.id = 0;
return *this;
}
NetOp &NetOp::operator=(const NetOp &op)
{
if (this == &op)
return *this;
id = op.id;
name = op.name;
return *this;
}
UInt_64 NetOp::GetId() const
{
return id;
}
Str_8 NetOp::GetName() const
{
return name;
}
void NetOp::Execute(NetChannel *channel, NetEnd *endpoint, NetSys *sys, Serializer<UInt_64> &payload)
{
}
}

View File

@ -0,0 +1,602 @@
#include "ehs/io/socket/ehc/NetServerCh.h"
#include "ehs/io/socket/ehc/NetEnd.h"
#include "ehs/io/socket/ehc/NetSys.h"
#include "ehs/io/socket/EHC.h"
#include "ehs/PRNG.h"
namespace ehs
{
NetServerCh::~NetServerCh()
{
Shutdown();
}
NetServerCh::NetServerCh()
: maxEndpoints(0)
{
}
NetServerCh::NetServerCh(Str_8 name, const Version &version, const UInt_64 maxEndpoints)
: NetChannel((Str_8 &&)name, version), maxEndpoints(maxEndpoints)
{
}
NetServerCh::NetServerCh(NetServerCh &&server) noexcept
: NetChannel((NetChannel &&)server), endpoints((Vector<NetEnd *> &&)server.endpoints), maxEndpoints(server.maxEndpoints)
{
for (UInt_64 i = 0; i < endpoints.Size(); i++)
endpoints[i]->owner = this;
}
NetServerCh::NetServerCh(const NetServerCh &server)
: NetChannel(server), maxEndpoints(server.maxEndpoints)
{
}
NetServerCh &NetServerCh::operator=(NetServerCh &&server) noexcept
{
if (this == &server)
return *this;
NetChannel::operator=((NetChannel &&)server);
Shutdown();
endpoints = (Vector<NetEnd *> &&)server.endpoints;
for (UInt_64 i = 0; i < endpoints.Size(); i++)
endpoints[i]->owner = this;
maxEndpoints = server.maxEndpoints;
server.maxEndpoints = 0;
return *this;
}
NetServerCh &NetServerCh::operator=(const NetServerCh &server)
{
if (this == &server)
return *this;
NetChannel::operator=(server);
Shutdown();
endpoints = {};
maxEndpoints = server.maxEndpoints;
return *this;
}
bool NetServerCh::OnEndpointConnect(NetEnd *endpoint, Serializer<UInt_64> payload)
{
return true;
}
Serializer<UInt_64> NetServerCh::OnEndpointAccepted(NetEnd *endpoint)
{
return {};
}
void NetServerCh::OnEndpointDisconnect(NetEnd *endpoint, Serializer<UInt_64> payload)
{
}
void NetServerCh::OnEndpointTimeout(NetEnd *endpoint)
{
}
void NetServerCh::OnEndpointActive(NetEnd *endpoint)
{
}
Serializer<UInt_64> NetServerCh::OnShutdown()
{
return {};
}
Serializer<UInt_64> OnShutdown()
{
return {};
}
void NetServerCh::Broadcast(const NetStatus endStatus, const bool deltaLocked, const UInt_64 encHashId,
const bool ensure, const UInt_64 sysHashId, const UInt_64 opHashId, const Serializer<UInt_64> &payload)
{
if (!GetOwner()->udp.IsValid())
return;
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
if (endpoints[i]->GetStatus() == endStatus)
endpoints[i]->Send(deltaLocked, encHashId, ensure, sysHashId, opHashId, payload);
}
void NetServerCh::Broadcast(const NetStatus endStatus, const bool deltaLocked, const Str_8 &encId, const bool ensure,
const Str_8 &sysId, const Str_8 &opId,
const Serializer<UInt_64> &payload)
{
Broadcast(endStatus, deltaLocked, encId.Hash_64(), ensure, sysId.Hash_64(), opId.Hash_64(), payload);
}
bool NetServerCh::HasEndpoint(const NetStatus endStatus, const Char_8 token[64]) const
{
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
{
if (endpoints[i]->GetStatus() != endStatus)
continue;
if (Util::Compare(endpoints[i]->token, token, 64))
return true;
}
return false;
}
bool NetServerCh::HasEndpoint(const NetStatus endStatus, const UInt_64 hashName) const
{
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
{
if (endpoints[i]->GetStatus() != endStatus)
continue;
if (endpoints[i]->GetId() == hashName)
return true;
}
return false;
}
bool NetServerCh::HasEndpoint(const NetStatus endStatus, const Str_8 &id) const
{
return HasEndpoint(endStatus, id.Hash_64());
}
bool NetServerCh::HasEndpoint(const Char_8 token[64]) const
{
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
if (Util::Compare(endpoints[i]->token, token, 64))
return true;
return false;
}
bool NetServerCh::HasEndpoint(const UInt_64 hashName) const
{
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
if (endpoints[i]->GetId() == hashName)
return true;
return false;
}
bool NetServerCh::HasEndpoint(const Str_8 &id) const
{
return HasEndpoint(id.Hash_64());
}
bool NetServerCh::HasEndpoint(const Endpoint &endpoint) const
{
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
if (endpoints[i]->GetEndpoint().address == endpoint.address && endpoints[i]->GetEndpoint().port == endpoint.port)
return true;
return false;
}
NetEnd* NetServerCh::GetEndpoint(const NetStatus endStatus, const Char_8 token[64]) const
{
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
{
if (endpoints[i]->GetStatus() != endStatus)
continue;
if (Util::Compare(endpoints[i]->token, token, 64))
return endpoints[i];
}
return nullptr;
}
NetEnd *NetServerCh::GetEndpoint(const NetStatus endStatus, const UInt_64 hashName) const
{
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
{
if (endpoints[i]->GetStatus() != endStatus)
continue;
if (endpoints[i]->GetId() == hashName)
return endpoints[i];
}
return nullptr;
}
NetEnd *NetServerCh::GetEndpoint(const NetStatus endStatus, const Str_8 &id) const
{
return GetEndpoint(endStatus, id.Hash_64());
}
NetEnd *NetServerCh::GetEndpoint(const Char_8 token[64]) const
{
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
if (Util::Compare(endpoints[i]->token, token, 64))
return endpoints[i];
return nullptr;
}
NetEnd *NetServerCh::GetEndpoint(const UInt_64 hashName) const
{
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
if (endpoints[i]->GetId() == hashName)
return endpoints[i];
return nullptr;
}
NetEnd *NetServerCh::GetEndpoint(const Str_8 &id) const
{
return GetEndpoint(id.Hash_64());
}
NetEnd *NetServerCh::GetEndpoint(const Endpoint &endpoint) const
{
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
if (endpoints[i]->GetEndpoint().address == endpoint.address && endpoints[i]->GetEndpoint().port == endpoint.port)
return endpoints[i];
return nullptr;
}
Array<NetEnd *> NetServerCh::GetEndpoints(const NetStatus endStatus)
{
Array<NetEnd*> result(endpoints.Size());
UInt_64 count = 0;
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
if (endpoints[i]->GetStatus() == endStatus)
result[count++] = endpoints[i];
result.Resize(count);
return result;
}
UInt_64 NetServerCh::GetEndpointsCount(const NetStatus endStatus)
{
UInt_64 count = 0;
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
if (endpoints[i]->GetStatus() == endStatus)
++count;
return count;
}
UInt_64 NetServerCh::GetMaxEndpoints() const
{
return maxEndpoints;
}
void NetServerCh::Process(const float &delta, const Endpoint &endpoint, const Header &header, Serializer<UInt_64> &payload)
{
if (header.channelVer != GetVersion())
return;
if (!header.ensure && !header.token[0] && header.systemId == internalSys && header.opId == connectOp)
{
NetEnd* end = new NetEnd(payload.ReadStr(), endpoint);
end->owner = this;
GenerateToken(end->token);
end->SetStatus(NetStatus::PENDING);
Serializer sPayload(Endianness::LE);
if (!OnEndpointConnect(end, {Endianness::LE, &payload[payload.GetOffset()], payload.Size() - payload.GetOffset()}))
{
sPayload.WriteStr<Char_8, UInt_64>("Connection rejected.");
end->Send(false, true, false, internalSys, rejectedOp, sPayload);
return;
}
endpoints.Push(end);
UInt_64 active = GetEndpointsCount(NetStatus::ACTIVE);
if (maxEndpoints && active >= maxEndpoints)
{
end->SetStatus(NetStatus::QUEUED);
UpdateQueue(active);
sPayload.Write(NetStatus::QUEUED);
sPayload.Write(end->GetQueueSlot());
}
else
{
end->SetStatus(NetStatus::ACTIVE);
OnEndpointActive(end);
sPayload.Write(NetStatus::ACTIVE);
sPayload.Write(0);
}
sPayload.WriteSer(OnEndpointAccepted(end));
end->Send(false, 0, false, internalSys, connectedOp, sPayload);
}
else if (!header.ensure && header.token[0] && header.systemId == internalSys && header.opId == disconnectOp)
{
NetEnd* end = GetEndpoint(header.token);
if (!end)
return;
end->Send(false, 0, false, internalSys, disconnectedOp, {});
OnEndpointDisconnect(end, {Endianness::LE, &payload[payload.GetOffset()], payload.Size() - payload.GetOffset()});
RemoveEndpoint(end->token);
UpdateQueue();
}
else if (!header.ensure && header.token[0] && header.systemId == internalSys && header.opId == pongOp)
{
NetEnd* end = GetEndpoint(header.token);
if (!end)
return;
end->SetDeltaRate(payload.Read<float>());
end->SendLatency();
}
else if (!header.ensure && header.token[0] && header.systemId == internalSys && header.opId == receivedOp)
{
NetEnd* end = GetEndpoint(header.token);
if (!end)
return;
const UInt_64 msgId = payload.Read<UInt_64>();
const UInt_64 fragment = payload.Read<UInt_64>();
end->RemoveInsurance(msgId, fragment);
}
else if (header.token[0])
{
NetEnd* end = GetEndpoint(header.token);
if (!end)
return;
if (IsDropPacketsEnabled() && !header.ensure && header.id < end->GetNextRecvId())
{
EHS_LOG_INT(LogType::INFO, 6, "Old packet intentionally dropped.");
return;
}
if (header.ensure)
{
Serializer sPayload(Endianness::LE);
sPayload.Write(header.id);
sPayload.Write(header.fragment);
end->Send(false, 0, false, internalSys, receivedOp, sPayload);
}
end->AddReceived(
header,
Serializer<>(Endianness::LE, &payload[payload.GetOffset()], payload.Size() - payload.GetOffset())
);
}
else
{
EHS_LOG_INT(LogType::INFO, 7, "Corrupted packet.");
}
}
void NetServerCh::GenerateToken(Char_8 in[64])
{
PRNG_u64 rng(CPU::GetTSC());
for (UInt_64 i = 0; i < 8; ++i)
{
do
((UInt_64*)in)[i] = rng.Generate();
while (!i && ((UInt_64*)in)[i] == 0);
}
if (HasEndpoint(in))
GenerateToken(in);
}
void NetServerCh::UpdateQueue(UInt_64 active)
{
UInt_64 slot = 0;
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
{
if (endpoints[i]->GetStatus() == NetStatus::QUEUED)
{
if (active < maxEndpoints)
{
endpoints[i]->SetStatus(NetStatus::ACTIVE);
endpoints[i]->SetQueueSlot(0);
Serializer payload(Endianness::LE);
payload.Write(NetStatus::ACTIVE);
payload.Write(0);
endpoints[i]->Send(false, true, false, internalSys, statusUpdateOp, payload);
OnEndpointActive(endpoints[i]);
++active;
}
else
{
if (endpoints[i]->GetQueueSlot() != slot)
{
Serializer payload(Endianness::LE);
payload.Write(NetStatus::QUEUED);
payload.Write(slot);
endpoints[i]->Send(false, true, false, internalSys, statusUpdateOp, payload);
endpoints[i]->SetQueueSlot(slot++);
}
else
{
++slot;
}
}
}
}
}
void NetServerCh::UpdateQueue()
{
UpdateQueue(GetEndpointsCount(NetStatus::ACTIVE));
}
bool NetServerCh::RemoveEndpoint(const Char_8 token[64])
{
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
{
if (Util::Compare(endpoints[i]->token, token, 64))
{
delete endpoints[i];
if (i != endpoints.Size() - 1)
endpoints.Swap(i, endpoints.End());
endpoints.Pop();
return true;
}
}
return false;
}
bool NetServerCh::RemoveEndpoint(const Endpoint &endpoint)
{
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
{
if (endpoints[i]->GetEndpoint().address == endpoint.address && endpoints[i]->GetEndpoint().port == endpoint.port)
{
delete endpoints[i];
if (i != endpoints.Size() - 1)
endpoints.Swap(i, endpoints.End());
endpoints.Pop();
return true;
}
}
return false;
}
bool NetServerCh::RemoveEndpoint(const NetEnd* const end)
{
for (UInt_64 i = 0; i < endpoints.Size(); ++i)
{
if (endpoints[i] == end)
{
delete endpoints[i];
if (i != endpoints.Size() - 1)
endpoints.Swap(i, endpoints.End());
endpoints.Pop();
return true;
}
}
return false;
}
void NetServerCh::Poll(const float &delta)
{
UInt_64 i = 0;
while (i < endpoints.Size())
{
endpoints[i]->Poll(delta);
if (endpoints[i]->GetStatus() == NetStatus::PENDING)
{
if (endpoints[i]->GetTimeout() >= GetMaxTimeout())
{
OnEndpointTimeout(endpoints[i]);
delete endpoints[i];
if (i != endpoints.Size() - 1)
endpoints.Swap(i, endpoints.End());
endpoints.Pop();
continue;
}
}
else
{
if (endpoints[i]->GetTimeout() >= GetMaxTimeout())
{
OnEndpointTimeout(endpoints[i]);
delete endpoints[i];
if (i != endpoints.Size() - 1)
endpoints.Swap(i, endpoints.End());
endpoints.Pop();
UpdateQueue();
continue;
}
Vector<NetFrag>* frags = endpoints[i]->GetReceived();
UInt_64 f = 0;
while (f < frags->Size())
{
if (!(*frags)[f].IsComplete())
{
++f;
continue;
}
Packet packet = (*frags)[f].Combine();
NetSys* sys = GetSystem(packet.header.systemId);
if (!sys)
{
++f;
continue;
}
sys->Execute(this, endpoints[i], packet.header.opId, packet.payload);
frags->Swap(f, frags->End());
frags->Pop();
}
}
++i;
}
}
void NetServerCh::Shutdown()
{
Serializer<UInt_64> payload = OnShutdown();
for (UInt_64 i = 0; i < endpoints.Size(); i++)
{
endpoints[i]->Send(false, 0, false, internalSys, disconnectOp, payload);
delete endpoints[i];
}
}
}

View File

@ -0,0 +1,106 @@
#include "ehs/io/socket/ehc/NetSys.h"
#include "ehs/io/socket/EHC.h"
#include "ehs/io/socket/ehc/NetEnd.h"
#include "ehs/io/socket/ehc/NetOp.h"
#include "ehs/io/socket/ehc/NetChannel.h"
namespace ehs
{
NetSys::~NetSys()
{
for (UInt_64 i = 0; i < ops.Size(); ++i)
delete ops[i];
ops.Clear();
}
NetSys::NetSys()
: id(0)
{
}
NetSys::NetSys(Str_8 name)
: id(name.Hash_64()), name((Str_8&&)name)
{
}
NetSys::NetSys(NetSys&& sys) noexcept
: id(sys.id), name((Str_8&&)sys.name), ops((Array<NetOp*>&&)sys.ops)
{
sys.id = 0;
}
NetSys::NetSys(const NetSys& sys)
: id(sys.id), name(sys.name)
{
}
NetSys& NetSys::operator=(NetSys&& sys) noexcept
{
if (this == &sys)
return *this;
id = sys.id;
name = (Str_8&&)sys.name;
ops = (Array<NetOp*>&&)sys.ops;
sys.id = 0;
return *this;
}
NetSys& NetSys::operator=(const NetSys& sys)
{
if (this == &sys)
return *this;
id = sys.id;
name = sys.name;
ops = Array<NetOp*>();
return *this;
}
UInt_64 NetSys::GetId() const
{
return id;
}
Str_8 NetSys::GetName() const
{
return name;
}
bool NetSys::HasOperation(const UInt_64 id) const
{
for (UInt_64 i = 0; i < ops.Size(); ++i)
if (ops[i]->GetId() == id)
return true;
return false;
}
bool NetSys::AddOperation(NetOp* op)
{
if (HasOperation(op->GetId()))
return false;
ops.Push(op);
return true;
}
void NetSys::Execute(NetChannel *channel, NetEnd *endpoint, const UInt_64 hashId, Serializer<UInt_64> &payload)
{
for (UInt_64 i = 0; i < ops.Size(); ++i)
{
if (ops[i]->GetId() == hashId)
{
ops[i]->Execute(channel, endpoint, this, payload);
return;
}
}
EHS_LOG_INT(LogType::INFO, 0, "System not found.");
}
}

View File

@ -0,0 +1,44 @@
#include "ehs/io/socket/ehc/NetUtils.h"
namespace ehs
{
void WriteHeader(const Header &header, Serializer<UInt_64> &data)
{
data.WriteVersion(header.version);
data.Write(header.encId);
data.WriteVersion(header.encVer);
data.Write(header.channelId);
data.Write(header.channelType);
data.WriteVersion(header.channelVer);
data.Write(header.id);
data.Write(header.fragmentCount);
data.Write(header.fragment);
data.Write(header.ensure);
data.WriteArray(header.token, 64);
data.Write(header.systemId);
data.Write(header.opId);
}
Header ReadHeader(Serializer<UInt_64> &data)
{
Header header = {};
header.version = data.ReadVersion();
header.encId = data.Read<UInt_64>();
header.encVer = data.ReadVersion();
header.channelId = data.Read<UInt_64>();
header.channelType = data.Read<NetChannelType>();
header.channelVer = data.ReadVersion();
header.id = data.Read<UInt_64>();
header.fragmentCount = data.Read<UInt_64>();
header.fragment = data.Read<UInt_64>();
header.ensure = data.Read<bool>();
UInt_64 tokenSize = sizeof(header.token) / sizeof(Char_8);
data.ReadArray<Char_8, UInt_64>(header.token, &tokenSize);
header.systemId = data.Read<UInt_64>();
header.opId = data.Read<UInt_64>();
return header;
}
}

View File

@ -18,7 +18,7 @@ namespace ehs
} }
Spotify::Spotify(Str_8 clientId, Str_8 secret, Str_8 redURI, Array<Str_8> scopes, const bool forceVerify) Spotify::Spotify(Str_8 clientId, Str_8 secret, Str_8 redURI, Array<Str_8> scopes, const bool forceVerify)
: client(AddrType::IPV4), clientId((Str_8 &&)clientId), secret((Str_8 &&)secret), redURI((Str_8 &&)redURI), : client(IP::V4), clientId((Str_8 &&)clientId), secret((Str_8 &&)secret), redURI((Str_8 &&)redURI),
scopes((Array<Str_8> &&)scopes), forceVerify(forceVerify) scopes((Array<Str_8> &&)scopes), forceVerify(forceVerify)
{ {
} }
@ -41,7 +41,7 @@ namespace ehs
"&response_type=code&show_dialog=" + (forceVerify ? "true" : "false") + "&scope=" + "&response_type=code&show_dialog=" + (forceVerify ? "true" : "false") + "&scope=" +
scopesFinal; scopesFinal;
TCP server(AddrType::IPV4); TCP server(IP::V4);
server.Initialize(); server.Initialize();
server.Bind("", 65534); server.Bind("", 65534);
server.Listen(); server.Listen();
@ -73,7 +73,7 @@ namespace ehs
server.Release(); server.Release();
SSL accounts(AddrType::IPV4); SSL accounts(IP::V4);
accounts.Initialize(); accounts.Initialize();
accounts.Connect("accounts.spotify.com", SSL::HTTPS_Port); accounts.Connect("accounts.spotify.com", SSL::HTTPS_Port);
@ -588,7 +588,7 @@ namespace ehs
bool Spotify::ReAuthorize() bool Spotify::ReAuthorize()
{ {
SSL accounts(AddrType::IPV4); SSL accounts(IP::V4);
accounts.Initialize(); accounts.Initialize();
accounts.Connect("accounts.spotify.com", SSL::HTTPS_Port); accounts.Connect("accounts.spotify.com", SSL::HTTPS_Port);

View File

@ -16,7 +16,7 @@ namespace ehs
} }
Twitch::Twitch(const Str_8& clientId, const Str_8& secret, const Str_8& redURI, const Array<Str_8>& scopes, const bool forceVerify) Twitch::Twitch(const Str_8& clientId, const Str_8& secret, const Str_8& redURI, const Array<Str_8>& scopes, const bool forceVerify)
: client(AddrType::IPV4), clientId(clientId), secret(secret), redURI(redURI), scopes(scopes), forceVerify(forceVerify) : client(IP::V4), clientId(clientId), secret(secret), redURI(redURI), scopes(scopes), forceVerify(forceVerify)
{ {
} }
@ -38,7 +38,7 @@ namespace ehs
"&response_type=code&force_verify=" + (forceVerify ? "true" : "false") + "&scope=" + "&response_type=code&force_verify=" + (forceVerify ? "true" : "false") + "&scope=" +
scopesFinal; scopesFinal;
TCP server(AddrType::IPV4); TCP server(IP::V4);
server.Bind("", 65535); server.Bind("", 65535);
server.Listen(); server.Listen();

View File

@ -53,7 +53,7 @@ namespace ehs
if (initialized) if (initialized)
return; return;
client = TCP(ehs::AddrType::IPV4); client = TCP(ehs::IP::V4);
client.Connect(DNS::Resolve("irc.chat.twitch.tv"), 6667); client.Connect(DNS::Resolve("irc.chat.twitch.tv"), 6667);
client.SetBlocking(false); client.SetBlocking(false);

View File

@ -43,4 +43,9 @@ namespace ehs
void CPU::GetBrand(Char_8* input) void CPU::GetBrand(Char_8* input)
{ {
} }
UInt_8 CPU::GetCacheLineSize()
{
return 0;
}
} }

View File

@ -7,6 +7,7 @@ global _ZN3ehs3CPU19GetExtFeatureBits_1Ev
global _ZN3ehs3CPU19GetExtFeatureBits_2Ev global _ZN3ehs3CPU19GetExtFeatureBits_2Ev
global _ZN3ehs3CPU19GetExtFeatureBits_3Ev global _ZN3ehs3CPU19GetExtFeatureBits_3Ev
global _ZN3ehs3CPU8GetBrandEPc global _ZN3ehs3CPU8GetBrandEPc
global _ZN3ehs3CPU16GetCacheLineSizeEv
section .text section .text
_ZN3ehs3CPU6RDTSCPEPNS_3TSCE: _ZN3ehs3CPU6RDTSCPEPNS_3TSCE:
@ -129,4 +130,17 @@ section .text
POP RBX POP RBX
RET
_ZN3ehs3CPU16GetCacheLineSizeEv:
PUSH RBX
MOV EAX, 0x80000006
CPUID
XOR EAX, EAX
MOV AL, CL
POP RBX
RET RET

View File

@ -6,6 +6,7 @@ global ?GetExtFeatureBits_1@CPU@ehs@@SAIXZ
global ?GetExtFeatureBits_2@CPU@ehs@@SAKXZ global ?GetExtFeatureBits_2@CPU@ehs@@SAKXZ
global ?GetExtFeatureBits_3@CPU@ehs@@SAKXZ global ?GetExtFeatureBits_3@CPU@ehs@@SAKXZ
global ?GetBrand@CPU@ehs@@SAXPEAD@Z global ?GetBrand@CPU@ehs@@SAXPEAD@Z
global ?GetCacheLineSize@CPU@ehs@@SAEXZ
section .text section .text
?GetManufacturer@CPU@ehs@@SAXPEAD@Z: ?GetManufacturer@CPU@ehs@@SAXPEAD@Z:
@ -124,4 +125,17 @@ section .text
POP RBX POP RBX
RET
?GetCacheLineSize@CPU@ehs@@SAEXZ:
PUSH RBX
MOV EAX, 0x80000006
CPUID
XOR EAX, EAX
MOV AL, CL
POP RBX
RET RET