Compare commits
174
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
a539bc3dc8 | ||
|
|
974e5f39a5 | ||
|
|
2e0730061f | ||
|
|
1465d9f5fd | ||
|
|
1702883c11 | ||
|
|
c03ed2fd28 | ||
|
|
06041b4b90 | ||
|
|
4dbcf60393 | ||
|
|
d1e5ec22ad |
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.59
|
||||
|
||||
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,317 @@ 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: Install Android NDK r29
|
||||
run: |
|
||||
mkdir -p "$HOME/lib"
|
||||
cd "$HOME/lib"
|
||||
|
||||
wget -q https://dl.google.com/android/repository/android-ndk-r29-linux.zip
|
||||
unzip -q android-ndk-r29-linux.zip
|
||||
|
||||
EXTRACTED_DIR="$(find "$HOME/lib" -maxdepth 1 -type d -name 'android-ndk-r29*' | head -n 1)"
|
||||
|
||||
if [ -z "$EXTRACTED_DIR" ]; then
|
||||
echo "Android NDK r29 directory not found"
|
||||
ls -lah "$HOME/lib"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
ln -sfn "$EXTRACTED_DIR" "$HOME/lib/android-ndk-r29"
|
||||
|
||||
echo "NDK=$HOME/lib/android-ndk-r29" >> "$GITHUB_ENV"
|
||||
echo "ANDROID_NDK_ROOT=$HOME/lib/android-ndk-r29" >> "$GITHUB_ENV"
|
||||
|
||||
ls -ld "$HOME/lib/android-ndk-r29"
|
||||
|
||||
- name: Clone termux-packages
|
||||
run: |
|
||||
git clone --depth=1 https://github.com/termux/termux-packages.git
|
||||
|
||||
- name: Create Termux package recipe
|
||||
run: |
|
||||
mkdir -p termux-packages/packages/nipovpn
|
||||
|
||||
cat > termux-packages/packages/nipovpn/build.sh <<'EOF'
|
||||
TERMUX_PKG_HOMEPAGE=https://github.com/MortezaBashsiz/nipovpn
|
||||
TERMUX_PKG_DESCRIPTION="Powerful and secure HTTP/S proxy"
|
||||
TERMUX_PKG_LICENSE="MIT"
|
||||
TERMUX_PKG_MAINTAINER="Morteza Bashsiz"
|
||||
TERMUX_PKG_VERSION=@PACKAGE_VERSION@
|
||||
TERMUX_PKG_SRCURL=file://@GITHUB_WORKSPACE@/nipovpn-src
|
||||
TERMUX_PKG_SHA256=SKIP_CHECKSUM
|
||||
TERMUX_PKG_DEPENDS="openssl, boost, libyaml-cpp"
|
||||
TERMUX_PKG_BUILD_IN_SRC=false
|
||||
|
||||
termux_step_configure() {
|
||||
cmake -S "$TERMUX_PKG_SRCDIR" \
|
||||
-B "$TERMUX_PKG_BUILDDIR" \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_INSTALL_PREFIX="$TERMUX_PREFIX"
|
||||
}
|
||||
|
||||
termux_step_make() {
|
||||
cmake --build "$TERMUX_PKG_BUILDDIR" -j "$(nproc)"
|
||||
}
|
||||
|
||||
termux_step_make_install() {
|
||||
install -Dm755 \
|
||||
"$TERMUX_PKG_BUILDDIR/core/nipovpn" \
|
||||
"$TERMUX_PREFIX/bin/nipovpn"
|
||||
|
||||
if [ -d "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn" ]; then
|
||||
mkdir -p "$TERMUX_PREFIX/etc/nipovpn"
|
||||
cp -a "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn/." \
|
||||
"$TERMUX_PREFIX/etc/nipovpn/"
|
||||
fi
|
||||
}
|
||||
EOF
|
||||
|
||||
sed -i "s|@PACKAGE_VERSION@|${PACKAGE_VERSION}|g" termux-packages/packages/nipovpn/build.sh
|
||||
sed -i "s|@GITHUB_WORKSPACE@|${GITHUB_WORKSPACE}|g" termux-packages/packages/nipovpn/build.sh
|
||||
|
||||
cat termux-packages/packages/nipovpn/build.sh
|
||||
|
||||
- name: Prepare Termux build data dir
|
||||
run: |
|
||||
sudo mkdir -p /data
|
||||
sudo chown -R $USER:$USER /data
|
||||
|
||||
- name: Build Termux aarch64 package
|
||||
working-directory: termux-packages
|
||||
run: |
|
||||
./build-package.sh -I -a aarch64 nipovpn
|
||||
|
||||
- name: Collect Termux package
|
||||
run: |
|
||||
mkdir -p out
|
||||
|
||||
TERMUX_DEB="$(find termux-packages/output -type f -name '*.deb' | head -n 1)"
|
||||
|
||||
if [ -z "$TERMUX_DEB" ]; then
|
||||
echo "No Termux .deb package found"
|
||||
find termux-packages/output -type f || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cp "$TERMUX_DEB" "out/nipovpn_dev_${PACKAGE_VERSION}_termux_aarch64.deb"
|
||||
|
||||
ls -lah out/
|
||||
|
||||
- name: Upload Termux package artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: nipovpn-dev-termux-aarch64
|
||||
path: out/nipovpn_dev_${{ env.PACKAGE_VERSION }}_termux_aarch64.deb
|
||||
|
||||
release:
|
||||
needs: build
|
||||
needs:
|
||||
- build
|
||||
- build-termux
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Download build artifact
|
||||
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,322 @@
|
||||
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.59
|
||||
|
||||
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: Install Android NDK r29
|
||||
run: |
|
||||
mkdir -p "$HOME/lib"
|
||||
cd "$HOME/lib"
|
||||
|
||||
wget -q https://dl.google.com/android/repository/android-ndk-r29-linux.zip
|
||||
unzip -q android-ndk-r29-linux.zip
|
||||
|
||||
EXTRACTED_DIR="$(find "$HOME/lib" -maxdepth 1 -type d -name 'android-ndk-r29*' | head -n 1)"
|
||||
|
||||
if [ -z "$EXTRACTED_DIR" ]; then
|
||||
echo "Android NDK r29 directory not found"
|
||||
ls -lah "$HOME/lib"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
ln -sfn "$EXTRACTED_DIR" "$HOME/lib/android-ndk-r29"
|
||||
|
||||
echo "NDK=$HOME/lib/android-ndk-r29" >> "$GITHUB_ENV"
|
||||
echo "ANDROID_NDK_ROOT=$HOME/lib/android-ndk-r29" >> "$GITHUB_ENV"
|
||||
|
||||
ls -ld "$HOME/lib/android-ndk-r29"
|
||||
|
||||
- name: Clone termux-packages
|
||||
run: |
|
||||
git clone --depth=1 https://github.com/termux/termux-packages.git
|
||||
|
||||
- name: Create Termux package recipe
|
||||
run: |
|
||||
mkdir -p termux-packages/packages/nipovpn
|
||||
|
||||
cat > termux-packages/packages/nipovpn/build.sh <<'EOF'
|
||||
TERMUX_PKG_HOMEPAGE=https://github.com/MortezaBashsiz/nipovpn
|
||||
TERMUX_PKG_DESCRIPTION="Powerful and secure HTTP/S proxy"
|
||||
TERMUX_PKG_LICENSE="MIT"
|
||||
TERMUX_PKG_MAINTAINER="Morteza Bashsiz"
|
||||
TERMUX_PKG_VERSION=@PACKAGE_VERSION@
|
||||
TERMUX_PKG_SRCURL=file://@GITHUB_WORKSPACE@/nipovpn-src
|
||||
TERMUX_PKG_SHA256=SKIP_CHECKSUM
|
||||
TERMUX_PKG_DEPENDS="openssl, boost, libyaml-cpp"
|
||||
TERMUX_PKG_BUILD_IN_SRC=false
|
||||
|
||||
termux_step_configure() {
|
||||
cmake -S "$TERMUX_PKG_SRCDIR" \
|
||||
-B "$TERMUX_PKG_BUILDDIR" \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_INSTALL_PREFIX="$TERMUX_PREFIX"
|
||||
}
|
||||
|
||||
termux_step_make() {
|
||||
cmake --build "$TERMUX_PKG_BUILDDIR" -j "$(nproc)"
|
||||
}
|
||||
|
||||
termux_step_make_install() {
|
||||
install -Dm755 \
|
||||
"$TERMUX_PKG_BUILDDIR/core/nipovpn" \
|
||||
"$TERMUX_PREFIX/bin/nipovpn"
|
||||
|
||||
if [ -d "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn" ]; then
|
||||
mkdir -p "$TERMUX_PREFIX/etc/nipovpn"
|
||||
cp -a "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn/." \
|
||||
"$TERMUX_PREFIX/etc/nipovpn/"
|
||||
fi
|
||||
}
|
||||
EOF
|
||||
|
||||
sed -i "s|@PACKAGE_VERSION@|${PACKAGE_VERSION}|g" termux-packages/packages/nipovpn/build.sh
|
||||
sed -i "s|@GITHUB_WORKSPACE@|${GITHUB_WORKSPACE}|g" termux-packages/packages/nipovpn/build.sh
|
||||
|
||||
cat termux-packages/packages/nipovpn/build.sh
|
||||
|
||||
- name: Prepare Termux build data dir
|
||||
run: |
|
||||
sudo mkdir -p /data
|
||||
sudo chown -R $USER:$USER /data
|
||||
|
||||
- name: Build Termux aarch64 package
|
||||
working-directory: termux-packages
|
||||
run: |
|
||||
./build-package.sh -I -a aarch64 nipovpn
|
||||
|
||||
- name: Collect Termux package
|
||||
run: |
|
||||
mkdir -p out
|
||||
|
||||
TERMUX_DEB="$(find termux-packages/output -type f -name '*.deb' | head -n 1)"
|
||||
|
||||
if [ -z "$TERMUX_DEB" ]; then
|
||||
echo "No Termux .deb package found"
|
||||
find termux-packages/output -type f || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cp "$TERMUX_DEB" "out/nipovpn_${PACKAGE_VERSION}_termux_aarch64.deb"
|
||||
|
||||
ls -lah out/
|
||||
|
||||
- name: Upload Termux package artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: nipovpn-termux-aarch64
|
||||
path: out/nipovpn_${{ env.PACKAGE_VERSION }}_termux_aarch64.deb
|
||||
|
||||
release:
|
||||
needs:
|
||||
- build
|
||||
- build-termux
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Download package artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: nipovpn-*
|
||||
merge-multiple: true
|
||||
path: ./
|
||||
|
||||
- name: Show downloaded files
|
||||
run: |
|
||||
ls -lah
|
||||
|
||||
- name: Create 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.59
|
||||
|
||||
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,4 +1,4 @@
|
||||
# NipoVPN (Not ready yet :D)
|
||||
# NipoVPN
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -10,110 +10,89 @@ NipoVPN is a powerful proxy tool designed to conceal your HTTP requests within f
|
||||
- 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.
|
||||
- Support HTTP and SOCKS5 on agent side
|
||||
- Ability to use multiple Agents for one Server
|
||||
|
||||
|
||||
## Usecases
|
||||
|
||||
### Bypass filtering
|
||||
|
||||
This could help you to bypass the filtering in your country.
|
||||
|
||||

|
||||
|
||||
### Hide your requests in the Internet
|
||||
|
||||
If you want to hide your HTTP requests in the Internet, this proxy could help you.
|
||||
|
||||

|
||||
|
||||
## Flow
|
||||
|
||||
Here you can see the logical flow of a single request from first step to get the response
|
||||

|
||||
|
||||
|
||||
## Contribution
|
||||
|
||||
To contribute take a look at [contribution page](https://github.com/MortezaBashsiz/nipovpn/blob/main/CONTRIBUTING.md).
|
||||
|
||||
## Build
|
||||
|
||||
Build from source for [Linux](guides/BuildLinux.md)
|
||||
|
||||
## Docker
|
||||
|
||||
For running it with docker [Docker Guide](guides/Docker.md).
|
||||
|
||||
## Termux
|
||||
|
||||
Build from source for [Termux](guides/InstallTermux.md)
|
||||
|
||||
## Android Application
|
||||
|
||||
Official Android application [Android](https://github.com/MortezaBashsiz/nipovpn-android)
|
||||
|
||||
## Nix
|
||||
|
||||
For development, building, installation, and NixOS integration, see the [Nix Guide](guides/Nix.md).
|
||||
|
||||
## 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()
|
||||
+130
-163
@@ -1,19 +1,22 @@
|
||||
#include "agenthandler.hpp"
|
||||
|
||||
#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;
|
||||
@@ -22,175 +25,139 @@ AgentHandler::AgentHandler(boost::asio::streambuf &readBuffer,
|
||||
AgentHandler::~AgentHandler() {}
|
||||
|
||||
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_->doHandle();
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
BoolStr encryption{false, std::string("FAILED")};
|
||||
encryption = aes256Encrypt(hexStreambufToStr(readBuffer_), config_->general().token);
|
||||
if (!encryption.ok) {
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Encryption Failed] : [ " +
|
||||
encryption.message + "] ",
|
||||
Log::Level::DEBUG);
|
||||
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;
|
||||
}
|
||||
|
||||
const std::string innerRequest = encode64(encryption.message);
|
||||
const std::string action =
|
||||
request_->httpType() == HTTP::HttpType::connect ? "open" : "request";
|
||||
|
||||
std::ostringstream outer;
|
||||
const bool directTunnelOpen =
|
||||
config_->general().tunnelEnable &&
|
||||
request_->httpType() == HTTP::HttpType::connect;
|
||||
|
||||
outer << config_->randomMethod() + " /" + config_->randomEndPoint() + " HTTP/" << config_->agent().httpVersion << "\r\n"
|
||||
<< "Host: " << relayHostHeader(config_) << "\r\n"
|
||||
<< "User-Agent: " << config_->agent().userAgent << "\r\n"
|
||||
<< "Accept: */*\r\n"
|
||||
<< "Content-Type: application/text\r\n"
|
||||
<< "X-Nipo-Session: " << to_string(uuid_) << "\r\n"
|
||||
<< "X-Nipo-Action: " << action << "\r\n"
|
||||
<< "Content-Length: " << innerRequest.size() << "\r\n"
|
||||
<< "Connection: "
|
||||
<< ((config_->general().connectionReuse || directTunnelOpen) ? "keep-alive" : "close")
|
||||
<< "\r\n"
|
||||
<< "\r\n"
|
||||
<< innerRequest;
|
||||
|
||||
copyStringToStreambuf(outer.str(), readBuffer_);
|
||||
|
||||
client_->doWrite(readBuffer_);
|
||||
client_->doReadAgent();
|
||||
|
||||
if (client_->readBuffer().size() == 0 && !config_->general().connectionReuse) {
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string outerResponse = streambufToString(client_->readBuffer());
|
||||
const auto bodyPos = outerResponse.find("\r\n\r\n");
|
||||
if (bodyPos == std::string::npos) {
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [NOT HTTP Response] [Response] : " +
|
||||
outerResponse,
|
||||
Log::Level::DEBUG);
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string encryptedBody = outerResponse.substr(bodyPos + 4);
|
||||
if (encryptedBody.empty()) {
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
BoolStr decryption{false, std::string("FAILED")};
|
||||
decryption = aes256Decrypt(encryptedBody, config_->general().token);
|
||||
if (!decryption.ok) {
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Decryption Failed] : [ " +
|
||||
decryption.message + "] ",
|
||||
Log::Level::DEBUG);
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
copyStringToStreambuf(decryption.message, writeBuffer_);
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Decryption Done]",
|
||||
Log::Level::DEBUG);
|
||||
|
||||
connect_ = request_->httpType() == HTTP::HttpType::connect;
|
||||
end_ = false;
|
||||
}
|
||||
|
||||
void AgentHandler::continueRead() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::string newReq(
|
||||
request_->genHttpRestPostReqString());
|
||||
copyStringToStreambuf(newReq, readBuffer_);
|
||||
client_->doWrite(readBuffer_);
|
||||
client_->doHandle();
|
||||
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();
|
||||
return;
|
||||
}
|
||||
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;
|
||||
}
|
||||
+16
-18
@@ -9,17 +9,17 @@
|
||||
#include "log.hpp"
|
||||
#include "tcpclient.hpp"
|
||||
|
||||
|
||||
class AgentHandler : private Uncopyable {
|
||||
public:
|
||||
using pointer = std::shared_ptr<AgentHandler>;
|
||||
|
||||
|
||||
static pointer create(boost::asio::streambuf &readBuffer,
|
||||
boost::asio::streambuf &writeBuffer,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
const TCPClient::pointer &client,
|
||||
const std::string &clientConnStr,
|
||||
TCPClient::pointer client,
|
||||
std::string clientConnStr,
|
||||
boost::uuids::uuid uuid) {
|
||||
return pointer(new AgentHandler(readBuffer, writeBuffer, config, log,
|
||||
client, clientConnStr, uuid));
|
||||
@@ -28,33 +28,31 @@ public:
|
||||
~AgentHandler();
|
||||
|
||||
void handle();
|
||||
void continueRead();
|
||||
|
||||
inline const HTTP::pointer &request() & { return request_; }
|
||||
inline const HTTP::pointer &request() const { return request_; }
|
||||
|
||||
inline const HTTP::pointer &&request() && { return std::move(request_); }
|
||||
|
||||
bool end_, connect_;
|
||||
bool end_;
|
||||
bool connect_;
|
||||
|
||||
private:
|
||||
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_;
|
||||
const std::shared_ptr<Log> &log_;
|
||||
const TCPClient::pointer &client_;
|
||||
boost::asio::streambuf &readBuffer_,
|
||||
&writeBuffer_;
|
||||
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_;
|
||||
const std::string
|
||||
&clientConnStr_;
|
||||
std::string clientConnStr_;
|
||||
|
||||
boost::uuids::uuid uuid_;
|
||||
|
||||
std::mutex mutex_;
|
||||
};
|
||||
};
|
||||
+137
-30
@@ -1,6 +1,7 @@
|
||||
#include "config.hpp"
|
||||
|
||||
Config::Config(const RunMode &mode, const std::string &filePath)
|
||||
|
||||
Config::Config(RunMode mode, const std::string &filePath)
|
||||
: runMode_(mode),
|
||||
filePath_(filePath),
|
||||
configYaml_(YAML::LoadFile(filePath)),
|
||||
@@ -8,31 +9,42 @@ 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"]["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;
|
||||
@@ -41,38 +53,83 @@ Config::Config(const RunMode &mode, const std::string &filePath)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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;
|
||||
|
||||
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"
|
||||
<< " 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"
|
||||
<< " 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"
|
||||
@@ -80,6 +137,7 @@ std::string Config::toString() const {
|
||||
<< " serverPort: " << agent_.serverPort << "\n"
|
||||
<< " httpVersion: " << agent_.httpVersion << "\n"
|
||||
<< " userAgent: " << agent_.userAgent << "\n";
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
@@ -103,7 +161,7 @@ const Config::Agent &Config::agent() const {
|
||||
return agent_;
|
||||
}
|
||||
|
||||
const unsigned short &Config::threads() const {
|
||||
unsigned short Config::threads() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return threads_;
|
||||
}
|
||||
@@ -123,7 +181,7 @@ void Config::listenIp(const std::string &ip) {
|
||||
listenIp_ = ip;
|
||||
}
|
||||
|
||||
const unsigned short &Config::listenPort() const {
|
||||
unsigned short Config::listenPort() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return listenPort_;
|
||||
}
|
||||
@@ -133,7 +191,7 @@ void Config::listenPort(unsigned short port) {
|
||||
listenPort_ = port;
|
||||
}
|
||||
|
||||
const RunMode &Config::runMode() const {
|
||||
RunMode Config::runMode() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
return runMode_;
|
||||
}
|
||||
@@ -145,6 +203,7 @@ const std::string &Config::filePath() const {
|
||||
|
||||
std::string Config::modeToString() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
|
||||
switch (runMode_) {
|
||||
case RunMode::server:
|
||||
return "server";
|
||||
@@ -154,3 +213,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)];
|
||||
}
|
||||
+46
-15
@@ -4,23 +4,36 @@
|
||||
|
||||
#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 tlsEnable;
|
||||
bool tlsVerifyPeer;
|
||||
std::string tlsCertFile;
|
||||
std::string tlsKeyFile;
|
||||
std::string tlsCaFile;
|
||||
};
|
||||
|
||||
struct Log {
|
||||
@@ -44,21 +57,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>;
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -68,20 +82,37 @@ public:
|
||||
const Agent agent_;
|
||||
|
||||
explicit Config(const Config::pointer &config);
|
||||
|
||||
~Config();
|
||||
|
||||
const General &general() const;
|
||||
const Log &log() const;
|
||||
const Server &server() const;
|
||||
const Agent &agent() const;
|
||||
const unsigned short &threads() const;
|
||||
|
||||
unsigned short threads() const;
|
||||
|
||||
void threads(unsigned short threads);
|
||||
|
||||
const std::string &listenIp() const;
|
||||
|
||||
void listenIp(const std::string &ip);
|
||||
const unsigned short &listenPort() const;
|
||||
|
||||
unsigned short listenPort() const;
|
||||
|
||||
void listenPort(unsigned short port);
|
||||
const RunMode &runMode() const;
|
||||
|
||||
RunMode runMode() const;
|
||||
|
||||
const std::string &filePath() const;
|
||||
|
||||
std::string modeToString() const;
|
||||
|
||||
std::string toString() const;
|
||||
};
|
||||
|
||||
std::string randomFakeUrl() const;
|
||||
|
||||
std::string randomMethod() const;
|
||||
|
||||
std::string randomEndPoint() const;
|
||||
};
|
||||
+58
-37
@@ -19,10 +19,13 @@
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static constexpr std::size_t BufferSize = 65536;
|
||||
|
||||
class Uncopyable {
|
||||
public:
|
||||
Uncopyable() = default;
|
||||
@@ -32,14 +35,14 @@ private:
|
||||
Uncopyable &operator=(const Uncopyable &) = delete;
|
||||
};
|
||||
|
||||
inline void FUCK(const auto &message) {
|
||||
std::cout << "FUCK FUCK FUCK FUCK FUCK FUCK FUCK FUCK : " << message
|
||||
inline void OUT(const auto &message) {
|
||||
std::cout << "OUT OUT OUT OUT OUT OUT OUT OUT : " << message
|
||||
<< std::endl;
|
||||
}
|
||||
|
||||
struct BoolStr {
|
||||
bool ok; ///< Indicates success or failure.
|
||||
std::string message;///< Message describing the result or error.
|
||||
bool ok;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
inline bool fileExists(const std::string &name) {
|
||||
@@ -77,14 +80,16 @@ inline void copyStreambuf(boost::asio::streambuf &source,
|
||||
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();
|
||||
}
|
||||
|
||||
inline unsigned short hexToInt(const std::string &hexString) {
|
||||
unsigned short result;
|
||||
inline unsigned int hexToInt(const std::string &hexString) {
|
||||
unsigned int result{};
|
||||
std::stringstream hexStr(hexString);
|
||||
hexStr >> std::hex >> result;
|
||||
return result;
|
||||
@@ -92,11 +97,13 @@ inline unsigned short hexToInt(const std::string &hexString) {
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -109,8 +116,11 @@ inline unsigned char charToHex(char c) {
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -121,20 +131,26 @@ inline std::string hexStreambufToStr(const boost::asio::streambuf &buff) {
|
||||
}
|
||||
|
||||
inline std::vector<std::string> splitString(const std::string &str,
|
||||
const std::string &token) {
|
||||
const std::string &delimiter) {
|
||||
std::vector<std::string> result;
|
||||
std::string tempStr = str;
|
||||
|
||||
while (!tempStr.empty()) {
|
||||
size_t index = tempStr.find(token);
|
||||
size_t index = tempStr.find(delimiter);
|
||||
|
||||
if (index != std::string::npos) {
|
||||
result.push_back(tempStr.substr(0, index));
|
||||
tempStr = tempStr.substr(index + token.size());
|
||||
if (tempStr.empty()) result.push_back(tempStr);
|
||||
tempStr = tempStr.substr(index + delimiter.size());
|
||||
|
||||
if (tempStr.empty()) {
|
||||
result.push_back(tempStr);
|
||||
}
|
||||
} else {
|
||||
result.push_back(tempStr);
|
||||
tempStr.clear();
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -149,7 +165,7 @@ 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");
|
||||
}
|
||||
}
|
||||
@@ -182,46 +198,42 @@ inline BoolStr aes256Encrypt(const std::string &plaintext,
|
||||
plaintext.size() + EVP_CIPHER_block_size(EVP_aes_256_cbc());
|
||||
std::vector<unsigned char> ciphertext(ciphertext_len);
|
||||
|
||||
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
|
||||
using EvpCipherCtxPtr = std::unique_ptr<EVP_CIPHER_CTX, decltype(&EVP_CIPHER_CTX_free)>;
|
||||
EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
|
||||
if (!ctx) {
|
||||
result.message = "Context initialization failed";
|
||||
return result;
|
||||
}
|
||||
|
||||
if (EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL,
|
||||
if (EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_cbc(), NULL,
|
||||
reinterpret_cast<const unsigned char *>(key.c_str()),
|
||||
iv) != 1) {
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
result.message = "Encryption initialization failed";
|
||||
return result;
|
||||
}
|
||||
|
||||
int len;
|
||||
if (EVP_EncryptUpdate(
|
||||
ctx, ciphertext.data(), &len,
|
||||
ctx.get(), ciphertext.data(), &len,
|
||||
reinterpret_cast<const unsigned char *>(plaintext.c_str()),
|
||||
plaintext.size()) != 1) {
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
result.message = "Encryption update failed";
|
||||
return result;
|
||||
}
|
||||
ciphertext_len = len;
|
||||
|
||||
if (EVP_EncryptFinal_ex(ctx, ciphertext.data() + len, &len) != 1) {
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
if (EVP_EncryptFinal_ex(ctx.get(), ciphertext.data() + len, &len) != 1) {
|
||||
result.message = "Encryption finalization failed";
|
||||
return result;
|
||||
}
|
||||
ciphertext_len += len;
|
||||
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
|
||||
std::string final_result(reinterpret_cast<char *>(iv), sizeof(iv));
|
||||
final_result.append(reinterpret_cast<char *>(ciphertext.data()),
|
||||
ciphertext_len);
|
||||
|
||||
result.ok = true;
|
||||
result.message = final_result;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -232,46 +244,43 @@ inline BoolStr aes256Decrypt(const std::string &ciphertext_with_iv,
|
||||
unsigned char iv[EVP_MAX_IV_LENGTH];
|
||||
std::memcpy(iv, ciphertext_with_iv.c_str(),
|
||||
EVP_CIPHER_iv_length(EVP_aes_256_cbc()));
|
||||
|
||||
std::string ciphertext =
|
||||
ciphertext_with_iv.substr(EVP_CIPHER_iv_length(EVP_aes_256_cbc()));
|
||||
|
||||
int max_plaintext_len = ciphertext.size();
|
||||
std::vector<unsigned char> plaintext(max_plaintext_len);
|
||||
|
||||
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
|
||||
using EvpCipherCtxPtr = std::unique_ptr<EVP_CIPHER_CTX, decltype(&EVP_CIPHER_CTX_free)>;
|
||||
EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
|
||||
if (!ctx) {
|
||||
result.message = "Context initialization failed";
|
||||
return result;
|
||||
}
|
||||
|
||||
if (EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL,
|
||||
if (EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_cbc(), NULL,
|
||||
reinterpret_cast<const unsigned char *>(key.c_str()),
|
||||
iv) != 1) {
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
result.message = "Decryption initialization failed";
|
||||
return result;
|
||||
}
|
||||
|
||||
int len;
|
||||
if (EVP_DecryptUpdate(
|
||||
ctx, plaintext.data(), &len,
|
||||
ctx.get(), plaintext.data(), &len,
|
||||
reinterpret_cast<const unsigned char *>(ciphertext.c_str()),
|
||||
ciphertext.size()) != 1) {
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
result.message = "Decryption update failed";
|
||||
return result;
|
||||
}
|
||||
int plaintext_len = len;
|
||||
|
||||
if (EVP_DecryptFinal_ex(ctx, plaintext.data() + len, &len) != 1) {
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
if (EVP_DecryptFinal_ex(ctx.get(), plaintext.data() + len, &len) != 1) {
|
||||
result.message = "Decryption finalization failed";
|
||||
return result;
|
||||
}
|
||||
plaintext_len += len;
|
||||
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
|
||||
result.ok = true;
|
||||
result.message =
|
||||
std::string(reinterpret_cast<char *>(plaintext.data()), plaintext_len);
|
||||
@@ -311,12 +320,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;
|
||||
@@ -350,7 +361,17 @@ 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;
|
||||
}
|
||||
|
||||
result.ok = true;
|
||||
result.message = "OK";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+163
-44
@@ -1,7 +1,9 @@
|
||||
#include "http.hpp"
|
||||
|
||||
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),
|
||||
@@ -9,7 +11,6 @@ HTTP::HTTP(const std::shared_ptr<Config> &config,
|
||||
httpType_(HTTP::HttpType::https),
|
||||
parsedTlsRequest_{"", "", TlsTypes::TLSHandshake},
|
||||
uuid_(uuid) {
|
||||
chunkHeader_ = "no";
|
||||
}
|
||||
|
||||
HTTP::HTTP(const HTTP &http)
|
||||
@@ -19,19 +20,23 @@ HTTP::HTTP(const HTTP &http)
|
||||
parsedHttpRequest_(http.parsedHttpRequest_),
|
||||
parsedTlsRequest_(http.parsedTlsRequest_),
|
||||
uuid_(http.uuid_) {
|
||||
chunkHeader_ = "no";
|
||||
}
|
||||
|
||||
|
||||
HTTP::~HTTP() {}
|
||||
|
||||
|
||||
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
|
||||
@@ -49,17 +54,21 @@ bool HTTP::parseHttp() {
|
||||
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;
|
||||
}
|
||||
@@ -69,7 +78,9 @@ 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);
|
||||
@@ -83,30 +94,39 @@ bool HTTP::parseHttpResp() {
|
||||
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;
|
||||
@@ -117,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()) +
|
||||
@@ -238,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 : " +
|
||||
|
||||
+34
-24
@@ -21,13 +21,17 @@ public:
|
||||
return pointer(new HTTP(config, log, buffer, uuid));
|
||||
}
|
||||
|
||||
enum class HttpType { https,
|
||||
http,
|
||||
connect };
|
||||
enum class HttpType {
|
||||
https,
|
||||
http,
|
||||
connect
|
||||
};
|
||||
|
||||
enum class TlsTypes { TLSHandshake,
|
||||
ChangeCipherSpec,
|
||||
ApplicationData };
|
||||
enum class TlsTypes {
|
||||
TLSHandshake,
|
||||
ChangeCipherSpec,
|
||||
ApplicationData
|
||||
};
|
||||
|
||||
struct TlsRequest {
|
||||
std::string sni;
|
||||
@@ -39,22 +43,28 @@ public:
|
||||
|
||||
~HTTP();
|
||||
|
||||
inline const HTTP::HttpType &httpType() const { return httpType_; }
|
||||
inline HTTP::HttpType httpType() const { return httpType_; }
|
||||
|
||||
inline void httpType(const HTTP::HttpType &httpType) { httpType_ = httpType; }
|
||||
|
||||
static bool parseHostPort(const std::string &input,
|
||||
std::string &host,
|
||||
unsigned short &port,
|
||||
unsigned short defaultPort);
|
||||
|
||||
bool detectType();
|
||||
|
||||
bool parseHttp();
|
||||
|
||||
bool parseHttpResp();
|
||||
|
||||
bool parseTls();
|
||||
|
||||
const std::string genHttpPostReqString(const std::string &body) const;
|
||||
std::string genHttpPostReqString(const std::string &body) const;
|
||||
|
||||
const std::string genHttpRestPostReqString() const;
|
||||
std::string genHttpRestPostReqString() const;
|
||||
|
||||
const std::string genHttpOkResString(const std::string &body) const;
|
||||
std::string genHttpOkResString(const std::string &body) const;
|
||||
|
||||
inline const boost::beast::http::request<boost::beast::http::string_body> &
|
||||
parsedHttpRequest() & {
|
||||
@@ -68,15 +78,15 @@ public:
|
||||
|
||||
inline const TlsRequest &parsedTlsRequest() & { return parsedTlsRequest_; }
|
||||
|
||||
const std::string tlsTypeToString() const;
|
||||
std::string tlsTypeToString() const;
|
||||
|
||||
inline const std::string &dstIP() { return dstIP_; }
|
||||
inline const std::string &dstIp() const { return dstIp_; }
|
||||
|
||||
inline const unsigned short &dstPort() { return dstPort_; }
|
||||
inline unsigned short dstPort() const { return dstPort_; }
|
||||
|
||||
const std::string toString() const;
|
||||
const std::string restoString() const;
|
||||
std::string chunkHeader_;
|
||||
std::string toString() const;
|
||||
|
||||
std::string restoString() const;
|
||||
|
||||
private:
|
||||
explicit HTTP(const std::shared_ptr<Config> &config,
|
||||
@@ -86,17 +96,17 @@ private:
|
||||
|
||||
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_;
|
||||
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
|
||||
+10
-2
@@ -2,12 +2,12 @@
|
||||
|
||||
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)
|
||||
mode_ = std::string("AGENT");
|
||||
|
||||
|
||||
std::ofstream logFile(config_->log().file, std::ios::out | std::ios::app);
|
||||
if (!logFile.is_open()) {
|
||||
std::cerr << "Error opening log file: " << config_->log().file
|
||||
@@ -15,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") {
|
||||
@@ -36,18 +37,25 @@ 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();
|
||||
|
||||
std::string line = timestamp + " [" + mode_ + "]" + " [" +
|
||||
levelToString(level) + "] " + message + "\n";
|
||||
|
||||
logFile << line;
|
||||
std::cout << line;
|
||||
|
||||
} else {
|
||||
std::cerr << "Error opening log file: " << config_->log().file
|
||||
<< ". Make sure the directory and file exist.\n";
|
||||
@@ -68,4 +76,4 @@ std::string Log::levelToString(Level level) {
|
||||
default:
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-7
@@ -12,10 +12,13 @@
|
||||
|
||||
class Log : private Uncopyable {
|
||||
public:
|
||||
enum class Level { INFO,
|
||||
TRACE,
|
||||
ERROR,
|
||||
DEBUG };
|
||||
enum class Level {
|
||||
INFO,
|
||||
TRACE,
|
||||
ERROR,
|
||||
DEBUG
|
||||
};
|
||||
|
||||
using pointer = std::shared_ptr<Log>;
|
||||
|
||||
static pointer create(const std::shared_ptr<Config> &config) {
|
||||
@@ -23,9 +26,11 @@ public:
|
||||
}
|
||||
|
||||
explicit Log(const std::shared_ptr<Log> &log);
|
||||
|
||||
~Log();
|
||||
|
||||
const std::shared_ptr<Config> &config() const { return config_; }
|
||||
std::shared_ptr<Config> config() const { return config_; }
|
||||
|
||||
Level level() const { return level_; }
|
||||
|
||||
void write(const std::string &message, Level level) const;
|
||||
@@ -35,9 +40,9 @@ private:
|
||||
|
||||
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_;
|
||||
};
|
||||
};
|
||||
+4
-4
@@ -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_);
|
||||
@@ -30,4 +30,4 @@ int main(int argc, char const *argv[]) {
|
||||
runner_.run();
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+8
-13
@@ -5,15 +5,14 @@ Runner::Runner(const std::shared_ptr<Config> &config,
|
||||
: config_(config),
|
||||
log_(log),
|
||||
io_context_(),
|
||||
work_guard_(boost::asio::make_work_guard(
|
||||
io_context_)),
|
||||
work_guard_(boost::asio::make_work_guard(io_context_)),
|
||||
running_(true),
|
||||
strand_(boost::asio::make_strand(io_context_)) {}
|
||||
|
||||
Runner::~Runner() {
|
||||
running_.store(
|
||||
false);
|
||||
running_.store(false);
|
||||
io_context_.stop();
|
||||
|
||||
for (auto &thread: threadPool_) {
|
||||
if (thread.joinable()) {
|
||||
thread.join();
|
||||
@@ -23,14 +22,12 @@ Runner::~Runner() {
|
||||
|
||||
void Runner::run() {
|
||||
try {
|
||||
|
||||
log_->write("Config initialized in " + config_->modeToString() + " mode",
|
||||
Log::Level::INFO);
|
||||
log_->write("Config initialized in " + config_->modeToString() + " mode", Log::Level::INFO);
|
||||
log_->write(config_->toString(), Log::Level::INFO);
|
||||
|
||||
auto tcpServer = TCPServer::create(io_context_, config_, log_);
|
||||
|
||||
for (auto i = 0; i < config_->threads() * 50; ++i) {
|
||||
for (auto i = 0; i < config_->threads(); ++i) {
|
||||
threadPool_.emplace_back([this] { workerThread(); });
|
||||
}
|
||||
|
||||
@@ -39,11 +36,10 @@ void Runner::run() {
|
||||
thread.join();
|
||||
}
|
||||
}
|
||||
} catch (const std::exception &error) {
|
||||
|
||||
} catch (const std::exception &error) {
|
||||
log_->write(std::string("[Runner run] ") + error.what(), Log::Level::ERROR);
|
||||
} catch (...) {
|
||||
|
||||
log_->write("[Runner run] Unknown error occurred", Log::Level::ERROR);
|
||||
}
|
||||
}
|
||||
@@ -54,8 +50,7 @@ void Runner::workerThread() {
|
||||
io_context_.run();
|
||||
break;
|
||||
} catch (const std::exception &e) {
|
||||
log_->write(std::string("[WorkerThread] Exception: ") + e.what(),
|
||||
Log::Level::ERROR);
|
||||
log_->write(std::string("[WorkerThread] Exception: ") + e.what(), Log::Level::ERROR);
|
||||
} catch (...) {
|
||||
log_->write("[WorkerThread] Unknown error occurred", Log::Level::ERROR);
|
||||
}
|
||||
@@ -65,4 +60,4 @@ void Runner::workerThread() {
|
||||
void Runner::stop() {
|
||||
running_.store(false);
|
||||
io_context_.stop();
|
||||
}
|
||||
}
|
||||
+19
-6
@@ -7,6 +7,12 @@
|
||||
#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"
|
||||
@@ -15,19 +21,26 @@ class Runner : private Uncopyable {
|
||||
public:
|
||||
explicit Runner(const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log);
|
||||
|
||||
~Runner();
|
||||
|
||||
void run();
|
||||
|
||||
private:
|
||||
void workerThread();
|
||||
|
||||
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_;
|
||||
boost::asio::executor_work_guard<boost::asio::io_context::executor_type>
|
||||
work_guard_;
|
||||
|
||||
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_;
|
||||
|
||||
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
|
||||
};
|
||||
};
|
||||
+354
-172
@@ -1,19 +1,45 @@
|
||||
#include "serverhandler.hpp"
|
||||
|
||||
#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;
|
||||
@@ -21,184 +47,340 @@ ServerHandler::ServerHandler(boost::asio::streambuf &readBuffer,
|
||||
|
||||
ServerHandler::~ServerHandler() {}
|
||||
|
||||
void ServerHandler::makePlainHttpResponse(const std::string &body,
|
||||
const std::string &status,
|
||||
const std::string &connection) {
|
||||
std::ostringstream outer;
|
||||
|
||||
outer << "HTTP/1.1 " << status << "\r\n"
|
||||
<< "Content-Type: application/text\r\n"
|
||||
<< "Content-Length: " << body.size() << "\r\n"
|
||||
<< "Connection: " << connection << "\r\n"
|
||||
<< "\r\n"
|
||||
<< body;
|
||||
|
||||
copyStringToStreambuf(outer.str(), writeBuffer_);
|
||||
|
||||
end_ = false;
|
||||
connect_ = false;
|
||||
}
|
||||
|
||||
void ServerHandler::makeEncryptedHttpResponse(const std::string &plainBody,
|
||||
const std::string &status,
|
||||
const std::string &connection) {
|
||||
BoolStr encryption = aes256Encrypt(plainBody, config_->general().token);
|
||||
|
||||
if (!encryption.ok) {
|
||||
log_->write("[" + to_string(uuid_) + "] [ServerHandler] [Encryption Failed] " + encryption.message,
|
||||
Log::Level::DEBUG);
|
||||
|
||||
makePlainHttpResponse("", "500 Internal Server Error", "close");
|
||||
return;
|
||||
}
|
||||
|
||||
makePlainHttpResponse(encryption.message, status, connection);
|
||||
}
|
||||
|
||||
void ServerHandler::handle() {
|
||||
std::lock_guard<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_->doHandle();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
void ServerHandler::continueRead() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
client_->doHandle();
|
||||
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_);
|
||||
const auto outerHeaderEnd = outerRaw.find("\r\n\r\n");
|
||||
const std::string outerHeaders =
|
||||
outerHeaderEnd == std::string::npos
|
||||
? ""
|
||||
: outerRaw.substr(0, outerHeaderEnd + 2);
|
||||
|
||||
const std::string session =
|
||||
HttpUtils::getRawHeader(outerHeaders, "X-Nipo-Session");
|
||||
|
||||
const std::string action =
|
||||
HttpUtils::getRawHeader(outerHeaders, "X-Nipo-Action");
|
||||
|
||||
std::string requestBody = std::string(outerReq.body());
|
||||
|
||||
if (requestBody.empty()) {
|
||||
requestBody = HttpUtils::extractHttpBody(outerRaw);
|
||||
}
|
||||
|
||||
BoolStr decryption{false, std::string("FAILED")};
|
||||
|
||||
try {
|
||||
decryption = aes256Decrypt(
|
||||
decode64(requestBody),
|
||||
config_->general().token);
|
||||
} catch (const std::exception &e) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [ServerHandler handle] [Base64 Decode Failed] " + e.what(),
|
||||
Log::Level::DEBUG);
|
||||
|
||||
makePlainHttpResponse("", "400 Bad Request", "close");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!decryption.ok) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [ServerHandler handle] [Decryption Failed] : [ " +
|
||||
decryption.message + "] ",
|
||||
Log::Level::DEBUG);
|
||||
|
||||
makePlainHttpResponse("", "400 Bad Request", "close");
|
||||
return;
|
||||
}
|
||||
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) + "] [ServerHandler handle] [Decryption Done]",
|
||||
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()) {
|
||||
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
return;
|
||||
}
|
||||
|
||||
boost::asio::streambuf tunnelBuf;
|
||||
copyStringToStreambuf(hexToASCII(decryption.message), tunnelBuf);
|
||||
targetClient->doWrite(tunnelBuf);
|
||||
|
||||
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (action == "recv") {
|
||||
TCPClient::pointer targetClient;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
|
||||
auto it = sessions_.find(session);
|
||||
|
||||
if (it != sessions_.end()) {
|
||||
targetClient = it->second;
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetClient || !targetClient->isOpen()) {
|
||||
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
return;
|
||||
}
|
||||
|
||||
boost::system::error_code ec;
|
||||
std::size_t available = targetClient->socket().available(ec);
|
||||
|
||||
if (ec || available == 0) {
|
||||
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<char> data(std::min<std::size_t>(available, config_->general().bufferSize));
|
||||
std::size_t n = targetClient->socket().read_some(
|
||||
boost::asio::buffer(data),
|
||||
ec);
|
||||
|
||||
if (ec || n == 0) {
|
||||
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
return;
|
||||
}
|
||||
|
||||
makeEncryptedHttpResponse(
|
||||
std::string(data.data(), n),
|
||||
"200 OK",
|
||||
(config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (action == "close") {
|
||||
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
|
||||
auto it = sessions_.find(session);
|
||||
|
||||
if (it != sessions_.end()) {
|
||||
it->second->socketShutdown();
|
||||
sessions_.erase(it);
|
||||
}
|
||||
|
||||
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string innerRequest = hexToASCII(decryption.message);
|
||||
|
||||
const std::size_t headerEnd = innerRequest.find("\r\n\r\n");
|
||||
|
||||
if (headerEnd == std::string::npos) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [ServerHandler handle] [INNER REQUEST MISSING HEADER END]",
|
||||
Log::Level::DEBUG);
|
||||
|
||||
makeEncryptedHttpResponse("", "400 Bad Request", "close");
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string innerHeaders = innerRequest.substr(0, headerEnd + 4);
|
||||
const std::string pendingTunnelData = innerRequest.substr(headerEnd + 4);
|
||||
|
||||
copyStringToStreambuf(innerHeaders, readBuffer_);
|
||||
|
||||
HTTP::pointer inner = HTTP::create(config_, log_, readBuffer_, uuid_);
|
||||
|
||||
if (!inner->detectType()) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [ServerHandler handle] [NOT INNER HTTP Request] [Request] : " +
|
||||
streambufToString(readBuffer_),
|
||||
Log::Level::DEBUG);
|
||||
|
||||
makeEncryptedHttpResponse("", "400 Bad Request", "close");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (inner->httpType()) {
|
||||
case HTTP::HttpType::connect: {
|
||||
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);
|
||||
|
||||
makeEncryptedHttpResponse(
|
||||
"HTTP/1.1 502 Bad Gateway\r\n\r\n",
|
||||
"502 Bad Gateway",
|
||||
"close");
|
||||
|
||||
connect_ = false;
|
||||
end_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [CONNECT] [SRC " +
|
||||
clientConnStr_ + "] [DST " +
|
||||
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
|
||||
makeEncryptedHttpResponse(
|
||||
"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);
|
||||
|
||||
makeEncryptedHttpResponse(
|
||||
"HTTP/1.1 502 Bad Gateway\r\n\r\n",
|
||||
"502 Bad Gateway",
|
||||
"close");
|
||||
|
||||
connect_ = false;
|
||||
end_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [CONNECT] [SRC " +
|
||||
clientConnStr_ + "] [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;
|
||||
}
|
||||
|
||||
makeEncryptedHttpResponse(
|
||||
"HTTP/1.1 200 Connection Established\r\n\r\n",
|
||||
"200 OK",
|
||||
"keep-alive");
|
||||
|
||||
connect_ = false;
|
||||
end_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
case HTTP::HttpType::http:
|
||||
case HTTP::HttpType::https: {
|
||||
copyStringToStreambuf(innerRequest, readBuffer_);
|
||||
|
||||
if (!client_->socket().is_open()) {
|
||||
if (!client_->doConnect(inner->dstIp(), inner->dstPort())) {
|
||||
client_->socket().close();
|
||||
makeEncryptedHttpResponse("", "502 Bad Gateway", "close");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
client_->doWrite(readBuffer_);
|
||||
client_->doReadServer();
|
||||
|
||||
if (client_->readBuffer().size() == 0) {
|
||||
client_->socket().close();
|
||||
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
return;
|
||||
}
|
||||
|
||||
makeEncryptedHttpResponse(
|
||||
streambufToString(client_->readBuffer()),
|
||||
"200 OK",
|
||||
(config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
|
||||
connect_ = false;
|
||||
end_ = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
+36
-21
@@ -1,6 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "config.hpp"
|
||||
#include "general.hpp"
|
||||
@@ -8,51 +11,63 @@
|
||||
#include "log.hpp"
|
||||
#include "tcpclient.hpp"
|
||||
|
||||
|
||||
class ServerHandler : private Uncopyable {
|
||||
public:
|
||||
using pointer = std::shared_ptr<ServerHandler>;
|
||||
|
||||
|
||||
static pointer create(boost::asio::streambuf &readBuffer,
|
||||
boost::asio::streambuf &writeBuffer,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
const TCPClient::pointer &client,
|
||||
const std::string &clientConnStr,
|
||||
TCPClient::pointer client,
|
||||
std::string clientConnStr,
|
||||
boost::uuids::uuid uuid) {
|
||||
return pointer(new ServerHandler(readBuffer, writeBuffer, config, log,
|
||||
client, clientConnStr, uuid));
|
||||
return pointer(new ServerHandler(readBuffer, writeBuffer, config, log, client, clientConnStr, uuid));
|
||||
}
|
||||
|
||||
~ServerHandler();
|
||||
|
||||
void handle();
|
||||
void continueRead();
|
||||
|
||||
inline const HTTP::pointer &request() & { return request_; }
|
||||
inline const HTTP::pointer &request() const { return request_; }
|
||||
|
||||
inline const HTTP::pointer &&request() && { return std::move(request_); }
|
||||
bool end_, connect_;
|
||||
bool end_;
|
||||
bool connect_;
|
||||
|
||||
private:
|
||||
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_;
|
||||
boost::asio::streambuf &readBuffer_,
|
||||
&writeBuffer_;
|
||||
void makeEncryptedHttpResponse(const std::string &plainBody,
|
||||
const std::string &status = "200 OK",
|
||||
const std::string &connection = "close");
|
||||
|
||||
void makePlainHttpResponse(const std::string &body,
|
||||
const std::string &status = "200 OK",
|
||||
const std::string &connection = "close");
|
||||
|
||||
static std::mutex sessionsMutex_;
|
||||
static std::unordered_map<std::string, TCPClient::pointer> sessions_;
|
||||
|
||||
std::shared_ptr<Config> config_;
|
||||
std::shared_ptr<Log> log_;
|
||||
TCPClient::pointer client_;
|
||||
boost::asio::streambuf &readBuffer_;
|
||||
boost::asio::streambuf &writeBuffer_;
|
||||
HTTP::pointer request_;
|
||||
const std::string
|
||||
&clientConnStr_;
|
||||
std::string clientConnStr_;
|
||||
boost::uuids::uuid uuid_;
|
||||
std::mutex mutex_;
|
||||
};
|
||||
};
|
||||
+632
-228
@@ -1,5 +1,16 @@
|
||||
#include "tcpclient.hpp"
|
||||
|
||||
#include <openssl/ssl.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "http_utils.hpp"
|
||||
|
||||
TCPClient::TCPClient(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
@@ -8,310 +19,703 @@ TCPClient::TCPClient(boost::asio::io_context &io_context,
|
||||
log_(log),
|
||||
io_context_(io_context),
|
||||
socket_(io_context),
|
||||
sslContext_(boost::asio::ssl::context::tls_client),
|
||||
sslSocket_(nullptr),
|
||||
tlsEnabled_(false),
|
||||
resolver_(io_context),
|
||||
timeout_(io_context) {
|
||||
end_ = false;
|
||||
}
|
||||
|
||||
boost::asio::ip::tcp::socket &TCPClient::socket() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return socket_;
|
||||
TCPClient::tcp::socket &TCPClient::socket() { return socket_; }
|
||||
|
||||
TCPClient::ssl_stream &TCPClient::sslSocket() { return *sslSocket_; }
|
||||
|
||||
bool TCPClient::tlsEnabled() const { return tlsEnabled_; }
|
||||
|
||||
bool TCPClient::isOpen() const {
|
||||
if (tlsEnabled_ && sslSocket_) return sslSocket_->lowest_layer().is_open();
|
||||
return socket_.is_open();
|
||||
}
|
||||
|
||||
void TCPClient::writeBuffer(boost::asio::streambuf &buffer) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
moveStreambuf(buffer, writeBuffer_);
|
||||
}
|
||||
bool TCPClient::enableTlsClient() {
|
||||
|
||||
bool TCPClient::doConnect(const std::string &dstIP,
|
||||
const unsigned short &dstPort) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
try {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doConnect] [DST " + dstIP + ":" +
|
||||
std::to_string(dstPort) + "]",
|
||||
Log::Level::DEBUG);
|
||||
if (tlsEnabled_) return true;
|
||||
|
||||
boost::system::error_code error_code;
|
||||
auto endpoint = resolver_.resolve(dstIP.c_str(), std::to_string(dstPort).c_str(), error_code);
|
||||
if (error_code) {
|
||||
return false;
|
||||
sslContext_ = boost::asio::ssl::context(boost::asio::ssl::context::tls_client);
|
||||
|
||||
sslContext_.set_options(
|
||||
boost::asio::ssl::context::default_workarounds |
|
||||
boost::asio::ssl::context::no_sslv2 |
|
||||
boost::asio::ssl::context::no_sslv3);
|
||||
|
||||
SSL_CTX_set_min_proto_version(sslContext_.native_handle(), TLS1_2_VERSION);
|
||||
|
||||
if (config_->general().tlsVerifyPeer) {
|
||||
sslContext_.set_verify_mode(boost::asio::ssl::verify_peer);
|
||||
|
||||
if (!config_->general().tlsCaFile.empty()) {
|
||||
sslContext_.load_verify_file(config_->general().tlsCaFile);
|
||||
}
|
||||
} else {
|
||||
boost::asio::connect(socket_, endpoint);
|
||||
return true;
|
||||
sslContext_.set_verify_mode(boost::asio::ssl::verify_none);
|
||||
}
|
||||
} catch (std::exception &error) {
|
||||
|
||||
log_->write(std::string("[" + to_string(uuid_) + "] [TCPClient doConnect] ") + error.what(),
|
||||
if (SSL_CTX_set_cipher_list(
|
||||
sslContext_.native_handle(),
|
||||
"ECDHE-RSA-AES256-GCM-SHA384:"
|
||||
"ECDHE-RSA-AES128-GCM-SHA256:"
|
||||
"ECDHE-RSA-CHACHA20-POLY1305:"
|
||||
"AES256-GCM-SHA384:"
|
||||
"AES128-GCM-SHA256") != 1) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient enableTlsClient] failed to set cipher list",
|
||||
Log::Level::ERROR);
|
||||
return false;
|
||||
}
|
||||
|
||||
#if defined(TLS1_3_VERSION)
|
||||
SSL_CTX_set_ciphersuites(
|
||||
sslContext_.native_handle(),
|
||||
"TLS_AES_256_GCM_SHA384:"
|
||||
"TLS_AES_128_GCM_SHA256:"
|
||||
"TLS_CHACHA20_POLY1305_SHA256");
|
||||
#endif
|
||||
|
||||
sslSocket_ = std::make_unique<ssl_stream>(io_context_, sslContext_);
|
||||
tlsEnabled_ = true;
|
||||
return true;
|
||||
|
||||
} catch (std::exception &error) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient enableTlsClient] " + error.what(),
|
||||
Log::Level::ERROR);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void TCPClient::doWrite(boost::asio::streambuf &buffer) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
bool TCPClient::doConnect(const std::string &dstIp, unsigned short dstPort) {
|
||||
try {
|
||||
moveStreambuf(buffer, writeBuffer_);
|
||||
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doWrite] [DST " +
|
||||
socket_.remote_endpoint().address().to_string() + ":" +
|
||||
std::to_string(socket_.remote_endpoint().port()) + "] " +
|
||||
"[Bytes " + std::to_string(writeBuffer_.size()) + "] ",
|
||||
Log::Level::DEBUG);
|
||||
log_->write("[" + to_string(uuid_) + "] [Write to] [DST " +
|
||||
socket_.remote_endpoint().address().to_string() + ":" +
|
||||
std::to_string(socket_.remote_endpoint().port()) + "] " +
|
||||
"[Bytes " + std::to_string(writeBuffer_.size()) + "] ",
|
||||
Log::Level::TRACE);
|
||||
|
||||
boost::system::error_code error;
|
||||
if (writeBuffer_.size() > 0) {
|
||||
resetTimeout();
|
||||
boost::asio::write(socket_, writeBuffer_, error);
|
||||
cancelTimeout();
|
||||
if (error) {
|
||||
log_->write(std::string("[" + to_string(uuid_) + "] [TCPClient doWrite] [error] ") + error.message(),
|
||||
Log::Level::DEBUG);
|
||||
socketShutdown();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doWrite] [ZERO Bytes] [DST " +
|
||||
socket_.remote_endpoint().address().to_string() + ":" +
|
||||
std::to_string(socket_.remote_endpoint().port()) + "] " +
|
||||
"[Bytes " + std::to_string(writeBuffer_.size()) + "] ",
|
||||
Log::Level::DEBUG);
|
||||
socketShutdown();
|
||||
return;
|
||||
if (tlsEnabled_ && sslSocket_ && sslSocket_->lowest_layer().is_open()) {
|
||||
return true;
|
||||
}
|
||||
} catch (std::exception &error) {
|
||||
|
||||
log_->write(std::string("[" + to_string(uuid_) + "] [TCPClient doWrite] [catch] ") + error.what(),
|
||||
if (!tlsEnabled_ && socket_.is_open()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doConnect] [DST " + dstIp + ":" +
|
||||
std::to_string(dstPort) + "]",
|
||||
Log::Level::DEBUG);
|
||||
socketShutdown();
|
||||
}
|
||||
}
|
||||
|
||||
void TCPClient::doReadAgent() {
|
||||
boost::system::error_code error;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
boost::asio::streambuf tempBuff;
|
||||
boost::system::error_code error_code;
|
||||
|
||||
try {
|
||||
if (!socket_.is_open()) {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doReadAgent] Socket is not OPEN",
|
||||
Log::Level::DEBUG);
|
||||
return;
|
||||
auto endpoints = resolver_.resolve(
|
||||
dstIp,
|
||||
std::to_string(dstPort),
|
||||
error_code);
|
||||
|
||||
if (error_code) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doConnect] resolve error: " +
|
||||
error_code.message(),
|
||||
Log::Level::ERROR);
|
||||
return false;
|
||||
}
|
||||
|
||||
resetTimeout();
|
||||
boost::asio::read_until(socket_, tempBuff, "COMP\r\n\r\n",
|
||||
error);
|
||||
cancelTimeout();
|
||||
if (error == boost::asio::error::eof) {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doReadAgent] [EOF] Connection closed by peer.",
|
||||
Log::Level::TRACE);
|
||||
socketShutdown();
|
||||
return;
|
||||
} else if (error) {
|
||||
log_->write(
|
||||
std::string("[" + to_string(uuid_) + "] [TCPClient doReadAgent] [error] ") + error.message(),
|
||||
Log::Level::ERROR);
|
||||
socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
if (tempBuff.size() > 0) {
|
||||
copyStreambuf(tempBuff, buffer_);
|
||||
try {
|
||||
if (tlsEnabled_) {
|
||||
sslSocket_ = std::make_unique<ssl_stream>(io_context_, sslContext_);
|
||||
closed_ = false;
|
||||
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doReadAgent] [SRC " +
|
||||
socket_.remote_endpoint().address().to_string() + ":" +
|
||||
std::to_string(socket_.remote_endpoint().port()) +
|
||||
"] [Bytes " + std::to_string(tempBuff.size()) + "] ",
|
||||
Log::Level::DEBUG);
|
||||
log_->write("[" + to_string(uuid_) + "] [Read from] [SRC " +
|
||||
socket_.remote_endpoint().address().to_string() + ":" +
|
||||
std::to_string(socket_.remote_endpoint().port()) +
|
||||
"] " + "[Bytes " + std::to_string(tempBuff.size()) +
|
||||
"] ",
|
||||
Log::Level::TRACE);
|
||||
} catch (std::exception &error) {
|
||||
|
||||
log_->write(
|
||||
std::string("[" + to_string(uuid_) + "] [TCPClient doReadAgent] [catch log] ") + error.what(),
|
||||
Log::Level::DEBUG);
|
||||
}
|
||||
boost::asio::connect(
|
||||
sslSocket_->lowest_layer(),
|
||||
endpoints,
|
||||
error_code);
|
||||
} else {
|
||||
socketShutdown();
|
||||
return;
|
||||
}
|
||||
} catch (std::exception &error) {
|
||||
socket_ = tcp::socket(io_context_);
|
||||
closed_ = false;
|
||||
|
||||
log_->write(std::string("[" + to_string(uuid_) + "] [TCPClient doReadAgent] [catch read] ") + error.what(),
|
||||
boost::asio::connect(
|
||||
socket_,
|
||||
endpoints,
|
||||
error_code);
|
||||
}
|
||||
|
||||
cancelTimeout();
|
||||
|
||||
if (error_code) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doConnect] connect error: " +
|
||||
error_code.message(),
|
||||
Log::Level::ERROR);
|
||||
socketShutdown();
|
||||
return false;
|
||||
}
|
||||
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doConnect] connected",
|
||||
Log::Level::DEBUG);
|
||||
|
||||
return true;
|
||||
|
||||
} catch (const std::exception &ex) {
|
||||
cancelTimeout();
|
||||
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doConnect] exception: " + ex.what(),
|
||||
Log::Level::ERROR);
|
||||
|
||||
socketShutdown();
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool TCPClient::doHandshakeClient() {
|
||||
try {
|
||||
if (!tlsEnabled_ || !sslSocket_) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!sslSocket_->lowest_layer().is_open()) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doHandshakeClient] socket is not open",
|
||||
Log::Level::ERROR);
|
||||
socketShutdown();
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string sniHost = config_->randomFakeUrl();
|
||||
|
||||
auto pos = sniHost.find("://");
|
||||
if (pos != std::string::npos) {
|
||||
sniHost = sniHost.substr(pos + 3);
|
||||
}
|
||||
|
||||
pos = sniHost.find('/');
|
||||
if (pos != std::string::npos) {
|
||||
sniHost = sniHost.substr(0, pos);
|
||||
}
|
||||
|
||||
pos = sniHost.find(':');
|
||||
if (pos != std::string::npos) {
|
||||
sniHost = sniHost.substr(0, pos);
|
||||
}
|
||||
|
||||
if (!sniHost.empty()) {
|
||||
if (!SSL_set_tlsext_host_name(
|
||||
sslSocket_->native_handle(),
|
||||
sniHost.c_str())) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TLS] Failed to set SNI: " + sniHost,
|
||||
Log::Level::ERROR);
|
||||
socketShutdown();
|
||||
return false;
|
||||
}
|
||||
|
||||
static const unsigned char alpn[] = {
|
||||
0x08, 'h', 't', 't', 'p', '/', '1', '.', '1'};
|
||||
|
||||
if (SSL_set_alpn_protos(
|
||||
sslSocket_->native_handle(),
|
||||
alpn,
|
||||
sizeof(alpn)) != 0) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TLS] Failed to set ALPN http/1.1",
|
||||
Log::Level::ERROR);
|
||||
socketShutdown();
|
||||
return false;
|
||||
}
|
||||
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TLS] Starting client handshake with SNI: " +
|
||||
sniHost,
|
||||
Log::Level::DEBUG);
|
||||
}
|
||||
|
||||
boost::system::error_code error;
|
||||
resetTimeout();
|
||||
|
||||
sslSocket_->handshake(
|
||||
boost::asio::ssl::stream_base::client,
|
||||
error);
|
||||
|
||||
cancelTimeout();
|
||||
|
||||
if (error) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doHandshakeClient] handshake error: " +
|
||||
error.message(),
|
||||
Log::Level::ERROR);
|
||||
socketShutdown();
|
||||
return false;
|
||||
}
|
||||
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TLS] Client handshake completed",
|
||||
Log::Level::DEBUG);
|
||||
|
||||
const unsigned char *selected = nullptr;
|
||||
unsigned int selectedLen = 0;
|
||||
|
||||
SSL_get0_alpn_selected(
|
||||
sslSocket_->native_handle(),
|
||||
&selected,
|
||||
&selectedLen);
|
||||
|
||||
if (selected != nullptr && selectedLen > 0) {
|
||||
std::string negotiated(
|
||||
reinterpret_cast<const char *>(selected),
|
||||
selectedLen);
|
||||
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TLS] Negotiated ALPN: " + negotiated,
|
||||
Log::Level::DEBUG);
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TLS] No ALPN negotiated",
|
||||
Log::Level::DEBUG);
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
} catch (const std::exception &ex) {
|
||||
cancelTimeout();
|
||||
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doHandshakeClient] exception: " +
|
||||
ex.what(),
|
||||
Log::Level::ERROR);
|
||||
|
||||
socketShutdown();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void TCPClient::writeBuffer(boost::asio::streambuf &buffer) {
|
||||
moveStreambuf(buffer, writeBuffer_);
|
||||
}
|
||||
|
||||
|
||||
bool TCPClient::doWrite(boost::asio::streambuf &buffer) {
|
||||
try {
|
||||
writeBuffer_.consume(writeBuffer_.size());
|
||||
moveStreambuf(buffer, writeBuffer_);
|
||||
|
||||
if (!isOpen()) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doWrite] socket is not open",
|
||||
Log::Level::DEBUG);
|
||||
socketShutdown();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (writeBuffer_.size() == 0) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doWrite] empty write buffer",
|
||||
Log::Level::DEBUG);
|
||||
socketShutdown();
|
||||
return false;
|
||||
}
|
||||
|
||||
boost::system::error_code error;
|
||||
resetTimeout();
|
||||
|
||||
if (tlsEnabled_ && sslSocket_) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doWrite] [SSL] [Bytes " +
|
||||
std::to_string(writeBuffer_.size()) + "]",
|
||||
Log::Level::DEBUG);
|
||||
|
||||
boost::asio::write(*sslSocket_, writeBuffer_, error);
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doWrite] [TCP] [Bytes " +
|
||||
std::to_string(writeBuffer_.size()) + "]",
|
||||
Log::Level::DEBUG);
|
||||
|
||||
boost::asio::write(socket_, writeBuffer_, error);
|
||||
}
|
||||
|
||||
cancelTimeout();
|
||||
|
||||
if (error) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doWrite] [error] " + error.message(),
|
||||
Log::Level::DEBUG);
|
||||
socketShutdown();
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
} catch (const std::exception &ex) {
|
||||
cancelTimeout();
|
||||
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doWrite] [catch] " + ex.what(),
|
||||
Log::Level::DEBUG);
|
||||
|
||||
socketShutdown();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool TCPClient::doReadAgent() {
|
||||
boost::system::error_code error;
|
||||
|
||||
try {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
readBuffer_.consume(readBuffer_.size());
|
||||
buffer_.consume(buffer_.size());
|
||||
|
||||
if (!isOpen()) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadAgent] Socket is not OPEN",
|
||||
Log::Level::DEBUG);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
resetTimeout();
|
||||
|
||||
bool ok = false;
|
||||
if (tlsEnabled_) {
|
||||
if (!sslSocket_) {
|
||||
cancelTimeout();
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadAgent] SSL socket is null",
|
||||
Log::Level::DEBUG);
|
||||
socketShutdown();
|
||||
return false;
|
||||
}
|
||||
|
||||
ok = HttpUtils::readHttpMessage(*sslSocket_, readBuffer_, error);
|
||||
} else {
|
||||
ok = HttpUtils::readHttpMessage(socket_, readBuffer_, error);
|
||||
}
|
||||
|
||||
cancelTimeout();
|
||||
|
||||
if (!ok) {
|
||||
if (error == boost::asio::error::operation_aborted) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadAgent] [aborted]",
|
||||
Log::Level::DEBUG);
|
||||
} else if (error == boost::asio::error::eof) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadAgent] [EOF] Connection closed by peer.",
|
||||
Log::Level::TRACE);
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadAgent] [error] " + error.message(),
|
||||
Log::Level::ERROR);
|
||||
}
|
||||
|
||||
socketShutdown();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (readBuffer_.size() == 0) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadAgent] empty read buffer",
|
||||
Log::Level::DEBUG);
|
||||
socketShutdown();
|
||||
return false;
|
||||
}
|
||||
|
||||
copyStreambuf(readBuffer_, buffer_);
|
||||
return true;
|
||||
|
||||
} catch (const std::exception &ex) {
|
||||
cancelTimeout();
|
||||
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadAgent] [catch read] " + ex.what(),
|
||||
Log::Level::DEBUG);
|
||||
|
||||
socketShutdown();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void TCPClient::doReadServer() {
|
||||
boost::system::error_code error;
|
||||
end_ = false;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
boost::asio::streambuf tempBuff;
|
||||
boost::asio::steady_timer timer(io_context_);
|
||||
bool isTlsRecord{false};
|
||||
readBuffer_.consume(readBuffer_.size());
|
||||
|
||||
try {
|
||||
if (!socket_.is_open()) {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doReadServer] Socket is not OPEN",
|
||||
if (!isOpen()) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadServer] Socket is not OPEN",
|
||||
Log::Level::DEBUG);
|
||||
return;
|
||||
}
|
||||
|
||||
std::array<char, 16384> temp{};
|
||||
resetTimeout();
|
||||
boost::asio::read(socket_, tempBuff, boost::asio::transfer_exactly(2),
|
||||
error);
|
||||
std::string bufStr{hexStreambufToStr(tempBuff)};
|
||||
if (bufStr == "1403" || bufStr == "1503" || bufStr == "1603" || bufStr == "1703") {
|
||||
isTlsRecord = true;
|
||||
boost::asio::streambuf tempTempBuff;
|
||||
boost::asio::read(socket_, tempBuff, boost::asio::transfer_exactly(1),
|
||||
error);
|
||||
boost::asio::read(socket_, tempTempBuff, boost::asio::transfer_exactly(2),
|
||||
error);
|
||||
int readSize{hexToInt(hexStreambufToStr(tempTempBuff))};
|
||||
moveStreambuf(tempTempBuff, tempBuff);
|
||||
boost::asio::read(socket_, tempBuff, boost::asio::transfer_exactly(readSize),
|
||||
error);
|
||||
|
||||
std::size_t bytes = 0;
|
||||
if (tlsEnabled_ && sslSocket_) {
|
||||
bytes = sslSocket_->read_some(boost::asio::buffer(temp), error);
|
||||
} else {
|
||||
bytes = socket_.read_some(boost::asio::buffer(temp), error);
|
||||
}
|
||||
|
||||
cancelTimeout();
|
||||
|
||||
|
||||
if (error == boost::asio::error::eof) {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doReadServer] [EOF] Connection closed by peer.",
|
||||
Log::Level::TRACE);
|
||||
socketShutdown();
|
||||
return;
|
||||
} else if (error) {
|
||||
log_->write(
|
||||
std::string("[" + to_string(uuid_) + "] [TCPClient doReadServer] [error] ") + error.message(),
|
||||
Log::Level::ERROR);
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadServer] [error] " + error.message(),
|
||||
Log::Level::ERROR);
|
||||
socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isTlsRecord) {
|
||||
for (auto i = 0; i <= config_->general().repeatWait; i++) {
|
||||
while (true) {
|
||||
if (socket_.available() == 0) break;
|
||||
resetTimeout();
|
||||
boost::asio::read(socket_, tempBuff,
|
||||
boost::asio::transfer_at_least(1), error);
|
||||
cancelTimeout();
|
||||
if (error == boost::asio::error::eof) {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doReadServer] [EOF] Connection closed by peer.",
|
||||
Log::Level::TRACE);
|
||||
socketShutdown();
|
||||
return;
|
||||
} else if (error) {
|
||||
log_->write(
|
||||
std::string("[" + to_string(uuid_) + "] [TCPClient doReadServer] [error] ") + error.message(),
|
||||
Log::Level::ERROR);
|
||||
socketShutdown();
|
||||
return;
|
||||
}
|
||||
}
|
||||
timer.expires_after(std::chrono::milliseconds(config_->general().timeWait));
|
||||
timer.wait();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
timer.expires_after(std::chrono::milliseconds(config_->general().timeWait));
|
||||
timer.wait();
|
||||
if (socket_.available() == 0) {
|
||||
if (bytes == 0) {
|
||||
end_ = true;
|
||||
}
|
||||
|
||||
if (tempBuff.size() > 0) {
|
||||
copyStreambuf(tempBuff, buffer_);
|
||||
try {
|
||||
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doReadServer] [SRC " +
|
||||
socket_.remote_endpoint().address().to_string() + ":" +
|
||||
std::to_string(socket_.remote_endpoint().port()) +
|
||||
"] [Bytes " + std::to_string(tempBuff.size()) + "] ",
|
||||
Log::Level::DEBUG);
|
||||
log_->write("[" + to_string(uuid_) + "] [Read from] [SRC " +
|
||||
socket_.remote_endpoint().address().to_string() + ":" +
|
||||
std::to_string(socket_.remote_endpoint().port()) +
|
||||
"] " + "[Bytes " + std::to_string(tempBuff.size()) +
|
||||
"] ",
|
||||
Log::Level::TRACE);
|
||||
} catch (std::exception &error) {
|
||||
|
||||
log_->write(
|
||||
std::string("[" + to_string(uuid_) + "] [TCPClient doReadServer] [catch log] ") + error.what(),
|
||||
Log::Level::DEBUG);
|
||||
}
|
||||
} else {
|
||||
socketShutdown();
|
||||
return;
|
||||
}
|
||||
} catch (std::exception &error) {
|
||||
|
||||
log_->write(std::string("[" + to_string(uuid_) + "] [TCPClient doReadServer] [catch read] ") + error.what(),
|
||||
std::ostream os(&readBuffer_);
|
||||
os.write(temp.data(), static_cast<std::streamsize>(bytes));
|
||||
|
||||
end_ = false;
|
||||
|
||||
if (tlsEnabled_ && sslSocket_) {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doReadServer] [SRC " +
|
||||
sslSocket_->lowest_layer().remote_endpoint().address().to_string() +
|
||||
":" +
|
||||
std::to_string(sslSocket_->lowest_layer().remote_endpoint().port()) +
|
||||
"] [Bytes " + std::to_string(readBuffer_.size()) + "] ",
|
||||
Log::Level::DEBUG);
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doReadServer] [SRC " +
|
||||
socket_.remote_endpoint().address().to_string() + ":" +
|
||||
std::to_string(socket_.remote_endpoint().port()) +
|
||||
"] [Bytes " + std::to_string(readBuffer_.size()) + "] ",
|
||||
Log::Level::DEBUG);
|
||||
}
|
||||
|
||||
copyStreambuf(readBuffer_, buffer_);
|
||||
|
||||
} catch (std::exception &error) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadServer] [catch read] " + error.what(),
|
||||
Log::Level::DEBUG);
|
||||
socketShutdown();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void TCPClient::doHandle() {
|
||||
buffer_.consume(buffer_.size());
|
||||
readBuffer_.consume(readBuffer_.size());
|
||||
if (config_->runMode() == RunMode::server) {
|
||||
doReadServer();
|
||||
} else {
|
||||
doReadAgent();
|
||||
}
|
||||
copyStreambuf(buffer_, readBuffer_);
|
||||
}
|
||||
|
||||
void TCPClient::resetTimeout() {
|
||||
if (!config_->general().timeout)
|
||||
return;
|
||||
timeout_.expires_from_now(boost::posix_time::seconds(config_->general().timeout));
|
||||
timeout_.async_wait(boost::bind(&TCPClient::onTimeout,
|
||||
shared_from_this(),
|
||||
boost::asio::placeholders::error));
|
||||
if (!config_->general().timeout) return;
|
||||
|
||||
timeout_.expires_after(std::chrono::seconds(config_->general().timeout));
|
||||
timeout_.async_wait(
|
||||
[self = shared_from_this()](const boost::system::error_code &error) {
|
||||
self->onTimeout(error);
|
||||
});
|
||||
}
|
||||
|
||||
void TCPClient::cancelTimeout() {
|
||||
|
||||
if (config_->general().timeout)
|
||||
timeout_.cancel();
|
||||
if (config_->general().timeout) timeout_.cancel();
|
||||
}
|
||||
|
||||
void TCPClient::onTimeout(const boost::system::error_code &error) {
|
||||
if (error || error == boost::asio::error::operation_aborted) return;
|
||||
if (error == boost::asio::error::operation_aborted) {
|
||||
return;
|
||||
}
|
||||
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient onTimeout] timeout expired",
|
||||
Log::Level::TRACE);
|
||||
|
||||
log_->write(
|
||||
std::string("[" + to_string(uuid_) + "] [TCPClient onTimeout] [expiration] ") +
|
||||
std::to_string(+config_->general().timeout) +
|
||||
" seconds has passed, and the timeout has expired",
|
||||
Log::Level::TRACE);
|
||||
socketShutdown();
|
||||
}
|
||||
|
||||
void TCPClient::socketShutdown() {
|
||||
try {
|
||||
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_send);
|
||||
socket_.close();
|
||||
} catch (std::exception &error) {
|
||||
log_->write(
|
||||
std::string("[" + to_string(uuid_) + "] [TCPClient socketShutdown] [catch] ") + error.what(),
|
||||
Log::Level::DEBUG);
|
||||
boost::system::error_code ec;
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (closed_) return;
|
||||
closed_ = true;
|
||||
|
||||
cancelTimeout();
|
||||
|
||||
if (sslSocket_) {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient socketShutdown] [SSL]",
|
||||
Log::Level::DEBUG);
|
||||
|
||||
auto &lowest = sslSocket_->lowest_layer();
|
||||
|
||||
lowest.cancel(ec);
|
||||
ec.clear();
|
||||
|
||||
if (lowest.is_open()) {
|
||||
lowest.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
|
||||
ec.clear();
|
||||
|
||||
lowest.close(ec);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (socket_.is_open()) {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient socketShutdown] [TCP]",
|
||||
Log::Level::DEBUG);
|
||||
|
||||
socket_.cancel(ec);
|
||||
ec.clear();
|
||||
|
||||
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
|
||||
ec.clear();
|
||||
|
||||
socket_.close(ec);
|
||||
}
|
||||
|
||||
tlsEnabled_ = false;
|
||||
}
|
||||
|
||||
std::string TCPClient::HttpUtils::toLowerCopy(std::string s) {
|
||||
return http_utils::toLowerCopy(std::move(s));
|
||||
}
|
||||
|
||||
std::string TCPClient::HttpUtils::extractHeaders(const std::string &msg) {
|
||||
return http_utils::extractHeaders(msg);
|
||||
}
|
||||
|
||||
std::string TCPClient::HttpUtils::extractBody(const std::string &msg) {
|
||||
return http_utils::extractBody(msg);
|
||||
}
|
||||
|
||||
bool TCPClient::HttpUtils::parseContentLength(const std::string &headers, std::size_t &value) {
|
||||
return http_utils::parseContentLength(headers, value);
|
||||
}
|
||||
|
||||
bool TCPClient::HttpUtils::isChunked(const std::string &headers) {
|
||||
return http_utils::isChunked(headers);
|
||||
}
|
||||
|
||||
bool TCPClient::HttpUtils::readHttpMessage(
|
||||
tcp::socket &stream,
|
||||
boost::asio::streambuf &out,
|
||||
boost::system::error_code &ec) {
|
||||
return readHttpMessageImpl(
|
||||
out,
|
||||
ec,
|
||||
[&stream](boost::asio::mutable_buffer buffer,
|
||||
boost::system::error_code &error) {
|
||||
return stream.read_some(buffer, error);
|
||||
},
|
||||
[&stream](boost::asio::streambuf &buffer,
|
||||
boost::system::error_code &error) {
|
||||
boost::asio::read_until(stream, buffer, "\r\n\r\n", error);
|
||||
return !error;
|
||||
});
|
||||
}
|
||||
|
||||
bool TCPClient::HttpUtils::readHttpMessage(
|
||||
ssl_stream &stream,
|
||||
boost::asio::streambuf &out,
|
||||
boost::system::error_code &ec) {
|
||||
return readHttpMessageImpl(
|
||||
out,
|
||||
ec,
|
||||
[&stream](boost::asio::mutable_buffer buffer,
|
||||
boost::system::error_code &error) {
|
||||
return stream.read_some(buffer, error);
|
||||
},
|
||||
[&stream](boost::asio::streambuf &buffer,
|
||||
boost::system::error_code &error) {
|
||||
boost::asio::read_until(stream, buffer, "\r\n\r\n", error);
|
||||
return !error;
|
||||
});
|
||||
}
|
||||
|
||||
bool TCPClient::HttpUtils::readHttpMessageImpl(
|
||||
boost::asio::streambuf &out,
|
||||
boost::system::error_code &ec,
|
||||
const std::function<std::size_t(
|
||||
boost::asio::mutable_buffer,
|
||||
boost::system::error_code &)> &readSome,
|
||||
const std::function<bool(
|
||||
boost::asio::streambuf &,
|
||||
boost::system::error_code &)> &readHeaders) {
|
||||
|
||||
out.consume(out.size());
|
||||
|
||||
if (!readHeaders(out, ec)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string current = streambufToString(out);
|
||||
std::string headers = extractHeaders(current);
|
||||
std::string body = extractBody(current);
|
||||
|
||||
std::size_t contentLength = 0;
|
||||
if (parseContentLength(headers, contentLength)) {
|
||||
while (body.size() < contentLength) {
|
||||
char tmp[8192];
|
||||
std::size_t remaining =
|
||||
contentLength - body.size();
|
||||
std::size_t toRead =
|
||||
std::min<std::size_t>(
|
||||
sizeof(tmp),
|
||||
remaining);
|
||||
std::size_t n =
|
||||
readSome(
|
||||
boost::asio::buffer(
|
||||
tmp,
|
||||
toRead),
|
||||
ec);
|
||||
if (ec) {
|
||||
return false;
|
||||
}
|
||||
if (n == 0) {
|
||||
ec = boost::asio::error::eof;
|
||||
return false;
|
||||
}
|
||||
boost::asio::buffer_copy(
|
||||
out.prepare(n),
|
||||
boost::asio::buffer(tmp, n));
|
||||
out.commit(n);
|
||||
body.append(tmp, n);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (isChunked(headers)) {
|
||||
while (
|
||||
body.find("\r\n0\r\n\r\n") ==
|
||||
std::string::npos &&
|
||||
body.find("\r\n0\r\n") ==
|
||||
std::string::npos) {
|
||||
char tmp[8192];
|
||||
std::size_t n =
|
||||
readSome(
|
||||
boost::asio::buffer(tmp),
|
||||
ec);
|
||||
if (ec) {
|
||||
return false;
|
||||
}
|
||||
if (n == 0) {
|
||||
ec = boost::asio::error::eof;
|
||||
return false;
|
||||
}
|
||||
boost::asio::buffer_copy(
|
||||
out.prepare(n),
|
||||
boost::asio::buffer(tmp, n));
|
||||
out.commit(n);
|
||||
body.append(tmp, n);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
+73
-25
@@ -1,58 +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"
|
||||
|
||||
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>;
|
||||
|
||||
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));
|
||||
}
|
||||
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);
|
||||
|
||||
void writeBuffer(boost::asio::streambuf &buffer);
|
||||
|
||||
inline boost::asio::streambuf &writeBuffer() & { return writeBuffer_; }
|
||||
inline boost::asio::streambuf &&writeBuffer() && {
|
||||
return std::move(writeBuffer_);
|
||||
}
|
||||
|
||||
inline boost::asio::streambuf &readBuffer() & { return readBuffer_; }
|
||||
inline boost::asio::streambuf &&readBuffer() && {
|
||||
return std::move(readBuffer_);
|
||||
}
|
||||
bool doConnect(const std::string &dstIP, const unsigned short &dstPort);
|
||||
void doWrite(boost::asio::streambuf &buffer);
|
||||
void doReadAgent();
|
||||
|
||||
bool doReadAgent();
|
||||
bool doWrite(boost::asio::streambuf &buffer);
|
||||
void doReadServer();
|
||||
void doHandle();
|
||||
|
||||
void socketShutdown();
|
||||
|
||||
boost::uuids::uuid uuid() const { return uuid_; }
|
||||
bool ended() const { return end_; }
|
||||
|
||||
boost::uuids::uuid uuid_;
|
||||
bool end_;
|
||||
|
||||
private:
|
||||
struct HttpUtils {
|
||||
static std::string toLowerCopy(std::string s);
|
||||
static std::string extractHeaders(const std::string &msg);
|
||||
static std::string extractBody(const std::string &msg);
|
||||
static bool parseContentLength(const std::string &headers, std::size_t &value);
|
||||
static bool isChunked(const std::string &headers);
|
||||
|
||||
static bool readHttpMessage(tcp::socket &stream,
|
||||
boost::asio::streambuf &out,
|
||||
boost::system::error_code &ec);
|
||||
|
||||
static bool readHttpMessage(ssl_stream &stream,
|
||||
boost::asio::streambuf &out,
|
||||
boost::system::error_code &ec);
|
||||
|
||||
static bool readHttpMessageImpl(
|
||||
boost::asio::streambuf &out,
|
||||
boost::system::error_code &ec,
|
||||
const std::function<std::size_t(boost::asio::mutable_buffer,
|
||||
boost::system::error_code &)> &readSome,
|
||||
const std::function<bool(boost::asio::streambuf &,
|
||||
boost::system::error_code &)> &readHeaders);
|
||||
};
|
||||
|
||||
explicit TCPClient(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log);
|
||||
|
||||
void resetTimeout();
|
||||
void cancelTimeout();
|
||||
void onTimeout(const boost::system::error_code &error);
|
||||
const std::shared_ptr<Config>
|
||||
&config_;
|
||||
const std::shared_ptr<Log> &log_;
|
||||
|
||||
std::shared_ptr<Config> config_;
|
||||
std::shared_ptr<Log> log_;
|
||||
boost::asio::io_context &io_context_;
|
||||
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;
|
||||
};
|
||||
+1074
-218
File diff suppressed because it is too large.
Load diff
+111
-22
@@ -1,18 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/asio/ssl.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <boost/enable_shared_from_this.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/uuid/uuid.hpp>
|
||||
#include <boost/uuid/uuid_generators.hpp>
|
||||
#include <boost/uuid/uuid_io.hpp>
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
#include "agenthandler.hpp"
|
||||
#include "general.hpp"
|
||||
#include "serverhandler.hpp"
|
||||
|
||||
class TCPConnection : public boost::enable_shared_from_this<TCPConnection> {
|
||||
class TCPConnection : public std::enable_shared_from_this<TCPConnection> {
|
||||
public:
|
||||
using pointer =
|
||||
boost::shared_ptr<TCPConnection>;
|
||||
using pointer = std::shared_ptr<TCPConnection>;
|
||||
using ssl_stream = boost::asio::ssl::stream<boost::asio::ip::tcp::socket>;
|
||||
|
||||
static pointer create(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
@@ -22,45 +31,125 @@ public:
|
||||
}
|
||||
|
||||
boost::asio::ip::tcp::socket &socket();
|
||||
inline TCPClient::pointer client() const { return client_; }
|
||||
ssl_stream &tlsSocket();
|
||||
|
||||
bool initTlsServerContext();
|
||||
bool doHandshakeServer();
|
||||
|
||||
inline void writeBuffer(boost::asio::streambuf &buffer) {
|
||||
moveStreambuf(buffer, writeBuffer_);
|
||||
}
|
||||
|
||||
inline const boost::asio::streambuf &readBuffer() & { return readBuffer_; }
|
||||
inline const boost::asio::streambuf &&readBuffer() && {
|
||||
return std::move(readBuffer_);
|
||||
}
|
||||
|
||||
inline boost::uuids::uuid uuid() { return uuid_; }
|
||||
inline boost::uuids::uuid uuid() const { return uuid_; }
|
||||
|
||||
void startAgent();
|
||||
void startServer();
|
||||
|
||||
void doReadAgent();
|
||||
void doReadServer();
|
||||
void handleReadAgent(const boost::system::error_code &error, size_t bytes_transferred);
|
||||
void handleReadServer(const boost::system::error_code &error, size_t bytes_transferred);
|
||||
|
||||
void start();
|
||||
void doRead();
|
||||
void handleRead(const boost::system::error_code &error,
|
||||
size_t bytes_transferred);
|
||||
void doReadRest();
|
||||
void doWrite(auto handlerPointer);
|
||||
void socketShutdown();
|
||||
bool end_, connect_;
|
||||
|
||||
void enableDirectTunnelMode();
|
||||
|
||||
void relayClientToServer();
|
||||
void relayServerToClient();
|
||||
|
||||
void relayAgentToTarget();
|
||||
void relayTargetToAgent();
|
||||
|
||||
std::mutex relayMutex_;
|
||||
|
||||
inline void asyncWriteToAgentConnection(
|
||||
const char *data,
|
||||
std::size_t bytes,
|
||||
std::function<void(const boost::system::error_code &)> done);
|
||||
|
||||
inline void asyncReadFromAgentConnection(
|
||||
std::array<char, BufferSize> &buffer,
|
||||
std::function<void(const boost::system::error_code &, std::size_t)> done);
|
||||
|
||||
inline void asyncWriteToAgentServerConnection(
|
||||
const char *data,
|
||||
std::size_t bytes,
|
||||
std::function<void(const boost::system::error_code &)> done);
|
||||
|
||||
inline void asyncReadFromAgentServerConnection(
|
||||
std::array<char, BufferSize> &buffer,
|
||||
std::function<void(const boost::system::error_code &, std::size_t)> done);
|
||||
|
||||
private:
|
||||
struct HttpUtils {
|
||||
static std::string toLowerCopy(std::string s);
|
||||
static std::string extractHeaders(const std::string &msg);
|
||||
static std::string extractBody(const std::string &msg);
|
||||
static bool parseContentLength(const std::string &headers, std::size_t &value);
|
||||
static bool isChunked(const std::string &headers);
|
||||
|
||||
static bool readRemainingHttpBody(boost::asio::ip::tcp::socket &stream,
|
||||
boost::asio::streambuf &buf,
|
||||
boost::system::error_code &ec);
|
||||
|
||||
static bool readRemainingHttpBody(ssl_stream &stream,
|
||||
boost::asio::streambuf &buf,
|
||||
boost::system::error_code &ec);
|
||||
|
||||
static bool readRemainingHttpBodyImpl(
|
||||
boost::asio::streambuf &buf,
|
||||
boost::system::error_code &ec,
|
||||
const std::function<std::size_t(boost::asio::mutable_buffer,
|
||||
boost::system::error_code &)> &readSome);
|
||||
};
|
||||
|
||||
explicit TCPConnection(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
TCPClient::pointer client);
|
||||
|
||||
bool handleSocks5Handshake();
|
||||
bool readExactFromClient(void *data, std::size_t size);
|
||||
|
||||
void resetTimeout();
|
||||
void cancelTimeout();
|
||||
void onTimeout(const boost::system::error_code &error);
|
||||
|
||||
void startTunnelReadFromClient();
|
||||
void startTunnelPollServer();
|
||||
std::string postTunnelAction(const std::string &action, const std::string &rawBody);
|
||||
std::string makeRelayHostHeader() const;
|
||||
void closeTunnelSession();
|
||||
|
||||
boost::asio::ip::tcp::socket socket_;
|
||||
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_;
|
||||
bool connect_;
|
||||
bool tunnelMode_;
|
||||
bool tunnelClosed_;
|
||||
bool pollInProgress_;
|
||||
std::atomic_bool closed_{false};
|
||||
|
||||
std::array<char, BufferSize> downstreamBuf_;
|
||||
std::array<char, BufferSize> upstreamBuf_;
|
||||
};
|
||||
+40
-15
@@ -1,5 +1,7 @@
|
||||
#include "tcpserver.hpp"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
|
||||
TCPServer::TCPServer(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
@@ -8,8 +10,9 @@ 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();
|
||||
}
|
||||
@@ -17,6 +20,7 @@ TCPServer::TCPServer(boost::asio::io_context &io_context,
|
||||
void TCPServer::startAccept() {
|
||||
auto client = TCPClient::create(io_context_, config_, log_);
|
||||
auto connection = TCPConnection::create(io_context_, config_, log_, client);
|
||||
|
||||
acceptor_.async_accept(
|
||||
connection->socket(),
|
||||
[this, connection](const boost::system::error_code &error) {
|
||||
@@ -24,22 +28,43 @@ void TCPServer::startAccept() {
|
||||
});
|
||||
}
|
||||
|
||||
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) {
|
||||
connection->start();
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,20 @@
|
||||
#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"
|
||||
|
||||
class TCPServer {
|
||||
public:
|
||||
using pointer = boost::shared_ptr<TCPServer>;
|
||||
using pointer = std::shared_ptr<TCPServer>;
|
||||
|
||||
static pointer create(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log) {
|
||||
return pointer(new TCPServer(io_context, config, log));
|
||||
}
|
||||
|
||||
void startAccept();
|
||||
|
||||
private:
|
||||
@@ -29,8 +25,8 @@ private:
|
||||
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:
|
||||
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
|
||||
@@ -3,33 +3,72 @@
|
||||
general:
|
||||
# token: 32 bytes of string. this will be used on agent and server side to encryption
|
||||
token: "af445adb-2434-4975-9445-2c1b2231"
|
||||
# fakeUrl: string
|
||||
# Defines the fake url and endpoint between agent and server
|
||||
fakeUrl: "http://www.adas.com/api01"
|
||||
# method: "HEAD|GET|POST|PUT|DELETE"
|
||||
# Defines with which method
|
||||
# protocol:
|
||||
# Defines the protocol between client and agent
|
||||
# Choose http or socks5
|
||||
protocol: 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: 1
|
||||
# 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: 3
|
||||
# repeatWait: unsigned short(1-65,635)
|
||||
# Defines the loop count which will try to repeat read from socket.
|
||||
# Same as timeWait
|
||||
repeatWait: 25
|
||||
# chunkHeader: String
|
||||
# Defines the chunk header that you want to inform Agent/Server if it is end or not.
|
||||
chunkHeader: "END"
|
||||
timeout: 10
|
||||
# pullTimeout: unsigned short
|
||||
# Defines the timeout for I/O Operation in milliseconds.
|
||||
# Useful to expire serverside read timer.
|
||||
pullTimeout: 1
|
||||
# tunnelEnable: bool
|
||||
# Defines the connection mode between agent and server. If enabled then the traffic
|
||||
# will be TCP/TLS tunnel like.
|
||||
tunnelEnable: false
|
||||
# connectionReuse: bool
|
||||
# If true then it will use same connection between agent and server to handle client request
|
||||
# If false then it will create new connection for each request between agent and server
|
||||
connectionReuse: true
|
||||
# tlsEnable: bool
|
||||
# It enables or disables tls between agent and server
|
||||
tlsEnable: true
|
||||
# tlsVerifyPeer: bool
|
||||
# Use it to controll if the certificate should be validated or not
|
||||
tlsVerifyPeer: false
|
||||
# Use following configurations to specify the key and cert which will be used between agent and server
|
||||
tlsCertFile: "/etc/nipovpn/server.crt"
|
||||
tlsKeyFile: "/etc/nipovpn/server.key"
|
||||
tlsCaFile: ""
|
||||
|
||||
|
||||
# This block is to define log directives
|
||||
log:
|
||||
# logLevel: "INFO|TRACE|DEBUG"
|
||||
logLevel: "DEBUG"
|
||||
logLevel: "INFO"
|
||||
# logFile: "/var/log/nipo/nipo.log"
|
||||
# Path of log file
|
||||
logFile: "/var/log/nipovpn/nipovpn.log"
|
||||
@@ -43,6 +82,7 @@ server:
|
||||
# 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 +98,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.
Reference in new issue
Block a user