Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
edc38248bf |
No files matched your search
@@ -1,96 +0,0 @@
|
||||
name: Build and Release Debian Package - DEV
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- dev
|
||||
paths:
|
||||
- 'core/src/**'
|
||||
- 'core/**'
|
||||
- 'nipovpn/**'
|
||||
- '.github/workflows/debian-dev.yml'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
PACKAGE_VERSION: 0.1.${{ github.run_number }}
|
||||
PACKAGE_FILE: nipovpn_dev_0.1.${{ github.run_number }}_amd64.deb
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
steps:
|
||||
- name: Checkout source code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- 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 binary
|
||||
run: |
|
||||
rm -rf build
|
||||
mkdir -p build
|
||||
cd build
|
||||
cmake -DCMAKE_BUILD_TYPE=Release ..
|
||||
make -j$(nproc)
|
||||
|
||||
- name: Build Debian package
|
||||
run: |
|
||||
mkdir -p nipovpn/usr/bin
|
||||
|
||||
cp build/core/nipovpn nipovpn/usr/bin/nipovpn
|
||||
chmod 755 nipovpn/usr/bin/nipovpn
|
||||
|
||||
sed -i -E "s/^Version[[:space:]]*:.*/Version: ${PACKAGE_VERSION}/" nipovpn/DEBIAN/control
|
||||
|
||||
echo "Final control file:"
|
||||
cat nipovpn/DEBIAN/control
|
||||
|
||||
grep "^Version: ${PACKAGE_VERSION}$" nipovpn/DEBIAN/control
|
||||
|
||||
dpkg-deb --build nipovpn "build/${PACKAGE_FILE}"
|
||||
|
||||
- name: Show package information
|
||||
run: |
|
||||
dpkg -I "build/${PACKAGE_FILE}"
|
||||
dpkg -c "build/${PACKAGE_FILE}"
|
||||
|
||||
- name: Upload Debian package as artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: nipovpn-dev-deb
|
||||
path: build/${{ env.PACKAGE_FILE }}
|
||||
|
||||
release:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Download Debian package artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: nipovpn-dev-deb
|
||||
path: ./
|
||||
|
||||
- name: Create DEV GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: dev-v${{ env.PACKAGE_VERSION }}
|
||||
name: DEV Version v${{ env.PACKAGE_VERSION }}
|
||||
prerelease: true
|
||||
files: ${{ env.PACKAGE_FILE }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
@@ -1,96 +0,0 @@
|
||||
name: Build and Release Debian Package - MORI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- mori
|
||||
paths:
|
||||
- 'core/src/**'
|
||||
- 'core/**'
|
||||
- 'nipovpn/**'
|
||||
- '.github/workflows/debian-mori.yml'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
PACKAGE_VERSION: 0.2.${{ github.run_number }}
|
||||
PACKAGE_FILE: nipovpn_mori_0.2.${{ github.run_number }}_amd64.deb
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
steps:
|
||||
- name: Checkout source code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- 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 binary
|
||||
run: |
|
||||
rm -rf build
|
||||
mkdir -p build
|
||||
cd build
|
||||
cmake -DCMAKE_BUILD_TYPE=Release ..
|
||||
make -j$(nproc)
|
||||
|
||||
- name: Build Debian package
|
||||
run: |
|
||||
mkdir -p nipovpn/usr/bin
|
||||
|
||||
cp build/core/nipovpn nipovpn/usr/bin/nipovpn
|
||||
chmod 755 nipovpn/usr/bin/nipovpn
|
||||
|
||||
sed -i -E "s/^Version[[:space:]]*:.*/Version: ${PACKAGE_VERSION}/" nipovpn/DEBIAN/control
|
||||
|
||||
echo "Final control file:"
|
||||
cat nipovpn/DEBIAN/control
|
||||
|
||||
grep "^Version: ${PACKAGE_VERSION}$" nipovpn/DEBIAN/control
|
||||
|
||||
dpkg-deb --build nipovpn "build/${PACKAGE_FILE}"
|
||||
|
||||
- name: Show package information
|
||||
run: |
|
||||
dpkg -I "build/${PACKAGE_FILE}"
|
||||
dpkg -c "build/${PACKAGE_FILE}"
|
||||
|
||||
- name: Upload Debian package as artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: nipovpn-mori-deb
|
||||
path: build/${{ env.PACKAGE_FILE }}
|
||||
|
||||
release:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Download Debian package artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: nipovpn-mori-deb
|
||||
path: ./
|
||||
|
||||
- name: Create MORI GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: mori-v${{ env.PACKAGE_VERSION }}
|
||||
name: MORI Version v${{ env.PACKAGE_VERSION }}
|
||||
prerelease: true
|
||||
files: ${{ env.PACKAGE_FILE }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
@@ -1,21 +1,12 @@
|
||||
name: Build and Release Debian Package - MAIN
|
||||
name: Build and Release Debian Package
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- 'core/src/**'
|
||||
- 'core/**'
|
||||
- 'nipovpn/**'
|
||||
- '.github/workflows/debian.yml'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
PACKAGE_VERSION: 1.1.${{ github.run_number }}
|
||||
PACKAGE_FILE: nipovpn_1.1.${{ github.run_number }}_amd64.deb
|
||||
- morteza/debian
|
||||
pull_request:
|
||||
branches:
|
||||
- morteza/debian
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -23,78 +14,63 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout source code
|
||||
uses: actions/checkout@v4
|
||||
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
|
||||
sudo apt-get install -y dpkg-dev build-essential lintian fakeroot devscripts cmake libssl-dev libboost-all-dev libyaml-cpp-dev
|
||||
|
||||
- name: Build binary
|
||||
- name: Build the package
|
||||
run: |
|
||||
rm -rf build
|
||||
mkdir -p build
|
||||
cd build
|
||||
cmake -DCMAKE_BUILD_TYPE=Release ..
|
||||
cmake -DCMAKE_BUILD_TYPE=Debug ..
|
||||
make -j$(nproc)
|
||||
|
||||
- name: Build Debian package
|
||||
run: |
|
||||
mkdir -p nipovpn/usr/bin
|
||||
|
||||
cd ..
|
||||
mkdir -p nipovpn/usr/bin/
|
||||
cp build/core/nipovpn nipovpn/usr/bin/nipovpn
|
||||
chmod 755 nipovpn/usr/bin/nipovpn
|
||||
dpkg-deb --build nipovpn/ build/nipovpn.deb
|
||||
|
||||
sed -i -E "s/^Version[[:space:]]*:.*/Version: ${PACKAGE_VERSION}/" nipovpn/DEBIAN/control
|
||||
|
||||
echo "Final control file:"
|
||||
cat nipovpn/DEBIAN/control
|
||||
|
||||
grep "^Version: ${PACKAGE_VERSION}$" nipovpn/DEBIAN/control
|
||||
|
||||
dpkg-deb --build nipovpn "build/${PACKAGE_FILE}"
|
||||
|
||||
- name: Show package information
|
||||
run: |
|
||||
dpkg -I "build/${PACKAGE_FILE}"
|
||||
dpkg -c "build/${PACKAGE_FILE}"
|
||||
|
||||
- name: Upload Debian package as artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
- name: Upload the Debian nipovpn as an artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: nipovpn-main-deb
|
||||
path: build/${{ env.PACKAGE_FILE }}
|
||||
name: nipovpn
|
||||
path: build/nipovpn.deb
|
||||
|
||||
- name: Show nipovpn information
|
||||
run: |
|
||||
dpkg -I build/nipovpn.deb
|
||||
|
||||
release:
|
||||
needs: build
|
||||
needs: build # This ensures that the release job runs after the build job
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Download Debian package artifact
|
||||
uses: actions/download-artifact@v4
|
||||
- name: Download build artifact
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: nipovpn-main-deb
|
||||
path: ./
|
||||
name: nipovpn
|
||||
path: ./ # Download the artifact to the current directory
|
||||
|
||||
- name: Check 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: false
|
||||
files: ${{ env.PACKAGE_FILE }}
|
||||
- name: Create GitHub Release
|
||||
id: create_release
|
||||
uses: actions/create-release@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }} # GitHub token to authenticate the release
|
||||
with:
|
||||
tag_name: 'v1.0.${{ github.run_number }}' # Example versioning
|
||||
release_name: Release ${{ github.run_number }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
|
||||
- name: List build directory contents
|
||||
run: ls -la
|
||||
|
||||
- name: Upload Debian Package to Release
|
||||
uses: actions/upload-release-asset@v1
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: ./nipovpn.deb
|
||||
asset_name: nipovpn.deb
|
||||
asset_content_type: application/octet-stream
|
||||
@@ -36,4 +36,3 @@ temp
|
||||
build
|
||||
.idea
|
||||
/cmake-build-debug/
|
||||
test
|
||||
+1
-1
@@ -11,7 +11,7 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -ggdb")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -MMD -MP")
|
||||
|
||||
# https://cmake.org/cmake/help/latest/module/FindBoost.html
|
||||
find_package(Boost REQUIRED COMPONENTS regex OPTIONAL_COMPONENTS system)
|
||||
find_package(Boost REQUIRED COMPONENTS system regex)
|
||||
|
||||
# /usr/local/lib/cmake/yaml-cpp/yaml-cpp-config.cmake
|
||||
# declared variables: YAML_CPP_INCLUDE_DIR & YAML_CPP_LIBRARY_DIR
|
||||
|
||||
+4
-5
@@ -13,8 +13,7 @@ If you're new, we encourage you to take a look at [issues](https://github.com/Mo
|
||||
0. Create a GitHub issue proposing a new example and make sure it's substantially different from an existing one.
|
||||
1. Fork the repo and create your branch from `dev`.
|
||||
2. Make your changes.
|
||||
3. Always use `scripts/format.sh` to format code.
|
||||
4. Always build and test your branch.
|
||||
5. Write proper comments
|
||||
6. Creat a pull request to dev.
|
||||
7. Wait for response
|
||||
3. Always build and test your branch.
|
||||
4. Write proper comments
|
||||
5. Creat a pull request to dev.
|
||||
6. Wait for response
|
||||
@@ -1,4 +1,4 @@
|
||||
# NipoVPN
|
||||
# NipoVPN (Not ready yet :D)
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -50,22 +50,67 @@ Create the log directory and log file
|
||||
Run it
|
||||
```bash
|
||||
sudo build/core/nipovpn server nipovpn/etc/nipovpn/config.yaml
|
||||
2024-08-02_15:30:07 [INFO] Config initialized in server mode
|
||||
2024-08-02_15:30:07 [INFO]
|
||||
Config :
|
||||
General :
|
||||
fakeUrl: http://www.adas.com/api01
|
||||
method: HEAD
|
||||
timeWait: 0
|
||||
repeatWait: 1
|
||||
Log :
|
||||
logLevel: DEBUG
|
||||
logFile: /var/log/nipovpn/nipovpn.log
|
||||
server :
|
||||
threads: 4
|
||||
listenIp: 0.0.0.0
|
||||
listenPort: 443
|
||||
agent :
|
||||
threads: 4
|
||||
listenIp: 0.0.0.0
|
||||
listenPort: 8080
|
||||
serverIp: 127.0.0.1
|
||||
serverPort: 443
|
||||
token: af445adb-2434-4975-9445-2c1b2231
|
||||
httpVersion: 1.1
|
||||
userAgent: NipoAgent
|
||||
```
|
||||
|
||||
### Package
|
||||
|
||||
#### 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.
|
||||
Currently it is only available for debian based Linuxs and fully tested on ubuntu 24.04
|
||||
You can simply install the package
|
||||
```bash
|
||||
[~]>$ wget https://raw.githubusercontent.com/MortezaBashsiz/nipovpn/main/files/deb/nipovpn.deb
|
||||
[~]>$ 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
|
||||
[~]>$ sudo nipovpn server /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
|
||||
```
|
||||
+155
-136
@@ -1,7 +1,6 @@
|
||||
#include "agenthandler.hpp"
|
||||
|
||||
#include <sstream>
|
||||
|
||||
// Constructor for the AgentHandler class
|
||||
AgentHandler::AgentHandler(boost::asio::streambuf &readBuffer,
|
||||
boost::asio::streambuf &writeBuffer,
|
||||
const std::shared_ptr<Config> &config,
|
||||
@@ -9,150 +8,170 @@ AgentHandler::AgentHandler(boost::asio::streambuf &readBuffer,
|
||||
const TCPClient::pointer &client,
|
||||
const std::string &clientConnStr,
|
||||
boost::uuids::uuid uuid)
|
||||
: config_(config),
|
||||
log_(log),
|
||||
client_(client),
|
||||
readBuffer_(readBuffer),
|
||||
writeBuffer_(writeBuffer),
|
||||
: config_(config), // Initialize configuration
|
||||
log_(log), // Initialize logging
|
||||
client_(client), // Initialize TCP client
|
||||
readBuffer_(readBuffer), // Reference to the read buffer
|
||||
writeBuffer_(writeBuffer),// Reference to the write buffer
|
||||
request_(HTTP::create(config, log, readBuffer, uuid)),
|
||||
clientConnStr_(clientConnStr),
|
||||
uuid_(uuid) {
|
||||
end_ = false;
|
||||
connect_ = false;
|
||||
}
|
||||
clientConnStr_(clientConnStr),// Initialize client connection string
|
||||
uuid_(uuid) {}
|
||||
|
||||
// Destructor for the AgentHandler class
|
||||
AgentHandler::~AgentHandler() {}
|
||||
|
||||
// Main handler function for processing requests
|
||||
void AgentHandler::handle() {
|
||||
std::lock_guard lock(mutex_);
|
||||
|
||||
if (!request_->detectType()) {
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [NOT HTTP Request] [Request] : " +
|
||||
streambufToString(readBuffer_),
|
||||
Log::Level::DEBUG);
|
||||
client_->socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
if (request_->parsedHttpRequest().target().length() > 0) {
|
||||
log_->write("[" + to_string(uuid_) + "] [FORWARD] [SRC " + clientConnStr_ + "] [DST " +
|
||||
std::string(request_->parsedHttpRequest().target()) + "]",
|
||||
Log::Level::INFO);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(mutex_);// Lock the mutex for thread safety
|
||||
|
||||
// Initialize encryption status
|
||||
BoolStr encryption{false, std::string("FAILED")};
|
||||
encryption = aes256Encrypt(hexStreambufToStr(readBuffer_), config_->general().token);
|
||||
if (!encryption.ok) {
|
||||
|
||||
// Encrypt the request data from the read buffer
|
||||
encryption =
|
||||
aes256Encrypt(hexStreambufToStr(readBuffer_), config_->agent().token);
|
||||
|
||||
if (encryption.ok) {
|
||||
// Log successful token validation
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Encryption Done]", Log::Level::DEBUG);
|
||||
|
||||
// Generate a new HTTP POST request string with the encrypted message
|
||||
std::string newReq(
|
||||
request_->genHttpPostReqString(encode64(encryption.message)));
|
||||
|
||||
// Check if the request type is valid
|
||||
if (request_->detectType()) {
|
||||
// Log the HTTP request details
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Request] : " + request_->toString(),
|
||||
Log::Level::DEBUG);
|
||||
|
||||
// Log the client connention string and HTTP request target
|
||||
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 the client socket is not open or the request type is HTTP or CONNECT
|
||||
if (!client_->socket().is_open() ||
|
||||
request_->httpType() == HTTP::HttpType::http ||
|
||||
request_->httpType() == HTTP::HttpType::connect) {
|
||||
// Connect the TCP client to the server
|
||||
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);
|
||||
}
|
||||
|
||||
// Check for connection errors
|
||||
if (ec) {
|
||||
log_->write(std::string("[" + to_string(uuid_) + "] [AgentHandler handle] Connection error: ") +
|
||||
ec.message(),
|
||||
Log::Level::ERROR);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Copy the new request to the read buffer
|
||||
copyStringToStreambuf(newReq, readBuffer_);
|
||||
|
||||
// Log the request to be sent to the server
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Request To Server] : \n" + newReq,
|
||||
Log::Level::DEBUG);
|
||||
|
||||
// Write the request to the client socket and initiate a read
|
||||
// operation
|
||||
client_->doWrite(readBuffer_);
|
||||
client_->doRead();
|
||||
|
||||
// Check if there is data available in the read buffer
|
||||
if (client_->readBuffer().size() > 0) {
|
||||
// If the HTTP request type is not CONNECT
|
||||
if (request_->httpType() != HTTP::HttpType::connect) {
|
||||
// Create an HTTP response handler
|
||||
HTTP::pointer response =
|
||||
HTTP::create(config_, log_, client_->readBuffer(), uuid_);
|
||||
|
||||
// Parse the HTTP response
|
||||
if (response->parseHttpResp()) {
|
||||
// Log the response details
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) + "] [AgentHandler handle] [Response] : " + response->restoString(),
|
||||
Log::Level::DEBUG);
|
||||
|
||||
// Decrypt the response body
|
||||
BoolStr decryption{false, std::string("FAILED")};
|
||||
decryption =
|
||||
aes256Decrypt(decode64(boost::lexical_cast<std::string>(
|
||||
response->parsedHttpResponse().body())),
|
||||
config_->agent().token);
|
||||
|
||||
// Check if decryption was successful
|
||||
if (decryption.ok) {
|
||||
// Copy the decrypted message to the write buffer
|
||||
copyStringToStreambuf(decryption.message, writeBuffer_);
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Decryption Done]", Log::Level::DEBUG);
|
||||
} else {
|
||||
// Log decryption failure and close the socket
|
||||
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 if the response is not an HTTP response
|
||||
log_->write(
|
||||
"[AgentHandler handle] [NOT HTTP Response] "
|
||||
"[Response] : " +
|
||||
streambufToString(client_->readBuffer()),
|
||||
Log::Level::DEBUG);
|
||||
}
|
||||
} else {
|
||||
// Log the response to a CONNECT request
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Response to connect] : \n" +
|
||||
streambufToString(client_->readBuffer()),
|
||||
Log::Level::DEBUG);
|
||||
|
||||
// Move the response from the read buffer to the write buffer
|
||||
moveStreambuf(client_->readBuffer(), writeBuffer_);
|
||||
}
|
||||
} else {
|
||||
// Close the socket if no data is available
|
||||
client_->socket().close();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// Log if the request is not a valid HTTP request
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [NOT HTTP Request] [Request] : " +
|
||||
streambufToString(readBuffer_),
|
||||
Log::Level::DEBUG);
|
||||
// Close the socket if no data is available
|
||||
client_->socket().close();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// Log encryption failure and close the socket
|
||||
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Encryption Failed] : [ " +
|
||||
encryption.message + "] ",
|
||||
Log::Level::DEBUG);
|
||||
client_->socketShutdown();
|
||||
log_->write(
|
||||
"[AgentHandler handle] [Encryption Failed] : " +
|
||||
client_->socket().remote_endpoint().address().to_string() + ":" +
|
||||
std::to_string(client_->socket().remote_endpoint().port()) + "] ",
|
||||
Log::Level::INFO);
|
||||
// Close the socket if no data is available
|
||||
client_->socket().close();
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
+60
-16
@@ -1,4 +1,6 @@
|
||||
#pragma once
|
||||
#ifndef AGENTHADLER_HPP
|
||||
#define AGENTHADLER_HPP
|
||||
|
||||
#include <boost/beast/core/detail/base64.hpp>
|
||||
#include <memory>
|
||||
@@ -9,11 +11,28 @@
|
||||
#include "log.hpp"
|
||||
#include "tcpclient.hpp"
|
||||
|
||||
|
||||
/**
|
||||
* @brief This class handles requests when the process is running in agent
|
||||
* mode.
|
||||
*
|
||||
* The AgentHandler processes HTTP requests by encrypting/decrypting data,
|
||||
* forwarding requests to a TCP server, and handling responses.
|
||||
*/
|
||||
class AgentHandler : private Uncopyable {
|
||||
public:
|
||||
using pointer = std::shared_ptr<AgentHandler>;
|
||||
using pointer = std::shared_ptr<AgentHandler>;///< Shared pointer type for
|
||||
///< AgentHandler
|
||||
|
||||
/**
|
||||
* @brief Factory method to create an instance of AgentHandler.
|
||||
*
|
||||
* @param readBuffer The buffer to read incoming data from.
|
||||
* @param writeBuffer The buffer to write outgoing data to.
|
||||
* @param config Shared configuration object.
|
||||
* @param log Shared logging object.
|
||||
* @param client Shared pointer to a TCP client.
|
||||
* @return pointer A shared pointer to the created AgentHandler instance.
|
||||
*/
|
||||
static pointer create(boost::asio::streambuf &readBuffer,
|
||||
boost::asio::streambuf &writeBuffer,
|
||||
const std::shared_ptr<Config> &config,
|
||||
@@ -25,18 +44,41 @@ public:
|
||||
client, clientConnStr, uuid));
|
||||
}
|
||||
|
||||
~AgentHandler();
|
||||
~AgentHandler();///< Destructor for AgentHandler
|
||||
|
||||
/**
|
||||
* @brief Handles the HTTP request.
|
||||
*
|
||||
* This function is called from the TCPConnection::handleRead function.
|
||||
* It processes the request, encrypts or decrypts data as needed,
|
||||
* forwards requests to the server, and handles responses.
|
||||
*/
|
||||
void handle();
|
||||
|
||||
/**
|
||||
* @brief Gets a reference to the HTTP request object.
|
||||
*
|
||||
* @return The HTTP request object.
|
||||
*/
|
||||
inline const HTTP::pointer &request() & { return request_; }
|
||||
|
||||
/**
|
||||
* @brief Gets a rvalue reference to the HTTP request object.
|
||||
*
|
||||
* @return The HTTP request object (rvalue).
|
||||
*/
|
||||
inline const HTTP::pointer &&request() && { return std::move(request_); }
|
||||
|
||||
bool end_;
|
||||
bool connect_;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Constructs an AgentHandler instance.
|
||||
*
|
||||
* @param readBuffer The buffer to read incoming data from.
|
||||
* @param writeBuffer The buffer to write outgoing data to.
|
||||
* @param config Shared configuration object.
|
||||
* @param log Shared logging object.
|
||||
* @param client Shared pointer to a TCP client.
|
||||
*/
|
||||
AgentHandler(boost::asio::streambuf &readBuffer,
|
||||
boost::asio::streambuf &writeBuffer,
|
||||
const std::shared_ptr<Config> &config,
|
||||
@@ -45,16 +87,18 @@ private:
|
||||
const std::string &clientConnStr,
|
||||
boost::uuids::uuid uuid);
|
||||
|
||||
std::string relayHostHeader(const std::shared_ptr<Config> &config);
|
||||
const std::shared_ptr<Config> &config_;
|
||||
const std::shared_ptr<Log> &log_;
|
||||
const TCPClient::pointer &client_;
|
||||
boost::asio::streambuf &readBuffer_;
|
||||
boost::asio::streambuf &writeBuffer_;
|
||||
HTTP::pointer request_;
|
||||
const std::string &clientConnStr_;
|
||||
const std::shared_ptr<Config> &config_;///< Shared configuration object
|
||||
const std::shared_ptr<Log> &log_; ///< Shared logging object
|
||||
const TCPClient::pointer &client_; ///< Shared pointer to a TCP client
|
||||
boost::asio::streambuf &readBuffer_,
|
||||
&writeBuffer_; ///< References to buffers for reading and writing data
|
||||
HTTP::pointer request_;///< HTTP request object
|
||||
const std::string
|
||||
&clientConnStr_;///< socket client connection string "ip:port"
|
||||
|
||||
boost::uuids::uuid uuid_;
|
||||
|
||||
std::mutex mutex_;
|
||||
};
|
||||
std::mutex mutex_;///< Mutex to make the class thread-safe
|
||||
};
|
||||
|
||||
#endif /* AGENTHADLER_HPP */
|
||||
+31
-119
@@ -1,6 +1,11 @@
|
||||
#include "config.hpp"
|
||||
|
||||
|
||||
/**
|
||||
* @brief Constructs a Config instance with specified mode and file path.
|
||||
*
|
||||
* @param mode The operational mode of the application (server or agent).
|
||||
* @param filePath The path to the configuration file.
|
||||
*/
|
||||
Config::Config(const RunMode &mode, const std::string &filePath)
|
||||
: runMode_(mode),
|
||||
filePath_(filePath),
|
||||
@@ -8,19 +13,11 @@ Config::Config(const RunMode &mode, const std::string &filePath)
|
||||
threads_(0),
|
||||
listenIp_("127.0.0.1"),
|
||||
listenPort_(0),
|
||||
general_({configYaml_["general"]["token"].as<std::string>(),
|
||||
configYaml_["general"]["fakeUrls"].as<std::vector<std::string>>(),
|
||||
configYaml_["general"]["methods"].as<std::vector<std::string>>(),
|
||||
configYaml_["general"]["endPoints"].as<std::vector<std::string>>(),
|
||||
general_({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"]["pullTimeout"].as<unsigned short>(),
|
||||
configYaml_["general"]["tunnelEnable"].as<bool>(false),
|
||||
configYaml_["general"]["connectionReuse"].as<bool>(false),
|
||||
configYaml_["general"]["tlsEnable"].as<bool>(false),
|
||||
configYaml_["general"]["tlsVerifyPeer"].as<bool>(false),
|
||||
configYaml_["general"]["tlsCertFile"].as<std::string>(""),
|
||||
configYaml_["general"]["tlsKeyFile"].as<std::string>(""),
|
||||
configYaml_["general"]["tlsCaFile"].as<std::string>("")}),
|
||||
configYaml_["general"]["repeatWait"].as<unsigned short>()}),
|
||||
log_({configYaml_["log"]["logLevel"].as<std::string>(),
|
||||
configYaml_["log"]["logFile"].as<std::string>()}),
|
||||
server_({configYaml_["server"]["threads"].as<unsigned short>(),
|
||||
@@ -31,18 +28,16 @@ Config::Config(const RunMode &mode, const std::string &filePath)
|
||||
configYaml_["agent"]["listenPort"].as<unsigned short>(),
|
||||
configYaml_["agent"]["serverIp"].as<std::string>(),
|
||||
configYaml_["agent"]["serverPort"].as<unsigned short>(),
|
||||
configYaml_["agent"]["token"].as<std::string>(),
|
||||
configYaml_["agent"]["httpVersion"].as<std::string>(),
|
||||
configYaml_["agent"]["userAgent"].as<std::string>()}) {
|
||||
|
||||
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;
|
||||
@@ -51,89 +46,55 @@ Config::Config(const RunMode &mode, const std::string &filePath)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Copy constructor for Config.
|
||||
*
|
||||
* @param config A shared pointer to another Config instance.
|
||||
*/
|
||||
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()) {}
|
||||
|
||||
/**
|
||||
* @brief Destructor for Config.
|
||||
*/
|
||||
Config::~Config() = default;
|
||||
|
||||
/**
|
||||
* @brief Returns a string representation of the current configuration.
|
||||
*
|
||||
* @return A string describing the configuration settings.
|
||||
*/
|
||||
std::string Config::toString() const {
|
||||
std::lock_guard<std::mutex> lock(configMutex_);
|
||||
|
||||
std::stringstream ss;
|
||||
|
||||
ss << "\nConfig :\n"
|
||||
<< " General :\n"
|
||||
<< " token: " << general_.token << "\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"
|
||||
<< " fakeUrl: " << general_.fakeUrl << "\n"
|
||||
<< " method: " << general_.method << "\n"
|
||||
<< " timeWait: " << general_.timeWait << "\n"
|
||||
<< " timeout: " << general_.timeout << "\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"
|
||||
|
||||
<< " repeatWait: " << general_.repeatWait << "\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"
|
||||
<< " serverIp: " << agent_.serverIp << "\n"
|
||||
<< " serverPort: " << agent_.serverPort << "\n"
|
||||
<< " token: " << agent_.token << "\n"
|
||||
<< " httpVersion: " << agent_.httpVersion << "\n"
|
||||
<< " userAgent: " << agent_.userAgent << "\n";
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
@@ -199,7 +160,6 @@ 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";
|
||||
@@ -209,51 +169,3 @@ 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)];
|
||||
}
|
||||
+13
-40
@@ -1,37 +1,25 @@
|
||||
#pragma once
|
||||
#ifndef CONFIG_HPP
|
||||
#define CONFIG_HPP
|
||||
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <random>
|
||||
#include <mutex>// Include mutex header for thread safety
|
||||
#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::vector<std::string> fakeUrls;
|
||||
std::vector<std::string> methods;
|
||||
std::vector<std::string> endPoints;
|
||||
std::string fakeUrl;
|
||||
std::string method;
|
||||
unsigned int timeWait;
|
||||
unsigned short timeout;
|
||||
unsigned short pullTimeout;
|
||||
bool tunnelEnable;
|
||||
bool connectionReuse;
|
||||
bool tlsEnable;
|
||||
bool tlsVerifyPeer;
|
||||
std::string tlsCertFile;
|
||||
std::string tlsKeyFile;
|
||||
std::string tlsCaFile;
|
||||
unsigned short repeatWait;
|
||||
};
|
||||
|
||||
struct Log {
|
||||
@@ -51,6 +39,7 @@ private:
|
||||
unsigned short listenPort;
|
||||
std::string serverIp;
|
||||
unsigned short serverPort;
|
||||
std::string token;
|
||||
std::string httpVersion;
|
||||
std::string userAgent;
|
||||
};
|
||||
@@ -58,12 +47,11 @@ private:
|
||||
const RunMode &runMode_;
|
||||
std::string filePath_;
|
||||
const YAML::Node configYaml_;
|
||||
|
||||
unsigned short threads_;
|
||||
std::string listenIp_;
|
||||
unsigned short listenPort_;
|
||||
|
||||
mutable std::mutex configMutex_;
|
||||
mutable std::mutex configMutex_;// Mutex for thread safety
|
||||
|
||||
explicit Config(const RunMode &mode, const std::string &filePath);
|
||||
|
||||
@@ -80,37 +68,22 @@ 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;
|
||||
|
||||
void threads(unsigned short threads);
|
||||
|
||||
const std::string &listenIp() const;
|
||||
|
||||
void listenIp(const std::string &ip);
|
||||
|
||||
const unsigned short &listenPort() const;
|
||||
|
||||
void listenPort(unsigned short port);
|
||||
|
||||
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;
|
||||
};
|
||||
#endif /* CONFIG_HPP */
|
||||
+140
-40
@@ -1,4 +1,6 @@
|
||||
#pragma once
|
||||
#ifndef GENERAL_HPP
|
||||
#define GENERAL_HPP
|
||||
|
||||
#include <openssl/conf.h>
|
||||
#include <openssl/err.h>
|
||||
@@ -23,6 +25,12 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
/**
|
||||
* @brief Base class to prevent copying of derived classes.
|
||||
*
|
||||
* This class is used to make derived classes uncopyable by deleting the
|
||||
* copy constructor and copy assignment operator.
|
||||
*/
|
||||
class Uncopyable {
|
||||
public:
|
||||
Uncopyable() = default;
|
||||
@@ -32,26 +40,53 @@ private:
|
||||
Uncopyable &operator=(const Uncopyable &) = delete;
|
||||
};
|
||||
|
||||
inline void OUT(const auto &message) {
|
||||
std::cout << "OUT OUT OUT OUT OUT OUT OUT OUT : " << message
|
||||
/*
|
||||
* FUCK function prints it on screen
|
||||
*/
|
||||
inline void FUCK(const auto &message) {
|
||||
std::cout << "FUCK FUCK FUCK FUCK FUCK FUCK FUCK FUCK : " << message
|
||||
<< std::endl;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Structure to return a boolean status and a message.
|
||||
*
|
||||
* This is used for returning status and messages from functions, particularly
|
||||
* those dealing with encryption or configuration validation.
|
||||
*/
|
||||
struct BoolStr {
|
||||
bool ok;
|
||||
std::string message;
|
||||
bool ok; ///< Indicates success or failure.
|
||||
std::string message;///< Message describing the result or error.
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Checks if a file exists.
|
||||
*
|
||||
* @param name The name of the file to check.
|
||||
* @return true if the file exists, false otherwise.
|
||||
*/
|
||||
inline bool fileExists(const std::string &name) {
|
||||
std::ifstream file(name.c_str());
|
||||
return file.good();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts a `boost::asio::streambuf` to a `std::string`.
|
||||
*
|
||||
* @param buff The streambuf to convert.
|
||||
* @return The resulting string.
|
||||
*/
|
||||
inline std::string streambufToString(const boost::asio::streambuf &buff) {
|
||||
return {boost::asio::buffers_begin(buff.data()),
|
||||
boost::asio::buffers_begin(buff.data()) + buff.size()};
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Copies a string to a `boost::asio::streambuf`.
|
||||
*
|
||||
* @param inputStr The string to copy.
|
||||
* @param buff The target streambuf.
|
||||
*/
|
||||
inline void copyStringToStreambuf(const std::string &inputStr,
|
||||
boost::asio::streambuf &buff) {
|
||||
buff.consume(buff.size());
|
||||
@@ -59,6 +94,12 @@ inline void copyStringToStreambuf(const std::string &inputStr,
|
||||
os << inputStr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Moves data from one `boost::asio::streambuf` to another.
|
||||
*
|
||||
* @param source The source streambuf.
|
||||
* @param target The target streambuf.
|
||||
*/
|
||||
inline void moveStreambuf(boost::asio::streambuf &source,
|
||||
boost::asio::streambuf &target) {
|
||||
auto bytes_copied =
|
||||
@@ -67,6 +108,12 @@ inline void moveStreambuf(boost::asio::streambuf &source,
|
||||
source.consume(source.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Copies data from one `boost::asio::streambuf` to another.
|
||||
*
|
||||
* @param source The source streambuf.
|
||||
* @param target The target streambuf.
|
||||
*/
|
||||
inline void copyStreambuf(boost::asio::streambuf &source,
|
||||
boost::asio::streambuf &target) {
|
||||
auto bytes_copied =
|
||||
@@ -74,36 +121,57 @@ inline void copyStreambuf(boost::asio::streambuf &source,
|
||||
target.commit(bytes_copied);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts a hex array to a string.
|
||||
*
|
||||
* @param data Pointer to the data array.
|
||||
* @param size The size of the data array.
|
||||
* @return The resulting string.
|
||||
*/
|
||||
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 int hexToInt(const std::string &hexString) {
|
||||
/**
|
||||
* @brief Converts a hex string to an integer.
|
||||
*
|
||||
* @param hexString The hex string.
|
||||
* @return The resulting integer.
|
||||
*/
|
||||
inline unsigned short hexToInt(const std::string &hexString) {
|
||||
unsigned short result;
|
||||
std::stringstream hexStr(hexString);
|
||||
hexStr >> std::hex >> result;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts a hex string to ASCII.
|
||||
*
|
||||
* @param hex The hex string.
|
||||
* @return The resulting ASCII string.
|
||||
*/
|
||||
inline std::string hexToASCII(const std::string &hex) {
|
||||
std::string ascii;
|
||||
|
||||
for (size_t i = 0; i < hex.length(); i += 2) {
|
||||
std::string part = hex.substr(i, 2);
|
||||
char ch = static_cast<char>(stoul(part, nullptr, 16));
|
||||
ascii += ch;
|
||||
}
|
||||
|
||||
return ascii;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts a character to its hex value.
|
||||
*
|
||||
* @param c The character.
|
||||
* @return The hex value.
|
||||
*/
|
||||
inline unsigned char charToHex(char c) {
|
||||
if ('0' <= c && c <= '9') return c - '0';
|
||||
if ('A' <= c && c <= 'F') return c - 'A' + 10;
|
||||
@@ -111,46 +179,62 @@ inline unsigned char charToHex(char c) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts a hex string to a hex array.
|
||||
*
|
||||
* @param hexStr The hex string.
|
||||
* @return The resulting hex array.
|
||||
*/
|
||||
inline std::vector<unsigned char> strToHexArr(const std::string &hexStr) {
|
||||
std::vector<unsigned char> result(hexStr.size() / 2);
|
||||
|
||||
for (std::size_t i = 0; i < hexStr.size() / 2; ++i) {
|
||||
for (std::size_t i = 0; i < hexStr.size() / 2; ++i)
|
||||
result[i] = 16 * charToHex(hexStr[2 * i]) + charToHex(hexStr[2 * i + 1]);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts a hex `boost::asio::streambuf` to a string.
|
||||
*
|
||||
* @param buff The streambuf.
|
||||
* @return The resulting string.
|
||||
*/
|
||||
inline std::string hexStreambufToStr(const boost::asio::streambuf &buff) {
|
||||
return hexArrToStr(
|
||||
reinterpret_cast<const unsigned char *>(streambufToString(buff).c_str()),
|
||||
buff.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Splits a string by a specified token.
|
||||
*
|
||||
* @param str The string to split.
|
||||
* @param token The token to split by.
|
||||
* @return A vector of strings resulting from the split.
|
||||
*/
|
||||
inline std::vector<std::string> splitString(const std::string &str,
|
||||
const std::string &delimiter) {
|
||||
const std::string &token) {
|
||||
std::vector<std::string> result;
|
||||
std::string tempStr = str;
|
||||
|
||||
while (!tempStr.empty()) {
|
||||
size_t index = tempStr.find(delimiter);
|
||||
|
||||
size_t index = tempStr.find(token);
|
||||
if (index != std::string::npos) {
|
||||
result.push_back(tempStr.substr(0, index));
|
||||
tempStr = tempStr.substr(index + delimiter.size());
|
||||
|
||||
if (tempStr.empty()) {
|
||||
result.push_back(tempStr);
|
||||
}
|
||||
tempStr = tempStr.substr(index + token.size());
|
||||
if (tempStr.empty()) result.push_back(tempStr);
|
||||
} else {
|
||||
result.push_back(tempStr);
|
||||
tempStr.clear();
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Decodes a Base64 encoded string.
|
||||
*
|
||||
* @param inputStr The Base64 encoded string.
|
||||
* @return The decoded string.
|
||||
*/
|
||||
inline std::string decode64(const std::string &inputStr) {
|
||||
using namespace boost::archive::iterators;
|
||||
|
||||
@@ -162,11 +246,17 @@ 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 &) {
|
||||
} catch (const std::exception &e) {
|
||||
throw std::runtime_error("Invalid Base64 encoding");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Encodes a string to Base64.
|
||||
*
|
||||
* @param inputStr The string to encode.
|
||||
* @return The Base64 encoded string.
|
||||
*/
|
||||
inline std::string encode64(const std::string &inputStr) {
|
||||
using namespace boost::archive::iterators;
|
||||
|
||||
@@ -181,6 +271,13 @@ inline std::string encode64(const std::string &inputStr) {
|
||||
return encoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Encrypts a plaintext string using AES-256-CBC.
|
||||
*
|
||||
* @param plaintext The plaintext string.
|
||||
* @param key The encryption key.
|
||||
* @return BoolStr containing success status and the encrypted message.
|
||||
*/
|
||||
inline BoolStr aes256Encrypt(const std::string &plaintext,
|
||||
const std::string &key) {
|
||||
BoolStr result{false, "Encryption failed"};
|
||||
@@ -232,12 +329,19 @@ inline BoolStr aes256Encrypt(const std::string &plaintext,
|
||||
std::string final_result(reinterpret_cast<char *>(iv), sizeof(iv));
|
||||
final_result.append(reinterpret_cast<char *>(ciphertext.data()),
|
||||
ciphertext_len);
|
||||
|
||||
result.ok = true;
|
||||
result.message = final_result;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Decrypts an AES-256-CBC encrypted string.
|
||||
*
|
||||
* @param ciphertext_with_iv The encrypted string with IV.
|
||||
* @param key The decryption key.
|
||||
* @return BoolStr containing success status and the decrypted message.
|
||||
*/
|
||||
inline BoolStr aes256Decrypt(const std::string &ciphertext_with_iv,
|
||||
const std::string &key) {
|
||||
BoolStr result{false, "Decryption failed"};
|
||||
@@ -245,7 +349,6 @@ 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()));
|
||||
|
||||
@@ -293,6 +396,13 @@ inline BoolStr aes256Decrypt(const std::string &ciphertext_with_iv,
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Validates the command-line arguments and configuration file.
|
||||
*
|
||||
* @param argc The number of command-line arguments.
|
||||
* @param argv The command-line arguments.
|
||||
* @return BoolStr containing success status and validation message.
|
||||
*/
|
||||
inline BoolStr validateConfig(int argc, const char *argv[]) {
|
||||
BoolStr result{false, "Validation failed"};
|
||||
|
||||
@@ -323,19 +433,6 @@ inline BoolStr validateConfig(int argc, const char *argv[]) {
|
||||
return result;
|
||||
}
|
||||
|
||||
try {
|
||||
configYaml["general"]["token"].as<std::string>();
|
||||
configYaml["general"]["fakeUrls"].as<std::vector<std::string>>();
|
||||
configYaml["general"]["methods"].as<std::vector<std::string>>();
|
||||
configYaml["general"]["endPoints"].as<std::vector<std::string>>();
|
||||
configYaml["general"]["timeout"].as<unsigned short>();
|
||||
configYaml["general"]["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;
|
||||
}
|
||||
|
||||
try {
|
||||
configYaml["log"]["logFile"].as<std::string>();
|
||||
configYaml["log"]["logLevel"].as<std::string>();
|
||||
@@ -357,6 +454,7 @@ inline BoolStr validateConfig(int argc, const char *argv[]) {
|
||||
configYaml["agent"]["listenPort"].as<unsigned short>();
|
||||
configYaml["agent"]["serverIp"].as<std::string>();
|
||||
configYaml["agent"]["serverPort"].as<unsigned short>();
|
||||
configYaml["agent"]["token"].as<std::string>();
|
||||
configYaml["agent"]["httpVersion"].as<std::string>();
|
||||
configYaml["agent"]["userAgent"].as<std::string>();
|
||||
} catch (const std::exception &e) {
|
||||
@@ -367,4 +465,6 @@ inline BoolStr validateConfig(int argc, const char *argv[]) {
|
||||
result.ok = true;
|
||||
result.message = "OK";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
#endif// GENERAL_HPP
|
||||
+28
-119
@@ -1,17 +1,14 @@
|
||||
#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),
|
||||
parsedHttpRequest_(),
|
||||
httpType_(HTTP::HttpType::https),
|
||||
parsedTlsRequest_{"", "", TlsTypes::TLSHandshake},
|
||||
uuid_(uuid) {
|
||||
}
|
||||
uuid_(uuid) {}
|
||||
|
||||
HTTP::HTTP(const HTTP &http)
|
||||
: config_(http.config_),
|
||||
@@ -19,24 +16,18 @@ HTTP::HTTP(const HTTP &http)
|
||||
buffer_(http.buffer_),
|
||||
parsedHttpRequest_(http.parsedHttpRequest_),
|
||||
parsedTlsRequest_(http.parsedTlsRequest_),
|
||||
uuid_(http.uuid_) {
|
||||
}
|
||||
|
||||
uuid_(http.uuid_) {}
|
||||
|
||||
HTTP::~HTTP() {}
|
||||
|
||||
|
||||
bool HTTP::detectType() {
|
||||
std::string requestStr{hexStreambufToStr(buffer_)};
|
||||
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
|
||||
@@ -54,21 +45,17 @@ 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;
|
||||
}
|
||||
@@ -78,9 +65,7 @@ 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);
|
||||
@@ -94,39 +79,30 @@ 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;
|
||||
@@ -137,45 +113,29 @@ 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 {
|
||||
auto fakeUrl = config_->randomFakeUrl();
|
||||
return std::string(config_->randomMethod() + " " +
|
||||
fakeUrl + " HTTP/" +
|
||||
return std::string(config_->general().method + " " +
|
||||
config_->general().fakeUrl + " HTTP/" +
|
||||
config_->agent().httpVersion + "\r\n") +
|
||||
"Host: " + fakeUrl + "\r\n" +
|
||||
"Host: " + config_->general().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 {
|
||||
auto fakeUrl = config_->randomFakeUrl();
|
||||
return std::string(config_->randomMethod() + " " +
|
||||
fakeUrl + " HTTP/" +
|
||||
config_->agent().httpVersion + "\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";
|
||||
"Content-Type: application/x-www-form-urlencoded\r\n" + "\r\n" + body;
|
||||
}
|
||||
|
||||
const std::string HTTP::genHttpOkResString(const std::string &body) const {
|
||||
@@ -183,98 +143,44 @@ const std::string HTTP::genHttpOkResString(const std::string &body) const {
|
||||
"Content-Type: application/x-www-form-urlencoded\r\n" +
|
||||
"Content-Length: " + std::to_string(body.length()) + "\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";
|
||||
"Pragma: no-cache\r\n" + "\r\n" + body;
|
||||
}
|
||||
|
||||
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.empty()) {
|
||||
if (splitted.size() > 1) {
|
||||
dstIP_ = splitted[0];
|
||||
if (splitted.size() > 1 && !splitted[1].empty()) {
|
||||
dstPort_ = std::stoi(splitted[1]);
|
||||
} else {
|
||||
dstPort_ = 443;
|
||||
}
|
||||
dstPort_ = std::stoi(splitted[1]);
|
||||
} else {
|
||||
dstIP_.clear();
|
||||
dstIP_ = target;
|
||||
dstPort_ = 443;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case HTTP::HttpType::http: {
|
||||
case HTTP::HttpType::http:
|
||||
target = boost::lexical_cast<std::string>(parsedHttpRequest_.target());
|
||||
|
||||
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 {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
splitted = splitString(hostPort, ":");
|
||||
splitted = splitString(
|
||||
splitString(splitString(target, "http://")[1], "/")[0], ":");
|
||||
if (!splitted.empty()) {
|
||||
dstIP_ = splitted[0];
|
||||
if (splitted.size() > 1 && !splitted[1].empty()) {
|
||||
if (splitted.size() > 1)
|
||||
dstPort_ = std::stoi(splitted[1]);
|
||||
} else {
|
||||
else
|
||||
dstPort_ = 80;
|
||||
}
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [HTTP setIPPort] wrong request",
|
||||
Log::Level::DEBUG);
|
||||
dstIP_.clear();
|
||||
dstPort_ = 80;
|
||||
log_->write("[" + to_string(uuid_) + "] [HTTP setIPPort] wrong request", Log::Level::DEBUG);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case HTTP::HttpType::connect: {
|
||||
case HTTP::HttpType::connect:
|
||||
target = boost::lexical_cast<std::string>(parsedHttpRequest_.target());
|
||||
splitted = splitString(target, ":");
|
||||
|
||||
if (!splitted.empty()) {
|
||||
dstIP_ = splitted[0];
|
||||
if (splitted.size() > 1 && !splitted[1].empty()) {
|
||||
dstPort_ = std::stoi(splitted[1]);
|
||||
} else {
|
||||
dstPort_ = 443;
|
||||
}
|
||||
} else {
|
||||
dstIP_.clear();
|
||||
dstPort_ = 443;
|
||||
}
|
||||
dstIP_ = splitted[0];
|
||||
dstPort_ = std::stoi(splitted[1]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,10 +188,13 @@ 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";
|
||||
}
|
||||
@@ -298,7 +207,7 @@ const std::string HTTP::toString() const {
|
||||
"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()) +
|
||||
@@ -314,14 +223,14 @@ 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";
|
||||
}
|
||||
|
||||
+64
-21
@@ -1,4 +1,6 @@
|
||||
#pragma once
|
||||
#ifndef HTTP_HPP
|
||||
#define HTTP_HPP
|
||||
|
||||
#include <boost/algorithm/string.hpp>
|
||||
#include <boost/asio.hpp>
|
||||
@@ -10,6 +12,12 @@
|
||||
#include "general.hpp"
|
||||
#include "log.hpp"
|
||||
|
||||
/*
|
||||
* This class is for handling request. When a request comes to
|
||||
* TCPConnection(see tcp.hpp), It calls the AgentHanler::handle function(see
|
||||
* agenthandler.hpp) and object from this class will be created in
|
||||
* AgentHanler::handle function to do all operations related to the request
|
||||
*/
|
||||
class HTTP {
|
||||
public:
|
||||
using pointer = std::shared_ptr<HTTP>;
|
||||
@@ -21,44 +29,64 @@ public:
|
||||
return pointer(new HTTP(config, log, buffer, uuid));
|
||||
}
|
||||
|
||||
enum class HttpType {
|
||||
https,
|
||||
http,
|
||||
connect
|
||||
};
|
||||
/*
|
||||
* To define the type of HTTP/HTTPS request
|
||||
*/
|
||||
enum class HttpType { https,
|
||||
http,
|
||||
connect };
|
||||
|
||||
enum class TlsTypes {
|
||||
TLSHandshake,
|
||||
ChangeCipherSpec,
|
||||
ApplicationData
|
||||
};
|
||||
/*
|
||||
* To define the type of the TLS request
|
||||
*/
|
||||
enum class TlsTypes { TLSHandshake,
|
||||
ChangeCipherSpec,
|
||||
ApplicationData };
|
||||
|
||||
/*
|
||||
* To define the TLS request, This struct is used while parsing a request
|
||||
* after we detect that it is a TLS HTTP
|
||||
*/
|
||||
struct TlsRequest {
|
||||
std::string sni;
|
||||
std::string body;
|
||||
TlsTypes type;
|
||||
};
|
||||
|
||||
/*
|
||||
* Copy constructor if you want to copy and initialize it
|
||||
*/
|
||||
explicit HTTP(const HTTP &request);
|
||||
|
||||
~HTTP();
|
||||
|
||||
/*
|
||||
* Functions to handle private members
|
||||
*/
|
||||
inline const HTTP::HttpType &httpType() const { return httpType_; }
|
||||
|
||||
inline void httpType(const HTTP::HttpType &httpType) { httpType_ = httpType; }
|
||||
|
||||
/*
|
||||
* This function will detect the type of request (HTTP|HTTPS)
|
||||
* It checks the first byte of the body, in case of 16, 14, 17 it is HTTPS
|
||||
* and else it may be HTTP
|
||||
*/
|
||||
bool detectType();
|
||||
|
||||
/*
|
||||
* If the request is HTTP it will parse it and store in parsedHttpRequest_
|
||||
*/
|
||||
bool parseHttp();
|
||||
|
||||
bool parseHttpResp();
|
||||
|
||||
/*
|
||||
* If the request is HTTPS it will parse it and store in parsedTlsRequest_
|
||||
*/
|
||||
bool parseTls();
|
||||
|
||||
const std::string genHttpPostReqString(const std::string &body) const;
|
||||
|
||||
const std::string genHttpRestPostReqString() const;
|
||||
|
||||
const std::string genHttpOkResString(const std::string &body) const;
|
||||
|
||||
inline const boost::beast::http::request<boost::beast::http::string_body> &
|
||||
@@ -73,35 +101,50 @@ public:
|
||||
|
||||
inline const TlsRequest &parsedTlsRequest() & { return parsedTlsRequest_; }
|
||||
|
||||
/*
|
||||
* This function returns the string of parsedTlsRequest_.type
|
||||
*/
|
||||
const std::string tlsTypeToString() const;
|
||||
|
||||
inline const std::string &dstIP() { return dstIP_; }
|
||||
inline const std::string &dstIP() & { return dstIP_; }
|
||||
inline const std::string &&dstIP() && { return std::move(dstIP_); }
|
||||
|
||||
inline const unsigned short &dstPort() { return dstPort_; }
|
||||
inline const unsigned short &dstPort() & { return dstPort_; }
|
||||
inline const unsigned short &&dstPort() && { return std::move(dstPort_); }
|
||||
|
||||
/*
|
||||
* This function returns string of request based on the HttpType (HTTP|HTTPS)
|
||||
*/
|
||||
const std::string toString() const;
|
||||
|
||||
const std::string restoString() const;
|
||||
|
||||
private:
|
||||
/*
|
||||
* default constructor
|
||||
*/
|
||||
explicit HTTP(const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
boost::asio::streambuf &buffer,
|
||||
boost::uuids::uuid uuid);
|
||||
|
||||
/*
|
||||
* This function returns map of dst IP and Port for request
|
||||
*/
|
||||
void setIPPort();
|
||||
|
||||
const std::shared_ptr<Config> &config_;
|
||||
const 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_;
|
||||
unsigned short dstPort_;
|
||||
TlsRequest parsedTlsRequest_;
|
||||
boost::uuids::uuid uuid_;
|
||||
};
|
||||
};
|
||||
|
||||
#endif /* HTTP_HPP */
|
||||
+3
-11
@@ -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");
|
||||
|
||||
// Open the log file for appending.
|
||||
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,7 +15,6 @@ Log::Log(const std::shared_ptr<Config> &config)
|
||||
}
|
||||
|
||||
const auto &logLevel = config_->log().level;
|
||||
|
||||
if (logLevel == "INFO") {
|
||||
level_ = Level::INFO;
|
||||
} else if (logLevel == "TRACE") {
|
||||
@@ -34,28 +33,21 @@ Log::Log(const std::shared_ptr<Log> &log)
|
||||
Log::~Log() {}
|
||||
|
||||
void Log::write(const std::string &message, Level level) const {
|
||||
std::lock_guard<std::mutex> lock(logMutex_);
|
||||
std::lock_guard<std::mutex> lock(logMutex_);// Lock the mutex before writing
|
||||
|
||||
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";
|
||||
@@ -76,4 +68,4 @@ std::string Log::levelToString(Level level) {
|
||||
default:
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-13
@@ -10,16 +10,20 @@
|
||||
#include "config.hpp"
|
||||
#include "general.hpp"
|
||||
|
||||
|
||||
/**
|
||||
* @brief A class for logging messages with different levels (INFO, TRACE,
|
||||
* ERROR, DEBUG).
|
||||
*
|
||||
* The Log class handles logging messages to a file and/or console based on the
|
||||
* configured log level. It provides facilities to create log instances, set
|
||||
* the log level, and write log messages.
|
||||
*/
|
||||
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) {
|
||||
@@ -27,12 +31,9 @@ public:
|
||||
}
|
||||
|
||||
explicit Log(const std::shared_ptr<Log> &log);
|
||||
|
||||
|
||||
~Log();
|
||||
|
||||
const std::shared_ptr<Config> &config() const { return config_; }
|
||||
|
||||
Level level() const { return level_; }
|
||||
|
||||
void write(const std::string &message, Level level) const;
|
||||
@@ -46,5 +47,5 @@ private:
|
||||
Level level_;
|
||||
std::string mode_;
|
||||
|
||||
mutable std::mutex logMutex_;
|
||||
};
|
||||
mutable std::mutex logMutex_;// Mutex to protect write operations
|
||||
};
|
||||
+14
-5
@@ -6,28 +6,37 @@
|
||||
#include "runner.hpp"
|
||||
|
||||
int main(int argc, char const *argv[]) {
|
||||
|
||||
// Ensure that at least two arguments are provided: the mode and the config
|
||||
// file path.
|
||||
if (argc < 3) {
|
||||
std::cerr << "Usage: " << argv[0] << " <mode> <config_file_path>\n";
|
||||
return 1;
|
||||
return 1;// Exit with error code 1 indicating incorrect usage.
|
||||
}
|
||||
|
||||
// Validate the configuration using the provided arguments.
|
||||
BoolStr configValidation = validateConfig(argc, argv);
|
||||
if (!configValidation.ok) {
|
||||
std::cerr << "Configuration validation failed: " << configValidation.message
|
||||
<< "\n";
|
||||
return 1;
|
||||
return 1;// Exit with error code 1 indicating configuration validation
|
||||
// failure.
|
||||
}
|
||||
|
||||
// Determine the run mode based on the first argument.
|
||||
// If "agent" is specified, set runMode_ to RunMode::agent; otherwise, set it
|
||||
// to RunMode::server.
|
||||
std::string mode(argv[1]);
|
||||
RunMode runMode_ = (mode == "agent") ? RunMode::agent : RunMode::server;
|
||||
|
||||
// Initialize the main Config object with the run mode and config file path.
|
||||
Config::pointer config_ = Config::create(runMode_, std::string(argv[2]));
|
||||
|
||||
// Initialize the main Log object using the created Config object.
|
||||
Log::pointer log_ = Log::create(config_);
|
||||
|
||||
// Create and run the Runner object with the Config and Log objects.
|
||||
Runner runner_(config_, log_);
|
||||
runner_.run();
|
||||
|
||||
return 0;
|
||||
}
|
||||
return 0;// Exit with success code 0.
|
||||
}
|
||||
+27
-14
@@ -1,63 +1,76 @@
|
||||
#include "runner.hpp"
|
||||
|
||||
// Constructor for the Runner class
|
||||
Runner::Runner(const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log)
|
||||
: config_(config),
|
||||
log_(log),
|
||||
io_context_(),
|
||||
work_guard_(boost::asio::make_work_guard(io_context_)),
|
||||
running_(true),
|
||||
: config_(config),// Store the configuration object
|
||||
log_(log), // Store the log object
|
||||
io_context_(), // Initialize the I/O context for asynchronous operations
|
||||
work_guard_(boost::asio::make_work_guard(
|
||||
io_context_)),// Prevents io_context from running out of work
|
||||
running_(true), // Initialize running state to true
|
||||
strand_(boost::asio::make_strand(io_context_)) {}
|
||||
|
||||
// Destructor for the Runner class
|
||||
Runner::~Runner() {
|
||||
running_.store(false);
|
||||
io_context_.stop();
|
||||
|
||||
for (auto &thread: threadPool_) {
|
||||
running_.store(
|
||||
false); // Set the running flag to false to stop the worker threads
|
||||
io_context_.stop(); // Stop the I/O context, which will end the processing
|
||||
for (auto &thread: threadPool_) {// Wait for all threads to complete
|
||||
if (thread.joinable()) {
|
||||
thread.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Main function to run the server
|
||||
void Runner::run() {
|
||||
try {
|
||||
log_->write("Config initialized in " + config_->modeToString() + " mode", Log::Level::INFO);
|
||||
// Log the configuration mode and details
|
||||
log_->write("Config initialized in " + config_->modeToString() + " mode",
|
||||
Log::Level::INFO);
|
||||
log_->write(config_->toString(), Log::Level::INFO);
|
||||
|
||||
// Create and initialize the TCP server
|
||||
auto tcpServer = TCPServer::create(io_context_, config_, log_);
|
||||
|
||||
// Start initial worker threads
|
||||
for (auto i = 0; i < config_->threads(); ++i) {
|
||||
threadPool_.emplace_back([this] { workerThread(); });
|
||||
}
|
||||
|
||||
// Wait for all threads to finish
|
||||
for (auto &thread: threadPool_) {
|
||||
if (thread.joinable()) {
|
||||
thread.join();
|
||||
}
|
||||
}
|
||||
|
||||
} catch (const std::exception &error) {
|
||||
// Log any exceptions thrown during execution
|
||||
log_->write(std::string("[Runner run] ") + error.what(), Log::Level::ERROR);
|
||||
} catch (...) {
|
||||
// Log any unknown exceptions
|
||||
log_->write("[Runner run] Unknown error occurred", Log::Level::ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
// Function for worker threads to process tasks
|
||||
void Runner::workerThread() {
|
||||
while (running_.load()) {
|
||||
try {
|
||||
io_context_.run();
|
||||
break;
|
||||
break;// Exit loop if io_context_.run() completes
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Function to stop thread
|
||||
void Runner::stop() {
|
||||
running_.store(false);
|
||||
io_context_.stop();
|
||||
}
|
||||
}
|
||||
+41
-2
@@ -1,5 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef RUNNER_HPP
|
||||
#define RUNNER_HPP
|
||||
|
||||
#include <atomic>
|
||||
#include <boost/asio/executor_work_guard.hpp>
|
||||
#include <boost/asio/io_context.hpp>
|
||||
@@ -11,30 +14,66 @@
|
||||
#include "log.hpp"
|
||||
#include "tcpserver.hpp"
|
||||
|
||||
/*
|
||||
* The Runner class is responsible for managing the application's main
|
||||
* execution loop. It initializes the server, starts worker threads, and
|
||||
* handles exceptions. This class is used in the main function to run the I/O
|
||||
* context and manage the server lifecycle.
|
||||
*/
|
||||
class Runner : private Uncopyable {
|
||||
public:
|
||||
/*
|
||||
* Constructor to initialize the Runner object with configuration and logging
|
||||
* objects.
|
||||
* @param config - Shared pointer to the configuration object.
|
||||
* @param log - Shared pointer to the logging object.
|
||||
*/
|
||||
explicit Runner(const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log);
|
||||
|
||||
/*
|
||||
* Destructor to clean up resources, stop the I/O context, and join all
|
||||
* threads.
|
||||
*/
|
||||
~Runner();
|
||||
|
||||
/*
|
||||
* Main function to start the server and run the I/O context.
|
||||
* This function sets up the server, starts worker threads, and manages
|
||||
* execution.
|
||||
*/
|
||||
void run();
|
||||
|
||||
private:
|
||||
/*
|
||||
* Worker thread function that processes asynchronous operations.
|
||||
* This function runs the I/O context and handles exceptions.
|
||||
*/
|
||||
void workerThread();
|
||||
|
||||
void stop();
|
||||
|
||||
// Configuration object for the server.
|
||||
const std::shared_ptr<Config> &config_;
|
||||
|
||||
// Logging object for recording messages and errors.
|
||||
const std::shared_ptr<Log> &log_;
|
||||
|
||||
// Boost.Asio I/O context to manage asynchronous operations.
|
||||
boost::asio::io_context io_context_;
|
||||
|
||||
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work_guard_;
|
||||
// Work guard to prevent the I/O context from running out of work.
|
||||
boost::asio::executor_work_guard<boost::asio::io_context::executor_type>
|
||||
work_guard_;
|
||||
|
||||
// Atomic flag to indicate if the server is still running.
|
||||
std::atomic<bool> running_;
|
||||
|
||||
// Thread pool to manage worker threads.
|
||||
std::vector<std::jthread> threadPool_;
|
||||
|
||||
// Add strand to manage concurrency
|
||||
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
|
||||
};
|
||||
};
|
||||
|
||||
#endif /* RUNNER_HPP */
|
||||
+158
-397
@@ -1,69 +1,13 @@
|
||||
#include "serverhandler.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
std::mutex ServerHandler::sessionsMutex_;
|
||||
std::unordered_map<std::string, TCPClient::pointer> ServerHandler::sessions_;
|
||||
|
||||
std::string ServerHandler::HttpUtils::lowerCopy(std::string s) {
|
||||
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) {
|
||||
return static_cast<char>(std::tolower(c));
|
||||
});
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
std::string ServerHandler::HttpUtils::trimCopy(std::string s) {
|
||||
while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) {
|
||||
s.erase(s.begin());
|
||||
}
|
||||
|
||||
while (!s.empty() &&
|
||||
(s.back() == ' ' ||
|
||||
s.back() == '\t' ||
|
||||
s.back() == '\r' ||
|
||||
s.back() == '\n')) {
|
||||
s.pop_back();
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
std::string ServerHandler::HttpUtils::getRawHeader(const std::string &headers,
|
||||
const std::string &name) {
|
||||
std::istringstream iss(headers);
|
||||
std::string line;
|
||||
|
||||
const std::string prefix = lowerCopy(name) + ":";
|
||||
|
||||
while (std::getline(iss, line)) {
|
||||
if (!line.empty() && line.back() == '\r') {
|
||||
line.pop_back();
|
||||
}
|
||||
|
||||
std::string lower = lowerCopy(line);
|
||||
|
||||
if (lower.rfind(prefix, 0) == 0) {
|
||||
return trimCopy(line.substr(name.size() + 1));
|
||||
}
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
std::string ServerHandler::HttpUtils::extractHttpBody(const std::string &msg) {
|
||||
const auto pos = msg.find("\r\n\r\n");
|
||||
|
||||
if (pos == std::string::npos) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return msg.substr(pos + 4);
|
||||
}
|
||||
|
||||
/*
|
||||
* Constructor to initialize the ServerHandler object.
|
||||
* @param readBuffer - Buffer for reading incoming data.
|
||||
* @param writeBuffer - Buffer for writing outgoing data.
|
||||
* @param config - Shared pointer to the configuration object.
|
||||
* @param log - Shared pointer to the logging object.
|
||||
* @param client - Shared pointer to the TCP client object.
|
||||
*/
|
||||
ServerHandler::ServerHandler(boost::asio::streambuf &readBuffer,
|
||||
boost::asio::streambuf &writeBuffer,
|
||||
const std::shared_ptr<Config> &config,
|
||||
@@ -78,347 +22,164 @@ ServerHandler::ServerHandler(boost::asio::streambuf &readBuffer,
|
||||
writeBuffer_(writeBuffer),
|
||||
request_(HTTP::create(config, log, readBuffer, uuid)),
|
||||
clientConnStr_(clientConnStr),
|
||||
uuid_(uuid) {
|
||||
end_ = false;
|
||||
connect_ = false;
|
||||
}
|
||||
uuid_(uuid) {}
|
||||
|
||||
/*
|
||||
* Destructor for cleanup. No specific resources to release.
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
||||
/*
|
||||
* Handles the incoming request by processing it based on its type
|
||||
* (HTTP/HTTPS). It performs decryption, handles connection, and processes the
|
||||
* request.
|
||||
*/
|
||||
void ServerHandler::handle() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::lock_guard<std::mutex> lock(mutex_);// Lock the mutex for thread safety
|
||||
|
||||
if (!request_->detectType()) {
|
||||
// Detects the type of request (HTTP/HTTPS).
|
||||
if (request_->detectType()) {
|
||||
// Log the received request from the agent.
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [ServerHandler handle] [NOT HTTP Request From Agent] [Request] : " +
|
||||
streambufToString(readBuffer_),
|
||||
"[" + to_string(uuid_) + "] [ServerHandler handle] [Request From Agent] : " + request_->toString(),
|
||||
Log::Level::DEBUG);
|
||||
|
||||
// Decrypt the request body using AES256.
|
||||
BoolStr decryption{false, std::string("FAILED")};
|
||||
decryption = aes256Decrypt(decode64(boost::lexical_cast<std::string>(
|
||||
request_->parsedHttpRequest().body())),
|
||||
config_->agent().token);
|
||||
|
||||
if (decryption.ok) {
|
||||
// Log successful decryption and process the request.
|
||||
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_);
|
||||
|
||||
// Re-check the request type and process accordingly.
|
||||
if (request_->detectType()) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) + "] [ServerHandler handle] [Request] : " + request_->toString(),
|
||||
Log::Level::DEBUG);
|
||||
switch (request_->httpType()) {
|
||||
case HTTP::HttpType::connect: {
|
||||
// Handle CONNECT request to establish a connection.
|
||||
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\r\n\r\n");
|
||||
os << message;
|
||||
} else {
|
||||
std::string message("HTTP/1.1 500 Connection failed\r\n\r\n");
|
||||
os << message;
|
||||
}
|
||||
moveStreambuf(tempBuff, writeBuffer_);
|
||||
} break;
|
||||
case HTTP::HttpType::http:
|
||||
case HTTP::HttpType::https: {
|
||||
// Handle HTTP or HTTPS requests.
|
||||
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_->doRead();
|
||||
if (client_->readBuffer().size() > 0) {
|
||||
// Encrypt the response and send it back.
|
||||
BoolStr encryption{false, std::string("FAILED")};
|
||||
encryption =
|
||||
aes256Encrypt(streambufToString(client_->readBuffer()),
|
||||
config_->agent().token);
|
||||
if (encryption.ok) {
|
||||
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 encryption failure and close the connection.
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [ServerHandler handle] [Encryption "
|
||||
"Failed] : [ " +
|
||||
decryption.message + "] ",
|
||||
Log::Level::DEBUG);
|
||||
log_->write("[" + to_string(uuid_) + "] [ServerHandler handle] [Encryption Failed] : " +
|
||||
request_->toString(),
|
||||
Log::Level::INFO);
|
||||
client_->socket().close();
|
||||
}
|
||||
} else {
|
||||
// Close the connection if no data was read.
|
||||
client_->socket().close();
|
||||
return;
|
||||
}
|
||||
} break;
|
||||
}
|
||||
} else {
|
||||
// Log non-HTTP requests if detected.
|
||||
log_->write("[" + to_string(uuid_) + "] [ServerHandler handle] [NOT HTTP Request] [Request] : " +
|
||||
streambufToString(readBuffer_),
|
||||
Log::Level::DEBUG);
|
||||
// Close the socket if no data is available
|
||||
client_->socket().close();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// Log decryption failure and close the connection.
|
||||
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);
|
||||
// Close the socket if no data is available
|
||||
client_->socket().close();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// Log if the request is not from an agent.
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) + "] [ServerHandler handle] [NOT HTTP Request From Agent] [Request] : " +
|
||||
streambufToString(readBuffer_),
|
||||
Log::Level::DEBUG);
|
||||
// Close the socket if no data is available
|
||||
client_->socket().close();
|
||||
return;
|
||||
}
|
||||
|
||||
const auto &outerReq = request_->parsedHttpRequest();
|
||||
|
||||
const std::string outerRaw = streambufToString(readBuffer_);
|
||||
const auto outerHeaderEnd = outerRaw.find("\r\n\r\n");
|
||||
const std::string outerHeaders =
|
||||
outerHeaderEnd == std::string::npos
|
||||
? ""
|
||||
: outerRaw.substr(0, outerHeaderEnd + 2);
|
||||
|
||||
const std::string session =
|
||||
HttpUtils::getRawHeader(outerHeaders, "X-Nipo-Session");
|
||||
|
||||
const std::string action =
|
||||
HttpUtils::getRawHeader(outerHeaders, "X-Nipo-Action");
|
||||
|
||||
std::string requestBody = std::string(outerReq.body());
|
||||
|
||||
if (requestBody.empty()) {
|
||||
requestBody = HttpUtils::extractHttpBody(outerRaw);
|
||||
}
|
||||
|
||||
BoolStr decryption{false, std::string("FAILED")};
|
||||
|
||||
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, 65536));
|
||||
std::size_t n = targetClient->socket().read_some(
|
||||
boost::asio::buffer(data),
|
||||
ec);
|
||||
|
||||
if (ec || n == 0) {
|
||||
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
return;
|
||||
}
|
||||
|
||||
makeEncryptedHttpResponse(
|
||||
std::string(data.data(), n),
|
||||
"200 OK",
|
||||
(config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (action == "close") {
|
||||
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
|
||||
auto it = sessions_.find(session);
|
||||
|
||||
if (it != sessions_.end()) {
|
||||
it->second->socketShutdown();
|
||||
sessions_.erase(it);
|
||||
}
|
||||
|
||||
makeEncryptedHttpResponse("", "200 OK", (config_->general().connectionReuse ? "keep-alive" : "close"));
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string innerRequest = hexToASCII(decryption.message);
|
||||
|
||||
const std::size_t headerEnd = innerRequest.find("\r\n\r\n");
|
||||
|
||||
if (headerEnd == std::string::npos) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [ServerHandler handle] [INNER REQUEST MISSING HEADER END]",
|
||||
Log::Level::DEBUG);
|
||||
|
||||
makeEncryptedHttpResponse("", "400 Bad Request", "close");
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string innerHeaders = innerRequest.substr(0, headerEnd + 4);
|
||||
const std::string pendingTunnelData = innerRequest.substr(headerEnd + 4);
|
||||
|
||||
copyStringToStreambuf(innerHeaders, readBuffer_);
|
||||
|
||||
HTTP::pointer inner = HTTP::create(config_, log_, readBuffer_, uuid_);
|
||||
|
||||
if (!inner->detectType()) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [ServerHandler handle] [NOT INNER HTTP Request] [Request] : " +
|
||||
streambufToString(readBuffer_),
|
||||
Log::Level::DEBUG);
|
||||
|
||||
makeEncryptedHttpResponse("", "400 Bad Request", "close");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (inner->httpType()) {
|
||||
case HTTP::HttpType::connect: {
|
||||
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] [TUNNEL] [SRC " +
|
||||
clientConnStr_ + "] [DST " +
|
||||
inner->dstIP() + ":" + std::to_string(inner->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
|
||||
makeEncryptedHttpResponse(
|
||||
"HTTP/1.1 200 Connection Established\r\n\r\n",
|
||||
"200 OK",
|
||||
"keep-alive");
|
||||
|
||||
connect_ = true;
|
||||
end_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
TCPClient::pointer targetClient = TCPClient::create(
|
||||
static_cast<boost::asio::io_context &>(
|
||||
client_->socket().get_executor().context()),
|
||||
config_,
|
||||
log_);
|
||||
|
||||
targetClient->uuid_ = uuid_;
|
||||
|
||||
if (!targetClient->doConnect(inner->dstIP(), inner->dstPort())) {
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [CONNECT] [ERROR] [Resolving Host] [SRC " +
|
||||
clientConnStr_ + "] [DST " +
|
||||
inner->dstIP() + ":" + std::to_string(inner->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
|
||||
makeEncryptedHttpResponse(
|
||||
"HTTP/1.1 502 Bad Gateway\r\n\r\n",
|
||||
"502 Bad Gateway",
|
||||
"close");
|
||||
|
||||
connect_ = false;
|
||||
end_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
log_->write(
|
||||
"[" + to_string(uuid_) +
|
||||
"] [CONNECT] [SRC " +
|
||||
clientConnStr_ + "] [DST " +
|
||||
inner->dstIP() + ":" + std::to_string(inner->dstPort()) + "]",
|
||||
Log::Level::INFO);
|
||||
|
||||
if (!pendingTunnelData.empty()) {
|
||||
boost::asio::streambuf pendingBuf;
|
||||
copyStringToStreambuf(pendingTunnelData, pendingBuf);
|
||||
targetClient->doWrite(pendingBuf);
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
|
||||
sessions_[session.empty() ? to_string(uuid_) : session] = targetClient;
|
||||
}
|
||||
|
||||
makeEncryptedHttpResponse(
|
||||
"HTTP/1.1 200 Connection Established\r\n\r\n",
|
||||
"200 OK",
|
||||
"keep-alive");
|
||||
|
||||
connect_ = false;
|
||||
end_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
case HTTP::HttpType::http:
|
||||
case HTTP::HttpType::https: {
|
||||
copyStringToStreambuf(innerRequest, readBuffer_);
|
||||
|
||||
if (!client_->socket().is_open()) {
|
||||
if (!client_->doConnect(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+61
-34
@@ -1,9 +1,8 @@
|
||||
#pragma once
|
||||
#ifndef SERVERHANDLER_HPP
|
||||
#define SERVERHANDLER_HPP
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "config.hpp"
|
||||
#include "general.hpp"
|
||||
@@ -11,10 +10,27 @@
|
||||
#include "log.hpp"
|
||||
#include "tcpclient.hpp"
|
||||
|
||||
/*
|
||||
* The ServerHandler class is responsible for managing and handling HTTP/HTTPS
|
||||
* requests when the process is running in server mode. It is initialized with
|
||||
* buffers for reading and writing data, as well as configuration and logging
|
||||
* objects, and a TCP client object for communication.
|
||||
*/
|
||||
class ServerHandler : private Uncopyable {
|
||||
public:
|
||||
using pointer = std::shared_ptr<ServerHandler>;
|
||||
using pointer = std::shared_ptr<ServerHandler>;// Type alias for shared
|
||||
// pointer to ServerHandler.
|
||||
|
||||
/*
|
||||
* Static factory method to create a shared pointer to a ServerHandler
|
||||
* instance.
|
||||
* @param readBuffer - Buffer used for reading incoming data.
|
||||
* @param writeBuffer - Buffer used for writing outgoing data.
|
||||
* @param config - Shared pointer to the configuration object.
|
||||
* @param log - Shared pointer to the logging object.
|
||||
* @param client - Shared pointer to the TCP client object.
|
||||
* @return A shared pointer to the created ServerHandler instance.
|
||||
*/
|
||||
static pointer create(boost::asio::streambuf &readBuffer,
|
||||
boost::asio::streambuf &writeBuffer,
|
||||
const std::shared_ptr<Config> &config,
|
||||
@@ -22,27 +38,43 @@ public:
|
||||
const TCPClient::pointer &client,
|
||||
const 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));
|
||||
}
|
||||
|
||||
/*
|
||||
* Destructor to clean up resources.
|
||||
*/
|
||||
~ServerHandler();
|
||||
|
||||
/*
|
||||
* Handles incoming requests by processing them based on their type
|
||||
* (HTTP/HTTPS). This method is invoked from the TCPConnection::handleRead
|
||||
* function.
|
||||
*/
|
||||
void handle();
|
||||
|
||||
/*
|
||||
* Accessor for the HTTP request object.
|
||||
* @return A reference to the HTTP request object.
|
||||
*/
|
||||
inline const HTTP::pointer &request() & { return request_; }
|
||||
|
||||
/*
|
||||
* Move accessor for the HTTP request object.
|
||||
* @return An rvalue reference to the HTTP request object.
|
||||
*/
|
||||
inline const HTTP::pointer &&request() && { return std::move(request_); }
|
||||
|
||||
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);
|
||||
};
|
||||
|
||||
/*
|
||||
* Constructor to initialize the ServerHandler object.
|
||||
* @param readBuffer - Buffer used for reading incoming data.
|
||||
* @param writeBuffer - Buffer used for writing outgoing data.
|
||||
* @param config - Shared pointer to the configuration object.
|
||||
* @param log - Shared pointer to the logging object.
|
||||
* @param client - Shared pointer to the TCP client object.
|
||||
*/
|
||||
explicit ServerHandler(boost::asio::streambuf &readBuffer,
|
||||
boost::asio::streambuf &writeBuffer,
|
||||
const std::shared_ptr<Config> &config,
|
||||
@@ -51,24 +83,19 @@ private:
|
||||
const std::string &clientConnStr,
|
||||
boost::uuids::uuid uuid);
|
||||
|
||||
void makeEncryptedHttpResponse(const std::string &plainBody,
|
||||
const std::string &status = "200 OK",
|
||||
const std::string &connection = "close");
|
||||
const std::shared_ptr<Config>
|
||||
&config_; // Reference to the configuration object.
|
||||
const std::shared_ptr<Log> &log_; // Reference to the logging object.
|
||||
const TCPClient::pointer &client_;// Reference to the TCP client object.
|
||||
boost::asio::streambuf &readBuffer_,
|
||||
&writeBuffer_; // References to the read and write buffers.
|
||||
HTTP::pointer request_;// Shared pointer to the HTTP request object.
|
||||
const std::string
|
||||
&clientConnStr_;///< socket client connection string "ip:port"
|
||||
|
||||
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_;
|
||||
|
||||
const std::shared_ptr<Config> &config_;
|
||||
const std::shared_ptr<Log> &log_;
|
||||
const TCPClient::pointer &client_;
|
||||
boost::asio::streambuf &readBuffer_;
|
||||
boost::asio::streambuf &writeBuffer_;
|
||||
HTTP::pointer request_;
|
||||
const std::string &clientConnStr_;
|
||||
boost::uuids::uuid uuid_;
|
||||
std::mutex mutex_;
|
||||
};
|
||||
|
||||
std::mutex mutex_;///< Mutex to make the class thread-safe
|
||||
};
|
||||
|
||||
#endif /* SERVERHANDLER_HPP */
|
||||
+185
-623
@@ -1,12 +1,17 @@
|
||||
#include "tcpclient.hpp"
|
||||
|
||||
#include <openssl/ssl.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
#include <boost/asio/steady_timer.hpp>
|
||||
|
||||
/*
|
||||
* Constructor for the TCPClient class.
|
||||
* Initializes the TCP client with given configuration and logging objects,
|
||||
* and sets up the required I/O context, socket, resolver, and timer.
|
||||
*
|
||||
* @param io_context - The Boost Asio I/O context to be used for asynchronous
|
||||
* operations.
|
||||
* @param config - Shared pointer to the configuration object.
|
||||
* @param log - Shared pointer to the logging object.
|
||||
*/
|
||||
TCPClient::TCPClient(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log)
|
||||
@@ -14,673 +19,230 @@ 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;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
bool TCPClient::enableTlsClient() {
|
||||
|
||||
try {
|
||||
if (tlsEnabled_) return true;
|
||||
|
||||
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 {
|
||||
sslContext_.set_verify_mode(boost::asio::ssl::verify_none);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
bool TCPClient::doConnect(const std::string &dstIP, const unsigned short &dstPort) {
|
||||
|
||||
try {
|
||||
if (tlsEnabled_ && sslSocket_ && sslSocket_->lowest_layer().is_open()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!tlsEnabled_ && socket_.is_open()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doConnect] [DST " + dstIP +
|
||||
":" + std::to_string(dstPort) + "]",
|
||||
Log::Level::DEBUG);
|
||||
|
||||
boost::system::error_code error_code;
|
||||
|
||||
auto endpoint = resolver_.resolve(
|
||||
dstIP.c_str(),
|
||||
std::to_string(dstPort).c_str(),
|
||||
error_code);
|
||||
|
||||
if (error_code) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doConnect] resolve error: " +
|
||||
error_code.message(),
|
||||
Log::Level::ERROR);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (tlsEnabled_) {
|
||||
if (!sslSocket_ || closed_ || !sslSocket_->lowest_layer().is_open()) {
|
||||
sslSocket_ = std::make_unique<ssl_stream>(io_context_, sslContext_);
|
||||
closed_ = false;
|
||||
}
|
||||
|
||||
boost::asio::connect(sslSocket_->lowest_layer(), endpoint, error_code);
|
||||
} else {
|
||||
if (!socket_.is_open()) {
|
||||
socket_ = tcp::socket(io_context_);
|
||||
closed_ = false;
|
||||
}
|
||||
|
||||
boost::asio::connect(socket_, endpoint, error_code);
|
||||
}
|
||||
|
||||
if (error_code) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doConnect] connect error: " +
|
||||
error_code.message(),
|
||||
Log::Level::ERROR);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
} catch (std::exception &error) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doConnect] " +
|
||||
error.what(),
|
||||
Log::Level::ERROR);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool TCPClient::doHandshakeClient() {
|
||||
|
||||
try {
|
||||
if (!tlsEnabled_ || !sslSocket_) return true;
|
||||
|
||||
std::string sniHost = config_->randomFakeUrl();
|
||||
|
||||
if (!sniHost.empty()) {
|
||||
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);
|
||||
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);
|
||||
return false;
|
||||
}
|
||||
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TLS] Using SNI/ALPN host: " + sniHost +
|
||||
" [ALPN http/1.1]",
|
||||
Log::Level::DEBUG);
|
||||
}
|
||||
}
|
||||
|
||||
resetTimeout();
|
||||
sslSocket_->handshake(boost::asio::ssl::stream_base::client);
|
||||
cancelTimeout();
|
||||
|
||||
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);
|
||||
|
||||
if (negotiated != "http/1.1") {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TLS] Unsupported negotiated ALPN: " + negotiated,
|
||||
Log::Level::ERROR);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TLS] No ALPN negotiated",
|
||||
Log::Level::DEBUG);
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
} catch (std::exception &error) {
|
||||
cancelTimeout();
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doHandshakeClient] " + error.what(),
|
||||
Log::Level::ERROR);
|
||||
return false;
|
||||
}
|
||||
timeout_(io_context) {}
|
||||
|
||||
/*
|
||||
* Getter for the socket.
|
||||
*
|
||||
* @return Reference to the Boost Asio TCP socket.
|
||||
*/
|
||||
boost::asio::ip::tcp::socket &TCPClient::socket() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return socket_;
|
||||
}
|
||||
|
||||
/*
|
||||
* Moves the contents of the given stream buffer to the internal write buffer.
|
||||
*
|
||||
* @param buffer - Stream buffer containing data to be written.
|
||||
*/
|
||||
void TCPClient::writeBuffer(boost::asio::streambuf &buffer) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
moveStreambuf(buffer, writeBuffer_);
|
||||
}
|
||||
|
||||
|
||||
void TCPClient::doWrite(boost::asio::streambuf &buffer) {
|
||||
|
||||
/*
|
||||
* Connects the TCP client to a specified destination IP and port.
|
||||
* Logs the connection attempt and handles any connection errors.
|
||||
*
|
||||
* @param dstIP - Destination IP address as a string.
|
||||
* @param dstPort - Destination port number.
|
||||
*/
|
||||
bool TCPClient::doConnect(const std::string &dstIP,
|
||||
const unsigned short &dstPort) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
try {
|
||||
moveStreambuf(buffer, writeBuffer_);
|
||||
|
||||
if (!isOpen()) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doWrite] socket is not open",
|
||||
Log::Level::DEBUG);
|
||||
socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
if (writeBuffer_.size() == 0) {
|
||||
socketShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
boost::system::error_code error;
|
||||
resetTimeout();
|
||||
|
||||
if (tlsEnabled_ && sslSocket_) {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doWrite] [SSL] [DST " +
|
||||
sslSocket_->lowest_layer().remote_endpoint().address().to_string() +
|
||||
":" +
|
||||
std::to_string(sslSocket_->lowest_layer().remote_endpoint().port()) +
|
||||
"] [Bytes " + std::to_string(writeBuffer_.size()) + "] ",
|
||||
Log::Level::DEBUG);
|
||||
boost::asio::write(*sslSocket_, writeBuffer_, error);
|
||||
} else {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doWrite] [TCP] [DST " +
|
||||
socket_.remote_endpoint().address().to_string() + ":" +
|
||||
std::to_string(socket_.remote_endpoint().port()) +
|
||||
"] [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;
|
||||
}
|
||||
|
||||
} catch (std::exception &error) {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doWrite] [catch] " +
|
||||
error.what(),
|
||||
// Log connection attempt
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doConnect] [DST " + dstIP + ":" +
|
||||
std::to_string(dstPort) + "]",
|
||||
Log::Level::DEBUG);
|
||||
socketShutdown();
|
||||
|
||||
// Resolve the endpoint and connect
|
||||
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;
|
||||
} else {
|
||||
boost::asio::connect(socket_, endpoint);
|
||||
return true;
|
||||
}
|
||||
} catch (std::exception &error) {
|
||||
// Log connection errors
|
||||
log_->write(std::string("[" + to_string(uuid_) + "] [TCPClient doConnect] ") + error.what(),
|
||||
Log::Level::ERROR);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void TCPClient::doReadAgent() {
|
||||
boost::system::error_code error;
|
||||
|
||||
/*
|
||||
* Writes data from the internal write buffer to the connected socket.
|
||||
* Logs the write operation and handles any write errors.
|
||||
*
|
||||
* @param buffer - Stream buffer containing data to be written.
|
||||
*/
|
||||
void TCPClient::doWrite(boost::asio::streambuf &buffer) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
try {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
readBuffer_.consume(readBuffer_.size());
|
||||
|
||||
if (!isOpen()) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadAgent] Socket is not OPEN",
|
||||
Log::Level::DEBUG);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
resetTimeout();
|
||||
bool ok = false;
|
||||
if (tlsEnabled_) {
|
||||
if (!sslSocket_) {
|
||||
cancelTimeout();
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadAgent] SSL socket is null",
|
||||
moveStreambuf(buffer, writeBuffer_);
|
||||
// Log details of the write operation
|
||||
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);
|
||||
// Perform the write operation
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
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 (readBuffer_.size() > 0) {
|
||||
copyStreambuf(readBuffer_, buffer_);
|
||||
return;
|
||||
}
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadAgent] empty read buffer",
|
||||
Log::Level::DEBUG);
|
||||
socketShutdown();
|
||||
} catch (const std::exception &ex) {
|
||||
cancelTimeout();
|
||||
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadAgent] [catch read] " +
|
||||
ex.what(),
|
||||
} catch (std::exception &error) {
|
||||
// Log exceptions during the write operation
|
||||
log_->write(std::string("[" + to_string(uuid_) + "] [TCPClient doWrite] [catch] ") + error.what(),
|
||||
Log::Level::DEBUG);
|
||||
socketShutdown();
|
||||
}
|
||||
}
|
||||
|
||||
void TCPClient::doReadServer() {
|
||||
boost::system::error_code error;
|
||||
end_ = false;
|
||||
readBuffer_.consume(readBuffer_.size());
|
||||
|
||||
/*
|
||||
* Reads data from the connected socket into the internal read buffer.
|
||||
* Handles data reading, potential errors, and logs the read operation.
|
||||
* Implements a retry mechanism based on configuration settings.
|
||||
*/
|
||||
void TCPClient::doRead() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
try {
|
||||
if (!isOpen()) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadServer] Socket is not OPEN",
|
||||
Log::Level::DEBUG);
|
||||
return;
|
||||
}
|
||||
|
||||
std::array<char, 16384> temp{};
|
||||
// Clear the read buffer
|
||||
readBuffer_.consume(readBuffer_.size());
|
||||
boost::system::error_code error;
|
||||
resetTimeout();
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// Read at least 39 bytes from the socket
|
||||
boost::asio::read(socket_, readBuffer_, boost::asio::transfer_at_least(1),
|
||||
error);
|
||||
cancelTimeout();
|
||||
|
||||
if (error == boost::asio::error::eof) {
|
||||
socketShutdown();
|
||||
return;
|
||||
} else if (error) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadServer] [error] " + error.message(),
|
||||
Log::Level::ERROR);
|
||||
socketShutdown();
|
||||
return;
|
||||
// Implement retry mechanism if data is still available
|
||||
boost::asio::steady_timer timer(io_context_);
|
||||
for (auto i = 0; i <= config_->general().repeatWait; i++) {
|
||||
while (true) {
|
||||
if (!socket_.is_open()) {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doRead] Socket is not OPEN",
|
||||
Log::Level::DEBUG);
|
||||
socketShutdown();
|
||||
return;
|
||||
}
|
||||
if (socket_.available() == 0) break;
|
||||
resetTimeout();
|
||||
boost::asio::read(socket_, readBuffer_,
|
||||
boost::asio::transfer_at_least(1), error);
|
||||
cancelTimeout();
|
||||
if (error == boost::asio::error::eof) {
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doRead] [EOF] Connection closed by peer.",
|
||||
Log::Level::TRACE);
|
||||
socketShutdown();
|
||||
return;// Exit after closing the socket
|
||||
} else if (error) {
|
||||
log_->write(
|
||||
std::string("[" + to_string(uuid_) + "] [TCPClient doRead] [error] ") + error.message(),
|
||||
Log::Level::ERROR);
|
||||
socketShutdown();
|
||||
return;// Exit after closing the socket
|
||||
}
|
||||
}
|
||||
timer.expires_after(std::chrono::milliseconds(config_->general().timeWait));
|
||||
timer.wait();
|
||||
}
|
||||
|
||||
if (bytes == 0) {
|
||||
end_ = true;
|
||||
return;
|
||||
}
|
||||
|
||||
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()) + "] ",
|
||||
if (readBuffer_.size() > 0) {
|
||||
try {
|
||||
// Log the successful read operation
|
||||
log_->write("[" + to_string(uuid_) + "] [TCPClient doRead] [SRC " +
|
||||
socket_.remote_endpoint().address().to_string() + ":" +
|
||||
std::to_string(socket_.remote_endpoint().port()) +
|
||||
"] [Bytes " + std::to_string(readBuffer_.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(readBuffer_.size()) +
|
||||
"] ",
|
||||
Log::Level::TRACE);
|
||||
} catch (std::exception &error) {
|
||||
// Log exceptions during logging
|
||||
log_->write(
|
||||
std::string("[" + to_string(uuid_) + "] [TCPClient doRead] [catch log] ") + error.what(),
|
||||
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);
|
||||
socketShutdown();
|
||||
return;// Exit after closing the socket
|
||||
}
|
||||
|
||||
copyStreambuf(readBuffer_, buffer_);
|
||||
|
||||
} catch (std::exception &error) {
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient doReadServer] [catch read] " + error.what(),
|
||||
// Log exceptions during the read operation
|
||||
log_->write(std::string("[" + to_string(uuid_) + "] [TCPClient doRead] [catch read] ") + error.what(),
|
||||
Log::Level::DEBUG);
|
||||
socketShutdown();
|
||||
return;// Exit after closing the socket
|
||||
}
|
||||
}
|
||||
|
||||
void TCPClient::resetTimeout() {
|
||||
if (!config_->general().timeout) return;
|
||||
// indicates no timeout
|
||||
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);
|
||||
});
|
||||
// Start/Reset the timer and cancel old handlers
|
||||
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));
|
||||
}
|
||||
|
||||
void TCPClient::cancelTimeout() {
|
||||
if (config_->general().timeout) timeout_.cancel();
|
||||
// If timeout is enabled, cancel the handlers
|
||||
if (config_->general().timeout)
|
||||
timeout_.cancel();
|
||||
}
|
||||
|
||||
void TCPClient::onTimeout(const boost::system::error_code &error) {
|
||||
if (error || error == boost::asio::error::operation_aborted) return;
|
||||
// Ignore cancellation and only handle timer expiration.
|
||||
if (error /* No Error */ || error == boost::asio::error::operation_aborted) return;
|
||||
|
||||
log_->write("[" + to_string(uuid_) +
|
||||
"] [TCPClient onTimeout] [expiration] " +
|
||||
std::to_string(+config_->general().timeout) +
|
||||
" seconds has passed, and the timeout has expired",
|
||||
Log::Level::TRACE);
|
||||
socketShutdown();
|
||||
// Timeout has expired, do necessary actions
|
||||
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);
|
||||
}
|
||||
|
||||
void TCPClient::socketShutdown() {
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
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) {
|
||||
std::transform(s.begin(), s.end(), s.begin(),
|
||||
[](unsigned char c) {
|
||||
return static_cast<char>(std::tolower(c));
|
||||
});
|
||||
return s;
|
||||
}
|
||||
|
||||
std::string TCPClient::HttpUtils::extractHeaders(const std::string &msg) {
|
||||
auto pos = msg.find("\r\n\r\n");
|
||||
if (pos == std::string::npos) return {};
|
||||
return msg.substr(0, pos + 4);
|
||||
}
|
||||
|
||||
std::string TCPClient::HttpUtils::extractBody(const std::string &msg) {
|
||||
auto pos = msg.find("\r\n\r\n");
|
||||
if (pos == std::string::npos) return {};
|
||||
return msg.substr(pos + 4);
|
||||
}
|
||||
|
||||
bool TCPClient::HttpUtils::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();
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
bool TCPClient::HttpUtils::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();
|
||||
|
||||
auto lower = toLowerCopy(line);
|
||||
|
||||
if (lower.rfind("transfer-encoding:", 0) == 0 &&
|
||||
lower.find("chunked") != std::string::npos) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
+89
-61
@@ -1,107 +1,135 @@
|
||||
#pragma once
|
||||
#ifndef TCPCLIENT_HPP
|
||||
#define TCPCLIENT_HPP
|
||||
|
||||
#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 <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
#include "config.hpp"
|
||||
#include "general.hpp"
|
||||
#include "http.hpp"
|
||||
#include "log.hpp"
|
||||
|
||||
/*
|
||||
* TCPClient is a class for managing a TCP client connection.
|
||||
* It handles connecting to an endpoint, sending data, and receiving data.
|
||||
*/
|
||||
class TCPClient : public boost::enable_shared_from_this<TCPClient> {
|
||||
public:
|
||||
// Type alias for shared pointer to TCPClient
|
||||
using pointer = boost::shared_ptr<TCPClient>;
|
||||
using tcp = boost::asio::ip::tcp;
|
||||
using ssl_stream = boost::asio::ssl::stream<tcp::socket>;
|
||||
|
||||
/*
|
||||
* Factory method to create a new TCPClient instance.
|
||||
*
|
||||
* @param io_context - The Boost Asio I/O context for asynchronous
|
||||
* operations.
|
||||
* @param config - Shared pointer to the configuration object.
|
||||
* @param log - Shared pointer to the logging object.
|
||||
* @return Shared pointer to a new TCPClient instance.
|
||||
*/
|
||||
static pointer create(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log) {
|
||||
return pointer(new TCPClient(io_context, config, log));
|
||||
}
|
||||
|
||||
tcp::socket &socket();
|
||||
ssl_stream &sslSocket();
|
||||
|
||||
bool tlsEnabled() const;
|
||||
bool isOpen() const;
|
||||
|
||||
bool enableTlsClient();
|
||||
bool doHandshakeClient();
|
||||
bool doConnect(const std::string &dstIP, const unsigned short &dstPort);
|
||||
/*
|
||||
* Getter for the socket.
|
||||
*
|
||||
* @return Reference to the Boost Asio TCP socket.
|
||||
*/
|
||||
boost::asio::ip::tcp::socket &socket();
|
||||
|
||||
/*
|
||||
* Moves data from a given stream buffer to the internal write buffer.
|
||||
*
|
||||
* @param buffer - Stream buffer containing data to be written.
|
||||
*/
|
||||
void writeBuffer(boost::asio::streambuf &buffer);
|
||||
|
||||
/*
|
||||
* Accessors for the internal buffers.
|
||||
*
|
||||
* @return Reference or rvalue reference to the internal write buffer.
|
||||
*/
|
||||
inline boost::asio::streambuf &writeBuffer() & { return writeBuffer_; }
|
||||
inline boost::asio::streambuf &&writeBuffer() && { return std::move(writeBuffer_); }
|
||||
inline boost::asio::streambuf &&writeBuffer() && {
|
||||
return std::move(writeBuffer_);
|
||||
}
|
||||
|
||||
/*
|
||||
* Accessors for the internal buffers.
|
||||
*
|
||||
* @return Reference or rvalue reference to the internal read buffer.
|
||||
*/
|
||||
inline boost::asio::streambuf &readBuffer() & { return readBuffer_; }
|
||||
inline boost::asio::streambuf &&readBuffer() && { return std::move(readBuffer_); }
|
||||
inline boost::asio::streambuf &&readBuffer() && {
|
||||
return std::move(readBuffer_);
|
||||
}
|
||||
|
||||
/*
|
||||
* Initiates a connection to the specified destination IP and port.
|
||||
*
|
||||
* @param dstIP - Destination IP address as a string.
|
||||
* @param dstPort - Destination port number.
|
||||
*/
|
||||
bool doConnect(const std::string &dstIP, const unsigned short &dstPort);
|
||||
|
||||
/*
|
||||
* Writes data from the internal write buffer to the connected socket.
|
||||
*
|
||||
* @param buffer - Stream buffer containing data to be written.
|
||||
*/
|
||||
void doWrite(boost::asio::streambuf &buffer);
|
||||
void doReadAgent();
|
||||
void doReadServer();
|
||||
|
||||
/*
|
||||
* Reads data from the connected socket into the internal read buffer.
|
||||
*/
|
||||
void doRead();
|
||||
|
||||
void socketShutdown();
|
||||
|
||||
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);
|
||||
};
|
||||
|
||||
/*
|
||||
* Private constructor for TCPClient.
|
||||
* Initializes the TCP client with the given I/O context, configuration, and
|
||||
* logging objects.
|
||||
*
|
||||
* @param io_context - The Boost Asio I/O context for asynchronous
|
||||
* operations.
|
||||
* @param config - Shared pointer to the configuration object.
|
||||
* @param log - Shared pointer to the logging object.
|
||||
*/
|
||||
explicit TCPClient(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log);
|
||||
|
||||
// If the timeout is enabled, start/reset it
|
||||
void resetTimeout();
|
||||
// Cancel the timeout
|
||||
void cancelTimeout();
|
||||
// Handler in case of a timeout expiration
|
||||
void onTimeout(const boost::system::error_code &error);
|
||||
|
||||
const std::shared_ptr<Config> &config_;
|
||||
const std::shared_ptr<Log> &log_;
|
||||
boost::asio::io_context &io_context_;
|
||||
// Members
|
||||
const std::shared_ptr<Config>
|
||||
&config_; // Reference to the configuration object
|
||||
const std::shared_ptr<Log> &log_; // Reference to the logging object
|
||||
boost::asio::io_context &io_context_; // Reference to the I/O context
|
||||
boost::asio::ip::tcp::socket socket_; // TCP socket for communication
|
||||
boost::asio::streambuf writeBuffer_; // Buffer for data to be written
|
||||
boost::asio::streambuf readBuffer_; // Buffer for data to be read
|
||||
boost::asio::ip::tcp::resolver resolver_;// Resolver for endpoint resolution
|
||||
boost::asio::deadline_timer timeout_; // Timer for managing timeouts
|
||||
|
||||
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_;
|
||||
// Mutex for protecting access to the socket and buffers
|
||||
mutable std::mutex mutex_;
|
||||
bool closed_ = false;
|
||||
};
|
||||
};
|
||||
|
||||
#endif /* TCPCLIENT_HPP */
|
||||
+157
-946
File diff suppressed because it is too large.
Load diff
+46
-104
@@ -1,152 +1,94 @@
|
||||
#pragma once
|
||||
#ifndef TCPCONNECTION_HPP
|
||||
#define TCPCONNECTION_HPP
|
||||
|
||||
#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"
|
||||
|
||||
/*
|
||||
* This class handles a single TCP connection.
|
||||
* It is responsible for managing the TCP socket and its associated
|
||||
* buffers, and it processes incoming and outgoing data.
|
||||
*/
|
||||
class TCPConnection : public boost::enable_shared_from_this<TCPConnection> {
|
||||
public:
|
||||
using pointer = boost::shared_ptr<TCPConnection>;
|
||||
using ssl_stream = boost::asio::ssl::stream<boost::asio::ip::tcp::socket>;
|
||||
using pointer =
|
||||
boost::shared_ptr<TCPConnection>;// Define a type alias for a shared
|
||||
// pointer to TCPConnection
|
||||
|
||||
// Factory method to create a new TCPConnection instance
|
||||
static pointer create(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
TCPClient::pointer client) {
|
||||
const TCPClient::pointer &client) {
|
||||
return pointer(new TCPConnection(io_context, config, log, client));
|
||||
}
|
||||
|
||||
// Provides access to the TCP socket
|
||||
boost::asio::ip::tcp::socket &socket();
|
||||
inline TCPClient::pointer client() { return client_; }
|
||||
ssl_stream &tlsSocket();
|
||||
|
||||
bool initTlsServerContext();
|
||||
bool doHandshakeServer();
|
||||
|
||||
// Moves the content of the given buffer to the write buffer
|
||||
inline void writeBuffer(boost::asio::streambuf &buffer) {
|
||||
moveStreambuf(buffer, writeBuffer_);
|
||||
}
|
||||
|
||||
// Accessors for the read buffer
|
||||
inline const boost::asio::streambuf &readBuffer() & { return readBuffer_; }
|
||||
inline const boost::asio::streambuf &&readBuffer() && { return std::move(readBuffer_); }
|
||||
inline const boost::asio::streambuf &&readBuffer() && {
|
||||
return std::move(readBuffer_);
|
||||
}
|
||||
|
||||
inline boost::uuids::uuid uuid() { return uuid_; }
|
||||
|
||||
void startAgent();
|
||||
void startServer();
|
||||
// Starts the reading process
|
||||
void start();
|
||||
|
||||
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);
|
||||
// Initiates an asynchronous read operation
|
||||
void doRead();
|
||||
|
||||
// Handles the completion of an asynchronous read operation
|
||||
void handleRead(const boost::system::error_code &error,
|
||||
size_t bytes_transferred);
|
||||
|
||||
// Initiates an asynchronous write operation
|
||||
void doWrite();
|
||||
|
||||
void socketShutdown();
|
||||
|
||||
void enableDirectTunnelMode();
|
||||
|
||||
void relayClientToServer();
|
||||
void relayServerToClient();
|
||||
|
||||
void relayAgentToTarget();
|
||||
void relayTargetToAgent();
|
||||
|
||||
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, 8192> &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, 8192> &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);
|
||||
};
|
||||
|
||||
// Private constructor to enforce use of the factory method
|
||||
explicit TCPConnection(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log,
|
||||
TCPClient::pointer client);
|
||||
const TCPClient::pointer &client);
|
||||
|
||||
// If the timeout is enabled, start/reset it
|
||||
void resetTimeout();
|
||||
// Cancel the timeout
|
||||
void cancelTimeout();
|
||||
// Handler in case of a timeout expiration
|
||||
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_; // The TCP socket for this connection
|
||||
const std::shared_ptr<Config> &config_;// Configuration settings
|
||||
const std::shared_ptr<Log> &log_; // Logging object
|
||||
boost::asio::io_context &io_context_; // The I/O context
|
||||
const TCPClient::pointer &client_; // Pointer to the associated TCP client
|
||||
boost::asio::streambuf readBuffer_,
|
||||
writeBuffer_; // Buffers for reading and writing data
|
||||
boost::asio::deadline_timer timeout_;// Connections timeout
|
||||
|
||||
boost::asio::ip::tcp::socket socket_;
|
||||
boost::asio::ssl::context sslContext_;
|
||||
std::unique_ptr<ssl_stream> tlsSocket_;
|
||||
|
||||
const std::shared_ptr<Config> &config_;
|
||||
const std::shared_ptr<Log> &log_;
|
||||
boost::asio::io_context &io_context_;
|
||||
TCPClient::pointer client_;
|
||||
|
||||
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::mutex mutex_;///< Mutex to make the class thread-safe
|
||||
};
|
||||
|
||||
std::array<char, 8192> downstreamBuf_;
|
||||
std::array<char, 8192> upstreamBuf_;
|
||||
};
|
||||
#endif /* TCPCONNECTION_HPP */
|
||||
+38
-56
@@ -1,72 +1,54 @@
|
||||
#include "tcpserver.hpp"
|
||||
|
||||
// Constructor for TCPServer
|
||||
TCPServer::TCPServer(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log)
|
||||
: config_(config),
|
||||
log_(log),
|
||||
io_context_(io_context),
|
||||
acceptor_(io_context,
|
||||
boost::asio::ip::tcp::endpoint(
|
||||
boost::asio::ip::make_address(config->listenIp()),
|
||||
config->listenPort())) {
|
||||
: config_(config),// Initialize configuration
|
||||
log_(log), // Initialize logging
|
||||
client_(TCPClient::create(io_context, config,
|
||||
log)),// Create a TCPClient instance
|
||||
io_context_(io_context), // Initialize the I/O context
|
||||
acceptor_(
|
||||
io_context,
|
||||
boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(
|
||||
config->listenIp()),// Listen IP
|
||||
config->listenPort())), // Listen port
|
||||
strand_(boost::asio::make_strand(io_context)) // Initialize the strand
|
||||
{
|
||||
startAccept();// Begin accepting incoming connections
|
||||
}
|
||||
|
||||
// Starts an asynchronous accept operation
|
||||
void TCPServer::startAccept() {
|
||||
// Create a new TCP connection
|
||||
auto connection = TCPConnection::create(io_context_, config_, log_, client_);
|
||||
|
||||
// Set socket option to allow address reuse
|
||||
acceptor_.set_option(boost::asio::socket_base::reuse_address(true));
|
||||
|
||||
startAccept();
|
||||
}
|
||||
|
||||
void TCPServer::startAccept() {
|
||||
auto client = TCPClient::create(io_context_, config_, log_);
|
||||
auto connection = TCPConnection::create(io_context_, config_, log_, client);
|
||||
|
||||
// Initiate asynchronous accept operation using strand to synchronize
|
||||
acceptor_.async_accept(
|
||||
connection->socket(),
|
||||
[this, connection](const boost::system::error_code &error) {
|
||||
handleAccept(connection, error);
|
||||
});
|
||||
connection->socket(),// Socket to be accepted
|
||||
boost::asio::bind_executor(
|
||||
strand_, [this, connection](const boost::system::error_code &error) {
|
||||
// Handle the result of the accept operation
|
||||
handleAccept(connection, error);
|
||||
}));
|
||||
}
|
||||
|
||||
// Handles the result of an asynchronous accept operation
|
||||
void TCPServer::handleAccept(TCPConnection::pointer connection,
|
||||
const boost::system::error_code &error) {
|
||||
try {
|
||||
if (!error) {
|
||||
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();
|
||||
startAccept();
|
||||
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();
|
||||
startAccept();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
connection->startServer();
|
||||
} else {
|
||||
connection->startAgent();
|
||||
}
|
||||
} else {
|
||||
log_->write("[TCPServer handleAccept] Error: " + error.message(),
|
||||
Log::Level::ERROR);
|
||||
}
|
||||
} catch (const std::exception &ex) {
|
||||
log_->write("[TCPServer handleAccept] Exception: " + std::string(ex.what()),
|
||||
Log::Level::ERROR);
|
||||
} catch (...) {
|
||||
log_->write("[TCPServer handleAccept] Unknown exception",
|
||||
if (!error) {
|
||||
// No error, start the connection
|
||||
connection->start();
|
||||
} else {
|
||||
// Log error details
|
||||
log_->write("TCPServer handleAccept] " + std::string(error.message()),
|
||||
Log::Level::ERROR);
|
||||
}
|
||||
|
||||
// Continue accepting new connections
|
||||
startAccept();
|
||||
}
|
||||
}
|
||||
+44
-3
@@ -1,32 +1,73 @@
|
||||
#pragma once
|
||||
#ifndef TCPSERVER_HPP
|
||||
#define TCPSERVER_HPP
|
||||
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <boost/enable_shared_from_this.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
|
||||
#include "agenthandler.hpp"
|
||||
#include "general.hpp"
|
||||
#include "serverhandler.hpp"
|
||||
#include "tcpconnection.hpp"
|
||||
|
||||
/**
|
||||
* @brief This class is to create and handle a TCP server.
|
||||
* It listens to the IP:Port and handles the socket.
|
||||
*/
|
||||
class TCPServer {
|
||||
public:
|
||||
using pointer = boost::shared_ptr<TCPServer>;
|
||||
|
||||
/**
|
||||
* @brief Factory method to create a TCPServer instance.
|
||||
*
|
||||
* @param io_context The io_context to be used for asynchronous operations.
|
||||
* @param config The shared configuration object.
|
||||
* @param log The shared log object.
|
||||
* @return pointer A shared pointer to the created TCPServer instance.
|
||||
*/
|
||||
static pointer create(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log) {
|
||||
return pointer(new TCPServer(io_context, config, log));
|
||||
}
|
||||
|
||||
void startAccept();
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Constructs a TCPServer instance.
|
||||
*
|
||||
* @param io_context The io_context to be used for asynchronous operations.
|
||||
* @param config The shared configuration object.
|
||||
* @param log The shared log object.
|
||||
*/
|
||||
explicit TCPServer(boost::asio::io_context &io_context,
|
||||
const std::shared_ptr<Config> &config,
|
||||
const std::shared_ptr<Log> &log);
|
||||
|
||||
/**
|
||||
* @brief Starts accepting incoming connections.
|
||||
*/
|
||||
void startAccept();
|
||||
|
||||
/**
|
||||
* @brief Handles the acceptance of a new connection.
|
||||
*
|
||||
* @param connection The pointer to the new TCP connection.
|
||||
* @param error The error code from the accept operation.
|
||||
*/
|
||||
void handleAccept(TCPConnection::pointer connection,
|
||||
const boost::system::error_code &error);
|
||||
|
||||
const std::shared_ptr<Config> &config_;
|
||||
const std::shared_ptr<Log> &log_;
|
||||
TCPClient::pointer client_;
|
||||
boost::asio::io_context &io_context_;
|
||||
boost::asio::ip::tcp::acceptor acceptor_;
|
||||
};
|
||||
|
||||
// Strand to ensure that handler functions are not called concurrently.
|
||||
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
|
||||
};
|
||||
|
||||
#endif /* TCPSERVER_HPP */
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
C++20 or higher
|
||||
libyaml-cpp >= 0.8
|
||||
boost-libs >= 1.88.0
|
||||
boost-libs >= 1.75.0
|
||||
OpenSSL
|
||||
|
||||
### Dependencies
|
||||
|
||||
@@ -1,66 +1,28 @@
|
||||
---
|
||||
# This block contains general and global configuration which is in both modes
|
||||
general:
|
||||
# token: 32 bytes of string. this will be used on agent and server side to encryption
|
||||
token: "af445adb-2434-4975-9445-2c1b2231"
|
||||
# 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
|
||||
fakeUrl: "http://www.adas.com/api01"
|
||||
# method: "HEAD|GET|POST|PUT|DELETE"
|
||||
# Defines with which method
|
||||
# you like to send requests from agent to server
|
||||
# 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
|
||||
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
|
||||
# timeout: unsigned short
|
||||
# Defines the timeout for I/O Operation in seconds. 0 indicates no timeout.
|
||||
# Useful to automatically close stalled connections.
|
||||
timeout: 10
|
||||
# pullTimeout: unsigned short
|
||||
# Defines the timeout for I/O Operation in milliseconds.
|
||||
# Useful to expire serverside read timer.
|
||||
pullTimeout: 50
|
||||
# tunnelEnable: bool
|
||||
# Defines the connection mode between agent and server. If enabled then the traffic
|
||||
# will be TCP/TLS tunnel like.
|
||||
tunnelEnable: false
|
||||
# connectionReuse: bool
|
||||
# If false then it will use same connection between agent and server to handle client request
|
||||
# If true then it will create new connection for each request between agent and server
|
||||
connectionReuse: true
|
||||
# tlsEnable: bool
|
||||
# It enables or disables tls between agent and server
|
||||
tlsEnable: false
|
||||
# tlsVerifyPeer: bool
|
||||
# Use it to controll if the certificate should be validated or not
|
||||
tlsVerifyPeer: false
|
||||
# Use following configurations to specify the key and cert which will be used between agent and server
|
||||
tlsCertFile: "/etc/nipovpn/server.crt"
|
||||
tlsKeyFile: "/etc/nipovpn/server.key"
|
||||
tlsCaFile: ""
|
||||
|
||||
# repeatWait: unsigned short(1-65,635)
|
||||
# Defines the loop count which will try to repeat read from socket.
|
||||
# Same as timeWait
|
||||
repeatWait: 10
|
||||
|
||||
# This block is to define log directives
|
||||
log:
|
||||
# logLevel: "INFO|TRACE|DEBUG"
|
||||
logLevel: "DEBUG"
|
||||
logLevel: "TRACE"
|
||||
# logFile: "/var/log/nipo/nipo.log"
|
||||
# Path of log file
|
||||
logFile: "/var/log/nipovpn/nipovpn.log"
|
||||
@@ -72,8 +34,7 @@ server:
|
||||
# listenIp: which must be IPv4 which is used on server
|
||||
listenIp: "0.0.0.0"
|
||||
# listenPort: the port number which will be used on server
|
||||
listenPort: 80
|
||||
|
||||
listenPort: 443
|
||||
|
||||
# This block is to define agent directives
|
||||
agent:
|
||||
@@ -84,10 +45,12 @@ agent:
|
||||
# listenPort: the port number which will be used on agent
|
||||
listenPort: 8080
|
||||
# serverIp: IPv4 of the nipoServer
|
||||
serverIp: "127.0.0.10"
|
||||
serverIp: "127.0.0.1"
|
||||
# serverPort: port number of the nipoServer
|
||||
serverPort: 80
|
||||
serverPort: 443
|
||||
# token: 32 bytes of string. this will be used on agent and server side to encryption
|
||||
token: "af445adb-2434-4975-9445-2c1b2231"
|
||||
# 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 : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0"
|
||||
userAgent : "NipoAgent"
|
||||
Reference in new issue
Block a user