Compare commits
189
Commits
v1.0.18
...
dev-v0.1.75
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3de78c2f6b | ||
|
|
abc8ae9a6b | ||
|
|
0a45ccc315 | ||
|
|
bd283fbf22 | ||
|
|
29eab9f955 | ||
|
|
1d95451402 | ||
|
|
230ea19b34 | ||
|
|
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 | ||
|
|
cd3c88f90d | ||
|
|
78adf29ff2 | ||
|
|
6650839c66 | ||
|
|
4bbbf10e3c | ||
|
|
ad0d921032 | ||
|
|
b4871b9b95 | ||
|
|
3c0f8714b9 | ||
|
|
cf012afa87 | ||
|
|
914eb2d3e1 | ||
|
|
a3257799d9 | ||
|
|
4c0a3c4df7 | ||
|
|
e11591755f | ||
|
|
0b19f77d02 | ||
|
|
b46529b2c2 | ||
|
|
39053baf6d | ||
|
|
a0485d753d | ||
|
|
0b916898ad | ||
|
|
e3d61c64c7 | ||
|
|
21fec88b6e | ||
|
|
f114eb147b | ||
|
|
b3d8343975 | ||
|
|
182d2da3c2 | ||
|
|
42031b86a0 | ||
|
|
fd16b0046c | ||
|
|
7484eab9af | ||
|
|
6a33488c36 | ||
|
|
451e1825c4 | ||
|
|
ec8769929c | ||
|
|
8d0b247445 | ||
|
|
c7bee7ebd7 | ||
|
|
a355ea46dc | ||
|
|
0248959624 |
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,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: |
|
||||
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_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
|
||||
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-0-${{ github.run_number }}.deb
|
||||
dpkg-deb --build package-root "build/${PACKAGE_FILE}"
|
||||
|
||||
- name: Upload the Debian nipovpn as an artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: nipovpn
|
||||
path: build/nipovpn_staging_v1-0-${{ github.run_number }}.deb
|
||||
ls -lah build/
|
||||
|
||||
- name: Show nipovpn information
|
||||
- name: Show Debian package information
|
||||
run: |
|
||||
dpkg -I build/nipovpn_staging_v1-0-${{ github.run_number }}.deb
|
||||
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-dev-deb-${{ matrix.arch }}
|
||||
path: build/nipovpn_dev_${{ 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_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
|
||||
uses: actions/download-artifact@v3
|
||||
- name: Download package artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: nipovpn
|
||||
pattern: nipovpn-dev-*
|
||||
merge-multiple: true
|
||||
path: ./
|
||||
|
||||
- name: Create GitHub Release
|
||||
id: create_release
|
||||
uses: actions/create-release@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
|
||||
with:
|
||||
tag_name: 'v1.0.${{ github.run_number }}'
|
||||
release_name: Staging v1.0.${{ 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-0-${{ github.run_number }}.deb
|
||||
asset_name: nipovpn_staging_v1-0-${{ 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,74 +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-0-${{ github.run_number }}.deb
|
||||
|
||||
- name: Upload the Debian nipovpn as an artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: nipovpn
|
||||
path: build/nipovpn_v1-0-${{ github.run_number }}.deb
|
||||
|
||||
- name: Show nipovpn information
|
||||
run: |
|
||||
dpkg -I build/nipovpn_v1-0-${{ github.run_number }}.deb
|
||||
|
||||
release:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Download build artifact
|
||||
uses: actions/download-artifact@v3
|
||||
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.0.${{ github.run_number }}'
|
||||
release_name: Version v1.0.${{ 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-0-${{ github.run_number }}.deb
|
||||
asset_name: nipovpn_v1-0-${{ 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
|
||||
+5
-1
@@ -10,8 +10,12 @@ 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 system regex)
|
||||
find_package(Boost REQUIRED COMPONENTS regex OPTIONAL_COMPONENTS system)
|
||||
|
||||
# /usr/local/lib/cmake/yaml-cpp/yaml-cpp-config.cmake
|
||||
# declared variables: YAML_CPP_INCLUDE_DIR & YAML_CPP_LIBRARY_DIR
|
||||
|
||||
@@ -1,119 +1,342 @@
|
||||
# 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
|
||||
|
||||
NipoVPN is released under the [GNU General Public License v3.0](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
|
||||
2024-08-02_15:30:07 [INFO] Config initialized in server mode
|
||||
2024-08-02_15:30:07 [INFO]
|
||||
Config :
|
||||
General :
|
||||
fakeUrl: http://www.adas.com/api01
|
||||
method: HEAD
|
||||
timeWait: 0
|
||||
repeatWait: 1
|
||||
Log :
|
||||
logLevel: DEBUG
|
||||
logFile: /var/log/nipovpn/nipovpn.log
|
||||
server :
|
||||
threads: 4
|
||||
listenIp: 0.0.0.0
|
||||
listenPort: 443
|
||||
agent :
|
||||
threads: 4
|
||||
listenIp: 0.0.0.0
|
||||
listenPort: 8080
|
||||
serverIp: 127.0.0.1
|
||||
serverPort: 443
|
||||
token: af445adb-2434-4975-9445-2c1b2231
|
||||
httpVersion: 1.1
|
||||
userAgent: NipoAgent
|
||||
```
|
||||
|
||||
### Package
|
||||
|
||||
#### 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
|
||||
2024-08-02_15:30:07 [INFO] Config initialized in server mode
|
||||
2024-08-02_15:30:07 [INFO]
|
||||
Config :
|
||||
General :
|
||||
fakeUrl: http://www.adas.com/api01
|
||||
method: HEAD
|
||||
timeWait: 0
|
||||
repeatWait: 1
|
||||
Log :
|
||||
logLevel: DEBUG
|
||||
logFile: /var/log/nipovpn/nipovpn.log
|
||||
server :
|
||||
threads: 4
|
||||
listenIp: 0.0.0.0
|
||||
listenPort: 443
|
||||
agent :
|
||||
threads: 4
|
||||
listenIp: 0.0.0.0
|
||||
listenPort: 8080
|
||||
serverIp: 127.0.0.1
|
||||
serverPort: 443
|
||||
token: af445adb-2434-4975-9445-2c1b2231
|
||||
httpVersion: 1.1
|
||||
userAgent: NipoAgent
|
||||
```
|
||||
@@ -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()
|
||||
+132
-222
@@ -1,40 +1,22 @@
|
||||
#include "agenthandler.hpp"
|
||||
|
||||
/**
|
||||
* @brief Constructs an AgentHandler object to manage client-agent interactions.
|
||||
*
|
||||
* This constructor initializes the AgentHandler with the necessary resources,
|
||||
* including read and write buffers, configuration, logging, client connection,
|
||||
* and a unique identifier for the session.
|
||||
*
|
||||
* @param readBuffer Reference to the stream buffer used for reading data.
|
||||
* @param writeBuffer Reference to the stream buffer used for writing data.
|
||||
* @param config Shared pointer to the configuration object containing system settings.
|
||||
* @param log Shared pointer to the logging object for recording events and errors.
|
||||
* @param client Shared pointer to the TCPClient object managing the client connection.
|
||||
* @param clientConnStr A string representing the client's connection details.
|
||||
* @param uuid A unique identifier for the session, provided as a Boost UUID.
|
||||
*
|
||||
* @details
|
||||
* - Initializes the HTTP request handler using the provided configuration, logger,
|
||||
* read buffer, and UUID.
|
||||
* - Sets the `end_` flag to `false`, indicating the handler is active and ready.
|
||||
* - Initializes the `connect_` flag to `false`, indicating no active connection initially.
|
||||
*/
|
||||
#include <sstream>
|
||||
#include <utility>
|
||||
|
||||
AgentHandler::AgentHandler(boost::asio::streambuf &readBuffer,
|
||||
boost::asio::streambuf &writeBuffer,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
const TCPClient::pointer &client,
|
||||
const std::string &clientConnStr,
|
||||
TCPClient::pointer client,
|
||||
std::string clientConnStr,
|
||||
boost::uuids::uuid uuid)
|
||||
: config_(config),
|
||||
log_(log),
|
||||
client_(client),
|
||||
client_(std::move(client)),
|
||||
readBuffer_(readBuffer),
|
||||
writeBuffer_(writeBuffer),
|
||||
request_(HTTP::create(config, log, readBuffer, uuid)),
|
||||
clientConnStr_(clientConnStr),
|
||||
clientConnStr_(std::move(clientConnStr)),
|
||||
uuid_(uuid) {
|
||||
end_ = false;
|
||||
connect_ = false;
|
||||
@@ -42,217 +24,145 @@ AgentHandler::AgentHandler(boost::asio::streambuf &readBuffer,
|
||||
|
||||
AgentHandler::~AgentHandler() {}
|
||||
|
||||
/**
|
||||
* @brief Handles the processing of incoming requests, encryption, server communication, and response handling.
|
||||
*
|
||||
* This function coordinates multiple tasks, including:
|
||||
* - Encrypting the incoming data.
|
||||
* - Generating and sending an HTTP request to the server.
|
||||
* - Receiving and decrypting the server's response.
|
||||
* - Managing the connection state and logging detailed information at each step.
|
||||
*
|
||||
* @details
|
||||
* - The function ensures thread safety using a mutex lock.
|
||||
* - The incoming data is encrypted using AES-256 with a token retrieved from the configuration.
|
||||
* - If encryption is successful, the function builds an HTTP POST request and determines the request type.
|
||||
* - It establishes a connection to the server if required and sends the encrypted request.
|
||||
* - The server's response is parsed and decrypted. If successful, the decrypted data is copied to the write buffer.
|
||||
* - Handles HTTP and non-HTTP responses, including error scenarios and connection cleanup.
|
||||
* - Maintains logging for debugging and informational purposes throughout the process.
|
||||
*
|
||||
* @note In case of any error during encryption, connection, or response handling, the client socket is closed.
|
||||
*/
|
||||
void AgentHandler::handle() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::lock_guard lock(mutex_);
|
||||
|
||||
BoolStr encryption{false, std::string("FAILED")};
|
||||
if (!request_->detectType()) {
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [NOT HTTP Request] [Request] : " +
|
||||
streambufToString(readBuffer_),
|
||||
Log::Level::DEBUG);
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
encryption =
|
||||
aes256Encrypt(hexStreambufToStr(readBuffer_), config_->general().token);
|
||||
if (request_->parsedHttpRequest().target().length() > 0) {
|
||||
log_->write("[" + to_string(uuid_) + "] [FORWARD] [SRC " + clientConnStr_ + "] [DST " +
|
||||
std::string(request_->parsedHttpRequest().target()) + "]",
|
||||
Log::Level::TRACE);
|
||||
}
|
||||
|
||||
if (encryption.ok) {
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Encryption Done]", Log::Level::DEBUG);
|
||||
std::string newReq(
|
||||
request_->genHttpPostReqString(encode64(encryption.message)));
|
||||
|
||||
if (request_->detectType()) {
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Request] : " + request_->toString(),
|
||||
Log::Level::DEBUG);
|
||||
if (request_->parsedHttpRequest().target().length() > 0) {
|
||||
log_->write("[" + to_string(uuid_) + "] [CONNECT] [SRC " + clientConnStr_ + "]" + " [DST " +
|
||||
boost::lexical_cast<std::string>(
|
||||
request_->parsedHttpRequest().target()) +
|
||||
"]",
|
||||
Log::Level::INFO);
|
||||
}
|
||||
if (!client_->socket().is_open() ||
|
||||
request_->httpType() == HTTP::HttpType::http ||
|
||||
request_->httpType() == HTTP::HttpType::connect) {
|
||||
connect_ = true;
|
||||
boost::system::error_code ec;
|
||||
if (!client_->doConnect(config_->agent().serverIp,
|
||||
config_->agent().serverPort)) {
|
||||
log_->write(std::string("[" + to_string(uuid_) + "] [CONNECT] [ERROR] [To Server] [SRC ") +
|
||||
clientConnStr_ + "] [DST " +
|
||||
config_->agent().serverIp + ":" +
|
||||
std::to_string(config_->agent().serverPort) + "]",
|
||||
Log::Level::INFO);
|
||||
}
|
||||
if (ec) {
|
||||
log_->write(std::string("[" + to_string(uuid_) + "] [AgentHandler handle] Connection error: ") +
|
||||
ec.message(),
|
||||
Log::Level::ERROR);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
copyStringToStreambuf(newReq, readBuffer_);
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Request To Server] : \n" + newReq,
|
||||
Log::Level::DEBUG);
|
||||
|
||||
client_->doWrite(readBuffer_);
|
||||
client_->doReadAgent();
|
||||
|
||||
if (client_->readBuffer().size() > 0) {
|
||||
if (request_->httpType() != HTTP::HttpType::connect) {
|
||||
HTTP::pointer response =
|
||||
HTTP::create(config_, log_, client_->readBuffer(), uuid_);
|
||||
if (response->parseHttpResp()) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) + "] [AgentHandler handle] [Response] : " + response->restoString(),
|
||||
Log::Level::DEBUG);
|
||||
BoolStr decryption{false, std::string("FAILED")};
|
||||
decryption =
|
||||
aes256Decrypt(decode64(boost::lexical_cast<std::string>(
|
||||
response->parsedHttpResponse().body())),
|
||||
config_->general().token);
|
||||
if (boost::lexical_cast<std::string>(response->parsedHttpResponse()[config_->general().chunkHeader]) == "yes") {
|
||||
end_ = true;
|
||||
}
|
||||
if (decryption.ok) {
|
||||
copyStringToStreambuf(decryption.message, writeBuffer_);
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Decryption Done]", Log::Level::DEBUG);
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Decryption Failed] : [ " +
|
||||
decryption.message + "] ",
|
||||
Log::Level::DEBUG);
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Decryption Failed] : " +
|
||||
request_->toString(),
|
||||
Log::Level::INFO);
|
||||
client_->socket().close();
|
||||
}
|
||||
} else {
|
||||
log_->write(
|
||||
"[AgentHandler handle] [NOT HTTP Response] "
|
||||
"[Response] : " +
|
||||
streambufToString(client_->readBuffer()),
|
||||
Log::Level::DEBUG);
|
||||
}
|
||||
} else {
|
||||
connect_ = true;
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Response to connect] : \n" +
|
||||
streambufToString(client_->readBuffer()),
|
||||
Log::Level::DEBUG);
|
||||
moveStreambuf(client_->readBuffer(), writeBuffer_);
|
||||
}
|
||||
} else {
|
||||
client_->socket().close();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [NOT HTTP Request] [Request] : " +
|
||||
streambufToString(readBuffer_),
|
||||
Log::Level::DEBUG);
|
||||
|
||||
client_->socket().close();
|
||||
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::Level::ERROR);
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
}
|
||||
|
||||
if (!client_->isOpen()) {
|
||||
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() && !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 action =
|
||||
request_->httpType() == HTTP::HttpType::connect ? "open" : "request";
|
||||
|
||||
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);
|
||||
log_->write(
|
||||
"[AgentHandler handle] [Encryption Failed] : " +
|
||||
client_->socket().remote_endpoint().address().to_string() + ":" +
|
||||
std::to_string(client_->socket().remote_endpoint().port()) + "] ",
|
||||
Log::Level::INFO);
|
||||
client_->socket().close();
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Continues reading and processing data from the server, handling encryption, decryption, and responses.
|
||||
*
|
||||
* This function performs the following tasks:
|
||||
* - Generates a REST-based HTTP POST request and sends it to the server.
|
||||
* - Handles the server's response, including parsing, decryption, and processing.
|
||||
* - Logs detailed information about the request, response, and errors encountered during processing.
|
||||
*
|
||||
* @details
|
||||
* - Thread safety is ensured using a mutex lock.
|
||||
* - The request data is generated using the `genHttpRestPostReqString` method and sent to the server.
|
||||
* - Upon receiving the server's response, the function parses it as an HTTP response.
|
||||
* - The body of the response is decrypted using AES-256, and the decrypted content is stored in the write buffer.
|
||||
* - If the response indicates the end of a chunked transfer (`chunkHeader` set to "yes"), the `end_` flag is set to `true`.
|
||||
* - Handles both HTTP and non-HTTP responses, logging any issues encountered.
|
||||
* - In case of decryption failure or an empty response, the client socket is closed.
|
||||
*
|
||||
* @note
|
||||
* - This function assumes that the client connection is already established and ready for communication.
|
||||
* - Errors in decryption, parsing, or an empty response buffer will terminate the connection.
|
||||
*/
|
||||
void AgentHandler::continueRead() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::string newReq(
|
||||
request_->genHttpRestPostReqString());
|
||||
copyStringToStreambuf(newReq, readBuffer_);
|
||||
const std::string innerRequest = encode64(encryption.message);
|
||||
|
||||
std::ostringstream outer;
|
||||
const bool directTunnelOpen =
|
||||
config_->general().tunnelEnable &&
|
||||
request_->httpType() == HTTP::HttpType::connect;
|
||||
|
||||
outer << config_->randomMethod() + " /" + config_->randomEndPoint() + " HTTP/" << config_->agent().httpVersion << "\r\n"
|
||||
<< "Host: " << relayHostHeader(config_) << "\r\n"
|
||||
<< "User-Agent: " << config_->agent().userAgent << "\r\n"
|
||||
<< "Accept: */*\r\n"
|
||||
<< "Content-Type: text/plain; charset=utf-8\r\n"
|
||||
<< "Content-Length: " << innerRequest.size() << "\r\n"
|
||||
<< "Connection: "
|
||||
<< ((config_->general().connectionReuse || directTunnelOpen) ? "keep-alive" : "close")
|
||||
<< "\r\n"
|
||||
<< "\r\n"
|
||||
<< innerRequest;
|
||||
|
||||
copyStringToStreambuf(outer.str(), readBuffer_);
|
||||
|
||||
client_->doWrite(readBuffer_);
|
||||
client_->doReadAgent();
|
||||
if (client_->readBuffer().size() > 0) {
|
||||
if (request_->httpType() != HTTP::HttpType::connect) {
|
||||
HTTP::pointer response =
|
||||
HTTP::create(config_, log_, client_->readBuffer(), uuid_);
|
||||
if (response->parseHttpResp()) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) + "] [AgentHandler continueRead handle] [Response] : " + response->restoString(),
|
||||
Log::Level::DEBUG);
|
||||
BoolStr decryption{false, std::string("FAILED")};
|
||||
decryption =
|
||||
aes256Decrypt(decode64(boost::lexical_cast<std::string>(
|
||||
response->parsedHttpResponse().body())),
|
||||
config_->general().token);
|
||||
if (boost::lexical_cast<std::string>(response->parsedHttpResponse()[config_->general().chunkHeader]) == "yes") {
|
||||
end_ = true;
|
||||
}
|
||||
if (decryption.ok) {
|
||||
copyStringToStreambuf(decryption.message, writeBuffer_);
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler continueRead handle] [Decryption Done]", Log::Level::DEBUG);
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler continueRead handle] [Decryption Failed] : [ " +
|
||||
decryption.message + "] ",
|
||||
Log::Level::DEBUG);
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler continueRead handle] [Decryption Failed] : " +
|
||||
request_->toString(),
|
||||
Log::Level::INFO);
|
||||
client_->socket().close();
|
||||
}
|
||||
} else {
|
||||
log_->write(
|
||||
"[AgentHandler continueRead handle] [NOT HTTP Response] "
|
||||
"[Response] : " +
|
||||
streambufToString(client_->readBuffer()),
|
||||
Log::Level::DEBUG);
|
||||
}
|
||||
} else {
|
||||
connect_ = true;
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler continueRead handle] [Response to connect] : \n" +
|
||||
streambufToString(client_->readBuffer()),
|
||||
Log::Level::DEBUG);
|
||||
moveStreambuf(client_->readBuffer(), writeBuffer_);
|
||||
}
|
||||
} else {
|
||||
client_->socket().close();
|
||||
|
||||
if (client_->readBuffer().size() == 0 && !config_->general().connectionReuse) {
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string outerResponse = streambufToString(client_->readBuffer());
|
||||
const auto bodyPos = outerResponse.find("\r\n\r\n");
|
||||
if (bodyPos == std::string::npos) {
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [NOT HTTP Response] [Response] : " +
|
||||
outerResponse,
|
||||
Log::Level::DEBUG);
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string responseBody = outerResponse.substr(bodyPos + 4);
|
||||
if (responseBody.empty()) {
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
+19
-78
@@ -9,46 +9,17 @@
|
||||
#include "log.hpp"
|
||||
#include "tcpclient.hpp"
|
||||
|
||||
/**
|
||||
* @brief The `AgentHandler` class manages the interaction between the client and the agent,
|
||||
* including handling requests, responses, and connection state.
|
||||
*
|
||||
* @details
|
||||
* - This class is derived from `Uncopyable` to prevent copying or assignment.
|
||||
* - It provides functionality for handling initial requests (`handle`) and continuing
|
||||
* with subsequent reads and responses (`continueRead`).
|
||||
* - Uses Boost.Asio stream buffers for managing input and output data streams.
|
||||
* - Ensures thread safety with an internal mutex.
|
||||
* - Maintains the connection state with `end_` and `connect_` flags.
|
||||
* - Supports logging and configuration through shared pointers to external objects.
|
||||
*
|
||||
* @note
|
||||
* - The class uses a `pointer` alias for shared ownership management via `std::shared_ptr`.
|
||||
* - The `create` static factory method constructs an instance and returns it as a `pointer`.
|
||||
* - Requires a valid Boost.Asio I/O context and other dependencies to function properly.
|
||||
*/
|
||||
|
||||
class AgentHandler : private Uncopyable {
|
||||
public:
|
||||
using pointer = std::shared_ptr<AgentHandler>;
|
||||
|
||||
/**
|
||||
* @brief Factory method to create an instance of `AgentHandler`.
|
||||
*
|
||||
* @param readBuffer Reference to the stream buffer for reading data.
|
||||
* @param writeBuffer Reference to the stream buffer for writing data.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param client Shared pointer to the `TCPClient` object managing the connection.
|
||||
* @param clientConnStr String containing the client connection information.
|
||||
* @param uuid Unique identifier for this handler, represented as a Boost UUID.
|
||||
* @return A shared pointer to the newly created `AgentHandler` instance.
|
||||
*/
|
||||
static pointer create(boost::asio::streambuf &readBuffer,
|
||||
boost::asio::streambuf &writeBuffer,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
const TCPClient::pointer &client,
|
||||
const std::string &clientConnStr,
|
||||
TCPClient::pointer client,
|
||||
std::string clientConnStr,
|
||||
boost::uuids::uuid uuid) {
|
||||
return pointer(new AgentHandler(readBuffer, writeBuffer, config, log,
|
||||
client, clientConnStr, uuid));
|
||||
@@ -56,62 +27,32 @@ public:
|
||||
|
||||
~AgentHandler();
|
||||
|
||||
/**
|
||||
* @brief Handles the initial processing of requests, encryption, and server communication.
|
||||
*/
|
||||
void handle();
|
||||
|
||||
/**
|
||||
* @brief Continues processing subsequent reads, handling responses, and decryption.
|
||||
*/
|
||||
void continueRead();
|
||||
inline const HTTP::pointer &request() const { return request_; }
|
||||
|
||||
/**
|
||||
* @brief Accessor for the HTTP request object.
|
||||
*
|
||||
* @return A reference to the HTTP request object.
|
||||
*/
|
||||
inline const HTTP::pointer &request() & { return request_; }
|
||||
|
||||
/**
|
||||
* @brief Accessor for the HTTP request object, allowing move semantics.
|
||||
*
|
||||
* @return An rvalue reference to the HTTP request object.
|
||||
*/
|
||||
inline const HTTP::pointer &&request() && { return std::move(request_); }
|
||||
|
||||
bool end_; ///< Indicates whether the handler has completed its operations.
|
||||
bool connect_;///< Indicates the connection state.
|
||||
bool end_;
|
||||
bool connect_;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Constructs an `AgentHandler` instance with the specified parameters.
|
||||
*
|
||||
* @param readBuffer Reference to the stream buffer for reading data.
|
||||
* @param writeBuffer Reference to the stream buffer for writing data.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param client Shared pointer to the `TCPClient` object managing the connection.
|
||||
* @param clientConnStr String containing the client connection information.
|
||||
* @param uuid Unique identifier for this handler, represented as a Boost UUID.
|
||||
*/
|
||||
AgentHandler(boost::asio::streambuf &readBuffer,
|
||||
boost::asio::streambuf &writeBuffer,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
const TCPClient::pointer &client,
|
||||
const std::string &clientConnStr,
|
||||
TCPClient::pointer client,
|
||||
std::string clientConnStr,
|
||||
boost::uuids::uuid uuid);
|
||||
|
||||
const std::shared_ptr<Config> &config_;///< Configuration object reference.
|
||||
const std::shared_ptr<Log> &log_; ///< Logging object reference.
|
||||
const TCPClient::pointer &client_; ///< TCP client managing the connection.
|
||||
boost::asio::streambuf &readBuffer_; ///< Buffer for reading data.
|
||||
boost::asio::streambuf &writeBuffer_; ///< Buffer for writing data.
|
||||
HTTP::pointer request_; ///< HTTP request handler.
|
||||
const std::string &clientConnStr_; ///< Client connection string.
|
||||
std::string relayHostHeader(const std::shared_ptr<Config> &config);
|
||||
std::shared_ptr<Config> config_;
|
||||
std::shared_ptr<Log> log_;
|
||||
TCPClient::pointer client_;
|
||||
boost::asio::streambuf &readBuffer_;
|
||||
boost::asio::streambuf &writeBuffer_;
|
||||
HTTP::pointer request_;
|
||||
std::string clientConnStr_;
|
||||
|
||||
boost::uuids::uuid uuid_;///< Unique identifier for this handler.
|
||||
boost::uuids::uuid uuid_;
|
||||
|
||||
std::mutex mutex_;///< Mutex for ensuring thread safety.
|
||||
};
|
||||
std::mutex mutex_;
|
||||
};
|
||||
+140
-102
@@ -1,21 +1,7 @@
|
||||
#include "config.hpp"
|
||||
|
||||
/**
|
||||
* @brief Constructs an Config object to manage program configuration.
|
||||
*
|
||||
* This constructor initializes the Config with the necessary resources,
|
||||
* including read and write buffers, configuration, logging, client connection,
|
||||
* and a unique identifier for the session.
|
||||
*
|
||||
* @param mode Reference to the RunMode which program is running.
|
||||
* @param filePath Reference to config file path.
|
||||
*
|
||||
* @details
|
||||
* - Initializes the config directives.
|
||||
* - Sets the `runMode_` which defines the mode that program is running Server or Agent mode.
|
||||
* - Initializes the `configYaml_` which will load config gile in to variables.
|
||||
*/
|
||||
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)),
|
||||
@@ -23,31 +9,43 @@ 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"]["timeWait"].as<unsigned int>(),
|
||||
configYaml_["general"]["timeout"].as<unsigned short>(),
|
||||
configYaml_["general"]["repeatWait"].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>()}),
|
||||
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>()}) {
|
||||
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_);
|
||||
|
||||
switch (runMode_) {
|
||||
case RunMode::server:
|
||||
threads_ = server_.threads;
|
||||
listenIp_ = server_.listenIp;
|
||||
listenPort_ = server_.listenPort;
|
||||
break;
|
||||
|
||||
case RunMode::agent:
|
||||
threads_ = agent_.threads;
|
||||
listenIp_ = agent_.listenIp;
|
||||
@@ -56,49 +54,84 @@ Config::Config(const RunMode &mode, const std::string &filePath)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Constructs an Config object from a config refrence.
|
||||
*
|
||||
* This constructor initializes the Config with the necessary resources,
|
||||
* including read and write buffers, configuration, logging, client connection,
|
||||
* and a unique identifier for the session.
|
||||
*
|
||||
* @param config Reference to the Config pointer.
|
||||
*/
|
||||
Config::Config(const Config::pointer &config)
|
||||
: runMode_(config->runMode()),
|
||||
filePath_(config->filePath()),
|
||||
configYaml_(YAML::LoadFile(config->filePath())),
|
||||
threads_(config->threads()),
|
||||
listenIp_(config->listenIp()),
|
||||
listenPort_(config->listenPort()),
|
||||
general_(config->general()),
|
||||
log_(config->log()),
|
||||
server_(config->server()),
|
||||
agent_(config->agent()) {}
|
||||
|
||||
|
||||
Config::~Config() = default;
|
||||
|
||||
/**
|
||||
* @brief returns Config in string format to print on output.
|
||||
*/
|
||||
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"
|
||||
<< " timeWait: " << general_.timeWait << "\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"
|
||||
<< " repeatWait: " << general_.repeatWait << "\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"
|
||||
<< " agent :\n"
|
||||
|
||||
<< " Agent :\n"
|
||||
<< " threads: " << agent_.threads << "\n"
|
||||
<< " listenIp: " << agent_.listenIp << "\n"
|
||||
<< " listenPort: " << agent_.listenPort << "\n"
|
||||
@@ -106,116 +139,73 @@ std::string Config::toString() const {
|
||||
<< " serverPort: " << agent_.serverPort << "\n"
|
||||
<< " httpVersion: " << agent_.httpVersion << "\n"
|
||||
<< " userAgent: " << agent_.userAgent << "\n";
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief returns General struct from Config.
|
||||
*/
|
||||
const Config::General &Config::general() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return general_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief returns Log struct from Config.
|
||||
*/
|
||||
const Config::Log &Config::log() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return log_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief returns Server struct from Config.
|
||||
*/
|
||||
const Config::Server &Config::server() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return server_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief returns Agent struct from Config.
|
||||
*/
|
||||
const Config::Agent &Config::agent() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return agent_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief returns Threads count from Config.
|
||||
*/
|
||||
const unsigned short &Config::threads() const {
|
||||
unsigned short Config::threads() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return threads_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief sets threads count in Config to specific amount.
|
||||
*
|
||||
* @param threads which is threads count.
|
||||
*/
|
||||
void Config::threads(unsigned short threads) {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
threads_ = threads;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief returns listenIp_ from Config.
|
||||
*/
|
||||
const std::string &Config::listenIp() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return listenIp_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief sets listenIp_ in config
|
||||
*
|
||||
* @param refrence to string ip.
|
||||
*/
|
||||
void Config::listenIp(const std::string &ip) {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
listenIp_ = ip;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief returns listenPort_ from Config.
|
||||
*/
|
||||
const unsigned short &Config::listenPort() const {
|
||||
unsigned short Config::listenPort() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return listenPort_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief sets listenPort_ in config
|
||||
*
|
||||
* @param port number.
|
||||
*/
|
||||
void Config::listenPort(unsigned short port) {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
listenPort_ = port;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief returns RunMode struct from Config.
|
||||
*/
|
||||
const RunMode &Config::runMode() const {
|
||||
RunMode Config::runMode() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return runMode_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief returns filePath_ in string format.
|
||||
*/
|
||||
const std::string &Config::filePath() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return filePath_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief returns runMode in string format.
|
||||
*/
|
||||
std::string Config::modeToString() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
|
||||
switch (runMode_) {
|
||||
case RunMode::server:
|
||||
return "server";
|
||||
@@ -225,3 +215,51 @@ std::string Config::modeToString() const {
|
||||
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)];
|
||||
}
|
||||
+37
-95
@@ -4,23 +4,37 @@
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <random>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "general.hpp"
|
||||
|
||||
enum class RunMode { server,
|
||||
agent };
|
||||
enum class RunMode {
|
||||
server,
|
||||
agent
|
||||
};
|
||||
|
||||
class Config : private Uncopyable {
|
||||
private:
|
||||
struct General {
|
||||
std::string token;
|
||||
std::string fakeUrl;
|
||||
std::string method;
|
||||
unsigned int timeWait;
|
||||
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 repeatWait;
|
||||
std::string chunkHeader;
|
||||
unsigned short pullTimeout;
|
||||
bool tunnelEnable;
|
||||
bool connectionReuse;
|
||||
bool aesEnable;
|
||||
bool tlsEnable;
|
||||
bool tlsVerifyPeer;
|
||||
std::string tlsCertFile;
|
||||
std::string tlsKeyFile;
|
||||
std::string tlsCaFile;
|
||||
};
|
||||
|
||||
struct Log {
|
||||
@@ -44,28 +58,22 @@ private:
|
||||
std::string userAgent;
|
||||
};
|
||||
|
||||
const RunMode &runMode_;
|
||||
RunMode runMode_;
|
||||
std::string filePath_;
|
||||
const YAML::Node configYaml_;
|
||||
YAML::Node configYaml_;
|
||||
|
||||
unsigned short threads_;
|
||||
std::string listenIp_;
|
||||
unsigned short listenPort_;
|
||||
|
||||
mutable std::mutex configMutex_;
|
||||
|
||||
explicit Config(const RunMode &mode, const std::string &filePath);
|
||||
explicit Config(RunMode mode, const std::string &filePath);
|
||||
|
||||
public:
|
||||
using pointer = std::shared_ptr<Config>;
|
||||
|
||||
/**
|
||||
* @brief Creates a shared pointer to a Config object.
|
||||
*
|
||||
* @param mode The run mode (server or agent).
|
||||
* @param filePath Path to the configuration file.
|
||||
* @return pointer A shared pointer to the created Config instance.
|
||||
*/
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -75,103 +83,37 @@ public:
|
||||
const Agent agent_;
|
||||
|
||||
explicit Config(const Config::pointer &config);
|
||||
|
||||
~Config();
|
||||
|
||||
/**
|
||||
* @brief Retrieves the general configuration.
|
||||
*
|
||||
* @return const General& A reference to the general configuration.
|
||||
*/
|
||||
const General &general() const;
|
||||
|
||||
/**
|
||||
* @brief Retrieves the logging configuration.
|
||||
*
|
||||
* @return const Log& A reference to the logging configuration.
|
||||
*/
|
||||
const Log &log() const;
|
||||
|
||||
/**
|
||||
* @brief Retrieves the server configuration.
|
||||
*
|
||||
* @return const Server& A reference to the server configuration.
|
||||
*/
|
||||
const Server &server() const;
|
||||
|
||||
/**
|
||||
* @brief Retrieves the agent configuration.
|
||||
*
|
||||
* @return const Agent& A reference to the agent configuration.
|
||||
*/
|
||||
const Agent &agent() const;
|
||||
|
||||
/**
|
||||
* @brief Retrieves the number of threads configured.
|
||||
*
|
||||
* @return const unsigned short& The number of threads.
|
||||
*/
|
||||
const unsigned short &threads() const;
|
||||
unsigned short threads() const;
|
||||
|
||||
/**
|
||||
* @brief Sets the number of threads in the configuration.
|
||||
*
|
||||
* @param threads The number of threads to set.
|
||||
*/
|
||||
void threads(unsigned short threads);
|
||||
|
||||
/**
|
||||
* @brief Retrieves the IP address the application listens on.
|
||||
*
|
||||
* @return const std::string& The listen IP address.
|
||||
*/
|
||||
const std::string &listenIp() const;
|
||||
|
||||
/**
|
||||
* @brief Sets the listen IP address in the configuration.
|
||||
*
|
||||
* @param ip The IP address to set.
|
||||
*/
|
||||
void listenIp(const std::string &ip);
|
||||
|
||||
/**
|
||||
* @brief Retrieves the port number the application listens on.
|
||||
*
|
||||
* @return const unsigned short& The listen port.
|
||||
*/
|
||||
const unsigned short &listenPort() const;
|
||||
unsigned short listenPort() const;
|
||||
|
||||
/**
|
||||
* @brief Sets the listen port number in the configuration.
|
||||
*
|
||||
* @param port The port number to set.
|
||||
*/
|
||||
void listenPort(unsigned short port);
|
||||
|
||||
/**
|
||||
* @brief Retrieves the current run mode (server or agent).
|
||||
*
|
||||
* @return const RunMode& The current run mode.
|
||||
*/
|
||||
const RunMode &runMode() const;
|
||||
RunMode runMode() const;
|
||||
|
||||
/**
|
||||
* @brief Retrieves the path to the configuration file.
|
||||
*
|
||||
* @return const std::string& The configuration file path.
|
||||
*/
|
||||
const std::string &filePath() const;
|
||||
|
||||
/**
|
||||
* @brief Converts the current run mode to a string representation.
|
||||
*
|
||||
* @return std::string A string representing the current run mode.
|
||||
*/
|
||||
std::string modeToString() const;
|
||||
|
||||
/**
|
||||
* @brief Converts the entire configuration to a string representation.
|
||||
*
|
||||
* @return std::string A string representing the entire configuration.
|
||||
*/
|
||||
std::string toString() const;
|
||||
};
|
||||
|
||||
std::string randomFakeUrl() const;
|
||||
|
||||
std::string randomMethod() const;
|
||||
|
||||
std::string randomEndPoint() const;
|
||||
};
|
||||
+141
-180
@@ -19,13 +19,15 @@
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
/**
|
||||
* @brief Abstract for inheritance to make classes Uncopyable.
|
||||
*/
|
||||
static constexpr std::size_t BufferSize = 65536;
|
||||
static constexpr std::size_t MinTokenLength = 32;
|
||||
static constexpr const char *SampleToken = "af445adb-2434-4975-9445-2c1b2231";
|
||||
|
||||
class Uncopyable {
|
||||
public:
|
||||
Uncopyable() = default;
|
||||
@@ -35,52 +37,26 @@ private:
|
||||
Uncopyable &operator=(const Uncopyable &) = delete;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Prints message to output.
|
||||
*
|
||||
* @param message an auto refrence to message.
|
||||
*/
|
||||
inline void OUT(const auto &message) {
|
||||
std::cout << "OUT OUT OUT OUT OUT OUT OUT OUT : " << message
|
||||
<< std::endl;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief struct for return a bool with specific message.
|
||||
*/
|
||||
struct BoolStr {
|
||||
bool ok;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief checks if the file exists or not.
|
||||
*
|
||||
* @param name which is refrenced to the string path of file.
|
||||
* @return bool as result of existance.
|
||||
*/
|
||||
inline bool fileExists(const std::string &name) {
|
||||
std::ifstream file(name.c_str());
|
||||
return file.good();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief converts streambuffer to string.
|
||||
*
|
||||
* @param buff is a refrence to streambuffer.
|
||||
* @return string format of given buffer.
|
||||
*/
|
||||
inline std::string streambufToString(const boost::asio::streambuf &buff) {
|
||||
return {boost::asio::buffers_begin(buff.data()),
|
||||
boost::asio::buffers_begin(buff.data()) + buff.size()};
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief copies a string to streambuffer.
|
||||
*
|
||||
* @param inputStr a refrence to the string.
|
||||
* @param buff a refrence to the streambuffer.
|
||||
*/
|
||||
inline void copyStringToStreambuf(const std::string &inputStr,
|
||||
boost::asio::streambuf &buff) {
|
||||
buff.consume(buff.size());
|
||||
@@ -88,13 +64,6 @@ inline void copyStringToStreambuf(const std::string &inputStr,
|
||||
os << inputStr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief moves a streambuffer to another streambuffer.
|
||||
* it will consume(clean) the source streambuffer.
|
||||
*
|
||||
* @param source a refrence to the source streambuffer.
|
||||
* @param target a refrence to the target streambuffer.
|
||||
*/
|
||||
inline void moveStreambuf(boost::asio::streambuf &source,
|
||||
boost::asio::streambuf &target) {
|
||||
auto bytes_copied =
|
||||
@@ -103,13 +72,6 @@ inline void moveStreambuf(boost::asio::streambuf &source,
|
||||
source.consume(source.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief copies a streambuffer to another streambuffer.
|
||||
* it will keep the source streambuffer as is.
|
||||
*
|
||||
* @param source a refrence to the source streambuffer.
|
||||
* @param target a refrence to the target streambuffer.
|
||||
*/
|
||||
inline void copyStreambuf(boost::asio::streambuf &source,
|
||||
boost::asio::streambuf &target) {
|
||||
auto bytes_copied =
|
||||
@@ -117,58 +79,36 @@ inline void copyStreambuf(boost::asio::streambuf &source,
|
||||
target.commit(bytes_copied);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief converts hexadecimal array to string.
|
||||
*
|
||||
* @param data is a refrence to the hexadecimal array.
|
||||
* @size is size of hexadecimal array.
|
||||
* @return string format of given array.
|
||||
*/
|
||||
inline std::string hexArrToStr(const unsigned char *data, std::size_t size) {
|
||||
std::stringstream tempStr;
|
||||
tempStr << std::hex << std::setfill('0');
|
||||
|
||||
for (std::size_t i = 0; i < size; ++i) {
|
||||
tempStr << std::setw(2) << static_cast<unsigned>(data[i]);
|
||||
}
|
||||
|
||||
return tempStr.str();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief converts hexadecimal string to int.
|
||||
*
|
||||
* @param hexString is a refrence to the hexadecimal string.
|
||||
* @return the result as unsigned int.
|
||||
*/
|
||||
inline unsigned int hexToInt(const std::string &hexString) {
|
||||
unsigned short result;
|
||||
unsigned int result{};
|
||||
std::stringstream hexStr(hexString);
|
||||
hexStr >> std::hex >> result;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief converts hexadecimal string to ASCII string format.
|
||||
*
|
||||
* @param hex is a refrence to the hexadecimal string.
|
||||
* @return the result as string.
|
||||
*/
|
||||
inline std::string hexToASCII(const std::string &hex) {
|
||||
std::string ascii;
|
||||
|
||||
for (size_t i = 0; i < hex.length(); i += 2) {
|
||||
std::string part = hex.substr(i, 2);
|
||||
char ch = static_cast<char>(stoul(part, nullptr, 16));
|
||||
ascii += ch;
|
||||
}
|
||||
|
||||
return ascii;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief converts a char hexadecimal char.
|
||||
*
|
||||
* @param c is a char.
|
||||
* @return the result as hex char.
|
||||
*/
|
||||
inline unsigned char charToHex(char c) {
|
||||
if ('0' <= c && c <= '9') return c - '0';
|
||||
if ('A' <= c && c <= 'F') return c - 'A' + 10;
|
||||
@@ -176,64 +116,46 @@ inline unsigned char charToHex(char c) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief converts string to hexadecimal array.
|
||||
*
|
||||
* @param hexStr is a refrence to the hexadecimal string.
|
||||
* @return the result as a vector of chars.
|
||||
*/
|
||||
inline std::vector<unsigned char> strToHexArr(const std::string &hexStr) {
|
||||
std::vector<unsigned char> result(hexStr.size() / 2);
|
||||
for (std::size_t i = 0; i < hexStr.size() / 2; ++i)
|
||||
|
||||
for (std::size_t i = 0; i < hexStr.size() / 2; ++i) {
|
||||
result[i] = 16 * charToHex(hexStr[2 * i]) + charToHex(hexStr[2 * i + 1]);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief converts streambuffer to string.
|
||||
* first we need to convert the streambuffer to hex array and then to string
|
||||
*
|
||||
* @param buff is a refrence to the streambuffer.
|
||||
* @return the result as a string.
|
||||
*/
|
||||
inline std::string hexStreambufToStr(const boost::asio::streambuf &buff) {
|
||||
return hexArrToStr(
|
||||
reinterpret_cast<const unsigned char *>(streambufToString(buff).c_str()),
|
||||
buff.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief splits string based on delimiter.
|
||||
*
|
||||
* @param str is a refrence to the string.
|
||||
* @param delimiter is a refrence to the delimiter string.
|
||||
* @return the result as a vector of strings.
|
||||
*/
|
||||
inline std::vector<std::string> splitString(const std::string &str,
|
||||
const std::string &delimiter) {
|
||||
std::vector<std::string> result;
|
||||
std::string tempStr = str;
|
||||
|
||||
while (!tempStr.empty()) {
|
||||
size_t index = tempStr.find(delimiter);
|
||||
|
||||
if (index != std::string::npos) {
|
||||
result.push_back(tempStr.substr(0, index));
|
||||
tempStr = tempStr.substr(index + delimiter.size());
|
||||
if (tempStr.empty()) result.push_back(tempStr);
|
||||
|
||||
if (tempStr.empty()) {
|
||||
result.push_back(tempStr);
|
||||
}
|
||||
} else {
|
||||
result.push_back(tempStr);
|
||||
tempStr.clear();
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief decodes based64 encoded string.
|
||||
*
|
||||
* @param inputStr is a refrence to the encoded string.
|
||||
* @return decoded string.
|
||||
*/
|
||||
inline std::string decode64(const std::string &inputStr) {
|
||||
using namespace boost::archive::iterators;
|
||||
|
||||
@@ -245,17 +167,11 @@ inline std::string decode64(const std::string &inputStr) {
|
||||
using transformWidth = transform_width<binaryFromBase64, 8, 6>;
|
||||
|
||||
return {transformWidth(temp.begin()), transformWidth(temp.end())};
|
||||
} catch (const std::exception &e) {
|
||||
} catch (const std::exception &) {
|
||||
throw std::runtime_error("Invalid Base64 encoding");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief encodes string in base64 format.
|
||||
*
|
||||
* @param inputStr is a refrence to the string.
|
||||
* @return encoded string.
|
||||
*/
|
||||
inline std::string encode64(const std::string &inputStr) {
|
||||
using namespace boost::archive::iterators;
|
||||
|
||||
@@ -270,124 +186,131 @@ inline std::string encode64(const std::string &inputStr) {
|
||||
return encoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief encrypt string in aes256 by given key.
|
||||
*
|
||||
* @param plaintext is a refrence to the string.
|
||||
* @param key is a refrence to the key string.
|
||||
* @return encrypted BoolStr.
|
||||
*/
|
||||
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 *>(nonce), sizeof(nonce));
|
||||
final_result.append(reinterpret_cast<char *>(ciphertext.data()), ciphertext_len);
|
||||
final_result.append(reinterpret_cast<char *>(tag), sizeof(tag));
|
||||
|
||||
std::string final_result(reinterpret_cast<char *>(iv), sizeof(iv));
|
||||
final_result.append(reinterpret_cast<char *>(ciphertext.data()),
|
||||
ciphertext_len);
|
||||
result.ok = true;
|
||||
result.message = final_result;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief decrypt string in aes256 by given key.
|
||||
*
|
||||
* @param ciphertext_with_iv is a refrence to the encrypted string.
|
||||
* @param key is a refrence to the key string.
|
||||
* @return decrypted BoolStr.
|
||||
*/
|
||||
inline BoolStr aes256Decrypt(const std::string &ciphertext_with_iv,
|
||||
const std::string &key) {
|
||||
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()));
|
||||
std::string ciphertext =
|
||||
ciphertext_with_iv.substr(EVP_CIPHER_iv_length(EVP_aes_256_cbc()));
|
||||
if (sealed.size() < AesGcmNonceLength + AesGcmTagLength) {
|
||||
result.message = "Ciphertext too short";
|
||||
return result;
|
||||
}
|
||||
|
||||
int max_plaintext_len = ciphertext.size();
|
||||
std::vector<unsigned char> plaintext(max_plaintext_len);
|
||||
const std::string key = deriveAesKey(token);
|
||||
|
||||
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
|
||||
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);
|
||||
|
||||
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);
|
||||
@@ -395,11 +318,31 @@ inline BoolStr aes256Decrypt(const std::string &ciphertext_with_iv,
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief validates if the config is correct or not.
|
||||
*
|
||||
* @return result BoolStr.
|
||||
*/
|
||||
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"};
|
||||
|
||||
@@ -432,12 +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"]["timeWait"].as<unsigned int>();
|
||||
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"]["repeatWait"].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;
|
||||
@@ -471,7 +416,23 @@ 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;
|
||||
}
|
||||
}
|
||||
+163
-97
@@ -1,18 +1,9 @@
|
||||
#include "http.hpp"
|
||||
|
||||
/**
|
||||
* @brief Constructs an HTTP object with configuration, logging, and buffer handling.
|
||||
*
|
||||
* Initializes member variables including configuration, logging, stream buffer,
|
||||
* and UUID, with default values for HTTP type and TLS request parameters.
|
||||
*
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param buffer Reference to the Boost Asio stream buffer.
|
||||
* @param uuid Unique identifier for the HTTP session.
|
||||
*/
|
||||
HTTP::HTTP(const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log, boost::asio::streambuf &buffer, boost::uuids::uuid uuid)
|
||||
const std::shared_ptr<Log> &log,
|
||||
boost::asio::streambuf &buffer,
|
||||
boost::uuids::uuid uuid)
|
||||
: config_(config),
|
||||
log_(log),
|
||||
buffer_(buffer),
|
||||
@@ -20,16 +11,8 @@ HTTP::HTTP(const std::shared_ptr<Config> &config,
|
||||
httpType_(HTTP::HttpType::https),
|
||||
parsedTlsRequest_{"", "", TlsTypes::TLSHandshake},
|
||||
uuid_(uuid) {
|
||||
chunkHeader_ = "no";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Copy constructor for the HTTP class.
|
||||
*
|
||||
* Copies all member variables from another HTTP object.
|
||||
*
|
||||
* @param http Reference to another HTTP object to copy.
|
||||
*/
|
||||
HTTP::HTTP(const HTTP &http)
|
||||
: config_(http.config_),
|
||||
log_(http.log_),
|
||||
@@ -37,32 +20,23 @@ HTTP::HTTP(const HTTP &http)
|
||||
parsedHttpRequest_(http.parsedHttpRequest_),
|
||||
parsedTlsRequest_(http.parsedTlsRequest_),
|
||||
uuid_(http.uuid_) {
|
||||
chunkHeader_ = "no";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Destructor for the HTTP class.
|
||||
*
|
||||
* Cleans up any allocated resources. Currently, no explicit cleanup is required.
|
||||
*/
|
||||
|
||||
HTTP::~HTTP() {}
|
||||
|
||||
/**
|
||||
* @brief Detects the type of HTTP or HTTPS request based on the input buffer.
|
||||
*
|
||||
* Determines whether the request is HTTPS or plain HTTP by inspecting the initial bytes
|
||||
* of the stream buffer. Parses the request accordingly.
|
||||
*
|
||||
* @return True if the request type is successfully detected and parsed, false otherwise.
|
||||
*/
|
||||
|
||||
bool HTTP::detectType() {
|
||||
std::string requestStr{hexStreambufToStr(buffer_)};
|
||||
std::string tmpStr;
|
||||
unsigned short pos = 0;
|
||||
|
||||
tmpStr = requestStr.substr(pos, 2);
|
||||
|
||||
if (tmpStr == "16" || tmpStr == "14" || tmpStr == "17") {
|
||||
httpType(HTTP::HttpType::https);
|
||||
parsedTlsRequest_.body = requestStr;
|
||||
|
||||
if (parseTls())
|
||||
return true;
|
||||
else
|
||||
@@ -75,47 +49,38 @@ bool HTTP::detectType() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Parses an HTTP request from the input buffer.
|
||||
*
|
||||
* Converts the buffer data into an HTTP request object and sets the HTTP type
|
||||
* based on the request method.
|
||||
*
|
||||
* @return True if parsing is successful, false otherwise.
|
||||
*/
|
||||
bool HTTP::parseHttp() {
|
||||
std::string requestStr(streambufToString(buffer_));
|
||||
boost::beast::http::request_parser<boost::beast::http::string_body> parser;
|
||||
parser.eager(true);
|
||||
boost::beast::error_code error;
|
||||
|
||||
parser.put(boost::asio::buffer(requestStr), error);
|
||||
|
||||
if (error) {
|
||||
log_->write(std::string("[" + to_string(uuid_) + "] [HTTP parseHttp] ") + error.what(),
|
||||
Log::Level::DEBUG);
|
||||
return false;
|
||||
} else {
|
||||
parsedHttpRequest_ = parser.get();
|
||||
|
||||
if (parsedHttpRequest_.method() == boost::beast::http::verb::connect)
|
||||
httpType(HTTP::HttpType::connect);
|
||||
else
|
||||
httpType(HTTP::HttpType::http);
|
||||
|
||||
setIPPort();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Parses an HTTP response from the input buffer.
|
||||
*
|
||||
* Converts the buffer data into an HTTP response object.
|
||||
*
|
||||
* @return True if parsing is successful, false otherwise.
|
||||
*/
|
||||
bool HTTP::parseHttpResp() {
|
||||
std::string requestStr(streambufToString(buffer_));
|
||||
parser_.eager(true);
|
||||
boost::beast::error_code error;
|
||||
|
||||
parser_.put(boost::asio::buffer(requestStr), error);
|
||||
|
||||
if (error) {
|
||||
log_->write(std::string("[" + to_string(uuid_) + "] [HTTP parseHttpResp] ") + error.what(),
|
||||
Log::Level::DEBUG);
|
||||
@@ -126,40 +91,42 @@ bool HTTP::parseHttpResp() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Parses a TLS request from the input buffer.
|
||||
*
|
||||
* Identifies the TLS request type and extracts relevant fields such as SNI (Server Name Indication).
|
||||
*
|
||||
* @return True if parsing is successful, false otherwise.
|
||||
*/
|
||||
bool HTTP::parseTls() {
|
||||
std::string tmpStr;
|
||||
unsigned short pos = 0;
|
||||
|
||||
tmpStr = parsedTlsRequest_.body.substr(pos, 2);
|
||||
|
||||
if (tmpStr == "16") {
|
||||
parsedTlsRequest_.type = TlsTypes::TLSHandshake;
|
||||
pos = 10;
|
||||
tmpStr = parsedTlsRequest_.body.substr(pos, 2);
|
||||
|
||||
if (tmpStr == "01") {
|
||||
unsigned short tmpPos(0);
|
||||
|
||||
pos = 86;
|
||||
tmpStr = parsedTlsRequest_.body.substr(pos, 2);
|
||||
tmpPos = hexToInt(tmpStr);
|
||||
|
||||
pos += 2;
|
||||
tmpStr = parsedTlsRequest_.body.substr(pos, tmpPos);
|
||||
pos = pos + (tmpPos * 2);
|
||||
|
||||
tmpStr = parsedTlsRequest_.body.substr(pos, 4);
|
||||
tmpPos = hexToInt(tmpStr);
|
||||
pos += 4;
|
||||
pos = pos + (tmpPos * 2);
|
||||
|
||||
tmpStr = parsedTlsRequest_.body.substr(pos, 2);
|
||||
tmpPos = hexToInt(tmpStr);
|
||||
pos += 2;
|
||||
pos = pos + (tmpPos * 2);
|
||||
|
||||
tmpStr = parsedTlsRequest_.body.substr(pos, 4);
|
||||
tmpPos = hexToInt(tmpStr);
|
||||
pos += 4;
|
||||
|
||||
tmpStr = parsedTlsRequest_.body.substr(pos, 4);
|
||||
if (hexToInt(tmpStr) == 0) {
|
||||
pos += 14;
|
||||
@@ -170,112 +137,211 @@ bool HTTP::parseTls() {
|
||||
parsedTlsRequest_.sni = hexToASCII(tmpStr);
|
||||
}
|
||||
}
|
||||
|
||||
setIPPort();
|
||||
return true;
|
||||
|
||||
} else if (tmpStr == "14") {
|
||||
parsedTlsRequest_.type = TlsTypes::ChangeCipherSpec;
|
||||
setIPPort();
|
||||
return true;
|
||||
|
||||
} else if (tmpStr == "17") {
|
||||
parsedTlsRequest_.type = TlsTypes::ApplicationData;
|
||||
setIPPort();
|
||||
return true;
|
||||
|
||||
} else
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::string HTTP::genHttpPostReqString(const std::string &body) const {
|
||||
return std::string(config_->general().method + " " +
|
||||
config_->general().fakeUrl + " HTTP/" +
|
||||
std::string HTTP::genHttpPostReqString(const std::string &body) const {
|
||||
auto fakeUrl = config_->randomFakeUrl();
|
||||
return std::string(config_->randomMethod() + " " +
|
||||
fakeUrl + " HTTP/" +
|
||||
config_->agent().httpVersion + "\r\n") +
|
||||
"Host: " + config_->general().fakeUrl + "\r\n" +
|
||||
"Host: " + fakeUrl + "\r\n" +
|
||||
"User-Agent: " + config_->agent().userAgent + "\r\n" +
|
||||
"Accept: */*\r\n" + "Connection: keep-alive\r\n" +
|
||||
"Content-Length: " + std::to_string(body.length()) + "\r\n" +
|
||||
"Content-Type: application/x-www-form-urlencoded\r\n" + "\r\n" + body + "COMP\r\n\r\n";
|
||||
}
|
||||
|
||||
const std::string HTTP::genHttpRestPostReqString() const {
|
||||
return std::string(config_->general().method + " " +
|
||||
config_->general().fakeUrl + " HTTP/" +
|
||||
std::string HTTP::genHttpRestPostReqString() const {
|
||||
auto fakeUrl = config_->randomFakeUrl();
|
||||
return std::string(config_->randomMethod() + " " +
|
||||
fakeUrl + " HTTP/" +
|
||||
config_->agent().httpVersion + "\r\n") +
|
||||
"Host: " + config_->general().fakeUrl + "\r\n" +
|
||||
"Host: " + fakeUrl + "\r\n" +
|
||||
"User-Agent: " + config_->agent().userAgent + "\r\n" +
|
||||
"Accept: */*\r\n" + "Connection: keep-alive\r\n" +
|
||||
"Rest: yes\r\n" + "COMP\r\n\r\n";
|
||||
}
|
||||
|
||||
const std::string HTTP::genHttpOkResString(const std::string &body) const {
|
||||
std::string HTTP::genHttpOkResString(const std::string &body) const {
|
||||
return std::string("HTTP/1.1 200 OK\r\n") +
|
||||
"Content-Type: application/x-www-form-urlencoded\r\n" +
|
||||
"Content-Length: " + std::to_string(body.length()) + "\r\n" +
|
||||
config_->general().chunkHeader + ": " + chunkHeader_ + "\r\n" +
|
||||
"Connection: keep-alive\r\n" + "Cache-Control: no-cache\r\n" +
|
||||
"Pragma: no-cache\r\n" + "\r\n" + body + "COMP\r\n\r\n";
|
||||
}
|
||||
|
||||
|
||||
bool HTTP::parseHostPort(const std::string &input,
|
||||
std::string &host,
|
||||
unsigned short &port,
|
||||
unsigned short defaultPort) {
|
||||
host.clear();
|
||||
port = defaultPort;
|
||||
|
||||
if (input.empty()) return false;
|
||||
|
||||
auto parsePort = [](const std::string &value,
|
||||
unsigned short &out) -> bool {
|
||||
try {
|
||||
int p = std::stoi(value);
|
||||
if (p < 1 || p > 65535) return false;
|
||||
out = static_cast<unsigned short>(p);
|
||||
return true;
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
if (input.front() == '[') {
|
||||
auto close = input.find(']');
|
||||
if (close == std::string::npos) return false;
|
||||
|
||||
host = input.substr(1, close - 1);
|
||||
|
||||
if (close + 1 < input.size()) {
|
||||
if (input[close + 1] != ':') return false;
|
||||
if (!parsePort(input.substr(close + 2), port)) return false;
|
||||
}
|
||||
|
||||
return !host.empty();
|
||||
}
|
||||
|
||||
auto firstColon = input.find(':');
|
||||
auto lastColon = input.rfind(':');
|
||||
|
||||
if (firstColon != std::string::npos && firstColon != lastColon) {
|
||||
const std::string maybePort = input.substr(lastColon + 1);
|
||||
|
||||
unsigned short parsedPort = defaultPort;
|
||||
if (parsePort(maybePort, parsedPort)) {
|
||||
host = input.substr(0, lastColon);
|
||||
port = parsedPort;
|
||||
return !host.empty();
|
||||
}
|
||||
|
||||
host = input;
|
||||
port = defaultPort;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (lastColon != std::string::npos) {
|
||||
host = input.substr(0, lastColon);
|
||||
if (!parsePort(input.substr(lastColon + 1), port)) return false;
|
||||
} else {
|
||||
host = input;
|
||||
port = defaultPort;
|
||||
}
|
||||
|
||||
return !host.empty();
|
||||
}
|
||||
|
||||
void HTTP::setIPPort() {
|
||||
std::string target{};
|
||||
std::vector<std::string> splitted;
|
||||
|
||||
switch (httpType()) {
|
||||
case HTTP::HttpType::https:
|
||||
case HTTP::HttpType::https: {
|
||||
target = parsedTlsRequest_.sni;
|
||||
splitted = splitString(target, ":");
|
||||
if (splitted.size() > 1) {
|
||||
dstIP_ = splitted[0];
|
||||
dstPort_ = std::stoi(splitted[1]);
|
||||
} else {
|
||||
dstIP_ = target;
|
||||
|
||||
if (!parseHostPort(target, dstIp_, dstPort_, 443)) {
|
||||
dstIp_.clear();
|
||||
dstPort_ = 443;
|
||||
}
|
||||
|
||||
break;
|
||||
case HTTP::HttpType::http:
|
||||
}
|
||||
|
||||
case HTTP::HttpType::http: {
|
||||
target = boost::lexical_cast<std::string>(parsedHttpRequest_.target());
|
||||
splitted = splitString(
|
||||
splitString(splitString(target, "http://")[1], "/")[0], ":");
|
||||
if (!splitted.empty()) {
|
||||
dstIP_ = splitted[0];
|
||||
if (splitted.size() > 1)
|
||||
dstPort_ = std::stoi(splitted[1]);
|
||||
else
|
||||
dstPort_ = 80;
|
||||
|
||||
std::string hostPort;
|
||||
|
||||
if (target.rfind("http://", 0) == 0) {
|
||||
std::string withoutScheme = target.substr(std::string("http://").size());
|
||||
auto slashPos = withoutScheme.find('/');
|
||||
hostPort = (slashPos == std::string::npos)
|
||||
? withoutScheme
|
||||
: withoutScheme.substr(0, slashPos);
|
||||
} else if (target.rfind("https://", 0) == 0) {
|
||||
std::string withoutScheme = target.substr(std::string("https://").size());
|
||||
auto slashPos = withoutScheme.find('/');
|
||||
hostPort = (slashPos == std::string::npos)
|
||||
? withoutScheme
|
||||
: withoutScheme.substr(0, slashPos);
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) + "] [HTTP setIPPort] wrong request", Log::Level::DEBUG);
|
||||
auto hostIt = parsedHttpRequest_.find("Host");
|
||||
if (hostIt != parsedHttpRequest_.end()) {
|
||||
hostPort = boost::lexical_cast<std::string>(hostIt->value());
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [HTTP setIPPort] missing Host header",
|
||||
Log::Level::DEBUG);
|
||||
dstIp_.clear();
|
||||
dstPort_ = 80;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!parseHostPort(hostPort, dstIp_, dstPort_, 80)) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [HTTP setIPPort] wrong request",
|
||||
Log::Level::DEBUG);
|
||||
dstIp_.clear();
|
||||
dstPort_ = 80;
|
||||
}
|
||||
|
||||
break;
|
||||
case HTTP::HttpType::connect:
|
||||
}
|
||||
|
||||
case HTTP::HttpType::connect: {
|
||||
target = boost::lexical_cast<std::string>(parsedHttpRequest_.target());
|
||||
splitted = splitString(target, ":");
|
||||
dstIP_ = splitted[0];
|
||||
dstPort_ = std::stoi(splitted[1]);
|
||||
|
||||
if (!parseHostPort(target, dstIp_, dstPort_, 443)) {
|
||||
dstIp_.clear();
|
||||
dstPort_ = 443;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const std::string HTTP::tlsTypeToString() const {
|
||||
std::string HTTP::tlsTypeToString() const {
|
||||
switch (parsedTlsRequest_.type) {
|
||||
case TlsTypes::TLSHandshake:
|
||||
return "TLSHandshake";
|
||||
break;
|
||||
case TlsTypes::ChangeCipherSpec:
|
||||
return "ChangeCipherSpec";
|
||||
break;
|
||||
case TlsTypes::ApplicationData:
|
||||
return "ApplicationData";
|
||||
break;
|
||||
default:
|
||||
return "UNKNOWN TLSTYPE";
|
||||
}
|
||||
}
|
||||
|
||||
const std::string HTTP::toString() const {
|
||||
std::string HTTP::toString() const {
|
||||
switch (httpType()) {
|
||||
case HTTP::HttpType::https:
|
||||
return std::string("\n") + "TLS Type : " + tlsTypeToString() + "\n" +
|
||||
"SNI : " + parsedTlsRequest_.sni + "\n" + "Body Size : " +
|
||||
boost::lexical_cast<std::string>(parsedTlsRequest_.body.size()) +
|
||||
"\n" + "Body : " + parsedTlsRequest_.body + "\n";
|
||||
break;
|
||||
|
||||
case HTTP::HttpType::http:
|
||||
return std::string("\n") + "Method : " +
|
||||
boost::lexical_cast<std::string>(parsedHttpRequest_.method()) +
|
||||
@@ -291,20 +357,20 @@ const std::string HTTP::toString() const {
|
||||
parsedHttpRequest_.body().size()) +
|
||||
"\n" + "Body : " +
|
||||
boost::lexical_cast<std::string>(parsedHttpRequest_.body()) + "\n";
|
||||
break;
|
||||
|
||||
case HTTP::HttpType::connect:
|
||||
return std::string("\n") + "Method : " +
|
||||
boost::lexical_cast<std::string>(parsedHttpRequest_.method()) +
|
||||
"\n" + "Target : " +
|
||||
boost::lexical_cast<std::string>(parsedHttpRequest_.target()) +
|
||||
"\n";
|
||||
break;
|
||||
|
||||
default:
|
||||
return "UNKNOWN HTTPTYPE";
|
||||
}
|
||||
}
|
||||
|
||||
const std::string HTTP::restoString() const {
|
||||
std::string HTTP::restoString() const {
|
||||
return std::string("\n") +
|
||||
boost::lexical_cast<std::string>(parsedHttpResponse_.base()) + "\n" +
|
||||
"Body Size : " +
|
||||
|
||||
+20
-146
@@ -10,26 +10,10 @@
|
||||
#include "general.hpp"
|
||||
#include "log.hpp"
|
||||
|
||||
/**
|
||||
* @brief The HTTP class provides functionality for handling HTTP and TLS protocol parsing and generation.
|
||||
*
|
||||
* This class encapsulates logic to parse and generate HTTP requests and responses, handle TLS requests,
|
||||
* and manage associated data like IP addresses, ports, and configuration details. It supports both
|
||||
* HTTP and HTTPS (TLS) connections.
|
||||
*/
|
||||
class HTTP {
|
||||
public:
|
||||
using pointer = std::shared_ptr<HTTP>;
|
||||
|
||||
/**
|
||||
* @brief Factory method to create a new HTTP object.
|
||||
*
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object for recording events and errors.
|
||||
* @param buffer Reference to a stream buffer containing data for processing.
|
||||
* @param uuid A unique identifier for the session, provided as a Boost UUID.
|
||||
* @return Shared pointer to the newly created HTTP object.
|
||||
*/
|
||||
static pointer create(const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
boost::asio::streambuf &buffer,
|
||||
@@ -37,202 +21,92 @@ public:
|
||||
return pointer(new HTTP(config, log, buffer, uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Enumeration representing the type of HTTP connection.
|
||||
*/
|
||||
enum class HttpType {
|
||||
https,
|
||||
http,
|
||||
connect
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Enumeration representing types of TLS messages.
|
||||
*/
|
||||
enum class TlsTypes {
|
||||
TLSHandshake,
|
||||
ChangeCipherSpec,
|
||||
ApplicationData
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Structure to store parsed TLS request data.
|
||||
*/
|
||||
struct TlsRequest {
|
||||
std::string sni;
|
||||
std::string body;
|
||||
TlsTypes type;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Copy constructor for HTTP objects.
|
||||
*
|
||||
* @param request The HTTP object to copy.
|
||||
*/
|
||||
explicit HTTP(const HTTP &request);
|
||||
|
||||
/**
|
||||
* @brief Destructor for the HTTP class.
|
||||
*/
|
||||
~HTTP();
|
||||
|
||||
/**
|
||||
* @brief Getter for the HTTP connection type.
|
||||
*
|
||||
* @return The type of HTTP connection (http, https, or connect).
|
||||
*/
|
||||
inline const HTTP::HttpType &httpType() const { return httpType_; }
|
||||
inline HTTP::HttpType httpType() const { return httpType_; }
|
||||
|
||||
/**
|
||||
* @brief Setter for the HTTP connection type.
|
||||
*
|
||||
* @param httpType The new type of HTTP connection.
|
||||
*/
|
||||
inline void httpType(const HTTP::HttpType &httpType) { httpType_ = httpType; }
|
||||
|
||||
/**
|
||||
* @brief Detects the type of HTTP connection based on the buffer data.
|
||||
*
|
||||
* @return True if detection is successful, false otherwise.
|
||||
*/
|
||||
static bool parseHostPort(const std::string &input,
|
||||
std::string &host,
|
||||
unsigned short &port,
|
||||
unsigned short defaultPort);
|
||||
|
||||
bool detectType();
|
||||
|
||||
/**
|
||||
* @brief Parses an HTTP request from the buffer.
|
||||
*
|
||||
* @return True if parsing is successful, false otherwise.
|
||||
*/
|
||||
bool parseHttp();
|
||||
|
||||
/**
|
||||
* @brief Parses an HTTP response from the buffer.
|
||||
*
|
||||
* @return True if parsing is successful, false otherwise.
|
||||
*/
|
||||
bool parseHttpResp();
|
||||
|
||||
/**
|
||||
* @brief Parses a TLS request from the buffer.
|
||||
*
|
||||
* @return True if parsing is successful, false otherwise.
|
||||
*/
|
||||
bool parseTls();
|
||||
|
||||
/**
|
||||
* @brief Generates an HTTP POST request string.
|
||||
*
|
||||
* @param body The body of the HTTP POST request.
|
||||
* @return A string representation of the HTTP POST request.
|
||||
*/
|
||||
const std::string genHttpPostReqString(const std::string &body) const;
|
||||
std::string genHttpPostReqString(const std::string &body) const;
|
||||
|
||||
/**
|
||||
* @brief Generates a REST-style HTTP POST request string.
|
||||
*
|
||||
* @return A string representation of the REST-style HTTP POST request.
|
||||
*/
|
||||
const std::string genHttpRestPostReqString() const;
|
||||
std::string genHttpRestPostReqString() const;
|
||||
|
||||
/**
|
||||
* @brief Generates an HTTP 200 OK response string.
|
||||
*
|
||||
* @param body The body of the HTTP response.
|
||||
* @return A string representation of the HTTP 200 OK response.
|
||||
*/
|
||||
const std::string genHttpOkResString(const std::string &body) const;
|
||||
std::string genHttpOkResString(const std::string &body) const;
|
||||
|
||||
/**
|
||||
* @brief Retrieves the parsed HTTP request.
|
||||
*
|
||||
* @return Reference to the parsed HTTP request.
|
||||
*/
|
||||
inline const boost::beast::http::request<boost::beast::http::string_body> &
|
||||
parsedHttpRequest() & {
|
||||
return parsedHttpRequest_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Retrieves the parsed HTTP response.
|
||||
*
|
||||
* @return Reference to the parsed HTTP response.
|
||||
*/
|
||||
inline const boost::beast::http::response<boost::beast::http::string_body> &
|
||||
parsedHttpResponse() & {
|
||||
return parsedHttpResponse_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Retrieves the parsed TLS request.
|
||||
*
|
||||
* @return Reference to the parsed TLS request.
|
||||
*/
|
||||
inline const TlsRequest &parsedTlsRequest() & { return parsedTlsRequest_; }
|
||||
|
||||
/**
|
||||
* @brief Converts the TLS message type to a string representation.
|
||||
*
|
||||
* @return String representation of the TLS message type.
|
||||
*/
|
||||
const std::string tlsTypeToString() const;
|
||||
std::string tlsTypeToString() const;
|
||||
|
||||
/**
|
||||
* @brief Getter for the destination IP address.
|
||||
*
|
||||
* @return Destination IP address as a string.
|
||||
*/
|
||||
inline const std::string &dstIP() { return dstIP_; }
|
||||
inline const std::string &dstIp() const { return dstIp_; }
|
||||
|
||||
/**
|
||||
* @brief Getter for the destination port.
|
||||
*
|
||||
* @return Destination port as an unsigned short.
|
||||
*/
|
||||
inline const unsigned short &dstPort() { return dstPort_; }
|
||||
inline unsigned short dstPort() const { return dstPort_; }
|
||||
|
||||
/**
|
||||
* @brief Converts the HTTP object state to a string representation.
|
||||
*
|
||||
* @return A string representation of the HTTP object's state.
|
||||
*/
|
||||
const std::string toString() const;
|
||||
std::string toString() const;
|
||||
|
||||
/**
|
||||
* @brief Converts the REST-related HTTP state to a string representation.
|
||||
*
|
||||
* @return A string representation of the REST-related state.
|
||||
*/
|
||||
const std::string restoString() const;
|
||||
|
||||
std::string chunkHeader_;
|
||||
std::string restoString() const;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Private constructor for the HTTP class.
|
||||
*
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param buffer Reference to a stream buffer containing data for processing.
|
||||
* @param uuid A unique identifier for the session.
|
||||
*/
|
||||
explicit HTTP(const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
boost::asio::streambuf &buffer,
|
||||
boost::uuids::uuid uuid);
|
||||
|
||||
/**
|
||||
* @brief Sets the destination IP and port based on the parsed data.
|
||||
*/
|
||||
void setIPPort();
|
||||
|
||||
const std::shared_ptr<Config> &config_;
|
||||
const std::shared_ptr<Log> &log_;
|
||||
std::shared_ptr<Config> config_;
|
||||
std::shared_ptr<Log> log_;
|
||||
boost::asio::streambuf &buffer_;
|
||||
|
||||
boost::beast::http::parser<false, boost::beast::http::string_body> parser_;
|
||||
boost::beast::http::request<boost::beast::http::string_body> parsedHttpRequest_;
|
||||
boost::beast::http::response<boost::beast::http::string_body> parsedHttpResponse_;
|
||||
|
||||
HttpType httpType_;
|
||||
std::string dstIP_;
|
||||
std::string dstIp_;
|
||||
unsigned short dstPort_;
|
||||
TlsRequest parsedTlsRequest_;
|
||||
boost::uuids::uuid uuid_;
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,126 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
namespace http_utils {
|
||||
|
||||
inline std::string makeHostPort(const std::string &host, uint16_t port) {
|
||||
if (host.find(':') != std::string::npos &&
|
||||
!(host.size() >= 2 && host.front() == '[' && host.back() == ']')) {
|
||||
return "[" + host + "]:" + std::to_string(port);
|
||||
}
|
||||
|
||||
return host + ":" + std::to_string(port);
|
||||
}
|
||||
|
||||
inline std::string toLowerCopy(std::string value) {
|
||||
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) {
|
||||
return static_cast<char>(std::tolower(c));
|
||||
});
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
inline std::string trimCopy(std::string value) {
|
||||
while (!value.empty() && (value.front() == ' ' || value.front() == '\t')) {
|
||||
value.erase(value.begin());
|
||||
}
|
||||
|
||||
while (!value.empty() &&
|
||||
(value.back() == ' ' ||
|
||||
value.back() == '\t' ||
|
||||
value.back() == '\r' ||
|
||||
value.back() == '\n')) {
|
||||
value.pop_back();
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
inline std::string extractHeaders(const std::string &message) {
|
||||
const auto pos = message.find("\r\n\r\n");
|
||||
if (pos == std::string::npos) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return message.substr(0, pos + 4);
|
||||
}
|
||||
|
||||
inline std::string extractBody(const std::string &message) {
|
||||
const auto pos = message.find("\r\n\r\n");
|
||||
if (pos == std::string::npos) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return message.substr(pos + 4);
|
||||
}
|
||||
|
||||
inline bool parseContentLength(const std::string &headers, std::size_t &value) {
|
||||
std::istringstream iss(headers);
|
||||
std::string line;
|
||||
|
||||
while (std::getline(iss, line)) {
|
||||
if (!line.empty() && line.back() == '\r') {
|
||||
line.pop_back();
|
||||
}
|
||||
|
||||
const auto lower = toLowerCopy(line);
|
||||
if (lower.rfind("content-length:", 0) == 0) {
|
||||
auto raw = line.substr(std::string("Content-Length:").size());
|
||||
raw.erase(0, raw.find_first_not_of(" \t"));
|
||||
|
||||
try {
|
||||
value = static_cast<std::size_t>(std::stoull(raw));
|
||||
return true;
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
inline bool isChunked(const std::string &headers) {
|
||||
std::istringstream iss(headers);
|
||||
std::string line;
|
||||
|
||||
while (std::getline(iss, line)) {
|
||||
if (!line.empty() && line.back() == '\r') {
|
||||
line.pop_back();
|
||||
}
|
||||
|
||||
const auto lower = toLowerCopy(line);
|
||||
if (lower.rfind("transfer-encoding:", 0) == 0 &&
|
||||
lower.find("chunked") != std::string::npos) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
inline std::string getRawHeader(const std::string &headers, const std::string &name) {
|
||||
std::istringstream iss(headers);
|
||||
std::string line;
|
||||
|
||||
const std::string prefix = toLowerCopy(name) + ":";
|
||||
|
||||
while (std::getline(iss, line)) {
|
||||
if (!line.empty() && line.back() == '\r') {
|
||||
line.pop_back();
|
||||
}
|
||||
|
||||
const std::string lower = toLowerCopy(line);
|
||||
if (lower.rfind(prefix, 0) == 0) {
|
||||
return trimCopy(line.substr(name.size() + 1));
|
||||
}
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
}// namespace http_utils
|
||||
+9
-36
@@ -1,15 +1,8 @@
|
||||
#include "log.hpp"
|
||||
|
||||
/**
|
||||
* @brief Constructs a `Log` object with the given configuration.
|
||||
*
|
||||
* Initializes the logging mode and log level based on the configuration.
|
||||
* Also verifies if the log file is accessible.
|
||||
*
|
||||
* @param config Shared pointer to the configuration object.
|
||||
*/
|
||||
Log::Log(const std::shared_ptr<Config> &config)
|
||||
: config_(config), level_(Level::INFO) {
|
||||
|
||||
if (config_->runMode() == RunMode::server)
|
||||
mode_ = std::string("SERVER");
|
||||
else if (config_->runMode() == RunMode::agent)
|
||||
@@ -22,6 +15,7 @@ Log::Log(const std::shared_ptr<Config> &config)
|
||||
}
|
||||
|
||||
const auto &logLevel = config_->log().level;
|
||||
|
||||
if (logLevel == "INFO") {
|
||||
level_ = Level::INFO;
|
||||
} else if (logLevel == "TRACE") {
|
||||
@@ -34,40 +28,24 @@ Log::Log(const std::shared_ptr<Config> &config)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Copy constructor for the `Log` class.
|
||||
*
|
||||
* Copies the configuration and log level from an existing `Log` instance.
|
||||
*
|
||||
* @param log Shared pointer to the source `Log` object.
|
||||
*/
|
||||
Log::Log(const std::shared_ptr<Log> &log)
|
||||
: config_(log->config_), level_(log->level_) {}
|
||||
|
||||
/**
|
||||
* @brief Destructor for the `Log` class.
|
||||
*
|
||||
* Ensures cleanup of any resources, although none are dynamically allocated here.
|
||||
*/
|
||||
Log::~Log() {}
|
||||
|
||||
/**
|
||||
* @brief Writes a log message to the log file and console.
|
||||
*
|
||||
* Ensures thread safety using a mutex. Messages are logged only if their severity
|
||||
* level meets or exceeds the configured logging level, or if they are errors.
|
||||
*
|
||||
* @param message The log message to write.
|
||||
* @param level The severity level of the message.
|
||||
*/
|
||||
void Log::write(const std::string &message, Level level) const {
|
||||
std::lock_guard<std::mutex> lock(logMutex_);
|
||||
|
||||
if (level <= level_ || level == Level::ERROR) {
|
||||
|
||||
std::ofstream logFile(config_->log().file, std::ios::out | std::ios::app);
|
||||
|
||||
if (logFile.is_open()) {
|
||||
|
||||
|
||||
auto now = std::time(nullptr);
|
||||
auto localTime = *std::localtime(&now);
|
||||
|
||||
std::ostringstream timestampStream;
|
||||
timestampStream << std::put_time(&localTime, "%Y-%m-%d_%H:%M:%S");
|
||||
std::string timestamp = timestampStream.str();
|
||||
@@ -77,6 +55,7 @@ void Log::write(const std::string &message, Level level) const {
|
||||
|
||||
logFile << line;
|
||||
std::cout << line;
|
||||
|
||||
} else {
|
||||
std::cerr << "Error opening log file: " << config_->log().file
|
||||
<< ". Make sure the directory and file exist.\n";
|
||||
@@ -84,12 +63,6 @@ void Log::write(const std::string &message, Level level) const {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts a log level enum value to its string representation.
|
||||
*
|
||||
* @param level The log level to convert.
|
||||
* @return The string representation of the log level.
|
||||
*/
|
||||
std::string Log::levelToString(Level level) {
|
||||
switch (level) {
|
||||
case Level::INFO:
|
||||
@@ -103,4 +76,4 @@ std::string Log::levelToString(Level level) {
|
||||
default:
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-68
@@ -1,6 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
// Standard library includes
|
||||
#include <ctime>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
@@ -8,24 +7,11 @@
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
// Project-specific includes
|
||||
#include "config.hpp"
|
||||
#include "general.hpp"
|
||||
|
||||
/**
|
||||
* @class Log
|
||||
* @brief Provides logging functionality with different log levels and thread safety.
|
||||
*
|
||||
* The `Log` class is responsible for writing log messages to a file or other output.
|
||||
* It supports various log levels (INFO, TRACE, ERROR, DEBUG) and ensures thread-safe
|
||||
* logging using a mutex.
|
||||
*/
|
||||
class Log : private Uncopyable {
|
||||
public:
|
||||
/**
|
||||
* @enum Level
|
||||
* @brief Defines the severity levels of log messages.
|
||||
*/
|
||||
enum class Level {
|
||||
INFO,
|
||||
TRACE,
|
||||
@@ -35,79 +21,28 @@ public:
|
||||
|
||||
using pointer = std::shared_ptr<Log>;
|
||||
|
||||
/**
|
||||
* @brief Creates a new instance of the Log class.
|
||||
*
|
||||
* This static method is the primary way to instantiate a Log object. It ensures
|
||||
* proper encapsulation and memory management via `std::shared_ptr`.
|
||||
*
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @return A shared pointer to the newly created Log instance.
|
||||
*/
|
||||
static pointer create(const std::shared_ptr<Config> &config) {
|
||||
return pointer(new Log(config));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Constructs a Log object by copying another Log instance.
|
||||
*
|
||||
* @param log Shared pointer to the Log object to copy.
|
||||
*/
|
||||
explicit Log(const std::shared_ptr<Log> &log);
|
||||
|
||||
/**
|
||||
* @brief Destructor for the Log class.
|
||||
*
|
||||
* Ensures proper cleanup of resources, such as closing log files, if necessary.
|
||||
*/
|
||||
~Log();
|
||||
|
||||
/**
|
||||
* @brief Gets the configuration associated with this Log instance.
|
||||
*
|
||||
* @return A shared pointer to the configuration object.
|
||||
*/
|
||||
const std::shared_ptr<Config> &config() const { return config_; }
|
||||
std::shared_ptr<Config> config() const { return config_; }
|
||||
|
||||
/**
|
||||
* @brief Gets the current logging level.
|
||||
*
|
||||
* @return The current logging level as an enum value.
|
||||
*/
|
||||
Level level() const { return level_; }
|
||||
|
||||
/**
|
||||
* @brief Writes a log message with a specified log level.
|
||||
*
|
||||
* This function is thread-safe and ensures that multiple threads can log messages
|
||||
* without interfering with each other.
|
||||
*
|
||||
* @param message The log message to write.
|
||||
* @param level The severity level of the message.
|
||||
*/
|
||||
void write(const std::string &message, Level level) const;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Constructs a Log object with a specified configuration.
|
||||
*
|
||||
* This constructor is private to enforce the use of the `create` factory method.
|
||||
*
|
||||
* @param config Shared pointer to the configuration object.
|
||||
*/
|
||||
explicit Log(const std::shared_ptr<Config> &config);
|
||||
|
||||
/**
|
||||
* @brief Converts a log level enum value to a string representation.
|
||||
*
|
||||
* @param level The log level to convert.
|
||||
* @return A string representation of the log level.
|
||||
*/
|
||||
static std::string levelToString(Level level);
|
||||
|
||||
const std::shared_ptr<Config> &config_;
|
||||
std::shared_ptr<Config> config_;
|
||||
Level level_;
|
||||
std::string mode_;
|
||||
|
||||
mutable std::mutex logMutex_;
|
||||
};
|
||||
};
|
||||
+3
-3
@@ -12,6 +12,9 @@ int main(int argc, char const *argv[]) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
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
|
||||
@@ -19,9 +22,6 @@ int main(int argc, char const *argv[]) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::string mode(argv[1]);
|
||||
RunMode runMode_ = (mode == "agent") ? RunMode::agent : RunMode::server;
|
||||
|
||||
Config::pointer config_ = Config::create(runMode_, std::string(argv[2]));
|
||||
|
||||
Log::pointer log_ = Log::create(config_);
|
||||
|
||||
+14
-35
@@ -1,13 +1,5 @@
|
||||
#include "runner.hpp"
|
||||
|
||||
/**
|
||||
* @brief Constructs a `Runner` object with the given configuration and log instance.
|
||||
*
|
||||
* Initializes the `io_context_`, work guard, and strand. Sets the `running_` flag to true.
|
||||
*
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging instance.
|
||||
*/
|
||||
Runner::Runner(const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log)
|
||||
: config_(config),
|
||||
@@ -17,14 +9,10 @@ Runner::Runner(const std::shared_ptr<Config> &config,
|
||||
running_(true),
|
||||
strand_(boost::asio::make_strand(io_context_)) {}
|
||||
|
||||
/**
|
||||
* @brief Destructor for the `Runner` class.
|
||||
*
|
||||
* Stops the `io_context_`, ensures all threads in the thread pool are joined, and safely cleans up resources.
|
||||
*/
|
||||
Runner::~Runner() {
|
||||
running_.store(false);
|
||||
io_context_.stop();
|
||||
|
||||
for (auto &thread: threadPool_) {
|
||||
if (thread.joinable()) {
|
||||
thread.join();
|
||||
@@ -32,26 +20,30 @@ Runner::~Runner() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Starts the Runner's main execution.
|
||||
*
|
||||
* Initializes the server and spawns multiple worker threads to handle tasks asynchronously.
|
||||
* Joins all threads to ensure proper shutdown.
|
||||
*/
|
||||
void Runner::run() {
|
||||
try {
|
||||
|
||||
log_->write("Config initialized in " + config_->modeToString() + " mode", Log::Level::INFO);
|
||||
log_->write(config_->toString(), Log::Level::INFO);
|
||||
|
||||
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() * 50; ++i) {
|
||||
|
||||
for (auto i = 0; i < config_->threads(); ++i) {
|
||||
threadPool_.emplace_back([this] { workerThread(); });
|
||||
}
|
||||
|
||||
for (auto &thread: threadPool_) {
|
||||
if (thread.joinable()) {
|
||||
thread.join();
|
||||
}
|
||||
}
|
||||
|
||||
} catch (const std::exception &error) {
|
||||
log_->write(std::string("[Runner run] ") + error.what(), Log::Level::ERROR);
|
||||
} catch (...) {
|
||||
@@ -59,33 +51,20 @@ void Runner::run() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Worker thread function to process tasks from the `io_context_`.
|
||||
*
|
||||
* Each thread calls `io_context_.run()` to handle asynchronous operations. If an exception occurs,
|
||||
* it logs the error and continues processing.
|
||||
*/
|
||||
void Runner::workerThread() {
|
||||
while (running_.load()) {
|
||||
try {
|
||||
io_context_.run();
|
||||
break;
|
||||
} catch (const std::exception &e) {
|
||||
|
||||
log_->write(std::string("[WorkerThread] Exception: ") + e.what(), Log::Level::ERROR);
|
||||
} catch (...) {
|
||||
|
||||
log_->write("[WorkerThread] Unknown error occurred", Log::Level::ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Stops the Runner.
|
||||
*
|
||||
* Sets the `running_` flag to false and stops the `io_context_` to terminate the processing loop.
|
||||
*/
|
||||
void Runner::stop() {
|
||||
running_.store(false);
|
||||
io_context_.stop();
|
||||
}
|
||||
}
|
||||
+10
-51
@@ -7,81 +7,40 @@
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#if defined(__ANDROID__)
|
||||
using runnerThread = std::thread;
|
||||
#else
|
||||
using runnerThread = std::jthread;
|
||||
#endif
|
||||
|
||||
#include "config.hpp"
|
||||
#include "log.hpp"
|
||||
#include "tcpserver.hpp"
|
||||
|
||||
/**
|
||||
* @class Runner
|
||||
* @brief Manages the execution of an asynchronous Boost.Asio-based server.
|
||||
*
|
||||
* The `Runner` class sets up a multi-threaded environment for handling
|
||||
* asynchronous tasks using Boost.Asio. It provides mechanisms to run, manage,
|
||||
* and stop the server efficiently.
|
||||
*/
|
||||
class Runner : private Uncopyable {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs the `Runner` object with the specified configuration and logging instance.
|
||||
*
|
||||
* Initializes the Boost.Asio context and sets up the necessary guards and threading environment.
|
||||
*
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging instance.
|
||||
*/
|
||||
explicit Runner(const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log);
|
||||
|
||||
/**
|
||||
* @brief Destructor for the `Runner` class.
|
||||
*
|
||||
* Ensures that the server and its threads are gracefully stopped.
|
||||
*/
|
||||
~Runner();
|
||||
|
||||
/**
|
||||
* @brief Starts the asynchronous server and its worker threads.
|
||||
*
|
||||
* This method runs the Boost.Asio `io_context` to process asynchronous tasks.
|
||||
*/
|
||||
void run();
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Executes tasks in a worker thread.
|
||||
*
|
||||
* Each worker thread runs the `io_context`, allowing it to process asynchronous operations.
|
||||
*/
|
||||
void workerThread();
|
||||
|
||||
/**
|
||||
* @brief Stops the server and shuts down all threads gracefully.
|
||||
*
|
||||
* Signals the termination of the server and cleans up resources.
|
||||
*/
|
||||
void stop();
|
||||
|
||||
const std::shared_ptr<Config> &config_;
|
||||
|
||||
const std::shared_ptr<Log> &log_;
|
||||
std::shared_ptr<Config> config_;
|
||||
std::shared_ptr<Log> log_;
|
||||
|
||||
boost::asio::io_context io_context_;
|
||||
|
||||
/**
|
||||
* @brief Work guard to keep the `io_context` running.
|
||||
*
|
||||
* Ensures that the `io_context` does not exit when there are no tasks to process.
|
||||
*/
|
||||
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work_guard_;
|
||||
|
||||
std::atomic<bool> running_;
|
||||
|
||||
std::vector<std::jthread> threadPool_;
|
||||
std::vector<runnerThread> threadPool_;
|
||||
|
||||
/**
|
||||
* @brief Strand to ensure serialized execution of tasks within the `io_context`.
|
||||
*
|
||||
* Provides thread safety for handlers that must not run concurrently.
|
||||
*/
|
||||
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
|
||||
};
|
||||
};
|
||||
+361
-194
@@ -1,226 +1,393 @@
|
||||
#include "serverhandler.hpp"
|
||||
|
||||
/**
|
||||
* @brief Constructs a `ServerHandler` object.
|
||||
*
|
||||
* Initializes the HTTP request handler, client connection, and assigns references
|
||||
* to configuration, logging, and buffers.
|
||||
*/
|
||||
#include <sstream>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "http_utils.hpp"
|
||||
|
||||
std::mutex ServerHandler::sessionsMutex_;
|
||||
std::unordered_map<std::string, TCPClient::pointer> ServerHandler::sessions_;
|
||||
|
||||
std::string ServerHandler::HttpUtils::lowerCopy(std::string s) {
|
||||
return http_utils::toLowerCopy(std::move(s));
|
||||
}
|
||||
|
||||
std::string ServerHandler::HttpUtils::trimCopy(std::string s) {
|
||||
return http_utils::trimCopy(std::move(s));
|
||||
}
|
||||
|
||||
std::string ServerHandler::HttpUtils::getRawHeader(const std::string &headers,
|
||||
const std::string &name) {
|
||||
return http_utils::getRawHeader(headers, name);
|
||||
}
|
||||
|
||||
std::string ServerHandler::HttpUtils::extractHttpBody(const std::string &msg) {
|
||||
return http_utils::extractBody(msg);
|
||||
}
|
||||
|
||||
ServerHandler::ServerHandler(boost::asio::streambuf &readBuffer,
|
||||
boost::asio::streambuf &writeBuffer,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
const TCPClient::pointer &client,
|
||||
const std::string &clientConnStr,
|
||||
TCPClient::pointer client,
|
||||
std::string clientConnStr,
|
||||
boost::uuids::uuid uuid)
|
||||
: config_(config),
|
||||
log_(log),
|
||||
client_(client),
|
||||
client_(std::move(client)),
|
||||
readBuffer_(readBuffer),
|
||||
writeBuffer_(writeBuffer),
|
||||
request_(HTTP::create(config, log, readBuffer, uuid)),
|
||||
clientConnStr_(clientConnStr),
|
||||
clientConnStr_(std::move(clientConnStr)),
|
||||
uuid_(uuid) {
|
||||
end_ = false;
|
||||
connect_ = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Destructor for `ServerHandler`.
|
||||
*
|
||||
* Ensures cleanup of resources, though currently the destructor does not perform specific actions.
|
||||
*/
|
||||
ServerHandler::~ServerHandler() {}
|
||||
|
||||
/**
|
||||
* @brief Handles the incoming request and processes it based on its type.
|
||||
*
|
||||
* Processes HTTP or HTTPS requests, decrypts payloads, performs appropriate actions
|
||||
* (e.g., connect or forward requests), and generates responses.
|
||||
*/
|
||||
void ServerHandler::makePlainHttpResponse(const std::string &body,
|
||||
const std::string &status,
|
||||
const std::string &connection) {
|
||||
std::ostringstream outer;
|
||||
|
||||
outer << "HTTP/1.1 " << status << "\r\n"
|
||||
<< "Content-Type: application/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()) {
|
||||
|
||||
if (!request_->detectType()) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) + "] [ServerHandler handle] [Request From Agent] : " + request_->toString(),
|
||||
Log::Level::DEBUG);
|
||||
BoolStr decryption{false, std::string("FAILED")};
|
||||
decryption = aes256Decrypt(decode64(boost::lexical_cast<std::string>(
|
||||
request_->parsedHttpRequest().body())),
|
||||
config_->general().token);
|
||||
|
||||
if (decryption.ok) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) + "] [ServerHandler handle] [Token Valid] : " + request_->toString(),
|
||||
Log::Level::DEBUG);
|
||||
auto tempHexArr = strToHexArr(decryption.message);
|
||||
std::string tempHexArrStr(tempHexArr.begin(), tempHexArr.end());
|
||||
copyStringToStreambuf(tempHexArrStr, readBuffer_);
|
||||
|
||||
if (request_->detectType()) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) + "] [ServerHandler handle] [Request] : " + request_->toString(),
|
||||
Log::Level::DEBUG);
|
||||
switch (request_->httpType()) {
|
||||
case HTTP::HttpType::connect: {
|
||||
connect_ = true;
|
||||
boost::asio::streambuf tempBuff;
|
||||
std::iostream os(&tempBuff);
|
||||
if (client_->doConnect(request_->dstIP(), request_->dstPort())) {
|
||||
log_->write("[" + to_string(uuid_) + "] [CONNECT] [SRC " + clientConnStr_ + "] [DST " +
|
||||
request_->dstIP() + ":" +
|
||||
std::to_string(request_->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
} else {
|
||||
log_->write(
|
||||
std::string("[" + to_string(uuid_) + "] [CONNECT] [ERROR] [Resolving Host] [SRC ") +
|
||||
clientConnStr_ + "] [DST " + request_->dstIP() + ":" +
|
||||
std::to_string(request_->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
}
|
||||
if (client_->socket().is_open()) {
|
||||
std::string message(
|
||||
"HTTP/1.1 200 Connection established COMP\r\n\r\n");
|
||||
os << message;
|
||||
} else {
|
||||
std::string message("HTTP/1.1 500 Connection failed COMP\r\n\r\n");
|
||||
os << message;
|
||||
}
|
||||
moveStreambuf(tempBuff, writeBuffer_);
|
||||
} break;
|
||||
case HTTP::HttpType::http:
|
||||
case HTTP::HttpType::https: {
|
||||
if (request_->httpType() == HTTP::HttpType::http) {
|
||||
if (client_->doConnect(request_->dstIP(), request_->dstPort())) {
|
||||
log_->write("[" + to_string(uuid_) + "] [CONNECT] [SRC " + clientConnStr_ + "] [DST " +
|
||||
request_->dstIP() + ":" +
|
||||
std::to_string(request_->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
} else {
|
||||
log_->write(
|
||||
std::string("[" + to_string(uuid_) + "] [CONNECT] [ERROR] [Resolving Host] [SRC ") +
|
||||
clientConnStr_ + "] [DST " + request_->dstIP() + ":" +
|
||||
std::to_string(request_->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
}
|
||||
}
|
||||
if (!client_->socket().is_open()) {
|
||||
client_->doConnect(request_->dstIP(), request_->dstPort());
|
||||
}
|
||||
client_->doWrite(readBuffer_);
|
||||
client_->doReadServer();
|
||||
end_ = client_->end_;
|
||||
if (client_->readBuffer().size() > 0) {
|
||||
BoolStr encryption{false, std::string("FAILED")};
|
||||
encryption =
|
||||
aes256Encrypt(streambufToString(client_->readBuffer()),
|
||||
config_->general().token);
|
||||
if (encryption.ok) {
|
||||
if (end_) {
|
||||
request_->chunkHeader_ = "yes";
|
||||
}
|
||||
std::string newRes(
|
||||
request_->genHttpOkResString(encode64(encryption.message)));
|
||||
copyStringToStreambuf(newRes, writeBuffer_);
|
||||
if (request_->httpType() == HTTP::HttpType::http) {
|
||||
client_->socket().close();
|
||||
} else {
|
||||
if (request_->parsedTlsRequest().type ==
|
||||
HTTP::TlsTypes::ApplicationData) {
|
||||
client_->socket().close();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [ServerHandler handle] [Encryption "
|
||||
"Failed] : [ " +
|
||||
encryption.message + "] ",
|
||||
Log::Level::DEBUG);
|
||||
log_->write("[" + to_string(uuid_) + "] [ServerHandler handle] [Encryption Failed] : " +
|
||||
request_->toString(),
|
||||
Log::Level::INFO);
|
||||
client_->socket().close();
|
||||
}
|
||||
} else {
|
||||
client_->socket().close();
|
||||
return;
|
||||
}
|
||||
} break;
|
||||
}
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) + "] [ServerHandler handle] [NOT HTTP Request] [Request] : " +
|
||||
streambufToString(readBuffer_),
|
||||
Log::Level::DEBUG);
|
||||
|
||||
client_->socket().close();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) + "] [ServerHandler handle] [Decryption Failed] : [ " +
|
||||
decryption.message + "] ",
|
||||
Log::Level::DEBUG);
|
||||
log_->write("[" + to_string(uuid_) + "] [ServerHandler handle] [Decryption Failed] : " +
|
||||
request_->toString(),
|
||||
Log::Level::INFO);
|
||||
|
||||
client_->socket().close();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) + "] [ServerHandler handle] [NOT HTTP Request From Agent] [Request] : " +
|
||||
"[" + to_string(uuid_) +
|
||||
"] [ServerHandler handle] [NOT HTTP Request From Agent] [Request] : " +
|
||||
streambufToString(readBuffer_),
|
||||
Log::Level::DEBUG);
|
||||
|
||||
client_->socket().close();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Continues reading and processing data from the client.
|
||||
*
|
||||
* Encrypts responses and manages the client socket's lifecycle based on the request type.
|
||||
*/
|
||||
void ServerHandler::continueRead() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
client_->doReadServer();
|
||||
end_ = client_->end_;
|
||||
if (client_->readBuffer().size() > 0) {
|
||||
BoolStr encryption{false, std::string("FAILED")};
|
||||
encryption =
|
||||
aes256Encrypt(streambufToString(client_->readBuffer()),
|
||||
config_->general().token);
|
||||
if (encryption.ok) {
|
||||
if (end_) {
|
||||
request_->chunkHeader_ = "yes";
|
||||
}
|
||||
std::string newRes(
|
||||
request_->genHttpOkResString(encode64(encryption.message)));
|
||||
copyStringToStreambuf(newRes, writeBuffer_);
|
||||
if (request_->httpType() == HTTP::HttpType::http) {
|
||||
client_->socket().close();
|
||||
} else {
|
||||
if (request_->parsedTlsRequest().type ==
|
||||
HTTP::TlsTypes::ApplicationData) {
|
||||
client_->socket().close();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [ServerHandler handle] [Encryption "
|
||||
"Failed] : [ " +
|
||||
encryption.message + "] ",
|
||||
Log::Level::DEBUG);
|
||||
log_->write("[" + to_string(uuid_) + "] [ServerHandler handle] [Encryption Failed] : " +
|
||||
request_->toString(),
|
||||
Log::Level::INFO);
|
||||
client_->socket().close();
|
||||
}
|
||||
} else {
|
||||
client_->socket().close();
|
||||
const auto &outerReq = request_->parsedHttpRequest();
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
makePayloadHttpResponse("", "400 Bad Request", "close");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (inner->httpType()) {
|
||||
case HTTP::HttpType::connect: {
|
||||
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);
|
||||
|
||||
makePayloadHttpResponse(
|
||||
"HTTP/1.1 502 Bad Gateway\r\n\r\n",
|
||||
"502 Bad Gateway",
|
||||
"close");
|
||||
|
||||
connect_ = false;
|
||||
end_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [CONNECT] [SRC " +
|
||||
clientConnStr_ + "] [DST " +
|
||||
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
|
||||
makePayloadHttpResponse(
|
||||
"HTTP/1.1 200 Connection Established\r\n\r\n",
|
||||
"200 OK",
|
||||
"keep-alive");
|
||||
|
||||
connect_ = true;
|
||||
end_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
TCPClient::pointer targetClient = TCPClient::create(
|
||||
static_cast<boost::asio::io_context &>(
|
||||
client_->socket().get_executor().context()),
|
||||
config_,
|
||||
log_);
|
||||
|
||||
targetClient->uuid_ = uuid_;
|
||||
|
||||
if (!targetClient->doConnect(inner->dstIp(), inner->dstPort())) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [CONNECT] [ERROR] [Resolving Host] [SRC " +
|
||||
clientConnStr_ + "] [DST " +
|
||||
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
|
||||
makePayloadHttpResponse(
|
||||
"HTTP/1.1 502 Bad Gateway\r\n\r\n",
|
||||
"502 Bad Gateway",
|
||||
"close");
|
||||
|
||||
connect_ = false;
|
||||
end_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [CONNECT] [SRC " +
|
||||
clientConnStr_ + "] [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())) {
|
||||
client_->socket().close();
|
||||
makePayloadHttpResponse("", "502 Bad Gateway", "close");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
client_->doWrite(readBuffer_);
|
||||
client_->doReadServer();
|
||||
|
||||
if (client_->readBuffer().size() == 0) {
|
||||
client_->socket().close();
|
||||
makePayloadHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
return;
|
||||
}
|
||||
|
||||
makePayloadHttpResponse(
|
||||
streambufToString(client_->readBuffer()),
|
||||
"200 OK",
|
||||
(config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
|
||||
connect_ = false;
|
||||
end_ = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
+33
-77
@@ -1,6 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "config.hpp"
|
||||
#include "general.hpp"
|
||||
@@ -8,110 +11,63 @@
|
||||
#include "log.hpp"
|
||||
#include "tcpclient.hpp"
|
||||
|
||||
/**
|
||||
* @class ServerHandler
|
||||
* @brief Handles server-side processing for a specific connection.
|
||||
*
|
||||
* The `ServerHandler` manages incoming requests, outgoing responses, and the connection state.
|
||||
* It is tightly coupled with the configuration, logging, and client connection objects.
|
||||
*/
|
||||
class ServerHandler : private Uncopyable {
|
||||
public:
|
||||
using pointer = std::shared_ptr<ServerHandler>;
|
||||
|
||||
/**
|
||||
* @brief Factory method to create a new `ServerHandler` instance.
|
||||
*
|
||||
* @param readBuffer Reference to the read buffer for incoming data.
|
||||
* @param writeBuffer Reference to the write buffer for outgoing data.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging instance.
|
||||
* @param client Pointer to the TCP client associated with the connection.
|
||||
* @param clientConnStr String representing the client connection (e.g., IP and port).
|
||||
* @param uuid UUID associated with the connection.
|
||||
* @return Shared pointer to the newly created `ServerHandler` instance.
|
||||
*/
|
||||
static pointer create(boost::asio::streambuf &readBuffer,
|
||||
boost::asio::streambuf &writeBuffer,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
const TCPClient::pointer &client,
|
||||
const std::string &clientConnStr,
|
||||
TCPClient::pointer client,
|
||||
std::string clientConnStr,
|
||||
boost::uuids::uuid uuid) {
|
||||
return pointer(new ServerHandler(readBuffer, writeBuffer, config, log,
|
||||
client, clientConnStr, uuid));
|
||||
return pointer(new ServerHandler(readBuffer, writeBuffer, config, log, client, clientConnStr, uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Destructor for the `ServerHandler` class.
|
||||
*/
|
||||
~ServerHandler();
|
||||
|
||||
/**
|
||||
* @brief Handles incoming requests and manages responses.
|
||||
*
|
||||
* This function is responsible for processing the request and initiating
|
||||
* the necessary actions based on the server's business logic.
|
||||
*/
|
||||
void handle();
|
||||
|
||||
/**
|
||||
* @brief Continues reading from the connection.
|
||||
*
|
||||
* This function is invoked when additional data is expected to be read.
|
||||
*/
|
||||
void continueRead();
|
||||
|
||||
/**
|
||||
* @brief Returns a reference to the HTTP request object.
|
||||
*
|
||||
* Provides access to the request being handled by the server.
|
||||
*
|
||||
* @return Reference to the HTTP request object.
|
||||
*/
|
||||
inline const HTTP::pointer &request() & { return request_; }
|
||||
|
||||
/**
|
||||
* @brief Returns an rvalue reference to the HTTP request object.
|
||||
*
|
||||
* Allows moving the HTTP request object when necessary.
|
||||
*
|
||||
* @return Rvalue reference to the HTTP request object.
|
||||
*/
|
||||
inline const HTTP::pointer &&request() && { return std::move(request_); }
|
||||
inline const HTTP::pointer &request() const { return request_; }
|
||||
|
||||
bool end_;
|
||||
bool connect_;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Constructor for `ServerHandler`.
|
||||
*
|
||||
* Initializes the handler with the given buffers, configuration, log, client,
|
||||
* connection string, and UUID.
|
||||
*
|
||||
* @param readBuffer Reference to the read buffer for incoming data.
|
||||
* @param writeBuffer Reference to the write buffer for outgoing data.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging instance.
|
||||
* @param client Pointer to the TCP client associated with the connection.
|
||||
* @param clientConnStr String representing the client connection (e.g., IP and port).
|
||||
* @param uuid UUID associated with the connection.
|
||||
*/
|
||||
struct HttpUtils {
|
||||
static std::string lowerCopy(std::string s);
|
||||
static std::string trimCopy(std::string s);
|
||||
static std::string getRawHeader(const std::string &headers, const std::string &name);
|
||||
static std::string extractHttpBody(const std::string &msg);
|
||||
};
|
||||
|
||||
explicit ServerHandler(boost::asio::streambuf &readBuffer,
|
||||
boost::asio::streambuf &writeBuffer,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
const TCPClient::pointer &client,
|
||||
const std::string &clientConnStr,
|
||||
TCPClient::pointer client,
|
||||
std::string clientConnStr,
|
||||
boost::uuids::uuid uuid);
|
||||
const std::shared_ptr<Config> &config_;
|
||||
const std::shared_ptr<Log> &log_;
|
||||
const TCPClient::pointer &client_;
|
||||
|
||||
void makePayloadHttpResponse(const std::string &plainBody,
|
||||
const std::string &status = "200 OK",
|
||||
const std::string &connection = "close");
|
||||
|
||||
void makePlainHttpResponse(const std::string &body,
|
||||
const std::string &status = "200 OK",
|
||||
const std::string &connection = "close");
|
||||
|
||||
static std::mutex sessionsMutex_;
|
||||
static std::unordered_map<std::string, TCPClient::pointer> sessions_;
|
||||
|
||||
std::shared_ptr<Config> config_;
|
||||
std::shared_ptr<Log> log_;
|
||||
TCPClient::pointer client_;
|
||||
boost::asio::streambuf &readBuffer_;
|
||||
boost::asio::streambuf &writeBuffer_;
|
||||
HTTP::pointer request_;
|
||||
const std::string &clientConnStr_;
|
||||
std::string clientConnStr_;
|
||||
boost::uuids::uuid uuid_;
|
||||
std::mutex mutex_;
|
||||
};
|
||||
};
|
||||
+717
-223
File diff suppressed because it is too large.
Load diff
+67
-94
@@ -1,133 +1,106 @@
|
||||
#pragma once
|
||||
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/asio/steady_timer.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <boost/enable_shared_from_this.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/asio/ssl.hpp>
|
||||
#include <boost/uuid/uuid.hpp>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
#include "config.hpp"
|
||||
#include "general.hpp"
|
||||
#include "http.hpp"
|
||||
#include "log.hpp"
|
||||
|
||||
/**
|
||||
* @brief Represents a TCP client that handles communication with a server.
|
||||
*
|
||||
* Uses Boost.Asio for asynchronous networking operations. Supports connection,
|
||||
* read, write, and timeout management.
|
||||
*/
|
||||
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 shared pointer to a TCPClient instance.
|
||||
*
|
||||
* @param io_context The IO context for asynchronous operations.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @return pointer A shared pointer to the newly created TCPClient instance.
|
||||
*/
|
||||
static pointer create(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log) {
|
||||
return pointer(new TCPClient(io_context, config, log));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Gets the socket associated with the TCP client.
|
||||
*
|
||||
* @return boost::asio::ip::tcp::socket& The socket used for communication.
|
||||
*/
|
||||
boost::asio::ip::tcp::socket &socket();
|
||||
tcp::socket &socket();
|
||||
ssl_stream &sslSocket();
|
||||
|
||||
bool tlsEnabled() const;
|
||||
bool isOpen() const;
|
||||
|
||||
bool enableTlsClient();
|
||||
bool doHandshakeClient();
|
||||
bool doConnect(const std::string &dstIp, unsigned short dstPort);
|
||||
|
||||
/**
|
||||
* @brief Writes data from the given buffer to the socket.
|
||||
*
|
||||
* @param buffer The buffer containing data to be written.
|
||||
*/
|
||||
void writeBuffer(boost::asio::streambuf &buffer);
|
||||
|
||||
inline boost::asio::streambuf &writeBuffer() & { return writeBuffer_; }
|
||||
inline boost::asio::streambuf &&writeBuffer() && {
|
||||
return std::move(writeBuffer_);
|
||||
}
|
||||
|
||||
inline boost::asio::streambuf &readBuffer() & { return readBuffer_; }
|
||||
inline boost::asio::streambuf &&readBuffer() && {
|
||||
return std::move(readBuffer_);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Establishes a connection to the specified server.
|
||||
*
|
||||
* @param dstIP The destination server's IP address.
|
||||
* @param dstPort The destination server's port.
|
||||
* @return bool True if the connection was successful, otherwise false.
|
||||
*/
|
||||
bool doConnect(const std::string &dstIP, const unsigned short &dstPort);
|
||||
|
||||
/**
|
||||
* @brief Sends data to the server using the provided buffer.
|
||||
*
|
||||
* @param buffer The buffer containing data to be sent.
|
||||
*/
|
||||
void doWrite(boost::asio::streambuf &buffer);
|
||||
|
||||
/**
|
||||
* @brief Reads data from the agent (client-side).
|
||||
*/
|
||||
void doReadAgent();
|
||||
|
||||
/**
|
||||
* @brief Reads data from the server (server-side).
|
||||
*/
|
||||
bool doReadAgent();
|
||||
bool doWrite(boost::asio::streambuf &buffer);
|
||||
void doReadServer();
|
||||
|
||||
/**
|
||||
* @brief Shuts down the socket gracefully.
|
||||
*/
|
||||
void socketShutdown();
|
||||
|
||||
boost::uuids::uuid uuid() const { return uuid_; }
|
||||
bool ended() const { return end_; }
|
||||
|
||||
boost::uuids::uuid uuid_;
|
||||
bool end_;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Constructs a `TCPClient` instance.
|
||||
*
|
||||
* Initializes the socket, resolver, timeout, and stores references to the
|
||||
* configuration and logging objects.
|
||||
*
|
||||
* @param io_context The IO context for asynchronous operations.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
*/
|
||||
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 timeout timer to handle long-running operations.
|
||||
*/
|
||||
void resetTimeout();
|
||||
|
||||
/**
|
||||
* @brief Cancels the timeout timer.
|
||||
*/
|
||||
void cancelTimeout();
|
||||
|
||||
/**
|
||||
* @brief Handles timeout events and performs appropriate actions.
|
||||
*
|
||||
* @param error The error code associated with the timeout event.
|
||||
*/
|
||||
void onTimeout(const boost::system::error_code &error);
|
||||
const std::shared_ptr<Config> &config_;
|
||||
const std::shared_ptr<Log> &log_;
|
||||
|
||||
std::shared_ptr<Config> config_;
|
||||
std::shared_ptr<Log> log_;
|
||||
boost::asio::io_context &io_context_;
|
||||
boost::asio::ip::tcp::socket socket_;
|
||||
boost::asio::streambuf buffer_, writeBuffer_, readBuffer_;
|
||||
boost::asio::ip::tcp::resolver resolver_;
|
||||
boost::asio::deadline_timer timeout_;
|
||||
|
||||
tcp::socket socket_;
|
||||
boost::asio::ssl::context sslContext_;
|
||||
std::unique_ptr<ssl_stream> sslSocket_;
|
||||
bool tlsEnabled_;
|
||||
|
||||
boost::asio::streambuf buffer_;
|
||||
boost::asio::streambuf writeBuffer_;
|
||||
boost::asio::streambuf readBuffer_;
|
||||
|
||||
tcp::resolver resolver_;
|
||||
boost::asio::steady_timer timeout_;
|
||||
mutable std::mutex mutex_;
|
||||
};
|
||||
bool closed_ = false;
|
||||
};
|
||||
+1049
-269
File diff suppressed because it is too large.
Load diff
+105
-108
@@ -1,33 +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/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 TCPConnection class that handles the communication with the TCP client.
|
||||
*
|
||||
* This class manages reading and writing data to a TCP socket, handles timeouts,
|
||||
* and provides methods for connecting, disconnecting, and reading or writing data.
|
||||
*/
|
||||
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 pointer = std::shared_ptr<TCPConnection>;
|
||||
using ssl_stream = boost::asio::ssl::stream<boost::asio::ip::tcp::socket>;
|
||||
|
||||
/**
|
||||
* @brief Factory method to create a shared pointer to a TCPConnection instance.
|
||||
*
|
||||
* @param io_context The IO context for asynchronous operations.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param client Shared pointer to the associated TCPClient.
|
||||
* @return A shared pointer to the newly created TCPConnection instance.
|
||||
*/
|
||||
static pointer create(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
@@ -35,125 +30,127 @@ public:
|
||||
return pointer(new TCPConnection(io_context, config, log, client));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the TCP socket associated with the TCPConnection.
|
||||
*
|
||||
* @return A reference to the TCP socket.
|
||||
*/
|
||||
boost::asio::ip::tcp::socket &socket();
|
||||
inline TCPClient::pointer client() const { return client_; }
|
||||
ssl_stream &tlsSocket();
|
||||
|
||||
bool initTlsServerContext();
|
||||
bool doHandshakeServer();
|
||||
|
||||
/**
|
||||
* @brief Writes the provided buffer to the TCP connection's write buffer.
|
||||
*
|
||||
* @param buffer The buffer containing data to write.
|
||||
*/
|
||||
inline void writeBuffer(boost::asio::streambuf &buffer) {
|
||||
moveStreambuf(buffer, writeBuffer_);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a constant reference to the TCP connection's read buffer.
|
||||
*
|
||||
* @return A constant reference to the read buffer.
|
||||
*/
|
||||
inline const boost::asio::streambuf &readBuffer() & { return readBuffer_; }
|
||||
|
||||
/**
|
||||
* @brief Returns a rvalue reference to the TCP connection's read buffer (after moving it).
|
||||
*
|
||||
* @return A rvalue reference to the read buffer.
|
||||
*/
|
||||
inline const boost::asio::streambuf &&readBuffer() && {
|
||||
return std::move(readBuffer_);
|
||||
}
|
||||
inline boost::uuids::uuid uuid() const { return uuid_; }
|
||||
|
||||
/**
|
||||
* @brief Returns the unique identifier (UUID) of the TCP connection.
|
||||
*
|
||||
* @return The UUID associated with the TCP connection.
|
||||
*/
|
||||
inline boost::uuids::uuid uuid() { return uuid_; }
|
||||
|
||||
/**
|
||||
* @brief Starts the TCP connection by initiating the reading process.
|
||||
*/
|
||||
void startAgent();
|
||||
void startServer();
|
||||
|
||||
/**
|
||||
* @brief Initiates the reading process from the TCP connection's socket.
|
||||
*/
|
||||
void doReadAgent();
|
||||
void doReadServer();
|
||||
void handleReadAgent(const boost::system::error_code &error, size_t bytes_transferred);
|
||||
void handleReadServer(const boost::system::error_code &error, size_t bytes_transferred);
|
||||
|
||||
/**
|
||||
* @brief Handles the completion of a read operation from the TCP connection's socket.
|
||||
*
|
||||
* @param error The error code indicating the result of the read operation.
|
||||
* @param bytes_transferred The number of bytes read from the socket.
|
||||
*/
|
||||
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 Reads the remaining data from the TCP connection after the initial read.
|
||||
*/
|
||||
void doReadRest();
|
||||
|
||||
/**
|
||||
* @brief Initiates the writing process to the TCP connection's socket.
|
||||
*
|
||||
* @param handlerPointer A pointer to the handler for the write operation.
|
||||
*/
|
||||
void doWrite(auto handlerPointer);
|
||||
|
||||
/**
|
||||
* @brief Shuts down the TCP connection's socket and closes the connection.
|
||||
*/
|
||||
void socketShutdown();
|
||||
|
||||
void enableDirectTunnelMode();
|
||||
|
||||
void relayClientToServer();
|
||||
void relayServerToClient();
|
||||
|
||||
void relayAgentToTarget();
|
||||
void relayTargetToAgent();
|
||||
|
||||
std::mutex relayMutex_;
|
||||
|
||||
inline void asyncWriteToAgentConnection(
|
||||
const char *data,
|
||||
std::size_t bytes,
|
||||
std::function<void(const boost::system::error_code &)> done);
|
||||
|
||||
inline void asyncReadFromAgentConnection(
|
||||
std::array<char, BufferSize> &buffer,
|
||||
std::function<void(const boost::system::error_code &, std::size_t)> done);
|
||||
|
||||
inline void asyncWriteToAgentServerConnection(
|
||||
const char *data,
|
||||
std::size_t bytes,
|
||||
std::function<void(const boost::system::error_code &)> done);
|
||||
|
||||
inline void asyncReadFromAgentServerConnection(
|
||||
std::array<char, BufferSize> &buffer,
|
||||
std::function<void(const boost::system::error_code &, std::size_t)> done);
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Constructs a new TCPConnection instance with the provided context, configuration, log, and client.
|
||||
*
|
||||
* @param io_context The IO context for asynchronous operations.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
* @param client Shared pointer to the associated 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 Resets the timeout timer for the TCP connection.
|
||||
*/
|
||||
bool handleSocks5Handshake();
|
||||
bool readExactFromClient(void *data, std::size_t size);
|
||||
|
||||
void resetTimeout();
|
||||
|
||||
/**
|
||||
* @brief Cancels the timeout timer for the TCP connection.
|
||||
*/
|
||||
void cancelTimeout();
|
||||
|
||||
/**
|
||||
* @brief Handles the timeout event for the TCP connection.
|
||||
*
|
||||
* @param error The error code indicating the result of the timeout event.
|
||||
*/
|
||||
void onTimeout(const boost::system::error_code &error);
|
||||
|
||||
void startTunnelReadFromClient();
|
||||
void startTunnelPollServer();
|
||||
std::string postTunnelAction(const std::string &action, const std::string &rawBody);
|
||||
std::string makeRelayHostHeader() const;
|
||||
void closeTunnelSession();
|
||||
|
||||
boost::asio::ip::tcp::socket socket_;
|
||||
const std::shared_ptr<Config> &config_;
|
||||
const std::shared_ptr<Log> &log_;
|
||||
boost::asio::ssl::context sslContext_;
|
||||
std::unique_ptr<ssl_stream> tlsSocket_;
|
||||
|
||||
std::shared_ptr<Config> config_;
|
||||
std::shared_ptr<Log> log_;
|
||||
boost::asio::io_context &io_context_;
|
||||
TCPClient::pointer client_;
|
||||
boost::asio::streambuf readBuffer_, writeBuffer_;
|
||||
boost::asio::deadline_timer timeout_;
|
||||
|
||||
boost::asio::streambuf readBuffer_;
|
||||
boost::asio::streambuf writeBuffer_;
|
||||
|
||||
boost::asio::steady_timer timeout_;
|
||||
boost::asio::steady_timer pollTimer_;
|
||||
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
|
||||
|
||||
boost::uuids::uuid uuid_;
|
||||
std::mutex mutex_;
|
||||
bool end_, connect_;
|
||||
};
|
||||
|
||||
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_;
|
||||
};
|
||||
+40
-45
@@ -1,15 +1,8 @@
|
||||
#include "tcpserver.hpp"
|
||||
|
||||
/**
|
||||
* @brief Constructs a new TCPServer instance.
|
||||
*
|
||||
* Initializes the `acceptor_` with the specified IP and port from the configuration, and sets the `reuse_address` option
|
||||
* to allow multiple bindings to the same address. This constructor also starts the process of accepting connections.
|
||||
*
|
||||
* @param io_context The IO context for asynchronous operations.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
*/
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
|
||||
TCPServer::TCPServer(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log)
|
||||
@@ -17,22 +10,15 @@ TCPServer::TCPServer(boost::asio::io_context &io_context,
|
||||
log_(log),
|
||||
io_context_(io_context),
|
||||
acceptor_(io_context,
|
||||
boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(config->listenIp()),
|
||||
config->listenPort())) {
|
||||
boost::asio::ip::tcp::endpoint(
|
||||
boost::asio::ip::make_address(config->listenIp()),
|
||||
config->listenPort())) {
|
||||
acceptor_.set_option(boost::asio::socket_base::reuse_address(true));
|
||||
|
||||
startAccept();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Starts accepting incoming client connections asynchronously.
|
||||
*
|
||||
* This method creates a new `TCPClient` and `TCPConnection` object to handle the connection, then starts the asynchronous
|
||||
* accept operation using the acceptor. Once a connection is accepted, the `handleAccept` method will be called.
|
||||
*/
|
||||
void TCPServer::startAccept() {
|
||||
auto client = TCPClient::create(io_context_, config_, log_);
|
||||
|
||||
auto connection = TCPConnection::create(io_context_, config_, log_, client);
|
||||
|
||||
acceptor_.async_accept(
|
||||
@@ -42,34 +28,43 @@ void TCPServer::startAccept() {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Handles the result of the asynchronous accept operation.
|
||||
*
|
||||
* If the connection was successfully accepted, this method starts the communication on the connection by invoking the
|
||||
* `start` method. If an error or exception occurs, it logs the error or exception.
|
||||
*
|
||||
* @param connection The `TCPConnection` object representing the accepted connection.
|
||||
* @param error The error code resulting from the accept operation.
|
||||
*/
|
||||
void TCPServer::handleAccept(TCPConnection::pointer connection,
|
||||
const boost::system::error_code &error) {
|
||||
void TCPServer::handleAccept(
|
||||
TCPConnection::pointer connection,
|
||||
const boost::system::error_code &error) {
|
||||
startAccept();
|
||||
|
||||
try {
|
||||
if (!error) {
|
||||
if (config_->runMode() == RunMode::server)
|
||||
connection->startServer();
|
||||
else
|
||||
connection->startAgent();
|
||||
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);
|
||||
connection->socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
connection->tlsSocket().lowest_layer() = std::move(connection->socket());
|
||||
|
||||
if (!connection->doHandshakeServer()) {
|
||||
log_->write("[TCPServer handleAccept] TLS server handshake failed", Log::Level::ERROR);
|
||||
connection->socketShutdown();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
connection->startServer();
|
||||
} else {
|
||||
log_->write("[TCPServer handleAccept] Error: " + error.message(),
|
||||
Log::Level::ERROR);
|
||||
connection->startAgent();
|
||||
}
|
||||
} catch (const std::exception &ex) {
|
||||
log_->write("[TCPServer handleAccept] Exception: " + std::string(ex.what()),
|
||||
Log::Level::ERROR);
|
||||
log_->write("[TCPServer handleAccept] Exception: " + std::string(ex.what()), Log::Level::ERROR);
|
||||
connection->socketShutdown();
|
||||
} catch (...) {
|
||||
log_->write("[TCPServer handleAccept] Unknown exception",
|
||||
Log::Level::ERROR);
|
||||
log_->write("[TCPServer handleAccept] Unknown exception", Log::Level::ERROR);
|
||||
connection->socketShutdown();
|
||||
}
|
||||
|
||||
startAccept();
|
||||
}
|
||||
}
|
||||
+5
-48
@@ -1,75 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <boost/enable_shared_from_this.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <memory>
|
||||
|
||||
#include "agenthandler.hpp"
|
||||
#include "general.hpp"
|
||||
#include "serverhandler.hpp"
|
||||
#include "tcpconnection.hpp"
|
||||
|
||||
/**
|
||||
* @brief A TCP server class that accepts incoming TCP connections and handles them.
|
||||
*
|
||||
* The class listens for incoming connections and creates `TCPConnection` objects to handle communication.
|
||||
*/
|
||||
class TCPServer {
|
||||
public:
|
||||
using pointer = boost::shared_ptr<TCPServer>;
|
||||
using pointer = std::shared_ptr<TCPServer>;
|
||||
|
||||
/**
|
||||
* @brief Creates a new TCPServer instance.
|
||||
*
|
||||
* This static factory method initializes a `TCPServer` with the provided IO context, configuration, and logging.
|
||||
*
|
||||
* @param io_context The IO context for asynchronous operations.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
*
|
||||
* @return A shared pointer to the newly created TCPServer instance.
|
||||
*/
|
||||
static pointer create(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log) {
|
||||
return pointer(new TCPServer(io_context, config, log));
|
||||
}
|
||||
/**
|
||||
* @brief Starts the process of accepting incoming connections.
|
||||
*
|
||||
* This method begins the asynchronous accept operation to listen for incoming client connections.
|
||||
*/
|
||||
|
||||
void startAccept();
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Constructs a TCPServer object.
|
||||
*
|
||||
* Initializes the acceptor, sets up the IO context, and stores the configuration and log objects.
|
||||
*
|
||||
* @param io_context The IO context for asynchronous operations.
|
||||
* @param config Shared pointer to the configuration object.
|
||||
* @param log Shared pointer to the logging object.
|
||||
*/
|
||||
explicit TCPServer(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log);
|
||||
|
||||
/**
|
||||
* @brief Handles the completion of an accept operation.
|
||||
*
|
||||
* Once a new connection is accepted, this method is called to handle the connection by creating a `TCPConnection`
|
||||
* object and starting communication with the client.
|
||||
*
|
||||
* @param connection A shared pointer to the new `TCPConnection` object.
|
||||
* @param error The error code indicating the result of the accept operation.
|
||||
*/
|
||||
void handleAccept(TCPConnection::pointer connection,
|
||||
const boost::system::error_code &error);
|
||||
|
||||
const std::shared_ptr<Config> &config_;
|
||||
const std::shared_ptr<Log> &log_;
|
||||
std::shared_ptr<Config> config_;
|
||||
std::shared_ptr<Log> log_;
|
||||
boost::asio::io_context &io_context_;
|
||||
boost::asio::ip::tcp::acceptor acceptor_;
|
||||
};
|
||||
@@ -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:
|
||||
@@ -1,3 +0,0 @@
|
||||
theme: jekyll-theme-minimal
|
||||
title: NipoVPN's homepage
|
||||
description: Safe and powerful http proxy
|
||||
@@ -1,74 +0,0 @@
|
||||
body {
|
||||
font-family: 'Karla', sans-serif;
|
||||
background-image: url("../images/bg.jpg");
|
||||
background-size: cover;
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
color: #ffffff;
|
||||
padding-bottom: 75px; }
|
||||
@media (min-width: 768px) {
|
||||
body {
|
||||
padding-bottom: 110px; } }
|
||||
|
||||
.navbar-brand {
|
||||
margin-right: 0; }
|
||||
.navbar-brand img {
|
||||
height: 21px; }
|
||||
|
||||
.navbar-dark {
|
||||
padding-top: 35px;
|
||||
padding-bottom: 35px; }
|
||||
.navbar-dark .navbar-text {
|
||||
color: #ffffff;
|
||||
opacity: 1;
|
||||
padding: 0 20px;
|
||||
border-right: 1px solid #ffffff;
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
text-align: center; }
|
||||
.navbar-dark .navbar-text:last-child {
|
||||
border-right: 0; }
|
||||
@media (max-width: 767px) {
|
||||
.navbar-dark {
|
||||
padding-bottom: 0; } }
|
||||
|
||||
.page-title {
|
||||
font-size: 80px;
|
||||
font-weight: bold;
|
||||
margin-bottom: 6px; }
|
||||
@media (max-width: 767px) {
|
||||
.page-title {
|
||||
font-size: 35px;
|
||||
margin-bottom: 14px; } }
|
||||
|
||||
.page-description {
|
||||
max-width: 465px;
|
||||
font-size: 18px;
|
||||
margin-bottom: 59px; }
|
||||
@media (max-width: 767px) {
|
||||
.page-description {
|
||||
font-size: 14px; } }
|
||||
|
||||
p {
|
||||
font-size: 14px;
|
||||
margin-bottom: 21px; }
|
||||
|
||||
.footer-social-links .social-link {
|
||||
display: inline-block;
|
||||
text-align: center;
|
||||
line-height: 40px;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
background-color: #ffffff;
|
||||
color: #000000;
|
||||
margin-right: 16px;
|
||||
transition: all 0.3s ease-in-out; }
|
||||
.footer-social-links .social-link:last-child {
|
||||
margin-right: 0; }
|
||||
.footer-social-links .social-link:hover {
|
||||
text-decoration: none;
|
||||
background-color: #000000;
|
||||
color: #ffffff; }
|
||||
|
||||
/*# sourceMappingURL=bd-coming-soon.css.map */
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["bd-coming-soon.scss"],"names":[],"mappings":"AAAA;EACI,gCAAgC;EAChC,yCAAyC;EACzC,sBAAsB;EACtB,4BAA4B;EAC5B,2BAA2B;EAC3B,cAAc;EACd,oBAAoB,EAAA;EAEpB;IATJ;MAUQ,qBAAqB,EAAA,EAE5B;;AACD;EACI,eAAe,EAAA;EADnB;IAIQ,YAAY,EAAA;;AAGpB;EACI,iBAAiB;EACjB,oBAAoB,EAAA;EAFxB;IAIQ,cAAc;IACd,UAAU;IACV,eAAe;IACf,+BAA+B;IAC/B,eAAe;IACf,iBAAiB;IACjB,kBAAkB,EAAA;IAV1B;MAaY,eAAe,EAAA;EAIvB;IAjBJ;MAkBQ,iBAAiB,EAAA,EAExB;;AACD;EACI,eAAe;EACf,iBAAiB;EACjB,kBAAkB,EAAA;EAElB;IALJ;MAMQ,eAAe;MACf,mBAAmB,EAAA,EAE1B;;AACD;EACI,gBAAgB;EAChB,eAAe;EACf,mBAAmB,EAAA;EAEnB;IALJ;MAMQ,eAAe,EAAA,EAEtB;;AAED;EACI,eAAe;EACf,mBAAmB,EAAA;;AAGvB;EAEQ,qBAAqB;EACrB,kBAAkB;EAClB,iBAAiB;EACjB,WAAW;EACX,YAAY;EACZ,kBAAkB;EAClB,yBAAyB;EACzB,cAAc;EACd,kBAAkB;EAClB,gCAAgC,EAAA;EAXxC;IAcY,eAAe,EAAA;EAd3B;IAkBY,qBAAqB;IACrB,yBAAyB;IACzB,cAAc,EAAA","file":"bd-coming-soon.css","sourcesContent":["body {\n font-family: 'Karla', sans-serif;\n background-image: url(\"../images/bg.jpg\");\n background-size: cover;\n background-repeat: no-repeat;\n background-position: center;\n color: #ffffff;\n padding-bottom: 75px;\n\n @media (min-width: 768px) {\n padding-bottom: 110px;\n }\n}\n.navbar-brand {\n margin-right: 0;\n\n img {\n height: 21px;\n }\n}\n.navbar-dark {\n padding-top: 35px;\n padding-bottom: 35px;\n .navbar-text {\n color: #ffffff;\n opacity: 1;\n padding: 0 20px;\n border-right: 1px solid #ffffff;\n font-size: 18px;\n font-weight: bold;\n text-align: center;\n\n &:last-child {\n border-right: 0;\n }\n }\n\n @media (max-width: 767px) {\n padding-bottom: 0;\n }\n}\n.page-title {\n font-size: 80px;\n font-weight: bold;\n margin-bottom: 6px;\n\n @media (max-width: 767px) {\n font-size: 35px;\n margin-bottom: 14px; \n }\n}\n.page-description {\n max-width: 465px;\n font-size: 18px;\n margin-bottom: 59px;\n\n @media (max-width: 767px) {\n font-size: 14px; \n }\n}\n\np {\n font-size: 14px;\n margin-bottom: 21px;\n}\n\n.footer-social-links {\n .social-link {\n display: inline-block;\n text-align: center;\n line-height: 40px;\n width: 40px;\n height: 40px;\n border-radius: 50%;\n background-color: #ffffff;\n color: #000000;\n margin-right: 16px;\n transition: all 0.3s ease-in-out;\n\n &:last-child {\n margin-right: 0;\n }\n\n &:hover {\n text-decoration: none;\n background-color: #000000;\n color: #ffffff;\n }\n }\n}"]}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 215 KiB |
@@ -1,3 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="59" height="25" viewBox="0 0 59 25" fill="#FFFFFF">
|
||||
<path d="M4.125,15.3 L10.05,15.3 L10.05,18 L0.6,18 L0.6,0.35 L4.125,0.35 L4.125,15.3 Z M18.55,3.975 C19.9000067,3.975 21.1124946,4.2583305 22.1875,4.825 C23.2625054,5.3916695 24.1083302,6.21249462 24.725,7.2875 C25.3416697,8.36250537 25.65,9.62499275 25.65,11.075 C25.65,12.5250073 25.3416697,13.783328 24.725,14.85 C24.1083302,15.916672 23.2625054,16.7374971 22.1875,17.3125 C21.1124946,17.8875029 19.9000067,18.175 18.55,18.175 C17.1999933,18.175 15.9875054,17.8875029 14.9125,17.3125 C13.8374946,16.7374971 12.9916697,15.916672 12.375,14.85 C11.7583302,13.783328 11.45,12.5250073 11.45,11.075 C11.45,9.62499275 11.7583302,8.36250537 12.375,7.2875 C12.9916697,6.21249462 13.8374946,5.3916695 14.9125,4.825 C15.9875054,4.2583305 17.1999933,3.975 18.55,3.975 Z M18.55,7.025 C17.5666618,7.025 16.7333368,7.37082987 16.05,8.0625 C15.3666633,8.75417013 15.025,9.75832675 15.025,11.075 C15.025,12.3916733 15.3666633,13.3958299 16.05,14.0875 C16.7333368,14.7791701 17.5666618,15.125 18.55,15.125 C19.5333382,15.125 20.3666633,14.7791701 21.05,14.0875 C21.7333367,13.3958299 22.075,12.3916733 22.075,11.075 C22.075,9.75832675 21.7333367,8.75417013 21.05,8.0625 C20.3666633,7.37082987 19.5333382,7.025 18.55,7.025 Z M33.575,3.975 C34.7416725,3.975 35.7416625,4.24999725 36.575,4.8 C37.4083375,5.35000275 37.9999982,6.091662 38.35,7.025 L38.35,4.15 L41.85,4.15 L41.85,18.05 C41.85,19.3333398 41.5958359,20.4874949 41.0875,21.5125 C40.5791641,22.5375051 39.8208384,23.3416638 38.8125,23.925 C37.8041616,24.5083363 36.5833405,24.8 35.15,24.8 C33.14999,24.8 31.5333395,24.3250048 30.3,23.375 C29.0666605,22.4249953 28.316668,21.1333415 28.05,19.5 L31.525,19.5 C31.725001,20.2000035 32.1124971,20.7458314 32.6875,21.1375 C33.2625029,21.5291686 33.9999955,21.725 34.9,21.725 C35.9333385,21.725 36.7666635,21.4208364 37.4,20.8125 C38.0333365,20.2041636 38.35,19.2833395 38.35,18.05 L38.35,15.1 C37.9999982,16.033338 37.4083375,16.7791639 36.575,17.3375 C35.7416625,17.8958361 34.7416725,18.175 33.575,18.175 C32.4083275,18.175 31.358338,17.8916695 30.425,17.325 C29.491662,16.7583305 28.7625026,15.9375054 28.2375,14.8625 C27.7124974,13.7874946 27.45,12.5250073 27.45,11.075 C27.45,9.62499275 27.7124974,8.36250537 28.2375,7.2875 C28.7625026,6.21249462 29.491662,5.3916695 30.425,4.825 C31.358338,4.2583305 32.4083275,3.975 33.575,3.975 Z M34.675,7.05 C33.5749945,7.05 32.69167,7.40832975 32.025,8.125 C31.35833,8.84167025 31.025,9.82499375 31.025,11.075 C31.025,12.3250063 31.35833,13.3041631 32.025,14.0125 C32.69167,14.7208369 33.5749945,15.075 34.675,15.075 C35.741672,15.075 36.6208299,14.7125036 37.3125,13.9875 C38.0041701,13.2624964 38.35,12.2916728 38.35,11.075 C38.35,9.8416605 38.0041701,8.86250363 37.3125,8.1375 C36.6208299,7.41249637 35.741672,7.05 34.675,7.05 Z M51.45,3.975 C52.8000068,3.975 54.0124946,4.2583305 55.0875,4.825 C56.1625054,5.3916695 57.0083302,6.21249462 57.625,7.2875 C58.2416697,8.36250537 58.55,9.62499275 58.55,11.075 C58.55,12.5250073 58.2416697,13.783328 57.625,14.85 C57.0083302,15.916672 56.1625054,16.7374971 55.0875,17.3125 C54.0124946,17.8875029 52.8000068,18.175 51.45,18.175 C50.0999933,18.175 48.8875054,17.8875029 47.8125,17.3125 C46.7374946,16.7374971 45.8916698,15.916672 45.275,14.85 C44.6583303,13.783328 44.35,12.5250073 44.35,11.075 C44.35,9.62499275 44.6583303,8.36250537 45.275,7.2875 C45.8916698,6.21249462 46.7374946,5.3916695 47.8125,4.825 C48.8875054,4.2583305 50.0999933,3.975 51.45,3.975 Z M51.45,7.025 C50.4666618,7.025 49.6333367,7.37082987 48.95,8.0625 C48.2666633,8.75417013 47.925,9.75832675 47.925,11.075 C47.925,12.3916733 48.2666633,13.3958299 48.95,14.0875 C49.6333367,14.7791701 50.4666618,15.125 51.45,15.125 C52.4333383,15.125 53.2666633,14.7791701 53.95,14.0875 C54.6333367,13.3958299 54.975,12.3916733 54.975,11.075 C54.975,9.75832675 54.6333367,8.75417013 53.95,8.0625 C53.2666633,7.37082987 52.4333383,7.025 51.45,7.025 Z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 3.9 KiB |
@@ -1,90 +0,0 @@
|
||||
body {
|
||||
font-family: 'Karla', sans-serif;
|
||||
background-image: url("../images/bg.jpg");
|
||||
background-size: cover;
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
color: #ffffff;
|
||||
padding-bottom: 75px;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
padding-bottom: 110px;
|
||||
}
|
||||
}
|
||||
.navbar-brand {
|
||||
margin-right: 0;
|
||||
|
||||
img {
|
||||
height: 21px;
|
||||
}
|
||||
}
|
||||
.navbar-dark {
|
||||
padding-top: 35px;
|
||||
padding-bottom: 35px;
|
||||
.navbar-text {
|
||||
color: #ffffff;
|
||||
opacity: 1;
|
||||
padding: 0 20px;
|
||||
border-right: 1px solid #ffffff;
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
text-align: center;
|
||||
|
||||
&:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
padding-bottom: 0;
|
||||
}
|
||||
}
|
||||
.page-title {
|
||||
font-size: 80px;
|
||||
font-weight: bold;
|
||||
margin-bottom: 6px;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
font-size: 35px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
}
|
||||
.page-description {
|
||||
max-width: 465px;
|
||||
font-size: 18px;
|
||||
margin-bottom: 59px;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 14px;
|
||||
margin-bottom: 21px;
|
||||
}
|
||||
|
||||
.footer-social-links {
|
||||
.social-link {
|
||||
display: inline-block;
|
||||
text-align: center;
|
||||
line-height: 40px;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
background-color: #ffffff;
|
||||
color: #000000;
|
||||
margin-right: 16px;
|
||||
transition: all 0.3s ease-in-out;
|
||||
|
||||
&:last-child {
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
text-decoration: none;
|
||||
background-color: #000000;
|
||||
color: #ffffff;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
//Import
|
||||
|
||||
const gulp = require('gulp');
|
||||
const sass = require('gulp-sass');
|
||||
const sourceMaps = require('gulp-sourcemaps');
|
||||
const autoprefixer = require('gulp-autoprefixer');
|
||||
const browserSync = require('browser-sync');
|
||||
|
||||
//SCSS
|
||||
|
||||
function style() {
|
||||
return gulp.src('./assets/scss/*.scss')
|
||||
.pipe(sourceMaps.init())
|
||||
.pipe(sass().on('error', sass.logError))
|
||||
.pipe(autoprefixer())
|
||||
.pipe(sourceMaps.write('./'))
|
||||
.pipe(gulp.dest('./assets/css'))
|
||||
.pipe(browserSync.stream());
|
||||
}
|
||||
|
||||
//Serve and watch
|
||||
|
||||
function watch() {
|
||||
browserSync.init({
|
||||
server: {
|
||||
baseDir: './',
|
||||
},
|
||||
startPath: './index.html',
|
||||
ghostMode: false,
|
||||
notify: false
|
||||
});
|
||||
gulp.watch('./assets/scss/*.scss', style);
|
||||
gulp.watch('./*.html').on('change', browserSync.reload);
|
||||
gulp.watch('./assets/js/*.js').on('change', browserSync.reload);
|
||||
|
||||
}
|
||||
|
||||
exports.style = style;
|
||||
exports.watch = watch;
|
||||
@@ -1,45 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="X-UA-Compatible" content="ie=edge">
|
||||
<title>NipoVPN documentation</title>
|
||||
<link href="https://fonts.googleapis.com/css?family=Karla:400,700&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="https://cdn.materialdesignicons.com/4.8.95/css/materialdesignicons.min.css">
|
||||
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
|
||||
<link rel="stylesheet" href="assets/css/bd-coming-soon.css">
|
||||
</head>
|
||||
|
||||
<body class="min-vh-100 d-flex flex-column">
|
||||
|
||||
<header>
|
||||
<div class="container">
|
||||
<nav class="navbar navbar-dark bg-transparenet">
|
||||
<a class="navbar-brand" href="#">
|
||||
<img src="assets/images/logo.svg" alt="logo">
|
||||
</a>
|
||||
<span class="navbar-text ml-auto d-none d-sm-inline-block">Email</span>
|
||||
<span class="navbar-text d-none d-sm-inline-block">morteza.bashsiz@gmail.com</span>
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
<main class="my-auto">
|
||||
<div class="container">
|
||||
<h1 class="page-title">We're coming soon</h1>
|
||||
<p class="page-description">We are working hard to make it possible
|
||||
</p>
|
||||
<p>Stay connected</p>
|
||||
<!-- <nav class="footer-social-links">
|
||||
<a href="#!" class="social-link"><i class="mdi mdi-facebook-box"></i></a>
|
||||
<a href="#!" class="social-link"><i class="mdi mdi-twitter"></i></a>
|
||||
<a href="#!" class="social-link"><i class="mdi mdi-google"></i></a>
|
||||
<a href="#!" class="social-link"><i class="mdi mdi-slack"></i></a>
|
||||
<a href="#!" class="social-link"><i class="mdi mdi-skype"></i></a>
|
||||
</nav> -->
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
Generated
-4995
File diff suppressed because it is too large.
Load diff
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"name": "bd-wizard-free-1",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"browser-sync": "^3.0.2",
|
||||
"gulp": "^5.0.0",
|
||||
"gulp-autoprefixer": "^7.0.1",
|
||||
"gulp-sass": "^5.1.0",
|
||||
"gulp-sourcemaps": "^2.6.5",
|
||||
"node-sass": "^9.0.0"
|
||||
}
|
||||
}
|
||||
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)"
|
||||
'';
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
C++20 or higher
|
||||
libyaml-cpp >= 0.8
|
||||
boost-libs >= 1.83.0
|
||||
boost-libs >= 1.88.0
|
||||
OpenSSL
|
||||
|
||||
### Dependencies
|
||||
|
||||
@@ -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,35 +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://www.adas.com/api01"
|
||||
# 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"
|
||||
# timeWait: unsigned int(0-4,294,967,295)
|
||||
# Defines the time wait between each repeat to read from socket.
|
||||
# This directive will be useful when you expect to read very long stream from socket
|
||||
timeWait: 50
|
||||
# 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
|
||||
# repeatWait: unsigned short(1-65,635)
|
||||
# Defines the loop count which will try to repeat read from socket.
|
||||
# Same as timeWait
|
||||
repeatWait: 5
|
||||
# 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: "TRACE"
|
||||
logLevel: "INFO"
|
||||
# logFile: "/var/log/nipo/nipo.log"
|
||||
# Path of log file
|
||||
logFile: "/var/log/nipovpn/nipovpn.log"
|
||||
@@ -37,12 +81,13 @@ 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
|
||||
|
||||
|
||||
# This block is to define agent directives
|
||||
agent:
|
||||
# threads: number of threads in agent
|
||||
@@ -58,4 +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"
|
||||
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.
Executable
+95
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
sys.exit("PyYAML is required: pip install pyyaml (or install python-yaml)")
|
||||
|
||||
DEFAULT_CONFIG = "/etc/nipovpn/config.yaml"
|
||||
|
||||
|
||||
def to_str(value):
|
||||
return "" if value is None else str(value)
|
||||
|
||||
|
||||
def to_lines(value):
|
||||
if isinstance(value, (list, tuple)):
|
||||
return "\n".join(str(v) for v in value)
|
||||
return to_str(value)
|
||||
|
||||
|
||||
def build_payload(cfg, name=None, server_ip=None):
|
||||
general = cfg.get("general", {}) or {}
|
||||
log = cfg.get("log", {}) or {}
|
||||
agent = cfg.get("agent", {}) or {}
|
||||
|
||||
server_ip = server_ip or to_str(agent.get("serverIp"))
|
||||
config = {
|
||||
"token": to_str(general.get("token")),
|
||||
"protocol": to_str(general.get("protocol")),
|
||||
"fakeUrls": to_lines(general.get("fakeUrls")),
|
||||
"methods": to_lines(general.get("methods")),
|
||||
"endPoints": to_lines(general.get("endPoints")),
|
||||
"timeout": to_str(general.get("timeout")),
|
||||
"pullTimeout": to_str(general.get("pullTimeout")),
|
||||
"tunnelEnable": bool(general.get("tunnelEnable", False)),
|
||||
"connectionReuse": bool(general.get("connectionReuse", False)),
|
||||
"tlsEnable": bool(general.get("tlsEnable", False)),
|
||||
"tlsVerifyPeer": bool(general.get("tlsVerifyPeer", False)),
|
||||
"tlsCertFile": to_str(general.get("tlsCertFile")),
|
||||
"tlsKeyFile": to_str(general.get("tlsKeyFile")),
|
||||
"tlsCaFile": to_str(general.get("tlsCaFile")),
|
||||
"logLevel": to_str(log.get("logLevel")),
|
||||
"listenIp": to_str(agent.get("listenIp")),
|
||||
"listenPort": to_str(agent.get("listenPort")),
|
||||
"serverIp": server_ip,
|
||||
"serverPort": to_str(agent.get("serverPort")),
|
||||
"httpVersion": to_str(agent.get("httpVersion")),
|
||||
"userAgent": to_str(agent.get("userAgent")),
|
||||
}
|
||||
return {"name": name or server_ip, "config": config}
|
||||
|
||||
|
||||
def encode(payload):
|
||||
text = json.dumps(payload, separators=(",", ":"), ensure_ascii=False)
|
||||
text = text.replace("/", "\\/")
|
||||
return "nipovpn://" + base64.b64encode(text.encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
def decode(url):
|
||||
data = url.strip()
|
||||
if data.startswith("nipovpn://"):
|
||||
data = data[len("nipovpn://"):]
|
||||
data += "=" * (-len(data) % 4)
|
||||
return json.loads(base64.b64decode(data).decode("utf-8"))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Convert nipovpn config.yaml to a nipovpn:// URL")
|
||||
parser.add_argument("config", nargs="?", default=DEFAULT_CONFIG,
|
||||
help=f"path to config.yaml (default: {DEFAULT_CONFIG})")
|
||||
parser.add_argument("--name", help="profile name (default: serverIp)")
|
||||
parser.add_argument("--server-ip", help="override agent.serverIp (e.g. the public IP of the server)")
|
||||
parser.add_argument("--decode", metavar="URL", help="decode a nipovpn:// URL and print its JSON")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.decode:
|
||||
print(json.dumps(decode(args.decode), indent=2, ensure_ascii=False))
|
||||
return
|
||||
|
||||
try:
|
||||
with open(args.config, "r", encoding="utf-8") as f:
|
||||
cfg = yaml.safe_load(f) or {}
|
||||
except OSError as e:
|
||||
sys.exit(f"Cannot read {args.config}: {e}")
|
||||
|
||||
print(encode(build_payload(cfg, args.name, args.server_ip)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user