Compare commits

..
Author SHA1 Message Date
Morteza Bashsiz a006ba4e0c Merge pull request #212 from MortezaBashsiz/dev
Version 1.1.56
2026-06-07 20:36:51 +02:00
Morteza Bashsiz 413bffba44 Version 1.1.56
Version 1.1.56
2026-06-07 20:25:44 +02:00
Morteza Bashsiz 3b2c01b095 Merge branch 'dev' into mori 2026-06-07 20:25:20 +02:00
Morteza Bashsiz 4c6a00e801 Version 1.1.56 2026-06-07 20:23:26 +02:00
Morteza Bashsiz c2dc1487a2 Version 1.1.55
Version 1.1.55
2026-06-07 20:15:34 +02:00
Morteza Bashsiz 4df70ae101 Merge pull request #209 from MortezaBashsiz/mori
fix version
2026-06-07 20:14:06 +02:00
Morteza Bashsiz 49026a2f0d fix version 2026-06-07 20:13:15 +02:00
Morteza Bashsiz 7c82f7f3b5 Versin 1.1.55
Versin 1.1.55
2026-06-07 19:02:48 +02:00
Morteza Bashsiz 3a965c904f Merge branch 'main' into dev 2026-06-07 19:00:57 +02:00
Morteza Bashsiz 1f03931aa4 Merge pull request #207 from MortezaBashsiz/mori
fix ipv6 bug
2026-06-07 18:57:43 +02:00
Morteza Bashsiz aa36749c47 fix ipv6 bug 2026-06-07 18:56:45 +02:00
Morteza Bashsiz 6535cb51b7 Fix IPv6 bug 2026-06-07 13:34:14 +02:00
Morteza Bashsiz 212003760b fix server freezing bug 2026-06-07 11:36:12 +02:00
Morteza Bashsiz 698da19a8c Merge pull request #204 from MortezaBashsiz/revert-202-dev
Revert "Version 1.1.55"
2026-06-07 07:41:46 +02:00
Morteza Bashsiz 451a169756 Revert "Version 1.1.55" 2026-06-07 07:38:50 +02:00
Morteza Bashsiz 277321306b Version 1.1.55
Version 1.1.55
2026-06-06 14:04:46 +02:00
Morteza Bashsiz d6e0161aa5 Merge pull request #201 from MortezaBashsiz/mori
Version 1.1.55
2026-06-06 14:02:13 +02:00
Morteza Bashsiz 14b0947140 Version 1.1.55 2026-06-06 14:01:16 +02:00
Morteza Bashsiz 134251779c Merge pull request #200 from MortezaBashsiz/mori
change tcpconnection handle accept method
2026-06-06 08:32:05 +02:00
Morteza Bashsiz 92d877be31 change tcpconnection handle accept method 2026-06-06 08:17:14 +02:00
Morteza Bashsiz 7e6ae56753 Version 1.1.54
In this version

Socks5 protocol is now supported. So user can choose socks5|http protocol between client and agent

Refactor of code base is done
2026-06-05 17:45:46 +02:00
Morteza Bashsiz deae50f9d4 Merge pull request #197 from MortezaBashsiz/mori
Add socks5 support
2026-06-05 16:59:20 +02:00
Morteza Bashsiz daa21a57db fix main branch support 2026-06-05 16:38:20 +02:00
Morteza Bashsiz d8f09b9fe2 Add socks5 support 2026-06-05 16:21:05 +02:00
Morteza Bashsiz aeeea2a527 Merge pull request #196 from MortezaBashsiz/mori
Refactor code with better style
2026-06-05 10:33:08 +02:00
Morteza Bashsiz 55004368e4 Refactor code with better style 2026-06-05 10:30:06 +02:00
Morteza Bashsiz d0da1c55d8 Version 1.1.53
Fix handshake bug, close connection after handshake failed
2026-06-05 07:53:48 +02:00
Morteza Bashsiz 3363a7a5d2 Fix handshake bug, close connection after handshake failed
Fix handshake bug, close connection after handshake failed
2026-06-04 23:38:55 +02:00
Morteza Bashsiz 4cdc66bdf1 Fix handshake bug, close connection after handshake failed 2026-06-04 23:36:15 +02:00
Morteza Bashsiz 2540b3a504 Add windows build 2026-06-04 18:33:56 +02:00
Morteza Bashsiz cb87555503 Version 1.1.52
Version 1.1.52
2026-06-04 17:17:48 +02:00
Morteza Bashsiz 20bb0d2b9d Version 1.1.52
Version 1.1.52
2026-06-04 17:14:08 +02:00
Morteza Bashsiz 31b7bb96a8 Version 1.1.52 2026-06-04 17:12:52 +02:00
Morteza Bashsiz 9abc319202 Add workflows for all branches & support android in threading
Add workflows for all branches & support android in threading
2026-06-04 16:51:51 +02:00
Morteza Bashsiz 6c21edfc40 Add workflows for all branches & support android in threading 2026-06-04 16:38:43 +02:00
Morteza Bashsiz 6493d88258 create workflows for all branches 2026-06-04 16:37:01 +02:00
Morteza Bashsiz ed10d097f1 fix missing args 2026-06-03 14:52:26 +02:00
Morteza Bashsiz 14ead78ff8 add release step to android dev 2026-06-02 19:25:05 +02:00
Morteza Bashsiz b1a18e243c change jthread to thread for android 2026-06-02 18:43:46 +02:00
Morteza Bashsiz 24390b6562 fix android binary action 2026-06-02 18:26:57 +02:00
Morteza Bashsiz ec4a68fdb6 Merge pull request #187 from MortezaBashsiz/dev
Fix main verion
2026-06-02 16:37:21 +02:00
Morteza Bashsiz bae6afa35b Merge pull request #186 from MortezaBashsiz/mori
Mori
2026-06-02 16:35:16 +02:00
Morteza Bashsiz 36315032d9 fix main version 2026-06-02 16:33:49 +02:00
Morteza Bashsiz 96758b6322 add android 2026-06-02 16:18:21 +02:00
Morteza Bashsiz 9b5b275275 Merge pull request #185 from MortezaBashsiz/dev
add termux version #182
2026-06-02 16:14:35 +02:00
Morteza Bashsiz 76a9e4acb0 Merge pull request #184 from MortezaBashsiz/mori
add aarch64 termux
2026-06-02 15:57:43 +02:00
Morteza Bashsiz 3b3d2f4d88 add aarch64 to the build 2026-06-02 15:55:23 +02:00
Morteza Bashsiz 9af39a5715 Merge pull request #181 from MortezaBashsiz/dev
Release arm64 and amd64
2026-06-02 09:28:44 +02:00
Morteza Bashsiz 2f043a6f83 Merge pull request #180 from MortezaBashsiz/mori
Build debian package for arm64
2026-06-02 07:26:11 +02:00
Morteza Bashsiz d94075e5c3 fix workflow dev and main 2026-06-02 07:09:44 +02:00
Morteza Bashsiz 9f1a7c8637 fix control 2026-06-02 07:09:44 +02:00
Morteza Bashsiz 2add09ea33 fix control 2026-06-02 07:09:44 +02:00
Morteza Bashsiz 8beee5d127 add arm to workflow 2026-06-02 07:09:44 +02:00
Morteza Bashsiz 84bb675b9c add arm to workflow 2026-06-02 07:09:44 +02:00
Morteza Bashsiz 67c43de80d implement pullTimeout
Add configurable
```
  # pullTimeout: unsigned short
  # Defines the timeout for I/O Operation in milliseconds.
  #   Useful to expire serverside read timer.
  pullTimeout: 50
```
Higher number helps when your network is slower
2026-06-01 15:53:38 +02:00
Morteza Bashsiz ab4580920f implement pullTimeout (#178) 2026-06-01 15:47:15 +02:00
Morteza Bashsiz c0942c4015 Implement Random fakeUrl
* implement random fakeUrl
2026-05-31 23:06:14 +02:00
Morteza Bashsiz 228aff5d63 Dev fix #167 (#174)
* Fix #167 package versioning
2026-05-29 10:46:51 +02:00
Morteza Bashsiz 5647fd2f69 Fix #167 (#171)
* Fix #167 package versioning
2026-05-29 10:00:14 +02:00
Morteza Bashsiz 92a290cca7 Merge pull request #169 from MortezaBashsiz/dev
Fix #167
2026-05-29 09:20:47 +02:00
Morteza Bashsiz 108b9729c7 Merge pull request #168 from MortezaBashsiz/mori
Fix #167
2026-05-29 09:17:28 +02:00
Morteza Bashsiz 7baaf6aefb Fix #167 package versioning 2026-05-29 08:40:03 +02:00
Morteza Bashsiz 4793a3f0e3 update workflows action 2026-05-29 01:27:44 +02:00
Morteza Bashsiz c8cd4066d7 Merge pull request #166 from MortezaBashsiz/dev
Fix segmentation fault
Improve performance
Move tls config to general
2026-05-28 18:25:46 +02:00
Morteza Bashsiz 33a4dbd0b8 Merge pull request #165 from MortezaBashsiz/mori
fix segmentation fault issue
2026-05-28 18:21:32 +02:00
Morteza Bashsiz 01d8b36ca0 fix segmentation fault issue 2026-05-28 10:07:23 +02:00
Morteza Bashsiz cd7b985da1 move all tls configs to general 2026-05-28 09:09:09 +02:00
Morteza Bashsiz 80c631f66b Merge pull request #164 from MortezaBashsiz/dev
Merge from dev version v1-1-41
2026-05-26 20:58:56 +02:00
Morteza Bashsiz 8a1fcde280 Merge pull request #163 from MortezaBashsiz/mori
Mori
2026-05-26 16:52:07 +02:00
Morteza Bashsiz 51feb98dc3 fix segmentation fault for server and test connectionReuse 2026-05-26 16:37:48 +02:00
Morteza Bashsiz 560b5d93cc dummy commit 2026-05-26 14:03:01 +02:00
Morteza Bashsiz 97ee705eec dummy commit 2026-05-26 14:00:31 +02:00
Morteza Bashsiz 8d1ecfc2dc dummy commit 2026-05-26 13:55:11 +02:00
Morteza Bashsiz b402144e9e Update config 2026-05-26 13:27:39 +02:00
Morteza Bashsiz e7c8cb51cc See if behind cf fixed or not 2026-05-26 13:07:15 +02:00
Morteza Bashsiz 51fd1d47cc test if it works behind cf 2026-05-26 12:02:39 +02:00
Morteza Bashsiz 251b0202e8 Try to implement connectionReuse 2026-05-26 09:59:48 +02:00
Morteza Bashsiz 10e4481376 Merge pull request #153 from MortezaBashsiz/dev
Random endpoint and method
2026-05-06 13:19:59 +02:00
Morteza Bashsiz 47b56af86e Merge pull request #152 from MortezaBashsiz/mori
Random endpoint and method
2026-05-06 12:34:08 +02:00
Morteza Bashsiz 1c8d2d610b add random endPoint 2026-05-06 10:47:17 +02:00
Morteza Bashsiz 86f2b750a8 add random method 2026-05-06 10:18:48 +02:00
Morteza Bashsiz 0e4c1bf00d Implement tunnel mode
Implement tunnel mode beside http mode, So you can configure if you like to have the connection between agent and data in tunnel or pure HTTP request/response
2026-05-04 12:39:52 +02:00
Morteza Bashsiz 1452c1bd82 Merge pull request #150 from MortezaBashsiz/mori
Implement tunnel mode beside http mode, So you can configure if you like to have the connection between agent and data in tunnel or pure HTTP request/response
2026-05-04 11:59:56 +02:00
Morteza Bashsiz 09d5e25509 rename function from browser to client 2026-05-04 11:33:22 +02:00
Morteza Bashsiz 73f9cb01c1 implement the tunnel mode 2026-05-04 09:35:33 +02:00
Morteza Bashsiz 88bf0953e3 Start to add tunnel mode as configurable 2026-05-02 17:20:36 +02:00
Morteza Bashsiz 83fbb7adf2 fix branch in mori action 2026-05-01 23:20:39 +02:00
Morteza Bashsiz 7ac2fb293f remove anonymous namespaces and use struct instead 2026-05-01 23:18:52 +02:00
Morteza Bashsiz f70ef566d7 Merge pull request #149 from MortezaBashsiz/dev
Update readme
Update actions
2026-05-01 21:00:09 +02:00
Morteza Bashsiz 064fe1614a Merge pull request #148 from MortezaBashsiz/mori
Change readme
2026-05-01 20:58:07 +02:00
Morteza Bashsiz 323380afa5 change readme 2026-05-01 20:56:56 +02:00
Morteza Bashsiz f2b63aacb9 init mori branch 2026-05-01 20:53:50 +02:00
Morteza Bashsiz d968046d8b Merge pull request #146 from MortezaBashsiz/dev
Implement pure HTTP interaction between server and agent
2026-04-30 14:35:12 +02:00
Morteza Bashsiz a9d290c788 Merge pull request #145 from MortezaBashsiz/mori/cf
Mori/cf
2026-04-30 13:34:55 +02:00
Morteza Bashsiz 268dcfb207 remove unused chunkHeader 2026-04-30 12:47:00 +02:00
Morteza Bashsiz f3bd05787b test http mode 2026-04-30 10:03:30 +02:00
Morteza Bashsiz 9f7e6ab713 Merge pull request #144 from MortezaBashsiz/dev
Change read bytes from exactly(1) to at_least(1)
2026-04-28 08:08:39 +02:00
Morteza Bashsiz 62d34bd3e8 Merge pull request #143 from MortezaBashsiz/mori/cf
return encryption
2026-04-23 10:53:19 +02:00
Morteza Bashsiz 97bb609bd6 return encryption 2026-04-23 10:27:46 +02:00
Morteza Bashsiz 7b6a23f508 Merge pull request #142 from MortezaBashsiz/dev
Fix tls enable true and false
2026-04-22 14:43:18 +02:00
Morteza Bashsiz 5473b4b7b1 Merge pull request #141 from MortezaBashsiz/mori/cf
Resolve tlsEnable true and false issue
2026-04-22 14:38:22 +02:00
Morteza Bashsiz 9cfe163ac2 fix tlsEnable true and false 2026-04-22 14:14:58 +02:00
Morteza Bashsiz b6a8954a4b fix tlsEnable true and false 2026-04-22 14:13:25 +02:00
Morteza Bashsiz 61a8b4ddae Remove all comments 2026-04-21 08:10:51 +02:00
Morteza Bashsiz 576bef360d change connect method 2026-04-20 14:20:24 +02:00
Morteza Bashsiz 750ed871c8 remove http2 2026-04-17 15:49:36 +02:00
Morteza Bashsiz cd3c88f90d check the cf 2026-04-17 15:36:39 +02:00
Morteza Bashsiz 78adf29ff2 check the cf 2026-04-17 15:30:03 +02:00
Morteza Bashsiz 6650839c66 Merge pull request #140 from MortezaBashsiz/mori/cf
change dev release
2026-04-16 19:19:43 +02:00
Morteza Bashsiz 4bbbf10e3c change dev release 2026-04-16 19:18:57 +02:00
Morteza Bashsiz ad0d921032 Merge pull request #139 from MortezaBashsiz/mori/cf
write proper comments
2026-04-16 19:12:58 +02:00
Morteza Bashsiz b4871b9b95 write proper comments 2026-04-16 07:44:44 +02:00
Morteza Bashsiz 3c0f8714b9 remove tlsDhFile 2026-04-15 22:11:11 +02:00
33 changed files with 3666 additions and 1715 deletions

No files matched your search

+157
View File
@@ -0,0 +1,157 @@
name: Build Android Binary - dev
on:
workflow_dispatch:
push:
branches:
- dev
paths:
- 'core/src/**'
- 'core/**'
- 'CMakeLists.txt'
- 'core/CMakeLists.txt'
- '.github/workflows/android-dev.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 0.1.${{ github.run_number }}
jobs:
build-android:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
build-essential \
cmake \
ninja-build \
git \
curl \
zip \
unzip \
tar \
pkg-config \
autoconf \
autoconf-archive \
automake \
libtool
- name: Setup Android NDK r29
uses: nttld/setup-ndk@v1
with:
ndk-version: r29
add-to-path: true
- name: Show Android NDK information
run: |
echo "ANDROID_NDK_HOME=$ANDROID_NDK_HOME"
echo "ANDROID_NDK_ROOT=$ANDROID_NDK_ROOT"
ls -lah "$ANDROID_NDK_HOME"
- name: Setup vcpkg
run: |
git clone https://github.com/microsoft/vcpkg.git "$HOME/vcpkg"
"$HOME/vcpkg/bootstrap-vcpkg.sh"
echo "VCPKG_ROOT=$HOME/vcpkg" >> "$GITHUB_ENV"
echo "$HOME/vcpkg" >> "$GITHUB_PATH"
- name: Build Android dependencies
run: |
"$VCPKG_ROOT/vcpkg" install \
boost:arm64-android \
openssl:arm64-android \
yaml-cpp:arm64-android
- name: Configure Android arm64-v8a build
run: |
rm -rf build-android-arm64
cmake -S . -B build-android-arm64 \
-G Ninja \
-DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" \
-DVCPKG_TARGET_TRIPLET=arm64-android \
-DVCPKG_CHAINLOAD_TOOLCHAIN_FILE="$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake" \
-DANDROID_ABI=arm64-v8a \
-DANDROID_PLATFORM=android-23 \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_EXE_LINKER_FLAGS="-Wl,-z,max-page-size=16384" \
-DCMAKE_SHARED_LINKER_FLAGS="-Wl,-z,max-page-size=16384"
- name: Build Android arm64-v8a binary
run: |
cmake --build build-android-arm64 -j"$(nproc)"
- name: Collect Android binary and libraries
run: |
mkdir -p out/android/arm64-v8a
if [ ! -f build-android-arm64/core/nipovpn ]; then
echo "Android binary not found:"
find build-android-arm64 -type f || true
exit 1
fi
cp build-android-arm64/core/nipovpn out/android/arm64-v8a/libnipovpn_dev_"${{ env.PACKAGE_VERSION }}".so
chmod 755 out/android/arm64-v8a/libnipovpn_dev_"${{ env.PACKAGE_VERSION }}".so
find "$VCPKG_ROOT/installed/arm64-android" -type f -name "*.so*" -exec cp -v {} out/android/arm64-v8a/ \; || true
ls -lah out/android/arm64-v8a/
- name: Check 16 KB ELF alignment
run: |
READELF="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-readelf"
for file in out/android/arm64-v8a/*.so*; do
echo "Checking $file"
"$READELF" -l "$file" | grep -A3 LOAD || true
if "$READELF" -l "$file" | awk '/LOAD/ && $NF != "0x4000" { bad=1 } END { exit bad }'; then
echo "OK: $file is 16 KB aligned"
else
echo "ERROR: $file is not 16 KB aligned"
exit 1
fi
done
- name: Upload Android artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-dev-android-arm64-v8a
path: out/android/arm64-v8a/
release-android:
needs:
- build-android
runs-on: ubuntu-24.04
steps:
- name: Download Android artifact
uses: actions/download-artifact@v4
with:
name: nipovpn-dev-android-arm64-v8a
path: ./android-artifact
- name: Show downloaded Android artifact
run: |
ls -lah android-artifact
- name: Create Android GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: dev-android-v${{ env.PACKAGE_VERSION }}
name: dev Android Binary v${{ env.PACKAGE_VERSION }}
prerelease: true
files: |
android-artifact/*
env:
GITHUB_TOKEN: ${{ github.token }}
+157
View File
@@ -0,0 +1,157 @@
name: Build Android Binary - main
on:
workflow_dispatch:
push:
branches:
- main
paths:
- 'core/src/**'
- 'core/**'
- 'CMakeLists.txt'
- 'core/CMakeLists.txt'
- '.github/workflows/android-main.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 1.1.56
jobs:
build-android:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
build-essential \
cmake \
ninja-build \
git \
curl \
zip \
unzip \
tar \
pkg-config \
autoconf \
autoconf-archive \
automake \
libtool
- name: Setup Android NDK r29
uses: nttld/setup-ndk@v1
with:
ndk-version: r29
add-to-path: true
- name: Show Android NDK information
run: |
echo "ANDROID_NDK_HOME=$ANDROID_NDK_HOME"
echo "ANDROID_NDK_ROOT=$ANDROID_NDK_ROOT"
ls -lah "$ANDROID_NDK_HOME"
- name: Setup vcpkg
run: |
git clone https://github.com/microsoft/vcpkg.git "$HOME/vcpkg"
"$HOME/vcpkg/bootstrap-vcpkg.sh"
echo "VCPKG_ROOT=$HOME/vcpkg" >> "$GITHUB_ENV"
echo "$HOME/vcpkg" >> "$GITHUB_PATH"
- name: Build Android dependencies
run: |
"$VCPKG_ROOT/vcpkg" install \
boost:arm64-android \
openssl:arm64-android \
yaml-cpp:arm64-android
- name: Configure Android arm64-v8a build
run: |
rm -rf build-android-arm64
cmake -S . -B build-android-arm64 \
-G Ninja \
-DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" \
-DVCPKG_TARGET_TRIPLET=arm64-android \
-DVCPKG_CHAINLOAD_TOOLCHAIN_FILE="$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake" \
-DANDROID_ABI=arm64-v8a \
-DANDROID_PLATFORM=android-23 \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_EXE_LINKER_FLAGS="-Wl,-z,max-page-size=16384" \
-DCMAKE_SHARED_LINKER_FLAGS="-Wl,-z,max-page-size=16384"
- name: Build Android arm64-v8a binary
run: |
cmake --build build-android-arm64 -j"$(nproc)"
- name: Collect Android binary and libraries
run: |
mkdir -p out/android/arm64-v8a
if [ ! -f build-android-arm64/core/nipovpn ]; then
echo "Android binary not found:"
find build-android-arm64 -type f || true
exit 1
fi
cp build-android-arm64/core/nipovpn out/android/arm64-v8a/libnipovpn_"${{ env.PACKAGE_VERSION }}".so
chmod 755 out/android/arm64-v8a/libnipovpn_"${{ env.PACKAGE_VERSION }}".so
find "$VCPKG_ROOT/installed/arm64-android" -type f -name "*.so*" -exec cp -v {} out/android/arm64-v8a/ \; || true
ls -lah out/android/arm64-v8a/
- name: Check 16 KB ELF alignment
run: |
READELF="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-readelf"
for file in out/android/arm64-v8a/*.so*; do
echo "Checking $file"
"$READELF" -l "$file" | grep -A3 LOAD || true
if "$READELF" -l "$file" | awk '/LOAD/ && $NF != "0x4000" { bad=1 } END { exit bad }'; then
echo "OK: $file is 16 KB aligned"
else
echo "ERROR: $file is not 16 KB aligned"
exit 1
fi
done
- name: Upload Android artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-main-android-arm64-v8a
path: out/android/arm64-v8a/
release-android:
needs:
- build-android
runs-on: ubuntu-24.04
steps:
- name: Download Android artifact
uses: actions/download-artifact@v4
with:
name: nipovpn-main-android-arm64-v8a
path: ./android-artifact
- name: Show downloaded Android artifact
run: |
ls -lah android-artifact
- name: Create Android GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: android-v${{ env.PACKAGE_VERSION }}
name: Android Binary v${{ env.PACKAGE_VERSION }}
prerelease: true
files: |
android-artifact/*
env:
GITHUB_TOKEN: ${{ github.token }}
+264 -40
View File
@@ -1,4 +1,4 @@
name: Build and Release Debian Package
name: Build and Release Package - dev
on:
push:
@@ -6,70 +6,294 @@ on:
- dev
paths:
- 'core/src/**'
- '.github/workflows/**'
- 'core/**'
- 'nipovpn/**'
- '.github/workflows/debian-dev.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 0.1.${{ github.run_number }}
jobs:
build:
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
include:
- arch: amd64
package_arch: amd64
- arch: arm64
package_arch: arm64
steps:
- name: Checkout source code
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Set up dependencies
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
with:
platforms: arm64
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y dpkg-dev build-essential lintian fakeroot devscripts cmake libssl-dev libboost-all-dev libyaml-cpp-dev
sudo apt-get install -y \
dpkg-dev \
build-essential \
lintian \
fakeroot \
devscripts \
cmake \
libssl-dev \
libboost-all-dev \
libyaml-cpp-dev
- name: Build the package
- name: Build binary
run: |
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Debug ..
make -j$(nproc)
cd ..
mkdir -p nipovpn/usr/bin/
cp build/core/nipovpn nipovpn/usr/bin/nipovpn
dpkg-deb --build nipovpn/ build/nipovpn_staging_v1-1-${{ github.run_number }}.deb
rm -rf build
- name: Upload the Debian nipovpn as an artifact
if [ "${{ matrix.arch }}" = "arm64" ]; then
docker run --rm --platform linux/arm64 \
-v "$PWD:/src" \
-w /src \
ubuntu:24.04 \
bash -c '
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y \
build-essential \
cmake \
libssl-dev \
libboost-all-dev \
libyaml-cpp-dev
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
'
sudo chown -R $USER:$USER build
else
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
fi
- name: Build Debian package
run: |
PACKAGE_FILE="nipovpn_dev_${PACKAGE_VERSION}_${{ matrix.arch }}.deb"
rm -rf package-root
cp -a nipovpn package-root
mkdir -p package-root/usr/bin
cp build/core/nipovpn package-root/usr/bin/nipovpn
chmod 755 package-root/usr/bin/nipovpn
sed -i -E "s/^Version[[:space:]]*:.*/Version: ${PACKAGE_VERSION}/" package-root/DEBIAN/control
sed -i -E "s/^Architecture[[:space:]]*:.*/Architecture: ${{ matrix.package_arch }}/" package-root/DEBIAN/control
sed -i -e '$a\' package-root/DEBIAN/control
echo "Final control file:"
cat package-root/DEBIAN/control
grep "^Version: ${PACKAGE_VERSION}$" package-root/DEBIAN/control
grep "^Architecture: ${{ matrix.package_arch }}$" package-root/DEBIAN/control
mkdir -p build
dpkg-deb --build package-root "build/${PACKAGE_FILE}"
ls -lah build/
- name: Show Debian package information
run: |
PACKAGE_FILE="nipovpn_dev_${PACKAGE_VERSION}_${{ matrix.arch }}.deb"
dpkg -I "build/${PACKAGE_FILE}"
dpkg -c "build/${PACKAGE_FILE}"
- name: Upload Debian package artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn
path: build/nipovpn_staging_v1-1-${{ github.run_number }}.deb
name: nipovpn-dev-deb-${{ matrix.arch }}
path: build/nipovpn_dev_${{ env.PACKAGE_VERSION }}_${{ matrix.arch }}.deb
- name: Show nipovpn information
build-termux:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v4
with:
path: nipovpn-src
- name: Install host dependencies
run: |
dpkg -I build/nipovpn_staging_v1-1-${{ github.run_number }}.deb
sudo apt-get update
sudo apt-get install -y \
git \
wget \
unzip \
curl \
python3 \
python3-pip \
build-essential \
cmake \
ninja-build \
pkg-config \
autoconf \
automake \
libtool \
autopoint \
bison \
flex \
gettext \
gperf \
help2man \
lzip \
libarchive-tools \
rsync \
texinfo \
jq
- name: Install Android NDK r29
run: |
mkdir -p "$HOME/lib"
cd "$HOME/lib"
wget -q https://dl.google.com/android/repository/android-ndk-r29-linux.zip
unzip -q android-ndk-r29-linux.zip
EXTRACTED_DIR="$(find "$HOME/lib" -maxdepth 1 -type d -name 'android-ndk-r29*' | head -n 1)"
if [ -z "$EXTRACTED_DIR" ]; then
echo "Android NDK r29 directory not found"
ls -lah "$HOME/lib"
exit 1
fi
ln -sfn "$EXTRACTED_DIR" "$HOME/lib/android-ndk-r29"
echo "NDK=$HOME/lib/android-ndk-r29" >> "$GITHUB_ENV"
echo "ANDROID_NDK_ROOT=$HOME/lib/android-ndk-r29" >> "$GITHUB_ENV"
ls -ld "$HOME/lib/android-ndk-r29"
- name: Clone termux-packages
run: |
git clone --depth=1 https://github.com/termux/termux-packages.git
- name: Create Termux package recipe
run: |
mkdir -p termux-packages/packages/nipovpn
cat > termux-packages/packages/nipovpn/build.sh <<'EOF'
TERMUX_PKG_HOMEPAGE=https://github.com/MortezaBashsiz/nipovpn
TERMUX_PKG_DESCRIPTION="Powerful and secure HTTP/S proxy"
TERMUX_PKG_LICENSE="MIT"
TERMUX_PKG_MAINTAINER="Morteza Bashsiz"
TERMUX_PKG_VERSION=@PACKAGE_VERSION@
TERMUX_PKG_SRCURL=file://@GITHUB_WORKSPACE@/nipovpn-src
TERMUX_PKG_SHA256=SKIP_CHECKSUM
TERMUX_PKG_DEPENDS="openssl, boost, libyaml-cpp"
TERMUX_PKG_BUILD_IN_SRC=false
termux_step_configure() {
cmake -S "$TERMUX_PKG_SRCDIR" \
-B "$TERMUX_PKG_BUILDDIR" \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX="$TERMUX_PREFIX"
}
termux_step_make() {
cmake --build "$TERMUX_PKG_BUILDDIR" -j "$(nproc)"
}
termux_step_make_install() {
install -Dm755 \
"$TERMUX_PKG_BUILDDIR/core/nipovpn" \
"$TERMUX_PREFIX/bin/nipovpn"
if [ -d "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn" ]; then
mkdir -p "$TERMUX_PREFIX/etc/nipovpn"
cp -a "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn/." \
"$TERMUX_PREFIX/etc/nipovpn/"
fi
}
EOF
sed -i "s|@PACKAGE_VERSION@|${PACKAGE_VERSION}|g" termux-packages/packages/nipovpn/build.sh
sed -i "s|@GITHUB_WORKSPACE@|${GITHUB_WORKSPACE}|g" termux-packages/packages/nipovpn/build.sh
cat termux-packages/packages/nipovpn/build.sh
- name: Prepare Termux build data dir
run: |
sudo mkdir -p /data
sudo chown -R $USER:$USER /data
- name: Build Termux aarch64 package
working-directory: termux-packages
run: |
./build-package.sh -I -a aarch64 nipovpn
- name: Collect Termux package
run: |
mkdir -p out
TERMUX_DEB="$(find termux-packages/output -type f -name '*.deb' | head -n 1)"
if [ -z "$TERMUX_DEB" ]; then
echo "No Termux .deb package found"
find termux-packages/output -type f || true
exit 1
fi
cp "$TERMUX_DEB" "out/nipovpn_dev_${PACKAGE_VERSION}_termux_aarch64.deb"
ls -lah out/
- name: Upload Termux package artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-dev-termux-aarch64
path: out/nipovpn_dev_${{ env.PACKAGE_VERSION }}_termux_aarch64.deb
release:
needs: build
needs:
- build
- build-termux
runs-on: ubuntu-latest
steps:
- name: Download build artifact
- name: Download package artifacts
uses: actions/download-artifact@v4
with:
name: nipovpn
pattern: nipovpn-dev-*
merge-multiple: true
path: ./
- name: Create GitHub Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
with:
tag_name: 'v1.1.${{ github.run_number }}'
release_name: Staging v1.1.${{ github.run_number }}
draft: false
prerelease: true
- name: Show downloaded files
run: |
ls -lah
- name: Upload Debian Package to Release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
- name: Create dev GitHub Release
uses: softprops/action-gh-release@v2
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./nipovpn_staging_v1-1-${{ github.run_number }}.deb
asset_name: nipovpn_staging_v1-1-${{ github.run_number }}.deb
asset_content_type: application/octet-stream
tag_name: dev-v${{ env.PACKAGE_VERSION }}
name: dev Version v${{ env.PACKAGE_VERSION }}
prerelease: true
files: |
nipovpn_dev_${{ env.PACKAGE_VERSION }}_amd64.deb
nipovpn_dev_${{ env.PACKAGE_VERSION }}_arm64.deb
nipovpn_dev_${{ env.PACKAGE_VERSION }}_termux_aarch64.deb
env:
GITHUB_TOKEN: ${{ github.token }}
+299
View File
@@ -0,0 +1,299 @@
name: Build and Release Package - Main
on:
push:
branches:
- main
paths:
- 'core/src/**'
- 'core/**'
- 'nipovpn/**'
- '.github/workflows/debian-main.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 1.1.56
jobs:
build:
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
include:
- arch: amd64
package_arch: amd64
- arch: arm64
package_arch: arm64
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
with:
platforms: arm64
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
dpkg-dev \
build-essential \
lintian \
fakeroot \
devscripts \
cmake \
libssl-dev \
libboost-all-dev \
libyaml-cpp-dev
- name: Build binary
run: |
rm -rf build
if [ "${{ matrix.arch }}" = "arm64" ]; then
docker run --rm --platform linux/arm64 \
-v "$PWD:/src" \
-w /src \
ubuntu:24.04 \
bash -c '
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y \
build-essential \
cmake \
libssl-dev \
libboost-all-dev \
libyaml-cpp-dev
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
'
sudo chown -R $USER:$USER build
else
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
fi
- name: Build Debian package
run: |
PACKAGE_FILE="nipovpn_${PACKAGE_VERSION}_${{ matrix.arch }}.deb"
rm -rf package-root
cp -a nipovpn package-root
mkdir -p package-root/usr/bin
cp build/core/nipovpn package-root/usr/bin/nipovpn
chmod 755 package-root/usr/bin/nipovpn
sed -i -E "s/^Version[[:space:]]*:.*/Version: ${PACKAGE_VERSION}/" package-root/DEBIAN/control
sed -i -E "s/^Architecture[[:space:]]*:.*/Architecture: ${{ matrix.package_arch }}/" package-root/DEBIAN/control
sed -i -e '$a\' package-root/DEBIAN/control
echo "Final control file:"
cat package-root/DEBIAN/control
grep "^Version: ${PACKAGE_VERSION}$" package-root/DEBIAN/control
grep "^Architecture: ${{ matrix.package_arch }}$" package-root/DEBIAN/control
mkdir -p build
dpkg-deb --build package-root "build/${PACKAGE_FILE}"
ls -lah build/
- name: Show Debian package information
run: |
PACKAGE_FILE="nipovpn_${PACKAGE_VERSION}_${{ matrix.arch }}.deb"
dpkg -I "build/${PACKAGE_FILE}"
dpkg -c "build/${PACKAGE_FILE}"
- name: Upload Debian package artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-deb-${{ matrix.arch }}
path: build/nipovpn_${{ env.PACKAGE_VERSION }}_${{ matrix.arch }}.deb
build-termux:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v4
with:
path: nipovpn-src
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
git \
wget \
unzip \
curl \
python3 \
python3-pip \
build-essential \
cmake \
ninja-build \
pkg-config \
autoconf \
automake \
libtool \
autopoint \
bison \
flex \
gettext \
gperf \
help2man \
lzip \
libarchive-tools \
rsync \
texinfo \
jq
- name: Install Android NDK r29
run: |
mkdir -p "$HOME/lib"
cd "$HOME/lib"
wget -q https://dl.google.com/android/repository/android-ndk-r29-linux.zip
unzip -q android-ndk-r29-linux.zip
EXTRACTED_DIR="$(find "$HOME/lib" -maxdepth 1 -type d -name 'android-ndk-r29*' | head -n 1)"
if [ -z "$EXTRACTED_DIR" ]; then
echo "Android NDK r29 directory not found"
ls -lah "$HOME/lib"
exit 1
fi
ln -sfn "$EXTRACTED_DIR" "$HOME/lib/android-ndk-r29"
echo "NDK=$HOME/lib/android-ndk-r29" >> "$GITHUB_ENV"
echo "ANDROID_NDK_ROOT=$HOME/lib/android-ndk-r29" >> "$GITHUB_ENV"
ls -ld "$HOME/lib/android-ndk-r29"
- name: Clone termux-packages
run: |
git clone --depth=1 https://github.com/termux/termux-packages.git
- name: Create Termux package recipe
run: |
mkdir -p termux-packages/packages/nipovpn
cat > termux-packages/packages/nipovpn/build.sh <<'EOF'
TERMUX_PKG_HOMEPAGE=https://github.com/MortezaBashsiz/nipovpn
TERMUX_PKG_DESCRIPTION="Powerful and secure HTTP/S proxy"
TERMUX_PKG_LICENSE="MIT"
TERMUX_PKG_MAINTAINER="Morteza Bashsiz"
TERMUX_PKG_VERSION=@PACKAGE_VERSION@
TERMUX_PKG_SRCURL=file://@GITHUB_WORKSPACE@/nipovpn-src
TERMUX_PKG_SHA256=SKIP_CHECKSUM
TERMUX_PKG_DEPENDS="openssl, boost, libyaml-cpp"
TERMUX_PKG_BUILD_IN_SRC=false
termux_step_configure() {
cmake -S "$TERMUX_PKG_SRCDIR" \
-B "$TERMUX_PKG_BUILDDIR" \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX="$TERMUX_PREFIX"
}
termux_step_make() {
cmake --build "$TERMUX_PKG_BUILDDIR" -j "$(nproc)"
}
termux_step_make_install() {
install -Dm755 \
"$TERMUX_PKG_BUILDDIR/core/nipovpn" \
"$TERMUX_PREFIX/bin/nipovpn"
if [ -d "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn" ]; then
mkdir -p "$TERMUX_PREFIX/etc/nipovpn"
cp -a "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn/." \
"$TERMUX_PREFIX/etc/nipovpn/"
fi
}
EOF
sed -i "s|@PACKAGE_VERSION@|${PACKAGE_VERSION}|g" termux-packages/packages/nipovpn/build.sh
sed -i "s|@GITHUB_WORKSPACE@|${GITHUB_WORKSPACE}|g" termux-packages/packages/nipovpn/build.sh
cat termux-packages/packages/nipovpn/build.sh
- name: Prepare Termux build data dir
run: |
sudo mkdir -p /data
sudo chown -R $USER:$USER /data
- name: Build Termux aarch64 package
working-directory: termux-packages
run: |
./build-package.sh -I -a aarch64 nipovpn
- name: Collect Termux package
run: |
mkdir -p out
TERMUX_DEB="$(find termux-packages/output -type f -name '*.deb' | head -n 1)"
if [ -z "$TERMUX_DEB" ]; then
echo "No Termux .deb package found"
find termux-packages/output -type f || true
exit 1
fi
cp "$TERMUX_DEB" "out/nipovpn_${PACKAGE_VERSION}_termux_aarch64.deb"
ls -lah out/
- name: Upload Termux package artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-termux-aarch64
path: out/nipovpn_${{ env.PACKAGE_VERSION }}_termux_aarch64.deb
release:
needs:
- build
- build-termux
runs-on: ubuntu-latest
steps:
- name: Download package artifacts
uses: actions/download-artifact@v4
with:
pattern: nipovpn-*
merge-multiple: true
path: ./
- name: Show downloaded files
run: |
ls -lah
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: v${{ env.PACKAGE_VERSION }}
name: Version v${{ env.PACKAGE_VERSION }}
prerelease: true
files: |
nipovpn_${{ env.PACKAGE_VERSION }}_amd64.deb
nipovpn_${{ env.PACKAGE_VERSION }}_arm64.deb
nipovpn_${{ env.PACKAGE_VERSION }}_termux_aarch64.deb
env:
GITHUB_TOKEN: ${{ github.token }}
-75
View File
@@ -1,75 +0,0 @@
name: Build and Release Debian Package
on:
push:
branches:
- main
paths:
- 'core/src/**'
jobs:
build:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v3
- name: Set up dependencies
run: |
sudo apt-get update
sudo apt-get install -y dpkg-dev build-essential lintian fakeroot devscripts cmake libssl-dev libboost-all-dev libyaml-cpp-dev
- name: Build the package
run: |
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Debug ..
make -j$(nproc)
cd ..
mkdir -p nipovpn/usr/bin/
cp build/core/nipovpn nipovpn/usr/bin/nipovpn
dpkg-deb --build nipovpn/ build/nipovpn_v1-1-${{ github.run_number }}.deb
- name: Upload the Debian nipovpn as an artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn
path: build/nipovpn_v1-1-${{ github.run_number }}.deb
- name: Show nipovpn information
run: |
dpkg -I build/nipovpn_v1-1-${{ github.run_number }}.deb
release:
needs: build
runs-on: ubuntu-latest
steps:
- name: Download build artifact
uses: actions/download-artifact@v4
with:
name: nipovpn
path: ./
- name: Create GitHub Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
with:
tag_name: 'v1.1.${{ github.run_number }}'
release_name: Version v1.1.${{ github.run_number }}
draft: false
prerelease: false
- name: Upload Debian Package to Release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./nipovpn_v1-1-${{ github.run_number }}.deb
asset_name: nipovpn_v1-1-${{ github.run_number }}.deb
asset_content_type: application/octet-stream
+98
View File
@@ -0,0 +1,98 @@
name: Build Windows Binary - dev
on:
push:
branches:
- dev
paths:
- 'core/**'
- 'server/**'
- 'agent/**'
- 'CMakeLists.txt'
- '.github/workflows/windows-dev.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 0.1.${{ github.run_number }}
jobs:
build-windows:
runs-on: windows-latest
defaults:
run:
shell: msys2 {0}
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Setup MSYS2
uses: msys2/setup-msys2@v2
with:
msystem: MINGW64
update: true
install: >-
git
zip
mingw-w64-x86_64-gcc
mingw-w64-x86_64-cmake
mingw-w64-x86_64-ninja
mingw-w64-x86_64-boost
mingw-w64-x86_64-openssl
mingw-w64-x86_64-yaml-cpp
- name: Build nipovpn.exe
run: |
rm -rf build dist
mkdir -p build dist
cmake -S . -B build \
-G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CXX_FLAGS="-DNOMINMAX -DWIN32_LEAN_AND_MEAN -DNOGDI -DOUT=NIPO_OUT"
cmake --build build -j$(nproc)
cp build/core/nipovpn.exe dist/
- name: Copy required DLL files
run: |
cd dist
for dll in $(ldd nipovpn.exe | grep 'mingw64' | awk '{print $3}'); do
cp "$dll" .
done
ls -lah
- name: Add config files
run: |
mkdir -p dist/etc/nipovpn
if [ -d nipovpn/etc/nipovpn ]; then
cp -a nipovpn/etc/nipovpn/. dist/etc/nipovpn/
fi
- name: Create ZIP package
run: |
cd dist
zip -r ../nipovpn_dev_${PACKAGE_VERSION}_windows_x86_64.zip .
- name: Upload Windows artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-dev-windows-x86_64
path: nipovpn_dev_${{ env.PACKAGE_VERSION }}_windows_x86_64.zip
- name: Create dev Windows Release
uses: softprops/action-gh-release@v2
with:
tag_name: dev-windows-v${{ env.PACKAGE_VERSION }}
name: dev Windows Binary v${{ env.PACKAGE_VERSION }}
prerelease: true
files: nipovpn_dev_${{ env.PACKAGE_VERSION }}_windows_x86_64.zip
env:
GITHUB_TOKEN: ${{ github.token }}
+99
View File
@@ -0,0 +1,99 @@
name: Build Windows Binary - main
on:
push:
branches:
- main
paths:
- 'core/**'
- 'server/**'
- 'agent/**'
- 'CMakeLists.txt'
- '.github/workflows/windows-main.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 1.1.56
jobs:
build-windows:
runs-on: windows-latest
defaults:
run:
shell: msys2 {0}
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Setup MSYS2
uses: msys2/setup-msys2@v2
with:
msystem: MINGW64
update: true
install: >-
git
zip
mingw-w64-x86_64-gcc
mingw-w64-x86_64-cmake
mingw-w64-x86_64-ninja
mingw-w64-x86_64-boost
mingw-w64-x86_64-openssl
mingw-w64-x86_64-yaml-cpp
- name: Build nipovpn.exe
run: |
rm -rf build dist
mkdir -p build dist
cmake -S . -B build \
-G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CXX_FLAGS="-DNOMINMAX -DWIN32_LEAN_AND_MEAN -DNOGDI -DOUT=NIPO_OUT"
cmake --build build -j$(nproc)
cp build/core/nipovpn.exe dist/
- name: Copy required DLL files
run: |
cd dist
for dll in $(ldd nipovpn.exe | grep 'mingw64' | awk '{print $3}'); do
cp "$dll" .
done
ls -lah
- name: Add config files
run: |
mkdir -p dist/etc/nipovpn
if [ -d nipovpn/etc/nipovpn ]; then
cp -a nipovpn/etc/nipovpn/. dist/etc/nipovpn/
fi
- name: Create ZIP package
run: |
cd dist
zip -r ../nipovpn_${PACKAGE_VERSION}_windows_x86_64.zip .
- name: Upload Windows artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-windows-x86_64
path: nipovpn_${{ env.PACKAGE_VERSION }}_windows_x86_64.zip
- name: Create Windows Release
uses: softprops/action-gh-release@v2
with:
tag_name: windows-v${{ env.PACKAGE_VERSION }}
name: Windows Binary v${{ env.PACKAGE_VERSION }}
prerelease: true
files: nipovpn_${{ env.PACKAGE_VERSION }}_windows_x86_64.zip
env:
GITHUB_TOKEN: ${{ github.token }}
+4
View File
@@ -10,6 +10,10 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -ggdb")
# Set the preprocessor flags
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -MMD -MP")
if(POLICY CMP0167)
cmake_policy(SET CMP0167 NEW)
endif()
# https://cmake.org/cmake/help/latest/module/FindBoost.html
find_package(Boost REQUIRED COMPONENTS regex OPTIONAL_COMPONENTS system)
+4 -49
View File
@@ -1,4 +1,4 @@
# NipoVPN (Not ready yet :D)
# NipoVPN
## Overview
@@ -36,6 +36,9 @@ To contribute take a look at [contribution page](https://github.com/MortezaBashs
Build from source for [Linux](guides/BuildLinux.md)
## Termux
Build from source for [Linux](guides/InstallTermux.md)
## Run
@@ -50,30 +53,6 @@ Create the log directory and log file
Run it
```bash
sudo build/core/nipovpn server nipovpn/etc/nipovpn/config.yaml
2024-08-02_15:30:07 [INFO] Config initialized in server mode
2024-08-02_15:30:07 [INFO]
Config :
General :
fakeUrl: http://www.adas.com/api01
method: HEAD
timeWait: 0
repeatWait: 1
Log :
logLevel: DEBUG
logFile: /var/log/nipovpn/nipovpn.log
server :
threads: 4
listenIp: 0.0.0.0
listenPort: 443
agent :
threads: 4
listenIp: 0.0.0.0
listenPort: 8080
serverIp: 127.0.0.1
serverPort: 443
token: af445adb-2434-4975-9445-2c1b2231
httpVersion: 1.1
userAgent: NipoAgent
```
### Package
@@ -92,28 +71,4 @@ There are systemd services to manage the nipovpn process.
```bash
[~]>$ sudo systemctl start nipovpn-server.service
[~]>$ cat /var/log/nipovpn/nipovpn.log
2024-08-02_15:30:07 [INFO] Config initialized in server mode
2024-08-02_15:30:07 [INFO]
Config :
General :
fakeUrl: http://www.adas.com/api01
method: HEAD
timeWait: 0
repeatWait: 1
Log :
logLevel: DEBUG
logFile: /var/log/nipovpn/nipovpn.log
server :
threads: 4
listenIp: 0.0.0.0
listenPort: 443
agent :
threads: 4
listenIp: 0.0.0.0
listenPort: 8080
serverIp: 127.0.0.1
serverPort: 443
token: af445adb-2434-4975-9445-2c1b2231
httpVersion: 1.1
userAgent: NipoAgent
```
+4
View File
@@ -38,3 +38,7 @@ target_include_directories(${CORE_TARGET} PUBLIC ${OPENSSL_INCLUDE_DIR})
target_link_libraries(${CORE_TARGET} ${Boost_LIBRARIES})
target_link_libraries(${CORE_TARGET} ${YAML_CPP_LIBRARIES})
target_link_libraries(${CORE_TARGET} ${OPENSSL_LIBRARIES})
if(WIN32)
target_link_libraries(${CORE_TARGET} ws2_32 mswsock)
endif()
+95 -118
View File
@@ -1,40 +1,22 @@
#include "agenthandler.hpp"
/**
* @brief Constructs an AgentHandler object to manage client-agent interactions.
*
* This constructor initializes the AgentHandler with the necessary resources,
* including read and write buffers, configuration, logging, client connection,
* and a unique identifier for the session.
*
* @param readBuffer Reference to the stream buffer used for reading data.
* @param writeBuffer Reference to the stream buffer used for writing data.
* @param config Shared pointer to the configuration object containing system settings.
* @param log Shared pointer to the logging object for recording events and errors.
* @param client Shared pointer to the TCPClient object managing the client connection.
* @param clientConnStr A string representing the client's connection details.
* @param uuid A unique identifier for the session, provided as a Boost UUID.
*
* @details
* - Initializes the HTTP request handler using the provided configuration, logger,
* read buffer, and UUID.
* - Sets the `end_` flag to `false`, indicating the handler is active and ready.
* - Initializes the `connect_` flag to `false`, indicating no active connection initially.
*/
#include <sstream>
#include <utility>
AgentHandler::AgentHandler(boost::asio::streambuf &readBuffer,
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid)
: config_(config),
log_(log),
client_(client),
client_(std::move(client)),
readBuffer_(readBuffer),
writeBuffer_(writeBuffer),
request_(HTTP::create(config, log, readBuffer, uuid)),
clientConnStr_(clientConnStr),
clientConnStr_(std::move(clientConnStr)),
uuid_(uuid) {
end_ = false;
connect_ = false;
@@ -42,50 +24,11 @@ AgentHandler::AgentHandler(boost::asio::streambuf &readBuffer,
AgentHandler::~AgentHandler() {}
/**
* @brief Handles the processing of incoming requests, encryption, server communication, and response handling.
*
* This function coordinates multiple tasks, including:
* - Encrypting the incoming data.
* - Generating and sending an HTTP request to the server.
* - Receiving and decrypting the server's response.
* - Managing the connection state and logging detailed information at each step.
*
* @details
* - The function ensures thread safety using a mutex lock.
* - The incoming data is encrypted using AES-256 with a token retrieved from the configuration.
* - If encryption is successful, the function builds an HTTP POST request and determines the request type.
* - It establishes a connection to the server if required and sends the encrypted request.
* - The server's response is parsed and decrypted. If successful, the decrypted data is copied to the write buffer.
* - Handles HTTP and non-HTTP responses, including error scenarios and connection cleanup.
* - Maintains logging for debugging and informational purposes throughout the process.
*
* @note In case of any error during encryption, connection, or response handling, the client socket is closed.
*/
void AgentHandler::handle() {
std::lock_guard lock(mutex_);
BoolStr encryption{false, std::string("FAILED")};
encryption = aes256Encrypt(hexStreambufToStr(readBuffer_),
config_->general().token);
if (!encryption.ok) {
log_->write("[" + to_string(uuid_) +
"] [AgentHandler handle] [Encryption Failed] : [ " +
encryption.message + "] ",
Log::Level::DEBUG);
client_->socketShutdown();
return;
}
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Encryption Done]",
Log::Level::DEBUG);
std::string newReq(
request_->genHttpPostReqString(encode64(encryption.message)));
if (!request_->detectType()) {
log_->write("[" + to_string(uuid_) +
"] [AgentHandler handle] [NOT HTTP Request] [Request] : " +
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [NOT HTTP Request] [Request] : " +
streambufToString(readBuffer_),
Log::Level::DEBUG);
client_->socketShutdown();
@@ -93,19 +36,16 @@ void AgentHandler::handle() {
}
if (request_->parsedHttpRequest().target().length() > 0) {
log_->write("[" + to_string(uuid_) + "] [CONNECT] [SRC " + clientConnStr_ +
"] [DST " +
std::string(request_->parsedHttpRequest().target()) +
"]",
Log::Level::INFO);
log_->write("[" + to_string(uuid_) + "] [FORWARD] [SRC " + clientConnStr_ + "] [DST " +
std::string(request_->parsedHttpRequest().target()) + "]",
Log::Level::TRACE);
}
if (config_->agent().tlsEnable && !client_->tlsEnabled()) {
if (config_->general().tlsEnable && !client_->tlsEnabled()) {
if (!client_->enableTlsClient()) {
log_->write("[" + to_string(uuid_) +
"] [TLS] [ERROR] [Init Client Context] [SRC " +
clientConnStr_ + "] [DST " + config_->agent().serverIp +
":" + std::to_string(config_->agent().serverPort) + "]",
log_->write("[" + to_string(uuid_) + "] [TLS] [ERROR] [Init Client Context] [SRC " +
clientConnStr_ + "] [DST " + config_->agent().serverIp + ":" +
std::to_string(config_->agent().serverPort) + "]",
Log::Level::ERROR);
client_->socketShutdown();
return;
@@ -113,65 +53,88 @@ void AgentHandler::handle() {
}
if (!client_->isOpen()) {
connect_ = true;
if (!client_->doConnect(config_->agent().serverIp,
config_->agent().serverPort)) {
log_->write("[" + to_string(uuid_) +
"] [CONNECT] [ERROR] [To Server] [SRC " + clientConnStr_ +
"] [DST " + config_->agent().serverIp + ":" +
if (!client_->doConnect(config_->agent().serverIp, config_->agent().serverPort)) {
log_->write("[" + to_string(uuid_) + "] [CONNECT] [ERROR] [To Server] [SRC " +
clientConnStr_ + "] [DST " + config_->agent().serverIp + ":" +
std::to_string(config_->agent().serverPort) + "]",
Log::Level::INFO);
client_->socketShutdown();
return;
}
if (client_->tlsEnabled()) {
if (!client_->doHandshakeClient()) {
log_->write("[" + to_string(uuid_) +
"] [TLS] [ERROR] [Client Handshake] [SRC " +
clientConnStr_ + "] [DST " + config_->agent().serverIp +
":" + std::to_string(config_->agent().serverPort) + "]",
Log::Level::ERROR);
client_->socketShutdown();
return;
}
if (client_->tlsEnabled() && !client_->doHandshakeClient()) {
log_->write("[" + to_string(uuid_) + "] [TLS] [ERROR] [Client Handshake] [SRC " +
clientConnStr_ + "] [DST " + config_->agent().serverIp + ":" +
std::to_string(config_->agent().serverPort) + "]",
Log::Level::ERROR);
client_->socketShutdown();
return;
}
}
copyStringToStreambuf(newReq, readBuffer_);
client_->doWrite(readBuffer_);
client_->doReadAgent();
if (client_->readBuffer().size() == 0) {
client_->socketShutdown();
return;
}
if (request_->httpType() == HTTP::HttpType::connect) {
connect_ = true;
moveStreambuf(client_->readBuffer(), writeBuffer_);
return;
}
HTTP::pointer response =
HTTP::create(config_, log_, client_->readBuffer(), uuid_);
if (!response->parseHttpResp()) {
log_->write("[AgentHandler handle] [NOT HTTP Response] [Response] : " +
streambufToString(client_->readBuffer()),
BoolStr encryption{false, std::string("FAILED")};
encryption = aes256Encrypt(hexStreambufToStr(readBuffer_), config_->general().token);
if (!encryption.ok) {
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Encryption Failed] : [ " +
encryption.message + "] ",
Log::Level::DEBUG);
client_->socketShutdown();
return;
}
BoolStr decryption{false, std::string("FAILED")};
decryption = aes256Decrypt(
decode64(std::string(response->parsedHttpResponse().body())),
config_->general().token);
const std::string innerRequest = encode64(encryption.message);
const std::string action =
request_->httpType() == HTTP::HttpType::connect ? "open" : "request";
std::ostringstream outer;
const bool directTunnelOpen =
config_->general().tunnelEnable &&
request_->httpType() == HTTP::HttpType::connect;
outer << config_->randomMethod() + " /" + config_->randomEndPoint() + " HTTP/" << config_->agent().httpVersion << "\r\n"
<< "Host: " << relayHostHeader(config_) << "\r\n"
<< "User-Agent: " << config_->agent().userAgent << "\r\n"
<< "Accept: */*\r\n"
<< "Content-Type: application/text\r\n"
<< "X-Nipo-Session: " << to_string(uuid_) << "\r\n"
<< "X-Nipo-Action: " << action << "\r\n"
<< "Content-Length: " << innerRequest.size() << "\r\n"
<< "Connection: "
<< ((config_->general().connectionReuse || directTunnelOpen) ? "keep-alive" : "close")
<< "\r\n"
<< "\r\n"
<< innerRequest;
copyStringToStreambuf(outer.str(), readBuffer_);
client_->doWrite(readBuffer_);
client_->doReadAgent();
if (client_->readBuffer().size() == 0 && !config_->general().connectionReuse) {
client_->socketShutdown();
return;
}
const std::string outerResponse = streambufToString(client_->readBuffer());
const auto bodyPos = outerResponse.find("\r\n\r\n");
if (bodyPos == std::string::npos) {
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [NOT HTTP Response] [Response] : " +
outerResponse,
Log::Level::DEBUG);
client_->socketShutdown();
return;
}
const std::string encryptedBody = outerResponse.substr(bodyPos + 4);
if (encryptedBody.empty()) {
client_->socketShutdown();
return;
}
BoolStr decryption{false, std::string("FAILED")};
decryption = aes256Decrypt(encryptedBody, config_->general().token);
if (!decryption.ok) {
log_->write("[" + to_string(uuid_) +
"] [AgentHandler handle] [Decryption Failed] : [ " +
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Decryption Failed] : [ " +
decryption.message + "] ",
Log::Level::DEBUG);
client_->socketShutdown();
@@ -179,4 +142,18 @@ void AgentHandler::handle() {
}
copyStringToStreambuf(decryption.message, writeBuffer_);
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Decryption Done]",
Log::Level::DEBUG);
connect_ = request_->httpType() == HTTP::HttpType::connect;
end_ = false;
}
std::string AgentHandler::relayHostHeader(const std::shared_ptr<Config> &config) {
std::string hostHeader = config->randomFakeUrl();
auto pos = hostHeader.find("://");
if (pos != std::string::npos) hostHeader = hostHeader.substr(pos + 3);
pos = hostHeader.find('/');
if (pos != std::string::npos) hostHeader = hostHeader.substr(0, pos);
return hostHeader;
}
+19 -73
View File
@@ -9,46 +9,17 @@
#include "log.hpp"
#include "tcpclient.hpp"
/**
* @brief The `AgentHandler` class manages the interaction between the client and the agent,
* including handling requests, responses, and connection state.
*
* @details
* - This class is derived from `Uncopyable` to prevent copying or assignment.
* - It provides functionality for handling initial requests (`handle`) and continuing
* with subsequent reads and responses (`continueRead`).
* - Uses Boost.Asio stream buffers for managing input and output data streams.
* - Ensures thread safety with an internal mutex.
* - Maintains the connection state with `end_` and `connect_` flags.
* - Supports logging and configuration through shared pointers to external objects.
*
* @note
* - The class uses a `pointer` alias for shared ownership management via `std::shared_ptr`.
* - The `create` static factory method constructs an instance and returns it as a `pointer`.
* - Requires a valid Boost.Asio I/O context and other dependencies to function properly.
*/
class AgentHandler : private Uncopyable {
public:
using pointer = std::shared_ptr<AgentHandler>;
/**
* @brief Factory method to create an instance of `AgentHandler`.
*
* @param readBuffer Reference to the stream buffer for reading data.
* @param writeBuffer Reference to the stream buffer for writing data.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @param client Shared pointer to the `TCPClient` object managing the connection.
* @param clientConnStr String containing the client connection information.
* @param uuid Unique identifier for this handler, represented as a Boost UUID.
* @return A shared pointer to the newly created `AgentHandler` instance.
*/
static pointer create(boost::asio::streambuf &readBuffer,
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid) {
return pointer(new AgentHandler(readBuffer, writeBuffer, config, log,
client, clientConnStr, uuid));
@@ -56,57 +27,32 @@ public:
~AgentHandler();
/**
* @brief Handles the initial processing of requests, encryption, and server communication.
*/
void handle();
/**
* @brief Accessor for the HTTP request object.
*
* @return A reference to the HTTP request object.
*/
inline const HTTP::pointer &request() & { return request_; }
inline const HTTP::pointer &request() const { return request_; }
/**
* @brief Accessor for the HTTP request object, allowing move semantics.
*
* @return An rvalue reference to the HTTP request object.
*/
inline const HTTP::pointer &&request() && { return std::move(request_); }
bool end_; ///< Indicates whether the handler has completed its operations.
bool connect_;///< Indicates the connection state.
bool end_;
bool connect_;
private:
/**
* @brief Constructs an `AgentHandler` instance with the specified parameters.
*
* @param readBuffer Reference to the stream buffer for reading data.
* @param writeBuffer Reference to the stream buffer for writing data.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @param client Shared pointer to the `TCPClient` object managing the connection.
* @param clientConnStr String containing the client connection information.
* @param uuid Unique identifier for this handler, represented as a Boost UUID.
*/
AgentHandler(boost::asio::streambuf &readBuffer,
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid);
const std::shared_ptr<Config> &config_;///< Configuration object reference.
const std::shared_ptr<Log> &log_; ///< Logging object reference.
const TCPClient::pointer &client_; ///< TCP client managing the connection.
boost::asio::streambuf &readBuffer_; ///< Buffer for reading data.
boost::asio::streambuf &writeBuffer_; ///< Buffer for writing data.
HTTP::pointer request_; ///< HTTP request handler.
const std::string &clientConnStr_; ///< Client connection string.
std::string relayHostHeader(const std::shared_ptr<Config> &config);
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
TCPClient::pointer client_;
boost::asio::streambuf &readBuffer_;
boost::asio::streambuf &writeBuffer_;
HTTP::pointer request_;
std::string clientConnStr_;
boost::uuids::uuid uuid_;///< Unique identifier for this handler.
boost::uuids::uuid uuid_;
std::mutex mutex_;///< Mutex for ensuring thread safety.
};
std::mutex mutex_;
};
+119 -33
View File
@@ -1,6 +1,7 @@
#include "config.hpp"
Config::Config(const RunMode &mode, const std::string &filePath)
Config::Config(RunMode mode, const std::string &filePath)
: runMode_(mode),
filePath_(filePath),
configYaml_(YAML::LoadFile(filePath)),
@@ -8,31 +9,32 @@ Config::Config(const RunMode &mode, const std::string &filePath)
listenIp_("127.0.0.1"),
listenPort_(0),
general_({configYaml_["general"]["token"].as<std::string>(),
configYaml_["general"]["fakeUrl"].as<std::string>(),
configYaml_["general"]["method"].as<std::string>(),
configYaml_["general"]["protocol"].as<std::string>(""),
configYaml_["general"]["fakeUrls"].as<std::vector<std::string>>(),
configYaml_["general"]["methods"].as<std::vector<std::string>>(),
configYaml_["general"]["endPoints"].as<std::vector<std::string>>(),
configYaml_["general"]["timeout"].as<unsigned short>(),
configYaml_["general"]["chunkHeader"].as<std::string>()}),
configYaml_["general"]["pullTimeout"].as<unsigned short>(),
configYaml_["general"]["tunnelEnable"].as<bool>(false),
configYaml_["general"]["connectionReuse"].as<bool>(false),
configYaml_["general"]["tlsEnable"].as<bool>(false),
configYaml_["general"]["tlsVerifyPeer"].as<bool>(false),
configYaml_["general"]["tlsCertFile"].as<std::string>(""),
configYaml_["general"]["tlsKeyFile"].as<std::string>(""),
configYaml_["general"]["tlsCaFile"].as<std::string>("")}),
log_({configYaml_["log"]["logLevel"].as<std::string>(),
configYaml_["log"]["logFile"].as<std::string>()}),
server_({configYaml_["server"]["threads"].as<unsigned short>(),
configYaml_["server"]["listenIp"].as<std::string>(),
configYaml_["server"]["listenPort"].as<unsigned short>(),
configYaml_["server"]["tlsEnable"].as<bool>(false),
configYaml_["server"]["tlsVerifyPeer"].as<bool>(false),
configYaml_["server"]["tlsCertFile"].as<std::string>(""),
configYaml_["server"]["tlsKeyFile"].as<std::string>(""),
configYaml_["server"]["tlsCaFile"].as<std::string>(""),
configYaml_["server"]["tlsDhFile"].as<std::string>("")}),
configYaml_["server"]["listenPort"].as<unsigned short>()}),
agent_({configYaml_["agent"]["threads"].as<unsigned short>(),
configYaml_["agent"]["listenIp"].as<std::string>(),
configYaml_["agent"]["listenPort"].as<unsigned short>(),
configYaml_["agent"]["serverIp"].as<std::string>(),
configYaml_["agent"]["serverPort"].as<unsigned short>(),
configYaml_["agent"]["httpVersion"].as<std::string>(),
configYaml_["agent"]["userAgent"].as<std::string>(),
configYaml_["agent"]["tlsEnable"].as<bool>(false),
configYaml_["agent"]["tlsVerifyPeer"].as<bool>(false),
configYaml_["agent"]["tlsCaFile"].as<std::string>("")}) {
configYaml_["agent"]["userAgent"].as<std::string>()}) {
std::lock_guard<std::mutex> lock(configMutex_);
switch (runMode_) {
@@ -41,6 +43,7 @@ Config::Config(const RunMode &mode, const std::string &filePath)
listenIp_ = server_.listenIp;
listenPort_ = server_.listenPort;
break;
case RunMode::agent:
threads_ = agent_.threads;
listenIp_ = agent_.listenIp;
@@ -65,39 +68,73 @@ Config::~Config() = default;
std::string Config::toString() const {
std::lock_guard<std::mutex> lock(configMutex_);
std::stringstream ss;
ss << "\nConfig :\n"
<< " General :\n"
<< " token: " << general_.token << "\n"
<< " fakeUrl: " << general_.fakeUrl << "\n"
<< " method: " << general_.method << "\n"
<< " protocol: " << general_.protocol << "\n"
<< " fakeUrls: ";
for (std::size_t i = 0; i < general_.fakeUrls.size(); ++i) {
ss << general_.fakeUrls[i];
if (i != general_.fakeUrls.size() - 1) {
ss << ", ";
}
}
ss << "\n"
<< " methods: ";
for (std::size_t i = 0; i < general_.methods.size(); ++i) {
ss << general_.methods[i];
if (i != general_.methods.size() - 1) {
ss << ", ";
}
}
ss << "\n"
<< " endPoints: ";
for (std::size_t i = 0; i < general_.endPoints.size(); ++i) {
ss << general_.endPoints[i];
if (i != general_.endPoints.size() - 1) {
ss << ", ";
}
}
ss << "\n"
<< " timeout: " << general_.timeout << "\n"
<< " chunkHeader: " << general_.chunkHeader << "\n"
<< " pullTimeout: " << general_.pullTimeout << "\n"
<< " tunnelEnable: " << std::boolalpha << general_.tunnelEnable << "\n"
<< " connectionReuse: " << std::boolalpha << general_.connectionReuse << "\n"
<< " tlsEnable: " << std::boolalpha << general_.tlsEnable << "\n"
<< " tlsVerifyPeer: " << std::boolalpha << general_.tlsVerifyPeer << "\n"
<< " tlsCertFile: " << general_.tlsCertFile << "\n"
<< " tlsKeyFile: " << general_.tlsKeyFile << "\n"
<< " tlsCaFile: " << general_.tlsCaFile << "\n"
<< " Log :\n"
<< " logLevel: " << log_.level << "\n"
<< " logFile: " << log_.file << "\n"
<< " server :\n"
<< " Server :\n"
<< " threads: " << server_.threads << "\n"
<< " listenIp: " << server_.listenIp << "\n"
<< " listenPort: " << server_.listenPort << "\n"
<< " tlsEnable: " << server_.tlsEnable << "\n"
<< " tlsVerifyPeer: " << server_.tlsVerifyPeer << "\n"
<< " tlsCertFile: " << server_.tlsCertFile << "\n"
<< " tlsKeyFile: " << server_.tlsKeyFile << "\n"
<< " tlsCaFile: " << server_.tlsCaFile << "\n"
<< " tlsDhFile: " << server_.tlsDhFile << "\n"
<< " agent :\n"
<< " Agent :\n"
<< " threads: " << agent_.threads << "\n"
<< " listenIp: " << agent_.listenIp << "\n"
<< " listenPort: " << agent_.listenPort << "\n"
<< " serverIp: " << agent_.serverIp << "\n"
<< " serverPort: " << agent_.serverPort << "\n"
<< " httpVersion: " << agent_.httpVersion << "\n"
<< " userAgent: " << agent_.userAgent << "\n"
<< " tlsEnable: " << agent_.tlsEnable << "\n"
<< " tlsVerifyPeer: " << agent_.tlsVerifyPeer << "\n"
<< " tlsCaFile: " << agent_.tlsCaFile << "\n";
<< " userAgent: " << agent_.userAgent << "\n";
return ss.str();
}
@@ -122,7 +159,7 @@ const Config::Agent &Config::agent() const {
return agent_;
}
const unsigned short &Config::threads() const {
unsigned short Config::threads() const {
std::lock_guard<std::mutex> lock(configMutex_);
return threads_;
}
@@ -142,7 +179,7 @@ void Config::listenIp(const std::string &ip) {
listenIp_ = ip;
}
const unsigned short &Config::listenPort() const {
unsigned short Config::listenPort() const {
std::lock_guard<std::mutex> lock(configMutex_);
return listenPort_;
}
@@ -152,7 +189,7 @@ void Config::listenPort(unsigned short port) {
listenPort_ = port;
}
const RunMode &Config::runMode() const {
RunMode Config::runMode() const {
std::lock_guard<std::mutex> lock(configMutex_);
return runMode_;
}
@@ -164,6 +201,7 @@ const std::string &Config::filePath() const {
std::string Config::modeToString() const {
std::lock_guard<std::mutex> lock(configMutex_);
switch (runMode_) {
case RunMode::server:
return "server";
@@ -172,4 +210,52 @@ std::string Config::modeToString() const {
default:
return "UNKNOWN MODE";
}
}
std::string Config::randomFakeUrl() const {
std::lock_guard<std::mutex> lock(configMutex_);
if (general_.fakeUrls.empty()) {
return "www.google.com";
}
static thread_local std::mt19937 generator{std::random_device{}()};
std::uniform_int_distribution<std::size_t> distribution(
0,
general_.fakeUrls.size() - 1);
return general_.fakeUrls[distribution(generator)];
}
std::string Config::randomMethod() const {
std::lock_guard<std::mutex> lock(configMutex_);
if (general_.methods.empty()) {
return "GET";
}
static thread_local std::mt19937 generator{std::random_device{}()};
std::uniform_int_distribution<std::size_t> distribution(
0,
general_.methods.size() - 1);
return general_.methods[distribution(generator)];
}
std::string Config::randomEndPoint() const {
std::lock_guard<std::mutex> lock(configMutex_);
if (general_.endPoints.empty()) {
return "api";
}
static thread_local std::mt19937 generator{std::random_device{}()};
std::uniform_int_distribution<std::size_t> distribution(
0,
general_.endPoints.size() - 1);
return general_.endPoints[distribution(generator)];
}
+38 -23
View File
@@ -4,22 +4,35 @@
#include <memory>
#include <mutex>
#include <random>
#include <sstream>
#include <string>
#include <vector>
#include "general.hpp"
enum class RunMode { server,
agent };
enum class RunMode {
server,
agent
};
class Config : private Uncopyable {
private:
struct General {
std::string token;
std::string fakeUrl;
std::string method;
std::string protocol;
std::vector<std::string> fakeUrls;
std::vector<std::string> methods;
std::vector<std::string> endPoints;
unsigned short timeout;
std::string chunkHeader;
unsigned short pullTimeout;
bool tunnelEnable;
bool connectionReuse;
bool tlsEnable;
bool tlsVerifyPeer;
std::string tlsCertFile;
std::string tlsKeyFile;
std::string tlsCaFile;
};
struct Log {
@@ -31,13 +44,6 @@ private:
unsigned short threads;
std::string listenIp;
unsigned short listenPort;
bool tlsEnable;
bool tlsVerifyPeer;
std::string tlsCertFile;
std::string tlsKeyFile;
std::string tlsCaFile;
std::string tlsDhFile;
};
struct Agent {
@@ -48,27 +54,24 @@ private:
unsigned short serverPort;
std::string httpVersion;
std::string userAgent;
bool tlsEnable;
bool tlsVerifyPeer;
std::string tlsCaFile;
};
const RunMode &runMode_;
RunMode runMode_;
std::string filePath_;
const YAML::Node configYaml_;
YAML::Node configYaml_;
unsigned short threads_;
std::string listenIp_;
unsigned short listenPort_;
mutable std::mutex configMutex_;
explicit Config(const RunMode &mode, const std::string &filePath);
explicit Config(RunMode mode, const std::string &filePath);
public:
using pointer = std::shared_ptr<Config>;
static pointer create(const RunMode &mode, const std::string &filePath) {
static pointer create(RunMode mode, const std::string &filePath) {
return pointer(new Config(mode, filePath));
}
@@ -78,6 +81,7 @@ public:
const Agent agent_;
explicit Config(const Config::pointer &config);
~Config();
const General &general() const;
@@ -85,18 +89,29 @@ public:
const Server &server() const;
const Agent &agent() const;
const unsigned short &threads() const;
unsigned short threads() const;
void threads(unsigned short threads);
const std::string &listenIp() const;
void listenIp(const std::string &ip);
const unsigned short &listenPort() const;
unsigned short listenPort() const;
void listenPort(unsigned short port);
const RunMode &runMode() const;
RunMode runMode() const;
const std::string &filePath() const;
std::string modeToString() const;
std::string toString() const;
std::string randomFakeUrl() const;
std::string randomMethod() const;
std::string randomEndPoint() const;
};
+44 -148
View File
@@ -19,13 +19,13 @@
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
/**
* @brief Abstract for inheritance to make classes Uncopyable.
*/
static constexpr std::size_t BufferSize = 8192;
class Uncopyable {
public:
Uncopyable() = default;
@@ -35,52 +35,26 @@ private:
Uncopyable &operator=(const Uncopyable &) = delete;
};
/**
* @brief Prints message to output.
*
* @param message an auto refrence to message.
*/
inline void OUT(const auto &message) {
std::cout << "OUT OUT OUT OUT OUT OUT OUT OUT : " << message
<< std::endl;
}
/**
* @brief struct for return a bool with specific message.
*/
struct BoolStr {
bool ok;
std::string message;
};
/**
* @brief checks if the file exists or not.
*
* @param name which is refrenced to the string path of file.
* @return bool as result of existance.
*/
inline bool fileExists(const std::string &name) {
std::ifstream file(name.c_str());
return file.good();
}
/**
* @brief converts streambuffer to string.
*
* @param buff is a refrence to streambuffer.
* @return string format of given buffer.
*/
inline std::string streambufToString(const boost::asio::streambuf &buff) {
return {boost::asio::buffers_begin(buff.data()),
boost::asio::buffers_begin(buff.data()) + buff.size()};
}
/**
* @brief copies a string to streambuffer.
*
* @param inputStr a refrence to the string.
* @param buff a refrence to the streambuffer.
*/
inline void copyStringToStreambuf(const std::string &inputStr,
boost::asio::streambuf &buff) {
buff.consume(buff.size());
@@ -88,13 +62,6 @@ inline void copyStringToStreambuf(const std::string &inputStr,
os << inputStr;
}
/**
* @brief moves a streambuffer to another streambuffer.
* it will consume(clean) the source streambuffer.
*
* @param source a refrence to the source streambuffer.
* @param target a refrence to the target streambuffer.
*/
inline void moveStreambuf(boost::asio::streambuf &source,
boost::asio::streambuf &target) {
auto bytes_copied =
@@ -103,13 +70,6 @@ inline void moveStreambuf(boost::asio::streambuf &source,
source.consume(source.size());
}
/**
* @brief copies a streambuffer to another streambuffer.
* it will keep the source streambuffer as is.
*
* @param source a refrence to the source streambuffer.
* @param target a refrence to the target streambuffer.
*/
inline void copyStreambuf(boost::asio::streambuf &source,
boost::asio::streambuf &target) {
auto bytes_copied =
@@ -117,58 +77,36 @@ inline void copyStreambuf(boost::asio::streambuf &source,
target.commit(bytes_copied);
}
/**
* @brief converts hexadecimal array to string.
*
* @param data is a refrence to the hexadecimal array.
* @size is size of hexadecimal array.
* @return string format of given array.
*/
inline std::string hexArrToStr(const unsigned char *data, std::size_t size) {
std::stringstream tempStr;
tempStr << std::hex << std::setfill('0');
for (std::size_t i = 0; i < size; ++i) {
tempStr << std::setw(2) << static_cast<unsigned>(data[i]);
}
return tempStr.str();
}
/**
* @brief converts hexadecimal string to int.
*
* @param hexString is a refrence to the hexadecimal string.
* @return the result as unsigned int.
*/
inline unsigned int hexToInt(const std::string &hexString) {
unsigned short result;
unsigned int result{};
std::stringstream hexStr(hexString);
hexStr >> std::hex >> result;
return result;
}
/**
* @brief converts hexadecimal string to ASCII string format.
*
* @param hex is a refrence to the hexadecimal string.
* @return the result as string.
*/
inline std::string hexToASCII(const std::string &hex) {
std::string ascii;
for (size_t i = 0; i < hex.length(); i += 2) {
std::string part = hex.substr(i, 2);
char ch = static_cast<char>(stoul(part, nullptr, 16));
ascii += ch;
}
return ascii;
}
/**
* @brief converts a char hexadecimal char.
*
* @param c is a char.
* @return the result as hex char.
*/
inline unsigned char charToHex(char c) {
if ('0' <= c && c <= '9') return c - '0';
if ('A' <= c && c <= 'F') return c - 'A' + 10;
@@ -176,64 +114,46 @@ inline unsigned char charToHex(char c) {
return 0;
}
/**
* @brief converts string to hexadecimal array.
*
* @param hexStr is a refrence to the hexadecimal string.
* @return the result as a vector of chars.
*/
inline std::vector<unsigned char> strToHexArr(const std::string &hexStr) {
std::vector<unsigned char> result(hexStr.size() / 2);
for (std::size_t i = 0; i < hexStr.size() / 2; ++i)
for (std::size_t i = 0; i < hexStr.size() / 2; ++i) {
result[i] = 16 * charToHex(hexStr[2 * i]) + charToHex(hexStr[2 * i + 1]);
}
return result;
}
/**
* @brief converts streambuffer to string.
* first we need to convert the streambuffer to hex array and then to string
*
* @param buff is a refrence to the streambuffer.
* @return the result as a string.
*/
inline std::string hexStreambufToStr(const boost::asio::streambuf &buff) {
return hexArrToStr(
reinterpret_cast<const unsigned char *>(streambufToString(buff).c_str()),
buff.size());
}
/**
* @brief splits string based on delimiter.
*
* @param str is a refrence to the string.
* @param delimiter is a refrence to the delimiter string.
* @return the result as a vector of strings.
*/
inline std::vector<std::string> splitString(const std::string &str,
const std::string &delimiter) {
std::vector<std::string> result;
std::string tempStr = str;
while (!tempStr.empty()) {
size_t index = tempStr.find(delimiter);
if (index != std::string::npos) {
result.push_back(tempStr.substr(0, index));
tempStr = tempStr.substr(index + delimiter.size());
if (tempStr.empty()) result.push_back(tempStr);
if (tempStr.empty()) {
result.push_back(tempStr);
}
} else {
result.push_back(tempStr);
tempStr.clear();
}
}
return result;
}
/**
* @brief decodes based64 encoded string.
*
* @param inputStr is a refrence to the encoded string.
* @return decoded string.
*/
inline std::string decode64(const std::string &inputStr) {
using namespace boost::archive::iterators;
@@ -245,17 +165,11 @@ inline std::string decode64(const std::string &inputStr) {
using transformWidth = transform_width<binaryFromBase64, 8, 6>;
return {transformWidth(temp.begin()), transformWidth(temp.end())};
} catch (const std::exception &e) {
} catch (const std::exception &) {
throw std::runtime_error("Invalid Base64 encoding");
}
}
/**
* @brief encodes string in base64 format.
*
* @param inputStr is a refrence to the string.
* @return encoded string.
*/
inline std::string encode64(const std::string &inputStr) {
using namespace boost::archive::iterators;
@@ -270,13 +184,6 @@ inline std::string encode64(const std::string &inputStr) {
return encoded;
}
/**
* @brief encrypt string in aes256 by given key.
*
* @param plaintext is a refrence to the string.
* @param key is a refrence to the key string.
* @return encrypted BoolStr.
*/
inline BoolStr aes256Encrypt(const std::string &plaintext,
const std::string &key) {
BoolStr result{false, "Encryption failed"};
@@ -291,56 +198,45 @@ inline BoolStr aes256Encrypt(const std::string &plaintext,
plaintext.size() + EVP_CIPHER_block_size(EVP_aes_256_cbc());
std::vector<unsigned char> ciphertext(ciphertext_len);
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
using EvpCipherCtxPtr = std::unique_ptr<EVP_CIPHER_CTX, decltype(&EVP_CIPHER_CTX_free)>;
EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
if (!ctx) {
result.message = "Context initialization failed";
return result;
}
if (EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL,
if (EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_cbc(), NULL,
reinterpret_cast<const unsigned char *>(key.c_str()),
iv) != 1) {
EVP_CIPHER_CTX_free(ctx);
result.message = "Encryption initialization failed";
return result;
}
int len;
if (EVP_EncryptUpdate(
ctx, ciphertext.data(), &len,
ctx.get(), ciphertext.data(), &len,
reinterpret_cast<const unsigned char *>(plaintext.c_str()),
plaintext.size()) != 1) {
EVP_CIPHER_CTX_free(ctx);
result.message = "Encryption update failed";
return result;
}
ciphertext_len = len;
if (EVP_EncryptFinal_ex(ctx, ciphertext.data() + len, &len) != 1) {
EVP_CIPHER_CTX_free(ctx);
if (EVP_EncryptFinal_ex(ctx.get(), ciphertext.data() + len, &len) != 1) {
result.message = "Encryption finalization failed";
return result;
}
ciphertext_len += len;
EVP_CIPHER_CTX_free(ctx);
std::string final_result(reinterpret_cast<char *>(iv), sizeof(iv));
final_result.append(reinterpret_cast<char *>(ciphertext.data()),
ciphertext_len);
result.ok = true;
result.message = final_result;
return result;
}
/**
* @brief decrypt string in aes256 by given key.
*
* @param ciphertext_with_iv is a refrence to the encrypted string.
* @param key is a refrence to the key string.
* @return decrypted BoolStr.
*/
inline BoolStr aes256Decrypt(const std::string &ciphertext_with_iv,
const std::string &key) {
BoolStr result{false, "Decryption failed"};
@@ -348,46 +244,43 @@ inline BoolStr aes256Decrypt(const std::string &ciphertext_with_iv,
unsigned char iv[EVP_MAX_IV_LENGTH];
std::memcpy(iv, ciphertext_with_iv.c_str(),
EVP_CIPHER_iv_length(EVP_aes_256_cbc()));
std::string ciphertext =
ciphertext_with_iv.substr(EVP_CIPHER_iv_length(EVP_aes_256_cbc()));
int max_plaintext_len = ciphertext.size();
std::vector<unsigned char> plaintext(max_plaintext_len);
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
using EvpCipherCtxPtr = std::unique_ptr<EVP_CIPHER_CTX, decltype(&EVP_CIPHER_CTX_free)>;
EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
if (!ctx) {
result.message = "Context initialization failed";
return result;
}
if (EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL,
if (EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_cbc(), NULL,
reinterpret_cast<const unsigned char *>(key.c_str()),
iv) != 1) {
EVP_CIPHER_CTX_free(ctx);
result.message = "Decryption initialization failed";
return result;
}
int len;
if (EVP_DecryptUpdate(
ctx, plaintext.data(), &len,
ctx.get(), plaintext.data(), &len,
reinterpret_cast<const unsigned char *>(ciphertext.c_str()),
ciphertext.size()) != 1) {
EVP_CIPHER_CTX_free(ctx);
result.message = "Decryption update failed";
return result;
}
int plaintext_len = len;
if (EVP_DecryptFinal_ex(ctx, plaintext.data() + len, &len) != 1) {
EVP_CIPHER_CTX_free(ctx);
if (EVP_DecryptFinal_ex(ctx.get(), plaintext.data() + len, &len) != 1) {
result.message = "Decryption finalization failed";
return result;
}
plaintext_len += len;
EVP_CIPHER_CTX_free(ctx);
result.ok = true;
result.message =
std::string(reinterpret_cast<char *>(plaintext.data()), plaintext_len);
@@ -395,11 +288,6 @@ inline BoolStr aes256Decrypt(const std::string &ciphertext_with_iv,
return result;
}
/**
* @brief validates if the config is correct or not.
*
* @return result BoolStr.
*/
inline BoolStr validateConfig(int argc, const char *argv[]) {
BoolStr result{false, "Validation failed"};
@@ -432,10 +320,13 @@ inline BoolStr validateConfig(int argc, const char *argv[]) {
try {
configYaml["general"]["token"].as<std::string>();
configYaml["general"]["fakeUrl"].as<std::string>();
configYaml["general"]["method"].as<std::string>();
configYaml["general"]["protocol"].as<std::string>();
configYaml["general"]["fakeUrls"].as<std::vector<std::string>>();
configYaml["general"]["methods"].as<std::vector<std::string>>();
configYaml["general"]["endPoints"].as<std::vector<std::string>>();
configYaml["general"]["timeout"].as<unsigned short>();
configYaml["general"]["chunkHeader"].as<std::string>();
configYaml["general"]["pullTimeout"].as<unsigned short>();
configYaml["general"]["tunnelEnable"].as<bool>();
} catch (const std::exception &e) {
result.message = std::string("Error in 'general' block: ") + e.what() + "\n";
return result;
@@ -469,7 +360,12 @@ inline BoolStr validateConfig(int argc, const char *argv[]) {
return result;
}
if (configYaml["general"]["protocol"].as<std::string>() != "http" && configYaml["general"]["protocol"].as<std::string>() != "socks5") {
result.message = "First argument must be one of [http|socks5]\n";
return result;
}
result.ok = true;
result.message = "OK";
return result;
}
}
+163 -97
View File
@@ -1,18 +1,9 @@
#include "http.hpp"
/**
* @brief Constructs an HTTP object with configuration, logging, and buffer handling.
*
* Initializes member variables including configuration, logging, stream buffer,
* and UUID, with default values for HTTP type and TLS request parameters.
*
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @param buffer Reference to the Boost Asio stream buffer.
* @param uuid Unique identifier for the HTTP session.
*/
HTTP::HTTP(const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log, boost::asio::streambuf &buffer, boost::uuids::uuid uuid)
const std::shared_ptr<Log> &log,
boost::asio::streambuf &buffer,
boost::uuids::uuid uuid)
: config_(config),
log_(log),
buffer_(buffer),
@@ -20,16 +11,8 @@ HTTP::HTTP(const std::shared_ptr<Config> &config,
httpType_(HTTP::HttpType::https),
parsedTlsRequest_{"", "", TlsTypes::TLSHandshake},
uuid_(uuid) {
chunkHeader_ = "no";
}
/**
* @brief Copy constructor for the HTTP class.
*
* Copies all member variables from another HTTP object.
*
* @param http Reference to another HTTP object to copy.
*/
HTTP::HTTP(const HTTP &http)
: config_(http.config_),
log_(http.log_),
@@ -37,32 +20,23 @@ HTTP::HTTP(const HTTP &http)
parsedHttpRequest_(http.parsedHttpRequest_),
parsedTlsRequest_(http.parsedTlsRequest_),
uuid_(http.uuid_) {
chunkHeader_ = "no";
}
/**
* @brief Destructor for the HTTP class.
*
* Cleans up any allocated resources. Currently, no explicit cleanup is required.
*/
HTTP::~HTTP() {}
/**
* @brief Detects the type of HTTP or HTTPS request based on the input buffer.
*
* Determines whether the request is HTTPS or plain HTTP by inspecting the initial bytes
* of the stream buffer. Parses the request accordingly.
*
* @return True if the request type is successfully detected and parsed, false otherwise.
*/
bool HTTP::detectType() {
std::string requestStr{hexStreambufToStr(buffer_)};
std::string tmpStr;
unsigned short pos = 0;
tmpStr = requestStr.substr(pos, 2);
if (tmpStr == "16" || tmpStr == "14" || tmpStr == "17") {
httpType(HTTP::HttpType::https);
parsedTlsRequest_.body = requestStr;
if (parseTls())
return true;
else
@@ -75,47 +49,38 @@ bool HTTP::detectType() {
}
}
/**
* @brief Parses an HTTP request from the input buffer.
*
* Converts the buffer data into an HTTP request object and sets the HTTP type
* based on the request method.
*
* @return True if parsing is successful, false otherwise.
*/
bool HTTP::parseHttp() {
std::string requestStr(streambufToString(buffer_));
boost::beast::http::request_parser<boost::beast::http::string_body> parser;
parser.eager(true);
boost::beast::error_code error;
parser.put(boost::asio::buffer(requestStr), error);
if (error) {
log_->write(std::string("[" + to_string(uuid_) + "] [HTTP parseHttp] ") + error.what(),
Log::Level::DEBUG);
return false;
} else {
parsedHttpRequest_ = parser.get();
if (parsedHttpRequest_.method() == boost::beast::http::verb::connect)
httpType(HTTP::HttpType::connect);
else
httpType(HTTP::HttpType::http);
setIPPort();
return true;
}
}
/**
* @brief Parses an HTTP response from the input buffer.
*
* Converts the buffer data into an HTTP response object.
*
* @return True if parsing is successful, false otherwise.
*/
bool HTTP::parseHttpResp() {
std::string requestStr(streambufToString(buffer_));
parser_.eager(true);
boost::beast::error_code error;
parser_.put(boost::asio::buffer(requestStr), error);
if (error) {
log_->write(std::string("[" + to_string(uuid_) + "] [HTTP parseHttpResp] ") + error.what(),
Log::Level::DEBUG);
@@ -126,40 +91,42 @@ bool HTTP::parseHttpResp() {
}
}
/**
* @brief Parses a TLS request from the input buffer.
*
* Identifies the TLS request type and extracts relevant fields such as SNI (Server Name Indication).
*
* @return True if parsing is successful, false otherwise.
*/
bool HTTP::parseTls() {
std::string tmpStr;
unsigned short pos = 0;
tmpStr = parsedTlsRequest_.body.substr(pos, 2);
if (tmpStr == "16") {
parsedTlsRequest_.type = TlsTypes::TLSHandshake;
pos = 10;
tmpStr = parsedTlsRequest_.body.substr(pos, 2);
if (tmpStr == "01") {
unsigned short tmpPos(0);
pos = 86;
tmpStr = parsedTlsRequest_.body.substr(pos, 2);
tmpPos = hexToInt(tmpStr);
pos += 2;
tmpStr = parsedTlsRequest_.body.substr(pos, tmpPos);
pos = pos + (tmpPos * 2);
tmpStr = parsedTlsRequest_.body.substr(pos, 4);
tmpPos = hexToInt(tmpStr);
pos += 4;
pos = pos + (tmpPos * 2);
tmpStr = parsedTlsRequest_.body.substr(pos, 2);
tmpPos = hexToInt(tmpStr);
pos += 2;
pos = pos + (tmpPos * 2);
tmpStr = parsedTlsRequest_.body.substr(pos, 4);
tmpPos = hexToInt(tmpStr);
pos += 4;
tmpStr = parsedTlsRequest_.body.substr(pos, 4);
if (hexToInt(tmpStr) == 0) {
pos += 14;
@@ -170,112 +137,211 @@ bool HTTP::parseTls() {
parsedTlsRequest_.sni = hexToASCII(tmpStr);
}
}
setIPPort();
return true;
} else if (tmpStr == "14") {
parsedTlsRequest_.type = TlsTypes::ChangeCipherSpec;
setIPPort();
return true;
} else if (tmpStr == "17") {
parsedTlsRequest_.type = TlsTypes::ApplicationData;
setIPPort();
return true;
} else
return false;
}
const std::string HTTP::genHttpPostReqString(const std::string &body) const {
return std::string(config_->general().method + " " +
config_->general().fakeUrl + " HTTP/" +
std::string HTTP::genHttpPostReqString(const std::string &body) const {
auto fakeUrl = config_->randomFakeUrl();
return std::string(config_->randomMethod() + " " +
fakeUrl + " HTTP/" +
config_->agent().httpVersion + "\r\n") +
"Host: " + config_->general().fakeUrl + "\r\n" +
"Host: " + fakeUrl + "\r\n" +
"User-Agent: " + config_->agent().userAgent + "\r\n" +
"Accept: */*\r\n" + "Connection: keep-alive\r\n" +
"Content-Length: " + std::to_string(body.length()) + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" + "\r\n" + body + "COMP\r\n\r\n";
}
const std::string HTTP::genHttpRestPostReqString() const {
return std::string(config_->general().method + " " +
config_->general().fakeUrl + " HTTP/" +
std::string HTTP::genHttpRestPostReqString() const {
auto fakeUrl = config_->randomFakeUrl();
return std::string(config_->randomMethod() + " " +
fakeUrl + " HTTP/" +
config_->agent().httpVersion + "\r\n") +
"Host: " + config_->general().fakeUrl + "\r\n" +
"Host: " + fakeUrl + "\r\n" +
"User-Agent: " + config_->agent().userAgent + "\r\n" +
"Accept: */*\r\n" + "Connection: keep-alive\r\n" +
"Rest: yes\r\n" + "COMP\r\n\r\n";
}
const std::string HTTP::genHttpOkResString(const std::string &body) const {
std::string HTTP::genHttpOkResString(const std::string &body) const {
return std::string("HTTP/1.1 200 OK\r\n") +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length: " + std::to_string(body.length()) + "\r\n" +
config_->general().chunkHeader + ": " + chunkHeader_ + "\r\n" +
"Connection: keep-alive\r\n" + "Cache-Control: no-cache\r\n" +
"Pragma: no-cache\r\n" + "\r\n" + body + "COMP\r\n\r\n";
}
bool HTTP::parseHostPort(const std::string &input,
std::string &host,
unsigned short &port,
unsigned short defaultPort) {
host.clear();
port = defaultPort;
if (input.empty()) return false;
auto parsePort = [](const std::string &value,
unsigned short &out) -> bool {
try {
int p = std::stoi(value);
if (p < 1 || p > 65535) return false;
out = static_cast<unsigned short>(p);
return true;
} catch (...) {
return false;
}
};
if (input.front() == '[') {
auto close = input.find(']');
if (close == std::string::npos) return false;
host = input.substr(1, close - 1);
if (close + 1 < input.size()) {
if (input[close + 1] != ':') return false;
if (!parsePort(input.substr(close + 2), port)) return false;
}
return !host.empty();
}
auto firstColon = input.find(':');
auto lastColon = input.rfind(':');
if (firstColon != std::string::npos && firstColon != lastColon) {
const std::string maybePort = input.substr(lastColon + 1);
unsigned short parsedPort = defaultPort;
if (parsePort(maybePort, parsedPort)) {
host = input.substr(0, lastColon);
port = parsedPort;
return !host.empty();
}
host = input;
port = defaultPort;
return true;
}
if (lastColon != std::string::npos) {
host = input.substr(0, lastColon);
if (!parsePort(input.substr(lastColon + 1), port)) return false;
} else {
host = input;
port = defaultPort;
}
return !host.empty();
}
void HTTP::setIPPort() {
std::string target{};
std::vector<std::string> splitted;
switch (httpType()) {
case HTTP::HttpType::https:
case HTTP::HttpType::https: {
target = parsedTlsRequest_.sni;
splitted = splitString(target, ":");
if (splitted.size() > 1) {
dstIP_ = splitted[0];
dstPort_ = std::stoi(splitted[1]);
} else {
dstIP_ = target;
if (!parseHostPort(target, dstIp_, dstPort_, 443)) {
dstIp_.clear();
dstPort_ = 443;
}
break;
case HTTP::HttpType::http:
}
case HTTP::HttpType::http: {
target = boost::lexical_cast<std::string>(parsedHttpRequest_.target());
splitted = splitString(
splitString(splitString(target, "http://")[1], "/")[0], ":");
if (!splitted.empty()) {
dstIP_ = splitted[0];
if (splitted.size() > 1)
dstPort_ = std::stoi(splitted[1]);
else
dstPort_ = 80;
std::string hostPort;
if (target.rfind("http://", 0) == 0) {
std::string withoutScheme = target.substr(std::string("http://").size());
auto slashPos = withoutScheme.find('/');
hostPort = (slashPos == std::string::npos)
? withoutScheme
: withoutScheme.substr(0, slashPos);
} else if (target.rfind("https://", 0) == 0) {
std::string withoutScheme = target.substr(std::string("https://").size());
auto slashPos = withoutScheme.find('/');
hostPort = (slashPos == std::string::npos)
? withoutScheme
: withoutScheme.substr(0, slashPos);
} else {
log_->write("[" + to_string(uuid_) + "] [HTTP setIPPort] wrong request", Log::Level::DEBUG);
auto hostIt = parsedHttpRequest_.find("Host");
if (hostIt != parsedHttpRequest_.end()) {
hostPort = boost::lexical_cast<std::string>(hostIt->value());
} else {
log_->write("[" + to_string(uuid_) +
"] [HTTP setIPPort] missing Host header",
Log::Level::DEBUG);
dstIp_.clear();
dstPort_ = 80;
break;
}
}
if (!parseHostPort(hostPort, dstIp_, dstPort_, 80)) {
log_->write("[" + to_string(uuid_) +
"] [HTTP setIPPort] wrong request",
Log::Level::DEBUG);
dstIp_.clear();
dstPort_ = 80;
}
break;
case HTTP::HttpType::connect:
}
case HTTP::HttpType::connect: {
target = boost::lexical_cast<std::string>(parsedHttpRequest_.target());
splitted = splitString(target, ":");
dstIP_ = splitted[0];
dstPort_ = std::stoi(splitted[1]);
if (!parseHostPort(target, dstIp_, dstPort_, 443)) {
dstIp_.clear();
dstPort_ = 443;
}
break;
}
}
}
const std::string HTTP::tlsTypeToString() const {
std::string HTTP::tlsTypeToString() const {
switch (parsedTlsRequest_.type) {
case TlsTypes::TLSHandshake:
return "TLSHandshake";
break;
case TlsTypes::ChangeCipherSpec:
return "ChangeCipherSpec";
break;
case TlsTypes::ApplicationData:
return "ApplicationData";
break;
default:
return "UNKNOWN TLSTYPE";
}
}
const std::string HTTP::toString() const {
std::string HTTP::toString() const {
switch (httpType()) {
case HTTP::HttpType::https:
return std::string("\n") + "TLS Type : " + tlsTypeToString() + "\n" +
"SNI : " + parsedTlsRequest_.sni + "\n" + "Body Size : " +
boost::lexical_cast<std::string>(parsedTlsRequest_.body.size()) +
"\n" + "Body : " + parsedTlsRequest_.body + "\n";
break;
case HTTP::HttpType::http:
return std::string("\n") + "Method : " +
boost::lexical_cast<std::string>(parsedHttpRequest_.method()) +
@@ -291,20 +357,20 @@ const std::string HTTP::toString() const {
parsedHttpRequest_.body().size()) +
"\n" + "Body : " +
boost::lexical_cast<std::string>(parsedHttpRequest_.body()) + "\n";
break;
case HTTP::HttpType::connect:
return std::string("\n") + "Method : " +
boost::lexical_cast<std::string>(parsedHttpRequest_.method()) +
"\n" + "Target : " +
boost::lexical_cast<std::string>(parsedHttpRequest_.target()) +
"\n";
break;
default:
return "UNKNOWN HTTPTYPE";
}
}
const std::string HTTP::restoString() const {
std::string HTTP::restoString() const {
return std::string("\n") +
boost::lexical_cast<std::string>(parsedHttpResponse_.base()) + "\n" +
"Body Size : " +
+20 -146
View File
@@ -10,26 +10,10 @@
#include "general.hpp"
#include "log.hpp"
/**
* @brief The HTTP class provides functionality for handling HTTP and TLS protocol parsing and generation.
*
* This class encapsulates logic to parse and generate HTTP requests and responses, handle TLS requests,
* and manage associated data like IP addresses, ports, and configuration details. It supports both
* HTTP and HTTPS (TLS) connections.
*/
class HTTP {
public:
using pointer = std::shared_ptr<HTTP>;
/**
* @brief Factory method to create a new HTTP object.
*
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object for recording events and errors.
* @param buffer Reference to a stream buffer containing data for processing.
* @param uuid A unique identifier for the session, provided as a Boost UUID.
* @return Shared pointer to the newly created HTTP object.
*/
static pointer create(const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
boost::asio::streambuf &buffer,
@@ -37,202 +21,92 @@ public:
return pointer(new HTTP(config, log, buffer, uuid));
}
/**
* @brief Enumeration representing the type of HTTP connection.
*/
enum class HttpType {
https,
http,
connect
};
/**
* @brief Enumeration representing types of TLS messages.
*/
enum class TlsTypes {
TLSHandshake,
ChangeCipherSpec,
ApplicationData
};
/**
* @brief Structure to store parsed TLS request data.
*/
struct TlsRequest {
std::string sni;
std::string body;
TlsTypes type;
};
/**
* @brief Copy constructor for HTTP objects.
*
* @param request The HTTP object to copy.
*/
explicit HTTP(const HTTP &request);
/**
* @brief Destructor for the HTTP class.
*/
~HTTP();
/**
* @brief Getter for the HTTP connection type.
*
* @return The type of HTTP connection (http, https, or connect).
*/
inline const HTTP::HttpType &httpType() const { return httpType_; }
inline HTTP::HttpType httpType() const { return httpType_; }
/**
* @brief Setter for the HTTP connection type.
*
* @param httpType The new type of HTTP connection.
*/
inline void httpType(const HTTP::HttpType &httpType) { httpType_ = httpType; }
/**
* @brief Detects the type of HTTP connection based on the buffer data.
*
* @return True if detection is successful, false otherwise.
*/
static bool parseHostPort(const std::string &input,
std::string &host,
unsigned short &port,
unsigned short defaultPort);
bool detectType();
/**
* @brief Parses an HTTP request from the buffer.
*
* @return True if parsing is successful, false otherwise.
*/
bool parseHttp();
/**
* @brief Parses an HTTP response from the buffer.
*
* @return True if parsing is successful, false otherwise.
*/
bool parseHttpResp();
/**
* @brief Parses a TLS request from the buffer.
*
* @return True if parsing is successful, false otherwise.
*/
bool parseTls();
/**
* @brief Generates an HTTP POST request string.
*
* @param body The body of the HTTP POST request.
* @return A string representation of the HTTP POST request.
*/
const std::string genHttpPostReqString(const std::string &body) const;
std::string genHttpPostReqString(const std::string &body) const;
/**
* @brief Generates a REST-style HTTP POST request string.
*
* @return A string representation of the REST-style HTTP POST request.
*/
const std::string genHttpRestPostReqString() const;
std::string genHttpRestPostReqString() const;
/**
* @brief Generates an HTTP 200 OK response string.
*
* @param body The body of the HTTP response.
* @return A string representation of the HTTP 200 OK response.
*/
const std::string genHttpOkResString(const std::string &body) const;
std::string genHttpOkResString(const std::string &body) const;
/**
* @brief Retrieves the parsed HTTP request.
*
* @return Reference to the parsed HTTP request.
*/
inline const boost::beast::http::request<boost::beast::http::string_body> &
parsedHttpRequest() & {
return parsedHttpRequest_;
}
/**
* @brief Retrieves the parsed HTTP response.
*
* @return Reference to the parsed HTTP response.
*/
inline const boost::beast::http::response<boost::beast::http::string_body> &
parsedHttpResponse() & {
return parsedHttpResponse_;
}
/**
* @brief Retrieves the parsed TLS request.
*
* @return Reference to the parsed TLS request.
*/
inline const TlsRequest &parsedTlsRequest() & { return parsedTlsRequest_; }
/**
* @brief Converts the TLS message type to a string representation.
*
* @return String representation of the TLS message type.
*/
const std::string tlsTypeToString() const;
std::string tlsTypeToString() const;
/**
* @brief Getter for the destination IP address.
*
* @return Destination IP address as a string.
*/
inline const std::string &dstIP() { return dstIP_; }
inline const std::string &dstIp() const { return dstIp_; }
/**
* @brief Getter for the destination port.
*
* @return Destination port as an unsigned short.
*/
inline const unsigned short &dstPort() { return dstPort_; }
inline unsigned short dstPort() const { return dstPort_; }
/**
* @brief Converts the HTTP object state to a string representation.
*
* @return A string representation of the HTTP object's state.
*/
const std::string toString() const;
std::string toString() const;
/**
* @brief Converts the REST-related HTTP state to a string representation.
*
* @return A string representation of the REST-related state.
*/
const std::string restoString() const;
std::string chunkHeader_;
std::string restoString() const;
private:
/**
* @brief Private constructor for the HTTP class.
*
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @param buffer Reference to a stream buffer containing data for processing.
* @param uuid A unique identifier for the session.
*/
explicit HTTP(const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
boost::asio::streambuf &buffer,
boost::uuids::uuid uuid);
/**
* @brief Sets the destination IP and port based on the parsed data.
*/
void setIPPort();
const std::shared_ptr<Config> &config_;
const std::shared_ptr<Log> &log_;
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
boost::asio::streambuf &buffer_;
boost::beast::http::parser<false, boost::beast::http::string_body> parser_;
boost::beast::http::request<boost::beast::http::string_body> parsedHttpRequest_;
boost::beast::http::response<boost::beast::http::string_body> parsedHttpResponse_;
HttpType httpType_;
std::string dstIP_;
std::string dstIp_;
unsigned short dstPort_;
TlsRequest parsedTlsRequest_;
boost::uuids::uuid uuid_;
};
};
+126
View File
@@ -0,0 +1,126 @@
#pragma once
#include <algorithm>
#include <cctype>
#include <sstream>
#include <string>
namespace http_utils {
inline std::string makeHostPort(const std::string &host, uint16_t port) {
if (host.find(':') != std::string::npos &&
!(host.size() >= 2 && host.front() == '[' && host.back() == ']')) {
return "[" + host + "]:" + std::to_string(port);
}
return host + ":" + std::to_string(port);
}
inline std::string toLowerCopy(std::string value) {
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return value;
}
inline std::string trimCopy(std::string value) {
while (!value.empty() && (value.front() == ' ' || value.front() == '\t')) {
value.erase(value.begin());
}
while (!value.empty() &&
(value.back() == ' ' ||
value.back() == '\t' ||
value.back() == '\r' ||
value.back() == '\n')) {
value.pop_back();
}
return value;
}
inline std::string extractHeaders(const std::string &message) {
const auto pos = message.find("\r\n\r\n");
if (pos == std::string::npos) {
return {};
}
return message.substr(0, pos + 4);
}
inline std::string extractBody(const std::string &message) {
const auto pos = message.find("\r\n\r\n");
if (pos == std::string::npos) {
return {};
}
return message.substr(pos + 4);
}
inline bool parseContentLength(const std::string &headers, std::size_t &value) {
std::istringstream iss(headers);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
const auto lower = toLowerCopy(line);
if (lower.rfind("content-length:", 0) == 0) {
auto raw = line.substr(std::string("Content-Length:").size());
raw.erase(0, raw.find_first_not_of(" \t"));
try {
value = static_cast<std::size_t>(std::stoull(raw));
return true;
} catch (...) {
return false;
}
}
}
return false;
}
inline bool isChunked(const std::string &headers) {
std::istringstream iss(headers);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
const auto lower = toLowerCopy(line);
if (lower.rfind("transfer-encoding:", 0) == 0 &&
lower.find("chunked") != std::string::npos) {
return true;
}
}
return false;
}
inline std::string getRawHeader(const std::string &headers, const std::string &name) {
std::istringstream iss(headers);
std::string line;
const std::string prefix = toLowerCopy(name) + ":";
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
const std::string lower = toLowerCopy(line);
if (lower.rfind(prefix, 0) == 0) {
return trimCopy(line.substr(name.size() + 1));
}
}
return {};
}
}// namespace http_utils
+9 -36
View File
@@ -1,15 +1,8 @@
#include "log.hpp"
/**
* @brief Constructs a `Log` object with the given configuration.
*
* Initializes the logging mode and log level based on the configuration.
* Also verifies if the log file is accessible.
*
* @param config Shared pointer to the configuration object.
*/
Log::Log(const std::shared_ptr<Config> &config)
: config_(config), level_(Level::INFO) {
if (config_->runMode() == RunMode::server)
mode_ = std::string("SERVER");
else if (config_->runMode() == RunMode::agent)
@@ -22,6 +15,7 @@ Log::Log(const std::shared_ptr<Config> &config)
}
const auto &logLevel = config_->log().level;
if (logLevel == "INFO") {
level_ = Level::INFO;
} else if (logLevel == "TRACE") {
@@ -34,40 +28,24 @@ Log::Log(const std::shared_ptr<Config> &config)
}
}
/**
* @brief Copy constructor for the `Log` class.
*
* Copies the configuration and log level from an existing `Log` instance.
*
* @param log Shared pointer to the source `Log` object.
*/
Log::Log(const std::shared_ptr<Log> &log)
: config_(log->config_), level_(log->level_) {}
/**
* @brief Destructor for the `Log` class.
*
* Ensures cleanup of any resources, although none are dynamically allocated here.
*/
Log::~Log() {}
/**
* @brief Writes a log message to the log file and console.
*
* Ensures thread safety using a mutex. Messages are logged only if their severity
* level meets or exceeds the configured logging level, or if they are errors.
*
* @param message The log message to write.
* @param level The severity level of the message.
*/
void Log::write(const std::string &message, Level level) const {
std::lock_guard<std::mutex> lock(logMutex_);
if (level <= level_ || level == Level::ERROR) {
std::ofstream logFile(config_->log().file, std::ios::out | std::ios::app);
if (logFile.is_open()) {
auto now = std::time(nullptr);
auto localTime = *std::localtime(&now);
std::ostringstream timestampStream;
timestampStream << std::put_time(&localTime, "%Y-%m-%d_%H:%M:%S");
std::string timestamp = timestampStream.str();
@@ -77,6 +55,7 @@ void Log::write(const std::string &message, Level level) const {
logFile << line;
std::cout << line;
} else {
std::cerr << "Error opening log file: " << config_->log().file
<< ". Make sure the directory and file exist.\n";
@@ -84,12 +63,6 @@ void Log::write(const std::string &message, Level level) const {
}
}
/**
* @brief Converts a log level enum value to its string representation.
*
* @param level The log level to convert.
* @return The string representation of the log level.
*/
std::string Log::levelToString(Level level) {
switch (level) {
case Level::INFO:
@@ -103,4 +76,4 @@ std::string Log::levelToString(Level level) {
default:
return "UNKNOWN";
}
}
}
+3 -68
View File
@@ -1,6 +1,5 @@
#pragma once
// Standard library includes
#include <ctime>
#include <fstream>
#include <iomanip>
@@ -8,24 +7,11 @@
#include <mutex>
#include <string>
// Project-specific includes
#include "config.hpp"
#include "general.hpp"
/**
* @class Log
* @brief Provides logging functionality with different log levels and thread safety.
*
* The `Log` class is responsible for writing log messages to a file or other output.
* It supports various log levels (INFO, TRACE, ERROR, DEBUG) and ensures thread-safe
* logging using a mutex.
*/
class Log : private Uncopyable {
public:
/**
* @enum Level
* @brief Defines the severity levels of log messages.
*/
enum class Level {
INFO,
TRACE,
@@ -35,79 +21,28 @@ public:
using pointer = std::shared_ptr<Log>;
/**
* @brief Creates a new instance of the Log class.
*
* This static method is the primary way to instantiate a Log object. It ensures
* proper encapsulation and memory management via `std::shared_ptr`.
*
* @param config Shared pointer to the configuration object.
* @return A shared pointer to the newly created Log instance.
*/
static pointer create(const std::shared_ptr<Config> &config) {
return pointer(new Log(config));
}
/**
* @brief Constructs a Log object by copying another Log instance.
*
* @param log Shared pointer to the Log object to copy.
*/
explicit Log(const std::shared_ptr<Log> &log);
/**
* @brief Destructor for the Log class.
*
* Ensures proper cleanup of resources, such as closing log files, if necessary.
*/
~Log();
/**
* @brief Gets the configuration associated with this Log instance.
*
* @return A shared pointer to the configuration object.
*/
const std::shared_ptr<Config> &config() const { return config_; }
std::shared_ptr<Config> config() const { return config_; }
/**
* @brief Gets the current logging level.
*
* @return The current logging level as an enum value.
*/
Level level() const { return level_; }
/**
* @brief Writes a log message with a specified log level.
*
* This function is thread-safe and ensures that multiple threads can log messages
* without interfering with each other.
*
* @param message The log message to write.
* @param level The severity level of the message.
*/
void write(const std::string &message, Level level) const;
private:
/**
* @brief Constructs a Log object with a specified configuration.
*
* This constructor is private to enforce the use of the `create` factory method.
*
* @param config Shared pointer to the configuration object.
*/
explicit Log(const std::shared_ptr<Config> &config);
/**
* @brief Converts a log level enum value to a string representation.
*
* @param level The log level to convert.
* @return A string representation of the log level.
*/
static std::string levelToString(Level level);
const std::shared_ptr<Config> &config_;
std::shared_ptr<Config> config_;
Level level_;
std::string mode_;
mutable std::mutex logMutex_;
};
};
+6 -34
View File
@@ -1,13 +1,5 @@
#include "runner.hpp"
/**
* @brief Constructs a `Runner` object with the given configuration and log instance.
*
* Initializes the `io_context_`, work guard, and strand. Sets the `running_` flag to true.
*
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging instance.
*/
Runner::Runner(const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log)
: config_(config),
@@ -17,14 +9,10 @@ Runner::Runner(const std::shared_ptr<Config> &config,
running_(true),
strand_(boost::asio::make_strand(io_context_)) {}
/**
* @brief Destructor for the `Runner` class.
*
* Stops the `io_context_`, ensures all threads in the thread pool are joined, and safely cleans up resources.
*/
Runner::~Runner() {
running_.store(false);
io_context_.stop();
for (auto &thread: threadPool_) {
if (thread.joinable()) {
thread.join();
@@ -32,26 +20,23 @@ Runner::~Runner() {
}
}
/**
* @brief Starts the Runner's main execution.
*
* Initializes the server and spawns multiple worker threads to handle tasks asynchronously.
* Joins all threads to ensure proper shutdown.
*/
void Runner::run() {
try {
log_->write("Config initialized in " + config_->modeToString() + " mode", Log::Level::INFO);
log_->write(config_->toString(), Log::Level::INFO);
auto tcpServer = TCPServer::create(io_context_, config_, log_);
for (auto i = 0; i < config_->threads(); ++i) {
threadPool_.emplace_back([this] { workerThread(); });
}
for (auto &thread: threadPool_) {
if (thread.joinable()) {
thread.join();
}
}
} catch (const std::exception &error) {
log_->write(std::string("[Runner run] ") + error.what(), Log::Level::ERROR);
} catch (...) {
@@ -59,33 +44,20 @@ void Runner::run() {
}
}
/**
* @brief Worker thread function to process tasks from the `io_context_`.
*
* Each thread calls `io_context_.run()` to handle asynchronous operations. If an exception occurs,
* it logs the error and continues processing.
*/
void Runner::workerThread() {
while (running_.load()) {
try {
io_context_.run();
break;
} catch (const std::exception &e) {
log_->write(std::string("[WorkerThread] Exception: ") + e.what(), Log::Level::ERROR);
} catch (...) {
log_->write("[WorkerThread] Unknown error occurred", Log::Level::ERROR);
}
}
}
/**
* @brief Stops the Runner.
*
* Sets the `running_` flag to false and stops the `io_context_` to terminate the processing loop.
*/
void Runner::stop() {
running_.store(false);
io_context_.stop();
}
}
+10 -51
View File
@@ -7,81 +7,40 @@
#include <thread>
#include <vector>
#if defined(__ANDROID__)
using runnerThread = std::thread;
#else
using runnerThread = std::jthread;
#endif
#include "config.hpp"
#include "log.hpp"
#include "tcpserver.hpp"
/**
* @class Runner
* @brief Manages the execution of an asynchronous Boost.Asio-based server.
*
* The `Runner` class sets up a multi-threaded environment for handling
* asynchronous tasks using Boost.Asio. It provides mechanisms to run, manage,
* and stop the server efficiently.
*/
class Runner : private Uncopyable {
public:
/**
* @brief Constructs the `Runner` object with the specified configuration and logging instance.
*
* Initializes the Boost.Asio context and sets up the necessary guards and threading environment.
*
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging instance.
*/
explicit Runner(const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log);
/**
* @brief Destructor for the `Runner` class.
*
* Ensures that the server and its threads are gracefully stopped.
*/
~Runner();
/**
* @brief Starts the asynchronous server and its worker threads.
*
* This method runs the Boost.Asio `io_context` to process asynchronous tasks.
*/
void run();
private:
/**
* @brief Executes tasks in a worker thread.
*
* Each worker thread runs the `io_context`, allowing it to process asynchronous operations.
*/
void workerThread();
/**
* @brief Stops the server and shuts down all threads gracefully.
*
* Signals the termination of the server and cleans up resources.
*/
void stop();
const std::shared_ptr<Config> &config_;
const std::shared_ptr<Log> &log_;
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
boost::asio::io_context io_context_;
/**
* @brief Work guard to keep the `io_context` running.
*
* Ensures that the `io_context` does not exit when there are no tasks to process.
*/
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work_guard_;
std::atomic<bool> running_;
std::vector<std::jthread> threadPool_;
std::vector<runnerThread> threadPool_;
/**
* @brief Strand to ensure serialized execution of tasks within the `io_context`.
*
* Provides thread safety for handlers that must not run concurrently.
*/
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
};
};
+321 -82
View File
@@ -1,114 +1,365 @@
#include "serverhandler.hpp"
/**
* @brief Constructs a `ServerHandler` object.
*
* Initializes the HTTP request handler, client connection, and assigns references
* to configuration, logging, and buffers.
*/
#include <sstream>
#include <utility>
#include <vector>
#include "http_utils.hpp"
std::mutex ServerHandler::sessionsMutex_;
std::unordered_map<std::string, TCPClient::pointer> ServerHandler::sessions_;
std::string ServerHandler::HttpUtils::lowerCopy(std::string s) {
return http_utils::toLowerCopy(std::move(s));
}
std::string ServerHandler::HttpUtils::trimCopy(std::string s) {
return http_utils::trimCopy(std::move(s));
}
std::string ServerHandler::HttpUtils::getRawHeader(const std::string &headers,
const std::string &name) {
return http_utils::getRawHeader(headers, name);
}
std::string ServerHandler::HttpUtils::extractHttpBody(const std::string &msg) {
return http_utils::extractBody(msg);
}
ServerHandler::ServerHandler(boost::asio::streambuf &readBuffer,
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid)
: config_(config),
log_(log),
client_(client),
client_(std::move(client)),
readBuffer_(readBuffer),
writeBuffer_(writeBuffer),
request_(HTTP::create(config, log, readBuffer, uuid)),
clientConnStr_(clientConnStr),
clientConnStr_(std::move(clientConnStr)),
uuid_(uuid) {
end_ = false;
connect_ = false;
}
/**
* @brief Destructor for `ServerHandler`.
*
* Ensures cleanup of resources, though currently the destructor does not perform specific actions.
*/
ServerHandler::~ServerHandler() {}
/**
* @brief Handles the incoming request and processes it based on its type.
*
* Processes HTTP or HTTPS requests, decrypts payloads, performs appropriate actions
* (e.g., connect or forward requests), and generates responses.
*/
void ServerHandler::makePlainHttpResponse(const std::string &body,
const std::string &status,
const std::string &connection) {
std::ostringstream outer;
outer << "HTTP/1.1 " << status << "\r\n"
<< "Content-Type: application/text\r\n"
<< "Content-Length: " << body.size() << "\r\n"
<< "Connection: " << connection << "\r\n"
<< "\r\n"
<< body;
copyStringToStreambuf(outer.str(), writeBuffer_);
end_ = false;
connect_ = false;
}
void ServerHandler::makeEncryptedHttpResponse(const std::string &plainBody,
const std::string &status,
const std::string &connection) {
BoolStr encryption = aes256Encrypt(plainBody, config_->general().token);
if (!encryption.ok) {
log_->write("[" + to_string(uuid_) + "] [ServerHandler] [Encryption Failed] " + encryption.message,
Log::Level::DEBUG);
makePlainHttpResponse("", "500 Internal Server Error", "close");
return;
}
makePlainHttpResponse(encryption.message, status, connection);
}
void ServerHandler::handle() {
std::lock_guard lock(mutex_);
std::lock_guard<std::mutex> lock(mutex_);
if (!request_->detectType()) {
log_->write("[" + to_string(uuid_) +
"] [ServerHandler handle] [NOT HTTP Request From Agent] "
"[Request] : " +
streambufToString(readBuffer_),
Log::Level::DEBUG);
log_->write(
"[" + to_string(uuid_) +
"] [ServerHandler handle] [NOT HTTP Request From Agent] [Request] : " +
streambufToString(readBuffer_),
Log::Level::DEBUG);
client_->socket().close();
return;
}
const auto &outerReq = request_->parsedHttpRequest();
const std::string outerRaw = streambufToString(readBuffer_);
const auto outerHeaderEnd = outerRaw.find("\r\n\r\n");
const std::string outerHeaders =
outerHeaderEnd == std::string::npos
? ""
: outerRaw.substr(0, outerHeaderEnd + 2);
const std::string session =
HttpUtils::getRawHeader(outerHeaders, "X-Nipo-Session");
const std::string action =
HttpUtils::getRawHeader(outerHeaders, "X-Nipo-Action");
std::string requestBody = std::string(outerReq.body());
if (requestBody.empty()) {
requestBody = HttpUtils::extractHttpBody(outerRaw);
}
BoolStr decryption{false, std::string("FAILED")};
decryption = aes256Decrypt(
decode64(std::string(request_->parsedHttpRequest().body())),
config_->general().token);
try {
decryption = aes256Decrypt(
decode64(requestBody),
config_->general().token);
} catch (const std::exception &e) {
log_->write(
"[" + to_string(uuid_) +
"] [ServerHandler handle] [Base64 Decode Failed] " + e.what(),
Log::Level::DEBUG);
makePlainHttpResponse("", "400 Bad Request", "close");
return;
}
if (!decryption.ok) {
log_->write("[" + to_string(uuid_) +
"] [ServerHandler handle] [Decryption Failed] : [ " +
decryption.message + "] ",
Log::Level::DEBUG);
client_->socket().close();
log_->write(
"[" + to_string(uuid_) +
"] [ServerHandler handle] [Decryption Failed] : [ " +
decryption.message + "] ",
Log::Level::DEBUG);
makePlainHttpResponse("", "400 Bad Request", "close");
return;
}
auto tempHexArr = strToHexArr(decryption.message);
std::string tempHexArrStr(tempHexArr.begin(), tempHexArr.end());
copyStringToStreambuf(tempHexArrStr, readBuffer_);
log_->write(
"[" + to_string(uuid_) + "] [ServerHandler handle] [Decryption Done]",
Log::Level::DEBUG);
if (!request_->detectType()) {
log_->write("[" + to_string(uuid_) +
"] [ServerHandler handle] [NOT HTTP Request] [Request] : " +
streambufToString(readBuffer_),
Log::Level::DEBUG);
client_->socket().close();
if (action == "send") {
TCPClient::pointer targetClient;
{
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
auto it = sessions_.find(session);
if (it != sessions_.end()) {
targetClient = it->second;
}
}
if (!targetClient || !targetClient->isOpen()) {
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
return;
}
boost::asio::streambuf tunnelBuf;
copyStringToStreambuf(hexToASCII(decryption.message), tunnelBuf);
targetClient->doWrite(tunnelBuf);
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
return;
}
switch (request_->httpType()) {
if (action == "recv") {
TCPClient::pointer targetClient;
{
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
auto it = sessions_.find(session);
if (it != sessions_.end()) {
targetClient = it->second;
}
}
if (!targetClient || !targetClient->isOpen()) {
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
return;
}
boost::system::error_code ec;
std::size_t available = targetClient->socket().available(ec);
if (ec || available == 0) {
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
return;
}
std::vector<char> data(std::min<std::size_t>(available, 65536));
std::size_t n = targetClient->socket().read_some(
boost::asio::buffer(data),
ec);
if (ec || n == 0) {
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
return;
}
makeEncryptedHttpResponse(
std::string(data.data(), n),
"200 OK",
(config_->general().connectionReuse ? "keep-alive" : "close"));
return;
}
if (action == "close") {
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
auto it = sessions_.find(session);
if (it != sessions_.end()) {
it->second->socketShutdown();
sessions_.erase(it);
}
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
return;
}
const std::string innerRequest = hexToASCII(decryption.message);
const std::size_t headerEnd = innerRequest.find("\r\n\r\n");
if (headerEnd == std::string::npos) {
log_->write(
"[" + to_string(uuid_) +
"] [ServerHandler handle] [INNER REQUEST MISSING HEADER END]",
Log::Level::DEBUG);
makeEncryptedHttpResponse("", "400 Bad Request", "close");
return;
}
const std::string innerHeaders = innerRequest.substr(0, headerEnd + 4);
const std::string pendingTunnelData = innerRequest.substr(headerEnd + 4);
copyStringToStreambuf(innerHeaders, readBuffer_);
HTTP::pointer inner = HTTP::create(config_, log_, readBuffer_, uuid_);
if (!inner->detectType()) {
log_->write(
"[" + to_string(uuid_) +
"] [ServerHandler handle] [NOT INNER HTTP Request] [Request] : " +
streambufToString(readBuffer_),
Log::Level::DEBUG);
makeEncryptedHttpResponse("", "400 Bad Request", "close");
return;
}
switch (inner->httpType()) {
case HTTP::HttpType::connect: {
connect_ = true;
boost::asio::streambuf tempBuff;
std::iostream os(&tempBuff);
if (client_->doConnect(request_->dstIP(), request_->dstPort())) {
log_->write("[" + to_string(uuid_) + "] [CONNECT] [SRC " +
clientConnStr_ + "] [DST " + request_->dstIP() + ":" +
std::to_string(request_->dstPort()) + "]",
Log::Level::INFO);
os << "HTTP/1.1 200 Connection established COMP\r\n\r\n";
} else {
log_->write(std::string("[") + to_string(uuid_) +
if (config_->general().tunnelEnable) {
if (!client_->doConnect(inner->dstIp(), inner->dstPort())) {
log_->write(
"[" + to_string(uuid_) +
"] [CONNECT] [ERROR] [Resolving Host] [SRC " +
clientConnStr_ + "] [DST " + request_->dstIP() + ":" +
std::to_string(request_->dstPort()) + "]",
clientConnStr_ + "] [DST " +
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
Log::Level::INFO);
os << "HTTP/1.1 500 Connection failed COMP\r\n\r\n";
makeEncryptedHttpResponse(
"HTTP/1.1 502 Bad Gateway\r\n\r\n",
"502 Bad Gateway",
"close");
connect_ = false;
end_ = false;
return;
}
log_->write(
"[" + to_string(uuid_) +
"] [CONNECT] [TUNNEL] [SRC " +
clientConnStr_ + "] [DST " +
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
Log::Level::INFO);
makeEncryptedHttpResponse(
"HTTP/1.1 200 Connection Established\r\n\r\n",
"200 OK",
"keep-alive");
connect_ = true;
end_ = false;
return;
}
moveStreambuf(tempBuff, writeBuffer_);
TCPClient::pointer targetClient = TCPClient::create(
static_cast<boost::asio::io_context &>(
client_->socket().get_executor().context()),
config_,
log_);
targetClient->uuid_ = uuid_;
if (!targetClient->doConnect(inner->dstIp(), inner->dstPort())) {
log_->write(
"[" + to_string(uuid_) +
"] [CONNECT] [ERROR] [Resolving Host] [SRC " +
clientConnStr_ + "] [DST " +
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
Log::Level::INFO);
makeEncryptedHttpResponse(
"HTTP/1.1 502 Bad Gateway\r\n\r\n",
"502 Bad Gateway",
"close");
connect_ = false;
end_ = false;
return;
}
log_->write(
"[" + to_string(uuid_) +
"] [CONNECT] [SRC " +
clientConnStr_ + "] [DST " +
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
Log::Level::INFO);
if (!pendingTunnelData.empty()) {
boost::asio::streambuf pendingBuf;
copyStringToStreambuf(pendingTunnelData, pendingBuf);
targetClient->doWrite(pendingBuf);
}
{
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
sessions_[session.empty() ? to_string(uuid_) : session] = targetClient;
}
makeEncryptedHttpResponse(
"HTTP/1.1 200 Connection Established\r\n\r\n",
"200 OK",
"keep-alive");
connect_ = false;
end_ = false;
return;
}
case HTTP::HttpType::http:
case HTTP::HttpType::https: {
copyStringToStreambuf(innerRequest, readBuffer_);
if (!client_->socket().is_open()) {
if (!client_->doConnect(request_->dstIP(), request_->dstPort())) {
if (!client_->doConnect(inner->dstIp(), inner->dstPort())) {
client_->socket().close();
makeEncryptedHttpResponse("", "502 Bad Gateway", "close");
return;
}
}
@@ -118,30 +369,18 @@ void ServerHandler::handle() {
if (client_->readBuffer().size() == 0) {
client_->socket().close();
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
return;
}
BoolStr encryption{false, std::string("FAILED")};
encryption =
aes256Encrypt(streambufToString(client_->readBuffer()),
config_->general().token);
makeEncryptedHttpResponse(
streambufToString(client_->readBuffer()),
"200 OK",
(config_->general().connectionReuse ? "keep-alive" : "close"));
if (!encryption.ok) {
log_->write("[" + to_string(uuid_) +
"] [ServerHandler handle] [Encryption Failed] : [ " +
encryption.message + "] ",
Log::Level::DEBUG);
client_->socket().close();
return;
}
std::string newRes(
request_->genHttpOkResString(encode64(encryption.message)));
copyStringToStreambuf(newRes, writeBuffer_);
connect_ = true;
connect_ = false;
end_ = false;
return;
}
}
}
}
+33 -70
View File
@@ -1,6 +1,9 @@
#pragma once
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include "config.hpp"
#include "general.hpp"
@@ -8,103 +11,63 @@
#include "log.hpp"
#include "tcpclient.hpp"
/**
* @class ServerHandler
* @brief Handles server-side processing for a specific connection.
*
* The `ServerHandler` manages incoming requests, outgoing responses, and the connection state.
* It is tightly coupled with the configuration, logging, and client connection objects.
*/
class ServerHandler : private Uncopyable {
public:
using pointer = std::shared_ptr<ServerHandler>;
/**
* @brief Factory method to create a new `ServerHandler` instance.
*
* @param readBuffer Reference to the read buffer for incoming data.
* @param writeBuffer Reference to the write buffer for outgoing data.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging instance.
* @param client Pointer to the TCP client associated with the connection.
* @param clientConnStr String representing the client connection (e.g., IP and port).
* @param uuid UUID associated with the connection.
* @return Shared pointer to the newly created `ServerHandler` instance.
*/
static pointer create(boost::asio::streambuf &readBuffer,
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid) {
return pointer(new ServerHandler(readBuffer, writeBuffer, config, log,
client, clientConnStr, uuid));
return pointer(new ServerHandler(readBuffer, writeBuffer, config, log, client, clientConnStr, uuid));
}
/**
* @brief Destructor for the `ServerHandler` class.
*/
~ServerHandler();
/**
* @brief Handles incoming requests and manages responses.
*
* This function is responsible for processing the request and initiating
* the necessary actions based on the server's business logic.
*/
void handle();
/**
* @brief Returns a reference to the HTTP request object.
*
* Provides access to the request being handled by the server.
*
* @return Reference to the HTTP request object.
*/
inline const HTTP::pointer &request() & { return request_; }
/**
* @brief Returns an rvalue reference to the HTTP request object.
*
* Allows moving the HTTP request object when necessary.
*
* @return Rvalue reference to the HTTP request object.
*/
inline const HTTP::pointer &&request() && { return std::move(request_); }
inline const HTTP::pointer &request() const { return request_; }
bool end_;
bool connect_;
private:
/**
* @brief Constructor for `ServerHandler`.
*
* Initializes the handler with the given buffers, configuration, log, client,
* connection string, and UUID.
*
* @param readBuffer Reference to the read buffer for incoming data.
* @param writeBuffer Reference to the write buffer for outgoing data.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging instance.
* @param client Pointer to the TCP client associated with the connection.
* @param clientConnStr String representing the client connection (e.g., IP and port).
* @param uuid UUID associated with the connection.
*/
struct HttpUtils {
static std::string lowerCopy(std::string s);
static std::string trimCopy(std::string s);
static std::string getRawHeader(const std::string &headers, const std::string &name);
static std::string extractHttpBody(const std::string &msg);
};
explicit ServerHandler(boost::asio::streambuf &readBuffer,
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid);
const std::shared_ptr<Config> &config_;
const std::shared_ptr<Log> &log_;
const TCPClient::pointer &client_;
void makeEncryptedHttpResponse(const std::string &plainBody,
const std::string &status = "200 OK",
const std::string &connection = "close");
void makePlainHttpResponse(const std::string &body,
const std::string &status = "200 OK",
const std::string &connection = "close");
static std::mutex sessionsMutex_;
static std::unordered_map<std::string, TCPClient::pointer> sessions_;
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
TCPClient::pointer client_;
boost::asio::streambuf &readBuffer_;
boost::asio::streambuf &writeBuffer_;
HTTP::pointer request_;
const std::string &clientConnStr_;
std::string clientConnStr_;
boost::uuids::uuid uuid_;
std::mutex mutex_;
};
};
+436 -128
View File
@@ -2,6 +2,16 @@
#include <openssl/ssl.h>
#include <algorithm>
#include <cctype>
#include <chrono>
#include <memory>
#include <sstream>
#include <utility>
#include <vector>
#include "http_utils.hpp"
TCPClient::TCPClient(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log)
@@ -29,7 +39,7 @@ bool TCPClient::isOpen() const {
}
bool TCPClient::enableTlsClient() {
std::lock_guard lock(mutex_);
try {
if (tlsEnabled_) return true;
@@ -42,10 +52,11 @@ bool TCPClient::enableTlsClient() {
SSL_CTX_set_min_proto_version(sslContext_.native_handle(), TLS1_2_VERSION);
if (config_->agent().tlsVerifyPeer) {
if (config_->general().tlsVerifyPeer) {
sslContext_.set_verify_mode(boost::asio::ssl::verify_peer);
if (!config_->agent().tlsCaFile.empty()) {
sslContext_.load_verify_file(config_->agent().tlsCaFile);
if (!config_->general().tlsCaFile.empty()) {
sslContext_.load_verify_file(config_->general().tlsCaFile);
}
} else {
sslContext_.set_verify_mode(boost::asio::ssl::verify_none);
@@ -75,6 +86,7 @@ bool TCPClient::enableTlsClient() {
sslSocket_ = std::make_unique<ssl_stream>(io_context_, sslContext_);
tlsEnabled_ = true;
return true;
} catch (std::exception &error) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient enableTlsClient] " + error.what(),
@@ -83,16 +95,27 @@ bool TCPClient::enableTlsClient() {
}
}
bool TCPClient::doConnect(const std::string &dstIP, const unsigned short &dstPort) {
std::lock_guard lock(mutex_);
bool TCPClient::doConnect(const std::string &dstIp, unsigned short dstPort) {
try {
log_->write("[" + to_string(uuid_) + "] [TCPClient doConnect] [DST " + dstIP +
":" + std::to_string(dstPort) + "]",
if (tlsEnabled_ && sslSocket_ && sslSocket_->lowest_layer().is_open()) {
return true;
}
if (!tlsEnabled_ && socket_.is_open()) {
return true;
}
log_->write("[" + to_string(uuid_) +
"] [TCPClient doConnect] [DST " + dstIp + ":" +
std::to_string(dstPort) + "]",
Log::Level::DEBUG);
boost::system::error_code error_code;
auto endpoint =
resolver_.resolve(dstIP.c_str(), std::to_string(dstPort).c_str(), error_code);
auto endpoints = resolver_.resolve(
dstIp,
std::to_string(dstPort),
error_code);
if (error_code) {
log_->write("[" + to_string(uuid_) +
@@ -102,94 +125,184 @@ bool TCPClient::doConnect(const std::string &dstIP, const unsigned short &dstPor
return false;
}
if (tlsEnabled_ && sslSocket_) {
boost::asio::connect(sslSocket_->lowest_layer(), endpoint, error_code);
resetTimeout();
if (tlsEnabled_) {
sslSocket_ = std::make_unique<ssl_stream>(io_context_, sslContext_);
closed_ = false;
boost::asio::connect(
sslSocket_->lowest_layer(),
endpoints,
error_code);
} else {
boost::asio::connect(socket_, endpoint, error_code);
socket_ = tcp::socket(io_context_);
closed_ = false;
boost::asio::connect(
socket_,
endpoints,
error_code);
}
cancelTimeout();
if (error_code) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doConnect] connect error: " +
error_code.message(),
Log::Level::ERROR);
socketShutdown();
return false;
}
log_->write("[" + to_string(uuid_) +
"] [TCPClient doConnect] connected",
Log::Level::DEBUG);
return true;
} catch (std::exception &error) {
log_->write("[" + to_string(uuid_) + "] [TCPClient doConnect] " +
error.what(),
} catch (const std::exception &ex) {
cancelTimeout();
log_->write("[" + to_string(uuid_) +
"] [TCPClient doConnect] exception: " + ex.what(),
Log::Level::ERROR);
socketShutdown();
return false;
}
}
bool TCPClient::doHandshakeClient() {
std::lock_guard lock(mutex_);
try {
if (!tlsEnabled_ || !sslSocket_) return true;
std::string sniHost = config_->general().fakeUrl;
// If fakeUrl is a full URL (e.g. https://example.com/path),
// extract only hostname
if (!sniHost.empty()) {
// remove scheme if present
auto pos = sniHost.find("://");
if (pos != std::string::npos) {
sniHost = sniHost.substr(pos + 3);
}
// remove path if present
pos = sniHost.find('/');
if (pos != std::string::npos) {
sniHost = sniHost.substr(0, pos);
}
// remove port if present
pos = sniHost.find(':');
if (pos != std::string::npos) {
sniHost = sniHost.substr(0, pos);
}
if (!sniHost.empty()) {
if (!SSL_set_tlsext_host_name(sslSocket_->native_handle(),
sniHost.c_str())) {
log_->write("[" + to_string(uuid_) +
"] [TLS] Failed to set SNI: " + sniHost,
Log::Level::ERROR);
return false;
}
log_->write("[" + to_string(uuid_) +
"] [TLS] Using SNI: " + sniHost,
Log::Level::DEBUG);
}
if (!tlsEnabled_ || !sslSocket_) {
return true;
}
if (!sslSocket_->lowest_layer().is_open()) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doHandshakeClient] socket is not open",
Log::Level::ERROR);
socketShutdown();
return false;
}
std::string sniHost = config_->randomFakeUrl();
auto pos = sniHost.find("://");
if (pos != std::string::npos) {
sniHost = sniHost.substr(pos + 3);
}
pos = sniHost.find('/');
if (pos != std::string::npos) {
sniHost = sniHost.substr(0, pos);
}
pos = sniHost.find(':');
if (pos != std::string::npos) {
sniHost = sniHost.substr(0, pos);
}
if (!sniHost.empty()) {
if (!SSL_set_tlsext_host_name(
sslSocket_->native_handle(),
sniHost.c_str())) {
log_->write("[" + to_string(uuid_) +
"] [TLS] Failed to set SNI: " + sniHost,
Log::Level::ERROR);
socketShutdown();
return false;
}
static const unsigned char alpn[] = {
0x08, 'h', 't', 't', 'p', '/', '1', '.', '1'};
if (SSL_set_alpn_protos(
sslSocket_->native_handle(),
alpn,
sizeof(alpn)) != 0) {
log_->write("[" + to_string(uuid_) +
"] [TLS] Failed to set ALPN http/1.1",
Log::Level::ERROR);
socketShutdown();
return false;
}
log_->write("[" + to_string(uuid_) +
"] [TLS] Starting client handshake with SNI: " +
sniHost,
Log::Level::DEBUG);
}
boost::system::error_code error;
resetTimeout();
sslSocket_->handshake(boost::asio::ssl::stream_base::client);
sslSocket_->handshake(
boost::asio::ssl::stream_base::client,
error);
cancelTimeout();
return true;
} catch (std::exception &error) {
cancelTimeout();
if (error) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doHandshakeClient] handshake error: " +
error.message(),
Log::Level::ERROR);
socketShutdown();
return false;
}
log_->write("[" + to_string(uuid_) +
"] [TCPClient doHandshakeClient] " + error.what(),
"] [TLS] Client handshake completed",
Log::Level::DEBUG);
const unsigned char *selected = nullptr;
unsigned int selectedLen = 0;
SSL_get0_alpn_selected(
sslSocket_->native_handle(),
&selected,
&selectedLen);
if (selected != nullptr && selectedLen > 0) {
std::string negotiated(
reinterpret_cast<const char *>(selected),
selectedLen);
log_->write("[" + to_string(uuid_) +
"] [TLS] Negotiated ALPN: " + negotiated,
Log::Level::DEBUG);
} else {
log_->write("[" + to_string(uuid_) +
"] [TLS] No ALPN negotiated",
Log::Level::DEBUG);
}
return true;
} catch (const std::exception &ex) {
cancelTimeout();
log_->write("[" + to_string(uuid_) +
"] [TCPClient doHandshakeClient] exception: " +
ex.what(),
Log::Level::ERROR);
socketShutdown();
return false;
}
}
void TCPClient::writeBuffer(boost::asio::streambuf &buffer) {
std::lock_guard lock(mutex_);
moveStreambuf(buffer, writeBuffer_);
}
void TCPClient::doWrite(boost::asio::streambuf &buffer) {
std::lock_guard lock(mutex_);
bool TCPClient::doWrite(boost::asio::streambuf &buffer) {
try {
writeBuffer_.consume(writeBuffer_.size());
moveStreambuf(buffer, writeBuffer_);
if (!isOpen()) {
@@ -197,31 +310,33 @@ void TCPClient::doWrite(boost::asio::streambuf &buffer) {
"] [TCPClient doWrite] socket is not open",
Log::Level::DEBUG);
socketShutdown();
return;
return false;
}
if (writeBuffer_.size() == 0) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doWrite] empty write buffer",
Log::Level::DEBUG);
socketShutdown();
return;
return false;
}
boost::system::error_code error;
resetTimeout();
if (tlsEnabled_ && sslSocket_) {
log_->write("[" + to_string(uuid_) + "] [TCPClient doWrite] [DST " +
sslSocket_->lowest_layer().remote_endpoint().address().to_string() +
":" +
std::to_string(sslSocket_->lowest_layer().remote_endpoint().port()) +
"] [Bytes " + std::to_string(writeBuffer_.size()) + "] ",
log_->write("[" + to_string(uuid_) +
"] [TCPClient doWrite] [SSL] [Bytes " +
std::to_string(writeBuffer_.size()) + "]",
Log::Level::DEBUG);
boost::asio::write(*sslSocket_, writeBuffer_, error);
} else {
log_->write("[" + to_string(uuid_) + "] [TCPClient doWrite] [DST " +
socket_.remote_endpoint().address().to_string() + ":" +
std::to_string(socket_.remote_endpoint().port()) +
"] [Bytes " + std::to_string(writeBuffer_.size()) + "] ",
log_->write("[" + to_string(uuid_) +
"] [TCPClient doWrite] [TCP] [Bytes " +
std::to_string(writeBuffer_.size()) + "]",
Log::Level::DEBUG);
boost::asio::write(socket_, writeBuffer_, error);
}
@@ -232,72 +347,106 @@ void TCPClient::doWrite(boost::asio::streambuf &buffer) {
"] [TCPClient doWrite] [error] " + error.message(),
Log::Level::DEBUG);
socketShutdown();
return;
return false;
}
} catch (std::exception &error) {
log_->write("[" + to_string(uuid_) + "] [TCPClient doWrite] [catch] " +
error.what(),
return true;
} catch (const std::exception &ex) {
cancelTimeout();
log_->write("[" + to_string(uuid_) +
"] [TCPClient doWrite] [catch] " + ex.what(),
Log::Level::DEBUG);
socketShutdown();
return false;
}
}
void TCPClient::doReadAgent() {
bool TCPClient::doReadAgent() {
boost::system::error_code error;
std::lock_guard lock(mutex_);
readBuffer_.consume(readBuffer_.size());
try {
if (!isOpen()) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] Socket is not OPEN",
Log::Level::DEBUG);
return;
{
std::lock_guard<std::mutex> lock(mutex_);
readBuffer_.consume(readBuffer_.size());
buffer_.consume(buffer_.size());
if (!isOpen()) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] Socket is not OPEN",
Log::Level::DEBUG);
return false;
}
}
resetTimeout();
if (tlsEnabled_ && sslSocket_) {
boost::asio::read_until(*sslSocket_, readBuffer_, "COMP\r\n\r\n", error);
bool ok = false;
if (tlsEnabled_) {
if (!sslSocket_) {
cancelTimeout();
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] SSL socket is null",
Log::Level::DEBUG);
socketShutdown();
return false;
}
ok = HttpUtils::readHttpMessage(*sslSocket_, readBuffer_, error);
} else {
boost::asio::read_until(socket_, readBuffer_, "COMP\r\n\r\n", error);
ok = HttpUtils::readHttpMessage(socket_, readBuffer_, error);
}
cancelTimeout();
if (error == boost::asio::error::eof) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] [EOF] Connection closed by peer.",
Log::Level::TRACE);
if (!ok) {
if (error == boost::asio::error::operation_aborted) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] [aborted]",
Log::Level::DEBUG);
} else if (error == boost::asio::error::eof) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] [EOF] Connection closed by peer.",
Log::Level::TRACE);
} else {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] [error] " + error.message(),
Log::Level::ERROR);
}
socketShutdown();
return;
} else if (error) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] [error] " + error.message(),
Log::Level::ERROR);
socketShutdown();
return;
return false;
}
if (readBuffer_.size() > 0) {
copyStreambuf(readBuffer_, buffer_);
} else {
if (readBuffer_.size() == 0) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] empty read buffer",
Log::Level::DEBUG);
socketShutdown();
return;
return false;
}
} catch (std::exception &error) {
copyStreambuf(readBuffer_, buffer_);
return true;
} catch (const std::exception &ex) {
cancelTimeout();
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] [catch read] " + error.what(),
"] [TCPClient doReadAgent] [catch read] " + ex.what(),
Log::Level::DEBUG);
socketShutdown();
return;
return false;
}
}
void TCPClient::doReadServer() {
boost::system::error_code error;
end_ = false;
std::lock_guard lock(mutex_);
readBuffer_.consume(readBuffer_.size());
try {
@@ -357,6 +506,7 @@ void TCPClient::doReadServer() {
}
copyStreambuf(readBuffer_, buffer_);
} catch (std::exception &error) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadServer] [catch read] " + error.what(),
@@ -380,34 +530,192 @@ void TCPClient::cancelTimeout() {
}
void TCPClient::onTimeout(const boost::system::error_code &error) {
if (error || error == boost::asio::error::operation_aborted) return;
if (error == boost::asio::error::operation_aborted) {
return;
}
log_->write("[" + to_string(uuid_) +
"] [TCPClient onTimeout] [expiration] " +
std::to_string(+config_->general().timeout) +
" seconds has passed, and the timeout has expired",
"] [TCPClient onTimeout] timeout expired",
Log::Level::TRACE);
socketShutdown();
}
void TCPClient::socketShutdown() {
try {
boost::system::error_code ignored;
boost::system::error_code ec;
if (sslSocket_) {
sslSocket_->shutdown(ignored);
sslSocket_->lowest_layer().shutdown(
boost::asio::ip::tcp::socket::shutdown_both, ignored);
sslSocket_->lowest_layer().close(ignored);
}
std::lock_guard<std::mutex> lock(mutex_);
if (socket_.is_open()) {
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored);
socket_.close(ignored);
}
} catch (std::exception &error) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient socketShutdown] [catch] " + error.what(),
if (closed_) return;
closed_ = true;
cancelTimeout();
if (sslSocket_) {
log_->write("[" + to_string(uuid_) + "] [TCPClient socketShutdown] [SSL]",
Log::Level::DEBUG);
auto &lowest = sslSocket_->lowest_layer();
lowest.cancel(ec);
ec.clear();
if (lowest.is_open()) {
lowest.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
ec.clear();
lowest.close(ec);
}
}
}
if (socket_.is_open()) {
log_->write("[" + to_string(uuid_) + "] [TCPClient socketShutdown] [TCP]",
Log::Level::DEBUG);
socket_.cancel(ec);
ec.clear();
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
ec.clear();
socket_.close(ec);
}
tlsEnabled_ = false;
}
std::string TCPClient::HttpUtils::toLowerCopy(std::string s) {
return http_utils::toLowerCopy(std::move(s));
}
std::string TCPClient::HttpUtils::extractHeaders(const std::string &msg) {
return http_utils::extractHeaders(msg);
}
std::string TCPClient::HttpUtils::extractBody(const std::string &msg) {
return http_utils::extractBody(msg);
}
bool TCPClient::HttpUtils::parseContentLength(const std::string &headers, std::size_t &value) {
return http_utils::parseContentLength(headers, value);
}
bool TCPClient::HttpUtils::isChunked(const std::string &headers) {
return http_utils::isChunked(headers);
}
bool TCPClient::HttpUtils::readHttpMessage(
tcp::socket &stream,
boost::asio::streambuf &out,
boost::system::error_code &ec) {
return readHttpMessageImpl(
out,
ec,
[&stream](boost::asio::mutable_buffer buffer,
boost::system::error_code &error) {
return stream.read_some(buffer, error);
},
[&stream](boost::asio::streambuf &buffer,
boost::system::error_code &error) {
boost::asio::read_until(stream, buffer, "\r\n\r\n", error);
return !error;
});
}
bool TCPClient::HttpUtils::readHttpMessage(
ssl_stream &stream,
boost::asio::streambuf &out,
boost::system::error_code &ec) {
return readHttpMessageImpl(
out,
ec,
[&stream](boost::asio::mutable_buffer buffer,
boost::system::error_code &error) {
return stream.read_some(buffer, error);
},
[&stream](boost::asio::streambuf &buffer,
boost::system::error_code &error) {
boost::asio::read_until(stream, buffer, "\r\n\r\n", error);
return !error;
});
}
bool TCPClient::HttpUtils::readHttpMessageImpl(
boost::asio::streambuf &out,
boost::system::error_code &ec,
const std::function<std::size_t(
boost::asio::mutable_buffer,
boost::system::error_code &)> &readSome,
const std::function<bool(
boost::asio::streambuf &,
boost::system::error_code &)> &readHeaders) {
out.consume(out.size());
if (!readHeaders(out, ec)) {
return false;
}
std::string current = streambufToString(out);
std::string headers = extractHeaders(current);
std::string body = extractBody(current);
std::size_t contentLength = 0;
if (parseContentLength(headers, contentLength)) {
while (body.size() < contentLength) {
char tmp[8192];
std::size_t remaining =
contentLength - body.size();
std::size_t toRead =
std::min<std::size_t>(
sizeof(tmp),
remaining);
std::size_t n =
readSome(
boost::asio::buffer(
tmp,
toRead),
ec);
if (ec) {
return false;
}
if (n == 0) {
ec = boost::asio::error::eof;
return false;
}
boost::asio::buffer_copy(
out.prepare(n),
boost::asio::buffer(tmp, n));
out.commit(n);
body.append(tmp, n);
}
return true;
}
if (isChunked(headers)) {
while (
body.find("\r\n0\r\n\r\n") ==
std::string::npos &&
body.find("\r\n0\r\n") ==
std::string::npos) {
char tmp[8192];
std::size_t n =
readSome(
boost::asio::buffer(tmp),
ec);
if (ec) {
return false;
}
if (n == 0) {
ec = boost::asio::error::eof;
return false;
}
boost::asio::buffer_copy(
out.prepare(n),
boost::asio::buffer(tmp, n));
out.commit(n);
body.append(tmp, n);
}
return true;
}
return true;
}
+37 -14
View File
@@ -2,9 +2,8 @@
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/uuid/uuid.hpp>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
@@ -14,9 +13,9 @@
#include "http.hpp"
#include "log.hpp"
class TCPClient : public boost::enable_shared_from_this<TCPClient> {
class TCPClient : public std::enable_shared_from_this<TCPClient> {
public:
using pointer = boost::shared_ptr<TCPClient>;
using pointer = std::shared_ptr<TCPClient>;
using tcp = boost::asio::ip::tcp;
using ssl_stream = boost::asio::ssl::stream<tcp::socket>;
@@ -34,28 +33,51 @@ public:
bool enableTlsClient();
bool doHandshakeClient();
bool doConnect(const std::string &dstIp, unsigned short dstPort);
void writeBuffer(boost::asio::streambuf &buffer);
inline boost::asio::streambuf &writeBuffer() & { return writeBuffer_; }
inline boost::asio::streambuf &&writeBuffer() && {
return std::move(writeBuffer_);
}
inline boost::asio::streambuf &readBuffer() & { return readBuffer_; }
inline boost::asio::streambuf &&readBuffer() && { return std::move(readBuffer_); }
bool doConnect(const std::string &dstIP, const unsigned short &dstPort);
void doWrite(boost::asio::streambuf &buffer);
void doReadAgent();
bool doReadAgent();
bool doWrite(boost::asio::streambuf &buffer);
void doReadServer();
void socketShutdown();
boost::uuids::uuid uuid() const { return uuid_; }
bool ended() const { return end_; }
boost::uuids::uuid uuid_;
bool end_;
private:
struct HttpUtils {
static std::string toLowerCopy(std::string s);
static std::string extractHeaders(const std::string &msg);
static std::string extractBody(const std::string &msg);
static bool parseContentLength(const std::string &headers, std::size_t &value);
static bool isChunked(const std::string &headers);
static bool readHttpMessage(tcp::socket &stream,
boost::asio::streambuf &out,
boost::system::error_code &ec);
static bool readHttpMessage(ssl_stream &stream,
boost::asio::streambuf &out,
boost::system::error_code &ec);
static bool readHttpMessageImpl(
boost::asio::streambuf &out,
boost::system::error_code &ec,
const std::function<std::size_t(boost::asio::mutable_buffer,
boost::system::error_code &)> &readSome,
const std::function<bool(boost::asio::streambuf &,
boost::system::error_code &)> &readHeaders);
};
explicit TCPClient(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log);
@@ -64,8 +86,8 @@ private:
void cancelTimeout();
void onTimeout(const boost::system::error_code &error);
const std::shared_ptr<Config> &config_;
const std::shared_ptr<Log> &log_;
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
boost::asio::io_context &io_context_;
tcp::socket socket_;
@@ -80,4 +102,5 @@ private:
tcp::resolver resolver_;
boost::asio::steady_timer timeout_;
mutable std::mutex mutex_;
bool closed_ = false;
};
+913 -286
View File
File diff suppressed because it is too large. Load diff
+79 -24
View File
@@ -1,25 +1,27 @@
#pragma once
#include <array>
#include <atomic>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <chrono>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include "agenthandler.hpp"
#include "general.hpp"
#include "serverhandler.hpp"
class TCPConnection : public boost::enable_shared_from_this<TCPConnection> {
class TCPConnection : public std::enable_shared_from_this<TCPConnection> {
public:
using pointer = boost::shared_ptr<TCPConnection>;
using ssl_stream =
boost::asio::ssl::stream<boost::asio::ip::tcp::socket>;
using pointer = std::shared_ptr<TCPConnection>;
using ssl_stream = boost::asio::ssl::stream<boost::asio::ip::tcp::socket>;
static pointer create(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
@@ -29,7 +31,7 @@ public:
}
boost::asio::ip::tcp::socket &socket();
inline TCPClient::pointer client() { return client_; }
inline TCPClient::pointer client() const { return client_; }
ssl_stream &tlsSocket();
bool initTlsServerContext();
@@ -40,45 +42,94 @@ public:
}
inline const boost::asio::streambuf &readBuffer() & { return readBuffer_; }
inline const boost::asio::streambuf &&readBuffer() && {
return std::move(readBuffer_);
}
inline boost::uuids::uuid uuid() { return uuid_; }
inline boost::uuids::uuid uuid() const { return uuid_; }
void startAgent();
void startServer();
void doReadAgent();
void doReadServer();
void handleReadAgent(const boost::system::error_code &error,
size_t bytes_transferred);
void handleReadServer(const boost::system::error_code &error,
size_t bytes_transferred);
void handleReadAgent(const boost::system::error_code &error, size_t bytes_transferred);
void handleReadServer(const boost::system::error_code &error, size_t bytes_transferred);
void socketShutdown();
void enableTunnelMode();
void relayClientToRemote();
void relayRemoteToClient();
void enableDirectTunnelMode();
void relayClientToServer();
void relayServerToClient();
void relayAgentToTarget();
void relayTargetToAgent();
std::mutex relayMutex_;
inline void asyncWriteToAgentConnection(
const char *data,
std::size_t bytes,
std::function<void(const boost::system::error_code &)> done);
inline void asyncReadFromAgentConnection(
std::array<char, BufferSize> &buffer,
std::function<void(const boost::system::error_code &, std::size_t)> done);
inline void asyncWriteToAgentServerConnection(
const char *data,
std::size_t bytes,
std::function<void(const boost::system::error_code &)> done);
inline void asyncReadFromAgentServerConnection(
std::array<char, BufferSize> &buffer,
std::function<void(const boost::system::error_code &, std::size_t)> done);
private:
struct HttpUtils {
static std::string toLowerCopy(std::string s);
static std::string extractHeaders(const std::string &msg);
static std::string extractBody(const std::string &msg);
static bool parseContentLength(const std::string &headers, std::size_t &value);
static bool isChunked(const std::string &headers);
static bool readRemainingHttpBody(boost::asio::ip::tcp::socket &stream,
boost::asio::streambuf &buf,
boost::system::error_code &ec);
static bool readRemainingHttpBody(ssl_stream &stream,
boost::asio::streambuf &buf,
boost::system::error_code &ec);
static bool readRemainingHttpBodyImpl(
boost::asio::streambuf &buf,
boost::system::error_code &ec,
const std::function<std::size_t(boost::asio::mutable_buffer,
boost::system::error_code &)> &readSome);
};
explicit TCPConnection(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
TCPClient::pointer client);
bool handleSocks5Handshake();
bool readExactFromClient(void *data, std::size_t size);
void resetTimeout();
void cancelTimeout();
void onTimeout(const boost::system::error_code &error);
void startTunnelReadFromClient();
void startTunnelPollServer();
std::string postTunnelAction(const std::string &action, const std::string &rawBody);
std::string makeRelayHostHeader() const;
void closeTunnelSession();
boost::asio::ip::tcp::socket socket_;
boost::asio::ssl::context sslContext_;
std::unique_ptr<ssl_stream> tlsSocket_;
const std::shared_ptr<Config> &config_;
const std::shared_ptr<Log> &log_;
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
boost::asio::io_context &io_context_;
TCPClient::pointer client_;
@@ -86,6 +137,7 @@ private:
boost::asio::streambuf writeBuffer_;
boost::asio::steady_timer timeout_;
boost::asio::steady_timer pollTimer_;
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
boost::uuids::uuid uuid_;
@@ -94,7 +146,10 @@ private:
bool end_;
bool connect_;
bool tunnelMode_;
bool tunnelClosed_;
bool pollInProgress_;
std::atomic_bool closed_{false};
std::array<char, 16384> downstreamBuf_;
std::array<char, 16384> upstreamBuf_;
std::array<char, BufferSize> downstreamBuf_;
std::array<char, BufferSize> upstreamBuf_;
};
+24 -48
View File
@@ -1,15 +1,8 @@
#include "tcpserver.hpp"
/**
* @brief Constructs a new TCPServer instance.
*
* Initializes the `acceptor_` with the specified IP and port from the configuration, and sets the `reuse_address` option
* to allow multiple bindings to the same address. This constructor also starts the process of accepting connections.
*
* @param io_context The IO context for asynchronous operations.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
*/
#include <atomic>
#include <chrono>
TCPServer::TCPServer(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log)
@@ -21,16 +14,9 @@ TCPServer::TCPServer(boost::asio::io_context &io_context,
boost::asio::ip::make_address(config->listenIp()),
config->listenPort())) {
acceptor_.set_option(boost::asio::socket_base::reuse_address(true));
startAccept();
}
/**
* @brief Starts accepting incoming client connections asynchronously.
*
* This method creates a new `TCPClient` and `TCPConnection` object to handle the connection, then starts the asynchronous
* accept operation using the acceptor. Once a connection is accepted, the `handleAccept` method will be called.
*/
void TCPServer::startAccept() {
auto client = TCPClient::create(io_context_, config_, log_);
auto connection = TCPConnection::create(io_context_, config_, log_, client);
@@ -42,53 +28,43 @@ void TCPServer::startAccept() {
});
}
/**
* @brief Handles the result of the asynchronous accept operation.
*
* If the connection was successfully accepted, this method starts the communication on the connection by invoking the
* `start` method. If an error or exception occurs, it logs the error or exception.
*
* @param connection The `TCPConnection` object representing the accepted connection.
* @param error The error code resulting from the accept operation.
*/
void TCPServer::handleAccept(TCPConnection::pointer connection,
const boost::system::error_code &error) {
void TCPServer::handleAccept(
TCPConnection::pointer connection,
const boost::system::error_code &error) {
startAccept();
try {
if (!error) {
if (config_->runMode() == RunMode::server) {
if (error) {
log_->write("[TCPServer handleAccept] Error: " + error.message(), Log::Level::ERROR);
return;
}
if (config_->runMode() == RunMode::server) {
if (config_->general().tlsEnable) {
if (!connection->initTlsServerContext()) {
log_->write("[TCPServer handleAccept] TLS server context init failed",
Log::Level::ERROR);
log_->write("[TCPServer handleAccept] TLS server context init failed", Log::Level::ERROR);
connection->socketShutdown();
startAccept();
return;
}
connection->tlsSocket().lowest_layer() = std::move(connection->socket());
if (!connection->doHandshakeServer()) {
log_->write("[TCPServer handleAccept] TLS server handshake failed",
Log::Level::ERROR);
log_->write("[TCPServer handleAccept] TLS server handshake failed", Log::Level::ERROR);
connection->socketShutdown();
startAccept();
return;
}
connection->startServer();
} else {
connection->startAgent();
}
connection->startServer();
} else {
log_->write("[TCPServer handleAccept] Error: " + error.message(),
Log::Level::ERROR);
connection->startAgent();
}
} catch (const std::exception &ex) {
log_->write("[TCPServer handleAccept] Exception: " + std::string(ex.what()),
Log::Level::ERROR);
log_->write("[TCPServer handleAccept] Exception: " + std::string(ex.what()), Log::Level::ERROR);
connection->socketShutdown();
} catch (...) {
log_->write("[TCPServer handleAccept] Unknown exception",
Log::Level::ERROR);
log_->write("[TCPServer handleAccept] Unknown exception", Log::Level::ERROR);
connection->socketShutdown();
}
startAccept();
}
+5 -44
View File
@@ -1,71 +1,32 @@
#pragma once
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <memory>
#include "tcpconnection.hpp"
/**
* @brief A TCP server class that accepts incoming TCP connections and handles them.
*
* The class listens for incoming connections and creates `TCPConnection` objects to handle communication.
*/
class TCPServer {
public:
using pointer = boost::shared_ptr<TCPServer>;
using pointer = std::shared_ptr<TCPServer>;
/**
* @brief Creates a new TCPServer instance.
*
* This static factory method initializes a `TCPServer` with the provided IO context, configuration, and logging.
*
* @param io_context The IO context for asynchronous operations.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
*
* @return A shared pointer to the newly created TCPServer instance.
*/
static pointer create(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log) {
return pointer(new TCPServer(io_context, config, log));
}
/**
* @brief Starts the process of accepting incoming connections.
*
* This method begins the asynchronous accept operation to listen for incoming client connections.
*/
void startAccept();
private:
/**
* @brief Constructs a TCPServer object.
*
* Initializes the acceptor, sets up the IO context, and stores the configuration and log objects.
*
* @param io_context The IO context for asynchronous operations.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
*/
explicit TCPServer(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log);
/**
* @brief Handles the completion of an accept operation.
*
* Once a new connection is accepted, this method is called to handle the connection by creating a `TCPConnection`
* object and starting communication with the client.
*
* @param connection A shared pointer to the new `TCPConnection` object.
* @param error The error code indicating the result of the accept operation.
*/
void handleAccept(TCPConnection::pointer connection,
const boost::system::error_code &error);
const std::shared_ptr<Config> &config_;
const std::shared_ptr<Log> &log_;
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
boost::asio::io_context &io_context_;
boost::asio::ip::tcp::acceptor acceptor_;
};
};
+18
View File
@@ -0,0 +1,18 @@
## Install on Termux
### Requirements
libyaml-cpp >= 0.8
boost >= 1.88.0
### Dependencies
Install the dependencies
```bash
pkg install boost libyaml-cpp
```
### Install
Download the nipovpn_VERSION_termux_aarch64 version from releases pages
```bash
pkg install ./nipovpn_VERSION_termux_aarch64.deb
```
+7 -7
View File
@@ -1,7 +1,7 @@
Package : nipovpn
Version : 0.1
Maintainer : Morteza Bashsiz
Architecture : amd64
Description : Powerfull and Secure http/s Proxy
Depends : libyaml-cpp0.8
Homepage : https://github.com/MortezaBashsiz/nipovpn
Package: nipovpn
Version: ${PACKAGE_VERSION}
Maintainer: Morteza Bashsiz
Architecture: ${{ matrix.arch }}
Description: Powerfull and Secure http/s Proxy
Depends: libyaml-cpp0.8
Homepage: https://github.com/MortezaBashsiz/nipovpn
+55 -21
View File
@@ -3,20 +3,62 @@
general:
# token: 32 bytes of string. this will be used on agent and server side to encryption
token: "af445adb-2434-4975-9445-2c1b2231"
# fakeUrl: string
# Defines the fake url and endpoint between agent and server
fakeUrl: "http://www.adas.com/api01"
# method: "HEAD|GET|POST|PUT|DELETE"
# Defines with which method
# protocol:
# Defines the protocol between client and agent
# Choose http or socks5
protocol: http
# fakeUrls:
# Defines the list of fake urls between agent and server
fakeUrls:
- nipo.ciron.net
- sudoer.ir
- sudoer.net
- google.com
- cloudflare.com
# methods:
# Defines the list of using methods
# you like to send requests from agent to server
method: "POST"
# Program will choose randomly from this list
methods:
- GET
- POST
- PUT
- DELETE
# endPoints:
# Defines the list of using endpoints
# you like to send requests from agent to server
# Program will choose randomly from this list
endPoints:
- api
- login
- user
- update
# timeout: unsigned short
# Defines the timeout for I/O Operation in seconds. 0 indicates no timeout.
# Useful to automatically close stalled connections.
timeout: 10
# chunkHeader: String
# Defines the chunk header that you want to inform Agent/Server if it is end or not.
chunkHeader: "END"
# pullTimeout: unsigned short
# Defines the timeout for I/O Operation in milliseconds.
# Useful to expire serverside read timer.
pullTimeout: 50
# tunnelEnable: bool
# Defines the connection mode between agent and server. If enabled then the traffic
# will be TCP/TLS tunnel like.
tunnelEnable: false
# connectionReuse: bool
# If false then it will use same connection between agent and server to handle client request
# If true then it will create new connection for each request between agent and server
connectionReuse: true
# tlsEnable: bool
# It enables or disables tls between agent and server
tlsEnable: false
# tlsVerifyPeer: bool
# Use it to controll if the certificate should be validated or not
tlsVerifyPeer: false
# Use following configurations to specify the key and cert which will be used between agent and server
tlsCertFile: "/etc/nipovpn/server.crt"
tlsKeyFile: "/etc/nipovpn/server.key"
tlsCaFile: ""
# This block is to define log directives
@@ -34,13 +76,8 @@ server:
# listenIp: which must be IPv4 which is used on server
listenIp: "0.0.0.0"
# listenPort: the port number which will be used on server
listenPort: 443
tlsEnable: true
tlsVerifyPeer: false
tlsCertFile: "/etc/nipovpn/server.crt"
tlsKeyFile: "/etc/nipovpn/server.key"
tlsCaFile: ""
tlsDhFile: "/etc/nipovpn/dh.pem"
listenPort: 80
# This block is to define agent directives
agent:
@@ -53,11 +90,8 @@ agent:
# serverIp: IPv4 of the nipoServer
serverIp: "127.0.0.10"
# serverPort: port number of the nipoServer
serverPort: 443
serverPort: 80
# httpVersion: This version will be used between agent and server
httpVersion: "1.1"
# userAgent: This is the http user agent which will be used between agent and server
userAgent : "NipoAgent"
tlsEnable: true
tlsVerifyPeer: false
tlsCaFile: ""
userAgent : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0"