Compare commits
156
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f42ceff35 | ||
|
|
65fd8f1fca | ||
|
|
4dd09b0d0e | ||
|
|
88782afbfd | ||
|
|
6bcc946f58 | ||
|
|
6770764f2b | ||
|
|
9199a0ded9 | ||
|
|
92de8a0bce | ||
|
|
679ab77dc2 | ||
|
|
04768f37de | ||
|
|
e52743c051 | ||
|
|
ce61bfd8ad | ||
|
|
78188d8ac3 | ||
|
|
1af9ede5ff | ||
|
|
5f3594b6d2 | ||
|
|
95e05cf59c | ||
|
|
a8205a716b | ||
|
|
c76b23f93c | ||
|
|
555cad3654 | ||
|
|
df310303da | ||
|
|
5056b7b907 | ||
|
|
5616828192 | ||
|
|
5a0c414f63 | ||
|
|
5ddfcf1a0d | ||
|
|
703595501c | ||
|
|
3b195208ff | ||
|
|
a63d7ca141 | ||
|
|
882c68179f | ||
|
|
5e8b76769d | ||
|
|
c1afc7dab2 | ||
|
|
ef04fb3fb2 | ||
|
|
ec5eaf824b | ||
|
|
de4606d884 | ||
|
|
4860804ef1 | ||
|
|
d9c3a45074 | ||
|
|
33adcf9541 | ||
|
|
02920acb49 | ||
|
|
b250ec47a9 | ||
|
|
8e677a826d | ||
|
|
2e2ef18529 | ||
|
|
fdf03a7ec7 | ||
|
|
14f7f107b7 | ||
|
|
13aa2cd816 | ||
|
|
042998095e | ||
|
|
a006ba4e0c | ||
|
|
413bffba44 | ||
|
|
3b2c01b095 | ||
|
|
4c6a00e801 | ||
|
|
c2dc1487a2 | ||
|
|
4df70ae101 | ||
|
|
49026a2f0d | ||
|
|
7c82f7f3b5 | ||
|
|
3a965c904f | ||
|
|
1f03931aa4 | ||
|
|
aa36749c47 | ||
|
|
6535cb51b7 | ||
|
|
212003760b | ||
|
|
698da19a8c | ||
|
|
451a169756 | ||
|
|
277321306b | ||
|
|
d6e0161aa5 | ||
|
|
14b0947140 | ||
|
|
134251779c | ||
|
|
92d877be31 | ||
|
|
7e6ae56753 | ||
|
|
deae50f9d4 | ||
|
|
daa21a57db | ||
|
|
d8f09b9fe2 | ||
|
|
aeeea2a527 | ||
|
|
55004368e4 | ||
|
|
d0da1c55d8 | ||
|
|
3363a7a5d2 | ||
|
|
4cdc66bdf1 | ||
|
|
2540b3a504 | ||
|
|
cb87555503 | ||
|
|
20bb0d2b9d | ||
|
|
31b7bb96a8 | ||
|
|
9abc319202 | ||
|
|
6c21edfc40 | ||
|
|
6493d88258 | ||
|
|
ed10d097f1 | ||
|
|
14ead78ff8 | ||
|
|
b1a18e243c | ||
|
|
24390b6562 | ||
|
|
ec4a68fdb6 | ||
|
|
bae6afa35b | ||
|
|
36315032d9 | ||
|
|
96758b6322 | ||
|
|
9b5b275275 | ||
|
|
76a9e4acb0 | ||
|
|
3b3d2f4d88 | ||
|
|
9af39a5715 | ||
|
|
2f043a6f83 | ||
|
|
d94075e5c3 | ||
|
|
9f1a7c8637 | ||
|
|
2add09ea33 | ||
|
|
8beee5d127 | ||
|
|
84bb675b9c | ||
|
|
67c43de80d | ||
|
|
ab4580920f | ||
|
|
c0942c4015 | ||
|
|
228aff5d63 | ||
|
|
5647fd2f69 | ||
|
|
92a290cca7 | ||
|
|
108b9729c7 | ||
|
|
7baaf6aefb | ||
|
|
4793a3f0e3 | ||
|
|
c8cd4066d7 | ||
|
|
33a4dbd0b8 | ||
|
|
01d8b36ca0 | ||
|
|
cd7b985da1 | ||
|
|
80c631f66b | ||
|
|
8a1fcde280 | ||
|
|
51feb98dc3 | ||
|
|
560b5d93cc | ||
|
|
97ee705eec | ||
|
|
8d1ecfc2dc | ||
|
|
b402144e9e | ||
|
|
e7c8cb51cc | ||
|
|
51fd1d47cc | ||
|
|
251b0202e8 | ||
|
|
10e4481376 | ||
|
|
47b56af86e | ||
|
|
1c8d2d610b | ||
|
|
86f2b750a8 | ||
|
|
0e4c1bf00d | ||
|
|
1452c1bd82 | ||
|
|
09d5e25509 | ||
|
|
73f9cb01c1 | ||
|
|
88bf0953e3 | ||
|
|
83fbb7adf2 | ||
|
|
7ac2fb293f | ||
|
|
f70ef566d7 | ||
|
|
064fe1614a | ||
|
|
323380afa5 | ||
|
|
f2b63aacb9 | ||
|
|
d968046d8b | ||
|
|
a9d290c788 | ||
|
|
268dcfb207 | ||
|
|
f3bd05787b | ||
|
|
9f7e6ab713 | ||
|
|
62d34bd3e8 | ||
|
|
97bb609bd6 | ||
|
|
7b6a23f508 | ||
|
|
5473b4b7b1 | ||
|
|
9cfe163ac2 | ||
|
|
b6a8954a4b | ||
|
|
61a8b4ddae | ||
|
|
576bef360d | ||
|
|
750ed871c8 | ||
|
|
6650839c66 | ||
|
|
ad0d921032 | ||
|
|
cf012afa87 | ||
|
|
4c0a3c4df7 | ||
|
|
b46529b2c2 | ||
|
|
21fec88b6e |
No files matched your search
@@ -0,0 +1,7 @@
|
||||
.git
|
||||
.github
|
||||
build
|
||||
cmake-build-*
|
||||
*.deb
|
||||
*.tar.gz
|
||||
*.log
|
||||
@@ -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 }}
|
||||
@@ -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.60
|
||||
|
||||
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 }}
|
||||
@@ -1,75 +0,0 @@
|
||||
name: Build and Release Debian Package
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- mori/cf
|
||||
paths:
|
||||
- 'core/src/**'
|
||||
- '.github/workflows/**'
|
||||
|
||||
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_cf_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_cf_v1-1-${{ github.run_number }}.deb
|
||||
|
||||
- name: Show nipovpn information
|
||||
run: |
|
||||
dpkg -I build/nipovpn_cf_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: 'v.10.1.1.${{ github.run_number }}'
|
||||
release_name: Staging v.10.1.1.${{ github.run_number }}
|
||||
draft: false
|
||||
prerelease: true
|
||||
|
||||
- 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_cf_v1-1-${{ github.run_number }}.deb
|
||||
asset_name: nipovpn_cf_v1-1-${{ github.run_number }}.deb
|
||||
asset_content_type: application/octet-stream
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Build and Release Debian Package
|
||||
name: Build and Release Package - dev
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -6,70 +6,331 @@ 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
|
||||
|
||||
mkdir -p package-root/DEBIAN
|
||||
cat > package-root/DEBIAN/conffiles <<'EOF'
|
||||
/etc/nipovpn/config.yaml
|
||||
EOF
|
||||
|
||||
rm -f package-root/var/log/nipovpn/nipovpn.log
|
||||
mkdir -p package-root/var/log/nipovpn
|
||||
|
||||
cat > package-root/DEBIAN/postinst <<'EOF'
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
mkdir -p /var/log/nipovpn
|
||||
|
||||
if [ ! -f /var/log/nipovpn/nipovpn.log ]; then
|
||||
touch /var/log/nipovpn/nipovpn.log
|
||||
chmod 0644 /var/log/nipovpn/nipovpn.log
|
||||
fi
|
||||
|
||||
exit 0
|
||||
EOF
|
||||
|
||||
chmod 755 package-root/DEBIAN/postinst
|
||||
|
||||
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: Clone termux-packages
|
||||
run: |
|
||||
git clone --depth=1 https://github.com/termux/termux-packages.git
|
||||
|
||||
- name: Install Android NDK required by termux-packages
|
||||
run: |
|
||||
NDK_NUM="$(sed -n 's/^: "${TERMUX_NDK_VERSION_NUM:="\([0-9]*\)"}"/\1/p' termux-packages/scripts/properties.sh)"
|
||||
NDK_REV="$(sed -n 's/^: "${TERMUX_NDK_REVISION:="\([a-z]*\)"}"/\1/p' termux-packages/scripts/properties.sh)"
|
||||
|
||||
if [ -z "$NDK_NUM" ]; then
|
||||
echo "Could not read the NDK version from termux-packages/scripts/properties.sh"
|
||||
grep -n NDK termux-packages/scripts/properties.sh || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
NDK_VERSION="r${NDK_NUM}${NDK_REV}"
|
||||
echo "termux-packages requires Android NDK $NDK_VERSION"
|
||||
|
||||
mkdir -p "$HOME/lib"
|
||||
cd "$HOME/lib"
|
||||
|
||||
wget -q "https://dl.google.com/android/repository/android-ndk-${NDK_VERSION}-linux.zip"
|
||||
unzip -q "android-ndk-${NDK_VERSION}-linux.zip"
|
||||
|
||||
EXTRACTED_DIR="$(find "$HOME/lib" -maxdepth 1 -type d -name "android-ndk-${NDK_VERSION}*" | head -n 1)"
|
||||
|
||||
if [ -z "$EXTRACTED_DIR" ]; then
|
||||
echo "Android NDK $NDK_VERSION directory not found"
|
||||
ls -lah "$HOME/lib"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$EXTRACTED_DIR" != "$HOME/lib/android-ndk-${NDK_VERSION}" ]; then
|
||||
ln -sfn "$EXTRACTED_DIR" "$HOME/lib/android-ndk-${NDK_VERSION}"
|
||||
fi
|
||||
|
||||
echo "NDK=$HOME/lib/android-ndk-${NDK_VERSION}" >> "$GITHUB_ENV"
|
||||
echo "ANDROID_NDK_ROOT=$HOME/lib/android-ndk-${NDK_VERSION}" >> "$GITHUB_ENV"
|
||||
|
||||
ls -ld "$HOME/lib/android-ndk-${NDK_VERSION}"
|
||||
|
||||
- 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: 'v.0.1.1.${{ github.run_number }}'
|
||||
release_name: Staging v.0.1.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 }}
|
||||
@@ -0,0 +1,336 @@
|
||||
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.60
|
||||
|
||||
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
|
||||
|
||||
mkdir -p package-root/DEBIAN
|
||||
cat > package-root/DEBIAN/conffiles <<'EOF'
|
||||
/etc/nipovpn/config.yaml
|
||||
EOF
|
||||
|
||||
rm -f package-root/var/log/nipovpn/nipovpn.log
|
||||
mkdir -p package-root/var/log/nipovpn
|
||||
|
||||
cat > package-root/DEBIAN/postinst <<'EOF'
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
mkdir -p /var/log/nipovpn
|
||||
|
||||
if [ ! -f /var/log/nipovpn/nipovpn.log ]; then
|
||||
touch /var/log/nipovpn/nipovpn.log
|
||||
chmod 0644 /var/log/nipovpn/nipovpn.log
|
||||
fi
|
||||
|
||||
exit 0
|
||||
EOF
|
||||
|
||||
chmod 755 package-root/DEBIAN/postinst
|
||||
|
||||
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: Clone termux-packages
|
||||
run: |
|
||||
git clone --depth=1 https://github.com/termux/termux-packages.git
|
||||
|
||||
- name: Install Android NDK required by termux-packages
|
||||
run: |
|
||||
NDK_NUM="$(sed -n 's/^: "${TERMUX_NDK_VERSION_NUM:="\([0-9]*\)"}"/\1/p' termux-packages/scripts/properties.sh)"
|
||||
NDK_REV="$(sed -n 's/^: "${TERMUX_NDK_REVISION:="\([a-z]*\)"}"/\1/p' termux-packages/scripts/properties.sh)"
|
||||
|
||||
if [ -z "$NDK_NUM" ]; then
|
||||
echo "Could not read the NDK version from termux-packages/scripts/properties.sh"
|
||||
grep -n NDK termux-packages/scripts/properties.sh || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
NDK_VERSION="r${NDK_NUM}${NDK_REV}"
|
||||
echo "termux-packages requires Android NDK $NDK_VERSION"
|
||||
|
||||
mkdir -p "$HOME/lib"
|
||||
cd "$HOME/lib"
|
||||
|
||||
wget -q "https://dl.google.com/android/repository/android-ndk-${NDK_VERSION}-linux.zip"
|
||||
unzip -q "android-ndk-${NDK_VERSION}-linux.zip"
|
||||
|
||||
EXTRACTED_DIR="$(find "$HOME/lib" -maxdepth 1 -type d -name "android-ndk-${NDK_VERSION}*" | head -n 1)"
|
||||
|
||||
if [ -z "$EXTRACTED_DIR" ]; then
|
||||
echo "Android NDK $NDK_VERSION directory not found"
|
||||
ls -lah "$HOME/lib"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$EXTRACTED_DIR" != "$HOME/lib/android-ndk-${NDK_VERSION}" ]; then
|
||||
ln -sfn "$EXTRACTED_DIR" "$HOME/lib/android-ndk-${NDK_VERSION}"
|
||||
fi
|
||||
|
||||
echo "NDK=$HOME/lib/android-ndk-${NDK_VERSION}" >> "$GITHUB_ENV"
|
||||
echo "ANDROID_NDK_ROOT=$HOME/lib/android-ndk-${NDK_VERSION}" >> "$GITHUB_ENV"
|
||||
|
||||
ls -ld "$HOME/lib/android-ndk-${NDK_VERSION}"
|
||||
|
||||
- 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 main 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 }}
|
||||
@@ -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
|
||||
|
||||
@@ -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 }}
|
||||
@@ -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.60
|
||||
|
||||
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 }}
|
||||
|
||||
@@ -37,3 +37,10 @@ build
|
||||
.idea
|
||||
/cmake-build-debug/
|
||||
test
|
||||
|
||||
|
||||
.git
|
||||
.github
|
||||
*.deb
|
||||
*.tar.gz
|
||||
*.log
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -1,71 +1,341 @@
|
||||
# NipoVPN (Not ready yet :D)
|
||||
# NipoVPN
|
||||
|
||||
## Overview
|
||||
NipoVPN is a proxy that hides your traffic inside ordinary-looking HTTP requests.
|
||||
It runs in two roles: an **agent** on your side and a **server** outside the
|
||||
censored or monitored network. The agent wraps each request in a decoy HTTP
|
||||
request (random method, endpoint and `Host`), optionally encrypts it with
|
||||
AES-256-GCM and sends it over TLS. The server unwraps it, talks to the real
|
||||
destination and sends the response back the same way.
|
||||
|
||||
NipoVPN is a powerful proxy tool designed to conceal your HTTP requests within fake HTTP requests. This program, written in C++, leverages the Boost library to handle networking functionalities efficiently.
|
||||
It is written in C++20 on top of Boost.Asio, OpenSSL and yaml-cpp.
|
||||
|
||||
- [Features](#features)
|
||||
- [How it works](#how-it-works)
|
||||
- [Installation](#installation)
|
||||
- [Quick start](#quick-start)
|
||||
- [Configuration reference](#configuration-reference)
|
||||
- [Security notes](#security-notes)
|
||||
- [Logging](#logging)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
- [Contribution](#contribution)
|
||||
- [License](#license)
|
||||
|
||||
## Features
|
||||
|
||||
- HTTP Request Obfuscation: Hide your legitimate HTTP requests inside decoy requests to avoid detection.
|
||||
- Boost Library Integration: Utilizes Boost for robust and reliable networking operations.
|
||||
- High Performance: Optimized for speed and efficiency, ensuring minimal impact on request latency.
|
||||
### Client side (agent)
|
||||
|
||||
- **HTTP proxy and SOCKS5 proxy** for local applications (`general.protocol`).
|
||||
- HTTP: plain HTTP requests and `CONNECT` tunnels (HTTPS).
|
||||
- SOCKS5: `CONNECT` command, no authentication, with IPv4, IPv6 and domain
|
||||
name targets.
|
||||
- **Multiple agents per server.** Each agent session is identified by a UUID, so
|
||||
many agents (and many clients behind each agent) can share one server.
|
||||
- **Multi-threaded.** The number of worker threads is configurable for the agent
|
||||
and the server separately.
|
||||
|
||||
## Usecases
|
||||
### Traffic obfuscation
|
||||
|
||||
### Bypass filtering
|
||||
This could help you to bypass the filtering in your country.
|
||||
- **Decoy HTTP requests.** Every request between the agent and server is a
|
||||
normal HTTP request whose method, path and `Host` header are picked at random
|
||||
from lists you configure (`methods`, `endPoints`, `fakeUrls`).
|
||||
- **Configurable `User-Agent` and HTTP version** for the decoy requests.
|
||||
- **Randomized TLS SNI.** With TLS enabled, the SNI sent to the server is also
|
||||
picked at random from `fakeUrls`.
|
||||
- **Hidden control data.** The session ID and action travel inside the
|
||||
(encrypted) body, not in custom headers, so the outer request carries no
|
||||
NipoVPN-specific headers.
|
||||
|
||||
### Encryption
|
||||
|
||||
- **AES-256-GCM payload encryption** (on by default). The key is the SHA-256 of
|
||||
`general.token`; each message gets a random 12-byte nonce and a 16-byte
|
||||
authentication tag, so tampered or wrongly keyed payloads are rejected.
|
||||
- **TLS between agent and server** (`tlsEnable`): TLS 1.2 minimum, TLS 1.3
|
||||
preferred, with AEAD-only cipher suites (AES-GCM, ChaCha20-Poly1305).
|
||||
- **Optional certificate verification** on the agent (`tlsVerifyPeer`) against
|
||||
a custom CA (`tlsCaFile`).
|
||||
|
||||
AES and TLS are independent: you can use either, both, or (not recommended)
|
||||
neither.
|
||||
|
||||
### Connection handling
|
||||
|
||||
- **Two tunnel modes** for `CONNECT`/SOCKS5 traffic:
|
||||
- **Polling mode** (default, `tunnelEnable: false`): every chunk of tunneled
|
||||
data is sent as its own decoy HTTP request (`send`), and the agent polls the
|
||||
server for incoming data (`recv`). Traffic looks like many short HTTP
|
||||
requests. Polling backs off from `pullTimeout` up to 50 ms while idle and
|
||||
snaps back as soon as data arrives.
|
||||
- **Direct tunnel mode** (`tunnelEnable: true`): after the first decoy
|
||||
request, the agent–server connection becomes a raw byte pipe to the
|
||||
destination. Faster, but only the opening request is disguised and
|
||||
encrypted. Use it together with `tlsEnable`.
|
||||
- **Connection reuse** (`connectionReuse`): keep one keep-alive connection
|
||||
between agent and server instead of opening a new one per request.
|
||||
- **Timeouts**: an I/O timeout that closes stalled connections (`timeout`) and
|
||||
a configurable buffer size per read (`bufferSize`).
|
||||
|
||||
### Operations
|
||||
|
||||
- **Config validation at startup** with clear error messages.
|
||||
- **Warning when the public sample token is still in use.**
|
||||
- **Log levels** `INFO`, `TRACE` (per-request source/destination) and `DEBUG`;
|
||||
logs go to a file and to stdout.
|
||||
- **Packaging**: `.deb` packages (amd64, arm64) with systemd units, a Docker
|
||||
image and compose file, a Nix flake with a NixOS module, a Termux package,
|
||||
Windows (x86_64) builds and an [Android app](https://github.com/MortezaBashsiz/nipovpn-android).
|
||||
|
||||
## How it works
|
||||
|
||||
### Use cases
|
||||
|
||||
**Bypass filtering.** Run the server outside the filtered network and the agent
|
||||
inside it. Filtering equipment sees only HTTP(S) requests to harmless-looking
|
||||
hosts.
|
||||
|
||||

|
||||
|
||||
### Hide your requests in the Internet
|
||||
If you want to hide your HTTP requests in the Internet, this proxy could help you.
|
||||
**Hide your requests on the Internet.** Even without censorship, NipoVPN hides
|
||||
which sites you visit from anyone watching your connection.
|
||||
|
||||

|
||||
|
||||
## Flow
|
||||
Here you can see the logical flow of a single request from first step to get the response
|
||||
### Request flow
|
||||
|
||||
```
|
||||
Browser/app ──HTTP or SOCKS5──▶ Agent ──decoy HTTP(S)──▶ Server ──real request──▶ Destination
|
||||
◀────────────────── ◀──────────────── ◀────────────────
|
||||
```
|
||||
|
||||
1. A local application sends a request to the agent (HTTP proxy or SOCKS5).
|
||||
SOCKS5 requests are converted to an HTTP `CONNECT` internally.
|
||||
2. The agent builds an envelope `action + session ID + request bytes`, encrypts
|
||||
it with AES-256-GCM (if `aesEnable`) and Base64-encodes it.
|
||||
3. The envelope is sent as the body of a decoy request such as
|
||||
`PUT /login` with `Host: cloudflare.com`, over TLS if `tlsEnable`.
|
||||
4. The server decodes and decrypts the body and performs the action:
|
||||
- `request` — forward a plain HTTP request and return the response.
|
||||
- `open` — open a TCP connection to the `CONNECT` target.
|
||||
- `send` / `recv` — write to / read from that connection (polling mode).
|
||||
- `close` — close the connection.
|
||||
5. The server's reply is encrypted and returned as the body of an HTTP
|
||||
`200 OK` response; the agent decrypts it and hands it to the application.
|
||||
|
||||

|
||||
|
||||
## Installation
|
||||
|
||||
| Platform | How |
|
||||
|---|---|
|
||||
| Debian / Ubuntu (amd64, arm64) | `.deb` from the [releases page](https://github.com/MortezaBashsiz/nipovpn/releases), tested on Ubuntu 24.04 |
|
||||
| Build from source on Linux | [Linux build guide](guides/BuildLinux.md) |
|
||||
| Docker | [Docker guide](guides/Docker.md) |
|
||||
| Nix / NixOS | [Nix guide](guides/Nix.md) |
|
||||
| Termux | [Termux guide](guides/InstallTermux.md) |
|
||||
| Windows (x86_64) | zip from the [releases page](https://github.com/MortezaBashsiz/nipovpn/releases) (`windows-v*` tags) |
|
||||
| Android | [nipovpn-android](https://github.com/MortezaBashsiz/nipovpn-android) |
|
||||
|
||||
### Debian package
|
||||
|
||||
```bash
|
||||
sudo apt install ./nipovpn.deb
|
||||
```
|
||||
|
||||
The package installs:
|
||||
|
||||
- `/usr/bin/nipovpn`
|
||||
- `/etc/nipovpn/config.yaml` (kept on upgrade)
|
||||
- `nipovpn-server.service` and `nipovpn-agent.service`
|
||||
|
||||
```bash
|
||||
sudo systemctl enable --now nipovpn-server.service # on the server
|
||||
sudo systemctl enable --now nipovpn-agent.service # on the agent machine
|
||||
```
|
||||
|
||||
### From source
|
||||
|
||||
Requirements: a C++20 compiler, CMake ≥ 3.22, Boost ≥ 1.88, yaml-cpp ≥ 0.8 and
|
||||
OpenSSL. See the [Linux build guide](guides/BuildLinux.md) for details.
|
||||
|
||||
```bash
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -B build
|
||||
cmake --build build -j$(nproc)
|
||||
```
|
||||
|
||||
## Quick start
|
||||
|
||||
The same binary and the same config file format are used on both sides; the
|
||||
first argument selects the role:
|
||||
|
||||
```bash
|
||||
nipovpn <server|agent> <config_file_path>
|
||||
```
|
||||
|
||||
### 1. Prepare the log file
|
||||
|
||||
```bash
|
||||
sudo mkdir -p /var/log/nipovpn/
|
||||
sudo touch /var/log/nipovpn/nipovpn.log
|
||||
```
|
||||
|
||||
### 2. Pick a shared token
|
||||
|
||||
`general.token` must be at least 32 bytes and identical on the agent and the
|
||||
server. Do not use the sample token from the shipped config.
|
||||
|
||||
```bash
|
||||
openssl rand -hex 16 # prints 32 hex characters
|
||||
```
|
||||
|
||||
### 3. TLS certificate (if `tlsEnable: true`)
|
||||
|
||||
The server needs a certificate and key. A self-signed pair is enough when
|
||||
`tlsVerifyPeer` is `false`:
|
||||
|
||||
```bash
|
||||
sudo openssl req -x509 -newkey rsa:2048 -nodes -days 3650 \
|
||||
-subj "/CN=example.com" \
|
||||
-keyout /etc/nipovpn/server.key -out /etc/nipovpn/server.crt
|
||||
```
|
||||
|
||||
### 4. Run the server
|
||||
|
||||
On the server, set `server.listenIp`/`server.listenPort`, then:
|
||||
|
||||
```bash
|
||||
sudo nipovpn server /etc/nipovpn/config.yaml
|
||||
```
|
||||
|
||||
### 5. Run the agent
|
||||
|
||||
On your machine, set `agent.serverIp`/`agent.serverPort` to the server's
|
||||
address and make sure `token`, `aesEnable`, `tlsEnable` and `tunnelEnable` match
|
||||
the server. Then:
|
||||
|
||||
```bash
|
||||
sudo nipovpn agent /etc/nipovpn/config.yaml
|
||||
```
|
||||
|
||||
### 6. Point your applications at the agent
|
||||
|
||||
```bash
|
||||
# protocol: socks5
|
||||
curl --socks5-hostname 127.0.0.1:8080 https://example.com
|
||||
|
||||
# protocol: http
|
||||
curl -x http://127.0.0.1:8080 https://example.com
|
||||
```
|
||||
|
||||
Or configure the agent's address as the SOCKS5/HTTP proxy in your browser or
|
||||
operating system.
|
||||
|
||||
## Configuration reference
|
||||
|
||||
The sample config lives at [nipovpn/etc/nipovpn/config.yaml](nipovpn/etc/nipovpn/config.yaml).
|
||||
Settings marked **must match** have to be the same on agent and server.
|
||||
|
||||
### `general`
|
||||
|
||||
| Key | Type | Default | Description |
|
||||
|---|---|---|---|
|
||||
| `token` | string | — | Shared secret, ≥ 32 bytes when `aesEnable` is on. The AES key is derived from it. **Must match.** |
|
||||
| `aesEnable` | bool | `true` | AES-256-GCM payload encryption. **Must match.** |
|
||||
| `protocol` | `http` \| `socks5` | — | Protocol the agent accepts from local applications. |
|
||||
| `bufferSize` | 1–65536 | `65536` | Maximum bytes read per operation. |
|
||||
| `fakeUrls` | list | — | Hosts used at random for the decoy `Host` header and TLS SNI. |
|
||||
| `methods` | list | — | HTTP methods used at random for decoy requests. |
|
||||
| `endPoints` | list | — | URL paths used at random for decoy requests (`/api`, `/login`, ...). |
|
||||
| `timeout` | seconds | `10` | I/O timeout for stalled connections. `0` disables it. |
|
||||
| `pullTimeout` | milliseconds | `1` | Base polling interval in polling mode. |
|
||||
| `tunnelEnable` | bool | `false` | `true` = direct tunnel mode, `false` = polling mode. **Must match.** |
|
||||
| `connectionReuse` | bool | `false` | Reuse one keep-alive connection between agent and server. |
|
||||
| `tlsEnable` | bool | `false` | TLS between agent and server. **Must match.** |
|
||||
| `tlsVerifyPeer` | bool | `false` | Agent verifies the server certificate. |
|
||||
| `tlsCertFile` | path | — | Server certificate (PEM, chain allowed). |
|
||||
| `tlsKeyFile` | path | — | Server private key (PEM). |
|
||||
| `tlsCaFile` | path | — | CA file the agent uses when `tlsVerifyPeer` is on. |
|
||||
|
||||
### `log`
|
||||
|
||||
| Key | Default | Description |
|
||||
|---|---|---|
|
||||
| `logLevel` | `INFO` | `INFO`, `TRACE` or `DEBUG`. Errors are always logged. |
|
||||
| `logFile` | — | Log file path. The directory and file must exist. |
|
||||
|
||||
### `server`
|
||||
|
||||
| Key | Default | Description |
|
||||
|---|---|---|
|
||||
| `threads` | `2` | Worker threads. |
|
||||
| `listenIp` | `127.0.0.1` | IPv4 address to listen on. |
|
||||
| `listenPort` | `8080` | Port to listen on (443 is a good choice to blend in). |
|
||||
|
||||
### `agent`
|
||||
|
||||
| Key | Default | Description |
|
||||
|---|---|---|
|
||||
| `threads` | `2` | Worker threads. |
|
||||
| `listenIp` | `127.0.0.1` | IPv4 address for local applications to connect to. |
|
||||
| `listenPort` | `8080` | Port for local applications. |
|
||||
| `serverIp` | `127.0.0.1` | IPv4 address of the NipoVPN server. |
|
||||
| `serverPort` | `8080` | Port of the NipoVPN server. |
|
||||
| `httpVersion` | `1.1` | HTTP version in decoy requests. |
|
||||
| `userAgent` | `NipoAgent` | `User-Agent` header in decoy requests. |
|
||||
|
||||
## Security notes
|
||||
|
||||
- **Change the token.** The sample token is public; the program logs a warning
|
||||
if it is still in use.
|
||||
- **Turn on at least one of `aesEnable` and `tlsEnable`.** Without either,
|
||||
traffic is only obfuscated, not encrypted.
|
||||
- **Direct tunnel mode** sends tunneled bytes without the decoy framing or AES,
|
||||
so pair it with `tlsEnable: true`.
|
||||
- **`tlsVerifyPeer: false`** protects against passive observers but not against
|
||||
an active man-in-the-middle. Enable it with a proper `tlsCaFile` if that
|
||||
matters to you. AES-GCM with a strong token still authenticates the payload.
|
||||
- **Listening on `0.0.0.0` on the agent** exposes your proxy to the local
|
||||
network. Use `127.0.0.1` unless you mean to share it.
|
||||
|
||||
> **Protocol change:** this version uses AES-256-GCM and carries the session and
|
||||
> action inside the encrypted body instead of `X-Nipo-*` headers. It is not
|
||||
> compatible with older agents, servers or the Android app; upgrade all of them
|
||||
> together.
|
||||
|
||||
## Logging
|
||||
|
||||
Log lines look like:
|
||||
|
||||
```
|
||||
2026-01-01_12:00:00 [AGENT] [INFO] [<session-uuid>] [CONNECT] [SRC 127.0.0.1:51234] [ORIGIN example.com:443]
|
||||
```
|
||||
|
||||
- `INFO`: startup, effective configuration (token hidden), connections opened.
|
||||
- `TRACE`: adds the destination of every forwarded request.
|
||||
- `DEBUG`: adds handshake, encryption and byte-level details. Use only for
|
||||
troubleshooting.
|
||||
|
||||
```bash
|
||||
tail -f /var/log/nipovpn/nipovpn.log
|
||||
journalctl -u nipovpn-server.service -f
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Likely cause |
|
||||
|---|---|
|
||||
| `Configuration validation failed: ...` | A required key is missing or invalid; the message names the block. |
|
||||
| `token must be at least 32 bytes when aesEnable is true` | Use a longer token (`openssl rand -hex 16`). |
|
||||
| `Error opening log file` | Create the log directory and file (see Quick start). |
|
||||
| Server logs `Decryption Failed` / `Invalid Envelope` | `token`, `aesEnable` or NipoVPN versions differ between agent and server. |
|
||||
| Agent logs `[TLS] [ERROR]` | `tlsEnable` differs between the two sides, or the certificate/key path is wrong. |
|
||||
| `[CONNECT] [ERROR] [To Server]` | Agent cannot reach `serverIp:serverPort` (firewall, wrong address, server not running). |
|
||||
|
||||
## Contribution
|
||||
To contribute take a look at [contribution page](https://github.com/MortezaBashsiz/nipovpn/blob/main/CONTRIBUTING.md).
|
||||
|
||||
## Build
|
||||
See the [contribution guide](CONTRIBUTING.md). In short: branch from `dev`,
|
||||
format with `scripts/format.sh`, build and test, and open a pull request against
|
||||
`dev`.
|
||||
|
||||
Build from source for [Linux](guides/BuildLinux.md)
|
||||
## License
|
||||
|
||||
|
||||
|
||||
## Run
|
||||
|
||||
#### Create directories
|
||||
Create the log directory and log file
|
||||
```bash
|
||||
[~/nipovpn]>$ sudo mkdir /var/log/nipovpn/
|
||||
[~/nipovpn]>$ sudo touch /var/log/nipovpn/nipovpn.log
|
||||
```
|
||||
|
||||
Run it
|
||||
```bash
|
||||
sudo build/core/nipovpn server nipovpn/etc/nipovpn/config.yaml
|
||||
```
|
||||
|
||||
### Package
|
||||
|
||||
#### Install
|
||||
Currently it is only available for debian-based Linuxes and fully tested on ubuntu 24.04
|
||||
You can simply download and install the package. To download it please visit the [releases page](https://github.com/MortezaBashsiz/nipovpn/tags) and get the latest release.
|
||||
```bash
|
||||
[~]>$ sudo apt install ./nipovpn.deb
|
||||
```
|
||||
|
||||
#### Run
|
||||
There are systemd services to manage the nipovpn process.
|
||||
`nipovpn-server.service` to manage as server.
|
||||
`nipovpn-agent.service` to manage as agent.
|
||||
```bash
|
||||
[~]>$ sudo systemctl start nipovpn-server.service
|
||||
[~]>$ cat /var/log/nipovpn/nipovpn.log
|
||||
```
|
||||
NipoVPN is released under the [GNU General Public License v3.0](LICENSE).
|
||||
@@ -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()
|
||||
+90
-112
@@ -1,86 +1,34 @@
|
||||
#include "agenthandler.hpp"
|
||||
|
||||
/**
|
||||
* @brief Constructs an `AgentHandler` instance with the required buffers, configuration,
|
||||
* logging, client connection, and session identifier.
|
||||
*
|
||||
* @details
|
||||
* - Initializes internal references to the read and write buffers.
|
||||
* - Stores shared references to the configuration and logging objects.
|
||||
* - Stores the associated `TCPClient` instance used for server communication.
|
||||
* - Creates an `HTTP` helper object for parsing and generating HTTP messages.
|
||||
* - Saves the client connection string and UUID for logging and tracking purposes.
|
||||
* - Sets the initial state flags:
|
||||
* - `end_` is initialized to `false`, indicating processing is not finished.
|
||||
* - `connect_` is initialized to `false`, indicating that no CONNECT tunnel is active.
|
||||
*
|
||||
* @param readBuffer Reference to the stream buffer used for reading incoming client data.
|
||||
* @param writeBuffer Reference to the stream buffer used for storing outgoing response data.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param client Shared pointer to the `TCPClient` used for communication with the remote server.
|
||||
* @param clientConnStr String describing the client connection source.
|
||||
* @param uuid Unique identifier for this handler session, represented as a Boost UUID.
|
||||
*/
|
||||
#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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Destroys the `AgentHandler` instance.
|
||||
*
|
||||
* @details
|
||||
* - Performs no additional cleanup explicitly.
|
||||
* - Resource lifetime is managed by referenced objects and smart pointers.
|
||||
*/
|
||||
AgentHandler::~AgentHandler() {}
|
||||
|
||||
/**
|
||||
* @brief Handles a client request by encrypting it, forwarding it to the agent server,
|
||||
* and processing the server response.
|
||||
*
|
||||
* @details
|
||||
* - Ensures thread-safe execution using an internal mutex.
|
||||
* - Reads the incoming request data from `readBuffer_` and encrypts it using AES-256.
|
||||
* - Encodes the encrypted payload with Base64 and wraps it into an HTTP POST request.
|
||||
* - Detects the type of the original HTTP request before forwarding it.
|
||||
* - Logs connection details when a valid HTTP target is available.
|
||||
* - Initializes TLS on the client connection when enabled in the configuration.
|
||||
* - Establishes a TCP connection to the configured server if one is not already open.
|
||||
* - Performs a TLS handshake when TLS is active on the client connection.
|
||||
* - Sends the generated HTTP request to the remote server and reads the response.
|
||||
* - Handles CONNECT requests specially by forwarding the raw response directly.
|
||||
* - Parses normal HTTP responses, decrypts their body content, and writes the
|
||||
* decrypted result into `writeBuffer_`.
|
||||
* - On any failure during encryption, connection, parsing, decryption, or I/O,
|
||||
* the client socket is shut down and processing stops.
|
||||
*
|
||||
* @note
|
||||
* - For CONNECT requests, the method does not decrypt the response body and instead
|
||||
* forwards the raw response stream directly to the write buffer.
|
||||
* - The `connect_` flag is updated when a connection or CONNECT tunnel is established.
|
||||
*/
|
||||
void AgentHandler::handle() {
|
||||
std::lock_guard lock(mutex_);
|
||||
|
||||
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();
|
||||
@@ -88,19 +36,16 @@ void AgentHandler::handle() {
|
||||
}
|
||||
|
||||
if (request_->parsedHttpRequest().target().length() > 0) {
|
||||
log_->write("[" + to_string(uuid_) + "] [FORWARD] [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;
|
||||
@@ -108,56 +53,71 @@ 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;
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) + "] [CONNECT] [SRC " +
|
||||
clientConnStr_ + "] [ORIGIN " + std::string(request_->parsedHttpRequest().target()) + "]",
|
||||
Log::Level::INFO);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
const std::string innerRequest = streambufToString(readBuffer_);
|
||||
const std::string action =
|
||||
request_->httpType() == HTTP::HttpType::connect ? "open" : "request";
|
||||
|
||||
std::string hostHeader = config_->general().fakeUrl;
|
||||
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);
|
||||
BoolStr encryption{false, std::string("FAILED")};
|
||||
const std::string payload =
|
||||
makeEnvelope(action, to_string(uuid_), hexStreambufToStr(readBuffer_));
|
||||
encryption = config_->general().aesEnable
|
||||
? aes256Encrypt(payload, config_->general().token)
|
||||
: BoolStr{true, payload};
|
||||
if (!encryption.ok) {
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Encryption Failed] : [ " +
|
||||
encryption.message + "] ",
|
||||
Log::Level::DEBUG);
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string innerRequest = encode64(encryption.message);
|
||||
|
||||
std::ostringstream outer;
|
||||
outer << "POST /relay HTTP/1.1\r\n"
|
||||
<< "Host: " << hostHeader << "\r\n"
|
||||
<< "User-Agent: Mozilla/5.0\r\n"
|
||||
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/octet-stream\r\n"
|
||||
<< "Content-Type: text/plain; charset=utf-8\r\n"
|
||||
<< "Content-Length: " << innerRequest.size() << "\r\n"
|
||||
<< "Connection: keep-alive\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) {
|
||||
if (client_->readBuffer().size() == 0 && !config_->general().connectionReuse) {
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
@@ -165,26 +125,44 @@ void AgentHandler::handle() {
|
||||
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] : " +
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [NOT HTTP Response] [Response] : " +
|
||||
outerResponse,
|
||||
Log::Level::DEBUG);
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string innerResponse = outerResponse.substr(bodyPos + 4);
|
||||
|
||||
// CONNECT: the outer response body itself is the proxy response to the browser,
|
||||
// usually "HTTP/1.1 200 Connection Established\r\n\r\n".
|
||||
if (request_->httpType() == HTTP::HttpType::connect) {
|
||||
copyStringToStreambuf(innerResponse, writeBuffer_);
|
||||
connect_ = true;
|
||||
end_ = false;
|
||||
const std::string responseBody = outerResponse.substr(bodyPos + 4);
|
||||
if (responseBody.empty()) {
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
copyStringToStreambuf(innerResponse, writeBuffer_);
|
||||
connect_ = false;
|
||||
BoolStr decryption{false, std::string("FAILED")};
|
||||
decryption = config_->general().aesEnable
|
||||
? aes256Decrypt(responseBody, config_->general().token)
|
||||
: BoolStr{true, responseBody};
|
||||
if (!decryption.ok) {
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Decryption Failed] : [ " +
|
||||
decryption.message + "] ",
|
||||
Log::Level::DEBUG);
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
copyStringToStreambuf(decryption.message, writeBuffer_);
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Payload Decoded]",
|
||||
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;
|
||||
}
|
||||
+18
-94
@@ -9,126 +9,50 @@
|
||||
#include "log.hpp"
|
||||
#include "tcpclient.hpp"
|
||||
|
||||
/**
|
||||
* @brief The `AgentHandler` class manages communication between the client and the agent server.
|
||||
*
|
||||
* @details
|
||||
* - Responsible for processing incoming client requests and forwarding them to the agent server.
|
||||
* - Handles encryption, HTTP request generation, and response processing.
|
||||
* - Maintains connection state and supports both normal HTTP and CONNECT tunneling.
|
||||
* - Uses Boost.Asio stream buffers for efficient I/O operations.
|
||||
* - Ensures thread safety using an internal mutex.
|
||||
* - Integrates with external components such as configuration, logging, and TCP client handling.
|
||||
*
|
||||
* @note
|
||||
* - Inherits from `Uncopyable` to prevent accidental copying.
|
||||
* - Uses shared ownership via `std::shared_ptr` (see `pointer` alias).
|
||||
* - Instances must be created using the `create` factory method.
|
||||
*/
|
||||
|
||||
class AgentHandler : private Uncopyable {
|
||||
public:
|
||||
using pointer = std::shared_ptr<AgentHandler>;
|
||||
|
||||
/**
|
||||
* @brief Factory method to create a new `AgentHandler` instance.
|
||||
*
|
||||
* @details
|
||||
* - Wraps object construction in a `std::shared_ptr`.
|
||||
* - Ensures consistent creation and ownership semantics.
|
||||
*
|
||||
* @param readBuffer Reference to the stream buffer used for reading client data.
|
||||
* @param writeBuffer Reference to the stream buffer used for writing response data.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param client Shared pointer to the `TCPClient` managing server communication.
|
||||
* @param clientConnStr String describing the client connection source.
|
||||
* @param uuid Unique identifier for this handler instance.
|
||||
* @return A shared pointer to the created `AgentHandler`.
|
||||
*/
|
||||
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));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Destructor for `AgentHandler`.
|
||||
*
|
||||
* @details
|
||||
* - Default destructor; resource management is handled by smart pointers and references.
|
||||
*/
|
||||
~AgentHandler();
|
||||
|
||||
/**
|
||||
* @brief Processes a client request and communicates with the agent server.
|
||||
*
|
||||
* @details
|
||||
* - Encrypts incoming data.
|
||||
* - Builds and sends an HTTP request to the agent server.
|
||||
* - Receives, parses, and decrypts the server response.
|
||||
* - Handles CONNECT tunneling and normal HTTP flows.
|
||||
*/
|
||||
void handle();
|
||||
|
||||
/**
|
||||
* @brief Provides access to the associated HTTP request object.
|
||||
*
|
||||
* @return A const reference to the HTTP request pointer.
|
||||
*/
|
||||
inline const HTTP::pointer &request() & { return request_; }
|
||||
inline const HTTP::pointer &request() const { return request_; }
|
||||
|
||||
/**
|
||||
* @brief Provides rvalue access to the HTTP request object.
|
||||
*
|
||||
* @details
|
||||
* - Enables move semantics when transferring ownership.
|
||||
*
|
||||
* @return An rvalue reference to the HTTP request pointer.
|
||||
*/
|
||||
inline const HTTP::pointer &&request() && { return std::move(request_); }
|
||||
|
||||
bool end_; ///< Indicates whether processing has completed.
|
||||
bool connect_;///< Indicates whether a CONNECT tunnel or server connection is active.
|
||||
bool end_;
|
||||
bool connect_;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Constructs an `AgentHandler` instance.
|
||||
*
|
||||
* @details
|
||||
* - Initializes buffers, configuration, logging, and client references.
|
||||
* - Creates the internal HTTP request handler.
|
||||
* - Stores connection metadata and unique identifier.
|
||||
*
|
||||
* @param readBuffer Reference to the input stream buffer.
|
||||
* @param writeBuffer Reference to the output stream buffer.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param client Shared pointer to the TCP client.
|
||||
* @param clientConnStr Client connection description string.
|
||||
* @param uuid Unique identifier for this handler instance.
|
||||
*/
|
||||
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_;///< Reference to the configuration object.
|
||||
const std::shared_ptr<Log> &log_; ///< Reference to the logging object.
|
||||
const TCPClient::pointer &client_; ///< Reference to the TCP client.
|
||||
boost::asio::streambuf &readBuffer_; ///< Buffer for incoming client data.
|
||||
boost::asio::streambuf &writeBuffer_; ///< Buffer for outgoing response data.
|
||||
HTTP::pointer request_; ///< HTTP request handler instance.
|
||||
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 used to ensure thread-safe operations.
|
||||
std::mutex mutex_;
|
||||
};
|
||||
+131
-129
@@ -1,23 +1,7 @@
|
||||
#include "config.hpp"
|
||||
|
||||
/**
|
||||
* @brief Constructs a `Config` instance by loading and parsing a YAML configuration file.
|
||||
*
|
||||
* @details
|
||||
* - Loads the YAML configuration from the provided file path.
|
||||
* - Initializes all configuration sections (`general_`, `log_`, `server_`, `agent_`)
|
||||
* directly from the parsed YAML structure.
|
||||
* - Sets default runtime values for threads, listen IP, and port.
|
||||
* - Based on the selected `RunMode`, initializes runtime parameters:
|
||||
* - `threads_`
|
||||
* - `listenIp_`
|
||||
* - `listenPort_`
|
||||
* - Ensures thread-safe initialization using a mutex lock.
|
||||
*
|
||||
* @param mode Runtime mode (server or agent).
|
||||
* @param filePath Path to the YAML configuration file.
|
||||
*/
|
||||
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)),
|
||||
@@ -25,36 +9,36 @@ 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"]["timeout"].as<unsigned short>(),
|
||||
configYaml_["general"]["chunkHeader"].as<std::string>()}),
|
||||
log_({configYaml_["log"]["logLevel"].as<std::string>(),
|
||||
configYaml_["general"]["protocol"].as<std::string>(""),
|
||||
configYaml_["general"]["bufferSize"].as<unsigned int>(65536),
|
||||
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>(10),
|
||||
configYaml_["general"]["pullTimeout"].as<unsigned short>(1),
|
||||
configYaml_["general"]["tunnelEnable"].as<bool>(false),
|
||||
configYaml_["general"]["connectionReuse"].as<bool>(false),
|
||||
configYaml_["general"]["aesEnable"].as<bool>(true),
|
||||
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>("INFO"),
|
||||
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>("")}),
|
||||
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>("")}) {
|
||||
server_({configYaml_["server"]["threads"].as<unsigned short>(2),
|
||||
configYaml_["server"]["listenIp"].as<std::string>("127.0.0.1"),
|
||||
configYaml_["server"]["listenPort"].as<unsigned short>(8080)}),
|
||||
agent_({configYaml_["agent"]["threads"].as<unsigned short>(2),
|
||||
configYaml_["agent"]["listenIp"].as<std::string>("127.0.0.1"),
|
||||
configYaml_["agent"]["listenPort"].as<unsigned short>(8080),
|
||||
configYaml_["agent"]["serverIp"].as<std::string>("127.0.0.1"),
|
||||
configYaml_["agent"]["serverPort"].as<unsigned short>(8080),
|
||||
configYaml_["agent"]["httpVersion"].as<std::string>("1.1"),
|
||||
configYaml_["agent"]["userAgent"].as<std::string>("NipoAgent")}) {
|
||||
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
|
||||
/**
|
||||
* @brief Initializes runtime parameters based on the selected run mode.
|
||||
*/
|
||||
switch (runMode_) {
|
||||
case RunMode::server:
|
||||
threads_ = server_.threads;
|
||||
@@ -70,16 +54,6 @@ Config::Config(const RunMode &mode, const std::string &filePath)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Copy constructor that creates a new `Config` instance from an existing one.
|
||||
*
|
||||
* @details
|
||||
* - Copies all configuration sections and runtime parameters.
|
||||
* - Reloads the YAML configuration from the original file path.
|
||||
* - Preserves the runtime mode and all derived values.
|
||||
*
|
||||
* @param config Shared pointer to the existing configuration.
|
||||
*/
|
||||
Config::Config(const Config::pointer &config)
|
||||
: runMode_(config->runMode()),
|
||||
filePath_(config->filePath()),
|
||||
@@ -92,163 +66,143 @@ Config::Config(const Config::pointer &config)
|
||||
server_(config->server()),
|
||||
agent_(config->agent()) {}
|
||||
|
||||
/**
|
||||
* @brief Destructor for `Config`.
|
||||
*
|
||||
* @details
|
||||
* - Defaulted destructor; no explicit resource cleanup required.
|
||||
*/
|
||||
Config::~Config() = default;
|
||||
|
||||
/**
|
||||
* @brief Converts the configuration into a human-readable string.
|
||||
*
|
||||
* @details
|
||||
* - Serializes all configuration sections into a formatted string.
|
||||
* - Includes General, Log, Server, and Agent sections.
|
||||
* - Useful for debugging and logging configuration state.
|
||||
*
|
||||
* @return A formatted string representation of the configuration.
|
||||
*/
|
||||
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"
|
||||
<< " token: " << (general_.token.empty() ? "" : "<hidden>") << "\n"
|
||||
<< " protocol: " << general_.protocol << "\n"
|
||||
<< " bufferSize: " << general_.bufferSize << "\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"
|
||||
<< " aesEnable: " << std::boolalpha << general_.aesEnable << "\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"
|
||||
<< " 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();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the General configuration section.
|
||||
*/
|
||||
const Config::General &Config::general() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return general_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the Log configuration section.
|
||||
*/
|
||||
const Config::Log &Config::log() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return log_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the Server configuration section.
|
||||
*/
|
||||
const Config::Server &Config::server() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return server_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the Agent configuration section.
|
||||
*/
|
||||
const Config::Agent &Config::agent() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return agent_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Gets the current thread count.
|
||||
*/
|
||||
const unsigned short &Config::threads() const {
|
||||
unsigned short Config::threads() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return threads_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sets the thread count at runtime.
|
||||
*/
|
||||
void Config::threads(unsigned short threads) {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
threads_ = threads;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Gets the listening IP address.
|
||||
*/
|
||||
const std::string &Config::listenIp() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return listenIp_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sets the listening IP address at runtime.
|
||||
*/
|
||||
void Config::listenIp(const std::string &ip) {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
listenIp_ = ip;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Gets the listening port.
|
||||
*/
|
||||
const unsigned short &Config::listenPort() const {
|
||||
unsigned short Config::listenPort() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return listenPort_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sets the listening port at runtime.
|
||||
*/
|
||||
void Config::listenPort(unsigned short port) {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
listenPort_ = port;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the current runtime mode.
|
||||
*/
|
||||
const RunMode &Config::runMode() const {
|
||||
RunMode Config::runMode() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return runMode_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the configuration file path.
|
||||
*/
|
||||
const std::string &Config::filePath() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return filePath_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts the runtime mode to a string.
|
||||
*
|
||||
* @return "server" or "agent" depending on the current mode.
|
||||
*/
|
||||
std::string Config::modeToString() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
|
||||
@@ -260,4 +214,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)];
|
||||
}
|
||||
+52
-155
@@ -4,219 +4,116 @@
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <random>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "general.hpp"
|
||||
|
||||
/**
|
||||
* @brief Defines the runtime mode of the application.
|
||||
*
|
||||
* @details
|
||||
* - `server`: Runs in server mode, accepting incoming client connections.
|
||||
* - `agent`: Runs in agent mode, forwarding traffic to a remote server.
|
||||
*/
|
||||
enum class RunMode {
|
||||
server,
|
||||
agent
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief The `Config` class manages application configuration loaded from a YAML file.
|
||||
*
|
||||
* @details
|
||||
* - Responsible for parsing and storing configuration values.
|
||||
* - Provides structured access to configuration sections:
|
||||
* - General
|
||||
* - Log
|
||||
* - Server
|
||||
* - Agent
|
||||
* - Ensures thread-safe access to mutable runtime parameters.
|
||||
* - Supports both server and agent runtime modes.
|
||||
*
|
||||
* @note
|
||||
* - Inherits from `Uncopyable` to prevent unintended copying.
|
||||
* - Uses shared ownership via `std::shared_ptr` (see `pointer` alias).
|
||||
* - Configuration values are primarily immutable after initialization,
|
||||
* except for selected runtime-adjustable parameters.
|
||||
*/
|
||||
class Config : private Uncopyable {
|
||||
private:
|
||||
/**
|
||||
* @brief General configuration section.
|
||||
*
|
||||
* @details
|
||||
* - Contains global settings shared across components.
|
||||
*/
|
||||
struct General {
|
||||
std::string token; ///< Shared secret used for encryption/decryption.
|
||||
std::string fakeUrl; ///< Fake URL used for obfuscation.
|
||||
std::string method; ///< HTTP method used for requests.
|
||||
unsigned short timeout; ///< Network timeout in seconds.
|
||||
std::string chunkHeader;///< Custom header for chunked communication.
|
||||
std::string token;
|
||||
std::string protocol;
|
||||
unsigned int bufferSize;
|
||||
std::vector<std::string> fakeUrls;
|
||||
std::vector<std::string> methods;
|
||||
std::vector<std::string> endPoints;
|
||||
unsigned short timeout;
|
||||
unsigned short pullTimeout;
|
||||
bool tunnelEnable;
|
||||
bool connectionReuse;
|
||||
bool aesEnable;
|
||||
bool tlsEnable;
|
||||
bool tlsVerifyPeer;
|
||||
std::string tlsCertFile;
|
||||
std::string tlsKeyFile;
|
||||
std::string tlsCaFile;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Logging configuration section.
|
||||
*/
|
||||
struct Log {
|
||||
std::string level;///< Log level (e.g., DEBUG, INFO, ERROR).
|
||||
std::string file; ///< Output file path for logs.
|
||||
std::string level;
|
||||
std::string file;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Server configuration section.
|
||||
*
|
||||
* @details
|
||||
* - Defines listening parameters and TLS settings for server mode.
|
||||
*/
|
||||
struct Server {
|
||||
unsigned short threads; ///< Number of worker threads.
|
||||
std::string listenIp; ///< IP address to bind.
|
||||
unsigned short listenPort;///< Port to listen on.
|
||||
|
||||
bool tlsEnable; ///< Enables TLS for incoming connections.
|
||||
bool tlsVerifyPeer; ///< Enables peer certificate verification.
|
||||
std::string tlsCertFile;///< Path to TLS certificate file.
|
||||
std::string tlsKeyFile; ///< Path to TLS private key file.
|
||||
std::string tlsCaFile; ///< Path to CA certificate file.
|
||||
unsigned short threads;
|
||||
std::string listenIp;
|
||||
unsigned short listenPort;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Agent configuration section.
|
||||
*
|
||||
* @details
|
||||
* - Defines client-side behavior and remote server connection settings.
|
||||
*/
|
||||
struct Agent {
|
||||
unsigned short threads; ///< Number of worker threads.
|
||||
std::string listenIp; ///< Local listening IP address.
|
||||
unsigned short listenPort;///< Local listening port.
|
||||
std::string serverIp; ///< Remote server IP address.
|
||||
unsigned short serverPort;///< Remote server port.
|
||||
std::string httpVersion; ///< HTTP version used for requests.
|
||||
std::string userAgent; ///< User-Agent header value.
|
||||
|
||||
bool tlsEnable; ///< Enables TLS for outbound connections.
|
||||
bool tlsVerifyPeer; ///< Enables server certificate verification.
|
||||
std::string tlsCaFile;///< Path to CA certificate file.
|
||||
unsigned short threads;
|
||||
std::string listenIp;
|
||||
unsigned short listenPort;
|
||||
std::string serverIp;
|
||||
unsigned short serverPort;
|
||||
std::string httpVersion;
|
||||
std::string userAgent;
|
||||
};
|
||||
|
||||
const RunMode &runMode_; ///< Current runtime mode.
|
||||
std::string filePath_; ///< Path to the configuration file.
|
||||
const YAML::Node configYaml_;///< Parsed YAML configuration root.
|
||||
RunMode runMode_;
|
||||
std::string filePath_;
|
||||
YAML::Node configYaml_;
|
||||
|
||||
unsigned short threads_; ///< Runtime thread count.
|
||||
std::string listenIp_; ///< Runtime listening IP.
|
||||
unsigned short listenPort_;///< Runtime listening port.
|
||||
unsigned short threads_;
|
||||
std::string listenIp_;
|
||||
unsigned short listenPort_;
|
||||
|
||||
mutable std::mutex configMutex_;///< Mutex for thread-safe runtime updates.
|
||||
mutable std::mutex configMutex_;
|
||||
|
||||
/**
|
||||
* @brief Private constructor for initializing configuration from file.
|
||||
*
|
||||
* @param mode Runtime mode (server or agent).
|
||||
* @param filePath Path to the YAML configuration file.
|
||||
*/
|
||||
explicit Config(const RunMode &mode, const std::string &filePath);
|
||||
explicit Config(RunMode mode, const std::string &filePath);
|
||||
|
||||
public:
|
||||
using pointer = std::shared_ptr<Config>;
|
||||
|
||||
/**
|
||||
* @brief Factory method to create a new `Config` instance.
|
||||
*
|
||||
* @param mode Runtime mode.
|
||||
* @param filePath Path to the configuration file.
|
||||
* @return Shared pointer to the created `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));
|
||||
}
|
||||
|
||||
const General general_;///< General configuration section.
|
||||
const Log log_; ///< Logging configuration section.
|
||||
const Server server_; ///< Server configuration section.
|
||||
const Agent agent_; ///< Agent configuration section.
|
||||
const General general_;
|
||||
const Log log_;
|
||||
const Server server_;
|
||||
const Agent agent_;
|
||||
|
||||
/**
|
||||
* @brief Copy constructor from shared pointer.
|
||||
*
|
||||
* @param config Existing configuration instance.
|
||||
*/
|
||||
explicit Config(const Config::pointer &config);
|
||||
|
||||
/**
|
||||
* @brief Destructor for `Config`.
|
||||
*/
|
||||
~Config();
|
||||
|
||||
/// @name Section Accessors
|
||||
/// @{
|
||||
|
||||
const General &general() const;
|
||||
const Log &log() const;
|
||||
const Server &server() const;
|
||||
const Agent &agent() const;
|
||||
|
||||
/// @}
|
||||
unsigned short threads() const;
|
||||
|
||||
/// @name Runtime Configuration Accessors
|
||||
/// @{
|
||||
|
||||
/**
|
||||
* @brief Gets the current thread count.
|
||||
*/
|
||||
const unsigned short &threads() const;
|
||||
|
||||
/**
|
||||
* @brief Sets the thread count.
|
||||
*/
|
||||
void threads(unsigned short threads);
|
||||
|
||||
/**
|
||||
* @brief Gets the listening IP address.
|
||||
*/
|
||||
const std::string &listenIp() const;
|
||||
|
||||
/**
|
||||
* @brief Sets the listening IP address.
|
||||
*/
|
||||
void listenIp(const std::string &ip);
|
||||
|
||||
/**
|
||||
* @brief Gets the listening port.
|
||||
*/
|
||||
const unsigned short &listenPort() const;
|
||||
unsigned short listenPort() const;
|
||||
|
||||
/**
|
||||
* @brief Sets the listening port.
|
||||
*/
|
||||
void listenPort(unsigned short port);
|
||||
|
||||
/// @}
|
||||
RunMode runMode() const;
|
||||
|
||||
/**
|
||||
* @brief Gets the current runtime mode.
|
||||
*/
|
||||
const RunMode &runMode() const;
|
||||
|
||||
/**
|
||||
* @brief Gets the configuration file path.
|
||||
*/
|
||||
const std::string &filePath() const;
|
||||
|
||||
/**
|
||||
* @brief Converts the runtime mode to a string representation.
|
||||
*
|
||||
* @return String representation of the mode.
|
||||
*/
|
||||
std::string modeToString() const;
|
||||
|
||||
/**
|
||||
* @brief Converts the full configuration into a human-readable string.
|
||||
*
|
||||
* @return Serialized configuration string.
|
||||
*/
|
||||
std::string toString() const;
|
||||
|
||||
std::string randomFakeUrl() const;
|
||||
|
||||
std::string randomMethod() const;
|
||||
|
||||
std::string randomEndPoint() const;
|
||||
};
|
||||
+124
-231
@@ -19,18 +19,15 @@
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
/**
|
||||
* @brief Base class used to disable copy construction and copy assignment.
|
||||
*
|
||||
* @details
|
||||
* - Intended to be inherited privately by classes that must not be copied.
|
||||
* - Keeps the default constructor available.
|
||||
* - Deletes copy constructor and copy assignment operator.
|
||||
*/
|
||||
static constexpr std::size_t BufferSize = 65536;
|
||||
static constexpr std::size_t MinTokenLength = 32;
|
||||
static constexpr const char *SampleToken = "af445adb-2434-4975-9445-2c1b2231";
|
||||
|
||||
class Uncopyable {
|
||||
public:
|
||||
Uncopyable() = default;
|
||||
@@ -40,62 +37,26 @@ private:
|
||||
Uncopyable &operator=(const Uncopyable &) = delete;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Prints a message to standard output.
|
||||
*
|
||||
* @details
|
||||
* - Intended for quick debugging output.
|
||||
* - Prefixes the message with a fixed marker.
|
||||
*
|
||||
* @param message Value to be written to `std::cout`.
|
||||
*/
|
||||
inline void OUT(const auto &message) {
|
||||
std::cout << "OUT OUT OUT OUT OUT OUT OUT OUT : " << message
|
||||
<< std::endl;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Simple result structure containing a success flag and message.
|
||||
*
|
||||
* @details
|
||||
* - Commonly used to return operation status along with an explanatory message.
|
||||
*/
|
||||
struct BoolStr {
|
||||
bool ok; ///< Indicates whether the operation succeeded.
|
||||
std::string message;///< Contains the result or error message.
|
||||
bool ok;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Checks whether a file exists.
|
||||
*
|
||||
* @param name Path to the file.
|
||||
* @return `true` if the file exists and is accessible, otherwise `false`.
|
||||
*/
|
||||
inline bool fileExists(const std::string &name) {
|
||||
std::ifstream file(name.c_str());
|
||||
return file.good();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts a Boost.Asio stream buffer into a string.
|
||||
*
|
||||
* @param buff Reference to the stream buffer.
|
||||
* @return String containing the current contents of the 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 Replaces the contents of a stream buffer with a string.
|
||||
*
|
||||
* @details
|
||||
* - Clears the destination buffer before writing the new string.
|
||||
*
|
||||
* @param inputStr Source string to copy into the buffer.
|
||||
* @param buff Destination stream buffer.
|
||||
*/
|
||||
inline void copyStringToStreambuf(const std::string &inputStr,
|
||||
boost::asio::streambuf &buff) {
|
||||
buff.consume(buff.size());
|
||||
@@ -103,16 +64,6 @@ inline void copyStringToStreambuf(const std::string &inputStr,
|
||||
os << inputStr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Moves all data from one stream buffer to another.
|
||||
*
|
||||
* @details
|
||||
* - Copies the source buffer contents into the target buffer.
|
||||
* - Consumes all data from the source buffer after copying.
|
||||
*
|
||||
* @param source Source stream buffer.
|
||||
* @param target Target stream buffer.
|
||||
*/
|
||||
inline void moveStreambuf(boost::asio::streambuf &source,
|
||||
boost::asio::streambuf &target) {
|
||||
auto bytes_copied =
|
||||
@@ -121,15 +72,6 @@ inline void moveStreambuf(boost::asio::streambuf &source,
|
||||
source.consume(source.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Copies all data from one stream buffer to another.
|
||||
*
|
||||
* @details
|
||||
* - Leaves the source buffer unchanged.
|
||||
*
|
||||
* @param source Source stream buffer.
|
||||
* @param target Target stream buffer.
|
||||
*/
|
||||
inline void copyStreambuf(boost::asio::streambuf &source,
|
||||
boost::asio::streambuf &target) {
|
||||
auto bytes_copied =
|
||||
@@ -137,13 +79,6 @@ inline void copyStreambuf(boost::asio::streambuf &source,
|
||||
target.commit(bytes_copied);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts a byte array to its hexadecimal string representation.
|
||||
*
|
||||
* @param data Pointer to the input byte array.
|
||||
* @param size Number of bytes in the array.
|
||||
* @return Lowercase hexadecimal string representation of the input.
|
||||
*/
|
||||
inline std::string hexArrToStr(const unsigned char *data, std::size_t size) {
|
||||
std::stringstream tempStr;
|
||||
tempStr << std::hex << std::setfill('0');
|
||||
@@ -155,29 +90,13 @@ inline std::string hexArrToStr(const unsigned char *data, std::size_t size) {
|
||||
return tempStr.str();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts a hexadecimal string to an integer.
|
||||
*
|
||||
* @param hexString Hexadecimal string input.
|
||||
* @return Parsed value as an unsigned integer.
|
||||
*/
|
||||
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 a hexadecimal string into its ASCII string representation.
|
||||
*
|
||||
* @details
|
||||
* - Processes the input two characters at a time.
|
||||
* - Each hexadecimal byte is converted into its character equivalent.
|
||||
*
|
||||
* @param hex Hexadecimal string input.
|
||||
* @return Decoded ASCII string.
|
||||
*/
|
||||
inline std::string hexToASCII(const std::string &hex) {
|
||||
std::string ascii;
|
||||
|
||||
@@ -190,12 +109,6 @@ inline std::string hexToASCII(const std::string &hex) {
|
||||
return ascii;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts a hexadecimal character into its numeric value.
|
||||
*
|
||||
* @param c Input character.
|
||||
* @return Numeric value of the hexadecimal character, or `0` if invalid.
|
||||
*/
|
||||
inline unsigned char charToHex(char c) {
|
||||
if ('0' <= c && c <= '9') return c - '0';
|
||||
if ('A' <= c && c <= 'F') return c - 'A' + 10;
|
||||
@@ -203,12 +116,6 @@ inline unsigned char charToHex(char c) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts a hexadecimal string into a byte array.
|
||||
*
|
||||
* @param hexStr Hexadecimal string input.
|
||||
* @return Vector containing the decoded bytes.
|
||||
*/
|
||||
inline std::vector<unsigned char> strToHexArr(const std::string &hexStr) {
|
||||
std::vector<unsigned char> result(hexStr.size() / 2);
|
||||
|
||||
@@ -219,29 +126,12 @@ inline std::vector<unsigned char> strToHexArr(const std::string &hexStr) {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts a stream buffer into a hexadecimal string.
|
||||
*
|
||||
* @details
|
||||
* - First converts the stream buffer into a raw string.
|
||||
* - Then converts the raw bytes into a hexadecimal representation.
|
||||
*
|
||||
* @param buff Source stream buffer.
|
||||
* @return Hexadecimal string representation of the buffer contents.
|
||||
*/
|
||||
inline std::string hexStreambufToStr(const boost::asio::streambuf &buff) {
|
||||
return hexArrToStr(
|
||||
reinterpret_cast<const unsigned char *>(streambufToString(buff).c_str()),
|
||||
buff.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Splits a string using a delimiter.
|
||||
*
|
||||
* @param str Input string.
|
||||
* @param delimiter Delimiter string.
|
||||
* @return Vector containing the split parts.
|
||||
*/
|
||||
inline std::vector<std::string> splitString(const std::string &str,
|
||||
const std::string &delimiter) {
|
||||
std::vector<std::string> result;
|
||||
@@ -266,17 +156,6 @@ inline std::vector<std::string> splitString(const std::string &str,
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Decodes a Base64-encoded string.
|
||||
*
|
||||
* @details
|
||||
* - Trims trailing padding characters before decoding.
|
||||
* - Uses Boost archive iterators for Base64 decoding.
|
||||
* - Throws `std::runtime_error` if decoding fails.
|
||||
*
|
||||
* @param inputStr Base64-encoded input string.
|
||||
* @return Decoded binary string.
|
||||
*/
|
||||
inline std::string decode64(const std::string &inputStr) {
|
||||
using namespace boost::archive::iterators;
|
||||
|
||||
@@ -293,16 +172,6 @@ inline std::string decode64(const std::string &inputStr) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Encodes a string into Base64 format.
|
||||
*
|
||||
* @details
|
||||
* - Uses Boost archive iterators for Base64 encoding.
|
||||
* - Appends the required padding characters (`=`).
|
||||
*
|
||||
* @param inputStr Input string.
|
||||
* @return Base64-encoded string.
|
||||
*/
|
||||
inline std::string encode64(const std::string &inputStr) {
|
||||
using namespace boost::archive::iterators;
|
||||
|
||||
@@ -317,134 +186,131 @@ inline std::string encode64(const std::string &inputStr) {
|
||||
return encoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Encrypts a string using AES-256-CBC.
|
||||
*
|
||||
* @details
|
||||
* - Generates a random IV for each encryption operation.
|
||||
* - Prepends the IV to the encrypted output.
|
||||
* - Uses OpenSSL EVP APIs for encryption.
|
||||
*
|
||||
* @param plaintext Input plaintext string.
|
||||
* @param key Encryption key.
|
||||
* @return A `BoolStr` containing success status and encrypted data or an error message.
|
||||
*/
|
||||
static constexpr std::size_t AesGcmNonceLength = 12;
|
||||
static constexpr std::size_t AesGcmTagLength = 16;
|
||||
|
||||
inline std::string deriveAesKey(const std::string &token) {
|
||||
unsigned char digest[EVP_MAX_MD_SIZE];
|
||||
unsigned int digestLen = 0;
|
||||
EVP_Digest(token.data(), token.size(), digest, &digestLen, EVP_sha256(), NULL);
|
||||
return std::string(reinterpret_cast<char *>(digest), digestLen);
|
||||
}
|
||||
|
||||
inline BoolStr aes256Encrypt(const std::string &plaintext,
|
||||
const std::string &key) {
|
||||
const std::string &token) {
|
||||
BoolStr result{false, "Encryption failed"};
|
||||
|
||||
unsigned char iv[EVP_MAX_IV_LENGTH];
|
||||
if (!RAND_bytes(iv, sizeof(iv))) {
|
||||
result.message = "IV generation failed";
|
||||
const std::string key = deriveAesKey(token);
|
||||
|
||||
unsigned char nonce[AesGcmNonceLength];
|
||||
if (!RAND_bytes(nonce, sizeof(nonce))) {
|
||||
result.message = "Nonce generation failed";
|
||||
return result;
|
||||
}
|
||||
|
||||
int ciphertext_len =
|
||||
plaintext.size() + EVP_CIPHER_block_size(EVP_aes_256_cbc());
|
||||
std::vector<unsigned char> ciphertext(ciphertext_len);
|
||||
std::vector<unsigned char> ciphertext(plaintext.size());
|
||||
|
||||
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,
|
||||
reinterpret_cast<const unsigned char *>(key.c_str()),
|
||||
iv) != 1) {
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
if (EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, NULL, NULL) != 1 ||
|
||||
EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, AesGcmNonceLength, NULL) != 1 ||
|
||||
EVP_EncryptInit_ex(ctx.get(), NULL, NULL,
|
||||
reinterpret_cast<const unsigned char *>(key.data()),
|
||||
nonce) != 1) {
|
||||
result.message = "Encryption initialization failed";
|
||||
return result;
|
||||
}
|
||||
|
||||
int len;
|
||||
int len = 0;
|
||||
if (EVP_EncryptUpdate(
|
||||
ctx, ciphertext.data(), &len,
|
||||
reinterpret_cast<const unsigned char *>(plaintext.c_str()),
|
||||
ctx.get(), ciphertext.data(), &len,
|
||||
reinterpret_cast<const unsigned char *>(plaintext.data()),
|
||||
plaintext.size()) != 1) {
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
result.message = "Encryption update failed";
|
||||
return result;
|
||||
}
|
||||
ciphertext_len = len;
|
||||
int 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);
|
||||
unsigned char tag[AesGcmTagLength];
|
||||
if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, AesGcmTagLength, tag) != 1) {
|
||||
result.message = "Tag generation failed";
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string final_result(reinterpret_cast<char *>(iv), sizeof(iv));
|
||||
final_result.append(reinterpret_cast<char *>(ciphertext.data()),
|
||||
ciphertext_len);
|
||||
std::string final_result(reinterpret_cast<char *>(nonce), sizeof(nonce));
|
||||
final_result.append(reinterpret_cast<char *>(ciphertext.data()), ciphertext_len);
|
||||
final_result.append(reinterpret_cast<char *>(tag), sizeof(tag));
|
||||
|
||||
result.ok = true;
|
||||
result.message = final_result;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Decrypts an AES-256-CBC encrypted string containing a prepended IV.
|
||||
*
|
||||
* @details
|
||||
* - Extracts the IV from the beginning of the input.
|
||||
* - Decrypts the remaining ciphertext using OpenSSL EVP APIs.
|
||||
*
|
||||
* @param ciphertext_with_iv Encrypted input containing IV + ciphertext.
|
||||
* @param key Decryption key.
|
||||
* @return A `BoolStr` containing success status and decrypted plaintext or an error message.
|
||||
*/
|
||||
inline BoolStr aes256Decrypt(const std::string &ciphertext_with_iv,
|
||||
const std::string &key) {
|
||||
inline BoolStr aes256Decrypt(const std::string &sealed,
|
||||
const std::string &token) {
|
||||
BoolStr result{false, "Decryption failed"};
|
||||
|
||||
unsigned char iv[EVP_MAX_IV_LENGTH];
|
||||
std::memcpy(iv, ciphertext_with_iv.c_str(),
|
||||
EVP_CIPHER_iv_length(EVP_aes_256_cbc()));
|
||||
if (sealed.size() < AesGcmNonceLength + AesGcmTagLength) {
|
||||
result.message = "Ciphertext too short";
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string ciphertext =
|
||||
ciphertext_with_iv.substr(EVP_CIPHER_iv_length(EVP_aes_256_cbc()));
|
||||
const std::string key = deriveAesKey(token);
|
||||
|
||||
int max_plaintext_len = ciphertext.size();
|
||||
std::vector<unsigned char> plaintext(max_plaintext_len);
|
||||
const auto *nonce = reinterpret_cast<const unsigned char *>(sealed.data());
|
||||
const auto *ciphertext = nonce + AesGcmNonceLength;
|
||||
const std::size_t ciphertextLen = sealed.size() - AesGcmNonceLength - AesGcmTagLength;
|
||||
std::string tag = sealed.substr(sealed.size() - AesGcmTagLength);
|
||||
|
||||
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
|
||||
std::vector<unsigned char> plaintext(ciphertextLen);
|
||||
|
||||
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,
|
||||
reinterpret_cast<const unsigned char *>(key.c_str()),
|
||||
iv) != 1) {
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
if (EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, NULL, NULL) != 1 ||
|
||||
EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, AesGcmNonceLength, NULL) != 1 ||
|
||||
EVP_DecryptInit_ex(ctx.get(), NULL, NULL,
|
||||
reinterpret_cast<const unsigned char *>(key.data()),
|
||||
nonce) != 1) {
|
||||
result.message = "Decryption initialization failed";
|
||||
return result;
|
||||
}
|
||||
|
||||
int len;
|
||||
if (EVP_DecryptUpdate(
|
||||
ctx, plaintext.data(), &len,
|
||||
reinterpret_cast<const unsigned char *>(ciphertext.c_str()),
|
||||
ciphertext.size()) != 1) {
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
int len = 0;
|
||||
if (EVP_DecryptUpdate(ctx.get(), plaintext.data(), &len, ciphertext,
|
||||
ciphertextLen) != 1) {
|
||||
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);
|
||||
result.message = "Decryption finalization failed";
|
||||
if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, AesGcmTagLength,
|
||||
tag.data()) != 1) {
|
||||
result.message = "Setting tag failed";
|
||||
return result;
|
||||
}
|
||||
|
||||
if (EVP_DecryptFinal_ex(ctx.get(), plaintext.data() + len, &len) != 1) {
|
||||
result.message = "Authentication failed (wrong token or tampered payload)";
|
||||
return result;
|
||||
}
|
||||
plaintext_len += len;
|
||||
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
|
||||
result.ok = true;
|
||||
result.message =
|
||||
std::string(reinterpret_cast<char *>(plaintext.data()), plaintext_len);
|
||||
@@ -452,24 +318,31 @@ inline BoolStr aes256Decrypt(const std::string &ciphertext_with_iv,
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Validates command-line arguments and the configuration file.
|
||||
*
|
||||
* @details
|
||||
* - Verifies the expected number of arguments.
|
||||
* - Ensures the selected mode is either `server` or `agent`.
|
||||
* - Checks that the configuration file exists.
|
||||
* - Loads and parses the YAML configuration file.
|
||||
* - Validates required keys in the following sections:
|
||||
* - `general`
|
||||
* - `log`
|
||||
* - `server`
|
||||
* - `agent`
|
||||
*
|
||||
* @param argc Number of command-line arguments.
|
||||
* @param argv Array of command-line argument strings.
|
||||
* @return A `BoolStr` containing validation status and an explanatory message.
|
||||
*/
|
||||
inline std::string makeEnvelope(const std::string &action,
|
||||
const std::string &session,
|
||||
const std::string &data) {
|
||||
return action + "\n" + session + "\n" + data;
|
||||
}
|
||||
|
||||
struct Envelope {
|
||||
std::string action;
|
||||
std::string session;
|
||||
std::string data;
|
||||
};
|
||||
|
||||
inline bool parseEnvelope(const std::string &raw, Envelope &out) {
|
||||
const auto actionEnd = raw.find('\n');
|
||||
if (actionEnd == std::string::npos) return false;
|
||||
|
||||
const auto sessionEnd = raw.find('\n', actionEnd + 1);
|
||||
if (sessionEnd == std::string::npos) return false;
|
||||
|
||||
out.action = raw.substr(0, actionEnd);
|
||||
out.session = raw.substr(actionEnd + 1, sessionEnd - actionEnd - 1);
|
||||
out.data = raw.substr(sessionEnd + 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
inline BoolStr validateConfig(int argc, const char *argv[]) {
|
||||
BoolStr result{false, "Validation failed"};
|
||||
|
||||
@@ -502,10 +375,14 @@ 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"]["bufferSize"].as<unsigned int>();
|
||||
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;
|
||||
@@ -539,6 +416,22 @@ 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 = "protocol must be one of [http|socks5]\n";
|
||||
return result;
|
||||
}
|
||||
|
||||
if (configYaml["general"]["bufferSize"].as<unsigned int>() < 1 || configYaml["general"]["bufferSize"].as<unsigned int>() > 65536) {
|
||||
result.message = "bufferSize must be between 1 and 65536\n";
|
||||
return result;
|
||||
}
|
||||
|
||||
if (configYaml["general"]["aesEnable"].as<bool>(true) &&
|
||||
configYaml["general"]["token"].as<std::string>().size() < MinTokenLength) {
|
||||
result.message = "token must be at least 32 bytes when aesEnable is true\n";
|
||||
return result;
|
||||
}
|
||||
|
||||
result.ok = true;
|
||||
result.message = "OK";
|
||||
return result;
|
||||
|
||||
+91
-212
@@ -1,22 +1,5 @@
|
||||
#include "http.hpp"
|
||||
|
||||
/**
|
||||
* @brief Constructs an `HTTP` instance with configuration, logging, input buffer,
|
||||
* and session identifier.
|
||||
*
|
||||
* @details
|
||||
* - Stores references to the configuration, logging, and stream buffer objects.
|
||||
* - Initializes the parsed HTTP request object and default HTTP type.
|
||||
* - Initializes the parsed TLS request state with empty values and a default
|
||||
* TLS handshake type.
|
||||
* - Stores the UUID used for logging and tracing this session.
|
||||
* - Sets the default chunk header state to `"no"`.
|
||||
*
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param buffer Reference to the stream buffer containing raw request or response data.
|
||||
* @param uuid Unique identifier for the current session.
|
||||
*/
|
||||
HTTP::HTTP(const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
boost::asio::streambuf &buffer,
|
||||
@@ -28,20 +11,8 @@ HTTP::HTTP(const std::shared_ptr<Config> &config,
|
||||
httpType_(HTTP::HttpType::https),
|
||||
parsedTlsRequest_{"", "", TlsTypes::TLSHandshake},
|
||||
uuid_(uuid) {
|
||||
chunkHeader_ = "no";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Copy-constructs an `HTTP` instance from another instance.
|
||||
*
|
||||
* @details
|
||||
* - Copies references to the configuration, logging, and stream buffer objects.
|
||||
* - Copies the parsed HTTP request and parsed TLS request state.
|
||||
* - Copies the UUID for session identification.
|
||||
* - Resets the chunk header state to `"no"`.
|
||||
*
|
||||
* @param http Existing `HTTP` object to copy.
|
||||
*/
|
||||
HTTP::HTTP(const HTTP &http)
|
||||
: config_(http.config_),
|
||||
log_(http.log_),
|
||||
@@ -49,33 +20,12 @@ HTTP::HTTP(const HTTP &http)
|
||||
parsedHttpRequest_(http.parsedHttpRequest_),
|
||||
parsedTlsRequest_(http.parsedTlsRequest_),
|
||||
uuid_(http.uuid_) {
|
||||
chunkHeader_ = "no";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Destroys the `HTTP` instance.
|
||||
*
|
||||
* @details
|
||||
* - Performs no explicit cleanup.
|
||||
* - Resource management is handled by referenced objects and standard class members.
|
||||
*/
|
||||
|
||||
HTTP::~HTTP() {}
|
||||
|
||||
/**
|
||||
* @brief Detects whether the current buffer contains TLS-related traffic or HTTP traffic.
|
||||
*
|
||||
* @details
|
||||
* - Reads the input buffer as a hexadecimal string.
|
||||
* - Inspects the first byte to distinguish TLS record types from plain HTTP data.
|
||||
* - Treats values `16`, `14`, and `17` as TLS record types:
|
||||
* - `16`: Handshake
|
||||
* - `14`: ChangeCipherSpec
|
||||
* - `17`: ApplicationData
|
||||
* - For TLS traffic, stores the raw body and invokes `parseTls()`.
|
||||
* - For non-TLS traffic, invokes `parseHttp()`.
|
||||
*
|
||||
* @return `true` if the request type is successfully detected and parsed, otherwise `false`.
|
||||
*/
|
||||
|
||||
bool HTTP::detectType() {
|
||||
std::string requestStr{hexStreambufToStr(buffer_)};
|
||||
std::string tmpStr;
|
||||
@@ -99,19 +49,6 @@ bool HTTP::detectType() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Parses an HTTP request from the current input buffer.
|
||||
*
|
||||
* @details
|
||||
* - Converts the stream buffer contents to a string.
|
||||
* - Uses Boost.Beast request parsing to parse the HTTP request.
|
||||
* - Detects whether the request method is `CONNECT` or a normal HTTP method.
|
||||
* - Sets the internal HTTP type accordingly.
|
||||
* - Extracts and stores the destination IP address and port.
|
||||
* - Logs parsing errors when request parsing fails.
|
||||
*
|
||||
* @return `true` if parsing succeeds, otherwise `false`.
|
||||
*/
|
||||
bool HTTP::parseHttp() {
|
||||
std::string requestStr(streambufToString(buffer_));
|
||||
boost::beast::http::request_parser<boost::beast::http::string_body> parser;
|
||||
@@ -137,17 +74,6 @@ bool HTTP::parseHttp() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Parses an HTTP response from the current input buffer.
|
||||
*
|
||||
* @details
|
||||
* - Converts the stream buffer contents to a string.
|
||||
* - Uses the internal Boost.Beast parser to parse the HTTP response.
|
||||
* - Stores the parsed response object on success.
|
||||
* - Logs parsing errors when response parsing fails.
|
||||
*
|
||||
* @return `true` if parsing succeeds, otherwise `false`.
|
||||
*/
|
||||
bool HTTP::parseHttpResp() {
|
||||
std::string requestStr(streambufToString(buffer_));
|
||||
parser_.eager(true);
|
||||
@@ -165,21 +91,6 @@ bool HTTP::parseHttpResp() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Parses TLS request data from the stored TLS body.
|
||||
*
|
||||
* @details
|
||||
* - Inspects the TLS record type from the first byte of the hex-encoded body.
|
||||
* - Supports parsing of:
|
||||
* - TLS Handshake
|
||||
* - ChangeCipherSpec
|
||||
* - ApplicationData
|
||||
* - For TLS handshake records, attempts to extract the Server Name Indication (SNI)
|
||||
* from the ClientHello message.
|
||||
* - Updates destination IP and port after successful parsing.
|
||||
*
|
||||
* @return `true` if parsing succeeds, otherwise `false`.
|
||||
*/
|
||||
bool HTTP::parseTls() {
|
||||
std::string tmpStr;
|
||||
unsigned short pos = 0;
|
||||
@@ -244,113 +155,120 @@ bool HTTP::parseTls() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Generates an HTTP POST request string containing the provided body.
|
||||
*
|
||||
* @details
|
||||
* - Builds an HTTP request using configured method, fake URL, HTTP version,
|
||||
* and User-Agent.
|
||||
* - Sets common headers including `Host`, `Accept`, `Connection`,
|
||||
* `Content-Length`, and `Content-Type`.
|
||||
* - Appends the payload body followed by the application terminator marker.
|
||||
*
|
||||
* @param body Body content to include in the HTTP request.
|
||||
* @return Serialized HTTP POST request string.
|
||||
*/
|
||||
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";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Generates a REST-style HTTP POST request string.
|
||||
*
|
||||
* @details
|
||||
* - Builds an HTTP request using configured method, fake URL, HTTP version,
|
||||
* and User-Agent.
|
||||
* - Adds the custom `Rest: yes` header to mark the request as a REST-style operation.
|
||||
* - Appends the application terminator marker.
|
||||
*
|
||||
* @return Serialized REST-style HTTP POST request string.
|
||||
*/
|
||||
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";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Generates an HTTP `200 OK` response string.
|
||||
*
|
||||
* @details
|
||||
* - Builds a successful HTTP response with content type, content length,
|
||||
* custom chunk header, and cache-related headers.
|
||||
* - Appends the response body followed by the application terminator marker.
|
||||
*
|
||||
* @param body Body content to include in the HTTP response.
|
||||
* @return Serialized HTTP `200 OK` response string.
|
||||
*/
|
||||
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";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Extracts and stores destination IP address and port from the parsed request data.
|
||||
*
|
||||
* @details
|
||||
* - For TLS traffic, uses the parsed SNI value and defaults to port `443`
|
||||
* when no explicit port is provided.
|
||||
* - For HTTP traffic, extracts the host and optional port from the request target
|
||||
* and defaults to port `80` when no port is present.
|
||||
* - For CONNECT traffic, splits the target directly into host and port.
|
||||
* - Logs an error when HTTP request parsing does not provide a usable target.
|
||||
*/
|
||||
|
||||
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: {
|
||||
target = parsedTlsRequest_.sni;
|
||||
splitted = splitString(target, ":");
|
||||
|
||||
if (!splitted.empty()) {
|
||||
dstIP_ = splitted[0];
|
||||
if (splitted.size() > 1 && !splitted[1].empty()) {
|
||||
dstPort_ = std::stoi(splitted[1]);
|
||||
} else {
|
||||
dstPort_ = 443;
|
||||
}
|
||||
} else {
|
||||
dstIP_.clear();
|
||||
if (!parseHostPort(target, dstIp_, dstPort_, 443)) {
|
||||
dstIp_.clear();
|
||||
dstPort_ = 443;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case HTTP::HttpType::http: {
|
||||
target = boost::lexical_cast<std::string>(parsedHttpRequest_.target());
|
||||
|
||||
// Absolute-form request target:
|
||||
// http://host:port/path
|
||||
// Origin-form request target:
|
||||
// /path
|
||||
// For origin-form, use Host header instead.
|
||||
std::string hostPort;
|
||||
|
||||
if (target.rfind("http://", 0) == 0) {
|
||||
@@ -366,7 +284,6 @@ void HTTP::setIPPort() {
|
||||
? withoutScheme
|
||||
: withoutScheme.substr(0, slashPos);
|
||||
} else {
|
||||
// origin-form like "/relay"
|
||||
auto hostIt = parsedHttpRequest_.find("Host");
|
||||
if (hostIt != parsedHttpRequest_.end()) {
|
||||
hostPort = boost::lexical_cast<std::string>(hostIt->value());
|
||||
@@ -374,56 +291,37 @@ void HTTP::setIPPort() {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [HTTP setIPPort] missing Host header",
|
||||
Log::Level::DEBUG);
|
||||
dstIP_.clear();
|
||||
dstIp_.clear();
|
||||
dstPort_ = 80;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
splitted = splitString(hostPort, ":");
|
||||
if (!splitted.empty()) {
|
||||
dstIP_ = splitted[0];
|
||||
if (splitted.size() > 1 && !splitted[1].empty()) {
|
||||
dstPort_ = std::stoi(splitted[1]);
|
||||
} else {
|
||||
dstPort_ = 80;
|
||||
}
|
||||
} else {
|
||||
if (!parseHostPort(hostPort, dstIp_, dstPort_, 80)) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [HTTP setIPPort] wrong request",
|
||||
Log::Level::DEBUG);
|
||||
dstIP_.clear();
|
||||
dstIp_.clear();
|
||||
dstPort_ = 80;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case HTTP::HttpType::connect: {
|
||||
target = boost::lexical_cast<std::string>(parsedHttpRequest_.target());
|
||||
splitted = splitString(target, ":");
|
||||
|
||||
if (!splitted.empty()) {
|
||||
dstIP_ = splitted[0];
|
||||
if (splitted.size() > 1 && !splitted[1].empty()) {
|
||||
dstPort_ = std::stoi(splitted[1]);
|
||||
} else {
|
||||
dstPort_ = 443;
|
||||
}
|
||||
} else {
|
||||
dstIP_.clear();
|
||||
if (!parseHostPort(target, dstIp_, dstPort_, 443)) {
|
||||
dstIp_.clear();
|
||||
dstPort_ = 443;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts the parsed TLS record type to a string.
|
||||
*
|
||||
* @return String representation of the current TLS type.
|
||||
*/
|
||||
const std::string HTTP::tlsTypeToString() const {
|
||||
std::string HTTP::tlsTypeToString() const {
|
||||
switch (parsedTlsRequest_.type) {
|
||||
case TlsTypes::TLSHandshake:
|
||||
return "TLSHandshake";
|
||||
@@ -436,18 +334,7 @@ const std::string HTTP::tlsTypeToString() const {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts the current parsed request state into a human-readable string.
|
||||
*
|
||||
* @details
|
||||
* - For TLS traffic, returns TLS type, SNI, body size, and body contents.
|
||||
* - For HTTP traffic, returns method, version, target, User-Agent, body size,
|
||||
* and body contents.
|
||||
* - For CONNECT traffic, returns method and target only.
|
||||
*
|
||||
* @return Formatted string representation of the current request state.
|
||||
*/
|
||||
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" +
|
||||
@@ -483,15 +370,7 @@ const std::string HTTP::toString() const {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts the parsed HTTP response into a human-readable string.
|
||||
*
|
||||
* @details
|
||||
* - Returns the response base fields, body size, and body contents.
|
||||
*
|
||||
* @return Formatted string representation of the parsed HTTP response.
|
||||
*/
|
||||
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 : " +
|
||||
|
||||
+31
-197
@@ -10,38 +10,10 @@
|
||||
#include "general.hpp"
|
||||
#include "log.hpp"
|
||||
|
||||
/**
|
||||
* @brief The `HTTP` class provides parsing and generation utilities for HTTP and TLS traffic.
|
||||
*
|
||||
* @details
|
||||
* - Parses HTTP requests and responses from a stream buffer.
|
||||
* - Detects whether incoming traffic is plain HTTP, HTTPS-related, or CONNECT tunneling.
|
||||
* - Parses selected TLS request data such as message type and SNI.
|
||||
* - Generates HTTP request and response strings used by the application.
|
||||
* - Tracks destination IP address and port derived from parsed request data.
|
||||
* - Integrates with configuration and logging components for runtime behavior and diagnostics.
|
||||
*
|
||||
* @note
|
||||
* - Instances are managed through shared ownership using `std::shared_ptr`.
|
||||
* - Objects should be created using the `create` factory method.
|
||||
*/
|
||||
class HTTP {
|
||||
public:
|
||||
using pointer = std::shared_ptr<HTTP>;
|
||||
|
||||
/**
|
||||
* @brief Factory method to create a new `HTTP` instance.
|
||||
*
|
||||
* @details
|
||||
* - Wraps object creation in a `std::shared_ptr`.
|
||||
* - Ensures consistent ownership handling across the application.
|
||||
*
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param buffer Reference to the stream buffer containing raw input data.
|
||||
* @param uuid Unique session identifier.
|
||||
* @return A shared pointer to the created `HTTP` instance.
|
||||
*/
|
||||
static pointer create(const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
boost::asio::streambuf &buffer,
|
||||
@@ -49,230 +21,92 @@ public:
|
||||
return pointer(new HTTP(config, log, buffer, uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Enumeration of supported HTTP traffic types.
|
||||
*
|
||||
* @details
|
||||
* - `https`: HTTPS-style traffic or TLS-related traffic.
|
||||
* - `http`: Standard HTTP request traffic.
|
||||
* - `connect`: HTTP CONNECT tunnel request.
|
||||
*/
|
||||
enum class HttpType {
|
||||
https,
|
||||
http,
|
||||
connect
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Enumeration of supported TLS record types.
|
||||
*/
|
||||
enum class TlsTypes {
|
||||
TLSHandshake, ///< TLS handshake record.
|
||||
ChangeCipherSpec,///< TLS ChangeCipherSpec record.
|
||||
ApplicationData ///< TLS application data record.
|
||||
TLSHandshake,
|
||||
ChangeCipherSpec,
|
||||
ApplicationData
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Stores parsed TLS request information.
|
||||
*
|
||||
* @details
|
||||
* - Contains the extracted Server Name Indication (SNI), payload body,
|
||||
* and detected TLS record type.
|
||||
*/
|
||||
struct TlsRequest {
|
||||
std::string sni; ///< Parsed Server Name Indication value.
|
||||
std::string body;///< Raw or extracted TLS payload body.
|
||||
TlsTypes type; ///< Detected TLS record type.
|
||||
std::string sni;
|
||||
std::string body;
|
||||
TlsTypes type;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Copy constructor.
|
||||
*
|
||||
* @param request Existing `HTTP` object to copy.
|
||||
*/
|
||||
explicit HTTP(const HTTP &request);
|
||||
|
||||
/**
|
||||
* @brief Destructor for `HTTP`.
|
||||
*/
|
||||
~HTTP();
|
||||
|
||||
/**
|
||||
* @brief Returns the detected HTTP traffic type.
|
||||
*
|
||||
* @return Reference to the current `HttpType`.
|
||||
*/
|
||||
inline const HTTP::HttpType &httpType() const { return httpType_; }
|
||||
inline HTTP::HttpType httpType() const { return httpType_; }
|
||||
|
||||
/**
|
||||
* @brief Sets the HTTP traffic type.
|
||||
*
|
||||
* @param httpType New HTTP type value.
|
||||
*/
|
||||
inline void httpType(const HTTP::HttpType &httpType) { httpType_ = httpType; }
|
||||
|
||||
/**
|
||||
* @brief Detects the type of traffic present in the buffer.
|
||||
*
|
||||
* @details
|
||||
* - Inspects the current buffer contents.
|
||||
* - Determines whether the input is HTTP, HTTPS-related, or CONNECT traffic.
|
||||
*
|
||||
* @return `true` if the type is successfully detected, otherwise `false`.
|
||||
*/
|
||||
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.
|
||||
*
|
||||
* @details
|
||||
* - Populates the internal parsed HTTP request object.
|
||||
* - May also derive destination information from the parsed request.
|
||||
*
|
||||
* @return `true` if parsing succeeds, otherwise `false`.
|
||||
*/
|
||||
bool parseHttp();
|
||||
|
||||
/**
|
||||
* @brief Parses an HTTP response from the buffer.
|
||||
*
|
||||
* @details
|
||||
* - Populates the internal parsed HTTP response object.
|
||||
*
|
||||
* @return `true` if parsing succeeds, otherwise `false`.
|
||||
*/
|
||||
bool parseHttpResp();
|
||||
|
||||
/**
|
||||
* @brief Parses a TLS request from the buffer.
|
||||
*
|
||||
* @details
|
||||
* - Extracts selected TLS metadata such as record type and SNI when available.
|
||||
*
|
||||
* @return `true` if parsing succeeds, otherwise `false`.
|
||||
*/
|
||||
bool parseTls();
|
||||
|
||||
/**
|
||||
* @brief Generates an HTTP POST request string with the given body.
|
||||
*
|
||||
* @param body Body content to include in the request.
|
||||
* @return Serialized HTTP POST request string.
|
||||
*/
|
||||
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 Serialized REST-style HTTP POST request string.
|
||||
*/
|
||||
const std::string genHttpRestPostReqString() const;
|
||||
std::string genHttpRestPostReqString() const;
|
||||
|
||||
/**
|
||||
* @brief Generates an HTTP `200 OK` response string.
|
||||
*
|
||||
* @param body Body content to include in the response.
|
||||
* @return Serialized HTTP response string.
|
||||
*/
|
||||
const std::string genHttpOkResString(const std::string &body) const;
|
||||
std::string genHttpOkResString(const std::string &body) const;
|
||||
|
||||
/**
|
||||
* @brief Returns the parsed HTTP request object.
|
||||
*
|
||||
* @return Const reference to the parsed HTTP request.
|
||||
*/
|
||||
inline const boost::beast::http::request<boost::beast::http::string_body> &
|
||||
parsedHttpRequest() & {
|
||||
return parsedHttpRequest_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the parsed HTTP response object.
|
||||
*
|
||||
* @return Const reference to the parsed HTTP response.
|
||||
*/
|
||||
inline const boost::beast::http::response<boost::beast::http::string_body> &
|
||||
parsedHttpResponse() & {
|
||||
return parsedHttpResponse_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the parsed TLS request information.
|
||||
*
|
||||
* @return Const reference to the parsed TLS request structure.
|
||||
*/
|
||||
inline const TlsRequest &parsedTlsRequest() & { return parsedTlsRequest_; }
|
||||
|
||||
/**
|
||||
* @brief Converts the parsed TLS type to a string.
|
||||
*
|
||||
* @return String representation of the current TLS record type.
|
||||
*/
|
||||
const std::string tlsTypeToString() const;
|
||||
std::string tlsTypeToString() const;
|
||||
|
||||
/**
|
||||
* @brief Returns the destination IP address.
|
||||
*
|
||||
* @return Const reference to the destination IP string.
|
||||
*/
|
||||
inline const std::string &dstIP() { return dstIP_; }
|
||||
inline const std::string &dstIp() const { return dstIp_; }
|
||||
|
||||
/**
|
||||
* @brief Returns the destination port.
|
||||
*
|
||||
* @return Const reference to the destination port.
|
||||
*/
|
||||
inline const unsigned short &dstPort() { return dstPort_; }
|
||||
inline unsigned short dstPort() const { return dstPort_; }
|
||||
|
||||
/**
|
||||
* @brief Converts the current HTTP object state to a human-readable string.
|
||||
*
|
||||
* @return String representation of the parsed or generated HTTP state.
|
||||
*/
|
||||
const std::string toString() const;
|
||||
std::string toString() const;
|
||||
|
||||
/**
|
||||
* @brief Converts REST-related HTTP state to a human-readable string.
|
||||
*
|
||||
* @return String representation of REST-specific state information.
|
||||
*/
|
||||
const std::string restoString() const;
|
||||
|
||||
std::string chunkHeader_;///< Custom chunk-related header value.
|
||||
std::string restoString() const;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Private constructor for `HTTP`.
|
||||
*
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param buffer Reference to the stream buffer used for input parsing.
|
||||
* @param uuid Unique session identifier.
|
||||
*/
|
||||
explicit HTTP(const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
boost::asio::streambuf &buffer,
|
||||
boost::uuids::uuid uuid);
|
||||
|
||||
/**
|
||||
* @brief Sets destination IP address and port from parsed request data.
|
||||
*
|
||||
* @details
|
||||
* - Extracts and stores destination connection information after parsing.
|
||||
*/
|
||||
void setIPPort();
|
||||
|
||||
const std::shared_ptr<Config> &config_;///< Reference to the configuration object.
|
||||
const std::shared_ptr<Log> &log_; ///< Reference to the logging object.
|
||||
boost::asio::streambuf &buffer_; ///< Buffer containing raw HTTP or TLS data.
|
||||
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_; ///< HTTP request parser.
|
||||
boost::beast::http::request<boost::beast::http::string_body> parsedHttpRequest_; ///< Parsed HTTP request.
|
||||
boost::beast::http::response<boost::beast::http::string_body> parsedHttpResponse_;///< Parsed HTTP response.
|
||||
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_; ///< Detected HTTP traffic type.
|
||||
std::string dstIP_; ///< Parsed destination IP or host.
|
||||
unsigned short dstPort_; ///< Parsed destination port.
|
||||
TlsRequest parsedTlsRequest_;///< Parsed TLS request metadata.
|
||||
boost::uuids::uuid uuid_; ///< Unique session identifier.
|
||||
HttpType httpType_;
|
||||
std::string dstIp_;
|
||||
unsigned short dstPort_;
|
||||
TlsRequest parsedTlsRequest_;
|
||||
boost::uuids::uuid uuid_;
|
||||
};
|
||||
@@ -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
|
||||
+1
-76
@@ -1,42 +1,19 @@
|
||||
#include "log.hpp"
|
||||
|
||||
/**
|
||||
* @brief Constructs a `Log` instance using the provided configuration.
|
||||
*
|
||||
* @details
|
||||
* - Initializes the runtime mode string based on the configured `RunMode`.
|
||||
* - Attempts to open the configured log file to verify accessibility.
|
||||
* - Initializes the logging level based on configuration:
|
||||
* - Supported levels: INFO, TRACE, DEBUG
|
||||
* - Defaults to INFO if not specified or invalid
|
||||
* - Prints an error to `std::cerr` if the log file cannot be opened or
|
||||
* if an invalid log level is provided.
|
||||
*
|
||||
* @param config Shared pointer to the configuration object.
|
||||
*/
|
||||
Log::Log(const std::shared_ptr<Config> &config)
|
||||
: config_(config), level_(Level::INFO) {
|
||||
|
||||
/**
|
||||
* @brief Determines the runtime mode string for log entries.
|
||||
*/
|
||||
if (config_->runMode() == RunMode::server)
|
||||
mode_ = std::string("SERVER");
|
||||
else if (config_->runMode() == RunMode::agent)
|
||||
mode_ = std::string("AGENT");
|
||||
|
||||
/**
|
||||
* @brief Verifies that the log file can be opened.
|
||||
*/
|
||||
std::ofstream logFile(config_->log().file, std::ios::out | std::ios::app);
|
||||
if (!logFile.is_open()) {
|
||||
std::cerr << "Error opening log file: " << config_->log().file
|
||||
<< ". Make sure the directory and file exist.\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sets the logging level based on configuration.
|
||||
*/
|
||||
const auto &logLevel = config_->log().level;
|
||||
|
||||
if (logLevel == "INFO") {
|
||||
@@ -51,48 +28,11 @@ Log::Log(const std::shared_ptr<Config> &config)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Copy-constructs a `Log` instance from another instance.
|
||||
*
|
||||
* @details
|
||||
* - Copies the configuration reference and logging level.
|
||||
* - Does not duplicate file handles or internal state beyond configuration.
|
||||
*
|
||||
* @param log Shared pointer to the source `Log` instance.
|
||||
*/
|
||||
Log::Log(const std::shared_ptr<Log> &log)
|
||||
: config_(log->config_), level_(log->level_) {}
|
||||
|
||||
/**
|
||||
* @brief Destroys the `Log` instance.
|
||||
*
|
||||
* @details
|
||||
* - No explicit resource cleanup is required.
|
||||
* - File streams are opened and closed per write operation.
|
||||
*/
|
||||
Log::~Log() {}
|
||||
|
||||
/**
|
||||
* @brief Writes a log message to the configured output.
|
||||
*
|
||||
* @details
|
||||
* - Ensures thread safety using an internal mutex.
|
||||
* - Writes messages only if:
|
||||
* - The message level is less than or equal to the configured level, OR
|
||||
* - The message level is `ERROR`.
|
||||
* - Each log entry includes:
|
||||
* - Timestamp (YYYY-MM-DD_HH:MM:SS)
|
||||
* - Runtime mode (SERVER or AGENT)
|
||||
* - Log level
|
||||
* - Message content
|
||||
* - Outputs the log entry to both:
|
||||
* - The configured log file
|
||||
* - Standard output (`std::cout`)
|
||||
* - Prints an error to `std::cerr` if the log file cannot be opened.
|
||||
*
|
||||
* @param message Log message to write.
|
||||
* @param level Severity level of the message.
|
||||
*/
|
||||
void Log::write(const std::string &message, Level level) const {
|
||||
std::lock_guard<std::mutex> lock(logMutex_);
|
||||
|
||||
@@ -102,9 +42,7 @@ void Log::write(const std::string &message, Level level) const {
|
||||
|
||||
if (logFile.is_open()) {
|
||||
|
||||
/**
|
||||
* @brief Generates a formatted timestamp.
|
||||
*/
|
||||
|
||||
auto now = std::time(nullptr);
|
||||
auto localTime = *std::localtime(&now);
|
||||
|
||||
@@ -112,9 +50,6 @@ void Log::write(const std::string &message, Level level) const {
|
||||
timestampStream << std::put_time(&localTime, "%Y-%m-%d_%H:%M:%S");
|
||||
std::string timestamp = timestampStream.str();
|
||||
|
||||
/**
|
||||
* @brief Formats the final log line.
|
||||
*/
|
||||
std::string line = timestamp + " [" + mode_ + "]" + " [" +
|
||||
levelToString(level) + "] " + message + "\n";
|
||||
|
||||
@@ -128,16 +63,6 @@ void Log::write(const std::string &message, Level level) const {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts a log level enum value to its string representation.
|
||||
*
|
||||
* @details
|
||||
* - Maps each `Level` enum value to its corresponding string.
|
||||
* - Returns `"UNKNOWN"` for unsupported values.
|
||||
*
|
||||
* @param level Log level to convert.
|
||||
* @return String representation of the log level.
|
||||
*/
|
||||
std::string Log::levelToString(Level level) {
|
||||
switch (level) {
|
||||
case Level::INFO:
|
||||
|
||||
+9
-83
@@ -1,6 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
// Standard library includes
|
||||
#include <ctime>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
@@ -8,115 +7,42 @@
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
// Project-specific includes
|
||||
#include "config.hpp"
|
||||
#include "general.hpp"
|
||||
|
||||
/**
|
||||
* @brief The `Log` class provides thread-safe logging functionality for the application.
|
||||
*
|
||||
* @details
|
||||
* - Supports multiple log severity levels.
|
||||
* - Writes log messages using configuration-defined logging behavior.
|
||||
* - Ensures thread-safe access through an internal mutex.
|
||||
* - Uses shared ownership via `std::shared_ptr`.
|
||||
*
|
||||
* @note
|
||||
* - Inherits from `Uncopyable` to prevent accidental copying.
|
||||
* - Instances should be created using the `create` factory method.
|
||||
*/
|
||||
class Log : private Uncopyable {
|
||||
public:
|
||||
/**
|
||||
* @brief Enumeration of supported log severity levels.
|
||||
*/
|
||||
enum class Level {
|
||||
INFO, ///< Informational messages.
|
||||
TRACE,///< Detailed tracing messages.
|
||||
ERROR,///< Error messages.
|
||||
DEBUG ///< Debugging messages.
|
||||
INFO,
|
||||
TRACE,
|
||||
ERROR,
|
||||
DEBUG
|
||||
};
|
||||
|
||||
using pointer = std::shared_ptr<Log>;
|
||||
|
||||
/**
|
||||
* @brief Factory method to create a new `Log` instance.
|
||||
*
|
||||
* @details
|
||||
* - Wraps object creation in a `std::shared_ptr`.
|
||||
* - Ensures consistent construction and ownership handling.
|
||||
*
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @return A shared pointer to the created `Log` instance.
|
||||
*/
|
||||
static pointer create(const std::shared_ptr<Config> &config) {
|
||||
return pointer(new Log(config));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Copy constructor that creates a `Log` instance from another `Log` object.
|
||||
*
|
||||
* @param log Shared pointer to the existing `Log` object.
|
||||
*/
|
||||
explicit Log(const std::shared_ptr<Log> &log);
|
||||
|
||||
/**
|
||||
* @brief Destructor for `Log`.
|
||||
*
|
||||
* @details
|
||||
* - Performs standard object cleanup.
|
||||
* - Any file handling or output cleanup is managed by implementation details.
|
||||
*/
|
||||
~Log();
|
||||
|
||||
/**
|
||||
* @brief Returns the configuration associated with this logger.
|
||||
*
|
||||
* @return Const reference to the shared configuration pointer.
|
||||
*/
|
||||
const std::shared_ptr<Config> &config() const { return config_; }
|
||||
std::shared_ptr<Config> config() const { return config_; }
|
||||
|
||||
/**
|
||||
* @brief Returns the currently configured log level.
|
||||
*
|
||||
* @return Current log severity level.
|
||||
*/
|
||||
Level level() const { return level_; }
|
||||
|
||||
/**
|
||||
* @brief Writes a log message using the specified severity level.
|
||||
*
|
||||
* @details
|
||||
* - Thread-safe through internal mutex protection.
|
||||
* - Uses configuration-defined logging mode and output destination.
|
||||
*
|
||||
* @param message Log message to write.
|
||||
* @param level Severity level of the message.
|
||||
*/
|
||||
void write(const std::string &message, Level level) const;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Private constructor for creating a `Log` instance from configuration.
|
||||
*
|
||||
* @details
|
||||
* - Intended to be used only through 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 its string representation.
|
||||
*
|
||||
* @param level Log level to convert.
|
||||
* @return String representation of the log level.
|
||||
*/
|
||||
static std::string levelToString(Level level);
|
||||
|
||||
const std::shared_ptr<Config> &config_;///< Reference to the configuration object.
|
||||
Level level_; ///< Active logging level.
|
||||
std::string mode_; ///< Current runtime mode string.
|
||||
std::shared_ptr<Config> config_;
|
||||
Level level_;
|
||||
std::string mode_;
|
||||
|
||||
mutable std::mutex logMutex_;///< Mutex used to ensure thread-safe logging.
|
||||
mutable std::mutex logMutex_;
|
||||
};
|
||||
+3
-39
@@ -5,37 +5,16 @@
|
||||
#include "log.hpp"
|
||||
#include "runner.hpp"
|
||||
|
||||
/**
|
||||
* @brief Application entry point.
|
||||
*
|
||||
* @details
|
||||
* - Validates command-line arguments.
|
||||
* - Validates the provided configuration file and runtime mode.
|
||||
* - Creates the main configuration and logging objects.
|
||||
* - Constructs the application runner and starts execution.
|
||||
*
|
||||
* @param argc Number of command-line arguments.
|
||||
* @param argv Array of command-line argument strings.
|
||||
* @return `0` on successful execution, otherwise `1`.
|
||||
*/
|
||||
int main(int argc, char const *argv[]) {
|
||||
|
||||
/**
|
||||
* @brief Ensures that the required command-line arguments are provided.
|
||||
*
|
||||
* @details
|
||||
* - Expects two arguments:
|
||||
* - runtime mode (`server` or `agent`)
|
||||
* - configuration file path
|
||||
*/
|
||||
if (argc < 3) {
|
||||
std::cerr << "Usage: " << argv[0] << " <mode> <config_file_path>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Validates the configuration file and command-line arguments.
|
||||
*/
|
||||
std::string mode(argv[1]);
|
||||
RunMode runMode_ = (mode == "agent") ? RunMode::agent : RunMode::server;
|
||||
|
||||
BoolStr configValidation = validateConfig(argc, argv);
|
||||
if (!configValidation.ok) {
|
||||
std::cerr << "Configuration validation failed: " << configValidation.message
|
||||
@@ -43,25 +22,10 @@ int main(int argc, char const *argv[]) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts the string mode argument into the internal `RunMode` enum.
|
||||
*/
|
||||
std::string mode(argv[1]);
|
||||
RunMode runMode_ = (mode == "agent") ? RunMode::agent : RunMode::server;
|
||||
|
||||
/**
|
||||
* @brief Creates the configuration object from the provided file.
|
||||
*/
|
||||
Config::pointer config_ = Config::create(runMode_, std::string(argv[2]));
|
||||
|
||||
/**
|
||||
* @brief Creates the logging object using the loaded configuration.
|
||||
*/
|
||||
Log::pointer log_ = Log::create(config_);
|
||||
|
||||
/**
|
||||
* @brief Creates the main runner instance and starts the application.
|
||||
*/
|
||||
Runner runner_(config_, log_);
|
||||
runner_.run();
|
||||
|
||||
|
||||
+7
-48
@@ -1,18 +1,5 @@
|
||||
#include "runner.hpp"
|
||||
|
||||
/**
|
||||
* @brief Constructs a `Runner` instance with configuration and logging support.
|
||||
*
|
||||
* @details
|
||||
* - Stores references to the configuration and logging objects.
|
||||
* - Initializes the internal Boost.Asio `io_context`.
|
||||
* - Creates a work guard to keep the `io_context` alive.
|
||||
* - Sets the running state to `true`.
|
||||
* - Initializes a strand for serialized handler execution.
|
||||
*
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
*/
|
||||
Runner::Runner(const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log)
|
||||
: config_(config),
|
||||
@@ -22,14 +9,6 @@ Runner::Runner(const std::shared_ptr<Config> &config,
|
||||
running_(true),
|
||||
strand_(boost::asio::make_strand(io_context_)) {}
|
||||
|
||||
/**
|
||||
* @brief Destroys the `Runner` instance and shuts down all execution resources.
|
||||
*
|
||||
* @details
|
||||
* - Sets the running state to `false`.
|
||||
* - Stops the Boost.Asio `io_context`.
|
||||
* - Joins all worker threads in the thread pool if they are still joinable.
|
||||
*/
|
||||
Runner::~Runner() {
|
||||
running_.store(false);
|
||||
io_context_.stop();
|
||||
@@ -41,22 +20,18 @@ Runner::~Runner() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Starts the server runtime and launches worker threads.
|
||||
*
|
||||
* @details
|
||||
* - Logs the current runtime mode and full configuration.
|
||||
* - Creates the `TCPServer` instance bound to the internal `io_context`.
|
||||
* - Spawns a number of worker threads based on the configured thread count.
|
||||
* - Each worker thread runs the `workerThread()` loop.
|
||||
* - Waits for all worker threads to finish before returning.
|
||||
* - Logs any exception that occurs during startup or runtime coordination.
|
||||
*/
|
||||
void Runner::run() {
|
||||
try {
|
||||
log_->write("Config initialized in " + config_->modeToString() + " mode", Log::Level::INFO);
|
||||
log_->write(config_->toString(), Log::Level::INFO);
|
||||
|
||||
if (config_->general().aesEnable && config_->general().token == SampleToken) {
|
||||
log_->write(
|
||||
"[WARNING] general.token is the public sample token; "
|
||||
"set a unique random token on both agent and server",
|
||||
Log::Level::ERROR);
|
||||
}
|
||||
|
||||
auto tcpServer = TCPServer::create(io_context_, config_, log_);
|
||||
|
||||
for (auto i = 0; i < config_->threads(); ++i) {
|
||||
@@ -76,15 +51,6 @@ void Runner::run() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Worker thread entry point for processing asynchronous operations.
|
||||
*
|
||||
* @details
|
||||
* - Repeatedly runs the Boost.Asio `io_context` while the runner is active.
|
||||
* - Exits the loop when `io_context_.run()` completes normally.
|
||||
* - Catches and logs exceptions so that a single handler failure does not
|
||||
* immediately terminate the worker loop.
|
||||
*/
|
||||
void Runner::workerThread() {
|
||||
while (running_.load()) {
|
||||
try {
|
||||
@@ -98,13 +64,6 @@ void Runner::workerThread() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Stops the runner and terminates asynchronous processing.
|
||||
*
|
||||
* @details
|
||||
* - Sets the running state to `false`.
|
||||
* - Stops the internal Boost.Asio `io_context`.
|
||||
*/
|
||||
void Runner::stop() {
|
||||
running_.store(false);
|
||||
io_context_.stop();
|
||||
|
||||
+11
-72
@@ -7,101 +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"
|
||||
|
||||
/**
|
||||
* @brief The `Runner` class manages the lifecycle and execution of the asynchronous server.
|
||||
*
|
||||
* @details
|
||||
* - Initializes and owns the Boost.Asio `io_context`.
|
||||
* - Creates and manages a pool of worker threads.
|
||||
* - Keeps the `io_context` alive using a work guard.
|
||||
* - Provides mechanisms to start and gracefully stop the server.
|
||||
* - Ensures thread-safe execution of handlers using a strand.
|
||||
*
|
||||
* @note
|
||||
* - Inherits from `Uncopyable` to prevent copying.
|
||||
* - Uses `std::jthread` for automatic thread cleanup on destruction.
|
||||
*/
|
||||
class Runner : private Uncopyable {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a `Runner` instance with configuration and logging support.
|
||||
*
|
||||
* @details
|
||||
* - Initializes the internal `io_context`.
|
||||
* - Creates a work guard to prevent premature exit of the event loop.
|
||||
* - Prepares the threading and execution environment.
|
||||
*
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
*/
|
||||
explicit Runner(const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log);
|
||||
|
||||
/**
|
||||
* @brief Destructor for `Runner`.
|
||||
*
|
||||
* @details
|
||||
* - Ensures that all worker threads are stopped.
|
||||
* - Releases the work guard and shuts down the `io_context`.
|
||||
*/
|
||||
~Runner();
|
||||
|
||||
/**
|
||||
* @brief Starts the server and worker thread pool.
|
||||
*
|
||||
* @details
|
||||
* - Launches multiple worker threads.
|
||||
* - Each thread runs the `io_context` event loop.
|
||||
* - Begins processing asynchronous operations.
|
||||
*/
|
||||
void run();
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Worker thread entry point.
|
||||
*
|
||||
* @details
|
||||
* - Executes the `io_context::run()` loop.
|
||||
* - Processes asynchronous tasks until the context is stopped.
|
||||
*/
|
||||
void workerThread();
|
||||
|
||||
/**
|
||||
* @brief Stops the server and shuts down execution.
|
||||
*
|
||||
* @details
|
||||
* - Signals termination via the `running_` flag.
|
||||
* - Stops the `io_context`.
|
||||
* - Ensures all threads exit cleanly.
|
||||
*/
|
||||
void stop();
|
||||
|
||||
const std::shared_ptr<Config> &config_;///< Reference to the configuration object.
|
||||
const std::shared_ptr<Log> &log_; ///< Reference to the logging object.
|
||||
std::shared_ptr<Config> config_;
|
||||
std::shared_ptr<Log> log_;
|
||||
|
||||
boost::asio::io_context io_context_;///< Core I/O execution context.
|
||||
boost::asio::io_context io_context_;
|
||||
|
||||
/**
|
||||
* @brief Work guard to keep the `io_context` active.
|
||||
*
|
||||
* @details
|
||||
* - Prevents `io_context::run()` from returning when no tasks are queued.
|
||||
*/
|
||||
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work_guard_;
|
||||
|
||||
std::atomic<bool> running_;///< Indicates whether the runner is active.
|
||||
std::atomic<bool> running_;
|
||||
|
||||
std::vector<std::jthread> threadPool_;///< Pool of worker threads.
|
||||
std::vector<runnerThread> threadPool_;
|
||||
|
||||
/**
|
||||
* @brief Strand for serialized handler execution.
|
||||
*
|
||||
* @details
|
||||
* - Ensures that certain handlers do not execute concurrently.
|
||||
*/
|
||||
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
|
||||
};
|
||||
+317
-116
@@ -1,166 +1,372 @@
|
||||
#include "serverhandler.hpp"
|
||||
|
||||
/**
|
||||
* @brief Constructs a `ServerHandler` instance with buffers, configuration,
|
||||
* logging, client connection, and session identifier.
|
||||
*
|
||||
* @details
|
||||
* - Stores references to the configuration, logging, and client objects.
|
||||
* - Stores references to the read and write stream buffers.
|
||||
* - Creates an internal `HTTP` helper object for parsing and generating HTTP data.
|
||||
* - Stores the client connection string and UUID for logging and tracing.
|
||||
* - Initializes the internal state flags:
|
||||
* - `end_` is set to `false`
|
||||
* - `connect_` is set to `false`
|
||||
*
|
||||
* @param readBuffer Reference to the input stream buffer.
|
||||
* @param writeBuffer Reference to the output stream buffer.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param client Shared pointer to the TCP client used for remote communication.
|
||||
* @param clientConnStr String describing the client connection source.
|
||||
* @param uuid Unique identifier for this handler instance.
|
||||
*/
|
||||
#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 Destroys the `ServerHandler` instance.
|
||||
*
|
||||
* @details
|
||||
* - Performs no explicit cleanup.
|
||||
* - Resource management is handled by referenced objects and smart pointers.
|
||||
*/
|
||||
ServerHandler::~ServerHandler() {}
|
||||
|
||||
/**
|
||||
* @brief Handles an incoming agent request, decrypts it, forwards it to the target,
|
||||
* and prepares the response.
|
||||
*
|
||||
* @details
|
||||
* - Ensures thread-safe execution using an internal mutex.
|
||||
* - Parses the incoming request received from the agent.
|
||||
* - Decrypts the HTTP request body using the configured token.
|
||||
* - Converts the decrypted hexadecimal payload back into raw request data.
|
||||
* - Re-parses the decrypted request as HTTP or TLS-related traffic.
|
||||
* - Handles requests based on detected type:
|
||||
* - `CONNECT`: Establishes a tunnel and returns a connection status response.
|
||||
* - `HTTP` / `HTTPS`: Connects to the destination, forwards the request,
|
||||
* reads the remote response, encrypts it, and wraps it in an HTTP `200 OK` response.
|
||||
* - On any parsing, decryption, encryption, or connection failure, closes the client socket.
|
||||
*/
|
||||
void ServerHandler::handle() {
|
||||
std::lock_guard lock(mutex_);
|
||||
void ServerHandler::makePlainHttpResponse(const std::string &body,
|
||||
const std::string &status,
|
||||
const std::string &connection) {
|
||||
std::ostringstream outer;
|
||||
|
||||
// Parse outer request from agent
|
||||
if (!request_->detectType()) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [ServerHandler handle] [NOT HTTP Request From Agent] "
|
||||
"[Request] : " +
|
||||
streambufToString(readBuffer_),
|
||||
outer << "HTTP/1.1 " << status << "\r\n"
|
||||
<< "Content-Type: application/octet-stream\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::makePayloadHttpResponse(const std::string &plainBody,
|
||||
const std::string &status,
|
||||
const std::string &connection) {
|
||||
BoolStr encryption = config_->general().aesEnable
|
||||
? aes256Encrypt(plainBody, config_->general().token)
|
||||
: BoolStr{true, plainBody};
|
||||
|
||||
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<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);
|
||||
|
||||
client_->socket().close();
|
||||
return;
|
||||
}
|
||||
|
||||
const auto &outerReq = request_->parsedHttpRequest();
|
||||
const std::string method = std::string(outerReq.method_string());
|
||||
const std::string target = std::string(outerReq.target());
|
||||
|
||||
if (method != "POST" || target != "/relay") {
|
||||
copyStringToStreambuf(
|
||||
"HTTP/1.1 404 Not Found\r\n"
|
||||
"Content-Length: 0\r\n"
|
||||
"Connection: close\r\n\r\n",
|
||||
writeBuffer_);
|
||||
const std::string outerRaw = streambufToString(readBuffer_);
|
||||
|
||||
std::string requestBody = std::string(outerReq.body());
|
||||
|
||||
if (requestBody.empty()) {
|
||||
requestBody = HttpUtils::extractHttpBody(outerRaw);
|
||||
}
|
||||
|
||||
BoolStr decryption{false, std::string("FAILED")};
|
||||
|
||||
try {
|
||||
const std::string payload = decode64(requestBody);
|
||||
decryption = config_->general().aesEnable
|
||||
? aes256Decrypt(payload, config_->general().token)
|
||||
: BoolStr{true, payload};
|
||||
} 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;
|
||||
}
|
||||
|
||||
// Extract inner raw request from outer HTTP body
|
||||
const std::string innerRequest = std::string(outerReq.body());
|
||||
copyStringToStreambuf(innerRequest, readBuffer_);
|
||||
if (!decryption.ok) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [ServerHandler handle] [Decryption Failed] : [ " +
|
||||
decryption.message + "] ",
|
||||
Log::Level::DEBUG);
|
||||
|
||||
makePlainHttpResponse("", "400 Bad Request", "close");
|
||||
return;
|
||||
}
|
||||
|
||||
Envelope envelope;
|
||||
if (!parseEnvelope(decryption.message, envelope)) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [ServerHandler handle] [Invalid Envelope] (agent and server versions or aesEnable may differ)",
|
||||
Log::Level::DEBUG);
|
||||
|
||||
makePlainHttpResponse("", "400 Bad Request", "close");
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string &action = envelope.action;
|
||||
const std::string &session = envelope.session;
|
||||
decryption.message = std::move(envelope.data);
|
||||
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) + "] [ServerHandler handle] [Payload Decoded]",
|
||||
Log::Level::DEBUG);
|
||||
|
||||
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()) {
|
||||
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
return;
|
||||
}
|
||||
|
||||
boost::asio::streambuf tunnelBuf;
|
||||
copyStringToStreambuf(hexToASCII(decryption.message), tunnelBuf);
|
||||
targetClient->doWrite(tunnelBuf);
|
||||
|
||||
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
return;
|
||||
}
|
||||
|
||||
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()) {
|
||||
makePayloadHttpResponse("", "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) {
|
||||
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<char> data(std::min<std::size_t>(available, config_->general().bufferSize));
|
||||
std::size_t n = targetClient->socket().read_some(
|
||||
boost::asio::buffer(data),
|
||||
ec);
|
||||
|
||||
if (ec || n == 0) {
|
||||
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
return;
|
||||
}
|
||||
|
||||
makePayloadHttpResponse(
|
||||
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);
|
||||
}
|
||||
|
||||
makePayloadHttpResponse("", "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);
|
||||
|
||||
makePayloadHttpResponse("", "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);
|
||||
client_->socket().close();
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [ServerHandler handle] [NOT INNER HTTP Request] [Request] : " +
|
||||
streambufToString(readBuffer_),
|
||||
Log::Level::DEBUG);
|
||||
|
||||
makePayloadHttpResponse("", "400 Bad Request", "close");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (inner->httpType()) {
|
||||
case HTTP::HttpType::connect: {
|
||||
// Connect to requested destination and return the CONNECT response
|
||||
// inside the body of the outer HTTP response.
|
||||
if (client_->doConnect(inner->dstIP(), inner->dstPort())) {
|
||||
log_->write("[" + to_string(uuid_) + "] [CONNECT] [SRC " +
|
||||
clientConnStr_ + "] [DST " + inner->dstIP() + ":" +
|
||||
std::to_string(inner->dstPort()) + "]",
|
||||
if (config_->general().tunnelEnable) {
|
||||
if (!client_->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);
|
||||
|
||||
const std::string connectEstablished =
|
||||
"HTTP/1.1 200 Connection Established\r\n\r\n";
|
||||
makePayloadHttpResponse(
|
||||
"HTTP/1.1 502 Bad Gateway\r\n\r\n",
|
||||
"502 Bad Gateway",
|
||||
"close");
|
||||
|
||||
std::ostringstream outer;
|
||||
outer << "HTTP/1.1 200 OK\r\n"
|
||||
<< "Content-Type: application/octet-stream\r\n"
|
||||
<< "Content-Length: " << connectEstablished.size() << "\r\n"
|
||||
<< "Connection: keep-alive\r\n"
|
||||
<< "\r\n"
|
||||
<< connectEstablished;
|
||||
connect_ = false;
|
||||
end_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [CONNECT] [SRC " +
|
||||
clientConnStr_ + "] [DST " +
|
||||
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
|
||||
makePayloadHttpResponse(
|
||||
"HTTP/1.1 200 Connection Established\r\n\r\n",
|
||||
"200 OK",
|
||||
"keep-alive");
|
||||
|
||||
copyStringToStreambuf(outer.str(), writeBuffer_);
|
||||
connect_ = true;
|
||||
end_ = false;
|
||||
return;
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [CONNECT] [ERROR] [Resolving Host] [SRC " +
|
||||
clientConnStr_ + "] [DST " + inner->dstIP() + ":" +
|
||||
std::to_string(inner->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
}
|
||||
|
||||
const std::string connectFailed =
|
||||
"HTTP/1.1 502 Bad Gateway\r\n\r\n";
|
||||
TCPClient::pointer targetClient = TCPClient::create(
|
||||
static_cast<boost::asio::io_context &>(
|
||||
client_->socket().get_executor().context()),
|
||||
config_,
|
||||
log_);
|
||||
|
||||
std::ostringstream outer;
|
||||
outer << "HTTP/1.1 502 Bad Gateway\r\n"
|
||||
<< "Content-Type: application/octet-stream\r\n"
|
||||
<< "Content-Length: " << connectFailed.size() << "\r\n"
|
||||
<< "Connection: close\r\n"
|
||||
<< "\r\n"
|
||||
<< connectFailed;
|
||||
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);
|
||||
|
||||
makePayloadHttpResponse(
|
||||
"HTTP/1.1 502 Bad Gateway\r\n\r\n",
|
||||
"502 Bad Gateway",
|
||||
"close");
|
||||
|
||||
copyStringToStreambuf(outer.str(), writeBuffer_);
|
||||
connect_ = false;
|
||||
end_ = true;
|
||||
end_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [CONNECT] [SRC " +
|
||||
clientConnStr_ + "] [ORIGIN " +
|
||||
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;
|
||||
}
|
||||
|
||||
makePayloadHttpResponse(
|
||||
"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(inner->dstIP(), inner->dstPort())) {
|
||||
if (!client_->doConnect(inner->dstIp(), inner->dstPort())) {
|
||||
client_->socket().close();
|
||||
makePayloadHttpResponse("", "502 Bad Gateway", "close");
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -170,20 +376,15 @@ void ServerHandler::handle() {
|
||||
|
||||
if (client_->readBuffer().size() == 0) {
|
||||
client_->socket().close();
|
||||
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string innerResponse = streambufToString(client_->readBuffer());
|
||||
makePayloadHttpResponse(
|
||||
streambufToString(client_->readBuffer()),
|
||||
"200 OK",
|
||||
(config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
|
||||
std::ostringstream outer;
|
||||
outer << "HTTP/1.1 200 OK\r\n"
|
||||
<< "Content-Type: application/octet-stream\r\n"
|
||||
<< "Content-Length: " << innerResponse.size() << "\r\n"
|
||||
<< "Connection: keep-alive\r\n"
|
||||
<< "\r\n"
|
||||
<< innerResponse;
|
||||
|
||||
copyStringToStreambuf(outer.str(), writeBuffer_);
|
||||
connect_ = false;
|
||||
end_ = false;
|
||||
return;
|
||||
|
||||
+37
-95
@@ -1,6 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "config.hpp"
|
||||
#include "general.hpp"
|
||||
@@ -8,124 +11,63 @@
|
||||
#include "log.hpp"
|
||||
#include "tcpclient.hpp"
|
||||
|
||||
/**
|
||||
* @brief The `ServerHandler` class manages server-side request processing for a single connection.
|
||||
*
|
||||
* @details
|
||||
* - Responsible for handling incoming client data and generating responses.
|
||||
* - Integrates with the `HTTP` parser for request processing.
|
||||
* - Uses `TCPClient` to manage the underlying connection.
|
||||
* - Maintains connection state such as completion and CONNECT tunneling.
|
||||
* - Ensures thread-safe operations using an internal mutex.
|
||||
*
|
||||
* @note
|
||||
* - Inherits from `Uncopyable` to prevent copying.
|
||||
* - Uses shared ownership via `std::shared_ptr`.
|
||||
* - Instances should be created using the `create` factory method.
|
||||
*/
|
||||
class ServerHandler : private Uncopyable {
|
||||
public:
|
||||
using pointer = std::shared_ptr<ServerHandler>;
|
||||
|
||||
/**
|
||||
* @brief Factory method to create a new `ServerHandler` instance.
|
||||
*
|
||||
* @details
|
||||
* - Wraps construction in a `std::shared_ptr`.
|
||||
* - Ensures consistent ownership and lifecycle management.
|
||||
*
|
||||
* @param readBuffer Reference to the stream buffer for incoming data.
|
||||
* @param writeBuffer Reference to the stream buffer for outgoing data.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param client Shared pointer to the associated `TCPClient`.
|
||||
* @param clientConnStr String describing the client connection (e.g., IP:port).
|
||||
* @param uuid Unique identifier for this connection.
|
||||
* @return A shared pointer to the created `ServerHandler`.
|
||||
*/
|
||||
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 `ServerHandler`.
|
||||
*
|
||||
* @details
|
||||
* - Performs no explicit cleanup.
|
||||
* - Resource management is handled by referenced objects and smart pointers.
|
||||
*/
|
||||
~ServerHandler();
|
||||
|
||||
/**
|
||||
* @brief Processes the incoming request and generates the appropriate response.
|
||||
*
|
||||
* @details
|
||||
* - Parses incoming data using the `HTTP` handler.
|
||||
* - Handles connection logic, including CONNECT tunneling.
|
||||
* - Coordinates communication with the client and remote endpoints.
|
||||
*/
|
||||
void handle();
|
||||
|
||||
/**
|
||||
* @brief Returns a reference to the associated HTTP request object.
|
||||
*
|
||||
* @return Const reference to the HTTP request pointer.
|
||||
*/
|
||||
inline const HTTP::pointer &request() & { return request_; }
|
||||
inline const HTTP::pointer &request() const { return request_; }
|
||||
|
||||
/**
|
||||
* @brief Returns an rvalue reference to the HTTP request object.
|
||||
*
|
||||
* @details
|
||||
* - Enables move semantics when transferring ownership.
|
||||
*
|
||||
* @return Rvalue reference to the HTTP request pointer.
|
||||
*/
|
||||
inline const HTTP::pointer &&request() && { return std::move(request_); }
|
||||
|
||||
bool end_; ///< Indicates whether request processing is complete.
|
||||
bool connect_;///< Indicates whether a CONNECT tunnel or persistent connection is active.
|
||||
bool end_;
|
||||
bool connect_;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Constructs a `ServerHandler` instance.
|
||||
*
|
||||
* @details
|
||||
* - Initializes buffers, configuration, logging, and client references.
|
||||
* - Creates the internal HTTP request handler.
|
||||
* - Stores connection metadata and unique identifier.
|
||||
*
|
||||
* @param readBuffer Reference to the input stream buffer.
|
||||
* @param writeBuffer Reference to the output stream buffer.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param client Shared pointer to the TCP client.
|
||||
* @param clientConnStr Client connection description string.
|
||||
* @param uuid Unique identifier for this handler instance.
|
||||
*/
|
||||
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_;///< Reference to the configuration object.
|
||||
const std::shared_ptr<Log> &log_; ///< Reference to the logging object.
|
||||
const TCPClient::pointer &client_; ///< Reference to the TCP client.
|
||||
boost::asio::streambuf &readBuffer_; ///< Buffer for incoming data.
|
||||
boost::asio::streambuf &writeBuffer_; ///< Buffer for outgoing data.
|
||||
HTTP::pointer request_; ///< HTTP request handler instance.
|
||||
const std::string &clientConnStr_; ///< Client connection string.
|
||||
boost::uuids::uuid uuid_; ///< Unique identifier for this handler.
|
||||
void makePayloadHttpResponse(const std::string &plainBody,
|
||||
const std::string &status = "200 OK",
|
||||
const std::string &connection = "close");
|
||||
|
||||
std::mutex mutex_;///< Mutex for thread-safe operations.
|
||||
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_;
|
||||
std::string clientConnStr_;
|
||||
boost::uuids::uuid uuid_;
|
||||
std::mutex mutex_;
|
||||
};
|
||||
+475
-376
File diff suppressed because it is too large.
Load diff
+49
-151
@@ -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,195 +13,94 @@
|
||||
#include "http.hpp"
|
||||
#include "log.hpp"
|
||||
|
||||
/**
|
||||
* @brief The `TCPClient` class manages TCP and optional TLS communication with remote endpoints.
|
||||
*
|
||||
* @details
|
||||
* - Provides connection management, including DNS resolution and socket handling.
|
||||
* - Supports both plain TCP and TLS (SSL) communication.
|
||||
* - Handles reading and writing of data using Boost.Asio stream buffers.
|
||||
* - Manages connection timeouts and error handling.
|
||||
* - Designed to be used with shared ownership (`boost::shared_ptr`).
|
||||
*
|
||||
* @note
|
||||
* - Inherits from `boost::enable_shared_from_this` to allow safe shared pointer usage.
|
||||
* - Thread safety is ensured using an internal mutex where required.
|
||||
*/
|
||||
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>;
|
||||
|
||||
/**
|
||||
* @brief Factory method to create a new `TCPClient` instance.
|
||||
*
|
||||
* @param io_context Reference to the Boost.Asio I/O context.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @return Shared pointer to the created `TCPClient`.
|
||||
*/
|
||||
static pointer create(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log) {
|
||||
return pointer(new TCPClient(io_context, config, log));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the underlying TCP socket.
|
||||
*
|
||||
* @return Reference to the TCP socket.
|
||||
*/
|
||||
tcp::socket &socket();
|
||||
|
||||
/**
|
||||
* @brief Returns the TLS (SSL) socket stream.
|
||||
*
|
||||
* @return Reference to the SSL stream.
|
||||
*/
|
||||
ssl_stream &sslSocket();
|
||||
|
||||
/**
|
||||
* @brief Indicates whether TLS is enabled for this client.
|
||||
*
|
||||
* @return `true` if TLS is enabled, otherwise `false`.
|
||||
*/
|
||||
bool tlsEnabled() const;
|
||||
|
||||
/**
|
||||
* @brief Checks whether the underlying socket is open.
|
||||
*
|
||||
* @return `true` if the socket is open, otherwise `false`.
|
||||
*/
|
||||
bool isOpen() const;
|
||||
|
||||
/**
|
||||
* @brief Enables TLS for the client connection.
|
||||
*
|
||||
* @details
|
||||
* - Initializes the SSL context.
|
||||
* - Prepares the SSL stream for encrypted communication.
|
||||
*
|
||||
* @return `true` if initialization succeeds, otherwise `false`.
|
||||
*/
|
||||
bool enableTlsClient();
|
||||
|
||||
/**
|
||||
* @brief Performs a TLS handshake with the remote endpoint.
|
||||
*
|
||||
* @details
|
||||
* - Must be called after establishing a TCP connection.
|
||||
*
|
||||
* @return `true` if the handshake succeeds, otherwise `false`.
|
||||
*/
|
||||
bool doHandshakeClient();
|
||||
bool doConnect(const std::string &dstIp, unsigned short dstPort);
|
||||
|
||||
/**
|
||||
* @brief Writes data into the internal write buffer.
|
||||
*
|
||||
* @param buffer Source buffer to copy into the internal write buffer.
|
||||
*/
|
||||
void writeBuffer(boost::asio::streambuf &buffer);
|
||||
|
||||
/**
|
||||
* @brief Returns the internal write buffer (lvalue).
|
||||
*/
|
||||
inline boost::asio::streambuf &writeBuffer() & { return writeBuffer_; }
|
||||
|
||||
/**
|
||||
* @brief Returns the internal write buffer (rvalue).
|
||||
*/
|
||||
inline boost::asio::streambuf &&writeBuffer() && {
|
||||
return std::move(writeBuffer_);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the internal read buffer (lvalue).
|
||||
*/
|
||||
inline boost::asio::streambuf &readBuffer() & { return readBuffer_; }
|
||||
|
||||
/**
|
||||
* @brief Returns the internal read buffer (rvalue).
|
||||
*/
|
||||
inline boost::asio::streambuf &&readBuffer() && { return std::move(readBuffer_); }
|
||||
|
||||
/**
|
||||
* @brief Establishes a connection to the specified destination.
|
||||
*
|
||||
* @param dstIP Destination IP address or hostname.
|
||||
* @param dstPort Destination port.
|
||||
* @return `true` if the connection succeeds, otherwise `false`.
|
||||
*/
|
||||
bool doConnect(const std::string &dstIP, const unsigned short &dstPort);
|
||||
|
||||
/**
|
||||
* @brief Writes data to the remote endpoint.
|
||||
*
|
||||
* @param buffer Buffer containing the data to send.
|
||||
*/
|
||||
void doWrite(boost::asio::streambuf &buffer);
|
||||
|
||||
/**
|
||||
* @brief Reads data from the agent-side connection.
|
||||
*/
|
||||
void doReadAgent();
|
||||
|
||||
/**
|
||||
* @brief Reads data from the server-side connection.
|
||||
*/
|
||||
bool doReadAgent();
|
||||
bool doWrite(boost::asio::streambuf &buffer);
|
||||
void doReadServer();
|
||||
|
||||
/**
|
||||
* @brief Shuts down and closes the socket connection.
|
||||
*/
|
||||
void socketShutdown();
|
||||
|
||||
boost::uuids::uuid uuid_;///< Unique identifier for this client session.
|
||||
bool end_; ///< Indicates whether the connection has completed.
|
||||
boost::uuids::uuid uuid() const { return uuid_; }
|
||||
bool ended() const { return end_; }
|
||||
|
||||
boost::uuids::uuid uuid_;
|
||||
bool end_;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Constructs a `TCPClient` instance.
|
||||
*
|
||||
* @param io_context Reference to the Boost.Asio I/O context.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
*/
|
||||
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);
|
||||
|
||||
/**
|
||||
* @brief Resets the connection timeout timer.
|
||||
*/
|
||||
void resetTimeout();
|
||||
|
||||
/**
|
||||
* @brief Cancels the connection timeout timer.
|
||||
*/
|
||||
void cancelTimeout();
|
||||
|
||||
/**
|
||||
* @brief Handles timeout events.
|
||||
*
|
||||
* @param error Boost system error code.
|
||||
*/
|
||||
void onTimeout(const boost::system::error_code &error);
|
||||
|
||||
const std::shared_ptr<Config> &config_;///< Reference to the configuration object.
|
||||
const std::shared_ptr<Log> &log_; ///< Reference to the logging object.
|
||||
boost::asio::io_context &io_context_; ///< Reference to the I/O context.
|
||||
std::shared_ptr<Config> config_;
|
||||
std::shared_ptr<Log> log_;
|
||||
boost::asio::io_context &io_context_;
|
||||
|
||||
tcp::socket socket_; ///< Underlying TCP socket.
|
||||
boost::asio::ssl::context sslContext_; ///< SSL context for TLS connections.
|
||||
std::unique_ptr<ssl_stream> sslSocket_;///< SSL stream wrapper.
|
||||
bool tlsEnabled_; ///< Indicates whether TLS is active.
|
||||
tcp::socket socket_;
|
||||
boost::asio::ssl::context sslContext_;
|
||||
std::unique_ptr<ssl_stream> sslSocket_;
|
||||
bool tlsEnabled_;
|
||||
|
||||
boost::asio::streambuf buffer_; ///< General-purpose buffer.
|
||||
boost::asio::streambuf writeBuffer_;///< Buffer for outgoing data.
|
||||
boost::asio::streambuf readBuffer_; ///< Buffer for incoming data.
|
||||
boost::asio::streambuf buffer_;
|
||||
boost::asio::streambuf writeBuffer_;
|
||||
boost::asio::streambuf readBuffer_;
|
||||
|
||||
tcp::resolver resolver_; ///< DNS resolver.
|
||||
boost::asio::steady_timer timeout_;///< Timeout timer.
|
||||
mutable std::mutex mutex_; ///< Mutex for thread-safe operations.
|
||||
tcp::resolver resolver_;
|
||||
boost::asio::steady_timer timeout_;
|
||||
mutable std::mutex mutex_;
|
||||
bool closed_ = false;
|
||||
};
|
||||
+925
-577
File diff suppressed because it is too large.
Load diff
+92
-192
@@ -1,57 +1,28 @@
|
||||
#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"
|
||||
|
||||
/**
|
||||
* @brief The `TCPConnection` class manages a single inbound connection and its forwarding lifecycle.
|
||||
*
|
||||
* @details
|
||||
* - Owns the accepted client-side socket.
|
||||
* - Optionally supports TLS on the server-facing accepted connection.
|
||||
* - Coordinates request handling using either `AgentHandler` or `ServerHandler`
|
||||
* depending on the runtime mode.
|
||||
* - Manages asynchronous reads, writes, timeout handling, and tunnel relaying.
|
||||
* - Maintains per-connection state such as connection completion, CONNECT mode,
|
||||
* and full tunnel mode.
|
||||
*
|
||||
* @note
|
||||
* - Inherits from `boost::enable_shared_from_this` to safely retain itself
|
||||
* during asynchronous operations.
|
||||
* - Uses shared ownership via `boost::shared_ptr`.
|
||||
* - Instances should be created using the `create` factory method.
|
||||
*/
|
||||
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>;
|
||||
|
||||
/**
|
||||
* @brief Factory method to create a new `TCPConnection` instance.
|
||||
*
|
||||
* @details
|
||||
* - Wraps construction in a `boost::shared_ptr`.
|
||||
* - Ensures consistent ownership and lifetime management for asynchronous use.
|
||||
*
|
||||
* @param io_context Reference to the Boost.Asio I/O context.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param client Shared pointer to the associated outbound `TCPClient`.
|
||||
* @return Shared pointer to the created `TCPConnection`.
|
||||
*/
|
||||
static pointer create(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
@@ -59,198 +30,127 @@ public:
|
||||
return pointer(new TCPConnection(io_context, config, log, client));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the accepted client-side socket.
|
||||
*
|
||||
* @return Reference to the underlying TCP socket.
|
||||
*/
|
||||
boost::asio::ip::tcp::socket &socket();
|
||||
|
||||
/**
|
||||
* @brief Returns the associated outbound `TCPClient`.
|
||||
*
|
||||
* @return Shared pointer to the client object.
|
||||
*/
|
||||
inline TCPClient::pointer client() { return client_; }
|
||||
|
||||
/**
|
||||
* @brief Returns the TLS server stream.
|
||||
*
|
||||
* @return Reference to the TLS socket stream.
|
||||
*/
|
||||
inline TCPClient::pointer client() const { return client_; }
|
||||
ssl_stream &tlsSocket();
|
||||
|
||||
/**
|
||||
* @brief Initializes the TLS server context for this connection.
|
||||
*
|
||||
* @details
|
||||
* - Loads certificates, private key, and related TLS configuration.
|
||||
* - Prepares the connection to accept inbound TLS handshakes.
|
||||
*
|
||||
* @return `true` if initialization succeeds, otherwise `false`.
|
||||
*/
|
||||
bool initTlsServerContext();
|
||||
|
||||
/**
|
||||
* @brief Performs the server-side TLS handshake.
|
||||
*
|
||||
* @return `true` if the handshake succeeds, otherwise `false`.
|
||||
*/
|
||||
bool doHandshakeServer();
|
||||
|
||||
/**
|
||||
* @brief Replaces the internal write buffer with the provided buffer contents.
|
||||
*
|
||||
* @param buffer Source buffer whose contents are moved into the internal write buffer.
|
||||
*/
|
||||
inline void writeBuffer(boost::asio::streambuf &buffer) {
|
||||
moveStreambuf(buffer, writeBuffer_);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the internal read buffer (lvalue).
|
||||
*
|
||||
* @return Const reference to the internal read buffer.
|
||||
*/
|
||||
inline const boost::asio::streambuf &readBuffer() & { return readBuffer_; }
|
||||
|
||||
/**
|
||||
* @brief Returns the internal read buffer (rvalue).
|
||||
*
|
||||
* @return Const rvalue reference to the internal read buffer.
|
||||
*/
|
||||
inline const boost::asio::streambuf &&readBuffer() && {
|
||||
return std::move(readBuffer_);
|
||||
}
|
||||
inline boost::uuids::uuid uuid() const { return uuid_; }
|
||||
|
||||
/**
|
||||
* @brief Returns the UUID associated with this connection.
|
||||
*
|
||||
* @return Connection UUID.
|
||||
*/
|
||||
inline boost::uuids::uuid uuid() { return uuid_; }
|
||||
|
||||
/**
|
||||
* @brief Starts connection processing in agent mode.
|
||||
*
|
||||
* @details
|
||||
* - Uses `AgentHandler` logic to process incoming traffic.
|
||||
*/
|
||||
void startAgent();
|
||||
|
||||
/**
|
||||
* @brief Starts connection processing in server mode.
|
||||
*
|
||||
* @details
|
||||
* - Uses `ServerHandler` logic to process incoming traffic.
|
||||
*/
|
||||
void startServer();
|
||||
|
||||
/**
|
||||
* @brief Initiates an asynchronous read for agent-side traffic.
|
||||
*/
|
||||
void doReadAgent();
|
||||
|
||||
/**
|
||||
* @brief Initiates an asynchronous read for server-side traffic.
|
||||
*/
|
||||
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);
|
||||
|
||||
/**
|
||||
* @brief Handles completion of an agent-side asynchronous read.
|
||||
*
|
||||
* @param error Boost system error code.
|
||||
* @param bytes_transferred Number of bytes received.
|
||||
*/
|
||||
void handleReadAgent(const boost::system::error_code &error,
|
||||
size_t bytes_transferred);
|
||||
|
||||
/**
|
||||
* @brief Handles completion of a server-side asynchronous read.
|
||||
*
|
||||
* @param error Boost system error code.
|
||||
* @param bytes_transferred Number of bytes received.
|
||||
*/
|
||||
void handleReadServer(const boost::system::error_code &error,
|
||||
size_t bytes_transferred);
|
||||
|
||||
/**
|
||||
* @brief Gracefully shuts down and closes the active connection.
|
||||
*/
|
||||
void socketShutdown();
|
||||
|
||||
/**
|
||||
* @brief Enables full tunnel relay mode.
|
||||
*
|
||||
* @details
|
||||
* - Used after CONNECT-style negotiation when traffic should be relayed
|
||||
* transparently in both directions.
|
||||
*/
|
||||
void enableTunnelMode();
|
||||
void enableDirectTunnelMode();
|
||||
|
||||
/**
|
||||
* @brief Relays traffic from the connected client to the remote endpoint.
|
||||
*/
|
||||
void relayClientToRemote();
|
||||
void relayClientToServer();
|
||||
void relayServerToClient();
|
||||
|
||||
/**
|
||||
* @brief Relays traffic from the remote endpoint back to the connected client.
|
||||
*/
|
||||
void relayRemoteToClient();
|
||||
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:
|
||||
/**
|
||||
* @brief Constructs a `TCPConnection` instance.
|
||||
*
|
||||
* @param io_context Reference to the Boost.Asio I/O context.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param client Shared pointer to the associated outbound `TCPClient`.
|
||||
*/
|
||||
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);
|
||||
|
||||
/**
|
||||
* @brief Starts or resets the timeout timer for the connection.
|
||||
*/
|
||||
bool handleSocks5Handshake();
|
||||
bool readExactFromClient(void *data, std::size_t size);
|
||||
|
||||
void resetTimeout();
|
||||
|
||||
/**
|
||||
* @brief Cancels the active timeout timer.
|
||||
*/
|
||||
void cancelTimeout();
|
||||
|
||||
/**
|
||||
* @brief Handles timeout expiration events.
|
||||
*
|
||||
* @param error Boost system error code for the timer event.
|
||||
*/
|
||||
void onTimeout(const boost::system::error_code &error);
|
||||
|
||||
boost::asio::ip::tcp::socket socket_; ///< Accepted inbound socket.
|
||||
boost::asio::ssl::context sslContext_; ///< TLS server context.
|
||||
std::unique_ptr<ssl_stream> tlsSocket_;///< Optional TLS-wrapped inbound socket.
|
||||
void startTunnelReadFromClient();
|
||||
void startTunnelPollServer();
|
||||
std::string postTunnelAction(const std::string &action, const std::string &rawBody);
|
||||
std::string makeRelayHostHeader() const;
|
||||
void closeTunnelSession();
|
||||
|
||||
const std::shared_ptr<Config> &config_;///< Reference to the configuration object.
|
||||
const std::shared_ptr<Log> &log_; ///< Reference to the logging object.
|
||||
boost::asio::io_context &io_context_; ///< Reference to the I/O context.
|
||||
TCPClient::pointer client_; ///< Associated outbound TCP client.
|
||||
boost::asio::ip::tcp::socket socket_;
|
||||
boost::asio::ssl::context sslContext_;
|
||||
std::unique_ptr<ssl_stream> tlsSocket_;
|
||||
|
||||
boost::asio::streambuf readBuffer_; ///< Buffer for incoming data.
|
||||
boost::asio::streambuf writeBuffer_;///< Buffer for outgoing data.
|
||||
std::shared_ptr<Config> config_;
|
||||
std::shared_ptr<Log> log_;
|
||||
boost::asio::io_context &io_context_;
|
||||
TCPClient::pointer client_;
|
||||
|
||||
boost::asio::steady_timer timeout_; ///< Per-connection timeout timer.
|
||||
boost::asio::strand<boost::asio::io_context::executor_type> strand_;///< Strand for serialized handlers.
|
||||
boost::asio::streambuf readBuffer_;
|
||||
boost::asio::streambuf writeBuffer_;
|
||||
|
||||
boost::uuids::uuid uuid_;///< Unique identifier for this connection.
|
||||
std::mutex mutex_; ///< Mutex for thread-safe state changes.
|
||||
boost::asio::steady_timer timeout_;
|
||||
boost::asio::steady_timer pollTimer_;
|
||||
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
|
||||
|
||||
bool end_; ///< Indicates whether processing has completed.
|
||||
bool connect_; ///< Indicates whether a connection or CONNECT tunnel is active.
|
||||
bool tunnelMode_;///< Indicates whether transparent bidirectional relay mode is enabled.
|
||||
boost::uuids::uuid uuid_;
|
||||
std::mutex mutex_;
|
||||
|
||||
std::array<char, 16384> downstreamBuf_;///< Buffer for traffic flowing to the remote side.
|
||||
std::array<char, 16384> upstreamBuf_; ///< Buffer for traffic flowing back to the client.
|
||||
bool end_;
|
||||
bool connect_;
|
||||
bool tunnelMode_;
|
||||
bool tunnelClosed_;
|
||||
bool pollInProgress_;
|
||||
unsigned int pollDelayMs_;
|
||||
std::atomic_bool closed_{false};
|
||||
|
||||
std::array<char, BufferSize> downstreamBuf_;
|
||||
std::array<char, BufferSize> upstreamBuf_;
|
||||
};
|
||||
+24
-70
@@ -1,17 +1,8 @@
|
||||
#include "tcpserver.hpp"
|
||||
|
||||
/**
|
||||
* @brief Constructs a `TCPServer` instance and initializes the listening acceptor.
|
||||
*
|
||||
* @details
|
||||
* - Binds the acceptor to the configured IP address and port.
|
||||
* - Enables `reuse_address` to allow quick restarts without waiting for socket release.
|
||||
* - Immediately starts accepting incoming connections.
|
||||
*
|
||||
* @param io_context Reference to the Boost.Asio I/O context.
|
||||
* @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)
|
||||
@@ -23,18 +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 Initiates an asynchronous accept operation for incoming connections.
|
||||
*
|
||||
* @details
|
||||
* - Creates a new `TCPClient` and associated `TCPConnection`.
|
||||
* - Calls `async_accept` to wait for incoming connections.
|
||||
* - On completion, forwards control to `handleAccept()`.
|
||||
*/
|
||||
void TCPServer::startAccept() {
|
||||
auto client = TCPClient::create(io_context_, config_, log_);
|
||||
auto connection = TCPConnection::create(io_context_, config_, log_, client);
|
||||
@@ -46,71 +28,43 @@ void TCPServer::startAccept() {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Handles the result of an asynchronous accept operation.
|
||||
*
|
||||
* @details
|
||||
* - On successful accept:
|
||||
* - In **server mode**:
|
||||
* - Initializes TLS server context.
|
||||
* - Transfers the accepted socket to the TLS stream.
|
||||
* - Performs TLS handshake.
|
||||
* - Starts server-side processing.
|
||||
* - In **agent mode**:
|
||||
* - Starts agent-side processing directly (no TLS termination).
|
||||
*
|
||||
* - On failure:
|
||||
* - Logs the error.
|
||||
*
|
||||
* - Always continues accepting new connections regardless of outcome.
|
||||
*
|
||||
* @param connection Shared pointer to the accepted `TCPConnection`.
|
||||
* @param error Error code returned by 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) {
|
||||
// Initialize TLS context for incoming server connections
|
||||
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;
|
||||
}
|
||||
|
||||
// Move plain socket into TLS layer
|
||||
connection->tlsSocket().lowest_layer() = std::move(connection->socket());
|
||||
|
||||
// Perform TLS handshake
|
||||
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;
|
||||
}
|
||||
|
||||
// Start server-side handling
|
||||
connection->startServer();
|
||||
} else {
|
||||
// Start agent-side handling (no TLS termination)
|
||||
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();
|
||||
}
|
||||
|
||||
// Continue accepting new connections
|
||||
startAccept();
|
||||
}
|
||||
+7
-61
@@ -1,86 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <memory>
|
||||
|
||||
#include "tcpconnection.hpp"
|
||||
|
||||
/**
|
||||
* @brief The `TCPServer` class accepts incoming TCP connections and dispatches them for handling.
|
||||
*
|
||||
* @details
|
||||
* - Owns the listening acceptor socket.
|
||||
* - Uses the provided Boost.Asio `io_context` for asynchronous accept operations.
|
||||
* - Creates `TCPConnection` instances for accepted clients.
|
||||
* - Integrates with configuration and logging components.
|
||||
*
|
||||
* @note
|
||||
* - Instances are managed through shared ownership using `boost::shared_ptr`.
|
||||
* - Objects should be created using the `create` factory method.
|
||||
*/
|
||||
class TCPServer {
|
||||
public:
|
||||
using pointer = boost::shared_ptr<TCPServer>;
|
||||
using pointer = std::shared_ptr<TCPServer>;
|
||||
|
||||
/**
|
||||
* @brief Factory method to create a new `TCPServer` instance.
|
||||
*
|
||||
* @details
|
||||
* - Wraps object construction in a `boost::shared_ptr`.
|
||||
* - Ensures consistent ownership and lifetime management.
|
||||
*
|
||||
* @param io_context Reference to the Boost.Asio I/O context.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @return Shared pointer to the created `TCPServer`.
|
||||
*/
|
||||
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 accepting incoming client connections.
|
||||
*
|
||||
* @details
|
||||
* - Begins an asynchronous accept operation on the listening socket.
|
||||
* - Accepted connections are passed to `handleAccept()`.
|
||||
*/
|
||||
void startAccept();
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Constructs a `TCPServer` instance.
|
||||
*
|
||||
* @details
|
||||
* - Stores references to the configuration, logging object, and I/O context.
|
||||
* - Initializes the listening acceptor socket.
|
||||
*
|
||||
* @param io_context Reference to the Boost.Asio I/O context.
|
||||
* @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 completion of an asynchronous accept operation.
|
||||
*
|
||||
* @details
|
||||
* - Receives the newly accepted `TCPConnection`.
|
||||
* - Inspects the accept result through the provided error code.
|
||||
* - Starts connection processing when accept succeeds.
|
||||
*
|
||||
* @param connection Shared pointer to the accepted `TCPConnection`.
|
||||
* @param error Result of the accept operation.
|
||||
*/
|
||||
void handleAccept(TCPConnection::pointer connection,
|
||||
const boost::system::error_code &error);
|
||||
|
||||
const std::shared_ptr<Config> &config_; ///< Reference to the configuration object.
|
||||
const std::shared_ptr<Log> &log_; ///< Reference to the logging object.
|
||||
boost::asio::io_context &io_context_; ///< Reference to the I/O context.
|
||||
boost::asio::ip::tcp::acceptor acceptor_;///< Listening TCP acceptor.
|
||||
};
|
||||
std::shared_ptr<Config> config_;
|
||||
std::shared_ptr<Log> log_;
|
||||
boost::asio::io_context &io_context_;
|
||||
boost::asio::ip::tcp::acceptor acceptor_;
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
FROM ubuntu:24.04 AS builder
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
build-essential \
|
||||
cmake \
|
||||
git \
|
||||
libboost-all-dev \
|
||||
libssl-dev \
|
||||
libyaml-cpp-dev \
|
||||
ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN cmake -S . -B build -DCMAKE_BUILD_TYPE=Release \
|
||||
&& cmake --build build --target nipovpn -j$(nproc)
|
||||
|
||||
|
||||
FROM ubuntu:24.04
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
libboost-regex1.83.0 \
|
||||
libssl3t64 \
|
||||
libyaml-cpp0.8 \
|
||||
ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN mkdir -p /etc/nipovpn /var/log/nipovpn
|
||||
|
||||
COPY --from=builder /src/build/core/nipovpn /usr/local/bin/nipovpn
|
||||
COPY nipovpn/etc/nipovpn/config.yaml /etc/nipovpn/config.yaml
|
||||
|
||||
ENTRYPOINT ["nipovpn"]
|
||||
CMD ["server", "/etc/nipovpn/config.yaml"]
|
||||
@@ -0,0 +1,26 @@
|
||||
services:
|
||||
nipovpn:
|
||||
container_name: nipovpn
|
||||
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile
|
||||
|
||||
image: nipovpn:latest
|
||||
|
||||
restart: unless-stopped
|
||||
|
||||
ports:
|
||||
- "443:443"
|
||||
- "8080:8080"
|
||||
|
||||
volumes:
|
||||
- ../nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro
|
||||
- nipovpn_logs:/var/log/nipovpn
|
||||
|
||||
command:
|
||||
- ${NIPOVPN_MODE:-server}
|
||||
- /etc/nipovpn/config.yaml
|
||||
|
||||
volumes:
|
||||
nipovpn_logs:
|
||||
Generated
+61
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"nodes": {
|
||||
"flake-utils": {
|
||||
"inputs": {
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1731533236,
|
||||
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1780243769,
|
||||
"narHash": "sha256-x5UQuRsH3MqI0U9afaXSNqzTPSeZlRLvFAav2Ux1pNw=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "331800de5053fcebacf6813adb5db9c9dca22a0c",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"flake-utils": "flake-utils",
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
},
|
||||
"systems": {
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
{
|
||||
description = "NipoVPN - Powerful HTTP proxy";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
flake-utils.url = "github:numtide/flake-utils";
|
||||
};
|
||||
|
||||
outputs = {
|
||||
self,
|
||||
nixpkgs,
|
||||
flake-utils,
|
||||
}:
|
||||
flake-utils.lib.eachSystem ["x86_64-linux" "aarch64-linux"] (system: let
|
||||
pkgs = nixpkgs.legacyPackages.${system};
|
||||
nipovpn = pkgs.stdenv.mkDerivation {
|
||||
pname = "nipovpn";
|
||||
version = "1.1.57";
|
||||
src = self;
|
||||
|
||||
nativeBuildInputs = with pkgs; [cmake];
|
||||
buildInputs = with pkgs; [boost yaml-cpp openssl];
|
||||
|
||||
cmakeFlags = ["-DCMAKE_BUILD_TYPE=Release"];
|
||||
|
||||
installPhase = ''
|
||||
runHook preInstall
|
||||
mkdir -p $out/bin $out/etc/nipovpn
|
||||
cp core/nipovpn $out/bin/nipovpn
|
||||
cp -r $src/nipovpn/etc/nipovpn/. $out/etc/nipovpn/
|
||||
runHook postInstall
|
||||
'';
|
||||
|
||||
meta = with pkgs.lib; {
|
||||
description = "Powerful HTTP proxy with traffic obfuscation";
|
||||
homepage = "https://github.com/MortezaBashsiz/nipovpn";
|
||||
license = licenses.gpl3Plus;
|
||||
platforms = platforms.linux;
|
||||
mainProgram = "nipovpn";
|
||||
};
|
||||
};
|
||||
in {
|
||||
packages.default = nipovpn;
|
||||
packages.nipovpn = nipovpn;
|
||||
|
||||
devShells.default = pkgs.mkShell {
|
||||
buildInputs = with pkgs; [
|
||||
cmake
|
||||
ninja
|
||||
boost
|
||||
yaml-cpp
|
||||
openssl
|
||||
clang-tools
|
||||
gdb
|
||||
valgrind
|
||||
];
|
||||
|
||||
shellHook = ''
|
||||
echo "NipoVPN dev environment ready"
|
||||
echo ""
|
||||
echo "You can build using either Make or Ninja:"
|
||||
echo " Standard (Make):"
|
||||
echo " cmake -B build -DCMAKE_BUILD_TYPE=Debug"
|
||||
echo " cmake --build build -j\$(nproc)"
|
||||
echo ""
|
||||
echo " Fast (Ninja):"
|
||||
echo " cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug"
|
||||
echo " cmake --build build -j\$(nproc)"
|
||||
'';
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
# NipoVPN Docker
|
||||
|
||||
This directory contains Docker files for building and running **NipoVPN** in either `server` or `agent` mode.
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```text
|
||||
nipovpn/
|
||||
├── docker/
|
||||
│ ├── Dockerfile
|
||||
│ ├── docker-compose.yml
|
||||
│ └── README.md
|
||||
├── nipovpn/
|
||||
│ └── etc/nipovpn/config.yaml
|
||||
├── core/
|
||||
├── CMakeLists.txt
|
||||
└── .dockerignore
|
||||
```
|
||||
|
||||
## Requirements
|
||||
|
||||
Install Docker and Docker Compose:
|
||||
|
||||
```bash
|
||||
docker --version
|
||||
docker compose version
|
||||
```
|
||||
|
||||
For older systems:
|
||||
|
||||
```bash
|
||||
docker-compose --version
|
||||
```
|
||||
|
||||
## Important: `.dockerignore`
|
||||
|
||||
Create `.dockerignore` in the repository root:
|
||||
|
||||
```text
|
||||
.git
|
||||
.github
|
||||
build
|
||||
cmake-build-*
|
||||
*.deb
|
||||
*.tar.gz
|
||||
*.log
|
||||
```
|
||||
|
||||
This prevents local build files from being copied into the Docker image.
|
||||
|
||||
## Docker Compose File
|
||||
|
||||
The compose file is located at:
|
||||
|
||||
```bash
|
||||
docker/docker-compose.yml
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
nipovpn:
|
||||
container_name: nipovpn
|
||||
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile
|
||||
|
||||
image: nipovpn:latest
|
||||
|
||||
restart: unless-stopped
|
||||
|
||||
ports:
|
||||
- "443:443"
|
||||
- "8080:8080"
|
||||
|
||||
volumes:
|
||||
- ../nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro
|
||||
- nipovpn_logs:/var/log/nipovpn
|
||||
|
||||
command:
|
||||
- ${NIPOVPN_MODE:-server}
|
||||
- /etc/nipovpn/config.yaml
|
||||
|
||||
volumes:
|
||||
nipovpn_logs:
|
||||
```
|
||||
|
||||
## Build Image
|
||||
|
||||
From the `docker` directory:
|
||||
|
||||
```bash
|
||||
cd docker
|
||||
docker compose build
|
||||
```
|
||||
|
||||
Or with old Docker Compose:
|
||||
|
||||
```bash
|
||||
cd docker
|
||||
docker-compose build
|
||||
```
|
||||
|
||||
To rebuild without cache:
|
||||
|
||||
```bash
|
||||
docker compose build --no-cache
|
||||
```
|
||||
|
||||
## Run in Server Mode
|
||||
|
||||
Using environment variable:
|
||||
|
||||
```bash
|
||||
cd docker
|
||||
NIPOVPN_MODE=server docker compose up -d
|
||||
```
|
||||
|
||||
Or create `docker/.env`:
|
||||
|
||||
```env
|
||||
NIPOVPN_MODE=server
|
||||
```
|
||||
|
||||
Then run:
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
The container will run:
|
||||
|
||||
```bash
|
||||
nipovpn server /etc/nipovpn/config.yaml
|
||||
```
|
||||
|
||||
## Run in Agent Mode
|
||||
|
||||
Using environment variable:
|
||||
|
||||
```bash
|
||||
cd docker
|
||||
NIPOVPN_MODE=agent docker compose up -d
|
||||
```
|
||||
|
||||
Or create `docker/.env`:
|
||||
|
||||
```env
|
||||
NIPOVPN_MODE=agent
|
||||
```
|
||||
|
||||
Then run:
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
The container will run:
|
||||
|
||||
```bash
|
||||
nipovpn agent /etc/nipovpn/config.yaml
|
||||
```
|
||||
|
||||
## Specify Config File
|
||||
|
||||
By default, this file is mounted into the container:
|
||||
|
||||
```bash
|
||||
../nipovpn/etc/nipovpn/config.yaml
|
||||
```
|
||||
|
||||
Inside the container it becomes:
|
||||
|
||||
```bash
|
||||
/etc/nipovpn/config.yaml
|
||||
```
|
||||
|
||||
To use another config file, change this line in `docker-compose.yml`:
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
- ../nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
- ./server-config.yaml:/etc/nipovpn/config.yaml:ro
|
||||
```
|
||||
|
||||
Then run:
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
## View Logs
|
||||
|
||||
Show live container logs:
|
||||
|
||||
```bash
|
||||
docker compose logs -f
|
||||
```
|
||||
|
||||
Show logs only for NipoVPN service:
|
||||
|
||||
```bash
|
||||
docker compose logs -f nipovpn
|
||||
```
|
||||
|
||||
Read the log file inside the container volume:
|
||||
|
||||
```bash
|
||||
docker exec -it nipovpn cat /var/log/nipovpn/nipovpn.log
|
||||
```
|
||||
|
||||
Follow the log file:
|
||||
|
||||
```bash
|
||||
docker exec -it nipovpn tail -f /var/log/nipovpn/nipovpn.log
|
||||
```
|
||||
|
||||
## Stop Container
|
||||
|
||||
```bash
|
||||
docker compose down
|
||||
```
|
||||
|
||||
## Restart Container
|
||||
|
||||
```bash
|
||||
docker compose restart
|
||||
```
|
||||
|
||||
## Rebuild and Restart
|
||||
|
||||
```bash
|
||||
docker compose down
|
||||
docker compose build --no-cache
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
## Check Container Status
|
||||
|
||||
```bash
|
||||
docker ps
|
||||
```
|
||||
|
||||
Or:
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
## Execute Shell Inside Container
|
||||
|
||||
```bash
|
||||
docker exec -it nipovpn bash
|
||||
```
|
||||
|
||||
## Run Manually Without Compose
|
||||
|
||||
Build image from repository root:
|
||||
|
||||
```bash
|
||||
docker build -f docker/Dockerfile -t nipovpn:latest .
|
||||
```
|
||||
|
||||
Run server mode:
|
||||
|
||||
```bash
|
||||
docker run --rm \
|
||||
--name nipovpn \
|
||||
-p 443:443 \
|
||||
-p 8080:8080 \
|
||||
-v ./nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro \
|
||||
nipovpn:latest server /etc/nipovpn/config.yaml
|
||||
```
|
||||
|
||||
Run agent mode:
|
||||
|
||||
```bash
|
||||
docker run --rm \
|
||||
--name nipovpn \
|
||||
-p 8080:8080 \
|
||||
-v ./nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro \
|
||||
nipovpn:latest agent /etc/nipovpn/config.yaml
|
||||
```
|
||||
|
||||
## Common Problems
|
||||
|
||||
### CMakeCache path error
|
||||
|
||||
If you see an error like:
|
||||
|
||||
```text
|
||||
CMakeCache.txt directory is different
|
||||
```
|
||||
|
||||
your local `build/` directory was copied into Docker.
|
||||
|
||||
Fix:
|
||||
|
||||
```bash
|
||||
rm -rf build
|
||||
docker compose build --no-cache
|
||||
```
|
||||
|
||||
Also make sure `.dockerignore` exists in the repository root.
|
||||
|
||||
### Port already in use
|
||||
|
||||
If port `443` or `8080` is already used, change the port mapping:
|
||||
|
||||
```yaml
|
||||
ports:
|
||||
- "8443:443"
|
||||
- "8081:8080"
|
||||
```
|
||||
|
||||
### Config changes are not applied
|
||||
|
||||
Restart the container:
|
||||
|
||||
```bash
|
||||
docker compose restart
|
||||
```
|
||||
|
||||
## Recommended Commands
|
||||
|
||||
Server:
|
||||
|
||||
```bash
|
||||
cd docker
|
||||
NIPOVPN_MODE=server docker compose up -d --build
|
||||
docker compose logs -f
|
||||
```
|
||||
|
||||
Agent:
|
||||
|
||||
```bash
|
||||
cd docker
|
||||
NIPOVPN_MODE=agent docker compose up -d --build
|
||||
docker compose logs -f
|
||||
```
|
||||
@@ -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
|
||||
```
|
||||
@@ -0,0 +1,84 @@
|
||||
## Nix Guide
|
||||
|
||||
**Note:** Nix Flakes are an experimental feature and must be enabled before using any of the commands in this guide.
|
||||
|
||||
### Enable Flakes
|
||||
|
||||
* **NixOS:** Follow the instructions in the NixOS & Flakes Book:
|
||||
|
||||
[Enabling NixOS with Flakes](https://nixos-and-flakes.thiscute.world/nixos-with-flakes/nixos-with-flakes-enabled?utm_source=chatgpt.com#enable-nix-flakes)
|
||||
|
||||
* **Non-NixOS systems:** Add the following to `~/.config/nix/nix.conf` (or `/etc/nix/nix.conf`):
|
||||
|
||||
```bash
|
||||
experimental-features = nix-command flakes
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
### Install into your Nix profile
|
||||
|
||||
```bash
|
||||
nix profile install github:MortezaBashsiz/nipovpn
|
||||
```
|
||||
|
||||
### NixOS (system-wide installation)
|
||||
|
||||
Add the flake as an input in your system `flake.nix`:
|
||||
|
||||
```nix
|
||||
{
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
nipovpn.url = "github:MortezaBashsiz/nipovpn";
|
||||
};
|
||||
|
||||
outputs = { self, nixpkgs, nipovpn, ... }: {
|
||||
nixosConfigurations.yourhostname = nixpkgs.lib.nixosSystem {
|
||||
system = "x86_64-linux"; # or "aarch64-linux"
|
||||
|
||||
modules = [
|
||||
./configuration.nix
|
||||
{
|
||||
environment.systemPackages = [
|
||||
nipovpn.packages.${pkgs.system}.default
|
||||
];
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
### Manual Build (without Nix)
|
||||
|
||||
For traditional builds on Linux, please refer to [`BuildLinux.md`](./BuildLinux.md).
|
||||
|
||||
### Build with Nix
|
||||
|
||||
From the repository root:
|
||||
|
||||
```bash
|
||||
nix build
|
||||
```
|
||||
|
||||
Or directly from GitHub without cloning:
|
||||
|
||||
```bash
|
||||
nix build github:MortezaBashsiz/nipovpn
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
Enter the development shell with all dependencies pre-configured:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/MortezaBashsiz/nipovpn.git
|
||||
cd nipovpn
|
||||
|
||||
nix develop
|
||||
```
|
||||
|
||||
If the command completes successfully, the development environment is ready to use.
|
||||
@@ -0,0 +1 @@
|
||||
/etc/nipovpn/config.yaml
|
||||
@@ -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: 0.0.0
|
||||
Maintainer: Morteza Bashsiz
|
||||
Architecture: amd64
|
||||
Depends: libyaml-cpp0.8
|
||||
Homepage: https://github.com/MortezaBashsiz/nipovpn
|
||||
Description: Powerful and secure proxy
|
||||
@@ -1,28 +1,79 @@
|
||||
---
|
||||
# This block contains general and global configuration which is in both modes
|
||||
general:
|
||||
# token: 32 bytes of string. this will be used on agent and server side to encryption
|
||||
# token: at least 32 bytes of string. The AES-256-GCM key is derived from it. Must match on agent and server.
|
||||
# This sample value is public: replace it, e.g. with the output of `openssl rand -hex 16`
|
||||
token: "af445adb-2434-4975-9445-2c1b2231"
|
||||
# fakeUrl: string
|
||||
# Defines the fake url and endpoint between agent and server
|
||||
fakeUrl: "http://nipo.ciron.net"
|
||||
# method: "HEAD|GET|POST|PUT|DELETE"
|
||||
# Defines with which method
|
||||
# aesEnable: bool (default: true)
|
||||
# Enables AES-256-GCM payload encryption (confidentiality and integrity). Must match on the agent and server.
|
||||
# Independent of tlsEnable; request encoding remains enabled.
|
||||
aesEnable: true
|
||||
# protocol:
|
||||
# Defines the protocol between client and agent
|
||||
# Choose http or socks5
|
||||
protocol: socks5
|
||||
# bufferSize: unsigned short
|
||||
# Defines the maximum buffer size for each request in Bytes. Default is 65536
|
||||
# Do not use less than 1 and more than 65536
|
||||
bufferSize: 65536
|
||||
# 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: 1
|
||||
# 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 true then it will use same connection between agent and server to handle client request
|
||||
# If false 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: true
|
||||
# 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
|
||||
log:
|
||||
# logLevel: "INFO|TRACE|DEBUG"
|
||||
logLevel: "DEBUG"
|
||||
logLevel: "INFO"
|
||||
# logFile: "/var/log/nipo/nipo.log"
|
||||
# Path of log file
|
||||
logFile: "/var/log/nipovpn/nipovpn.log"
|
||||
@@ -30,16 +81,12 @@ log:
|
||||
# This block is to define server directives
|
||||
server:
|
||||
# threads: number of threads in server
|
||||
threads: 8
|
||||
threads: 2
|
||||
# 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: ""
|
||||
|
||||
|
||||
# This block is to define agent directives
|
||||
agent:
|
||||
@@ -56,7 +103,4 @@ agent:
|
||||
# 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"
|
||||
@@ -8,6 +8,7 @@ ExecReload=/bin/kill -HUP $MAINPID
|
||||
KillMode=process
|
||||
Restart=on-failure
|
||||
Type=simple
|
||||
LimitNOFILE=1048576
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
||||
@@ -8,6 +8,7 @@ ExecReload=/bin/kill -HUP $MAINPID
|
||||
KillMode=process
|
||||
Restart=on-failure
|
||||
Type=simple
|
||||
LimitNOFILE=1048576
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
||||
Whitespace-only changes.
Reference in new issue
Block a user