90 Commits

Author SHA1 Message Date
5e4f4e27f6 Merge pull request 'Fixed Button dll input/output.' (#21) from NetChannels into main
Some checks failed
Build & Release / Windows-AMD64-Build (push) Failing after 2m8s
Build & Release / Linux-AARCH64-Build (push) Failing after 13s
Build & Release / Linux-AMD64-Build (push) Successful in 7m37s
Reviewed-on: #21
2025-08-13 21:35:56 -07:00
7db8486f1e Fixed Button dll input/output. 2025-08-13 21:31:57 -07:00
a6eb7f6e97 Merge pull request 'NetChannels' (#20) from NetChannels into main
Reviewed-on: #20
2025-08-13 19:32:54 -07:00
46184df89c Fixed the logger. 2025-07-27 23:50:13 -07:00
73f7ec1a8d Optimized Request and Response classes. 2025-06-01 22:16:32 -07:00
135f855309 Merge remote-tracking branch 'origin/NetChannels' into NetChannels
# Conflicts:
#	src/io/socket/SSL.cpp
2025-05-22 23:56:22 -07:00
159428ea76 Backup. 2025-05-22 23:56:00 -07:00
c23cbc275f Backup. 2025-05-22 17:34:09 -07:00
fbd8464043 Fixed SSL and TCP Bind. 2025-05-22 07:05:11 -07:00
f52afe9c92 Fixed audio destruction and construction. 2025-05-18 23:40:09 -07:00
61fb586f86 Added frequency counter to AARCH64.
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-05-17 17:37:12 -07:00
c19c6269aa Fixed CI/CD for Raspberry Pi.
All checks were successful
Build & Release / Windows-AMD64-Build (push) Successful in 4m17s
Build & Release / Linux-AMD64-Build (push) Successful in 7m12s
Build & Release / Linux-AARCH64-Build (push) Successful in 20m56s
2025-05-16 21:44:24 -07:00
0b1a0c9689 Fixed CI/CD.
Some checks failed
Build & Release / Linux-AARCH64-Build (push) Failing after 7s
Build & Release / Windows-AMD64-Build (push) Successful in 4m15s
Build & Release / Linux-AMD64-Build (push) Successful in 7m14s
2025-05-16 21:35:27 -07:00
83bb62456a Updated README.
Some checks failed
Build & Release / Linux-AARCH64-Build (push) Failing after 2s
Build & Release / Windows-AMD64-Build (push) Successful in 4m25s
Build & Release / Linux-AMD64-Build (push) Successful in 7m31s
2025-05-16 21:20:00 -07:00
f1d1a1cbb1 Updated README.
Some checks failed
Build & Release / Linux-AMD64-Build (push) Failing after 8s
Build & Release / Linux-AARCH64-Build (push) Failing after 14s
Build & Release / Windows-AMD64-Build (push) Successful in 5m9s
2025-05-16 21:18:34 -07:00
8bf4f6336f Fixed CMAKE to remove ALSA dependency. 2025-05-17 03:51:20 +01:00
25e40560b7 Updated README. 2025-05-11 19:46:25 -07:00
bce48fe121 Fixed "System::OpenURI". Added SHA256. Added URI safe Base64 methods.
All checks were successful
Build & Release / Windows-AMD64-Build (push) Successful in 6m9s
Build & Release / Linux-AMD64-Build (push) Successful in 15m26s
Build & Release / Linux-AARCH64-Build (push) Successful in 45m54s
2025-05-11 19:43:50 -07:00
2cb01a7c65 Fixed Windows CI/CD and fixed AVX on AARCH64 again.
All checks were successful
Build & Release / Windows-AMD64-Build (push) Successful in 5m35s
Build & Release / Linux-AMD64-Build (push) Successful in 15m24s
Build & Release / Linux-AARCH64-Build (push) Successful in 45m55s
2025-05-09 19:43:05 -07:00
3025b76bec Fixed AVX undefined symbols on AARCH64 and removed AVX from ehs::Util::Compare.
Some checks failed
Build & Release / Windows-AMD64-Build (push) Failing after 31s
Build & Release / Linux-AMD64-Build (push) Successful in 15m25s
Build & Release / Linux-AARCH64-Build (push) Failing after 22m49s
2025-05-09 19:17:09 -07:00
0cec9789b1 Cached CPU features, added AVX2, and AVX512.
Some checks failed
Build & Release / Windows-AMD64-Build (push) Failing after 4m42s
Build & Release / Linux-AMD64-Build (push) Successful in 15m40s
Build & Release / Linux-AARCH64-Build (push) Failing after 45m49s
2025-05-08 22:41:05 -07:00
63eba0d2db Fixed Str constructor not to check for a null-terminator if given a size of zero. 2025-05-02 07:01:40 -07:00
c5b281d73c Added String<T, N>.ParseArgs(). 2025-04-14 13:40:00 -07:00
8d28f3547c Merge remote-tracking branch 'origin/NetChannels' into NetChannels 2025-04-14 00:27:26 -07:00
a7f09382fd Fixed vector. 2025-04-14 00:22:10 -07:00
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 5m1s
Build & Release / Linux-AMD64-Build (push) Successful in 14m41s
Build & Release / Linux-AARCH64-Build (push) Successful in 43m40s
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
Some checks failed
Build & Release / Windows-AMD64-Build (push) Failing after 21s
Build & Release / Linux-AARCH64-Build (push) Successful in 43m31s
Build & Release / Linux-AMD64-Build (push) Successful in 15m15s
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
3343f8ca28 Fixed workflow.
All checks were successful
Build & Release / Windows-AMD64-Build (push) Successful in 7m5s
Build & Release / Linux-AMD64-Build (push) Successful in 12m7s
Build & Release / Linux-AARCH64-Build (push) Successful in 37m1s
2024-10-05 19:05:30 -07:00
3b8159b75f Fixed workflow.
Some checks failed
Build & Release / Windows-AMD64-Build (push) Failing after 6m8s
Build & Release / Linux-AMD64-Build (push) Failing after 17m38s
Build & Release / Linux-AARCH64-Build (push) Failing after 36m37s
2024-10-01 21:27:31 -07:00
62e7580d3a Added install dependency for pipewire.
Some checks failed
Build & Release / Linux-AARCH64-Build (push) Failing after 7s
Build & Release / Windows-AMD64-Build (push) Failing after 5m13s
Build & Release / Linux-AMD64-Build (push) Failing after 17m37s
2024-10-01 21:00:00 -07:00
11170006e9 Fixed workflow for Windows.
Some checks failed
Build & Release / Linux-AMD64-Build (push) Failing after 8s
Build & Release / Linux-AARCH64-Build (push) Failing after 14s
Build & Release / Windows-AMD64-Build (push) Failing after 5m15s
2024-10-01 20:19:38 -07:00
37e3ca9360 Fixed workflow for Windows.
Some checks failed
Build & Release / Linux-AMD64-Build (push) Failing after 8s
Build & Release / Linux-AARCH64-Build (push) Failing after 14s
Build & Release / Windows-AMD64-Build (push) Failing after 5m19s
2024-10-01 19:58:35 -07:00
daca00603a Fixed workflow for Windows.
Some checks failed
Build & Release / Linux-AMD64-Build (push) Failing after 8s
Build & Release / Linux-AARCH64-Build (push) Failing after 14s
Build & Release / Windows-AMD64-Build (push) Failing after 6m8s
2024-10-01 19:50:21 -07:00
1f5299ad1b Fixed Win32 audio.
Some checks failed
Build & Release / Linux-AMD64-Build (push) Failing after 8s
Build & Release / Linux-AARCH64-Build (push) Failing after 14s
Build & Release / Windows-AMD64-Build (push) Failing after 5m56s
2024-10-01 18:58:15 -07:00
dfa260b87c Backup. 2024-09-30 20:24:25 -07:00
fc8b771026 Added vcpkg.
Some checks failed
Build & Release / Linux-AMD64-Build (push) Failing after 8s
Build & Release / Linux-AARCH64-Build (push) Failing after 14s
Build & Release / Windows-AMD64-Build (push) Failing after 3m52s
2024-09-30 19:55:44 -07:00
0b77c074cf Added vcpkg.
Some checks failed
Build & Release / Linux-AMD64-Build (push) Failing after 8s
Build & Release / Linux-AARCH64-Build (push) Failing after 13s
Build & Release / Windows-AMD64-Build (push) Failing after 30s
2024-09-30 19:48:07 -07:00
5007a1047a Added vcpkg.
Some checks failed
Build & Release / Linux-AMD64-Build (push) Failing after 7s
Build & Release / Linux-AARCH64-Build (push) Failing after 14s
Build & Release / Windows-AMD64-Build (push) Failing after 30s
2024-09-30 19:22:22 -07:00
25860dc32a Added vcpkg. 2024-09-29 21:07:30 -07:00
d870599a60 Added vcpkg. 2024-09-29 21:06:30 -07:00
9bd3e1cd8d Added vcpkg. 2024-09-29 20:41:37 -07:00
681c0d09be Fixed Mat and CMakeLists 2024-09-16 16:18:49 -07:00
25762b0c29 Backup. 2024-09-03 05:37:23 -07:00
6afa08df82 Updated README.md again. 2024-08-15 19:41:05 -07:00
0a995a3f2c Updated README.md 2024-08-15 19:40:31 -07:00
c607b20bad Cleaned up and fixed some errors in the Json Parser. 2024-08-15 19:28:30 -07:00
2e705627ac Fixed CMakeLists.txt and System_LNX.cpp. 2024-08-15 17:33:04 -07:00
86a35fd668 Added System::GetDirDialog. 2024-08-04 02:09:10 -07:00
8d4420528a Optimized Button class. Added IsPressed and GetPressed methods. 2024-08-04 00:47:38 -07:00
3970b8d402 Fixed Mat and CMakeLists 2024-07-27 18:51:19 -07:00
6522994a1f Fixed Win32 keyboard input. 2024-07-27 10:12:10 -07:00
01a21032a5 Simplified Windows build again. 2024-07-24 15:37:45 -07:00
4d7e7596b6 Simplified Windows build. 2024-07-24 14:58:36 -07:00
139 changed files with 8864 additions and 2202 deletions

View File

@@ -8,6 +8,9 @@ on:
jobs: jobs:
Windows-AMD64-Build: Windows-AMD64-Build:
runs-on: windows-x86_64 runs-on: windows-x86_64
defaults:
run:
shell: powershell
steps: steps:
- name: Check out repository code - name: Check out repository code
uses: actions/checkout@v3 uses: actions/checkout@v3
@@ -19,8 +22,9 @@ jobs:
- name: Building/Compiling/Installing Project - name: Building/Compiling/Installing Project
run: | run: |
cd ${{ gitea.workspace }} cd ${{ gitea.workspace }}
cmake -A x64 -DCMAKE_BUILD_TYPE=Release --preset=default . mkdir build
cd build cd build
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 .
@@ -28,10 +32,14 @@ jobs:
run: | run: |
cd ${{ gitea.workspace }} cd ${{ gitea.workspace }}
mkdir bin mkdir bin
mv build/Release/EHS_Dyn.dll bin
mv build/Release/StrToHash.exe bin mv build/Release/StrToHash.exe bin
mv build/Release/zlib1.dll bin mv build/Release/zlib1.dll bin
mv build/Release/libcrypto-3-x64.dll bin
mv build/Release/libssl-3-x64.dll bin
mkdir lib mkdir lib
mv build/Release/EHS.lib lib mv build/Release/EHS_Stc.lib lib
mv build/Release/EHS_Dyn.lib lib
- name: Zipping Binaries - name: Zipping Binaries
run: | run: |
@@ -49,6 +57,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
@@ -58,7 +67,7 @@ jobs:
- name: Installing Dependencies - name: Installing Dependencies
run: | run: |
sudo pacman -S --noconfirm doxygen zip alsa-lib libxcb xcb-util-cursor sudo pacman -S --noconfirm doxygen ninja zip libxcb xcb-util-cursor pipewire
- name: Generating Documentation - name: Generating Documentation
run: | run: |
@@ -67,16 +76,18 @@ jobs:
- name: Building/Compiling/Installing Project - name: Building/Compiling/Installing Project
run: | run: |
cd ${{ gitea.workspace }} cd ${{ gitea.workspace }}
cmake -DCMAKE_BUILD_TYPE=Release -DLINUX_WINDOW_SYSTEM:STRING=XCB . cmake -G Ninja -DCMAKE_BUILD_TYPE=Release -DLINUX_WINDOW_SYSTEM:STRING=XCB .
cmake --build . --config Release cmake --build . --config Release
cmake --install . cmake --install .
- name: Creating Appropriate Directories - name: Creating Appropriate Directories
run: | run: |
cd ${{ gitea.workspace }}
mkdir bin mkdir bin
mv libEHS_Dyn.so bin
mv StrToHash bin mv StrToHash bin
mkdir lib mkdir lib
mv libEHS.a lib mv libEHS_Stc.a lib
- name: Zipping Binaries - name: Zipping Binaries
run: zip -r ehs-linux-amd64.zip include bin lib docs LICENSE RADME.md run: zip -r ehs-linux-amd64.zip include bin lib docs LICENSE RADME.md
@@ -92,6 +103,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
@@ -100,7 +112,7 @@ jobs:
uses: actions/checkout@v3 uses: actions/checkout@v3
- name: Installing Dependencies - name: Installing Dependencies
run: sudo apt install -y doxygen zip libasound2-dev libxcb1-dev libxcb-xinput-dev libxcb-cursor-dev run: sudo apt install -y doxygen ninja-build zip libxcb1-dev libxcb-xinput-dev libxcb-cursor-dev libpipewire-0.3-dev
- name: Generating Documentation - name: Generating Documentation
run: | run: |
@@ -109,16 +121,18 @@ jobs:
- name: Building/Compiling/Installing Project - name: Building/Compiling/Installing Project
run: | run: |
cd ${{ gitea.workspace }} cd ${{ gitea.workspace }}
cmake -DCMAKE_BUILD_TYPE=Release -DLINUX_WINDOW_SYSTEM:STRING=XCB . cmake -G Ninja -DCMAKE_BUILD_TYPE=Release -DLINUX_WINDOW_SYSTEM:STRING=XCB .
cmake --build . --config Release cmake --build . --config Release
cmake --install . cmake --install .
- name: Creating Appropriate Directories - name: Creating Appropriate Directories
run: | run: |
cd ${{ gitea.workspace }}
mkdir bin mkdir bin
mv libEHS_Dyn.so bin
mv StrToHash bin mv StrToHash bin
mkdir lib mkdir lib
mv libEHS.a lib mv libEHS_Stc.a lib
- name: Zipping Binaries - name: Zipping Binaries
run: zip -r ehs-linux-aarch64.zip include bin lib docs LICENSE README.md run: zip -r ehs-linux-aarch64.zip include bin lib docs LICENSE README.md
@@ -133,4 +147,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

26
Assembly.def Normal file
View File

@@ -0,0 +1,26 @@
LIBRARY EHS_Dyn
EXPORTS
?GenerateSeed_u64@HRNG@ehs@@SA_KXZ
?Generate_u64@HRNG@ehs@@SA_K_K0@Z
?Generate_u64@HRNG@ehs@@SA_KXZ
?GenerateSeed_s64@HRNG@ehs@@SA_JXZ
?Generate_s64@HRNG@ehs@@SA_J_J0@Z
?Generate_s64@HRNG@ehs@@SA_JXZ
?GenerateSeed_u32@HRNG@ehs@@SAIXZ
?Generate_u32@HRNG@ehs@@SAIII@Z
?Generate_u32@HRNG@ehs@@SAIXZ
?GenerateSeed_s32@HRNG@ehs@@SAHXZ
?Generate_s32@HRNG@ehs@@SAHHH@Z
?Generate_s32@HRNG@ehs@@SAHXZ
?GenerateSeed_u16@HRNG@ehs@@SAIXZ
?Generate_u16@HRNG@ehs@@SAGGG@Z
?Generate_u16@HRNG@ehs@@SAGXZ
?GenerateSeed_s16@HRNG@ehs@@SAFXZ
?Generate_s16@HRNG@ehs@@SAFFF@Z
?Generate_s16@HRNG@ehs@@SAFXZ
?GenerateSeed_u8@HRNG@ehs@@SAEXZ
?Generate_u8@HRNG@ehs@@SAEEE@Z
?Generate_u8@HRNG@ehs@@SAEXZ
?GenerateSeed_s8@HRNG@ehs@@SACXZ
?Generate_s8@HRNG@ehs@@SACCC@Z
?Generate_s8@HRNG@ehs@@SACXZ

View File

@@ -1,4 +1,4 @@
cmake_minimum_required(VERSION 3.25.1) cmake_minimum_required(VERSION 3.30.4)
set(IS_OS_WINDOWS FALSE) set(IS_OS_WINDOWS FALSE)
set(IS_OS_LINUX FALSE) set(IS_OS_LINUX FALSE)
@@ -11,9 +11,12 @@ set(IS_ARCH_ARM FALSE)
project(EHS CXX C) project(EHS CXX C)
set(CMAKE_VERBOSE_MAKEFILE ON)
if (${CMAKE_HOST_SYSTEM_NAME} STREQUAL "Windows") if (${CMAKE_HOST_SYSTEM_NAME} STREQUAL "Windows")
set(IS_OS_WINDOWS TRUE) set(IS_OS_WINDOWS TRUE)
set(USER_HOME_DIRECTORY $ENV{USERPROFILE}) set(USER_HOME_DIRECTORY "$ENV{USERPROFILE}")
string(REPLACE "\\" "/" USER_HOME_DIRECTORY "${USER_HOME_DIRECTORY}")
message("Building for the Windows operating system.") message("Building for the Windows operating system.")
elseif (${CMAKE_HOST_SYSTEM_NAME} STREQUAL "Linux") elseif (${CMAKE_HOST_SYSTEM_NAME} STREQUAL "Linux")
set(IS_OS_LINUX TRUE) set(IS_OS_LINUX TRUE)
@@ -39,182 +42,209 @@ endif ()
set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD 20)
set(EHS_SOURCES set(EHS_SOURCES
src/EHS.cpp include/ehs/EHS.h src/EHS.cpp include/ehs/EHS.h
src/Type.cpp include/ehs/Type.h src/Type.cpp include/ehs/Type.h
src/BaseObj.cpp include/ehs/BaseObj.h src/BaseObj.cpp include/ehs/BaseObj.h
src/GC.cpp include/ehs/GC.h src/GC.cpp include/ehs/GC.h
src/Log.cpp include/ehs/Log.h src/Log.cpp include/ehs/Log.h
src/URI.cpp include/ehs/URI.h src/URI.cpp include/ehs/URI.h
src/Math.cpp include/ehs/Math.h src/Math.cpp include/ehs/Math.h
src/Color4.cpp include/ehs/Color4.h src/Color4.cpp include/ehs/Color4.h
src/Color3.cpp include/ehs/Color3.h src/Color3.cpp include/ehs/Color3.h
src/Version.cpp include/ehs/Version.h src/Version.cpp include/ehs/Version.h
src/Base64.cpp include/ehs/Base64.h src/Base64.cpp include/ehs/Base64.h
src/Data.cpp include/ehs/Data.h src/SHA256.cpp include/ehs/SHA256.h
src/Range.cpp include/ehs/Range.h src/Data.cpp include/ehs/Data.h
src/Util.cpp include/ehs/Util.h src/Range.cpp include/ehs/Range.h
src/Task.cpp include/ehs/Task.h src/Util.cpp include/ehs/Util.h
src/DataType.cpp include/ehs/DataType.h src/Task.cpp include/ehs/Task.h
include/ehs/Anchor.h src/DataType.cpp include/ehs/DataType.h
include/ehs/Dock.h include/ehs/Anchor.h
include/ehs/HashMap.h include/ehs/Dock.h
include/ehs/HRNG.h include/ehs/HashMap.h
include/ehs/Link.h include/ehs/HRNG.h
include/ehs/LinkedList.h include/ehs/Link.h
include/ehs/Mat2.h include/ehs/LinkedList.h
include/ehs/Mat3.h include/ehs/Mat2.h
include/ehs/Mat4.h include/ehs/Mat3.h
include/ehs/PRNG.h include/ehs/Mat4.h
include/ehs/Quat.h include/ehs/PRNG.h
include/ehs/Rect.h include/ehs/Quat.h
include/ehs/Str.h include/ehs/Rect.h
include/ehs/Types.h include/ehs/Str.h
include/ehs/UTF.h include/ehs/Types.h
include/ehs/Vec2.h include/ehs/UTF.h
include/ehs/Vec3.h include/ehs/Vec2.h
include/ehs/Vec4.h include/ehs/Vec3.h
include/ehs/Serializer.h include/ehs/Vec4.h
include/ehs/Array.h include/ehs/Serializer.h
include/ehs/Vector.h include/ehs/Array.h
include/ehs/SArray.h include/ehs/Vector.h
src/PtrData.cpp include/ehs/PtrData.h include/ehs/SArray.h
include/ehs/UniPtr.h src/PtrData.cpp include/ehs/PtrData.h
include/ehs/ShdPtr.h include/ehs/UniPtr.h
include/ehs/WkPtr.h include/ehs/ShdPtr.h
include/ehs/WkPtr.h
src/db/DbVarTmpl.cpp include/ehs/db/DbVarTmpl.h src/db/DbVarTmpl.cpp include/ehs/db/DbVarTmpl.h
src/system/CPU.cpp include/ehs/system/CPU.h src/system/CPU.cpp include/ehs/system/CPU.h
src/system/Thread.cpp include/ehs/system/Thread.h src/system/Thread.cpp include/ehs/system/Thread.h
src/system/BaseMutex.cpp include/ehs/system/BaseMutex.h src/system/BaseMutex.cpp include/ehs/system/BaseMutex.h
src/system/BaseSemaphore.cpp include/ehs/system/BaseSemaphore.h src/system/BaseSemaphore.cpp include/ehs/system/BaseSemaphore.h
src/system/BaseSystem.cpp include/ehs/system/BaseSystem.h src/system/BaseSystem.cpp include/ehs/system/BaseSystem.h
src/system/BaseOpen.cpp include/ehs/system/BaseOpen.h src/system/BaseOpen.cpp include/ehs/system/BaseOpen.h
include/ehs/system/Architecture.h include/ehs/system/Architecture.h
include/ehs/system/Mutex.h include/ehs/system/Mutex.h
include/ehs/system/Open.h include/ehs/system/Open.h
include/ehs/system/OS.h include/ehs/system/OS.h
include/ehs/system/Semaphore.h include/ehs/system/Semaphore.h
include/ehs/system/System.h include/ehs/system/System.h
include/ehs/system/AVX2.h
include/ehs/system/AVX512.h
src/json/Json.cpp include/ehs/json/Json.h src/json/Json.cpp include/ehs/json/Json.h
src/json/JsonBase.cpp include/ehs/json/JsonBase.h src/json/JsonBase.cpp include/ehs/json/JsonBase.h
src/json/JsonNum.cpp include/ehs/json/JsonNum.h src/json/JsonNum.cpp include/ehs/json/JsonNum.h
src/json/JsonBool.cpp include/ehs/json/JsonBool.h src/json/JsonBool.cpp include/ehs/json/JsonBool.h
src/json/JsonStr.cpp include/ehs/json/JsonStr.h src/json/JsonStr.cpp include/ehs/json/JsonStr.h
src/json/JsonObj.cpp include/ehs/json/JsonObj.h src/json/JsonObj.cpp include/ehs/json/JsonObj.h
src/json/JsonArray.cpp include/ehs/json/JsonArray.h src/json/JsonArray.cpp include/ehs/json/JsonArray.h
src/json/JsonVar.cpp include/ehs/json/JsonVar.h src/json/JsonVar.cpp include/ehs/json/JsonVar.h
src/io/Resource.cpp include/ehs/io/Resource.h src/io/Resource.cpp include/ehs/io/Resource.h
src/io/Console.cpp include/ehs/io/Console.h src/io/Console.cpp include/ehs/io/Console.h
src/io/RIFF_Chunk.cpp include/ehs/io/RIFF_Chunk.h src/io/RIFF_Chunk.cpp include/ehs/io/RIFF_Chunk.h
src/io/RIFF.cpp include/ehs/io/RIFF.h src/io/RIFF.cpp include/ehs/io/RIFF.h
src/io/BaseWindow.cpp include/ehs/io/BaseWindow.h src/io/BaseWindow.cpp include/ehs/io/BaseWindow.h
src/io/BaseFile.cpp include/ehs/io/BaseFile.h src/io/BaseFile.cpp include/ehs/io/BaseFile.h
src/io/Glyph.cpp include/ehs/io/Glyph.h src/io/Glyph.cpp include/ehs/io/Glyph.h
src/io/FontAtlas.cpp include/ehs/io/FontAtlas.h src/io/FontAtlas.cpp include/ehs/io/FontAtlas.h
src/io/BaseFileMonitor.cpp include/ehs/io/BaseFileMonitor.h src/io/BaseFileMonitor.cpp include/ehs/io/BaseFileMonitor.h
include/ehs/io/COM.h include/ehs/io/COM.h
include/ehs/io/File.h include/ehs/io/File.h
include/ehs/io/FileMonitor.h include/ehs/io/FileMonitor.h
include/ehs/io/Window.h include/ehs/io/Window.h
src/io/socket/Request.cpp include/ehs/io/socket/Request.h include/ehs/io/socket/Socket.h
src/io/socket/Response.cpp include/ehs/io/socket/Response.h src/io/socket/Request.cpp include/ehs/io/socket/Request.h
src/io/socket/BaseDNS.cpp include/ehs/io/socket/BaseDNS.h src/io/socket/Response.cpp include/ehs/io/socket/Response.h
src/io/socket/BaseUDP.cpp include/ehs/io/socket/BaseUDP.h src/io/socket/BaseDNS.cpp include/ehs/io/socket/BaseDNS.h
src/io/socket/BaseTCP.cpp include/ehs/io/socket/BaseTCP.h include/ehs/io/socket/DNS.h
src/io/socket/SSL.cpp include/ehs/io/socket/SSL.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
include/ehs/io/socket/TCP.h
src/io/socket/SSL.cpp include/ehs/io/socket/SSL.h
src/io/socket/rest/Twitch.cpp include/ehs/io/socket/rest/Twitch.h include/ehs/io/socket/ehc/NetUtils.h
src/io/socket/rest/TwitchChat.cpp include/ehs/io/socket/rest/TwitchChat.h src/io/socket/EHC.cpp include/ehs/io/socket/EHC.h
src/io/socket/rest/Spotify.cpp include/ehs/io/socket/rest/Spotify.h src/io/socket/ehc/NetFrag.cpp include/ehs/io/socket/ehc/NetFrag.h
include/ehs/io/socket/Socket.h src/io/socket/ehc/NetEnd.cpp include/ehs/io/socket/ehc/NetEnd.h
include/ehs/io/socket/TCP.h src/io/socket/ehc/NetSys.cpp include/ehs/io/socket/ehc/NetSys.h
include/ehs/io/socket/UDP.h src/io/socket/ehc/NetOp.cpp include/ehs/io/socket/ehc/NetOp.h
include/ehs/io/socket/DNS.h
src/io/audio/Audio.cpp include/ehs/io/audio/Audio.h src/io/socket/rest/Twitch.cpp include/ehs/io/socket/rest/Twitch.h
src/io/audio/BaseAudioDevice.cpp include/ehs/io/audio/BaseAudioDevice.h src/io/socket/rest/TwitchChat.cpp include/ehs/io/socket/rest/TwitchChat.h
src/io/audio/AudioCodec.cpp include/ehs/io/audio/AudioCodec.h src/io/socket/rest/Spotify.cpp include/ehs/io/socket/rest/Spotify.h
include/ehs/io/audio/AudioDevice.h
src/io/img/PNG.cpp include/ehs/io/img/PNG.h src/io/audio/Audio.cpp include/ehs/io/audio/Audio.h
src/io/img/Img.cpp include/ehs/io/img/Img.h src/io/audio/BaseAudioDevice.cpp include/ehs/io/audio/BaseAudioDevice.h
src/io/img/PNG_Chunk.cpp include/ehs/io/img/PNG_Chunk.h src/io/audio/AudioCodec.cpp include/ehs/io/audio/AudioCodec.h
src/io/img/ImgCodec.cpp include/ehs/io/img/ImgCodec.h include/ehs/io/audio/AudioDevice.h
include/ehs/io/mdl/Vertex.h src/io/img/PNG.cpp include/ehs/io/img/PNG.h
src/io/model/Mesh.cpp include/ehs/io/mdl/Mesh.h src/io/img/Img.cpp include/ehs/io/img/Img.h
src/io/model/Bone.cpp include/ehs/io/mdl/Bone.h src/io/img/PNG_Chunk.cpp include/ehs/io/img/PNG_Chunk.h
src/io/model/Mdl.cpp include/ehs/io/mdl/Mdl.h src/io/img/ImgCodec.cpp include/ehs/io/img/ImgCodec.h
src/io/model/Animation.cpp include/ehs/io/mdl/Animation.h
src/io/model/AnimBone.cpp include/ehs/io/mdl/AnimBone.h
src/io/model/KeyFrame.cpp include/ehs/io/mdl/KeyFrame.h
src/io/model/PropertyChange.cpp include/ehs/io/mdl/PropertyChange.h
src/io/hid/ButtonState.cpp include/ehs/io/hid/ButtonState.h include/ehs/io/mdl/Vertex.h
src/io/hid/Button.cpp include/ehs/io/hid/Button.h src/io/model/Mesh.cpp include/ehs/io/mdl/Mesh.h
src/io/hid/Mouse.cpp include/ehs/io/hid/Mouse.h src/io/model/Bone.cpp include/ehs/io/mdl/Bone.h
src/io/hid/Keyboard.cpp include/ehs/io/hid/Keyboard.h src/io/model/Mdl.cpp include/ehs/io/mdl/Mdl.h
src/io/hid/HID.cpp include/ehs/io/hid/HID.h src/io/model/Animation.cpp include/ehs/io/mdl/Animation.h
src/io/hid/InputHandler.cpp include/ehs/io/hid/InputHandler.h src/io/model/AnimBone.cpp include/ehs/io/mdl/AnimBone.h
src/io/hid/Input.cpp include/ehs/io/hid/Input.h src/io/model/KeyFrame.cpp include/ehs/io/mdl/KeyFrame.h
src/io/model/MdlCodec.cpp src/io/model/PropertyChange.cpp include/ehs/io/mdl/PropertyChange.h
include/ehs/io/mdl/MdlCodec.h
include/ehs/io/UsbBase.h src/io/hid/ButtonState.cpp include/ehs/io/hid/ButtonState.h
src/io/UsbBase.cpp src/io/hid/Button.cpp include/ehs/io/hid/Button.h
include/ehs/db/DbTable.h src/io/hid/Mouse.cpp include/ehs/io/hid/Mouse.h
include/ehs/db/DbObject.h src/io/hid/Keyboard.cpp include/ehs/io/hid/Keyboard.h
include/ehs/db/DbVar.h src/io/hid/HID.cpp include/ehs/io/hid/HID.h
src/db/DbVar.cpp src/io/hid/InputHandler.cpp include/ehs/io/hid/InputHandler.h
include/ehs/db/Database.h src/io/hid/Input.cpp include/ehs/io/hid/Input.h
src/db/DbObject.cpp src/io/model/MdlCodec.cpp
src/db/Database.cpp include/ehs/io/mdl/MdlCodec.h
src/db/Database.cpp include/ehs/io/UsbBase.h
src/db/DbTable.cpp src/io/UsbBase.cpp
include/ehs/io/BaseDirectory.h include/ehs/db/DbTable.h
src/io/BaseDirectory.cpp include/ehs/db/DbObject.h
include/ehs/io/Directory.h include/ehs/db/DbVar.h
src/db/DbVar.cpp
include/ehs/db/Database.h
src/db/DbObject.cpp
src/db/Database.cpp
src/db/Database.cpp
src/db/DbTable.cpp
include/ehs/io/BaseDirectory.h
src/io/BaseDirectory.cpp
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
src/io/socket/QueryVar.cpp include/ehs/io/socket/QueryVar.h
src/io/socket/HeaderVar.cpp include/ehs/io/socket/HeaderVar.h
) )
if (IS_OS_WINDOWS) if (IS_OS_WINDOWS)
list(APPEND EHS_SOURCES list(APPEND EHS_SOURCES
src/io/socket/UDP_W32.cpp include/ehs/io/socket/UDP_W32.h src/io/socket/UDP_W32.cpp include/ehs/io/socket/UDP_W32.h
src/io/socket/TCP_W32.cpp include/ehs/io/socket/TCP_W32.h src/io/socket/TCP_W32.cpp include/ehs/io/socket/TCP_W32.h
src/io/socket/DNS_W32.cpp include/ehs/io/socket/DNS_W32.h src/io/socket/DNS_W32.cpp include/ehs/io/socket/DNS_W32.h
src/system/Semaphore_W32.cpp include/ehs/system/Semaphore_W32.h src/system/Semaphore_W32.cpp include/ehs/system/Semaphore_W32.h
src/system/System_W32.cpp include/ehs/system/System_W32.h src/system/System_W32.cpp include/ehs/system/System_W32.h
src/system/Mutex_W32.cpp include/ehs/system/Mutex_W32.h src/system/Mutex_W32.cpp include/ehs/system/Mutex_W32.h
src/system/Open_W32.cpp include/ehs/system/Open_W32.h src/system/Open_W32.cpp include/ehs/system/Open_W32.h
src/io/audio/audioDevice_W32.cpp include/ehs/io/audio/audioDevice_W32.h src/io/audio/audioDevice_W32.cpp include/ehs/io/audio/audioDevice_W32.h
src/io/File_W32.cpp include/ehs/io/File_W32.h src/io/File_W32.cpp include/ehs/io/File_W32.h
src/io/FileMonitor_W32.cpp include/ehs/io/FileMonitor_W32.h src/io/FileMonitor_W32.cpp include/ehs/io/FileMonitor_W32.h
src/io/Window_W32.cpp include/ehs/io/Window_W32.h src/io/Window_W32.cpp include/ehs/io/Window_W32.h
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) src/system/AVX2_MSVC_AMD64.asm src/system/AVX512_MSVC_AMD64.asm
list(APPEND EHS_SOURCES
src/io/socket/UDP_BSD.cpp include/ehs/io/socket/UDP_BSD.h
src/io/socket/TCP_BSD.cpp include/ehs/io/socket/TCP_BSD.h
src/io/socket/DNS_LNX.cpp include/ehs/io/socket/DNS_LNX.h
src/system/Semaphore_P.cpp include/ehs/system/Semaphore_P.h
src/system/System_LNX.cpp include/ehs/system/System_LNX.h
src/system/Open_UNX.cpp include/ehs/system/Open_UNX.h
src/io/File_UNX.cpp include/ehs/io/File_UNX.h
src/io/FileMonitor_UNX.cpp include/ehs/io/FileMonitor_UNX.h
src/system/Mutex_PT.cpp include/ehs/system/Mutex_PT.h
src/io/audio/AudioDevice_ALSA.cpp include/ehs/io/audio/AudioDevice_ALSA.h
src/system/FileSystem.cpp include/ehs/system/FileSystem.h
src/system/User.cpp include/ehs/system/User.h
src/io/Directory_LNX.cpp include/ehs/io/Directory_LNX.h
src/io/Usb_LNX.cpp include/ehs/io/Usb_LNX.h
) )
set(LINUX_WINDOW_SYSTEM "Wayland" CACHE STRING "Linux Window System") elseif (IS_OS_LINUX)
list(APPEND EHS_SOURCES
src/io/socket/UDP_BSD.cpp include/ehs/io/socket/UDP_BSD.h
src/io/socket/TCP_BSD.cpp include/ehs/io/socket/TCP_BSD.h
src/io/socket/DNS_LNX.cpp include/ehs/io/socket/DNS_LNX.h
src/system/Semaphore_P.cpp include/ehs/system/Semaphore_P.h
src/system/System_LNX.cpp include/ehs/system/System_LNX.h
src/system/Open_UNX.cpp include/ehs/system/Open_UNX.h
src/io/File_UNX.cpp include/ehs/io/File_UNX.h
src/io/FileMonitor_UNX.cpp include/ehs/io/FileMonitor_UNX.h
src/system/Mutex_PT.cpp include/ehs/system/Mutex_PT.h
src/io/audio/AudioDevice_PW.cpp include/ehs/io/audio/AudioDevice_PW.h
src/system/FileSystem.cpp include/ehs/system/FileSystem.h
src/system/User.cpp include/ehs/system/User.h
src/io/Directory_LNX.cpp include/ehs/io/Directory_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 "XCB" CACHE STRING "Linux Window System")
if (LINUX_WINDOW_SYSTEM STREQUAL "Wayland") if (LINUX_WINDOW_SYSTEM STREQUAL "Wayland")
add_compile_definitions(EHS_WS_WAYLAND) add_compile_definitions(EHS_WS_WAYLAND)
@@ -230,36 +260,43 @@ elseif (IS_OS_LINUX)
endif () endif ()
if (IS_ARCH_AMD64) if (IS_ARCH_AMD64)
list(APPEND EHS_SOURCES src/system/CPU_GCC_AMD64.asm src/HRNG_GCC.asm src/Math_GCC_AMD64.asm) list(APPEND EHS_SOURCES src/system/CPU_GCC_AMD64.asm src/HRNG_GCC.asm src/Math_GCC_AMD64.asm src/system/AVX2_GCC_AMD64.asm src/system/AVX512_GCC_AMD64.asm)
elseif (IS_ARCH_ARM64) elseif (IS_ARCH_ARM64)
list(APPEND EHS_SOURCES src/system/CPU_ARM64.cpp src/HRNG_ARM64.cpp src/Math_GCC_ARM64.s) list(APPEND EHS_SOURCES src/system/CPU_ARM64.cpp src/system/CPU_GCC_AARCH64.s src/HRNG_ARM64.cpp src/Math_GCC_ARM64.s src/system/AVX2_AARCH64.cpp src/system/AVX512_AARCH64.cpp)
endif () endif ()
endif() endif()
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") add_library(EHS_Stc STATIC ${EHS_SOURCES})
#message("${CMAKE_CXX_FLAGS}") add_library(EHS_Dyn SHARED ${EHS_SOURCES} Assembly.def)
add_library(EHS_STC STATIC ${EHS_SOURCES})
add_library(EHS_DYN SHARED ${EHS_SOURCES})
add_executable(StrToHash src/StrToHash.cpp) add_executable(StrToHash src/StrToHash.cpp)
target_compile_definitions(EHS_DYN PRIVATE EHS_LIB_EXPORT) target_compile_definitions(EHS_Dyn PRIVATE EHS_LIB_EXPORT)
target_include_directories(EHS_STC PUBLIC ${PROJECT_SOURCE_DIR}/include) target_include_directories(EHS_Stc PUBLIC ${PROJECT_SOURCE_DIR}/include)
target_include_directories(EHS_DYN PUBLIC ${PROJECT_SOURCE_DIR}/include) target_include_directories(EHS_Dyn PUBLIC ${PROJECT_SOURCE_DIR}/include)
if (IS_OS_LINUX) if (IS_OS_LINUX)
set(CMAKE_INSTALL_PREFIX "${USER_HOME_DIRECTORY}/.local") set(CMAKE_INSTALL_PREFIX "${USER_HOME_DIRECTORY}/.local")
install(TARGETS EHS_Dyn LIBRARY DESTINATION "bin")
find_package(PkgConfig REQUIRED)
pkg_check_modules(PIPEWIRE REQUIRED libpipewire-0.3)
target_include_directories(EHS_Stc PRIVATE ${PIPEWIRE_INCLUDE_DIRS})
target_include_directories(EHS_Dyn PRIVATE ${PIPEWIRE_INCLUDE_DIRS})
elseif (IS_OS_WINDOWS) elseif (IS_OS_WINDOWS)
set(CMAKE_INSTALL_PREFIX "${USER_HOME_DIRECTORY}/EHS") set(CMAKE_INSTALL_PREFIX "${USER_HOME_DIRECTORY}/EHS")
install(TARGETS EHS_Dyn LIBRARY DESTINATION "lib")
install(TARGETS EHS_Dyn RUNTIME DESTINATION "bin")
file(GLOB DLL_FILES "${CMAKE_CURRENT_BINARY_DIR}/*.dll")
install(FILES ${DLL_FILES} DESTINATION "bin")
endif () endif ()
install(TARGETS EHS_STC DESTINATION lib) install(TARGETS EHS_Stc DESTINATION "lib")
install(TARGETS EHS_DYN RUNTIME DESTINATION bin) install(TARGETS StrToHash DESTINATION "bin")
install(TARGETS EHS_DYN LIBRARY DESTINATION lib)
install(TARGETS StrToHash DESTINATION bin)
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/ DESTINATION include) install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/" DESTINATION "include")
find_package(ZLIB REQUIRED) find_package(ZLIB REQUIRED)
if (ZLIB_FOUND) if (ZLIB_FOUND)
@@ -275,17 +312,22 @@ else ()
message(STATUS "OpenSSL was not found.") message(STATUS "OpenSSL was not found.")
endif () endif ()
target_link_libraries(EHS_STC OpenSSL::SSL OpenSSL::Crypto ZLIB::ZLIB) target_link_libraries(EHS_Stc OpenSSL::SSL OpenSSL::Crypto ZLIB::ZLIB)
target_link_libraries(EHS_DYN OpenSSL::SSL OpenSSL::Crypto ZLIB::ZLIB avrt ws2_32) target_link_libraries(EHS_Dyn 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(StrToHash ws2_32 avrt EHS_STC) target_link_libraries(EHS_Dyn avrt ws2_32 IPHLPAPI)
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")
target_link_libraries(EHS_Dyn wayland-client)
target_link_libraries(StrToHash wayland-client) target_link_libraries(StrToHash wayland-client)
elseif (LINUX_WINDOW_SYSTEM STREQUAL "XCB") elseif (LINUX_WINDOW_SYSTEM STREQUAL "XCB")
target_link_libraries(EHS_Dyn xcb xcb-cursor xcb-xfixes xcb-xinput)
target_link_libraries(StrToHash xcb xcb-cursor xcb-xfixes xcb-xinput) target_link_libraries(StrToHash xcb xcb-cursor xcb-xfixes xcb-xinput)
endif () endif ()
target_link_libraries(StrToHash z asound EHS_STC) target_link_libraries(EHS_Dyn z pipewire-0.3)
target_link_libraries(StrToHash z EHS_Stc)
endif () endif ()

View File

@@ -1,12 +0,0 @@
{
"version": 3,
"configurePresets": [
{
"name": "default",
"binaryDir": "${sourceDir}/build",
"cacheVariables": {
"CMAKE_TOOLCHAIN_FILE": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"
}
}
]
}

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
@@ -37,6 +38,8 @@ This project does not fully follow the C++ standard.
- Asynchronous Task System - Asynchronous Task System
- URI Parsing - URI Parsing
- USB (WIP) - USB (WIP)
- Base64
- SHA256
### Supported Architectures ### Supported Architectures
- AMD64 - AMD64
@@ -73,8 +76,10 @@ 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 --preset=default /path/to/source` `cmake -A x64 -DCMAKE_BUILD_TYPE=Release /path/to/source`
### Compiling ### Compiling
`cmake --build /path/to/build --config Release` `cmake --build /path/to/build --config Release`
@@ -89,12 +94,10 @@ This will require the terminal to be running in administrator mode.
#include <ehs/EHS.h> #include <ehs/EHS.h>
#include <ehs/io/Console.h> #include <ehs/io/Console.h>
ehs::Int_32 Main(ehs::Str_8* appName, ehs::Str_8* appVerId, ehs::Version* appVer) int main()
{ {
// Simple identifying meta-data for the logger. // Simple identifying meta-data for the logger.
*appName = "Simple Example App"; // The application's name ehs::Initialize("Simple Example App", "Release", {1, 0, 0});
*appVerId = "Release"; // The app's version prefix; i.e. Alpha, Beta or Release as an example.
*appVer = {1, 0, 0}; // The app's version major, minor and patch number.
ehs::Console::Write_8("How old are you?"); // Write to the console in UTF_8 character encoding. ehs::Console::Write_8("How old are you?"); // Write to the console in UTF_8 character encoding.
@@ -103,13 +106,15 @@ ehs::Int_32 Main(ehs::Str_8* appName, ehs::Str_8* appVerId, ehs::Version* appVer
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.
ehs::Console::Write("Your age is " + ehs::Str_8::FromNum(age) + "."); // Write the console with the age converted back to string. ehs::Console::Write("Your age is " + ehs::Str_8::FromNum(age) + "."); // Write the console with the age converted back to string.
ehs::Uninitialize();
return 0; return 0;
} }
``` ```

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

@@ -8,17 +8,26 @@ namespace ehs
class EHS_LIB_IO Base64 class EHS_LIB_IO Base64
{ {
private: private:
static const char ascii[]; static constexpr UInt_8 asciiUrl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
static constexpr UInt_8 ascii[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
public: public:
static Str_8 EncodeURL(const Str_8 &input);
static Str_8 Encode(const Str_8 &input); static Str_8 Encode(const Str_8 &input);
static Str_8 DecodeURL(const Str_8 &input);
static Str_8 Decode(const Str_8 &input); static Str_8 Decode(const Str_8 &input);
private: private:
static char Find(char c); static UInt_8 FindURL(const UInt_8 &c);
static bool IsBase64(char c); static UInt_8 Find(const UInt_8 &c);
static bool IsBase64URL(const UInt_8 &c);
static bool IsBase64(const UInt_8 &c);
}; };
} }

View File

@@ -5,7 +5,7 @@
namespace ehs namespace ehs
{ {
class EHS_LIB_IO HRNG class HRNG
{ {
public: public:
static UInt_64 GenerateSeed_u64(); static UInt_64 GenerateSeed_u64();

View File

@@ -63,7 +63,7 @@ namespace ehs
/// @param [in] tags The tags to associate this log with. /// @param [in] tags The tags to associate this log with.
/// @param [in] code The unique code to use. /// @param [in] code The unique code to use.
/// @param [in] msg Detailed information about what happened. /// @param [in] msg Detailed information about what happened.
Log(LogType type, const std::initializer_list<Str_8> &tags, UInt_64 code, Str_8 msg); Log(LogType type, const Str_8 &tags, UInt_64 code, Str_8 msg);
/// Initializes members with the given information. /// Initializes members with the given information.
/// @param [in] tags The tags to associate this log with. /// @param [in] tags The tags to associate this log with.
@@ -134,20 +134,20 @@ namespace ehs
#ifndef EHS_LOG_INT #ifndef EHS_LOG_INT
#ifdef EHS_DEBUG #ifdef EHS_DEBUG
#define EHS_LOG_INT(type, code, msg) ehs::Log::Raise({type, {ehs::GetAcronym_8(), EHS_FILE, EHS_FUNC, ehs::Str_8::FromNum((ehs::UInt_32)EHS_LINE)}, code, msg}) #define EHS_LOG_INT(type, code, msg) ehs::Log::Raise(ehs::Log(type, ehs::Str_8(ehs::GetAcronym_8()) + ", " + EHS_FILE + ", " + EHS_FUNC + ", " + ehs::Str_8::FromNum((ehs::UInt_32)EHS_LINE), code, msg))
#else #else
#define EHS_LOG_INT(type, code, msg) ehs::Log::Raise({type, {ehs::GetAcronym_8(), EHS_FUNC}, code, msg}) #define EHS_LOG_INT(type, code, msg) ehs::Log::Raise(ehs::Log(type, ehs::Str_8(ehs::GetAcronym_8()) + ", " + EHS_FUNC, code, msg))
#endif #endif
#endif #endif
#ifndef EHS_LOG #ifndef EHS_LOG
#ifdef EHS_DEBUG #ifdef EHS_DEBUG
#define EHS_LOG(type, code, msg) ehs::Log::Raise({type, {ehs::GetAppName_8(), EHS_FILE, EHS_FUNC, ehs::Str_8::FromNum((ehs::UInt_32)EHS_LINE)}, code, msg}) #define EHS_LOG(type, code, msg) ehs::Log::Raise(ehs::Log(type, ehs::Str_8(ehs::GetAppName_8()) + ", " + EHS_FILE + ", " + EHS_FUNC + ", " + ehs::Str_8::FromNum((ehs::UInt_32)EHS_LINE), code, msg))
#else #else
#define EHS_LOG(type, code, msg) ehs::Log::Raise({type, {ehs::GetAppName_8(), EHS_FUNC}, code, msg}) #define EHS_LOG(type, code, msg) ehs::Log::Raise(ehs::Log(type, ehs::Str_8(ehs::GetAppName_8()) + ", " + EHS_FUNC, code, msg))
#endif #endif
#endif #endif
#ifndef EHS_LOG_SUCCESS #ifndef EHS_LOG_SUCCESS
#define EHS_LOG_SUCCESS() ehs::Log::Raise({}) #define EHS_LOG_SUCCESS() ehs::Log::Raise({})
#endif #endif

View File

@@ -332,14 +332,14 @@ namespace ehs
static Mat4<T> YawRotate(const T angle) static Mat4<T> YawRotate(const T angle)
{ {
T radians = Math::Rads(angle); T radians = Math::Rads<T>(angle);
Mat4<T> result; Mat4<T> result;
result.data[0] = Math::Cos(radians); result.data[0] = Math::Cos<T>(radians);
result.data[2] = -Math::Sin(radians); result.data[2] = -Math::Sin<T>(radians);
result.data[5] = 1; result.data[5] = 1;
result.data[8] = Math::Sin(radians); result.data[8] = Math::Sin<T>(radians);
result.data[10] = Math::Cos(radians); result.data[10] = Math::Cos<T>(radians);
result.data[15] = 1; result.data[15] = 1;
return result; return result;
@@ -347,7 +347,7 @@ namespace ehs
static Mat4<T> RollRotate(const T angle) static Mat4<T> RollRotate(const T angle)
{ {
T radians = Math::Rads(angle); T radians = Math::Rads<T>(angle);
Mat4<T> result; Mat4<T> result;
result.data[0] = Math::Cos(radians); result.data[0] = Math::Cos(radians);
@@ -367,7 +367,7 @@ namespace ehs
static Mat4<T> RH_Perspective(const T fov, const T aspect, const T zNear, const T zFar) static Mat4<T> RH_Perspective(const T fov, const T aspect, const T zNear, const T zFar)
{ {
const float tanHalfFovy = tan(Math::Rads(fov) / 2.0f); const T tanHalfFovy = Math::Tan<T>(Math::Rads(fov) / 2.0f);
Mat4<T> result; Mat4<T> result;
result[0] = 1.0f / (aspect * tanHalfFovy); result[0] = 1.0f / (aspect * tanHalfFovy);
@@ -380,7 +380,7 @@ namespace ehs
static Mat4<T> LH_Perspective(const T fov, const T aspect, const T zNear, const T zFar) static Mat4<T> LH_Perspective(const T fov, const T aspect, const T zNear, const T zFar)
{ {
const float tanHalfFovy = Math::Tan(Math::Rads(fov) / 2.0f); const T tanHalfFovy = Math::Tan<T>(Math::Rads(fov) / 2.0f);
Mat4<T> result; Mat4<T> result;
result[0] = 1.0f / (aspect * tanHalfFovy); result[0] = 1.0f / (aspect * tanHalfFovy);

59
include/ehs/SHA256.h Normal file
View File

@@ -0,0 +1,59 @@
#pragma once
#include "Types.h"
namespace ehs
{
class EHS_LIB_IO SHA256
{
private:
static UInt_32 ROTR(UInt_32 x, UInt_32 n);
static UInt_32 CH(UInt_32 x, UInt_32 y, UInt_32 z);
static UInt_32 MAJ(UInt_32 x, UInt_32 y, UInt_32 z);
static UInt_32 EP0(UInt_32 x);
static UInt_32 EP1(UInt_32 x);
static UInt_32 SIG0(UInt_32 x);
static UInt_32 SIG1(UInt_32 x);
static constexpr UInt_32 k[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
UInt_32 state[8];
UInt_64 bitLen;
Byte data[64];
UInt_64 dataLen;
public:
SHA256();
SHA256(SHA256 &&other) noexcept;
SHA256(const SHA256 &other);
SHA256 &operator=(SHA256 &&other) noexcept;
SHA256 &operator=(const SHA256 &other);
void Update(const Byte *data, UInt_64 len);
void Final(Byte hash[32]);
void Hash(const Byte *data, UInt_64 len, Byte hash[32]);
private:
void Transform(const Byte data[64]);
};
}

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,22 +42,22 @@ 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.
/// @param [in] str The C-style string. /// @param [in] str The C-style string.
/// @param [in] size The size of the given C-style string. /// @param [in] size The size of the given C-style string.
Str(const T* const str, const N size) Str(const T* const str, const N size)
: size((size) ? size : Len(str)), data(nullptr) : size(size), data(nullptr)
{ {
if (!size)
return;
data = new T[this->size + 1]; data = new T[this->size + 1];
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 +70,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 +78,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 +91,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 +103,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 +121,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;
@@ -925,10 +917,10 @@ namespace ehs
} }
/// Splits a string into a Vector with the given separator. /// Splits a string into a Vector with the given separator.
/// @param [in] ide The given string as the separator. /// @param [in] delimeter The given string as the separator.
/// @param [in] max The max amount of times to split the string. /// @param [in] max The max amount of times to split the string.
/// @returns The resulting string object. /// @returns The resulting string object.
Vector<Str<T, N>, N> Split(const Str<T, N>& ide, const N max = 0) const Vector<Str<T, N>, N> Split(const Str<T, N>& delimeter, const N max = 0) const
{ {
Vector<Str<T, N>, N> result(0, 5); Vector<Str<T, N>, N> result(0, 5);
@@ -936,9 +928,9 @@ namespace ehs
for (N i = 0, c = 0; i < size; ++i) for (N i = 0, c = 0; i < size; ++i)
{ {
if (data[i] == ide[c]) if (data[i] == delimeter[c])
{ {
if (++c == ide.Size()) if (++c == delimeter.Size())
{ {
N r = i - (c - 1) - b; N r = i - (c - 1) - b;
if (!r) if (!r)
@@ -966,17 +958,17 @@ namespace ehs
} }
/// Removes all instances of the ide. /// Removes all instances of the ide.
/// @param [in] ide The string to look for. /// @param [in] delimeter The string to look for.
/// @returns The resulting string object. /// @returns The resulting string object.
Str<T, N> RemoveAll(const Str<T, N>& ide) const Str<T, N> RemoveAll(const Str<T, N>& delimeter) const
{ {
Str<T, N> result(size); Str<T, N> result(size);
for (N i = 0, b = 0, c = 0; i < size; ++i) for (N i = 0, b = 0, c = 0; i < size; ++i)
{ {
if (data[i] == ide[c]) if (data[i] == delimeter[c])
{ {
if (++c == ide.Size()) if (++c == delimeter.Size())
c = 0; c = 0;
} }
else else
@@ -995,18 +987,18 @@ namespace ehs
} }
/// Replaces all instances of ide with the replacer. /// Replaces all instances of ide with the replacer.
/// @param [in] ide The string to look for. /// @param [in] delimeter The string to look for.
/// @param [in] replacer The string placed. /// @param [in] replacer The string placed.
/// @returns The resulting string object. /// @returns The resulting string object.
Str ReplaceAll(const Str& ide, const Str& replacer) const Str ReplaceAll(const Str& delimeter, const Str& replacer) const
{ {
Str<T, N> result; Str<T, N> result;
for (N i = 0, b = 0; i < size; ++i) for (N i = 0, b = 0; i < size; ++i)
{ {
if (data[i] == ide[b]) if (data[i] == delimeter[b])
{ {
if (++b == ide.Size()) if (++b == delimeter.Size())
{ {
result.Push(replacer); result.Push(replacer);
b = 0; b = 0;
@@ -1022,20 +1014,20 @@ namespace ehs
} }
/// Finds the first instance of the given string object. /// Finds the first instance of the given string object.
/// @param [in] ide The string to look for. /// @param [in] delimeter The string to look for.
/// @param [out] index The index of the string found. Can be a nullptr. /// @param [out] index The index of the string found. Can be a nullptr.
/// @param [in] pattern The search pattern for optimization. /// @param [in] pattern The search pattern for optimization.
/// @param [in] result What index to return where the first instance is found. /// @param [in] result What index to return where the first instance is found.
/// @returns The index where the instance was found with the result varying from the result parameter. /// @returns The index where the instance was found with the result varying from the result parameter.
bool Find(const Str<T, N> &ide, N* const index = nullptr, const SearchPattern pattern = SearchPattern::LEFT_RIGHT, const IndexResult result = IndexResult::BEGINNING) const bool Find(const Str<T, N> &delimeter, N* const index = nullptr, const SearchPattern pattern = SearchPattern::LEFT_RIGHT, const IndexResult result = IndexResult::BEGINNING) const
{ {
if (pattern == SearchPattern::LEFT_RIGHT) if (pattern == SearchPattern::LEFT_RIGHT)
{ {
for (N i = 0, c = 0; i < size; ++i) for (N i = 0, c = 0; i < size; ++i)
{ {
if (data[i] == ide[c]) if (data[i] == delimeter[c])
{ {
if (++c == ide.Size()) if (++c == delimeter.Size())
{ {
if (result == IndexResult::BEGINNING) if (result == IndexResult::BEGINNING)
{ {
@@ -1057,16 +1049,16 @@ namespace ehs
} }
else if (pattern == SearchPattern::RIGHT_LEFT) else if (pattern == SearchPattern::RIGHT_LEFT)
{ {
for (N i = size, c = ide.Size(); i > 0; --i) for (N i = size, c = delimeter.Size(); i > 0; --i)
{ {
if (data[i - 1] == ide[c - 1]) if (data[i - 1] == delimeter[c - 1])
{ {
if (--c == 0) if (--c == 0)
{ {
if (result == IndexResult::BEGINNING) if (result == IndexResult::BEGINNING)
{ {
if (index) if (index)
*index = i - (ide.Size() - 1); *index = i - (delimeter.Size() - 1);
return true; return true;
} }
@@ -1086,18 +1078,18 @@ namespace ehs
} }
/// Checks if the current string contains the given ide. /// Checks if the current string contains the given ide.
/// @param [in] ide The given ide to check for. /// @param [in] delimeter The given ide to check for.
/// @param [in] pattern The search pattern to use. /// @param [in] pattern The search pattern to use.
/// @returns True if the current string does contain the ide. /// @returns True if the current string does contain the ide.
bool Contains(const Str<T, N>& ide, const SearchPattern pattern = SearchPattern::LEFT_RIGHT) const bool Contains(const Str<T, N>& delimeter, const SearchPattern pattern = SearchPattern::LEFT_RIGHT) const
{ {
if (pattern == SearchPattern::LEFT_RIGHT) if (pattern == SearchPattern::LEFT_RIGHT)
{ {
for (N i = 0, c = 0; i < size; ++i) for (N i = 0, c = 0; i < size; ++i)
{ {
if (data[i] == ide[c]) if (data[i] == delimeter[c])
{ {
if (++c == ide.Size()) if (++c == delimeter.Size())
{ {
return true; return true;
} }
@@ -1106,9 +1098,9 @@ namespace ehs
} }
else if (pattern == SearchPattern::RIGHT_LEFT) else if (pattern == SearchPattern::RIGHT_LEFT)
{ {
for (N i = size, c = ide.Size(); i > 0; --i) for (N i = size, c = delimeter.Size(); i > 0; --i)
{ {
if (data[i - 1] == ide[c - 1]) if (data[i - 1] == delimeter[c - 1])
{ {
if (--c == 0) if (--c == 0)
{ {
@@ -1121,6 +1113,54 @@ namespace ehs
return false; return false;
} }
Vector<Str> ParseArgs() const
{
Vector<Str> args;
T *quoteStart = nullptr;
T *spaceStart = nullptr;
for (T *i = data; i <= data + size; ++i)
{
if (*i == '\"' && !spaceStart)
{
if (quoteStart)
{
args.Push(Str(quoteStart, i - quoteStart));
quoteStart = nullptr;
}
else
{
if (i + 1 < &data[size - 1])
quoteStart = i + 1;
else
args.Push({});
}
}
else if (*i == ' ' && !quoteStart)
{
if (spaceStart)
{
args.Push(Str(spaceStart, i - spaceStart));
spaceStart = i + 1;
}
else
{
if (i + 1 < &data[size - 1])
spaceStart = i + 1;
else
args.Push({});
}
}
}
if (quoteStart)
args.Push(Str(quoteStart, &data[size - 1] - (quoteStart - 1)));
else if (spaceStart)
args.Push(Str(spaceStart, &data[size - 1] - (spaceStart - 1)));
return args;
}
/// Checks if the string represents a number. Must not have any alphabetical characters. /// Checks if the string represents a number. Must not have any alphabetical characters.
/// @returns The result. /// @returns The result.
bool IsNum() const bool IsNum() const
@@ -1879,6 +1919,9 @@ namespace ehs
/// @returns The character count. /// @returns The character count.
static N Len(const T* const str) static N Len(const T* const str)
{ {
if (!str)
return 0;
N count = 0; N count = 0;
while (str[count]) while (str[count])
++count; ++count;

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;
@@ -402,7 +392,7 @@ namespace ehs
{ {
if (stride) if (stride)
{ {
rawSize = (this->size + size()) / stride * stride; rawSize = (this->size + size) / stride * stride;
if ((this->size + size) % stride) if ((this->size + size) % stride)
rawSize += stride; rawSize += stride;
} }
@@ -413,7 +403,7 @@ namespace ehs
T* result = new T[rawSize]; T* result = new T[rawSize];
for (N i = 0; i < size; ++i) for (N i = 0; i < this->size; ++i)
result[i] = std::move(data[i]); result[i] = std::move(data[i]);
delete[] data; delete[] data;

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

@@ -5,5 +5,5 @@
#if defined(EHS_OS_WINDOWS) #if defined(EHS_OS_WINDOWS)
#include "AudioDevice_W32.h" #include "AudioDevice_W32.h"
#elif defined(EHS_OS_LINUX) #elif defined(EHS_OS_LINUX)
#include "AudioDevice_ALSA.h" #include "AudioDevice_PW.h"
#endif #endif

View File

@@ -1,46 +0,0 @@
#pragma once
#include "ehs/EHS.h"
#include "BaseAudioDevice.h"
#include <alsa/asoundlib.h>
namespace ehs
{
class EHS_LIB_IO AudioDevice : public BaseAudioDevice
{
private:
snd_pcm_t* hdl;
public:
~AudioDevice() override;
AudioDevice();
AudioDevice(AudioDevice&& device) noexcept;
AudioDevice(const AudioDevice& device);
AudioDevice& operator=(AudioDevice&& device) noexcept;
AudioDevice& operator=(const AudioDevice& device);
void Release() override;
void OpenStream() override;
void CloseStream() override;
UInt_64 GetAvailFrames() const override;
Byte* Map(UInt_64* offset, UInt_64* frames) override;
void UnMap(const UInt_64 offset, const UInt_64 frames) override;
bool IsValid() const override;
static AudioDevice GetDefault(const AudioDeviceType type);
static Array<AudioDevice> Get(const AudioDeviceType type, const AudioDeviceState state);
};
}

View File

@@ -0,0 +1,68 @@
#pragma once
#include "ehs/EHS.h"
#include "BaseAudioDevice.h"
#include <pipewire/pipewire.h>
#include <pipewire/loop.h>
#include <pipewire/context.h>
#include <pipewire/stream.h>
#include <spa/param/audio/format-utils.h>
namespace ehs
{
class EHS_LIB_IO AudioDevice final : public BaseAudioDevice
{
private:
static Array<AudioDevice> devices;
static AudioDevice defOut;
static AudioDevice defIn;
UInt_32 id;
Str_8 name;
pw_loop *loop;
pw_context *context;
pw_core *core;
pw_stream *input;
pw_stream *output;
spa_hook paramsHook;
static void RegistryEventGlobal(void *data, UInt_32 id, UInt_32 permissions, const char *type, UInt_32 version, const spa_dict *props);
static void RegistryEventGlobalRemove(void *data, UInt_32 id);
static void OnParamChanged(void *data, UInt_32 id, const spa_pod *param);
public:
~AudioDevice() override;
AudioDevice();
AudioDevice(AudioDevice&& device) noexcept;
AudioDevice(const AudioDevice& device);
AudioDevice& operator=(AudioDevice&& device) noexcept;
AudioDevice& operator=(const AudioDevice& device);
void OpenStream() override;
void CloseStream() override;
UInt_64 SendStream(const void *data, UInt_64 size) override;
UInt_64 ReceiveStream(void *data, UInt_64 size) override;
bool IsStreaming() const override;
bool IsValid() const override;
static AudioDevice GetDefault(AudioDeviceType type);
static Array<AudioDevice> Get(AudioDeviceType type, AudioDeviceState state);
private:
Str_8 GetCategory() const;
};
}

View File

@@ -12,7 +12,7 @@ struct IMMDevice;
namespace ehs namespace ehs
{ {
class EHS_LIB_IO AudioDevice : public BaseAudioDevice class EHS_LIB_IO AudioDevice final : public BaseAudioDevice
{ {
private: private:
IMMDevice* hdl; IMMDevice* hdl;
@@ -33,17 +33,13 @@ namespace ehs
AudioDevice& operator=(const AudioDevice& device); AudioDevice& operator=(const AudioDevice& device);
void Release() override;
void OpenStream() override; void OpenStream() override;
void CloseStream() override; void CloseStream() override;
UInt_64 GetAvailFrames() const override; UInt_64 SendStream(const void *data, UInt_64 outFrameSize) override;
Byte* Map(UInt_64* offset, UInt_64* frames) override; UInt_64 ReceiveStream(void *data, UInt_64 inFrameSize) override;
void UnMap(const UInt_64 offset, const UInt_64 frames) override;
Str_32 GetInterfaceName_32() const; Str_32 GetInterfaceName_32() const;
@@ -57,10 +53,12 @@ namespace ehs
Str_8 GetName_8() const; Str_8 GetName_8() const;
bool IsStreaming() const override;
bool IsValid() const override; bool IsValid() const override;
static AudioDevice GetDefault(const AudioDeviceType type); static AudioDevice GetDefault(AudioDeviceType type);
static Array<AudioDevice> Get(const AudioDeviceType type, const AudioDeviceState state); static Array<AudioDevice> Get(AudioDeviceType type, AudioDeviceState state);
}; };
} }

View File

@@ -10,8 +10,8 @@ namespace ehs
{ {
enum class AudioDeviceType enum class AudioDeviceType
{ {
OUTPUT = 0x0,
INPUT = 0x1, INPUT = 0x1,
OUTPUT = 0x0,
ALL = 0x2 ALL = 0x2
}; };
@@ -28,13 +28,12 @@ namespace ehs
protected: protected:
AudioDeviceType type; AudioDeviceType type;
DataType dataType; DataType dataType;
UInt_16 bitDepth; UInt_16 byteDepth;
UInt_32 sampleRate; UInt_32 sampleRate;
UInt_32 channels; UInt_32 channels;
UInt_32 period; UInt_32 period;
UInt_32 latency; UInt_32 latency;
UInt_64 maxFrames; UInt_64 maxFrames;
bool streaming;
public: public:
virtual ~BaseAudioDevice() = default; virtual ~BaseAudioDevice() = default;
@@ -45,21 +44,21 @@ namespace ehs
BaseAudioDevice& operator=(const BaseAudioDevice& device); BaseAudioDevice& operator=(const BaseAudioDevice& device);
virtual void Release();
virtual void OpenStream(); virtual void OpenStream();
virtual void CloseStream(); virtual void CloseStream();
virtual UInt_64 GetAvailFrames() const; virtual UInt_64 SendStream(const void *data, UInt_64 size);
virtual Byte* Map(UInt_64* offset, UInt_64* frames); virtual UInt_64 ReceiveStream(void *data, UInt_64 size);
virtual void UnMap(const UInt_64 offset, const UInt_64 frames); void BridgeStreams(BaseAudioDevice *input, UInt_64 frameBufferSize);
void BridgeStreams(UInt_64 frameBufferSize);
AudioDeviceType GetType() const; AudioDeviceType GetType() const;
void SetDataType(const DataType newDataType); void SetDataType(DataType newDataType);
DataType GetDataType() const; DataType GetDataType() const;
@@ -67,39 +66,39 @@ namespace ehs
UInt_16 GetBitDepth() const; UInt_16 GetBitDepth() const;
void SetSampleRate(const UInt_32 newSampleRate); void SetSampleRate(UInt_32 newSampleRate);
UInt_32 GetSampleRate() const; UInt_32 GetSampleRate() const;
void SetChannels(const UInt_32 newChannels); void SetChannels(UInt_32 newChannels);
UInt_16 GetChannels() const; UInt_16 GetChannels() const;
UInt_32 GetFrameSize() const; UInt_32 GetFrameSize() const;
void SetPeriod(const UInt_32 newPeriod); void SetPeriod(UInt_32 newPeriod);
UInt_32 GetPeriod() const; UInt_32 GetPeriod() const;
void SetLatency(const UInt_32 newLatency); void SetLatency(UInt_32 newLatency);
UInt_32 GetLatency() const; UInt_32 GetLatency() const;
UInt_64 GetMaxFrames() const; UInt_64 GetMaxFrames() const;
bool IsStreaming() const; virtual bool IsStreaming() const;
virtual bool IsValid() const; virtual bool IsValid() const;
/// Retrieves the default audio input/output device. /// Retrieves the default audio input/output device.
/// @param [in] type The audio device type to retrieve. /// @param [in] type The audio device type to retrieve.
/// @param [out] device The default audio device. /// @param [out] device The default audio device.
static BaseAudioDevice GetDefault(const AudioDeviceType type); static BaseAudioDevice GetDefault(AudioDeviceType type);
/// Retrieves a list of audio input/output devices. /// Retrieves a list of audio input/output devices.
/// @param [in] type The audio device type to retrieve. /// @param [in] type The audio device type to retrieve.
/// @param [in] state The audio device state to retrieve. /// @param [in] state The audio device state to retrieve.
/// @param [out] devices The list of audio devices. /// @param [out] devices The list of audio devices.
static Array<BaseAudioDevice> Get(const AudioDeviceType type, const AudioDeviceState state); static Array<BaseAudioDevice> Get(AudioDeviceType type, AudioDeviceState state);
}; };
} }

View File

@@ -8,24 +8,30 @@ namespace ehs
class EHS_LIB_IO Button class EHS_LIB_IO Button
{ {
private: private:
Str_8 name;
UInt_32 hash; UInt_32 hash;
Str_8 name;
public: public:
Button(); Button();
Button(const Str_8& name); Button(Str_8 name);
Button(const Button& key); Button(Button &&key) noexcept;
Button& operator=(const Button& key); Button(const Button &key);
bool operator==(const Button& key) const; Button &operator=(Button &&key) noexcept;
bool operator!=(const Button& key) const; Button &operator=(const Button &key);
bool operator==(const Button &key) const;
bool operator!=(const Button &key) const;
UInt_32 GetHash() const;
Str_8 GetName() const; Str_8 GetName() const;
UInt_32 GetHash() const; bool IsValid() const;
}; };
} }

View File

@@ -15,11 +15,17 @@ namespace ehs
Str_8 name; Str_8 name;
UInt_64 id; UInt_64 id;
Array<ButtonState> states; Array<ButtonState> states;
Button lastState;
float heldTime;
float activateTime;
bool active;
public: public:
virtual ~HID() = default;
HID(); HID();
HID(const UInt_8 type, Str_8 name, const UInt_64 id); HID(UInt_8 type, Str_8 name, UInt_64 id);
HID(HID&& hid) noexcept; HID(HID&& hid) noexcept;
@@ -33,11 +39,11 @@ namespace ehs
bool operator!=(const HID& other) const; bool operator!=(const HID& other) const;
bool operator==(const UInt_64 otherId) const; bool operator==(UInt_64 otherId) const;
bool operator!=(const UInt_64 otherId) const; bool operator!=(UInt_64 otherId) const;
virtual void Poll(); virtual void Poll(float delta);
UInt_8 GetType() const; UInt_8 GetType() const;
@@ -71,6 +77,10 @@ namespace ehs
const ButtonState* IsUp() const; const ButtonState* IsUp() const;
const ButtonState *IsPressed(const Button &button);
const ButtonState *GetPressed();
void ButtonDown(const Button& button); void ButtonDown(const Button& button);
void ButtonUp(const Button& button); void ButtonUp(const Button& button);
@@ -87,5 +97,11 @@ namespace ehs
bool AddState(const ButtonState& state); bool AddState(const ButtonState& state);
ButtonState* GetState(const Button& button); ButtonState* GetState(const Button& button);
bool TickHoldTime(float delta);
void ResetTime();
void TickActivateTime(float delta);
}; };
} }

View File

@@ -10,6 +10,8 @@ namespace ehs
private: private:
UInt_64 hashId; UInt_64 hashId;
Str_8 id; Str_8 id;
UInt_64 start;
UInt_64 delta;
protected: protected:
Array<HID*> devices; Array<HID*> devices;
@@ -29,9 +31,9 @@ namespace ehs
InputHandler& operator=(const InputHandler& ih); InputHandler& operator=(const InputHandler& ih);
bool operator==(const UInt_64 otherHashId); bool operator==(const UInt_64 otherHashId) const;
bool operator!=(const UInt_64 otherHashId); bool operator!=(const UInt_64 otherHashId) const;
virtual bool Initialize(); virtual bool Initialize();

View File

@@ -23,96 +23,96 @@ namespace ehs
Keyboard& operator=(const Keyboard& hid); Keyboard& operator=(const Keyboard& hid);
void Poll() override; void Poll(float delta) override;
Keyboard* Clone() const override; Keyboard* Clone() const override;
static const Button Unknown; static inline const Button Unknown = Button("Unknown");
static const Button Escape; static inline const Button Escape = Button("Escape Button");
static const Button Backspace; static inline const Button Backspace = Button("Backspace Button");
static const Button Enter; static inline const Button Enter = Button("Enter Button");
static const Button LShift; static inline const Button LShift = Button("Left Shift Button");
static const Button RShift; static inline const Button RShift = Button("Right Shift Button");
static const Button LAlt; static inline const Button LAlt = Button("Left Alt Button");
static const Button RAlt; static inline const Button RAlt = Button("Right Alt Button");
static const Button LCtrl; static inline const Button LCtrl = Button("Left Control Button");
static const Button RCtrl; static inline const Button RCtrl = Button("Right Button");
static const Button Space; static inline const Button Space = Button("Space Button");
static const Button A; static inline const Button A = Button("A Button");
static const Button B; static inline const Button B = Button("B Button");
static const Button C; static inline const Button C = Button("C Button");
static const Button D; static inline const Button D = Button("D Button");
static const Button E; static inline const Button E = Button("E Button");
static const Button F; static inline const Button F = Button("F Button");
static const Button G; static inline const Button G = Button("G Button");
static const Button H; static inline const Button H = Button("H Button");
static const Button I; static inline const Button I = Button("I Button");
static const Button J; static inline const Button J = Button("J Button");
static const Button K; static inline const Button K = Button("K Button");
static const Button L; static inline const Button L = Button("L Button");
static const Button M; static inline const Button M = Button("M Button");
static const Button N; static inline const Button N = Button("N Button");
static const Button O; static inline const Button O = Button("O Button");
static const Button P; static inline const Button P = Button("P Button");
static const Button Q; static inline const Button Q = Button("Q Button");
static const Button R; static inline const Button R = Button("R Button");
static const Button S; static inline const Button S = Button("S Button");
static const Button T; static inline const Button T = Button("T Button");
static const Button U; static inline const Button U = Button("U Button");
static const Button V; static inline const Button V = Button("V Button");
static const Button W; static inline const Button W = Button("W Button");
static const Button X; static inline const Button X = Button("X Button");
static const Button Y; static inline const Button Y = Button("Y Button");
static const Button Z; static inline const Button Z = Button("Z Button");
static const Button One; static inline const Button One = Button("One Button");
static const Button Two; static inline const Button Two = Button("Two Button");
static const Button Three; static inline const Button Three = Button("Three Button");
static const Button Four; static inline const Button Four = Button("Four Button");
static const Button Five; static inline const Button Five = Button("Five Button");
static const Button Six; static inline const Button Six = Button("Six Button");
static const Button Seven; static inline const Button Seven = Button("Seven Button");
static const Button Eight; static inline const Button Eight = Button("Eight Button");
static const Button Nine; static inline const Button Nine = Button("Nine Button");
static const Button Zero; static inline const Button Zero = Button("Zero Button");
static const Button Minus; static inline const Button Minus = Button("Minus Button");
static const Button Equals; static inline const Button Equals = Button("Equals Button");
static const Button Tilde; static inline const Button Tilde = Button("Tilde Button");
static const Button BackSlash; static inline const Button BackSlash = Button("Back Slash Button");
static const Button LeftSquareBracket; static inline const Button LeftSquareBracket = Button("Left Square Bracket Button");
static const Button RightSquareBracket; static inline const Button RightSquareBracket = Button("Right Square Bracket Button");
static const Button SemiColon; static inline const Button SemiColon = Button("Semi Colon Button");
static const Button Apostrophe; static inline const Button Apostrophe = Button("Apostrophe Button");
static const Button Comma; static inline const Button Comma = Button("Comma Button");
static const Button Period; static inline const Button Period = Button("Period Button");
static const Button ForwardSlash; static inline const Button ForwardSlash = Button("Forward Slash Button");
static const Button F1; static inline const Button F1 = Button("Function One Button");
static const Button F2; static inline const Button F2 = Button("Function Two Button");
static const Button F3; static inline const Button F3 = Button("Function Three Button");
static const Button F4; static inline const Button F4 = Button("Function Four Button");
static const Button F5; static inline const Button F5 = Button("Function Five Button");
static const Button F6; static inline const Button F6 = Button("Function Six Button");
static const Button F7; static inline const Button F7 = Button("Function Seven Button");
static const Button F8; static inline const Button F8 = Button("Function Eight Button");
static const Button F9; static inline const Button F9 = Button("Function Nine Button");
static const Button F10; static inline const Button F10 = Button("Function Ten Button");
static const Button F11; static inline const Button F11 = Button("Function Eleven Button");
static const Button F12; static inline const Button F12 = Button("Function Twelve Button");
static const Button F13; static inline const Button F13 = Button("Function Thirteen Button");
static const Button F14; static inline const Button F14 = Button("Function Fourteen Button");
static const Button F15; static inline const Button F15 = Button("Function Fifteen Button");
static const Button F16; static inline const Button F16 = Button("Function Sixteen Button");
static const Button F17; static inline const Button F17 = Button("Function Seventeen Button");
static const Button F18; static inline const Button F18 = Button("Function Eighteen Button");
static const Button F19; static inline const Button F19 = Button("Function Nineteen Button");
static const Button F20; static inline const Button F20 = Button("Function Twenty Button");
static const Button F21; static inline const Button F21 = Button("Function Twenty One Button");
static const Button F22; static inline const Button F22 = Button("Function Twenty Two Button");
static const Button F23; static inline const Button F23 = Button("Function Twenty Three Button");
static const Button F24; static inline const Button F24 = Button("Function Twenty Four Button");
static const Button Left; static inline const Button Left = Button("Left Button");
static const Button Right; static inline const Button Right = Button("Right Button");
static const Button Up; static inline const Button Up = Button("Up Button");
static const Button Down; static inline const Button Down = Button("Down Button");
static Button TranslateScanCode(UInt_32 code); static Button TranslateScanCode(UInt_32 code);

View File

@@ -19,7 +19,7 @@ namespace ehs
public: public:
Mouse(); Mouse();
Mouse(Str_8 name, const UInt_64 id); Mouse(Str_8 name, UInt_64 id);
Mouse(Mouse&& hid) noexcept = default; Mouse(Mouse&& hid) noexcept = default;
@@ -29,7 +29,7 @@ namespace ehs
Mouse& operator=(const Mouse& hid); Mouse& operator=(const Mouse& hid);
void Poll() override; void Poll(float delta) override;
void SetDelta(const Vec2_s32& newDelta); void SetDelta(const Vec2_s32& newDelta);
@@ -37,18 +37,18 @@ namespace ehs
Mouse* Clone() const override; Mouse* Clone() const override;
static const Button Unknown; static inline const Button Unknown = Button("Unknown Button");
static const Button LMB; static inline const Button LMB = Button("Left Mouse Button");
static const Button MMB; static inline const Button MMB = Button("Middle Mouse Button");
static const Button RMB; static inline const Button RMB = Button("Right Mouse Button");
static const Button Four; static inline const Button Four = Button("Four Button");
static const Button Five; static inline const Button Five = Button("Five Button");
static const Button ScrollUp; static inline const Button ScrollUp = Button("Scroll Up Button");
static const Button ScrollDown; static inline const Button ScrollDown = Button("Scroll Down Button");
static const Button ScrollLeft; static inline const Button ScrollLeft = Button("Scroll Left Button");
static const Button ScrollRight; static inline const Button ScrollRight = Button("Scroll Right Button");
static const Button Back; static inline const Button Back = Button("Back Button");
static const Button Forward; static inline const Button Forward = Button("Forward Button");
static Button TranslateXCB(const UInt_32 code); static Button TranslateXCB(const UInt_32 code);
}; };

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;
@@ -24,9 +24,9 @@ namespace ehs
bool connected; bool connected;
public: public:
static const UInt_16 HTTPS_Port = 443; static constexpr UInt_16 HTTPS_Port = 443;
static const UInt_16 HTTP_Port = 80; static constexpr UInt_16 HTTP_Port = 80;
static const UInt_16 MaxHeaderSize = 8192; static constexpr UInt_16 MaxHeaderSize = 8192;
virtual ~BaseTCP() = default; virtual ~BaseTCP() = default;
@@ -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;
@@ -55,7 +55,7 @@ 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(const Str_8& address, UInt_16 port) = 0; virtual void Bind(Str_8 address, const UInt_16 &port) = 0;
/// Listens for new incoming connections. /// Listens for new incoming connections.
/// @note Used for servers. /// @note Used for servers.
@@ -63,13 +63,13 @@ namespace ehs
/// Accepts the new incoming connection. /// Accepts the new incoming connection.
/// @note Used for servers. /// @note Used for servers.
virtual BaseTCP* Accept() = 0; virtual BaseTCP *Accept() = 0;
/// Connects to a server at the specified address and port. /// Connects to a server at the specified address and port.
/// @param [in] address The ip address to connect to. /// @param [in] address The ip address to connect to.
/// @param [in] port The port to connect to. /// @param [in] port The port to connect to.
/// @note Used for clients. /// @note Used for clients.
virtual void Connect(const Str_8& address, UInt_16 port) = 0; virtual void Connect(Str_8 address, const UInt_16 &port) = 0;
/// Sends data to the connected endpoint. /// Sends data to the connected endpoint.
/// @param [in] buffer The data to send to the endpoint. /// @param [in] buffer The data to send to the endpoint.
@@ -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.
@@ -150,6 +150,8 @@ namespace ehs
virtual bool IsIPv6Only() const = 0; virtual bool IsIPv6Only() const = 0;
virtual void SetReuse(const bool &enabled) = 0;
/// Retrieves whether or not this socket was initialized. /// Retrieves whether or not this socket was initialized.
/// @returns The result. /// @returns The result.
virtual bool IsValid() const = 0; virtual bool IsValid() const = 0;

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,45 @@
#pragma once
#include "ehs/Str.h"
namespace ehs
{
class HeaderVar
{
private:
UInt_64 id;
Str_8 name;
Str_8 value;
public:
HeaderVar();
HeaderVar(Str_8 name, Str_8 value);
HeaderVar(HeaderVar &&other) noexcept;
HeaderVar(const HeaderVar &other);
HeaderVar &operator=(HeaderVar &&other) noexcept;
HeaderVar &operator=(const HeaderVar &other);
bool operator==(const HeaderVar &other) const;
bool operator!=(const HeaderVar &other) const;
bool operator==(const UInt_64 &otherId) const;
bool operator!=(const UInt_64 &otherId) const;
UInt_64 GetId() const;
Str_8 GetName() const;
Str_8 GetValue() const;
void SetValue(Str_8 value);
Str_8 ToStr() 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

@@ -0,0 +1,45 @@
#pragma once
#include "ehs/Str.h"
namespace ehs
{
class QueryVar
{
private:
UInt_64 id;
Str_8 name;
Str_8 value;
public:
QueryVar();
QueryVar(Str_8 name, Str_8 value);
QueryVar(QueryVar &&other) noexcept;
QueryVar(const QueryVar &other);
QueryVar &operator=(QueryVar &&other) noexcept;
QueryVar &operator=(const QueryVar &other);
bool operator==(const QueryVar &other) const;
bool operator!=(const QueryVar &other) const;
bool operator==(const UInt_64 &otherId) const;
bool operator!=(const UInt_64 &otherId) const;
UInt_64 GetId() const;
Str_8 GetName() const;
Str_8 GetValue() const;
void SetValue(Str_8 value);
Str_8 ToStr() const;
};
}

View File

@@ -5,6 +5,8 @@
#include "ehs/Str.h" #include "ehs/Str.h"
#include "ehs/json/Json.h" #include "ehs/json/Json.h"
#include "Socket.h" #include "Socket.h"
#include "QueryVar.h"
#include "HeaderVar.h"
namespace ehs namespace ehs
{ {
@@ -21,8 +23,8 @@ namespace ehs
private: private:
Verb verb; Verb verb;
Str_8 rsrc; Str_8 rsrc;
Vector<Str_8> queries; Vector<QueryVar> queries;
Vector<Str_8> header; Vector<HeaderVar> header;
ContentType cType; ContentType cType;
Str_8 body; Str_8 body;
@@ -33,25 +35,34 @@ namespace ehs
/// Initializes this request with a given verb and URI resource. /// Initializes this request with a given verb and URI resource.
/// @param [in] verb The type of request to make. /// @param [in] verb The type of request to make.
/// @param [in] rsrc The URI endpoint to make the request at. /// @param [in] rsrc The URI endpoint to make the request at.
Request(const Verb verb, const Str_8& rsrc); Request(const Verb &verb, Str_8 rsrc);
/// Initializes this request with the raw request data. /// Initializes this request with the raw request data.
/// @param [in] data The C-style string of the request. /// @param [in] data The C-style string of the request.
/// @param [in] size The size of the given C-style string. /// @param [in] size The size of the given C-style string.
Request(const char* data, const UInt_64 size); Request(const char *data, const UInt_64 &size);
/// Initializes this request with the raw request data. /// Initializes this request with the raw request data.
/// @param [in] data The string of the request. /// @param [in] data The string of the request.
Request(const Str_8& data); Request(const Str_8 &data);
/// Moves members from another object of the same type.
/// @param [in] other The object to move from.
Request(Request &&other) noexcept;
/// Copies members from another object of the same type. /// Copies members from another object of the same type.
/// @param [in] req The object to copy from. /// @param [in] other The object to copy from.
Request(const Request& req) = default; Request(const Request &other);
/// Moves members from another object of the same type.
/// @param [in] other The object to move from.
/// @returns The request that has been assigned to.
Request& operator=(Request &&other) noexcept;
/// Copies members from another object of the same type. /// Copies members from another object of the same type.
/// @param [in] req The object to copy from. /// @param [in] other The object to copy from.
/// @returns The request that has been assigned to. /// @returns The request that has been assigned to.
Request& operator=(const Request& req); Request& operator=(const Request &other);
/// Retrieves the verb for the request. /// Retrieves the verb for the request.
/// @returns The result. /// @returns The result.
@@ -59,7 +70,7 @@ namespace ehs
/// Sets the content type for the body. /// Sets the content type for the body.
/// @param [in] cType The content type to use. /// @param [in] cType The content type to use.
void SetContentType(const ContentType cType); void SetContentType(const ContentType &cType);
/// Retrieves the content type for the body. /// Retrieves the content type for the body.
/// @returns The result. /// @returns The result.
@@ -67,75 +78,145 @@ namespace ehs
/// Sets the URI resource. /// Sets the URI resource.
/// @param [in] rsrc The resource. /// @param [in] rsrc The resource.
void SetResource(const Str_8& rsrc); void SetResource(Str_8 rsrc);
/// Retrieves the URI resource. /// Retrieves the URI resource.
/// @returns The result. /// @returns The result.
Str_8 GetResource() const; Str_8 GetResource() const;
/// Adds a query variable to the URI. /// Checks whether a header variable exists using the id.
/// @param [in] var The variable identifier. /// @param [in] id The variable id to look for.
/// @param [in] value The value of the variable. /// @returns True if the variable exists. False otherwise.
void AddQuery(const Str_8& var, const Str_8& value); bool HasQueryVar(const UInt_64 &id) const;
/// Retrieves a query variable from the URI. /// Checks whether a header variable exists using the name.
/// @param [in] var The variable identifier to look for. /// @param [in] name The variable name to look for.
/// @returns The value of the query variable. Empty if it was not found. /// @returns True if the variable exists. False otherwise.
Str_8 GetQuery(const Str_8& var); bool HasQueryVar(const Str_8 &name) const;
/// Adds a header variable.
/// @param [in] var The variable to add to the header.
/// @returns False if the given variable name already exists. True otherwise.
bool AddQueryVar(QueryVar var);
/// Removes a header variable using the id.
/// @param [in] id The variable id to look for.
/// @returns True if the variable was found. False otherwise.
bool RemoveQueryVar(const UInt_64 &id);
/// Removes a header variable using the name.
/// @param [in] name The variable name to look for.
/// @returns True if the variable was found. False otherwise.
bool RemoveQueryVar(const Str_8 &name);
/// Retrieves a header variable using the id.
/// @param [in] id The variable id to look for.
/// @returns The variable object if found. Nullptr otherwise.
QueryVar *GetQueryVar(const UInt_64 &id) const;
/// Retrieves a header variable using the name.
/// @param [in] name The variable name to look for.
/// @returns The variable object if found. Nullptr otherwise.
QueryVar *GetQueryVar(const Str_8& name) const;
/// Retrieves a header variable value using the id.
/// @param [in] id The variable id to look for.
/// @returns The variable's value if found. Empty otherwise.
Str_8 GetQueryValue(const UInt_64 &id) const;
/// Retrieves a header variable value using the name.
/// @param [in] name The variable name to look for.
/// @returns The variable's value if found. Empty otherwise.
Str_8 GetQueryValue(const Str_8& name) const;
/// Retrieves all the query variables from the URI in a vector object. /// Retrieves all the query variables from the URI in a vector object.
/// @returns The result. /// @returns The result.
Vector<Str_8> GetQueries() const; Vector<QueryVar> GetQueries() const;
/// A helper method to automatically add the required header variables for basic authentication. /// A helper method to automatically add the required header variables for basic authentication.
/// @param [in] id The username or id. /// @param [in] id The username or id.
/// @param [in] secret The secret given by an API. /// @param [in] secret The secret given by an API.
void BasicAuth(const Str_8& id, const Str_8& secret); void BasicAuth(const Str_8 &id, const Str_8 &secret);
/// A helper method to automatically add the required header variables for bearer authentication. /// A helper method to automatically add the required header variables for bearer authentication.
/// @param [in] token The token given by an API. /// @param [in] token The token given by an API.
void BearerAuth(const Str_8& token); void BearerAuth(const Str_8 &token);
/// A helper method to automatically add the required header variables for bearer authentication. /// A helper method to automatically add the required header variables for bearer authentication.
/// @param [in] token The token given by an API. /// @param [in] token The token given by an API.
/// @param [in] clientId The client id given by an API. /// @param [in] clientId The client id given by an API.
void BearerAuth(const Str_8& token, const Str_8& clientId); void BearerAuth(const Str_8 &token, const Str_8 &clientId);
/// A helper method to automatically add the required header variables for bot authentication. /// A helper method to automatically add the required header variables for bot authentication.
/// @param [in] token The token given by an API. /// @param [in] token The token given by an API.
void BotAuth(const Str_8& token); void BotAuth(const Str_8 &token);
/// Checks whether a header variable exists using the id.
/// @param [in] id The variable id to look for.
/// @returns True if the variable exists. False otherwise.
bool HasHeaderVar(const UInt_64 &id) const;
/// Checks whether a header variable exists using the name.
/// @param [in] name The variable name to look for.
/// @returns True if the variable exists. False otherwise.
bool HasHeaderVar(const Str_8 &name) const;
/// Adds a header variable. /// Adds a header variable.
/// @param [in] var The variable identifier. /// @param [in] var The variable to add to the header.
/// @param [in] value The value of the variable. /// @returns False if the given variable name already exists. True otherwise.
void AddToHeader(const Str_8& var, const Str_8& value); bool AddHeaderVar(HeaderVar var);
/// Retrieves a header variable. /// Removes a header variable using the id.
/// @param [in] var The variable identifier to look for. /// @param [in] id The variable id to look for.
/// @returns The value of the header variable. Empty if it was not found. /// @returns True if the variable was found. False otherwise.
Str_8 GetHeader(const Str_8& var) const; bool RemoveHeaderVar(const UInt_64 &id);
/// Removes a header variable using the name.
/// @param [in] name The variable name to look for.
/// @returns True if the variable was found. False otherwise.
bool RemoveHeaderVar(const Str_8 &name);
/// Retrieves a header variable using the id.
/// @param [in] id The variable id to look for.
/// @returns The variable object if found. Nullptr otherwise.
HeaderVar *GetHeaderVar(const UInt_64 &id) const;
/// Retrieves a header variable using the name.
/// @param [in] name The variable name to look for.
/// @returns The variable object if found. Nullptr otherwise.
HeaderVar *GetHeaderVar(const Str_8& name) const;
/// Retrieves a header variable value using the id.
/// @param [in] id The variable id to look for.
/// @returns The variable's value if found. Empty otherwise.
Str_8 GetHeaderValue(const UInt_64 &id) const;
/// Retrieves a header variable value using the name.
/// @param [in] name The variable name to look for.
/// @returns The variable's value if found. Empty otherwise.
Str_8 GetHeaderValue(const Str_8& name) const;
/// Retrieves all the header variables in a vector object. /// Retrieves all the header variables in a vector object.
/// @returns The result. /// @returns The result.
Vector<Str_8> GetHeader() const; Vector<HeaderVar> GetHeader() const;
/// Adds a body variable. /// Adds a body variable.
/// @param [in] var The variable identifier. /// @param [in] var The variable identifier.
/// @param [in] value The value of the variable. /// @param [in] value The value of the variable.
void AddToBody(const Str_8& var, const Str_8& value); void AddToBody(const Str_8 &var, const Str_8 &value);
/// Adds a value to the body. /// Adds a value to the body.
/// @param [in] data The value to add. /// @param [in] data The value to add.
void AddToBody(const Str_8& data); void AddToBody(const Str_8 &data);
/// Sets the entire body. /// Sets the entire body.
/// @param [in] body The body to use. /// @param [in] body The body to use.
void SetBody(const Str_8& body); void SetBody(const Str_8 &body);
/// Retrieves a body variable. /// Retrieves a body variable.
/// @param [in] var The variable identifier to look for. /// @param [in] var The variable identifier to look for.
/// @returns The value of the body variable. Empty if it was not found. /// @returns The value of the body variable. Empty if it was not found.
Str_8 GetVar(const Str_8& var) const; Str_8 GetVar(const Str_8 &var) const;
/// Retrieves the entire body. /// Retrieves the entire body.
/// @returns The result. /// @returns The result.
@@ -152,13 +233,13 @@ namespace ehs
bool IsValid() const; bool IsValid() const;
private: private:
static Str_8 VerbToStr(const Verb verb); static Str_8 VerbToStr(const Verb &verb);
static Str_8 ContentTypeToStr(const ContentType cType); static Str_8 ContentTypeToStr(const ContentType &cType);
static ContentType StrToContentType(const Str_8& value); static ContentType StrToContentType(const Str_8 &value);
void ReadData(const Str_8& data); void ReadData(const Str_8 &data);
}; };
} }

View File

@@ -5,6 +5,7 @@
#include "ehs/Str.h" #include "ehs/Str.h"
#include "ehs/json/Json.h" #include "ehs/json/Json.h"
#include "Socket.h" #include "Socket.h"
#include "HeaderVar.h"
namespace ehs namespace ehs
{ {
@@ -14,7 +15,7 @@ namespace ehs
UInt_32 code; UInt_32 code;
Str_8 server; Str_8 server;
ContentType cType; ContentType cType;
Vector<Str_8> header; Vector<HeaderVar> header;
Str_8 body; Str_8 body;
public: public:
@@ -24,29 +25,38 @@ namespace ehs
/// Initializes this response with a given code and server identifier. /// Initializes this response with a given code and server identifier.
/// @param [in] code The code to give. /// @param [in] code The code to give.
/// @param [in] server The server identifier. /// @param [in] server The server identifier.
Response(const UInt_32 code, const Str_8& server); Response(const UInt_32 &code, Str_8 server);
/// Initializes this response with the raw response data. /// Initializes this response with the raw response data.
/// @param [in] data The C-style string of the response. /// @param [in] data The C-style string of the response.
/// @param [in] size The size of the given C-style string. /// @param [in] size The size of the given C-style string.
Response(const char* data, const UInt_64 size); Response(const char *data, const UInt_64 &size);
/// Initializes this response with the raw response data. /// Initializes this response with the raw response data.
/// @param [in] data The string of the response. /// @param [in] data The string of the response.
Response(const Str_8& data); Response(const Str_8 &data);
/// Moves members from another object of the same type.
/// @param [in] other The object to move from.
Response(Response &&other) noexcept;
/// Copies members from another object of the same type. /// Copies members from another object of the same type.
/// @param [in] res The object to copy from. /// @param [in] other The object to copy from.
Response(const Response& res) = default; Response(const Response &other);
/// Moves members from another object of the same type.
/// @param [in] other The object to move from.
/// @returns The response that has been assigned to.
Response &operator=(Response &&other) noexcept;
/// Copies members from another object of the same type. /// Copies members from another object of the same type.
/// @param [in] res The object to copy from. /// @param [in] res The object to copy from.
/// @returns The response that has been assigned to. /// @returns The response that has been assigned to.
Response& operator=(const Response& res); Response& operator=(const Response &other);
/// Sets the response code to send to the endpoint. /// Sets the response code to send to the endpoint.
/// @param [in] code The code for success, error or info. /// @param [in] code The code for success, error or info.
void SetCode(const UInt_32 code); void SetCode(const UInt_32 &code);
/// Retrieves the response code. /// Retrieves the response code.
/// @returns The result. /// @returns The result.
@@ -54,7 +64,7 @@ namespace ehs
/// Sets the server identifier. /// Sets the server identifier.
/// @param [in] server The server identifier to use. /// @param [in] server The server identifier to use.
void SetServer(const Str_8& server); void SetServer(Str_8 server);
/// Retrieves the server identifier. /// Retrieves the server identifier.
/// @returns The result. /// @returns The result.
@@ -62,25 +72,60 @@ namespace ehs
/// Sets the content type for the body. /// Sets the content type for the body.
/// @param [in] cType The content type to use. /// @param [in] cType The content type to use.
void SetContentType(const ContentType cType); void SetContentType(const ContentType &cType);
/// Retrieves the content type for the body. /// Retrieves the content type for the body.
/// @returns The result. /// @returns The result.
ContentType GetContentType() const; ContentType GetContentType() const;
/// Adds a header variable. /// Checks whether a header variable exists using the id.
/// @param [in] var The variable identifier. /// @param [in] id The variable id to look for.
/// @param [in] value The value of the variable. /// @returns True if the variable exists. False otherwise.
void AddToHeader(const Str_8& var, const Str_8& value); bool HasHeaderVar(const UInt_64 &id) const;
/// Retrieves a header variable. /// Checks whether a header variable exists using the name.
/// @param [in] var The variable identifier to look for. /// @param [in] name The variable name to look for.
/// @returns The value of the header variable. Empty if it was not found. /// @returns True if the variable exists. False otherwise.
Str_8 GetHeader(const Str_8& var) const; bool HasHeaderVar(const Str_8 &name) const;
/// Adds a header variable.
/// @param [in] var The variable to add to the header.
/// @returns False if the given variable name already exists. True otherwise.
bool AddHeaderVar(HeaderVar var);
/// Removes a header variable using the id.
/// @param [in] id The variable id to look for.
/// @returns True if the variable was found. False otherwise.
bool RemoveHeaderVar(const UInt_64 &id);
/// Removes a header variable using the name.
/// @param [in] name The variable name to look for.
/// @returns True if the variable was found. False otherwise.
bool RemoveHeaderVar(const Str_8 &name);
/// Retrieves a header variable using the id.
/// @param [in] id The variable id to look for.
/// @returns The variable object if found. Nullptr otherwise.
HeaderVar *GetHeaderVar(const UInt_64 &id) const;
/// Retrieves a header variable using the name.
/// @param [in] name The variable name to look for.
/// @returns The variable object if found. Nullptr otherwise.
HeaderVar *GetHeaderVar(const Str_8& name) const;
/// Retrieves a header variable value using the id.
/// @param [in] id The variable id to look for.
/// @returns The variable's value if found. Empty otherwise.
Str_8 GetHeaderValue(const UInt_64 &id) const;
/// Retrieves a header variable value using the name.
/// @param [in] name The variable name to look for.
/// @returns The variable's value if found. Empty otherwise.
Str_8 GetHeaderValue(const Str_8& name) const;
/// Retrieves all the header variables in a vector object. /// Retrieves all the header variables in a vector object.
/// @returns The result. /// @returns The result.
Vector<Str_8> GetHeader() const; Vector<HeaderVar> GetHeader() const;
/// Adds a body variable. /// Adds a body variable.
/// @param [in] var The variable identifier. /// @param [in] var The variable identifier.
@@ -115,13 +160,13 @@ namespace ehs
bool IsValid() const; bool IsValid() const;
private: private:
static Str_8 CodeToStr(const UInt_32 code); static Str_8 CodeToStr(const UInt_32 &code);
static Str_8 ContentTypeToStr(const ContentType cType); static Str_8 ContentTypeToStr(const ContentType &cType);
static ContentType StrToContentType(const Str_8& value); static ContentType StrToContentType(const Str_8 &value);
void ReadData(const Str_8& data); void ReadData(const Str_8 &data);
}; };
} }

View File

@@ -1,5 +1,7 @@
#pragma once #pragma once
#include <openssl/types.h>
#include "ehs/EHS.h" #include "ehs/EHS.h"
#include "ehs/Str.h" #include "ehs/Str.h"
#include "TCP.h" #include "TCP.h"
@@ -15,15 +17,18 @@ namespace ehs
class EHS_LIB_IO SSL : public TCP class EHS_LIB_IO SSL : public TCP
{ {
private: private:
bool server;
SSL_CTX* ctx; SSL_CTX* ctx;
::SSL* sslHdl; ::SSL* sslHdl;
X509 *cert;
EVP_PKEY* pkey;
public: public:
~SSL() override; ~SSL() override;
SSL(); SSL();
SSL(const AddrType type); SSL(const IP &type, const bool &server);
SSL(TCP&& tcp) noexcept; SSL(TCP&& tcp) noexcept;
@@ -37,19 +42,19 @@ namespace ehs
void Release() override; void Release() override;
void Bind(const Str_8& address, unsigned short port) override; void Listen() override;
SSL* Accept() override; SSL* Accept() override;
void Connect(const Str_8& address, const UInt_16 port) override; void Connect(Str_8 address, const UInt_16 &port) override;
UInt_64 Send(const Byte* const buffer, const UInt_32 size) override; UInt_64 Send(const Byte* buffer, const UInt_32 size) override;
UInt_64 Receive(Byte* const buffer, const UInt_32 size) override; UInt_64 Receive(Byte* buffer, const UInt_32 size) override;
void UseCertificate(const Byte* data, const UInt_64 size); void UseCertificate(const Char_8* data, const UInt_32 &size);
void UsePrivateKey(const Byte* data, const UInt_64 size); void UsePrivateKey(const Char_8* data, const UInt_32 &size);
bool IsValid(); bool IsValid();
}; };

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
@@ -37,10 +40,19 @@ namespace ehs
APP_XML, APP_XML,
TEXT_PLAIN, TEXT_PLAIN,
TEXT_HTML, TEXT_HTML,
TEXT_CSS,
TEXT_XML, TEXT_XML,
IMG_X_ICON,
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;
@@ -46,7 +46,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(const Str_8& address, UInt_16 port) override; void Bind(Str_8 address, const UInt_16 &port) override;
/// Listens for incoming connections. Used for servers or PtP. /// Listens for incoming connections. Used for servers or PtP.
void Listen() override; void Listen() override;
@@ -58,7 +58,7 @@ namespace ehs
/// Connects to a TCP Socket that listens for incoming connections. Used for clients or PtP. /// Connects to a TCP Socket that listens for incoming connections. Used for clients or PtP.
/// @param address The address of the listening TCP socket. Resolves domain names. The given address can be empty, "127.0.0.1", or "localhost" to automatically find the appropriate device. /// @param address The address of the listening TCP socket. Resolves domain names. The given address can be empty, "127.0.0.1", or "localhost" to automatically find the appropriate device.
/// @param port The port of the listening TCP socket. /// @param port The port of the listening TCP socket.
void Connect(const Str_8& address, UInt_16 port) override; void Connect(Str_8 address, const UInt_16 &port) override;
/// Sends data in a C-style array with raw functionality. Meaning no internal help outside of native functions besides error checking. /// Sends data in a C-style array with raw functionality. Meaning no internal help outside of native functions besides error checking.
/// @param [in] buffer The C-style array to send. /// @param [in] buffer The C-style array to send.
@@ -84,15 +84,17 @@ namespace ehs
bool IsIPv6Only() const override; bool IsIPv6Only() const override;
void SetReuse(const bool &value) override;
bool IsValid() const override; bool IsValid() const override;
private: private:
void Bind_v6(const Str_8& address, UInt_16 port); void Bind_v6(const Str_8 &address, const UInt_16 &port) const;
void Bind_v4(const Str_8& address, UInt_16 port); void Bind_v4(const Str_8 &address, const UInt_16 &port) const;
void Connect_v6(const Str_8& address, UInt_16 port); void Connect_v6(const Str_8 &address, const UInt_16 &port);
void Connect_v4(const Str_8& address, UInt_16 port); void Connect_v4(const Str_8 &address, const UInt_16 &port);
}; };
} }

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;
@@ -46,7 +46,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(const Str_8& address, UInt_16 port) override; void Bind(Str_8 address, const UInt_16 &port) override;
/// Listens for incoming connections. Used for servers or PtP. /// Listens for incoming connections. Used for servers or PtP.
void Listen() override; void Listen() override;
@@ -58,7 +58,7 @@ namespace ehs
/// Connects to a TCP Socket that listens for incoming connections. Used for clients or PtP. /// Connects to a TCP Socket that listens for incoming connections. Used for clients or PtP.
/// @param address The address of the listening TCP socket. Resolves domain names. The given address can be empty, "127.0.0.1", or "localhost" to automatically find the appropriate device. /// @param address The address of the listening TCP socket. Resolves domain names. The given address can be empty, "127.0.0.1", or "localhost" to automatically find the appropriate device.
/// @param port The port of the listening TCP socket. /// @param port The port of the listening TCP socket.
void Connect(const Str_8& address, UInt_16 port) override; void Connect(Str_8 address, const UInt_16 &port) override;
/// Sends data in a C-style array with raw functionality. Meaning no internal help outside of native functions besides error checking. /// Sends data in a C-style array with raw functionality. Meaning no internal help outside of native functions besides error checking.
/// @param [in] buffer The C-style array to send. /// @param [in] buffer The C-style array to send.
@@ -84,12 +84,14 @@ namespace ehs
bool IsIPv6Only() const override; bool IsIPv6Only() const override;
void SetReuse(const bool &value) override;
bool IsValid() const override; bool IsValid() const override;
private: private:
void Bind_v6(const Str_8& address, UInt_16 port); void Bind_v6(const Str_8& address, const UInt_16 &port);
void Bind_v4(const Str_8& address, UInt_16 port); void Bind_v4(const Str_8& address, const UInt_16 &port);
void Connect_v6(const Str_8& address, UInt_16 port); void Connect_v6(const Str_8& address, UInt_16 port);

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

@@ -12,57 +12,57 @@
namespace ehs namespace ehs
{ {
class EHS_LIB_IO Json class EHS_LIB_IO Json final
{ {
private: private:
JsonBase* value; JsonBase *value;
public: public:
virtual ~Json(); ~Json();
Json(); Json();
Json(const JsonBase& value); Json(const JsonBase &value);
Json(const JsonObj& value); Json(const JsonObj &value);
Json(const JsonArray& value); Json(const JsonArray &value);
Json(const JsonBool& value); Json(const JsonBool &value);
Json(const JsonNum& value); Json(const JsonNum &value);
Json(const JsonStr& value); Json(const JsonStr &value);
Json(const char* data, const UInt_64 size, const UInt_64 extra); Json(const char *data, UInt_64 size, UInt_64 extra);
Json(const Str_8& data, const UInt_64 extra); Json(const Str_8 &data, UInt_64 extra);
Json(Json&& json) noexcept; Json(Json &&json) noexcept;
Json(const Json &json); Json(const Json &json);
Json& operator=(Json&& json) noexcept; Json &operator=(Json &&json) noexcept;
Json& operator=(const Json& json); Json &operator=(const Json &json);
JsonBase* GetValue(); JsonBase *GetValue();
JsonBase* RetrieveValue(const Str_8& access); JsonBase *RetrieveValue(const Str_8 &access);
Str_8 ToStr(const bool compact) const; Str_8 ToStr(bool compact) const;
private: private:
static Vector<Str_8> ParseAccess(const Str_8& access); static Vector<Str_8> ParseAccess(const Str_8 &access);
void ParseValue(JsonVar* var, const Char_8** begin, const Char_8* end, const UInt_64 extra); void ParseValue(JsonVar *var, const Char_8 **begin, const Char_8 *end, UInt_64 extra);
JsonVar ParseVar(const Char_8** begin, const Char_8* end, const UInt_64 extra); JsonVar ParseVar(const Char_8 **begin, const Char_8 *end, UInt_64 extra);
void ParseObject(JsonObj* obj, const Char_8** begin, const Char_8* end, const UInt_64 extra); void ParseObject(JsonObj *obj, const Char_8 **begin, const Char_8 *end, UInt_64 extra);
void ParseArray(JsonArray* arr, const Char_8** begin, const Char_8* end, const UInt_64 extra); void ParseArray(JsonArray *arr, const Char_8 **begin, const Char_8 *end, UInt_64 extra);
void Parse(const Str_8& data, const UInt_64 extra); void Parse(const Str_8 &data, UInt_64 extra);
}; };
} }

View File

@@ -20,13 +20,13 @@ namespace ehs
JsonBase** data; JsonBase** data;
public: public:
virtual ~JsonArray(); ~JsonArray() override;
JsonArray(); JsonArray();
JsonArray(const UInt_64 extra); JsonArray(UInt_64 extra);
JsonArray(const UInt_64 size, const UInt_64 extra); JsonArray(UInt_64 size, UInt_64 extra);
JsonArray(JsonArray&& ja) noexcept; JsonArray(JsonArray&& ja) noexcept;
@@ -46,9 +46,9 @@ namespace ehs
UInt_64 Size() const; UInt_64 Size() const;
void Insert(const UInt_64 index, const JsonBase* const value); void Insert(UInt_64 index, const JsonBase* value);
void Push(const JsonBase* const value); void Push(const JsonBase* value);
void Push(const JsonBase& value); void Push(const JsonBase& value);
@@ -58,20 +58,20 @@ namespace ehs
void Push(const JsonBool& value); void Push(const JsonBool& value);
void Push(const bool value); void Push(bool value);
void Push(const JsonNum& value); void Push(const JsonNum& value);
void Push(const float value); void Push(float value);
void Push(const JsonStr& value); void Push(const JsonStr& value);
void Push(const Char_8* value, const UInt_64 size = 0); void Push(const Char_8* value, UInt_64 size = 0);
void Push(const Str_8& value); void Push(const Str_8& value);
void Pop(); void Pop();
Str_8 ToStr(const UInt_64 level, const bool compact) const; Str_8 ToStr(UInt_64 level, bool compact) const override;
}; };
} }

View File

@@ -21,14 +21,16 @@ namespace ehs
JsonType type; JsonType type;
public: public:
virtual ~JsonBase() = default;
JsonBase(); JsonBase();
JsonBase(const JsonType type); JsonBase(JsonType type);
JsonBase(const JsonBase& base) = default; JsonBase(const JsonBase& base) = default;
JsonType GetType() const; JsonType GetType() const;
virtual Str_8 ToStr(const UInt_64 level, const bool compact) const; virtual Str_8 ToStr(UInt_64 level, bool compact) const;
}; };
} }

View File

@@ -7,14 +7,14 @@
namespace ehs namespace ehs
{ {
class EHS_LIB_IO JsonBool : public JsonBase class EHS_LIB_IO JsonBool final : public JsonBase
{ {
public: public:
bool value; bool value;
JsonBool(); JsonBool();
JsonBool(const bool value); JsonBool(bool value);
JsonBool(const JsonBool& jb) = default; JsonBool(const JsonBool& jb) = default;
@@ -22,6 +22,6 @@ namespace ehs
operator bool&(); operator bool&();
Str_8 ToStr(const UInt_64 level, const bool compact) const; Str_8 ToStr(UInt_64 level, bool compact) const override;
}; };
} }

View File

@@ -7,39 +7,37 @@
namespace ehs namespace ehs
{ {
class EHS_LIB_IO JsonNum : public JsonBase class EHS_LIB_IO JsonNum final : public JsonBase
{ {
public: public:
float value; float value;
JsonNum(); JsonNum();
JsonNum(const SInt_64 value); JsonNum(SInt_64 value);
JsonNum(const UInt_64 value); JsonNum(UInt_64 value);
JsonNum(const SInt_32 value); JsonNum(SInt_32 value);
JsonNum(const UInt_32 value); JsonNum(UInt_32 value);
JsonNum(const SInt_16 value); JsonNum(SInt_16 value);
JsonNum(const UInt_16 value); JsonNum(UInt_16 value);
JsonNum(const SInt_8 value); JsonNum(SInt_8 value);
JsonNum(const UInt_8 value); JsonNum(UInt_8 value);
JsonNum(const double value); JsonNum(double value);
JsonNum(const float value); JsonNum(float value);
JsonNum(const JsonNum& jn) = default; JsonNum(const JsonNum& jn) = default;
operator float() const; operator float() const;
operator float&(); Str_8 ToStr(UInt_64 level, bool compact) const override;
Str_8 ToStr(const UInt_64 level, const bool compact) const;
}; };
} }

View File

@@ -9,7 +9,7 @@ namespace ehs
{ {
class JsonVar; class JsonVar;
class EHS_LIB_IO JsonObj : public JsonBase class EHS_LIB_IO JsonObj final : public JsonBase
{ {
protected: protected:
UInt_64 size; UInt_64 size;
@@ -18,25 +18,23 @@ namespace ehs
JsonVar* vars; JsonVar* vars;
public: public:
virtual ~JsonObj(); ~JsonObj() override;
JsonObj(); JsonObj();
JsonObj(const UInt_64 size, const UInt_64 extra); JsonObj(UInt_64 size, UInt_64 extra);
JsonObj(const UInt_64 extra); JsonObj(UInt_64 extra);
JsonObj(JsonObj&& value) noexcept; JsonObj(JsonObj &&value) noexcept;
JsonObj(const JsonObj& value); JsonObj(const JsonObj &value);
JsonObj& operator=(JsonObj&& value) noexcept; JsonObj& operator=(JsonObj &&value) noexcept;
JsonObj& operator=(const JsonObj& value); JsonObj& operator=(const JsonObj &value);
operator const JsonVar*() const; operator JsonVar *() const;
operator JsonVar*();
UInt_64 Size() const; UInt_64 Size() const;
@@ -44,20 +42,20 @@ namespace ehs
UInt_64 RawSize() const; UInt_64 RawSize() const;
bool HasVar(const UInt_64 hashId) const; bool HasVar(UInt_64 hashId) const;
bool HasVar(const Str_8& identifier) const; bool HasVar(const Str_8 &identifier) const;
bool AddVar(const JsonVar& var); bool AddVar(const JsonVar &var);
const JsonVar* GetVar(const UInt_64 hashId) const; const JsonVar *GetVar(UInt_64 hashId) const;
const JsonVar* GetVar(const Str_8& identifier) const; const JsonVar *GetVar(const Str_8& identifier) const;
JsonVar* GetVar(const UInt_64 hashId); JsonVar *GetVar(UInt_64 hashId);
JsonVar* GetVar(const Str_8& identifier); JsonVar *GetVar(const Str_8& identifier);
Str_8 ToStr(const UInt_64 level, const bool compact) const; Str_8 ToStr(UInt_64 level, bool compact) const override;
}; };
} }

View File

@@ -7,7 +7,7 @@
namespace ehs namespace ehs
{ {
class EHS_LIB_IO JsonStr : public JsonBase class EHS_LIB_IO JsonStr final : public JsonBase
{ {
public: public:
Str_8 value; Str_8 value;
@@ -16,18 +16,18 @@ namespace ehs
JsonStr(Str_8 value); JsonStr(Str_8 value);
JsonStr(const Char_8* value, const UInt_64 size = 0); JsonStr(const Char_8 *value, UInt_64 size = 0);
JsonStr(JsonStr&& js) noexcept; JsonStr(JsonStr &&js) noexcept;
JsonStr(const JsonStr& js) = default; JsonStr(const JsonStr &js) = default;
JsonStr& operator=(JsonStr&& js) noexcept; JsonStr& operator=(JsonStr &&js) noexcept;
operator Str_8() const; operator Str_8() const;
operator Str_8&(); operator Str_8 &();
Str_8 ToStr(const UInt_64 level, const bool compact) const; Str_8 ToStr(UInt_64 level, bool compact) const override;
}; };
} }

View File

@@ -12,7 +12,7 @@ namespace ehs
class JsonNum; class JsonNum;
class JsonStr; class JsonStr;
class EHS_LIB_IO JsonVar class EHS_LIB_IO JsonVar final
{ {
private: private:
UInt_64 hashId; UInt_64 hashId;
@@ -20,49 +20,49 @@ namespace ehs
JsonBase* value; JsonBase* value;
public: public:
virtual ~JsonVar(); ~JsonVar();
JsonVar(); JsonVar();
JsonVar(Str_8 id); JsonVar(Str_8 id);
JsonVar(Str_8 id, const JsonBase* const value); JsonVar(Str_8 id, const JsonBase *value);
JsonVar(Str_8 id, const JsonBase& value); JsonVar(Str_8 id, const JsonBase &value);
JsonVar(Str_8 id, const JsonObj& value); JsonVar(Str_8 id, const JsonObj &value);
JsonVar(Str_8 id, const JsonArray& value); JsonVar(Str_8 id, const JsonArray &value);
JsonVar(Str_8 id, const JsonBool& value); JsonVar(Str_8 id, const JsonBool &value);
JsonVar(Str_8 id, const bool boolean); JsonVar(Str_8 id, bool boolean);
JsonVar(Str_8 id, const JsonNum& value); JsonVar(Str_8 id, const JsonNum &value);
JsonVar(Str_8 id, const SInt_64 num); JsonVar(Str_8 id, SInt_64 num);
JsonVar(Str_8 id, const UInt_64 num); JsonVar(Str_8 id, UInt_64 num);
JsonVar(Str_8 id, const SInt_32 num); JsonVar(Str_8 id, SInt_32 num);
JsonVar(Str_8 id, const UInt_32 num); JsonVar(Str_8 id, UInt_32 num);
JsonVar(Str_8 id, const SInt_16 num); JsonVar(Str_8 id, SInt_16 num);
JsonVar(Str_8 id, const UInt_16 num); JsonVar(Str_8 id, UInt_16 num);
JsonVar(Str_8 id, const SInt_8 num); JsonVar(Str_8 id, SInt_8 num);
JsonVar(Str_8 id, const UInt_8 num); JsonVar(Str_8 id, UInt_8 num);
JsonVar(Str_8 id, const double num); JsonVar(Str_8 id, double num);
JsonVar(Str_8 id, const float num); JsonVar(Str_8 id, float num);
JsonVar(Str_8 id, const JsonStr& value); JsonVar(Str_8 id, const JsonStr &value);
JsonVar(Str_8 id, const Char_8* str, const UInt_64 size = 0); JsonVar(Str_8 id, const Char_8 *str, UInt_64 size = 0);
JsonVar(Str_8 id, Str_8 str); JsonVar(Str_8 id, Str_8 str);
@@ -78,25 +78,25 @@ namespace ehs
Str_8 GetId() const; Str_8 GetId() const;
void SetValue(const JsonBase* const newValue); void SetValue(const JsonBase *newValue);
void SetValue(const JsonBase& newValue); void SetValue(const JsonBase &newValue);
void SetValue(const JsonObj& newValue); void SetValue(const JsonObj &newValue);
void SetValue(const JsonArray& newValue); void SetValue(const JsonArray &newValue);
void SetValue(const JsonBool& newValue); void SetValue(const JsonBool &newValue);
void SetValue(const bool newValue); void SetValue(bool newValue);
void SetValue(const JsonNum& newValue); void SetValue(const JsonNum& newValue);
void SetValue(const float newValue); void SetValue(float newValue);
void SetValue(const JsonStr& newValue); void SetValue(const JsonStr& newValue);
void SetValue(const Char_8* newValue, const UInt_64 size = 0); void SetValue(const Char_8* newValue, UInt_64 size = 0);
void SetValue(const Str_8& newValue); void SetValue(const Str_8& newValue);
@@ -104,6 +104,6 @@ namespace ehs
JsonBase* GetValue(); JsonBase* GetValue();
Str_8 ToStr(const UInt_64 level, const bool compact) const; Str_8 ToStr(UInt_64 level, bool compact) const;
}; };
} }

36
include/ehs/system/AVX2.h Normal file
View File

@@ -0,0 +1,36 @@
#pragma once
#include "ehs/Types.h"
namespace ehs
{
class EHS_LIB_IO AVX2
{
public:
/// Compares two unaligned 4 element vectors using 64-bit integers.
/// @param [in] a First vector.
/// @param [in] b Second vector.
/// @returns True if all 4 elements are equal. False otherwise.
static bool CompareUnaligned(const UInt_64 *a, const UInt_64 *b);
/// Compares two unaligned 4 element vectors using 64-bit integers.
/// @param [in] a First vector.
/// @param [in] b Second vector.
/// @returns True if all 4 elements are equal. False otherwise.
static bool CompareUnaligned(const SInt_64 *a, const SInt_64 *b);
/// Compares two aligned 4 element vectors using 64-bit integers.
/// @param [in] a First vector.
/// @param [in] b Second vector.
/// @returns True if all 4 elements are equal. False otherwise.
/// @note The parameters "a", and "b" must have alignas(32).
static bool CompareAligned(const UInt_64 *a, const UInt_64 *b);
/// Compares two aligned 4 element vectors using 64-bit integers.
/// @param [in] a First vector.
/// @param [in] b Second vector.
/// @returns True if all 4 elements are equal. False otherwise.
/// @note The parameters "a", and "b" must have alignas(32).
static bool CompareAligned(const SInt_64 *a, const SInt_64 *b);
};
}

View File

@@ -0,0 +1,36 @@
#pragma once
#include "ehs/Types.h"
namespace ehs
{
class EHS_LIB_IO AVX512
{
public:
/// Compares two unaligned 8 element vectors using 64-bit integers.
/// @param [in] a First vector.
/// @param [in] b Second vector.
/// @returns True if all 8 elements are equal. False otherwise.
static bool CompareUnaligned(const UInt_64 *a, const UInt_64 *b);
/// Compares two unaligned 8 element vectors using 64-bit integers.
/// @param [in] a First vector.
/// @param [in] b Second vector.
/// @returns True if all 8 elements are equal. False otherwise.
static bool CompareUnaligned(const SInt_64 *a, const SInt_64 *b);
/// Compares two aligned 8 element vectors using 64-bit integers.
/// @param [in] a First vector.
/// @param [in] b Second vector.
/// @returns True if all 8 elements are equal. False otherwise.
/// @note The parameters "a", and "b" must have alignas(32).
static bool CompareAligned(const UInt_64 *a, const UInt_64 *b);
/// Compares two aligned 8 element vectors using 64-bit integers.
/// @param [in] a First vector.
/// @param [in] b Second vector.
/// @returns True if all 8 elements are equal. False otherwise.
/// @note The parameters "a", and "b" must have alignas(32).
static bool CompareAligned(const SInt_64 *a, const SInt_64 *b);
};
}

View File

@@ -6,7 +6,7 @@
#define EHS_64_BIT #define EHS_64_BIT
#elif defined(_M_ARM64) || defined(__aarch64__) #elif defined(_M_ARM64) || defined(__aarch64__)
#define EHS_LITTLE_ENDIAN #define EHS_LITTLE_ENDIAN
#define EHS_ARCH_ARM64 #define EHS_ARCH_AARCH64
#define EHS_64_BIT #define EHS_64_BIT
#else #else
#error Unsupported architecture. #error Unsupported architecture.

View File

@@ -8,6 +8,10 @@ namespace ehs
class EHS_LIB_IO BaseSystem class EHS_LIB_IO BaseSystem
{ {
public: public:
static void OpenURI(const Str_8& uri); static void OpenURI(Str_8 uri);
static Str_8 OpenFileDialog(const Str_8 &dir, const Str_8 &filters);
static Str_8 GetDirDialog(const Str_8 &dir);
}; };
} }

View File

@@ -38,6 +38,70 @@ namespace ehs
#endif #endif
public: public:
static const bool hasFPU;
static const bool hasVME;
static const bool hasDE;
static const bool hasPSE;
static const bool hasTSC;
static const bool hasMSR;
static const bool hasPAE;
static const bool hasMCE;
static const bool hasCX8;
static const bool hasAPIC;
static const bool hasSEP;
static const bool hasMTRR;
static const bool hasPGE;
static const bool hasMCA;
static const bool hasCMOV;
static const bool hasPSE_36;
static const bool hasPSN;
static const bool hasCLFSH;
static const bool hasDS;
static const bool hasACPI;
static const bool hasMMX;
static const bool hasFXSR;
static const bool hasSSE;
static const bool hasSSE2;
static const bool hasSS;
static const bool hasHTT;
static const bool hasTM;
static const bool hasIA64;
static const bool hasPBE;
static const bool hasSSE3;
static const bool hasPCLMULQDQ;
static const bool hasDTES64;
static const bool hasMONITOR;
static const bool hasVMX;
static const bool hasSMX;
static const bool hasEST;
static const bool hasTM2;
static const bool hasSSSE3;
static const bool hasCNXT_ID;
static const bool hasSDBG;
static const bool hasFMA;
static const bool hasCX16;
static const bool hasXTPR;
static const bool hasPDCM;
static const bool hasPCID;
static const bool hasDCA;
static const bool hasSSE4_1;
static const bool hasSSE4_2;
static const bool hasX2APIC;
static const bool hasMOVBE;
static const bool hasPOPCNT;
static const bool hasTSC_DEADLINE;
static const bool hasAES;
static const bool hasXSAVE;
static const bool hasOSXSAVE;
static const bool hasAVX;
static const bool hasF16C;
static const bool hasRDRND;
static const bool hasHYPERVISOR;
static const bool hasAVX2;
static const bool hasAVX512F;
static const bool hasRDSEED;
static const bool hasADX;
static Architecture GetArchitecture(); static Architecture GetArchitecture();
static UInt_8 PointerSize(); static UInt_8 PointerSize();
@@ -68,151 +132,157 @@ namespace ehs
static UInt_8 GetExtFamilyId(); static UInt_8 GetExtFamilyId();
/// Retrieves the CPU brand as a null-terminated ASCII string.
/// @param[out] input A 48 byte character array representing the brand.
static void GetBrand(Char_8* input);
static UInt_8 GetCacheLineSize();
static UInt_32 GetFeatureBits_1(); static UInt_32 GetFeatureBits_1();
static bool HasFPU(); static UInt_32 GetFeatureBits_2();
static bool HasVME(); static UInt_32 GetExtFeatureBits_1();
static bool HasDE(); static UInt_32 GetExtFeatureBits_2();
static bool HasPSE(); static UInt_32 GetExtFeatureBits_3();
static bool HasTSC(); private:
static bool RetrieveFPU();
static bool HasMSR(); static bool RetrieveVME();
static bool HasPAE(); static bool RetrieveDE();
static bool HasMCE(); static bool RetrievePSE();
static bool HasCX8(); static bool RetrieveTSC();
static bool HasAPIC(); static bool RetrieveMSR();
static bool HasSEP(); static bool RetrievePAE();
static bool HasMTRR(); static bool RetrieveMCE();
static bool HasPGE(); static bool RetrieveCX8();
static bool HasMCA(); static bool RetrieveAPIC();
static bool HasCMOV(); static bool RetrieveSEP();
static bool HasPAT(); static bool RetrieveMTRR();
static bool HasPSE_36(); static bool RetrievePGE();
static bool HasPSN(); static bool RetrieveMCA();
static bool HasCLFSH(); static bool RetrieveCMOV();
static bool HasDS(); static bool RetrievePAT();
static bool HasACPI(); static bool RetrievePSE_36();
static bool HasMMX(); static bool RetrievePSN();
static bool HasFXSR(); static bool RetrieveCLFSH();
static bool HasSSE(); static bool RetrieveDS();
static bool HasSSE2(); static bool RetrieveACPI();
static bool HasSS(); static bool RetrieveMMX();
static bool HasHTT(); static bool RetrieveFXSR();
static bool HasTM(); static bool RetrieveSSE();
static bool HasIA64(); static bool RetrieveSSE2();
static bool HasPBE(); static bool RetrieveSS();
static UInt_32 GetFeatureBits_2(); static bool RetrieveHTT();
static bool HasSSE3(); static bool RetrieveTM();
static bool HasPCLMULQDQ(); static bool RetrieveIA64();
static bool HasDTES64(); static bool RetrievePBE();
static bool HasMONITOR(); static bool RetrieveSSE3();
static bool HasDS_CPL(); static bool RetrievePCLMULQDQ();
static bool HasVMX(); static bool RetrieveDTES64();
static bool HasSMX(); static bool RetrieveMONITOR();
static bool HasEST(); static bool RetrieveDS_CPL();
static bool HasTM2(); static bool RetrieveVMX();
static bool HasSSSE3(); static bool RetrieveSMX();
static bool HasCNXT_ID(); static bool RetrieveEST();
static bool HasSDBG(); static bool RetrieveTM2();
static bool HasFMA(); static bool RetrieveSSSE3();
static bool HasCX16(); static bool RetrieveCNXT_ID();
static bool HasXTPR(); static bool RetrieveSDBG();
static bool HasPDCM(); static bool RetrieveFMA();
static bool HasPCID(); static bool RetrieveCX16();
static bool HasDCA(); static bool RetrieveXTPR();
static bool HasSSE4_1(); static bool RetrievePDCM();
static bool HasSSE4_2(); static bool RetrievePCID();
static bool HasX2APIC(); static bool RetrieveDCA();
static bool HasMOVBE(); static bool RetrieveSSE4_1();
static bool HasPOPCNT(); static bool RetrieveSSE4_2();
static bool HasTSC_DEADLINE(); static bool RetrieveX2APIC();
static bool HasAES(); static bool RetrieveMOVBE();
static bool HasXSAVE(); static bool RetrievePOPCNT();
static bool HasOSXSAVE(); static bool RetrieveTSC_DEADLINE();
static bool HasAVX(); static bool RetrieveAES();
static bool HasF16C(); static bool RetrieveXSAVE();
static bool HasRDRND(); static bool RetrieveOSXSAVE();
static bool HasHYPERVISOR(); static bool RetrieveAVX();
static UInt_32 GetExtFeatureBits_1(); static bool RetrieveF16C();
static bool HasAVX2(); static bool RetrieveRDRND();
static bool HasRDSEED(); static bool RetrieveHYPERVISOR();
static bool HasADX(); static bool RetrieveAVX2();
static UInt_32 GetExtFeatureBits_2(); static bool RetrieveAVX512F();
static UInt_32 GetExtFeatureBits_3(); static bool RetrieveRDSEED();
/// Retrieves the CPU brand as a null-terminated ASCII string. static bool RetrieveADX();
/// @param[out] input A 48 byte character array representing the brand.
static void GetBrand(Char_8* input);
//static Str_8 ToStr(); //static Str_8 ToStr();
private: static UInt_64 RetrieveFreq_AARCH64();
static UInt_64 RetrieveTSC_Freq(); static UInt_64 RetrieveTSC_Freq();
static UInt_64 CalculateTSC_Freq(); static UInt_64 CalculateTSC_Freq();

View File

@@ -8,6 +8,10 @@ namespace ehs
class EHS_LIB_IO System : public BaseSystem class EHS_LIB_IO System : public BaseSystem
{ {
public: public:
static void OpenURI(const Str_8& uri); static void OpenURI(Str_8 uri);
static Str_8 OpenFileDialog(const Str_8 &dir, const Str_8 &filters);
static Str_8 GetDirDialog(const Str_8 &dir);
}; };
} }

View File

@@ -7,6 +7,6 @@ namespace ehs
class EHS_LIB_IO System : public BaseSystem class EHS_LIB_IO System : public BaseSystem
{ {
public: public:
static void OpenURI(const Str_8& uri); static void OpenURI(Str_8 uri);
}; };
} }

View File

@@ -2,8 +2,36 @@
namespace ehs namespace ehs
{ {
const char Base64::ascii[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; Str_8 Base64::EncodeURL(const Str_8 &input)
{
UInt_64 input_length = input.Size();
// Calculate the output length
UInt_64 output_length = (input_length * 4 + 2) / 3;
// Allocate memory for the output
Str_8 result(output_length);
// Loop through the input and fill the output
for (int i = 0, j = 0; i < input_length;) {
// Take first byte and shift right by 2 bits
UInt_32 octet_a = (UInt_8)input[i++];
UInt_32 octet_b = i < input_length ? (UInt_8)input[i++] : 0;
UInt_32 octet_c = i < input_length ? (UInt_8)input[i++] : 0;
UInt_32 triple = (octet_a << 16) + (octet_b << 8) + octet_c;
// Encode the 24-bits into four 6-bits integers
result[j++] = asciiUrl[(triple >> 3 * 6) & 0x3F];
result[j++] = asciiUrl[(triple >> 2 * 6) & 0x3F];
result[j++] = asciiUrl[(triple >> 1 * 6) & 0x3F];
result[j++] = asciiUrl[(triple >> 0 * 6) & 0x3F];
}
return result;
}
Str_8 Base64::Encode(const Str_8 &input) Str_8 Base64::Encode(const Str_8 &input)
{ {
UInt_64 input_length = input.Size(); UInt_64 input_length = input.Size();
@@ -18,9 +46,9 @@ namespace ehs
for (int i = 0, j = 0; i < input_length;) { for (int i = 0, j = 0; i < input_length;) {
// Take first byte and shift right by 2 bits // Take first byte and shift right by 2 bits
UInt_32 octet_a = i < input_length ? input[i++] : 0; UInt_32 octet_a = i < input_length ? (UInt_8)input[i++] : 0;
UInt_32 octet_b = i < input_length ? input[i++] : 0; UInt_32 octet_b = i < input_length ? (UInt_8)input[i++] : 0;
UInt_32 octet_c = i < input_length ? input[i++] : 0; UInt_32 octet_c = i < input_length ? (UInt_8)input[i++] : 0;
UInt_32 triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c; UInt_32 triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
@@ -41,64 +69,152 @@ namespace ehs
return result; return result;
} }
Str_8 Base64::Decode(const Str_8 &input) Str_8 Base64::DecodeURL(const Str_8 &input)
{ {
UInt_64 in_len = input.Size(); Str_8 result(input.Size() * 3 / 4);
int i = 0;
int j = 0;
int in_ = 0;
char char_array_4[4], char_array_3[3];
Str_8 ret;
while (in_len-- && ( input[in_] != '=') && IsBase64(input[in_])) UInt_64 remaining = input.Size();
UInt_64 offsetIn = 0;
UInt_64 offsetOut = 0;
UInt_8 quartet[4];
while (remaining)
{ {
char_array_4[i++] = input[in_]; in_++; if (remaining >= 4)
if (i ==4)
{ {
for (i = 0; i <4; i++) for (UInt_8 i = 0; i < 4; ++i)
char_array_4[i] = Find(char_array_4[i]); {
if (!IsBase64URL(input[offsetIn + i]))
return {};
char_array_3[0] = ( char_array_4[0] << 2 ) + ((char_array_4[1] & 0x30) >> 4); quartet[i] = FindURL(input[offsetIn + i]);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); if (quartet[i] == EHS_UINT_8_MAX)
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; return {};
}
for (i = 0; (i < 3); i++) result[offsetOut++] = (Char_8)((((UInt_8*)&quartet)[0] << 2) | (((UInt_8*)&quartet)[1] >> 4));
ret += char_array_3[i]; result[offsetOut++] = (Char_8)((((UInt_8*)&quartet)[1] << 4) | (((UInt_8*)&quartet)[2] >> 2));
result[offsetOut++] = (Char_8)((((UInt_8*)&quartet)[2] << 6) | ((UInt_8*)&quartet)[3]);
i = 0; offsetIn += 4;
remaining -= 4;
}
else
{
for (UInt_8 i = 0; i < 4; ++i)
{
if (i < remaining)
{
if (!IsBase64URL(input[offsetIn + i]))
return {};
quartet[i] = FindURL(input[offsetIn + i]);
if (quartet[i] == EHS_UINT_8_MAX)
return {};
}
else
quartet[i] = 0;
}
result[offsetOut++] = (Char_8)((quartet[0] << 2) | (quartet[1] >> 4));
if (remaining == 3)
result[offsetOut++] = (Char_8)((quartet[1] << 4) | (quartet[2] >> 2));
offsetIn += remaining;
remaining = 0;
} }
} }
if (i) return result;
}
Str_8 Base64::Decode(const Str_8 &input)
{
Str_8 result(input.Size() * 3 / 4);
UInt_64 remaining = input.Size();
UInt_64 offsetIn = 0;
UInt_64 offsetOut = 0;
UInt_8 quartet[4];
while (remaining)
{ {
for (j = 0; j < i; j++) if (remaining >= 4)
char_array_4[j] = Find(char_array_4[j]); {
for (UInt_8 i = 0; i < 4; ++i)
{
if (!IsBase64(input[offsetIn + i]))
return {};
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); quartet[i] = Find(input[offsetIn + i]);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); if (quartet[i] == EHS_UINT_8_MAX)
return {};
}
for (j = 0; (j < i - 1); j++) result[offsetOut++] = (Char_8)((((UInt_8*)&quartet)[0] << 2) | (((UInt_8*)&quartet)[1] >> 4));
ret += char_array_3[j]; result[offsetOut++] = (Char_8)((((UInt_8*)&quartet)[1] << 4) | (((UInt_8*)&quartet)[2] >> 2));
result[offsetOut++] = (Char_8)((((UInt_8*)&quartet)[2] << 6) | ((UInt_8*)&quartet)[3]);
offsetIn += 4;
remaining -= 4;
}
else
{
for (UInt_8 i = 0; i < 4; ++i)
{
if (i < remaining)
{
if (!IsBase64(input[offsetIn + i]))
return {};
quartet[i] = Find(input[offsetIn + i]);
if (quartet[i] == EHS_UINT_8_MAX)
return {};
}
else
quartet[i] = 0;
}
result[offsetOut++] = (Char_8)((quartet[0] << 2) | (quartet[1] >> 4));
if (remaining == 3)
result[offsetOut++] = (Char_8)((quartet[1] << 4) | (quartet[2] >> 2));
offsetIn += remaining;
remaining = 0;
}
} }
return ret; return result;
} }
char Base64::Find(const char c) UInt_8 Base64::FindURL(const UInt_8 &c)
{ {
for (char i = 0; i < (char)sizeof(ascii); ++i) for (UInt_8 i = 0; i < (UInt_8)sizeof(asciiUrl) - 1; ++i)
{ if (asciiUrl[i] == c)
return i;
return EHS_UINT_8_MAX;;
}
UInt_8 Base64::Find(const UInt_8 &c)
{
for (UInt_8 i = 0; i < (UInt_8)sizeof(ascii) - 1; ++i)
if (ascii[i] == c) if (ascii[i] == c)
return i; return i;
}
return EHS_SINT_8_MAX; return EHS_SINT_8_MAX;
} }
bool Base64::IsBase64(const char c) bool Base64::IsBase64URL(const UInt_8 &c)
{ {
return (c > 47 && c < 58) || (c > 64 && c < 91) || (c > 96 && c < 123) || (c == '+') || (c == '/'); return (c > 47 && c < 58) || (c > 64 && c < 91) || (c > 96 && c < 123) || c == '-' || c == '_';
}
bool Base64::IsBase64(const UInt_8 &c)
{
return (c > 47 && c < 58) || (c > 64 && c < 91) || (c > 96 && c < 123) || c == '+' || c == '/';
} }
} }

View File

@@ -75,12 +75,12 @@ namespace ehs
{ {
} }
Log::Log(LogType type, const std::initializer_list<Str_8> &tags, const UInt_64 code, Str_8 msg) Log::Log(LogType type, const Str_8 &tags, const UInt_64 code, Str_8 msg)
: type(type), tags(tags.size()), code(code), msg((Str_8&&)msg) : type(type), code(code), msg((Str_8&&)msg)
{ {
UInt_64 i = 0; const Vector<Str_8> tmpTags = tags.Split(", ");
for (auto v = tags.begin(); v != tags.end(); ++v)
this->tags[i++] = *v; this->tags = Array<Str_8>(&tmpTags[0], tmpTags.Size());
} }
Log::Log(LogType type, Array<Str_8> tags, const UInt_64 code, Str_8 msg) Log::Log(LogType type, Array<Str_8> tags, const UInt_64 code, Str_8 msg)

View File

@@ -36,9 +36,9 @@ namespace ehs
double Math::Sqrt(const double from) double Math::Sqrt(const double from)
{ {
#if defined(EHS_ARCH_X64) #if defined(EHS_ARCH_X64)
if (CPU::HasAVX()) if (CPU::hasAVX)
return Sqrt_AVX(from); return Sqrt_AVX(from);
else if (CPU::HasSSE()) else if (CPU::hasSSE)
return Sqrt_SSE2(from); return Sqrt_SSE2(from);
double temp = 0.0; double temp = 0.0;
@@ -51,7 +51,7 @@ namespace ehs
} }
return result; return result;
#elif defined(EHS_ARCH_ARM64) #elif defined(EHS_ARCH_AARCH64)
return Sqrt_VFP4(from); return Sqrt_VFP4(from);
#endif #endif
} }
@@ -59,9 +59,9 @@ namespace ehs
float Math::Sqrt(const float from) float Math::Sqrt(const float from)
{ {
#if defined(EHS_ARCH_X64) #if defined(EHS_ARCH_X64)
if (CPU::HasAVX()) if (CPU::hasAVX)
return Sqrt_AVX(from); return Sqrt_AVX(from);
else if (CPU::HasSSE()) else if (CPU::hasSSE)
return Sqrt_SSE(from); return Sqrt_SSE(from);
float temp = 0.0f; float temp = 0.0f;
@@ -74,7 +74,7 @@ namespace ehs
} }
return result; return result;
#elif defined(EHS_ARCH_ARM64) #elif defined(EHS_ARCH_AARCH64)
return Sqrt_VFP4(from); return Sqrt_VFP4(from);
#endif #endif
} }

209
src/SHA256.cpp Normal file
View File

@@ -0,0 +1,209 @@
#include "ehs/SHA256.h"
#include "ehs/Util.h"
namespace ehs
{
UInt_32 SHA256::ROTR(const UInt_32 x, const UInt_32 n)
{
return (x >> n) | (x << (32 - n));
}
UInt_32 SHA256::CH(const UInt_32 x, const UInt_32 y, const UInt_32 z)
{
return (x & y) ^ (~x & z);
}
UInt_32 SHA256::MAJ(const UInt_32 x, const UInt_32 y, const UInt_32 z)
{
return (x & y) ^ (x & z) ^ (y & z);
}
UInt_32 SHA256::EP0(const UInt_32 x)
{
return ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22);
}
UInt_32 SHA256::EP1(const UInt_32 x)
{
return ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25);
}
UInt_32 SHA256::SIG0(const UInt_32 x)
{
return ROTR(x, 7) ^ ROTR(x, 18) ^ (x >> 3);
}
UInt_32 SHA256::SIG1(const UInt_32 x)
{
return ROTR(x,17) ^ ROTR(x, 19) ^ (x >> 10);
}
SHA256::SHA256()
: state{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19},
bitLen(0), data{}, dataLen(0)
{
}
SHA256::SHA256(SHA256&& other) noexcept
: state{}, bitLen(0), data{}, dataLen(0)
{
Util::Copy(state, other.state, sizeof(state) / sizeof(UInt_32));
bitLen = other.bitLen;
Util::Copy(data, other.data, sizeof(data));
dataLen = other.dataLen;
Util::Zero(other.state, sizeof(state) / sizeof(UInt_32));
other.bitLen = 0;
Util::Zero(other.data, sizeof(data));
other.dataLen = 0;
}
SHA256::SHA256(const SHA256& other)
: state{}, bitLen(0), data{}, dataLen(0)
{
Util::Copy(state, other.state, sizeof(state) / sizeof(UInt_32));
bitLen = other.bitLen;
Util::Copy(data, other.data, sizeof(data));
dataLen = other.dataLen;
}
SHA256& SHA256::operator=(SHA256&& other) noexcept
{
if (this == &other)
return *this;
Util::Copy(state, other.state, sizeof(state) / sizeof(UInt_32));
bitLen = other.bitLen;
Util::Copy(data, other.data, sizeof(data));
dataLen = other.dataLen;
Util::Zero(other.state, sizeof(state) / sizeof(UInt_32));
other.bitLen = 0;
Util::Zero(other.data, sizeof(data));
other.dataLen = 0;
return *this;
}
SHA256& SHA256::operator=(const SHA256& other)
{
if (this == &other)
return *this;
Util::Copy(state, other.state, sizeof(state) / sizeof(UInt_32));
bitLen = other.bitLen;
Util::Copy(data, other.data, sizeof(data));
dataLen = other.dataLen;
return *this;
}
void SHA256::Update(const Byte* data, const UInt_64 len)
{
for(UInt_64 i = 0; i < len; ++i)
{
this->data[dataLen++] = data[i];
if(dataLen == 64)
{
Transform(this->data);
bitLen += 512;
dataLen = 0;
}
}
}
void SHA256::Final(Byte hash[32])
{
UInt_32 i = dataLen;
/* Pad */
data[i++] = 0x80;
if(i > 56)
{
while(i < 64)
data[i++] = 0x00;
Transform(data);
i = 0;
}
while(i < 56)
data[i++] = 0x00;
/* Length in bits */
bitLen += dataLen * 8ULL;
data[63] = bitLen;
data[62] = bitLen >> 8;
data[61] = bitLen >> 16;
data[60] = bitLen >> 24;
data[59] = bitLen >> 32;
data[58] = bitLen >> 40;
data[57] = bitLen >> 48;
data[56] = bitLen >> 56;
Transform(data);
/* bigendian output */
for(i = 0; i < 4; ++i) {
hash[i] = (state[0] >> (24 - i * 8)) & 0xff;
hash[i + 4] = (state[1] >> (24 - i * 8)) & 0xff;
hash[i + 8] = (state[2] >> (24 - i * 8)) & 0xff;
hash[i + 12] = (state[3] >> (24 - i * 8)) & 0xff;
hash[i + 16] = (state[4] >> (24 - i * 8)) & 0xff;
hash[i + 20] = (state[5] >> (24 - i * 8)) & 0xff;
hash[i + 24] = (state[6] >> (24 - i * 8)) & 0xff;
hash[i + 28] = (state[7] >> (24 - i * 8)) & 0xff;
}
}
void SHA256::Hash(const Byte* data, const UInt_64 len, Byte hash[32])
{
Update(data, len);
Final(hash);
}
void SHA256::Transform(const Byte data[64])
{
UInt_32 m[64];
UInt_32 a = state[0];
UInt_32 b = state[1];
UInt_32 c = state[2];
UInt_32 d = state[3];
UInt_32 e = state[4];
UInt_32 f = state[5];
UInt_32 g = state[6];
UInt_32 h = state[7];
UInt_32 i, t1, t2;
for (i = 0; i < 16; ++i)
m[i] = (UInt_32)data[i * 4] << 24 | (UInt_32)data[i * 4 + 1] << 16 | (UInt_32)data[i * 4 + 2] << 8 | (UInt_32)data[i * 4 + 3];
for (; i < 64; ++i)
m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16];
for(i = 0; i < 64; ++i)
{
t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i];
t2 = EP0(a) + MAJ(a,b,c);
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
state[5] += f;
state[6] += g;
state[7] += h;
}
}

View File

@@ -1,5 +1,9 @@
#include "ehs/Util.h" #include "ehs/Util.h"
#include "ehs/system/CPU.h"
#include "ehs/system/AVX2.h"
#include "ehs/system/AVX512.h"
namespace ehs namespace ehs
{ {
bool Util::Compare(const void* const a, const void* const b, const UInt_64 size) bool Util::Compare(const void* const a, const void* const b, const UInt_64 size)
@@ -118,4 +122,4 @@ namespace ehs
remainder = size - i; remainder = size - i;
} }
} }
} }

View File

@@ -693,7 +693,7 @@ namespace ehs
Vector<Str_32> Console::GetArgs_32(const UInt_64 bufferSize) Vector<Str_32> Console::GetArgs_32(const UInt_64 bufferSize)
{ {
#if defined(EHS_OS_WINDOWS) #if defined(EHS_OS_WINDOWS)
return UTF::To_32(GetCommandLineW()).Split(U" "); return UTF::To_32(GetCommandLineW()).ParseArgs();
#elif defined(EHS_OS_LINUX) #elif defined(EHS_OS_LINUX)
File cmdFile("/proc/self/cmdline", Mode::READ, Disposition::OPEN); File cmdFile("/proc/self/cmdline", Mode::READ, Disposition::OPEN);
Array<Byte> data = cmdFile.ReadArray(bufferSize); Array<Byte> data = cmdFile.ReadArray(bufferSize);
@@ -725,7 +725,7 @@ namespace ehs
Vector<Str_16> Console::GetArgs_16(const UInt_64 bufferSize) Vector<Str_16> Console::GetArgs_16(const UInt_64 bufferSize)
{ {
#if defined(EHS_OS_WINDOWS) #if defined(EHS_OS_WINDOWS)
return Str_16(GetCommandLineW()).Split(L" "); return Str_16(GetCommandLineW()).ParseArgs();
#elif defined(EHS_OS_LINUX) #elif defined(EHS_OS_LINUX)
File cmdFile("/proc/self/cmdline", Mode::READ, Disposition::OPEN); File cmdFile("/proc/self/cmdline", Mode::READ, Disposition::OPEN);
Array<Byte> data = cmdFile.ReadArray(bufferSize); Array<Byte> data = cmdFile.ReadArray(bufferSize);
@@ -755,7 +755,7 @@ namespace ehs
Vector<Str_8> Console::GetArgs_8(const UInt_64 bufferSize) Vector<Str_8> Console::GetArgs_8(const UInt_64 bufferSize)
{ {
#if defined(EHS_OS_WINDOWS) #if defined(EHS_OS_WINDOWS)
return UTF::To_8(GetCommandLineW()).Split(" "); return UTF::To_8(GetCommandLineW()).ParseArgs();
#elif defined(EHS_OS_LINUX) #elif defined(EHS_OS_LINUX)
File cmdFile("/proc/self/cmdline", Mode::READ, Disposition::OPEN); File cmdFile("/proc/self/cmdline", Mode::READ, Disposition::OPEN);
Array<Byte> data = cmdFile.ReadArray(bufferSize); Array<Byte> data = cmdFile.ReadArray(bufferSize);

View File

@@ -383,7 +383,7 @@ namespace ehs
rid[0].usUsagePage = HID_USAGE_PAGE_GENERIC; rid[0].usUsagePage = HID_USAGE_PAGE_GENERIC;
rid[0].usUsage = HID_USAGE_GENERIC_MOUSE; rid[0].usUsage = HID_USAGE_GENERIC_MOUSE;
rid[0].dwFlags = RIDEV_INPUTSINK; rid[0].dwFlags = 0;
rid[0].hwndTarget = hdl; rid[0].hwndTarget = hdl;
rid[1].usUsagePage = HID_USAGE_PAGE_GENERIC; rid[1].usUsagePage = HID_USAGE_PAGE_GENERIC;
@@ -703,11 +703,118 @@ namespace ehs
Serializer<UInt_64> Window::GetClipboard() Serializer<UInt_64> Window::GetClipboard()
{ {
return {}; if (!OpenClipboard(hdl))
{
EHS_LOG_INT(LogType::ERR, 0, "Failed to open Clipboard with error #" + Str_8::FromNum(GetLastError()) + ".");
return {};
}
HANDLE hData = GetClipboardData(CF_TEXT);
if (!hData)
{
EHS_LOG_INT(LogType::ERR, 1, "Failed to get clipboard handle with error #" + Str_8::FromNum(GetLastError()) + ".");
if (!CloseClipboard())
EHS_LOG_INT(LogType::ERR, 4, "Failed to close clipboard with error #" + Str_8::FromNum(GetLastError()) + ".");
return {};
}
Char_8* text = (Char_8 *)GlobalLock(hData);
if (!text)
{
EHS_LOG_INT(LogType::ERR, 2, "Failed to get clipboard data with error #" + Str_8::FromNum(GetLastError()) + ".");
return {};
}
Serializer<UInt_64> data(Endianness::LE, (Byte *)text, Str_8::Len(text));
if (!GlobalUnlock(hData))
{
EHS_LOG_INT(LogType::ERR, 3, "Failed to free clipboard data with error #" + Str_8::FromNum(GetLastError()) + ".");
return data;
}
if (!CloseClipboard())
{
EHS_LOG_INT(LogType::ERR, 4, "Failed to close clipboard with error #" + Str_8::FromNum(GetLastError()) + ".");
return data;
}
EHS_LOG_SUCCESS();
return data;
} }
void Window::SetClipboard(Serializer<UInt_64> data) void Window::SetClipboard(Serializer<UInt_64> data)
{ {
if (!OpenClipboard(hdl))
{
EHS_LOG_INT(LogType::ERR, 0, "Failed to open Clipboard with error #" + Str_8::FromNum(GetLastError()) + ".");
return;
}
if (!EmptyClipboard())
{
EHS_LOG_INT(LogType::ERR, 1, "Failed to empty clipboard with error #" + Str_8::FromNum(GetLastError()) + ".");
if (!CloseClipboard())
EHS_LOG_INT(LogType::ERR, 6, "Failed to close clipboard with error #" + Str_8::FromNum(GetLastError()) + ".");
return;
}
HGLOBAL hGlob = GlobalAlloc(GMEM_MOVEABLE, data.Size());
if (!hGlob)
{
EHS_LOG_INT(LogType::ERR, 2, "Failed to allocate clipboard data with error #" + Str_8::FromNum(GetLastError()) + ".");
if (!CloseClipboard())
EHS_LOG_INT(LogType::ERR, 6, "Failed to close clipboard with error #" + Str_8::FromNum(GetLastError()) + ".");
return;
}
Byte* result = (Byte *)GlobalLock(hGlob);
if (!result)
{
EHS_LOG_INT(LogType::ERR, 3, "Failed to lock data with error #" + Str_8::FromNum(GetLastError()) + ".");
GlobalFree(hGlob);
if (!CloseClipboard())
EHS_LOG_INT(LogType::ERR, 6, "Failed to close clipboard with error #" + Str_8::FromNum(GetLastError()) + ".");
return;
}
Util::Copy(result, &data[0], data.Size());
GlobalUnlock(hGlob);
HANDLE hData = SetClipboardData(CF_TEXT, hGlob);
if (!hData)
{
EHS_LOG_INT(LogType::ERR, 5, "Failed to get clipboard handle with error #" + Str_8::FromNum(GetLastError()) + ".");
GlobalFree(hGlob);
if (!CloseClipboard())
EHS_LOG_INT(LogType::ERR, 6, "Failed to close clipboard with error #" + Str_8::FromNum(GetLastError()) + ".");
return;
}
if (!CloseClipboard())
{
EHS_LOG_INT(LogType::ERR, 6, "Failed to close clipboard with error #" + Str_8::FromNum(GetLastError()) + ".");
return;
}
EHS_LOG_SUCCESS();
} }
void Window::SetCursorImg(CursorImg img) void Window::SetCursorImg(CursorImg img)

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

@@ -1,392 +0,0 @@
#include "ehs/io/audio/AudioDevice_ALSA.h"
#include "ehs/EHS.h"
#include "ehs/Log.h"
#include "ehs/io/Console.h"
namespace ehs
{
AudioDevice::~AudioDevice()
{
if (!hdl)
return;
snd_pcm_drain(hdl);
snd_pcm_close(hdl);
}
AudioDevice::AudioDevice()
: hdl(nullptr)
{
}
AudioDevice::AudioDevice(AudioDevice&& device) noexcept
: BaseAudioDevice(device), hdl(device.hdl)
{
device.hdl = nullptr;
}
AudioDevice::AudioDevice(const AudioDevice& device)
: BaseAudioDevice(device), hdl(nullptr)
{
}
AudioDevice& AudioDevice::operator=(AudioDevice&& device) noexcept
{
if (this == &device)
return *this;
BaseAudioDevice::operator=(device);
hdl = device.hdl;
device.hdl = nullptr;
return *this;
}
AudioDevice& AudioDevice::operator=(const AudioDevice& device)
{
if (this == &device)
return *this;
BaseAudioDevice::operator=(device);
hdl = nullptr;
return *this;
}
void AudioDevice::Release()
{
if (!IsValid())
return;
snd_pcm_drain(hdl);
snd_pcm_close(hdl);
hdl = nullptr;
}
void AudioDevice::OpenStream()
{
if (streaming)
return;
snd_pcm_hw_params_t* params;
snd_pcm_hw_params_alloca(&params);
snd_pcm_hw_params_any(hdl, params);
if (snd_pcm_hw_params_set_access(hdl, params, SND_PCM_ACCESS_MMAP_INTERLEAVED) < 0)
{
EHS_LOG_INT(LogType::ERR, 0, "Failed to set access.");
return;
}
if (bitDepth)
{
snd_pcm_format_t format;
switch (dataType)
{
case DataType::FLOAT:
{
format = SND_PCM_FORMAT_FLOAT;
break;
}
case DataType::SINT_32:
{
format = SND_PCM_FORMAT_S32;
break;
}
case DataType::SINT_24:
{
format = SND_PCM_FORMAT_S24;
break;
}
case DataType::SINT_16:
{
format = SND_PCM_FORMAT_S16;
break;
}
case DataType::SINT_8:
{
format = SND_PCM_FORMAT_S8;
break;
}
default:
{
EHS_LOG_INT(LogType::ERR, 0, "Invalid data type.");
return;
}
}
snd_pcm_hw_params_set_format(hdl, params, format);
}
if (channels)
{
if (snd_pcm_hw_params_set_channels_near(hdl, params, &channels) < 0)
{
EHS_LOG_INT(LogType::ERR, 1, "Failed to set channels.");
return;
}
}
if (sampleRate)
{
if (snd_pcm_hw_params_set_rate_near(hdl, params, &sampleRate, nullptr) < 0)
{
EHS_LOG_INT(LogType::ERR, 2, "Failed to set sample rate.");
return;
}
}
if (snd_pcm_hw_params_set_period_time_near(hdl, params, &period, nullptr) < 0)
{
EHS_LOG_INT(LogType::ERR, 3, "Failed to set period.");
return;
}
if (snd_pcm_hw_params_set_buffer_time_near(hdl, params, &latency, nullptr) < 0)
{
EHS_LOG_INT(LogType::ERR, 4, "Failed to set latency.");
return;
}
if (snd_pcm_hw_params(hdl, params) < 0)
{
EHS_LOG_INT(LogType::ERR, 5, "Failed to apply hardware parameters.");
return;
}
if (!bitDepth)
{
snd_pcm_format_t format;
if (snd_pcm_hw_params_get_format(params, &format) < 0)
{
EHS_LOG_INT(LogType::ERR, 6, "Failed to retrieve audio device properties.");
return;
}
switch (format)
{
case SND_PCM_FORMAT_FLOAT:
{
dataType = DataType::FLOAT;
bitDepth = 32;
break;
}
case SND_PCM_FORMAT_S32:
{
dataType = DataType::SINT_32;
bitDepth = 32;
break;
}
case SND_PCM_FORMAT_S24:
{
dataType = DataType::SINT_24;
bitDepth = 24;
break;
}
case SND_PCM_FORMAT_S16:
{
dataType = DataType::SINT_16;
bitDepth = 16;
break;
}
case SND_PCM_FORMAT_S8:
{
dataType = DataType::SINT_8;
bitDepth = 8;
break;
}
default:
{
EHS_LOG_INT(LogType::ERR, 7, "Format unsupported.");
break;
}
}
}
if (!channels)
{
if (snd_pcm_hw_params_get_channels(params, &channels) < 0)
{
EHS_LOG_INT(LogType::ERR, 8, "Failed to retrieve channel count.");
return;
}
}
if (!sampleRate)
{
int dir;
if (snd_pcm_hw_params_get_rate(params, &sampleRate, &dir) < 0)
{
EHS_LOG_INT(LogType::ERR, 9, "Failed to retrieve sample rate.");
return;
}
}
if (snd_pcm_hw_params_get_buffer_size(params, &maxFrames) < 0)
{
EHS_LOG_INT(LogType::ERR, 10, "Failed to retrieve buffer size.");
}
snd_pcm_sw_params_t* swParams = nullptr;
snd_pcm_sw_params_alloca(&swParams);
if (snd_pcm_sw_params_current(hdl, swParams) < 0)
{
EHS_LOG_INT(LogType::ERR, 11, "Failed to retrieve software parameters.");
return;
}
if (snd_pcm_sw_params_set_silence_threshold(hdl, swParams, maxFrames) < 0)
{
EHS_LOG_INT(LogType::ERR, 12, "Failed to set silence threshold.");
return;
}
if (snd_pcm_sw_params_set_silence_size(hdl, swParams, maxFrames) < 0)
{
EHS_LOG_INT(LogType::ERR, 12, "Failed to set silence size.");
return;
}
if (snd_pcm_sw_params(hdl, swParams) < 0)
{
EHS_LOG_INT(LogType::ERR, 13, "Failed to set software parameters.");
return;
}
if (snd_pcm_prepare(hdl) < 0)
{
EHS_LOG_INT(LogType::ERR, 14, "Failed to prepare audio stream.");
return;
}
streaming = true;
}
void AudioDevice::CloseStream()
{
if (!streaming)
return;
snd_pcm_drain(hdl);
streaming = false;
}
UInt_64 AudioDevice::GetAvailFrames() const
{
snd_pcm_state_t state = snd_pcm_state(hdl);
if (state == SND_PCM_STATE_XRUN)
{
EHS_LOG_INT(LogType::WARN, 0, "Buffer overrun/underrun occurred.");
if (snd_pcm_recover(hdl, -EPIPE, 0) < 0)
{
EHS_LOG_INT(LogType::ERR, 1, "Failed to recover from buffer overrun/underrun.");
return 0;
}
return GetAvailFrames();
}
else if (state == SND_PCM_STATE_PREPARED)
{
if (snd_pcm_start(hdl) < 0)
{
EHS_LOG_INT(LogType::ERR, 2, "Failed to start audio stream.");
return 0;
}
return GetAvailFrames();
}
snd_pcm_sframes_t frames = snd_pcm_avail_update(hdl);
if (frames < 0)
{
if (frames == -EPIPE)
{
EHS_LOG_INT(LogType::WARN, 3, "Buffer overrun/underrun occurred.");
if (snd_pcm_recover(hdl, -EPIPE, 1) < 0)
{
EHS_LOG_INT(LogType::ERR, 4, "Failed to recover from buffer overrun/underrun.");
return 0;
}
return GetAvailFrames();
}
else
{
EHS_LOG_INT(LogType::ERR, 5, "Failed to retrieve available frames with error #" + Str_8::FromNum(frames) + ".");
return 0;
}
}
return frames;
}
Byte* AudioDevice::Map(UInt_64* offset, UInt_64* frames)
{
const snd_pcm_channel_area_t* areas;
if (snd_pcm_mmap_begin(hdl, &areas, offset, frames) < 0)
{
EHS_LOG_INT(LogType::ERR, 0, "Failed to map audio buffer.");
return nullptr;
}
return (Byte*)areas->addr + areas->first / 8;
}
void AudioDevice::UnMap(const UInt_64 offset, const UInt_64 frames)
{
snd_pcm_sframes_t committed = snd_pcm_mmap_commit(hdl, offset, frames);
if (committed < 0)
{
EHS_LOG_INT(LogType::ERR, 0, "Failed to commit mapped audio buffer.");
return;
}
}
bool AudioDevice::IsValid() const
{
return hdl;
}
AudioDevice AudioDevice::GetDefault(const AudioDeviceType type)
{
AudioDevice result;
snd_pcm_stream_t rType;
if (type == AudioDeviceType::INPUT)
{
rType = SND_PCM_STREAM_CAPTURE;
}
else if (type == AudioDeviceType::OUTPUT)
{
rType = SND_PCM_STREAM_PLAYBACK;
}
else
{
EHS_LOG_INT(LogType::ERR, 1, "Wrong value for the audio device type.");
return {};
}
int err = snd_pcm_open(&result.hdl, "default", rType, SND_PCM_NONBLOCK);
if (err < 0)
{
EHS_LOG_INT(LogType::ERR, 2, "Failed to retrieve default audio device with error #" + Str_8::FromNum(err) + ".");
return {};
}
result.type = AudioDeviceType::OUTPUT;
EHS_LOG_SUCCESS();
return result;
}
Array<AudioDevice> AudioDevice::Get(const AudioDeviceType type, const AudioDeviceState state)
{
return {};
}
}

View File

@@ -0,0 +1,438 @@
#include "ehs/io/audio/AudioDevice_PW.h"
#include "ehs/EHS.h"
#include "ehs/Log.h"
#include "ehs/system/Semaphore.h"
#include <spa/utils/result.h>
#include <spa/utils/dict.h>
#include <spa/buffer/buffer.h>
#include <spa/param/latency-utils.h>
namespace ehs
{
Array<AudioDevice> AudioDevice::devices;
void AudioDevice::RegistryEventGlobal(void *data, const UInt_32 id, UInt_32 permissions, const char *type, UInt_32 version, const spa_dict *props)
{
if (Str_8::Cmp(type, PW_TYPE_INTERFACE_Node))
{
const Str_8 mediaClass = spa_dict_lookup(props, PW_KEY_MEDIA_CLASS);
if (mediaClass.Size() && (mediaClass == "Audio/Sink" || mediaClass == "Audio/Source"))
{
AudioDevice device;
if (mediaClass == "Audio/Sink")
device.type = AudioDeviceType::OUTPUT;
else if (mediaClass == "Audio/Source")
device.type = AudioDeviceType::INPUT;
device.id = id;
device.name = spa_dict_lookup(props, PW_KEY_NODE_NAME);
EHS_LOG_INT(LogType::INFO, 1, "\nDevice Name: " + device.name + "\nId: " + Str_8::FromNum(device.id));
devices.Push(device);
}
}
}
void AudioDevice::RegistryEventGlobalRemove(void *data, UInt_32 id)
{
}
void AudioDevice::OnParamChanged(void *data, UInt_32 id, const spa_pod *param)
{
if (!param)
return;
if (id == SPA_PARAM_Buffers)
{
AudioDevice *device = (AudioDevice *)data;
spa_pod_object *obj = (spa_pod_object *)param;
spa_pod_prop *prop;
SPA_POD_OBJECT_FOREACH(obj, prop)
{
if (prop->key == SPA_PARAM_BUFFERS_size)
{
spa_pod_get_int(&prop->value, (int32_t *)&device->maxFrames);
device->maxFrames = device->maxFrames / device->byteDepth / device->channels;
}
}
}
}
AudioDevice::~AudioDevice()
{
if (!IsStreaming())
return;
if (output)
{
pw_stream_disconnect(output);
pw_stream_destroy(output);
output = nullptr;
}
if (input)
{
pw_stream_disconnect(input);
pw_stream_destroy(input);
input = nullptr;
}
pw_core_disconnect(core);
core = nullptr;
pw_context_destroy(context);
context = nullptr;
pw_loop_destroy(loop);
loop = nullptr;
}
AudioDevice::AudioDevice()
: id(0), loop(nullptr), context(nullptr), core(nullptr), input(nullptr), output(nullptr), paramsHook{}
{
}
AudioDevice::AudioDevice(AudioDevice&& device) noexcept
: BaseAudioDevice(device), id(device.id), name((Str_8 &&)device.name), loop(device.loop),
context(device.context), core(device.core), input(device.input), output(device.output), paramsHook(device.paramsHook)
{
device.id = 0;
device.loop = nullptr;
device.context = nullptr;
device.core = nullptr;
device.input = nullptr;
device.output = nullptr;
device.paramsHook = {};
}
AudioDevice::AudioDevice(const AudioDevice& device)
: BaseAudioDevice(device), id(device.id), name(device.name), loop(nullptr), context(nullptr), core(nullptr),
input(nullptr), output(nullptr), paramsHook{}
{
}
AudioDevice& AudioDevice::operator=(AudioDevice&& device) noexcept
{
if (this == &device)
return *this;
BaseAudioDevice::operator=(device);
id = device.id;
name = (Str_8 &&)device.name;
loop = device.loop;
context = device.context;
core = device.core;
input = device.input;
output = device.output;
paramsHook = device.paramsHook;
device.id = 0;
device.loop = nullptr;
device.context = nullptr;
device.core = nullptr;
device.input = nullptr;
device.output = nullptr;
device.paramsHook = {};
return *this;
}
AudioDevice& AudioDevice::operator=(const AudioDevice& device)
{
if (this == &device)
return *this;
BaseAudioDevice::operator=(device);
id = device.id;
name = device.name;
loop = nullptr;
context = nullptr;
core = nullptr;
input = nullptr;
output = nullptr;
paramsHook = {};
return *this;
}
void AudioDevice::OpenStream()
{
if (!IsValid() || IsStreaming())
return;
loop = pw_loop_new(nullptr);
context = pw_context_new(loop, nullptr, 0);
core = pw_context_connect(context, nullptr, 0);
spa_audio_info_raw info = {
.format = SPA_AUDIO_FORMAT_F32,
.rate = GetSampleRate(),
.channels = GetChannels(),
.position = {
SPA_AUDIO_CHANNEL_FL,
SPA_AUDIO_CHANNEL_FR,
SPA_AUDIO_CHANNEL_FC,
SPA_AUDIO_CHANNEL_LFE,
SPA_AUDIO_CHANNEL_SL,
SPA_AUDIO_CHANNEL_SR,
SPA_AUDIO_CHANNEL_RL,
SPA_AUDIO_CHANNEL_RR
}
};
pw_properties *props = pw_properties_new(
PW_KEY_MEDIA_TYPE, "Audio",
PW_KEY_MEDIA_CATEGORY, GetCategory(),
PW_KEY_MEDIA_ROLE, "Game",
nullptr
);
spa_pod_builder b = {};
Byte buffer[1024];
spa_pod_builder_init(&b, buffer, sizeof(buffer));
const spa_pod *pod[] = {spa_format_audio_raw_build(&b, SPA_PARAM_EnumFormat, &info)};
if (GetType() == AudioDeviceType::INPUT || GetType() == AudioDeviceType::ALL)
{
input = pw_stream_new(core, "", props);
if (!input)
{
EHS_LOG_INT(LogType::ERR, 1, "Failed to create input stream for audio device.");
return;
}
SInt_32 err = pw_stream_connect(
input,
PW_DIRECTION_INPUT,
id,
(pw_stream_flags)(PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_MAP_BUFFERS),
pod,
1
);
if (err)
{
EHS_LOG_INT(LogType::ERR, 2, "Failed to connect input stream for audio device.");
}
}
if (GetType() == AudioDeviceType::OUTPUT || GetType() == AudioDeviceType::ALL)
{
output = pw_stream_new(core, "", props);
if (!output)
{
EHS_LOG_INT(LogType::ERR, 1, "Failed to create output stream for audio device.");
return;
}
SInt_32 err = pw_stream_connect(
output,
PW_DIRECTION_OUTPUT,
id,
(pw_stream_flags)(PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_MAP_BUFFERS),
pod,
1
);
if (err)
{
EHS_LOG_INT(LogType::ERR, 2, "Failed to connect output stream for audio device.");
}
}
static constexpr pw_stream_events streamEvents = {
.version = PW_VERSION_STREAM_EVENTS,
.param_changed = OnParamChanged
};
pw_stream_add_listener(output, &paramsHook, &streamEvents, this);
while (pw_stream_get_state(output, nullptr) == PW_STREAM_STATE_CONNECTING)
{
SInt_32 err = pw_loop_iterate(loop, 0);
if (err < 0)
{
EHS_LOG_INT(LogType::ERR, 3, "Failed to update audio with error #" + Str_8::FromNum(err) + ".");
return;
}
}
EHS_LOG_SUCCESS();
}
void AudioDevice::CloseStream()
{
if (!IsStreaming())
return;
if (output)
{
pw_stream_disconnect(output);
pw_stream_destroy(output);
output = nullptr;
}
if (input)
{
pw_stream_disconnect(input);
pw_stream_destroy(input);
input = nullptr;
}
pw_core_disconnect(core);
core = nullptr;
pw_context_destroy(context);
context = nullptr;
pw_loop_destroy(loop);
loop = nullptr;
}
UInt_64 AudioDevice::SendStream(const void *data, const UInt_64 size)
{
if (GetType() != AudioDeviceType::OUTPUT && GetType() != AudioDeviceType::ALL)
{
EHS_LOG_INT(LogType::ERR, 0, "You can only send an audio stream on an output audio device.");
return 0;
}
if (!data || !size)
return 0;
SInt_32 err = pw_loop_iterate(loop, 0);
if (err < 0)
{
EHS_LOG_INT(LogType::ERR, 1, "Failed to update audio with error #" + Str_8::FromNum(err) + ".");
return 0;
}
if (pw_stream_get_state(output, nullptr) != PW_STREAM_STATE_STREAMING)
return 0;
pw_buffer *buf = pw_stream_dequeue_buffer(output);
if (!buf)
return 0;
UInt_64 out = 0;
spa_data &result = buf->buffer->datas[0];
if (size > result.maxsize)
out = result.maxsize;
else
out = size;
Util::Copy(result.data, data, out);
pw_stream_queue_buffer(output, buf);
EHS_LOG_SUCCESS();
return out;
}
UInt_64 AudioDevice::ReceiveStream(void *data, const UInt_64 size)
{
if (GetType() != AudioDeviceType::INPUT && GetType() != AudioDeviceType::ALL)
{
EHS_LOG_INT(LogType::ERR, 0, "You can only send an audio stream on an input audio device.");
return 0;
}
pw_loop_iterate(loop, 0);
if (pw_stream_get_state(input, nullptr) != PW_STREAM_STATE_STREAMING)
return 0;
pw_buffer *buf = pw_stream_dequeue_buffer(input);
if (!buf)
return 0;
spa_data &result = buf->buffer->datas[0];
UInt_64 in;
if (result.chunk->size <= size)
in = result.chunk->size;
else
in = size;
Util::Copy(data, result.data, in);
pw_stream_queue_buffer(input, buf);
EHS_LOG_SUCCESS();
return in;
}
bool AudioDevice::IsStreaming() const
{
return loop && context && core && (input || output);
}
bool AudioDevice::IsValid() const
{
return id;
}
AudioDevice AudioDevice::GetDefault(const AudioDeviceType type)
{
pw_init(nullptr, nullptr);
AudioDevice result;
result.type = type;
result.id = PW_ID_ANY;
return result;
}
Array<AudioDevice> AudioDevice::Get(const AudioDeviceType type, const AudioDeviceState state)
{
pw_init(nullptr, nullptr);
pw_loop *loop = pw_loop_new(nullptr);
pw_context *context = pw_context_new(loop, nullptr, 0);
pw_core *core = pw_context_connect(context, nullptr, 0);
pw_registry *registry = pw_core_get_registry(core, PW_VERSION_REGISTRY, 0);
spa_hook listener = {};
static constexpr pw_registry_events events = {
.version = PW_VERSION_REGISTRY_EVENTS,
.global = RegistryEventGlobal,
.global_remove = RegistryEventGlobalRemove
};
pw_registry_add_listener(registry, &listener, &events, registry);
while (pw_loop_iterate(loop, 10));
pw_core_disconnect(core);
pw_context_destroy(context);
pw_loop_destroy(loop);
return devices;
}
Str_8 AudioDevice::GetCategory() const
{
switch (GetType())
{
case AudioDeviceType::INPUT:
return "Capture";
case AudioDeviceType::OUTPUT:
return "Playback";
case AudioDeviceType::ALL:
return "Duplex";
default:
return "";
}
}
}

View File

@@ -68,37 +68,9 @@ namespace ehs
return *this; return *this;
} }
void AudioDevice::Release()
{
if (captureClient)
{
captureClient->Release();
captureClient = nullptr;
}
if (playbackClient)
{
playbackClient->Release();
playbackClient = nullptr;
}
if (hdl)
{
HRESULT r = client->Stop();
if (FAILED(r))
{
EHS_LOG_INT(LogType::ERR, 0, "Failed to stop audio with error #" + Str_8::FromNum(r) + ".");
return;
}
hdl->Release();
hdl = nullptr;
}
}
void AudioDevice::OpenStream() void AudioDevice::OpenStream()
{ {
if (streaming) if (IsStreaming())
return; return;
HRESULT r = hdl->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, (void**)&client); HRESULT r = hdl->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, (void**)&client);
@@ -108,14 +80,14 @@ namespace ehs
WAVEFORMATEXTENSIBLE* format; WAVEFORMATEXTENSIBLE* format;
client->GetMixFormat((WAVEFORMATEX**)&format); client->GetMixFormat((WAVEFORMATEX**)&format);
if (bitDepth) if (byteDepth)
{ {
if (dataType == DataType::FLOAT) if (dataType == DataType::FLOAT)
format->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; format->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
else else
format->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; format->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
format->Format.wBitsPerSample = bitDepth; format->Format.wBitsPerSample = byteDepth * 8;
} }
else else
{ {
@@ -124,7 +96,7 @@ namespace ehs
else else
dataType = FromAudioBitDepth(format->Format.wBitsPerSample); dataType = FromAudioBitDepth(format->Format.wBitsPerSample);
bitDepth = format->Format.wBitsPerSample; byteDepth = format->Format.wBitsPerSample / 8;
} }
if (sampleRate) if (sampleRate)
@@ -137,7 +109,7 @@ namespace ehs
else else
channels = format->Format.nChannels; channels = format->Format.nChannels;
format->Format.nBlockAlign = bitDepth / 8 * channels; format->Format.nBlockAlign = byteDepth * channels;
format->Format.nAvgBytesPerSec = format->Format.nBlockAlign * sampleRate; format->Format.nAvgBytesPerSec = format->Format.nBlockAlign * sampleRate;
WAVEFORMATEX* match = {}; WAVEFORMATEX* match = {};
@@ -293,12 +265,12 @@ namespace ehs
return; return;
} }
streaming = true; EHS_LOG_SUCCESS();
} }
void AudioDevice::CloseStream() void AudioDevice::CloseStream()
{ {
if (!streaming) if (!IsStreaming())
return; return;
if (playbackClient) if (playbackClient)
@@ -324,98 +296,134 @@ namespace ehs
client->Release(); client->Release();
client = nullptr; client = nullptr;
hdl->Release();
hdl = nullptr;
} }
streaming = false; EHS_LOG_SUCCESS();
} }
UInt_64 AudioDevice::GetAvailFrames() const UInt_64 AudioDevice::SendStream(const void *data, UInt_64 outFrameSize)
{ {
if (!IsValid() || !streaming) if (!IsValid() || !IsStreaming() || !playbackClient || !data || !outFrameSize)
return 0; return 0;
UInt_32 sampleSize = 0; UInt_32 frameOffset = 0;
if (playbackClient) HRESULT r = client->GetCurrentPadding(&frameOffset);
if (r == AUDCLNT_E_DEVICE_INVALIDATED)
{ {
HRESULT r = client->GetCurrentPadding(&sampleSize); EHS_LOG_INT(LogType::WARN, 0, "The audio device has been invalidated.");
if (r == AUDCLNT_E_DEVICE_INVALIDATED) return 0;
EHS_LOG_INT(LogType::ERR, 0, "The audio device has been invalidated.");
else if (FAILED(r))
EHS_LOG_INT(LogType::ERR, 1, "Failed to retrieve samples padding with error #" + Str_8::FromNum(r) + ".");
sampleSize = maxFrames - sampleSize;
} }
else if (captureClient) else if (FAILED(r))
{ {
HRESULT r = captureClient->GetNextPacketSize(&sampleSize); EHS_LOG_INT(LogType::ERR, 1, "Failed to retrieve samples padding with error #" + Str_8::FromNum(r) + ".");
if (r == AUDCLNT_E_DEVICE_INVALIDATED) return 0;
EHS_LOG_INT(LogType::ERR, 0, "The audio device has been invalidated.");
else if (FAILED(r))
EHS_LOG_INT(LogType::ERR, 1, "Failed to retrieve samples size with error #" + Str_8::FromNum(r) + ".");
} }
return sampleSize; UInt_32 frameSize = maxFrames - frameOffset;
if (frameSize > outFrameSize)
frameSize = outFrameSize;
Byte *buffer = nullptr;
r = playbackClient->GetBuffer(frameSize, &buffer);
if (r == AUDCLNT_E_DEVICE_INVALIDATED)
{
EHS_LOG_INT(LogType::WARN, 2, "The audio device has been invalidated.");
return 0;
}
else if (FAILED(r))
{
EHS_LOG_INT(LogType::ERR, 3, "Failed to retrieve buffer with error #" + Str_8::FromNum(r) + ".");
return 0;
}
Util::Copy(buffer, data, frameSize * byteDepth * channels);
r = playbackClient->ReleaseBuffer(frameSize, 0);
if (r == AUDCLNT_E_DEVICE_INVALIDATED)
{
EHS_LOG_INT(LogType::WARN, 4, "The audio device has been invalidated.");
return 0;
}
else if (FAILED(r))
{
EHS_LOG_INT(LogType::ERR, 5, "Failed to release buffer with error #" + Str_8::FromNum(r) + ".");
return 0;
}
return frameSize;
} }
Byte* AudioDevice::Map(UInt_64* offset, UInt_64* frames) UInt_64 AudioDevice::ReceiveStream(void *data, UInt_64 inFrameSize)
{ {
if (!IsValid() || !IsStreaming() || !captureClient || !data || !inFrameSize)
return 0;
UInt_32 frameSize = 0;
HRESULT r = captureClient->GetNextPacketSize(&frameSize);
if (r == AUDCLNT_E_DEVICE_INVALIDATED)
{
EHS_LOG_INT(LogType::WARN, 0, "The audio device has been invalidated.");
return 0;
}
else if (FAILED(r))
{
EHS_LOG_INT(LogType::ERR, 1, "Failed to retrieve samples size with error #" + Str_8::FromNum(r) + ".");
return 0;
}
if (frameSize > inFrameSize)
frameSize = inFrameSize;
UInt_64 frameOffset = 0;
r = client->GetCurrentPadding((UINT32*)&frameOffset);
if (r == AUDCLNT_E_DEVICE_INVALIDATED)
{
EHS_LOG_INT(LogType::WARN, 2, "The audio device has been invalidated.");
return 0;
}
else if (FAILED(r))
{
EHS_LOG_INT(LogType::ERR, 3, "Failed to retrieve samples padding with error #" + Str_8::FromNum(r) + ".");
return 0;
}
UInt_32 flags = 0;
Byte* buffer = nullptr; Byte* buffer = nullptr;
if (!IsValid()) r = captureClient->GetBuffer(&buffer, (UINT32*)&frameSize, (DWORD*)&flags, nullptr, nullptr);
return buffer;
HRESULT r = client->GetCurrentPadding((UINT32*)&offset);
if (r == AUDCLNT_E_DEVICE_INVALIDATED) if (r == AUDCLNT_E_DEVICE_INVALIDATED)
EHS_LOG_INT(LogType::ERR, 0, "The audio device has been invalidated."); {
EHS_LOG_INT(LogType::WARN, 4, "The audio device has been invalidated.");
return 0;
}
else if (FAILED(r)) else if (FAILED(r))
EHS_LOG_INT(LogType::ERR, 1, "Failed to retrieve samples padding with error #" + Str_8::FromNum(r) + ".");
if (playbackClient)
{ {
r = playbackClient->GetBuffer(*frames, &buffer); EHS_LOG_INT(LogType::ERR, 5, "Failed to retrieve buffer with error #" + Str_8::FromNum(r) + ".");
if (r == AUDCLNT_E_BUFFER_TOO_LARGE) return 0;
EHS_LOG_INT(LogType::ERR, 0, "The given frame size, " + Str_8::FromNum(*frames) + ", must be less than or equal to, " + Str_8::FromNum(maxFrames - *offset) + ".");
else if (r == AUDCLNT_E_DEVICE_INVALIDATED)
EHS_LOG_INT(LogType::ERR, 1, "The audio device has been invalidated.");
else if (FAILED(r))
EHS_LOG_INT(LogType::ERR, 2, "Failed to retrieve buffer with error #" + Str_8::FromNum(r) + ".");
}
else if (captureClient)
{
UInt_32 flags = 0;
r = captureClient->GetBuffer(&buffer, (UINT32*)frames, (DWORD*)&flags, nullptr, nullptr);
if (r == AUDCLNT_E_DEVICE_INVALIDATED)
EHS_LOG_INT(LogType::ERR, 1, "The audio device has been invalidated.");
else if (FAILED(r))
EHS_LOG_INT(LogType::ERR, 2, "Failed to retrieve buffer with error #" + Str_8::FromNum(r) + ".");
} }
return buffer; Util::Copy(data, &buffer[frameOffset], frameSize * byteDepth * channels);
}
void AudioDevice::UnMap(const UInt_64 offset, const UInt_64 frames) r = captureClient->ReleaseBuffer(frameSize);
{ if (r == AUDCLNT_E_DEVICE_INVALIDATED)
if (!IsValid() || !streaming) {
return; EHS_LOG_INT(LogType::WARN, 6, "The audio device has been invalidated.");
return 0;
}
else if (FAILED(r))
{
EHS_LOG_INT(LogType::ERR, 7, "Failed to release buffer with error #" + Str_8::FromNum(r) + ".");
return 0;
}
if (playbackClient) EHS_LOG_SUCCESS();
{
HRESULT r = playbackClient->ReleaseBuffer(frames, 0); return frameSize;
if (r == AUDCLNT_E_DEVICE_INVALIDATED)
EHS_LOG_INT(LogType::ERR, 0, "The audio device has been invalidated.");
else if (FAILED(r))
EHS_LOG_INT(LogType::ERR, 1, "Failed to release buffer with error #" + Str_8::FromNum(r) + ".");
}
else if (captureClient)
{
HRESULT r = captureClient->ReleaseBuffer(frames);
if (r == AUDCLNT_E_DEVICE_INVALIDATED)
EHS_LOG_INT(LogType::ERR, 0, "The audio device has been invalidated.");
else if (FAILED(r))
EHS_LOG_INT(LogType::ERR, 1, "Failed to release buffer with error #" + Str_8::FromNum(r) + ".");
}
} }
Str_32 AudioDevice::GetInterfaceName_32() const Str_32 AudioDevice::GetInterfaceName_32() const
@@ -484,6 +492,11 @@ namespace ehs
return UTF::To_8(GetName_16()); return UTF::To_8(GetName_16());
} }
bool AudioDevice::IsStreaming() const
{
return hdl && client && (playbackClient || captureClient);
}
bool AudioDevice::IsValid() const bool AudioDevice::IsValid() const
{ {
return hdl; return hdl;

View File

@@ -1,16 +1,17 @@
#include "ehs/io/audio/BaseAudioDevice.h" #include "ehs/io/audio/BaseAudioDevice.h"
#include "ehs/Log.h"
namespace ehs namespace ehs
{ {
BaseAudioDevice::BaseAudioDevice() BaseAudioDevice::BaseAudioDevice()
: type(AudioDeviceType::ALL), dataType(DataType::SINT_8), bitDepth(0), sampleRate(0), channels(0), : type(AudioDeviceType::ALL), dataType(DataType::SINT_8), byteDepth(0), sampleRate(0), channels(0),
period(20000), latency(150000), maxFrames(0), streaming(false) period(20000), latency(150000), maxFrames(0)
{ {
} }
BaseAudioDevice::BaseAudioDevice(const BaseAudioDevice& device) BaseAudioDevice::BaseAudioDevice(const BaseAudioDevice& device)
: type(device.type), dataType(device.dataType), bitDepth(device.bitDepth), sampleRate(device.sampleRate), : type(device.type), dataType(device.dataType), byteDepth(device.byteDepth), sampleRate(device.sampleRate),
channels(device.channels), period(device.period), latency(device.latency), maxFrames(0), streaming(false) channels(device.channels), period(device.period), latency(device.latency), maxFrames(0)
{ {
} }
@@ -21,21 +22,16 @@ namespace ehs
type = device.type; type = device.type;
dataType = device.dataType; dataType = device.dataType;
bitDepth = device.bitDepth; byteDepth = device.byteDepth;
sampleRate = device.sampleRate; sampleRate = device.sampleRate;
channels = device.channels; channels = device.channels;
period = device.period; period = device.period;
latency = device.latency; latency = device.latency;
maxFrames = device.maxFrames; maxFrames = device.maxFrames;
streaming = false;
return *this; return *this;
} }
void BaseAudioDevice::Release()
{
}
void BaseAudioDevice::OpenStream() void BaseAudioDevice::OpenStream()
{ {
} }
@@ -44,32 +40,72 @@ namespace ehs
{ {
} }
UInt_64 BaseAudioDevice::GetAvailFrames() const UInt_64 BaseAudioDevice::SendStream(const void *data, const UInt_64 size)
{ {
return 0; return 0;
} }
Byte* BaseAudioDevice::Map(UInt_64* offset, UInt_64* frames) UInt_64 BaseAudioDevice::ReceiveStream(void *data, const UInt_64 size)
{ {
return nullptr; return 0;
} }
void BaseAudioDevice::UnMap(const UInt_64 offset, const UInt_64 frames) void BaseAudioDevice::BridgeStreams(BaseAudioDevice* input, UInt_64 frameBufferSize)
{ {
if (type != AudioDeviceType::OUTPUT)
{
EHS_LOG_INT(LogType::WARN, 0, "The current audio device object is not an output device.");
return;
}
if (input->type != AudioDeviceType::INPUT)
{
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);
while (result)
result -= SendStream(&buffer[(frameBufferSize - result) * GetFrameSize()], result);
delete[] buffer;
EHS_LOG_SUCCESS();
} }
AudioDeviceType BaseAudioDevice::GetType() const 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
{ {
return type; return type;
} }
void BaseAudioDevice::SetDataType(const DataType newDataType) void BaseAudioDevice::SetDataType(const DataType newDataType)
{ {
if (streaming) if (IsStreaming())
return; return;
dataType = newDataType; dataType = newDataType;
bitDepth = ToBitDepth(newDataType); byteDepth = ToByteDepth(newDataType);
} }
DataType BaseAudioDevice::GetDataType() const DataType BaseAudioDevice::GetDataType() const
@@ -79,17 +115,17 @@ namespace ehs
UInt_8 BaseAudioDevice::GetByteDepth() const UInt_8 BaseAudioDevice::GetByteDepth() const
{ {
return bitDepth / 8; return byteDepth;
} }
UInt_16 BaseAudioDevice::GetBitDepth() const UInt_16 BaseAudioDevice::GetBitDepth() const
{ {
return bitDepth; return byteDepth * 8;
} }
void BaseAudioDevice::SetSampleRate(const UInt_32 newSampleRate) void BaseAudioDevice::SetSampleRate(const UInt_32 newSampleRate)
{ {
if (streaming) if (IsStreaming())
return; return;
sampleRate = newSampleRate; sampleRate = newSampleRate;
@@ -102,7 +138,7 @@ namespace ehs
void BaseAudioDevice::SetChannels(const UInt_32 newChannels) void BaseAudioDevice::SetChannels(const UInt_32 newChannels)
{ {
if (streaming) if (IsStreaming())
return; return;
channels = newChannels; channels = newChannels;
@@ -115,12 +151,12 @@ namespace ehs
UInt_32 BaseAudioDevice::GetFrameSize() const UInt_32 BaseAudioDevice::GetFrameSize() const
{ {
return bitDepth / 8 * channels; return byteDepth * channels;
} }
void BaseAudioDevice::SetPeriod(const UInt_32 newPeriod) void BaseAudioDevice::SetPeriod(const UInt_32 newPeriod)
{ {
if (streaming) if (IsStreaming())
return; return;
period = newPeriod; period = newPeriod;
@@ -133,7 +169,7 @@ namespace ehs
void BaseAudioDevice::SetLatency(const UInt_32 newLatency) void BaseAudioDevice::SetLatency(const UInt_32 newLatency)
{ {
if (streaming) if (IsStreaming())
return; return;
latency = newLatency; latency = newLatency;
@@ -151,7 +187,7 @@ namespace ehs
bool BaseAudioDevice::IsStreaming() const bool BaseAudioDevice::IsStreaming() const
{ {
return streaming; return false;
} }
bool BaseAudioDevice::IsValid() const bool BaseAudioDevice::IsValid() const

View File

@@ -7,44 +7,68 @@ namespace ehs
{ {
} }
Button::Button(const Str_8& name) Button::Button(Str_8 name)
: name(name), hash(name.Hash_32()) : hash(name.Hash_32()), name((Str_8 &&)name)
{ {
} }
Button::Button(const Button& key) Button::Button(Button &&key) noexcept
: name(key.name), hash(key.hash) : hash(key.hash), name((Str_8 &&)key.name)
{
key.hash = 0;
}
Button::Button(const Button &key)
: hash(key.hash), name(key.name)
{ {
} }
Button& Button::operator=(const Button& key) Button & Button::operator=(Button &&key) noexcept
{ {
if (this == &key) if (this == &key)
return *this; return *this;
name = key.name;
hash = key.hash; hash = key.hash;
name = (Str_8 &&)key.name;
key.hash = 0;
return *this; return *this;
} }
bool Button::operator==(const Button& key) const Button &Button::operator=(const Button &key)
{
if (this == &key)
return *this;
hash = key.hash;
name = key.name;
return *this;
}
bool Button::operator==(const Button &key) const
{ {
return key.hash == hash; return key.hash == hash;
} }
bool Button::operator!=(const Button& key) const bool Button::operator!=(const Button &key) const
{ {
return key.hash != hash; return key.hash != hash;
} }
UInt_32 Button::GetHash() const
{
return hash;
}
Str_8 Button::GetName() const Str_8 Button::GetName() const
{ {
return name; return name;
} }
UInt_32 Button::GetHash() const bool Button::IsValid() const
{ {
return hash; return hash;
} }
} }

View File

@@ -1,26 +1,39 @@
#include "ehs/io/hid/HID.h" #include "ehs/io/hid/HID.h"
#include "ehs/Log.h"
#include "ehs/Math.h"
#include "ehs/io/hid/Keyboard.h"
namespace ehs namespace ehs
{ {
HID::HID() HID::HID()
: type(EHS_HID_UNKNOWN), id(0) : type(EHS_HID_UNKNOWN), hashName(0), id(0), heldTime(0.0), activateTime(0.0f), active(false)
{ {
} }
HID::HID(const UInt_8 type, Str_8 name, const UInt_64 id) HID::HID(const UInt_8 type, Str_8 name, const UInt_64 id)
: type(type), name((Str_8&&)name), id(id) : type(type), hashName(name.Hash_64()), name((Str_8 &&)name), id(id), heldTime(0.0f), activateTime(0.0f),
active(false)
{ {
} }
HID::HID(HID&& hid) noexcept HID::HID(HID&& hid) noexcept
: type(hid.type), name((Str_8&&)hid.name), id(hid.id), states((Array<ButtonState>&&)hid.states) : type(hid.type), hashName(hid.hashName), name((Str_8&&)hid.name), id(hid.id),
states((Array<ButtonState> &&)hid.states), lastState((Button &&)hid.lastState), heldTime(hid.heldTime),
activateTime(hid.activateTime), active(hid.active)
{ {
hid.type = EHS_HID_UNKNOWN; hid.type = EHS_HID_UNKNOWN;
hid.hashName = 0;
hid.id = 0; hid.id = 0;
hid.lastState = {};
hid.heldTime = 0.0f;
hid.activateTime = 0.0f;
hid.active = false;
} }
HID::HID(const HID& hid) HID::HID(const HID& hid)
: type(hid.type), name(hid.name), id(hid.id), states(hid.states) : type(hid.type), hashName(hid.hashName), name(hid.name), id(hid.id), states(hid.states), heldTime(0.0f),
activateTime(0.0f), active(false)
{ {
} }
@@ -30,12 +43,22 @@ namespace ehs
return *this; return *this;
type = hid.type; type = hid.type;
hashName = hid.hashName;
name = (Str_8&&)hid.name; name = (Str_8&&)hid.name;
id = hid.id; id = hid.id;
states = (Array<ButtonState>&&)hid.states; states = (Array<ButtonState> &&)hid.states;
lastState = (Button &&)hid.lastState;
heldTime = hid.heldTime;
activateTime = hid.activateTime;
active = hid.active;
hid.type = EHS_HID_UNKNOWN; hid.type = EHS_HID_UNKNOWN;
hid.hashName = 0;
hid.id = 0; hid.id = 0;
hid.lastState = {};
hid.heldTime = 0.0f;
hid.activateTime = 0.0f;
hid.active = false;
return *this; return *this;
} }
@@ -46,9 +69,14 @@ namespace ehs
return *this; return *this;
type = hid.type; type = hid.type;
hashName = hid.hashName;
name = hid.name; name = hid.name;
id = hid.id; id = hid.id;
states = hid.states; states = hid.states;
lastState = {};
heldTime = 0.0f;
activateTime = 0.0f;
active = false;
return *this; return *this;
} }
@@ -73,16 +101,30 @@ namespace ehs
return id != otherId; return id != otherId;
} }
void HID::Poll() void HID::Poll(const float delta)
{ {
for (UInt_64 i = 0; i < states.Size(); ++i) for (UInt_64 i = 0; i < states.Size(); ++i)
{ {
if (states[i].IsPressed()) if (states[i].IsPressed())
{ {
if (states[i].GetState() == State::RELEASED) if (states[i].GetState() == State::RELEASED)
{
states[i].SetState(State::TOUCHED); states[i].SetState(State::TOUCHED);
lastState = states[i].GetButton();
ResetTime();
active = true;
}
else else
{
states[i].SetState(State::PRESSED); states[i].SetState(State::PRESSED);
if (lastState == states[i].GetButton())
{
if (TickHoldTime(delta))
TickActivateTime(delta);
}
}
} }
else else
{ {
@@ -90,6 +132,13 @@ namespace ehs
states[i].SetState(State::JUST_RELEASED); states[i].SetState(State::JUST_RELEASED);
else else
states[i].SetState(State::RELEASED); states[i].SetState(State::RELEASED);
if (lastState == states[i].GetButton())
{
lastState = {};
ResetTime();
active = false;
}
} }
} }
} }
@@ -149,7 +198,7 @@ namespace ehs
Vector<const ButtonState*> result(0, states.Size() + 1); Vector<const ButtonState*> result(0, states.Size() + 1);
for (UInt_64 i = 0; i < states.Size(); i++) for (UInt_64 i = 0; i < states.Size(); i++)
if (states[i] == State::PRESSED || states[i] == State::TOUCHED) if (states[i] == State::PRESSED)
result.Push(&states[i]); result.Push(&states[i]);
return result; return result;
@@ -158,7 +207,7 @@ namespace ehs
const ButtonState* HID::IsDown(const Button& button) const const ButtonState* HID::IsDown(const Button& button) const
{ {
const ButtonState* state = GetState(button); const ButtonState* state = GetState(button);
if (!state || (*state != State::PRESSED && *state != State::TOUCHED)) if (!state || (*state != State::PRESSED))
return nullptr; return nullptr;
return state; return state;
@@ -167,7 +216,7 @@ namespace ehs
const ButtonState* HID::IsDown() const const ButtonState* HID::IsDown() const
{ {
for (UInt_64 i = 0; i < states.Size(); i++) for (UInt_64 i = 0; i < states.Size(); i++)
if (states[i] == State::PRESSED || states[i] == State::TOUCHED) if (states[i] == State::PRESSED)
return &states[i]; return &states[i];
return nullptr; return nullptr;
@@ -231,6 +280,22 @@ namespace ehs
return nullptr; return nullptr;
} }
const ButtonState *HID::IsPressed(const Button &button)
{
if (active && lastState == button)
return GetState(lastState);
return nullptr;
}
const ButtonState *HID::GetPressed()
{
if (active)
return GetState(lastState);
return nullptr;
}
void HID::ButtonDown(const Button& button) void HID::ButtonDown(const Button& button)
{ {
if (ButtonState* state = GetState(button); state) if (ButtonState* state = GetState(button); state)
@@ -249,6 +314,9 @@ namespace ehs
const ButtonState* HID::GetState(const Button& button) const const ButtonState* HID::GetState(const Button& button) const
{ {
if (!button.IsValid())
return nullptr;
for (UInt_64 i = 0; i < states.Size(); ++i) for (UInt_64 i = 0; i < states.Size(); ++i)
if (states[i] == button) if (states[i] == button)
return &states[i]; return &states[i];
@@ -287,10 +355,42 @@ namespace ehs
ButtonState* HID::GetState(const Button& button) ButtonState* HID::GetState(const Button& button)
{ {
if (!button.IsValid())
return nullptr;
for (UInt_64 i = 0; i < states.Size(); i++) for (UInt_64 i = 0; i < states.Size(); i++)
if (states[i].GetButton() == button) if (states[i].GetButton() == button)
return &states[i]; return &states[i];
return nullptr; return nullptr;
} }
}
bool HID::TickHoldTime(const float delta)
{
if ((heldTime += delta) > 0.5f)
return true;
active = false;
return false;
}
void HID::ResetTime()
{
heldTime = 0.0f;
activateTime = 0.0f;
}
void HID::TickActivateTime(const float delta)
{
if ((activateTime += delta) > 0.075f)
{
activateTime = ehs::Math::Mod(activateTime, 0.075f);
active = true;
}
else
{
active = false;
}
}
}

View File

@@ -1,5 +1,7 @@
#include "ehs/io/hid/InputHandler.h" #include "ehs/io/hid/InputHandler.h"
#include "ehs/system/CPU.h"
namespace ehs namespace ehs
{ {
InputHandler::~InputHandler() InputHandler::~InputHandler()
@@ -9,23 +11,24 @@ namespace ehs
} }
InputHandler::InputHandler() InputHandler::InputHandler()
: hashId(0) : hashId(0), start(0)
{ {
} }
InputHandler::InputHandler(Str_8 id) InputHandler::InputHandler(Str_8 id)
: hashId(id.Hash_64()), id((Str_8&&)id) : hashId(id.Hash_64()), id((Str_8&&)id), start(CPU::GetTSC())
{ {
} }
InputHandler::InputHandler(InputHandler&& ih) noexcept InputHandler::InputHandler(InputHandler&& ih) noexcept
: hashId(ih.hashId), id((Str_8&&)ih.id), devices((Array<HID*>&&)ih.devices) : hashId(ih.hashId), id((Str_8&&)ih.id), devices((Array<HID*>&&)ih.devices), start(ih.start)
{ {
ih.hashId = 0; ih.hashId = 0;
ih.start = 0;
} }
InputHandler::InputHandler(const InputHandler& ih) InputHandler::InputHandler(const InputHandler& ih)
: hashId(ih.hashId), id(ih.id), devices(ih.devices.Size()) : hashId(ih.hashId), id(ih.id), devices(ih.devices.Size()), start(ih.start)
{ {
for (UInt_64 i = 0; i < devices.Size(); i++) for (UInt_64 i = 0; i < devices.Size(); i++)
devices[i] = ih.devices[i]->Clone(); devices[i] = ih.devices[i]->Clone();
@@ -39,8 +42,10 @@ namespace ehs
hashId = ih.hashId; hashId = ih.hashId;
id = (Str_8&&)ih.id; id = (Str_8&&)ih.id;
devices = (Array<HID*>&&)ih.devices; devices = (Array<HID*>&&)ih.devices;
start = ih.start;
ih.hashId = 0; ih.hashId = 0;
ih.start = 0;
return *this; return *this;
} }
@@ -56,6 +61,7 @@ namespace ehs
hashId = ih.hashId; hashId = ih.hashId;
id = ih.id; id = ih.id;
devices = Array<HID*>(ih.devices.Size()); devices = Array<HID*>(ih.devices.Size());
start = ih.start;
for (UInt_64 i = 0; i < devices.Size(); i++) for (UInt_64 i = 0; i < devices.Size(); i++)
devices[i] = ih.devices[i]->Clone(); devices[i] = ih.devices[i]->Clone();
@@ -63,12 +69,12 @@ namespace ehs
return *this; return *this;
} }
bool InputHandler::operator==(const UInt_64 otherHashId) bool InputHandler::operator==(const UInt_64 otherHashId) const
{ {
return hashId == otherHashId; return hashId == otherHashId;
} }
bool InputHandler::operator!=(const UInt_64 otherHashId) bool InputHandler::operator!=(const UInt_64 otherHashId) const
{ {
return hashId != otherHashId; return hashId != otherHashId;
} }
@@ -96,8 +102,14 @@ namespace ehs
void InputHandler::Poll() void InputHandler::Poll()
{ {
static UInt_64 freq = CPU::GetTSC_Freq();
const UInt_64 newTSC = CPU::GetTSC();
delta = newTSC - start;
start = newTSC;
for (UInt_64 i = 0; i < devices.Size(); i++) for (UInt_64 i = 0; i < devices.Size(); i++)
devices[i]->Poll(); devices[i]->Poll((float)delta / (float)freq);
} }
UInt_64 InputHandler::GetHashId() const UInt_64 InputHandler::GetHashId() const
@@ -157,4 +169,4 @@ namespace ehs
{ {
return false; return false;
} }
} }

View File

@@ -7,7 +7,7 @@ namespace ehs
} }
Keyboard::Keyboard(Str_8 name, const UInt_64 id) Keyboard::Keyboard(Str_8 name, const UInt_64 id)
: HID(EHS_HID_KEYBOARD, (Str_8&&)name, id) : HID(EHS_HID_KEYBOARD, (Str_8 &&)name, id)
{ {
} }
@@ -26,9 +26,9 @@ namespace ehs
return *this; return *this;
} }
void Keyboard::Poll() void Keyboard::Poll(const float delta)
{ {
HID::Poll(); HID::Poll(delta);
} }
Keyboard* Keyboard::Clone() const Keyboard* Keyboard::Clone() const
@@ -36,93 +36,6 @@ namespace ehs
return new Keyboard(*this); return new Keyboard(*this);
} }
const Button Keyboard::Unknown("Unknown");
const Button Keyboard::Escape("Escape Button");
const Button Keyboard::Backspace("Backspace Button");
const Button Keyboard::Enter("Enter Button");
const Button Keyboard::LShift("Left Shift Button");
const Button Keyboard::RShift("Right Shift Button");
const Button Keyboard::LAlt("Left Alt Button");
const Button Keyboard::RAlt("Right Alt Button");
const Button Keyboard::LCtrl("Left Control Button");
const Button Keyboard::RCtrl("Right Control Button");
const Button Keyboard::Space("Space Button");
const Button Keyboard::A("A Button");
const Button Keyboard::B("B Button");
const Button Keyboard::C("C Button");
const Button Keyboard::D("D Button");
const Button Keyboard::E("E Button");
const Button Keyboard::F("F Button");
const Button Keyboard::G("G Button");
const Button Keyboard::H("H Button");
const Button Keyboard::I("I Button");
const Button Keyboard::J("J Button");
const Button Keyboard::K("K Button");
const Button Keyboard::L("L Button");
const Button Keyboard::M("M Button");
const Button Keyboard::N("N Button");
const Button Keyboard::O("O Button");
const Button Keyboard::P("P Button");
const Button Keyboard::Q("Q Button");
const Button Keyboard::R("R Button");
const Button Keyboard::S("S Button");
const Button Keyboard::T("T Button");
const Button Keyboard::U("U Button");
const Button Keyboard::V("V Button");
const Button Keyboard::W("W Button");
const Button Keyboard::X("X Button");
const Button Keyboard::Y("Y Button");
const Button Keyboard::Z("Z Button");
const Button Keyboard::One("One Button");
const Button Keyboard::Two("Two Button");
const Button Keyboard::Three("Three Button");
const Button Keyboard::Four("Four Button");
const Button Keyboard::Five("Five Button");
const Button Keyboard::Six("Six Button");
const Button Keyboard::Seven("Seven Button");
const Button Keyboard::Eight("Eight Button");
const Button Keyboard::Nine("Nine Button");
const Button Keyboard::Zero("Zero Button");
const Button Keyboard::Equals("Equals Button");
const Button Keyboard::Minus("Minus Button");
const Button Keyboard::Tilde("Tilde Button");
const Button Keyboard::BackSlash("Back Slash Button");
const Button Keyboard::LeftSquareBracket("Left Square Bracket Button");
const Button Keyboard::RightSquareBracket("Right Square Bracket Button");
const Button Keyboard::SemiColon("Semi-Colon Button");
const Button Keyboard::Apostrophe("Apostrophe Button");
const Button Keyboard::Comma("Comma Button");
const Button Keyboard::Period("Period Button");
const Button Keyboard::ForwardSlash("Forward Slash Button");
const Button Keyboard::F1("Function 1 Button");
const Button Keyboard::F2("Function 2 Button");
const Button Keyboard::F3("Function 3 Button");
const Button Keyboard::F4("Function 4 Button");
const Button Keyboard::F5("Function 5 Button");
const Button Keyboard::F6("Function 6 Button");
const Button Keyboard::F7("Function 7 Button");
const Button Keyboard::F8("Function 8 Button");
const Button Keyboard::F9("Function 9 Button");
const Button Keyboard::F10("Function 10 Button");
const Button Keyboard::F11("Function 11 Button");
const Button Keyboard::F12("Function 12 Button");
const Button Keyboard::F13("Function 13 Button");
const Button Keyboard::F14("Function 14 Button");
const Button Keyboard::F15("Function 15 Button");
const Button Keyboard::F16("Function 16 Button");
const Button Keyboard::F17("Function 17 Button");
const Button Keyboard::F18("Function 18 Button");
const Button Keyboard::F19("Function 19 Button");
const Button Keyboard::F20("Function 20 Button");
const Button Keyboard::F21("Function 21 Button");
const Button Keyboard::F22("Function 22 Button");
const Button Keyboard::F23("Function 23 Button");
const Button Keyboard::F24("Function 24 Button");
const Button Keyboard::Left("Left Arrow Button");
const Button Keyboard::Right("Right Arrow Button");
const Button Keyboard::Up("Up Arrow Button");
const Button Keyboard::Down("Down Arrow Button");
Button Keyboard::TranslateScanCode(const UInt_32 code) Button Keyboard::TranslateScanCode(const UInt_32 code)
{ {
switch (code) switch (code)
@@ -268,23 +181,23 @@ namespace ehs
case 71: case 71:
return Keyboard::F13; return Keyboard::F13;
case 72: case 72:
return Keyboard::F14; return Keyboard::Up;
case 73: case 73:
return Keyboard::F15; return Keyboard::F15;
case 74: case 74:
return Keyboard::F16; return Keyboard::F16;
case 75: case 75:
return Keyboard::F17; return Keyboard::Left;
case 76: case 76:
return Keyboard::F18; return Keyboard::F18;
case 77: case 77:
return Keyboard::F19; return Keyboard::Right;
case 78: case 78:
return Keyboard::F20; return Keyboard::F20;
case 79: case 79:
return Keyboard::F21; return Keyboard::F21;
case 80: case 80:
return Keyboard::F22; return Keyboard::Down;
case 81: case 81:
return Keyboard::F23; return Keyboard::F23;
case 82: case 82:

View File

@@ -28,11 +28,11 @@ namespace ehs
return *this; return *this;
} }
void Mouse::Poll() void Mouse::Poll(const float delta)
{ {
delta = {}; this->delta = {};
HID::Poll(); HID::Poll(delta);
} }
void Mouse::SetDelta(const Vec2_s32& newDelta) void Mouse::SetDelta(const Vec2_s32& newDelta)
@@ -50,19 +50,6 @@ namespace ehs
return new Mouse(*this); return new Mouse(*this);
} }
const Button Mouse::Unknown("Unknown");
const Button Mouse::LMB("Left Mouse Button");
const Button Mouse::MMB("Middle Mouse Button");
const Button Mouse::RMB("Right Mouse Button");
const Button Mouse::Four("Mouse Button Four");
const Button Mouse::Five("Mouse Button Five");
const Button Mouse::ScrollUp("Scroll Up");
const Button Mouse::ScrollDown("Scroll Down");
const Button Mouse::ScrollLeft("Scroll Left");
const Button Mouse::ScrollRight("Scroll Right");
const Button Mouse::Back("Back Mouse Button");
const Button Mouse::Forward("Forward Mouse Button");
Button Mouse::TranslateXCB(const UInt_32 code) Button Mouse::TranslateXCB(const UInt_32 code)
{ {
switch (code) switch (code)

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();
@@ -108,7 +108,7 @@ namespace ehs
if (!IsValid()) if (!IsValid())
return; return;
req.AddToHeader("Host", remoteHostName); req.AddHeaderVar({"Host", remoteHostName});
SendStr(req.FormResult()); SendStr(req.FormResult());
} }
@@ -124,10 +124,10 @@ namespace ehs
Response response(header); Response response(header);
Str_8 encoding = response.GetHeader("Transfer-Encoding"); Str_8 encoding = response.GetHeaderValue("Transfer-Encoding");
if (!encoding.Size()) if (!encoding.Size())
{ {
int bodySize = response.GetHeader("content-length").ToDecimal<int>(); int bodySize = response.GetHeaderValue("content-length").ToDecimal<int>();
if (!bodySize) if (!bodySize)
return response; return response;
@@ -163,10 +163,10 @@ namespace ehs
if (request.GetVerb() == Verb::GET) if (request.GetVerb() == Verb::GET)
return request; return request;
Str_8 encoding = request.GetHeader("Transfer-Encoding"); Str_8 encoding = request.GetHeaderValue("Transfer-Encoding");
if (!encoding.Size()) if (!encoding.Size())
{ {
int bodySize = request.GetHeader("Content-Length").ToDecimal<int>(); int bodySize = request.GetHeaderValue("Content-Length").ToDecimal<int>();
if (!bodySize) if (!bodySize)
return request; return request;
@@ -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());
}
}

View File

@@ -0,0 +1,96 @@
#include "ehs/io/socket/HeaderVar.h"
namespace ehs
{
HeaderVar::HeaderVar()
: id(0)
{
}
HeaderVar::HeaderVar(Str_8 name, Str_8 value)
: id(name.Hash_64()), name((Str_8 &&)name), value((Str_8 &&)value)
{
}
HeaderVar::HeaderVar(HeaderVar&& other) noexcept
: id(other.id), name((Str_8 &&)other.name), value((Str_8 &&)other.value)
{
other.id = 0;
}
HeaderVar::HeaderVar(const HeaderVar& other)
: id(other.id), name(other.name), value(other.value)
{
}
HeaderVar& HeaderVar::operator=(HeaderVar&& other) noexcept
{
if (this == &other)
return *this;
id = other.id;
name = (Str_8 &&)other.name;
value = (Str_8 &&)other.value;
other.id = 0;
return *this;
}
HeaderVar& HeaderVar::operator=(const HeaderVar& other)
{
if (this == &other)
return *this;
id = other.id;
name = other.name;
value = other.value;
return *this;
}
bool HeaderVar::operator==(const HeaderVar& other) const
{
return id == other.id;
}
bool HeaderVar::operator!=(const HeaderVar& other) const
{
return id != other.id;
}
bool HeaderVar::operator==(const UInt_64& otherId) const
{
return id == otherId;
}
bool HeaderVar::operator!=(const UInt_64& otherId) const
{
return id != otherId;
}
UInt_64 HeaderVar::GetId() const
{
return id;
}
Str_8 HeaderVar::GetName() const
{
return name;
}
Str_8 HeaderVar::GetValue() const
{
return value;
}
void HeaderVar::SetValue(Str_8 value)
{
this->value = (Str_8 &&)value;
}
Str_8 HeaderVar::ToStr() const
{
return name + ": " + value;
}
}

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

@@ -0,0 +1,96 @@
#include "ehs/io/socket/QueryVar.h"
namespace ehs
{
QueryVar::QueryVar()
: id(0)
{
}
QueryVar::QueryVar(Str_8 name, Str_8 value)
: id(name.Hash_64()), name((Str_8 &&)name), value((Str_8 &&)value)
{
}
QueryVar::QueryVar(QueryVar&& other) noexcept
: id(other.id), name((Str_8 &&)other.name), value((Str_8 &&)other.value)
{
other.id = 0;
}
QueryVar::QueryVar(const QueryVar& other)
: id(other.id), name(other.name), value(other.value)
{
}
QueryVar& QueryVar::operator=(QueryVar&& other) noexcept
{
if (this == &other)
return *this;
id = other.id;
name = (Str_8 &&)other.name;
value = (Str_8 &&)other.value;
other.id = 0;
return *this;
}
QueryVar& QueryVar::operator=(const QueryVar& other)
{
if (this == &other)
return *this;
id = other.id;
name = other.name;
value = other.value;
return *this;
}
bool QueryVar::operator==(const QueryVar& other) const
{
return id == other.id;
}
bool QueryVar::operator!=(const QueryVar& other) const
{
return id != other.id;
}
bool QueryVar::operator==(const UInt_64& otherId) const
{
return id == otherId;
}
bool QueryVar::operator!=(const UInt_64& otherId) const
{
return id != otherId;
}
UInt_64 QueryVar::GetId() const
{
return id;
}
Str_8 QueryVar::GetName() const
{
return name;
}
Str_8 QueryVar::GetValue() const
{
return value;
}
void QueryVar::SetValue(Str_8 value)
{
this->value = (Str_8 &&)value;
}
Str_8 QueryVar::ToStr() const
{
return name + "=" + value;
}
}

View File

@@ -4,38 +4,70 @@
namespace ehs namespace ehs
{ {
Request::Request() Request::Request()
: verb(Verb::GET), cType(ContentType::NONE) : verb(Verb::POST), cType(ContentType::NONE)
{ {
} }
Request::Request(const Verb verb, const Str_8& rsrc) Request::Request(const Verb &verb, Str_8 rsrc)
: verb(verb), rsrc(rsrc), cType(ContentType::NONE) : verb(verb), rsrc((Str_8 &&)rsrc), cType(ContentType::NONE)
{ {
} }
Request::Request(const char* data, const UInt_64 size) Request::Request(const char *data, const UInt_64 &size)
: verb(Verb::POST), cType(ContentType::NONE) : verb(Verb::POST), cType(ContentType::NONE)
{ {
ReadData(Str_8(data, size)); ReadData(Str_8(data, size));
} }
Request::Request(const Str_8& data) Request::Request(const Str_8 &data)
: verb(Verb::POST), cType(ContentType::NONE) : verb(Verb::POST), cType(ContentType::NONE)
{ {
ReadData(data); ReadData(data);
} }
Request& Request::operator=(const Request &req) Request::Request(Request&& other) noexcept
: verb(other.verb), rsrc((Str_8 &&)other.rsrc), queries((Vector<QueryVar> &&)other.queries),
header((Vector<HeaderVar> &&)other.header), cType(other.cType), body((Str_8 &&)other.body)
{ {
if (this == &req) other.verb = Verb::POST;
other.cType = ContentType::NONE;
}
Request::Request(const Request& other)
: verb(other.verb), rsrc(other.rsrc), queries(other.queries), header(other.header), cType(other.cType),
body(other.body)
{
}
Request& Request::operator=(Request&& other) noexcept
{
if (this == &other)
return *this;
verb = other.verb;
rsrc = (Str_8 &&)other.rsrc;
queries = (Vector<QueryVar> &&)other.queries;
header = (Vector<HeaderVar> &&)other.header;
cType = other.cType;
body = (Str_8 &&)other.body;
other.verb = Verb::POST;
other.cType = ContentType::NONE;
return* this;
}
Request& Request::operator=(const Request &other)
{
if (this == &other)
return *this; return *this;
verb = req.verb; verb = other.verb;
rsrc = req.rsrc; rsrc = other.rsrc;
queries = req.queries; queries = other.queries;
header = req.header; header = other.header;
cType = req.cType; cType = other.cType;
body = req.body; body = other.body;
return* this; return* this;
} }
@@ -45,7 +77,7 @@ namespace ehs
return verb; return verb;
} }
void Request::SetContentType(const ContentType cType) void Request::SetContentType(const ContentType &cType)
{ {
if (body.Size()) if (body.Size())
body.Resize(0); body.Resize(0);
@@ -58,9 +90,9 @@ namespace ehs
return cType; return cType;
} }
void Request::SetResource(const Str_8& rsrc) void Request::SetResource(Str_8 rsrc)
{ {
this->rsrc = rsrc; this->rsrc = (Str_8 &&)rsrc;
} }
Str_8 Request::GetResource() const Str_8 Request::GetResource() const
@@ -68,69 +100,179 @@ namespace ehs
return rsrc; return rsrc;
} }
void Request::AddQuery(const Str_8& var, const Str_8& value) bool Request::HasQueryVar(const UInt_64& id) const
{ {
queries.Push(var + "=" + value); for (UInt_64 i = 0; i < queries.Size(); ++i)
if (queries[i] == id)
return true;
return false;
} }
Str_8 Request::GetQuery(const Str_8& var) bool Request::HasQueryVar(const Str_8& name) const
{
return HasQueryVar(name.Hash_64());
}
bool Request::AddQueryVar(QueryVar var)
{
if (HasQueryVar(var.GetId()))
return false;
queries.Push((QueryVar &&)var);
return true;
}
bool Request::RemoveQueryVar(const UInt_64& id)
{ {
for (UInt_64 i = 0; i < queries.Size(); ++i) for (UInt_64 i = 0; i < queries.Size(); ++i)
{ {
Vector<Str_8> data = queries[i].Split("="); if (queries[i] != id)
continue;
if (data[0] == var) queries.Swap(i, queries.End());
return data[1]; queries.Pop();
return true;
} }
return ""; return false;
} }
Vector<Str_8> Request::GetQueries() const bool Request::RemoveQueryVar(const Str_8& name)
{
return RemoveQueryVar(name.Hash_64());
}
QueryVar *Request::GetQueryVar(const UInt_64& id) const
{
for (UInt_64 i = 0; i < queries.Size(); ++i)
if (queries[i] == id)
return &queries[i];
return nullptr;
}
QueryVar *Request::GetQueryVar(const Str_8& name) const
{
return GetQueryVar(name.Hash_64());
}
Str_8 Request::GetQueryValue(const UInt_64& id) const
{
for (UInt_64 i = 0; i < queries.Size(); ++i)
if (queries[i] == id)
return queries[i].GetValue();
return {};
}
Str_8 Request::GetQueryValue(const Str_8& name) const
{
return GetQueryValue(name.Hash_64());
}
Vector<QueryVar> Request::GetQueries() const
{ {
return queries; return queries;
} }
void Request::BasicAuth(const Str_8& id, const Str_8& secret) void Request::BasicAuth(const Str_8& id, const Str_8& secret)
{ {
AddToHeader("Authorization", Str_8("Basic ") + Base64::Encode(id + ":" + secret)); AddHeaderVar({"Authorization", Str_8("Basic ") + Base64::Encode(id + ":" + secret)});
} }
void Request::BearerAuth(const Str_8& token) void Request::BearerAuth(const Str_8& token)
{ {
AddToHeader("Authorization", "Bearer " + token); AddHeaderVar({"Authorization", "Bearer " + token});
} }
void Request::BearerAuth(const Str_8& token, const Str_8& clientId) void Request::BearerAuth(const Str_8& token, const Str_8& clientId)
{ {
AddToHeader("Authorization", "Bearer " + token); AddHeaderVar({"Authorization", "Bearer " + token});
AddToHeader("Client-Id", clientId); AddHeaderVar({"Client-Id", clientId});
} }
void Request::BotAuth(const Str_8& token) void Request::BotAuth(const Str_8& token)
{ {
AddToHeader("Authorization", "Bot " + token); AddHeaderVar({"Authorization", "Bot " + token});
}
void Request::AddToHeader(const Str_8& var, const Str_8& value)
{
header.Push(var + ": " + value);
} }
Str_8 Request::GetHeader(const Str_8& var) const bool Request::HasHeaderVar(const UInt_64& id) const
{
for (UInt_64 i = 0; i < header.Size(); ++i)
if (header[i] == id)
return true;
return false;
}
bool Request::HasHeaderVar(const Str_8& name) const
{
return HasHeaderVar(name.Hash_64());
}
bool Request::AddHeaderVar(HeaderVar var)
{
if (HasHeaderVar(var.GetId()))
return false;
header.Push((HeaderVar &&)var);
return true;
}
bool Request::RemoveHeaderVar(const UInt_64 &id)
{ {
for (UInt_64 i = 0; i < header.Size(); ++i) for (UInt_64 i = 0; i < header.Size(); ++i)
{ {
Vector<Str_8> data = header[i].Split(": "); if (header[i] != id)
continue;
if (data[0] == var) header.Swap(i, header.End());
return data[1]; header.Pop();
return true;
} }
return ""; return false;
} }
Vector<Str_8> Request::GetHeader() const bool Request::RemoveHeaderVar(const Str_8 &name)
{
return RemoveHeaderVar(name.Hash_64());
}
HeaderVar *Request::GetHeaderVar(const UInt_64 &id) const
{
for (UInt_64 i = 0; i < header.Size(); ++i)
if (header[i] == id)
return &header[i];
return nullptr;
}
HeaderVar *Request::GetHeaderVar(const Str_8 &name) const
{
return GetHeaderVar(name.Hash_64());
}
Str_8 Request::GetHeaderValue(const UInt_64 &id) const
{
for (UInt_64 i = 0; i < header.Size(); ++i)
if (header[i] == id)
return header[i].GetValue();
return {};
}
Str_8 Request::GetHeaderValue(const Str_8 &name) const
{
return GetHeaderValue(name.Hash_64());
}
Vector<HeaderVar> Request::GetHeader() const
{ {
return header; return header;
} }
@@ -200,16 +342,20 @@ namespace ehs
Str_8 result = VerbToStr(verb) + " " + rsrc; Str_8 result = VerbToStr(verb) + " " + rsrc;
if (queries.Size()) if (queries.Size())
result += "?" + queries[0]; result += "?" + queries[0].ToStr();
for (UInt_64 i = 1; i < queries.Size(); ++i) for (UInt_64 i = 1; i < queries.Size(); ++i)
result += "&" + queries[i]; result += "&" + queries[i].ToStr();
result += " HTTP/1.1\r\n"; result += " HTTP/1.1\r\n";
for (UInt_64 i = 0; i < header.Size(); ++i) for (UInt_64 i = 0; i < header.Size(); ++i)
{ {
result += header[i] + "\r\n"; if (header[i] == 11245195881701120957ull || header[i] == 6556302699635904946ull ||
header[i] == 13347276190653935221ull) // Content-Length, Server, and Content-Type in order from left to right.
continue;
result += header[i].ToStr() + "\r\n";
} }
result += "Content-Type: " + ContentTypeToStr(cType) + "\r\n"; result += "Content-Type: " + ContentTypeToStr(cType) + "\r\n";
@@ -227,7 +373,7 @@ namespace ehs
return rsrc.Size() || queries.Size() || header.Size() || body.Size(); return rsrc.Size() || queries.Size() || header.Size() || body.Size();
} }
Str_8 Request::VerbToStr(const Verb verb) Str_8 Request::VerbToStr(const Verb &verb)
{ {
switch (verb) switch (verb)
{ {
@@ -244,7 +390,7 @@ namespace ehs
} }
} }
Str_8 Request::ContentTypeToStr(const ContentType cType) Str_8 Request::ContentTypeToStr(const ContentType &cType)
{ {
switch (cType) switch (cType)
{ {
@@ -262,14 +408,18 @@ namespace ehs
return "text/plain"; return "text/plain";
case ContentType::TEXT_HTML: case ContentType::TEXT_HTML:
return "text/html"; return "text/html";
case ContentType::TEXT_CSS:
return "text/css";
case ContentType::TEXT_XML: case ContentType::TEXT_XML:
return "text/xml"; return "text/xml";
case ContentType::IMG_X_ICON:
return "image/x-icon";
default: default:
return ""; return "";
} }
} }
ContentType Request::StrToContentType(const Str_8& value) ContentType Request::StrToContentType(const Str_8 &value)
{ {
if (value == "multipart/form-data") if (value == "multipart/form-data")
return ContentType::APP_MULTIPART_FORMDATA; return ContentType::APP_MULTIPART_FORMDATA;
@@ -285,13 +435,17 @@ namespace ehs
return ContentType::TEXT_PLAIN; return ContentType::TEXT_PLAIN;
else if (value == "text/html") else if (value == "text/html")
return ContentType::TEXT_HTML; return ContentType::TEXT_HTML;
else if (value == "text/css")
return ContentType::TEXT_CSS;
else if (value == "text/xml") else if (value == "text/xml")
return ContentType::TEXT_XML; return ContentType::TEXT_XML;
else if (value == "image/x-icon")
return ContentType::IMG_X_ICON;
else else
return ContentType::NONE; return ContentType::NONE;
} }
void Request::ReadData(const Str_8& data) void Request::ReadData(const Str_8 &data)
{ {
Vector<Str_8> lines = data.Split("\r\n"); Vector<Str_8> lines = data.Split("\r\n");
Vector<Str_8> meta = lines[0].Split(" "); Vector<Str_8> meta = lines[0].Split(" ");
@@ -308,7 +462,14 @@ namespace ehs
{ {
rsrc = meta[1].Sub(0, queryIndex); rsrc = meta[1].Sub(0, queryIndex);
cType = ContentType::APP_FORMURLENCODED; cType = ContentType::APP_FORMURLENCODED;
queries = meta[1].Sub(queryIndex + 1).Split("&");
Vector<Str_8> strQueries = meta[1].Sub(queryIndex + 1).Split("&");
for (UInt_64 i = 0; i < strQueries.Size(); ++i)
{
const Vector<Str_8> queryVar = strQueries[i].Split("=");
queries.Push({queryVar[0], queryVar[1]});
}
} }
else else
{ {
@@ -331,7 +492,9 @@ namespace ehs
if (var[0] == "Content-Length") if (var[0] == "Content-Length")
continue; continue;
header.Push(lines[i]); Vector<Str_8> headerVar = lines[i].Split(": ");
header.Push({headerVar[0], headerVar[1]});
} }
} }
} }

View File

@@ -2,43 +2,73 @@
namespace ehs namespace ehs
{ {
Response::Response(const UInt_32 code, const Str_8& server)
: code(code), server(server), cType(ContentType::NONE)
{
}
Response::Response(const char* data, const UInt_64 size)
: code(0), cType(ContentType::NONE)
{
ReadData(Str_8(data, size));
}
Response::Response(const Str_8& data)
: code(0), cType(ContentType::NONE)
{
ReadData(data);
}
Response::Response() Response::Response()
: code(0), cType(ContentType::NONE) : code(0), cType(ContentType::NONE)
{ {
} }
Response& Response::operator=(const Response& res) Response::Response(const UInt_32 &code, Str_8 server)
: code(code), server((Str_8 &&)server), cType(ContentType::NONE)
{ {
if (this == &res) }
return *this;
code = res.code; Response::Response(const char *data, const UInt_64 &size)
server = res.server; : code(0), cType(ContentType::NONE)
cType = res.cType; {
header = res.header; ReadData(Str_8(data, size));
body = res.body; }
Response::Response(const Str_8 &data)
: code(0), cType(ContentType::NONE)
{
ReadData(data);
}
Response::Response(Response&& other) noexcept
: code(other.code), server((Str_8 &&)other.server), cType(other.cType), header((Vector<HeaderVar> &&)other.header),
body((Str_8 &&)other.body)
{
other.code = 0;
other.cType = ContentType::NONE;
}
Response::Response(const Response &other)
: code(other.code), server(other.server), cType(other.cType), header(other.header), body(other.body)
{
}
Response& Response::operator=(Response&& other) noexcept
{
if (this == &other)
return *this;
code = other.code;
server = (Str_8 &&)other.server;
cType = other.cType;
header = (Vector<HeaderVar> &&)other.header;
body = (Str_8 &&)other.body;
other.code = 0;
other.cType = ContentType::NONE;
return *this; return *this;
} }
void Response::SetCode(const UInt_32 code) Response& Response::operator=(const Response& other)
{
if (this == &other)
return *this;
code = other.code;
server = other.server;
cType = other.cType;
header = other.header;
body = other.body;
return *this;
}
void Response::SetCode(const UInt_32 &code)
{ {
this->code = code; this->code = code;
} }
@@ -48,9 +78,9 @@ namespace ehs
return code; return code;
} }
void Response::SetServer(const Str_8& server) void Response::SetServer(Str_8 server)
{ {
this->server = server; this->server = (Str_8 &&)server;
} }
Str_8 Response::GetServer() const Str_8 Response::GetServer() const
@@ -58,7 +88,7 @@ namespace ehs
return server; return server;
} }
void Response::SetContentType(const ContentType cType) void Response::SetContentType(const ContentType &cType)
{ {
this->cType = cType; this->cType = cType;
} }
@@ -68,27 +98,80 @@ namespace ehs
return cType; return cType;
} }
void Response::AddToHeader(const Str_8& var, const Str_8& value) bool Response::HasHeaderVar(const UInt_64& id) const
{ {
header.Push(var + ": " + value); for (UInt_64 i = 0; i < header.Size(); ++i)
if (header[i] == id)
return true;
return false;
} }
Str_8 Response::GetHeader(const Str_8& var) const bool Response::HasHeaderVar(const Str_8& name) const
{ {
Str_8 lIdentity = var.GetLower(); return HasHeaderVar(name.Hash_64());
}
bool Response::AddHeaderVar(HeaderVar var)
{
if (HasHeaderVar(var.GetId()))
return false;
header.Push((HeaderVar &&)var);
return true;
}
bool Response::RemoveHeaderVar(const UInt_64& id)
{
for (UInt_64 i = 0; i < header.Size(); ++i) for (UInt_64 i = 0; i < header.Size(); ++i)
{ {
Vector<Str_8> data = header[i].Split(": "); if (header[i] != id)
continue;
if (data[0].GetLower() == lIdentity) header.Swap(i, header.End());
return data[1]; header.Pop();
return true;
} }
return ""; return false;
} }
Vector<Str_8> Response::GetHeader() const bool Response::RemoveHeaderVar(const Str_8& name)
{
return RemoveHeaderVar(name.Hash_64());
}
HeaderVar* Response::GetHeaderVar(const UInt_64 &id) const
{
for (UInt_64 i = 0; i < header.Size(); ++i)
if (header[i] == id)
return &header[i];
return nullptr;
}
HeaderVar *Response::GetHeaderVar(const Str_8 &name) const
{
return GetHeaderVar(name.Hash_64());
}
Str_8 Response::GetHeaderValue(const UInt_64& id) const
{
for (UInt_64 i = 0; i < header.Size(); ++i)
if (header[i] == id)
return header[i].GetValue();
return {};
}
Str_8 Response::GetHeaderValue(const Str_8& name) const
{
return GetHeaderValue(name.Hash_64());
}
Vector<HeaderVar> Response::GetHeader() const
{ {
return header; return header;
} }
@@ -159,14 +242,11 @@ namespace ehs
for (UInt_64 i = 0; i < header.Size(); ++i) for (UInt_64 i = 0; i < header.Size(); ++i)
{ {
if (header[i].Find("Content-Length", nullptr, SearchPattern::LEFT_RIGHT, IndexResult::ENDING)) if (header[i] == 11245195881701120957ull || header[i] == 6556302699635904946ull ||
continue; header[i] == 13347276190653935221ull) // Content-Length, Server, and Content-Type in order from left to right.
else if (header[i].Find("Server", nullptr, SearchPattern::LEFT_RIGHT, IndexResult::ENDING))
continue;
else if (header[i].Find("Content-Type", nullptr, SearchPattern::LEFT_RIGHT, IndexResult::ENDING))
continue; continue;
result += header[i] + "\r\n"; result += header[i].ToStr() + "\r\n";
} }
result += "Content-Type: " + ContentTypeToStr(cType) + "\r\nContent-Length: " + Str_8::FromNum(body.Size()) + "\r\n\r\n" + body; result += "Content-Type: " + ContentTypeToStr(cType) + "\r\nContent-Length: " + Str_8::FromNum(body.Size()) + "\r\n\r\n" + body;
@@ -179,7 +259,7 @@ namespace ehs
return server.Size() || header.Size() || body.Size(); return server.Size() || header.Size() || body.Size();
} }
Str_8 Response::CodeToStr(const UInt_32 code) Str_8 Response::CodeToStr(const UInt_32 &code)
{ {
if (code == 100) if (code == 100)
return "Continue"; return "Continue";
@@ -323,7 +403,7 @@ namespace ehs
return "Unused Status Code"; return "Unused Status Code";
} }
Str_8 Response::ContentTypeToStr(const ContentType cType) Str_8 Response::ContentTypeToStr(const ContentType &cType)
{ {
switch (cType) switch (cType)
{ {
@@ -341,14 +421,18 @@ namespace ehs
return "text/plain"; return "text/plain";
case ContentType::TEXT_HTML: case ContentType::TEXT_HTML:
return "text/html"; return "text/html";
case ContentType::TEXT_CSS:
return "text/css";
case ContentType::TEXT_XML: case ContentType::TEXT_XML:
return "text/xml"; return "text/xml";
case ContentType::IMG_X_ICON:
return "image/x-icon";
default: default:
return ""; return "";
} }
} }
ContentType Response::StrToContentType(const Str_8& value) ContentType Response::StrToContentType(const Str_8 &value)
{ {
if (value == "multipart/form-data") if (value == "multipart/form-data")
return ContentType::APP_MULTIPART_FORMDATA; return ContentType::APP_MULTIPART_FORMDATA;
@@ -364,13 +448,17 @@ namespace ehs
return ContentType::TEXT_PLAIN; return ContentType::TEXT_PLAIN;
else if (value == "text/html") else if (value == "text/html")
return ContentType::TEXT_HTML; return ContentType::TEXT_HTML;
else if (value == "text/css")
return ContentType::TEXT_CSS;
else if (value == "text/xml") else if (value == "text/xml")
return ContentType::TEXT_XML; return ContentType::TEXT_XML;
else if (value == "image/x-icon")
return ContentType::IMG_X_ICON;
else else
return ContentType::NONE; return ContentType::NONE;
} }
void Response::ReadData(const Str_8& data) void Response::ReadData(const Str_8 &data)
{ {
Vector<Str_8> lines = data.Split("\r\n"); Vector<Str_8> lines = data.Split("\r\n");
Vector<Str_8> meta = lines[0].Split(" "); Vector<Str_8> meta = lines[0].Split(" ");
@@ -384,12 +472,12 @@ namespace ehs
Vector<Str_8> var = lines[i].Split(": "); Vector<Str_8> var = lines[i].Split(": ");
if (var[0].GetLower() == "server") if (var[0] == "Server")
{ {
server = var[1]; server = var[1];
continue; continue;
} }
else if (var[0].GetLower() == "content-type") else if (var[0] == "Content-Type")
{ {
Vector<Str_8> ctData = var[1].Split(";"); Vector<Str_8> ctData = var[1].Split(";");
@@ -397,7 +485,9 @@ namespace ehs
continue; continue;
} }
header.Push(lines[i]); Vector<Str_8> headerVar = lines[i].Split(": ");
header.Push({headerVar[0], headerVar[1]});
} }
} }
} }

View File

@@ -4,6 +4,8 @@
#include <openssl/bio.h> #include <openssl/bio.h>
#include <openssl/err.h> #include <openssl/err.h>
#include <openssl/pem.h> #include <openssl/pem.h>
#include <openssl/opensslv.h>
#include <openssl/provider.h>
namespace ehs namespace ehs
{ {
@@ -12,6 +14,11 @@ namespace ehs
if (!IsValid()) if (!IsValid())
return; return;
EVP_PKEY_free(pkey);
X509_free(cert);
if (sslHdl) if (sslHdl)
{ {
if (connection) if (connection)
@@ -25,28 +32,28 @@ namespace ehs
} }
SSL::SSL() SSL::SSL()
: ctx(nullptr), sslHdl(nullptr) : server(false), ctx(nullptr), sslHdl(nullptr), cert(nullptr), pkey(nullptr)
{ {
} }
SSL::SSL(const AddrType type) SSL::SSL(const IP &type, const bool &server)
: TCP(type), ctx(nullptr), sslHdl(nullptr) : TCP(type), server(server), ctx(nullptr), sslHdl(nullptr), cert(nullptr), pkey(nullptr)
{ {
SSL::Initialize(); SSL::Initialize();
} }
SSL::SSL(TCP&& tcp) noexcept SSL::SSL(TCP&& tcp) noexcept
: TCP(std::move(tcp)), ctx(nullptr), sslHdl(nullptr) : TCP(std::move(tcp)), server(false), ctx(nullptr), sslHdl(nullptr), cert(nullptr), pkey(nullptr)
{ {
} }
SSL::SSL(const TCP& tcp) SSL::SSL(const TCP& tcp)
: TCP(tcp), ctx(nullptr), sslHdl(nullptr) : TCP(tcp), server(false), ctx(nullptr), sslHdl(nullptr), cert(nullptr), pkey(nullptr)
{ {
} }
SSL::SSL(const SSL& ssl) SSL::SSL(const SSL& ssl)
: TCP(ssl), ctx(nullptr), sslHdl(nullptr) : TCP(ssl), server(ssl.server), ctx(nullptr), sslHdl(nullptr), cert(nullptr), pkey(nullptr)
{ {
} }
@@ -57,8 +64,11 @@ namespace ehs
TCP::operator=(ssl); TCP::operator=(ssl);
server = ssl.server;
ctx = nullptr; ctx = nullptr;
sslHdl = nullptr; sslHdl = nullptr;
cert = nullptr;
pkey = nullptr;
return *this; return *this;
} }
@@ -71,6 +81,40 @@ namespace ehs
return; return;
SSL_library_init(); SSL_library_init();
OpenSSL_add_ssl_algorithms();
SSL_load_error_strings();
OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, nullptr);
OSSL_PROVIDER_load(nullptr, "default");
SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
if (server)
{
ctx = SSL_CTX_new(TLS_server_method());
if (!ctx)
{
UInt_32 code = ERR_get_error();
EHS_LOG_INT(LogType::ERR, 0, ERR_error_string(code, nullptr));
}
SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!MD5");
SSL_CTX_set_ciphersuites(ctx,
"TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:"
"TLS_CHACHA20_POLY1305_SHA256:ECDHE-RSA-AES128-GCM-SHA256"
);
}
else
{
ctx = SSL_CTX_new(TLS_client_method());
if (!ctx)
{
UInt_32 code = ERR_get_error();
EHS_LOG_INT(LogType::ERR, 0, ERR_error_string(code, nullptr));
}
SSL_CTX_set_default_verify_paths(ctx);
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, nullptr);
}
} }
void SSL::Release() void SSL::Release()
@@ -80,6 +124,12 @@ namespace ehs
if (!IsValid()) if (!IsValid())
return; return;
EVP_PKEY_free(pkey);
pkey = nullptr;
X509_free(cert);
cert = nullptr;
if (sslHdl) if (sslHdl)
{ {
if (connection) if (connection)
@@ -97,34 +147,37 @@ namespace ehs
} }
} }
void SSL::Bind(const Str_8& address, unsigned short port) void SSL::Listen()
{ {
if (bound) sslHdl = SSL_new(ctx);
return; SSL_set_fd(sslHdl, hdl);
OpenSSL_add_all_algorithms(); TCP::Listen();
SSL_load_error_strings();
ctx = SSL_CTX_new(SSLv23_server_method());
sslHdl = SSL_new(ctx); EHS_LOG_SUCCESS();
SSL_set_fd(sslHdl, hdl);
TCP::Bind(address, port);
} }
SSL* SSL::Accept() SSL* SSL::Accept()
{ {
if (!bound) if (!bound)
return nullptr; return nullptr;
TCP* tcp = TCP::Accept(); TCP* tcp = TCP::Accept();
if (!tcp)
return nullptr;
SSL* client = new SSL(std::move(*tcp)); SSL* client = new SSL(std::move(*tcp));
delete tcp; delete tcp;
client->ctx = nullptr; client->sslHdl = SSL_new(this->ctx);
client->sslHdl = SSL_new(ctx); if (!client->sslHdl)
{
UInt_32 code = ERR_get_error();
EHS_LOG_INT(LogType::ERR, 0, ERR_error_string(code, nullptr));
return nullptr;
}
SSL_set_fd(client->sslHdl, client->hdl); SSL_set_fd(client->sslHdl, client->hdl);
int err = SSL_accept(client->sslHdl); int err = SSL_accept(client->sslHdl);
@@ -134,21 +187,29 @@ namespace ehs
return {}; return {};
} }
EHS_LOG_SUCCESS();
return client; return client;
} }
void SSL::Connect(const Str_8& address, const UInt_16 port) void SSL::Connect(Str_8 address, const UInt_16 &port)
{ {
if (bound)
return;
TCP::Connect(address, port); TCP::Connect(address, port);
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
ctx = SSL_CTX_new(SSLv23_client_method());
sslHdl = SSL_new(ctx); sslHdl = SSL_new(ctx);
SSL_set_fd(sslHdl, hdl); SSL_set_fd(sslHdl, hdl);
SSL_connect(sslHdl);
SSL_set_tlsext_host_name(sslHdl, &address[0]);
SInt_32 rc = SSL_connect(sslHdl);
if (rc != 1)
{
EHS_LOG_INT(LogType::ERR, 1, "Failed to connect with error #" + Str_8::FromNum(SSL_get_error(sslHdl, rc)) + ".");
return;
}
EHS_LOG_SUCCESS();
} }
UInt_64 SSL::Send(const Byte* const buffer, const UInt_32 size) UInt_64 SSL::Send(const Byte* const buffer, const UInt_32 size)
@@ -157,8 +218,12 @@ namespace ehs
if (written <= 0) if (written <= 0)
{ {
int code = SSL_get_error(sslHdl, written); int code = SSL_get_error(sslHdl, written);
ERR_print_errors_fp(stderr); if (code != SSL_ERROR_WANT_WRITE)
EHS_LOG_INT(LogType::ERR, 0, "Failed to send data with error #" + Str_8::FromNum(code) + "."); {
ERR_print_errors_fp(stderr);
EHS_LOG_INT(LogType::ERR, 0, "Failed to send data with error #" + Str_8::FromNum(code) + ".");
}
return 0; return 0;
} }
@@ -171,48 +236,46 @@ namespace ehs
if (received <= 0) if (received <= 0)
{ {
int code = SSL_get_error(sslHdl, received); int code = SSL_get_error(sslHdl, received);
ERR_print_errors_fp(stderr); if (code != SSL_ERROR_WANT_READ)
EHS_LOG_INT(LogType::ERR, 0, "Failed to receive data with error #" + Str_8::FromNum(code) + "."); {
ERR_print_errors_fp(stderr);
EHS_LOG_INT(LogType::ERR, 0, "Failed to receive data with error #" + Str_8::FromNum(code) + ".");
}
return 0; return 0;
} }
return received; return received;
} }
void SSL::UseCertificate(const Byte* data, const UInt_64 size) void SSL::UseCertificate(const Char_8* data, const UInt_32 &size)
{ {
X509 *cert = d2i_X509(nullptr, &data, (long)size); BIO* certBio = BIO_new_mem_buf(data, (int)size);
if (!cert) X509 *cert = PEM_read_bio_X509(certBio, nullptr, nullptr, nullptr);
{
EHS_LOG_INT(LogType::ERR, 0, "Invalid certificate.");
return;
}
if (SSL_CTX_use_certificate(ctx, cert) != 1) if (!SSL_CTX_use_certificate(ctx, cert))
{ {
EHS_LOG_INT(LogType::ERR, 1, "Failed to use certificate."); UInt_32 code = ERR_get_error();
return; EHS_LOG_INT(LogType::ERR, 0, ERR_error_string(code, nullptr));
} return;
}
X509_free(cert); BIO_free(certBio);
} }
void SSL::UsePrivateKey(const Byte* data, const UInt_64 size) void SSL::UsePrivateKey(const Char_8* data, const UInt_32 &size)
{ {
EVP_PKEY *key = d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &data, (long)size); BIO* keyBio = BIO_new_mem_buf(data, (int)size);
if (!key) EVP_PKEY* pkey = PEM_read_bio_PrivateKey(keyBio, nullptr, nullptr, nullptr);
{
EHS_LOG_INT(LogType::ERR, 0, "Invalid private key.");
return;
}
if (SSL_CTX_use_PrivateKey(ctx, key) != 1) if (!SSL_CTX_use_PrivateKey(ctx, pkey))
{ {
EHS_LOG_INT(LogType::ERR, 1, "Failed to use private key."); UInt_32 code = ERR_get_error();
return; EHS_LOG_INT(LogType::ERR, 0, ERR_error_string(code, nullptr));
} return;
}
EVP_PKEY_free(key); BIO_free(keyBio);
} }
bool SSL::IsValid() bool SSL::IsValid()

Some files were not shown because too many files have changed in this diff Show More