Compare commits
30 Commits
33bbd7cce6
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| 7d56f9db5d | |||
| 4609e85ca9 | |||
| 154296bcdc | |||
| 867b2c953a | |||
| 83693ed1da | |||
| 62335f3693 | |||
| 2d3d6afb07 | |||
| ccbacd1180 | |||
| cf3ec30492 | |||
| 1d34953f25 | |||
| b9903f5a8e | |||
| 1f5a0585f3 | |||
| 3dc5c04bf1 | |||
| 37ddb82d9a | |||
| 8923f45356 | |||
| d5bf741650 | |||
| ae507c3fb9 | |||
| 072fb69a4a | |||
| 6031d9655a | |||
| 16cd980c0a | |||
| 68a825b7df | |||
| 17cc314c26 | |||
| 225aa2a55d | |||
| cab1362053 | |||
| c047cb90f0 | |||
| 5e3aef78a5 | |||
| 4ff33ffdab | |||
| 7d9018043d | |||
| b50b594d68 | |||
| 842752cd88 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -13,3 +13,4 @@ CMakeUserPresets.json
|
|||||||
|
|
||||||
build/
|
build/
|
||||||
.vscode/
|
.vscode/
|
||||||
|
.DS_Store
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
## ASIO C++ Library
|
## ASIO C++ Library
|
||||||
- **Name:** ASIO (standalone)
|
- **Name:** ASIO (standalone)
|
||||||
- **Website:** https://think-async.com/Asio/
|
- **Website:** https://think-async.com/Asio/
|
||||||
- **Copyright:** (c) 2003-2025 Christopher M. Kohlhoff
|
- **Copyright:** (c) 2003-2026 Christopher M. Kohlhoff
|
||||||
- **License:** Boost Software License, Version 1.0
|
- **License:** Boost Software License, Version 1.0
|
||||||
- **License Text:** See `third_party/asio/LICENSE_1_0.txt`
|
- **License Text:** See `third_party/asio/LICENSE_1_0.txt`
|
||||||
|
|
||||||
@@ -12,14 +12,14 @@ This project uses the standalone version of the ASIO C++ library for asynchronou
|
|||||||
## CXXOPTS C++ Library
|
## CXXOPTS C++ Library
|
||||||
- **Name:** cxxopts
|
- **Name:** cxxopts
|
||||||
- **Website:** https://github.com/jarro2783/cxxopts/
|
- **Website:** https://github.com/jarro2783/cxxopts/
|
||||||
- **Copyright:** (c) 2014-2025 Christopher M. Kohlhoff
|
- **Copyright:** (c) 2014-2026 Christopher M. Kohlhoff
|
||||||
- **License:** MIT License
|
- **License:** MIT License
|
||||||
- **License Text:** See `third_party/cxxopts/LICENSE_1_0.txt`
|
- **License Text:** See `third_party/cxxopts/LICENSE_1_0.txt`
|
||||||
|
|
||||||
## Wintun C++ Library
|
## Wintun C++ Library
|
||||||
- **Name:** wintun
|
- **Name:** wintun
|
||||||
- **Website:** https://www.wintun.net/
|
- **Website:** https://www.wintun.net/
|
||||||
- **Copyright:** (c) 2018-2025 WireGuard LLC
|
- **Copyright:** (c) 2018-2026 WireGuard LLC
|
||||||
- **License:** MIT License OR GPL-2.0 License
|
- **License:** MIT License OR GPL-2.0 License
|
||||||
- **License Text:** See `third_party/wintun/`
|
- **License Text:** See `third_party/wintun/`
|
||||||
- **Utilized Under:** MIT License
|
- **Utilized Under:** MIT License
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ cmake_minimum_required(VERSION 3.16)
|
|||||||
# If MAJOR is 0, and MINOR > 0, Version is BETA
|
# If MAJOR is 0, and MINOR > 0, Version is BETA
|
||||||
|
|
||||||
project(ColumnLynx
|
project(ColumnLynx
|
||||||
VERSION 0.0.6
|
VERSION 1.0.1
|
||||||
LANGUAGES CXX
|
LANGUAGES CXX
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -50,7 +50,7 @@ endif()
|
|||||||
FetchContent_Declare(
|
FetchContent_Declare(
|
||||||
Sodium
|
Sodium
|
||||||
GIT_REPOSITORY https://github.com/robinlinden/libsodium-cmake.git
|
GIT_REPOSITORY https://github.com/robinlinden/libsodium-cmake.git
|
||||||
GIT_TAG e5b985ad0dd235d8c4307ea3a385b45e76c74c6a # Last updated at 2025-04-13
|
GIT_TAG e5b985ad0dd235d8c4307ea3a385b45e76c74c6a
|
||||||
)
|
)
|
||||||
|
|
||||||
set(SODIUM_DISABLE_TESTS ON CACHE BOOL "" FORCE)
|
set(SODIUM_DISABLE_TESTS ON CACHE BOOL "" FORCE)
|
||||||
@@ -80,15 +80,6 @@ FetchContent_MakeAvailable(Sodium)
|
|||||||
FetchContent_MakeAvailable(asio)
|
FetchContent_MakeAvailable(asio)
|
||||||
FetchContent_MakeAvailable(cxxopts)
|
FetchContent_MakeAvailable(cxxopts)
|
||||||
|
|
||||||
# OpenSSL
|
|
||||||
find_package(OpenSSL REQUIRED)
|
|
||||||
if(OPENSSL_FOUND)
|
|
||||||
message(STATUS "Found OpenSSL version ${OPENSSL_VERSION}")
|
|
||||||
include_directories(${OPENSSL_INCLUDE_DIR})
|
|
||||||
else()
|
|
||||||
message(FATAL_ERROR "OpenSSL not found")
|
|
||||||
endif()
|
|
||||||
|
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
# Output directories
|
# Output directories
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
@@ -108,7 +99,17 @@ endforeach()
|
|||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
file(GLOB_RECURSE COMMON_SRC CONFIGURE_DEPENDS src/common/*.cpp)
|
file(GLOB_RECURSE COMMON_SRC CONFIGURE_DEPENDS src/common/*.cpp)
|
||||||
add_library(common STATIC ${COMMON_SRC})
|
add_library(common STATIC ${COMMON_SRC})
|
||||||
target_link_libraries(common PUBLIC sodium OpenSSL::SSL OpenSSL::Crypto cxxopts::cxxopts)
|
target_link_libraries(common PUBLIC sodium cxxopts::cxxopts)
|
||||||
|
|
||||||
|
if (WIN32)
|
||||||
|
target_link_libraries(common PUBLIC
|
||||||
|
ws2_32
|
||||||
|
iphlpapi
|
||||||
|
advapi32
|
||||||
|
mswsock
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
target_include_directories(common PUBLIC
|
target_include_directories(common PUBLIC
|
||||||
${PROJECT_SOURCE_DIR}/include
|
${PROJECT_SOURCE_DIR}/include
|
||||||
${sodium_SOURCE_DIR}/src/libsodium/include
|
${sodium_SOURCE_DIR}/src/libsodium/include
|
||||||
@@ -122,7 +123,12 @@ target_compile_definitions(common PUBLIC ASIO_STANDALONE)
|
|||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
file(GLOB_RECURSE CLIENT_SRC CONFIGURE_DEPENDS src/client/*.cpp)
|
file(GLOB_RECURSE CLIENT_SRC CONFIGURE_DEPENDS src/client/*.cpp)
|
||||||
add_executable(client ${CLIENT_SRC})
|
add_executable(client ${CLIENT_SRC})
|
||||||
target_link_libraries(client PRIVATE common sodium OpenSSL::SSL OpenSSL::Crypto cxxopts::cxxopts)
|
target_link_libraries(client PRIVATE common sodium cxxopts::cxxopts)
|
||||||
|
if (WIN32)
|
||||||
|
target_link_libraries(client PRIVATE
|
||||||
|
dbghelp
|
||||||
|
)
|
||||||
|
endif()
|
||||||
target_include_directories(client PRIVATE
|
target_include_directories(client PRIVATE
|
||||||
${PROJECT_SOURCE_DIR}/include
|
${PROJECT_SOURCE_DIR}/include
|
||||||
${sodium_SOURCE_DIR}/src/libsodium/include
|
${sodium_SOURCE_DIR}/src/libsodium/include
|
||||||
@@ -137,7 +143,12 @@ set_target_properties(client PROPERTIES OUTPUT_NAME "columnlynx_client")
|
|||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
file(GLOB_RECURSE SERVER_SRC CONFIGURE_DEPENDS src/server/*.cpp)
|
file(GLOB_RECURSE SERVER_SRC CONFIGURE_DEPENDS src/server/*.cpp)
|
||||||
add_executable(server ${SERVER_SRC})
|
add_executable(server ${SERVER_SRC})
|
||||||
target_link_libraries(server PRIVATE common sodium OpenSSL::SSL OpenSSL::Crypto cxxopts::cxxopts)
|
target_link_libraries(server PRIVATE common sodium cxxopts::cxxopts)
|
||||||
|
if (WIN32)
|
||||||
|
target_link_libraries(server PRIVATE
|
||||||
|
dbghelp
|
||||||
|
)
|
||||||
|
endif()
|
||||||
target_include_directories(server PRIVATE
|
target_include_directories(server PRIVATE
|
||||||
${PROJECT_SOURCE_DIR}/include
|
${PROJECT_SOURCE_DIR}/include
|
||||||
${sodium_SOURCE_DIR}/src/libsodium/include
|
${sodium_SOURCE_DIR}/src/libsodium/include
|
||||||
|
|||||||
151
README.md
151
README.md
@@ -18,22 +18,155 @@ This simplicity-focused design approach allows us to make an efficient, low-over
|
|||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
Configurating the server and client are are relatively easy. Currently (since the project is in alpha), the configuration files **must be in the same directory as the working directory**.
|
Configurating the server and client are are relatively easy. Currently (since the project is in alpha), the configuration files **must be in your system-specific config location** (which can be overriden via a CLI argument or the **COLUMNLYNX_CONFIG_DIR** Environment Variable).
|
||||||
|
|
||||||
|
The defaults depends on your system.
|
||||||
|
|
||||||
|
For the server:
|
||||||
|
- Linux: **/etc/columnlynx**
|
||||||
|
- macOS: **/etc/columnlynx**
|
||||||
|
- Windows: **C:\ProgramData\ColumnLynx**
|
||||||
|
|
||||||
|
For the client:
|
||||||
|
- Linux: **~/.config/columnlynx**
|
||||||
|
- macOS: **~/Library/Application Support/columnlynx**
|
||||||
|
- Windows: **C:\Users\USERNAME\AppData\Local\ColumnLynx**
|
||||||
|
|
||||||
|
### Getting a keypair
|
||||||
|
|
||||||
|
Release builds of the software force you to specify your own keypairs. That's why you need to generate a keypair with some other software that you can use.
|
||||||
|
|
||||||
|
This guide will show a generation example with openssl:
|
||||||
|
|
||||||
|
#### Generate a keypair:
|
||||||
|
```bash
|
||||||
|
openssl genpkey -algorithm ED25519 -out key.pem
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Extract the **Private Key Seed**:
|
||||||
|
```bash
|
||||||
|
openssl pkey -in key.pem -outform DER | tail -c 32 | xxd -p -c 32
|
||||||
|
# Output example: 9f3a2b6c0f8e4d1a7c3e9a4b5d2f8c6e1a9d0b7e3f4c2a8e6d5b1f0a3c4e
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Extract the **Raw Public Key**:
|
||||||
|
```bash
|
||||||
|
openssl pkey -in key.pem -pubout -outform DER | tail -c 32 | xxd -p -c 32
|
||||||
|
# Output example: 1c9d4f7a3b2e8a6d0f5c9b1e4d8a7f3c6e2b1a9d5f4c8e0a7b3d6c9f2e
|
||||||
|
```
|
||||||
|
|
||||||
|
You can then set these keys accordingly in the **server_config** and **client_config** files.
|
||||||
|
|
||||||
|
### Server Setup (Linux Server ONLY)
|
||||||
|
|
||||||
|
#### Creating the Tun Interface
|
||||||
|
|
||||||
|
In order for the VPN server to work, you need to create the Tun interface that the VPN will use.
|
||||||
|
|
||||||
|
This is the set of commands to create one on Linux. Replace the example 10.10.0.1/24 IPv4 address with the FIRST IPv4 in the Network and Subnet Mask that you set in server_config.
|
||||||
|
```bash
|
||||||
|
sudo ip tuntap add dev lynx0 mode tun
|
||||||
|
sudo ip addr add 10.10.0.1/24 dev lynx0
|
||||||
|
sudo ip link set dev lynx0 mtu 1420
|
||||||
|
sudo ip link set dev lynx0 up
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Creating the systemd service
|
||||||
|
|
||||||
|
It is highly recommended to **run the server as a systemd service**, as systemd is the primary service manager on Linux.
|
||||||
|
|
||||||
|
**1. Create a file for the service**
|
||||||
|
```bash
|
||||||
|
sudo touch /etc/systemd/system/columnlynx.service
|
||||||
|
```
|
||||||
|
|
||||||
|
**2. Open the file in your editor of choice**
|
||||||
|
```bash
|
||||||
|
sudo nano /etc/systemd/system/columnlynx.service
|
||||||
|
# OR
|
||||||
|
sudo vim /etc/systemd/system/columnlynx.service
|
||||||
|
# OR any other editor of your choice...
|
||||||
|
```
|
||||||
|
|
||||||
|
**3. Configure the service**
|
||||||
|
|
||||||
|
**Replace** the **ExecStart** and **WorkingDirectory** paths with the paths where your binaries are stored.
|
||||||
|
|
||||||
|
If you configured your tun interface to belong to a custom user, you may also replace the **User** and **Group** with that user, however you must ensure that that user owns the **tun interface**, **config directory in /etc/columnlynx** and the **working directory**.
|
||||||
|
|
||||||
|
This is a **simple example** for the **root user** and the executable in **/opt/columnlynx**:
|
||||||
|
|
||||||
|
```
|
||||||
|
[Unit]
|
||||||
|
Description=ColumnLynx Server Service
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
ExecStart=/opt/columnlynx/columnlynx_server
|
||||||
|
WorkingDirectory=/opt/columnlynx
|
||||||
|
User=root
|
||||||
|
Group=root
|
||||||
|
Restart=on-failure
|
||||||
|
StandardOutput=append:/var/log/columnlynx.log
|
||||||
|
StandardError=append:/var/log/columnlynx.err
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
```
|
||||||
|
|
||||||
|
**4. Reload systemd and enable the service**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
sudo systemctl enable columnlynx.service
|
||||||
|
sudo systemctl start columnlynx.service
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Set firewall rules
|
||||||
|
|
||||||
|
This part greatly depends on your firewall of choice. Generally you just need to **allow port 48042 on both TCP and UDP** (Both IPv4 and IPv6).
|
||||||
|
|
||||||
|
This example is for **UFW**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo ufw allow 48042
|
||||||
|
sudo ufw reload
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
#### IPTables rules for forwarding (Optional)
|
||||||
|
|
||||||
|
In addition to creating the interface, you'll also need to make some **iptables** rules if you want to be able to **send traffic to foreign networks** (more like a *commercial VPN*).
|
||||||
|
|
||||||
|
You can do these as such (example with NFT IPTABLES):
|
||||||
|
|
||||||
|
- Enable the **generic IPv4 forwarding**:
|
||||||
|
```bash
|
||||||
|
sudo sysctl net.ipv4.ip_forward=1
|
||||||
|
```
|
||||||
|
- Create the masquerade (**Replace the IP subnet** with your own that you set in the config and **replace the interface** with your server's main (NOT *lynx0*) interface):
|
||||||
|
```bash
|
||||||
|
sudo nft add table nat
|
||||||
|
sudo nft add chain nat postroute { type nat hook postrouting priority 100 \; }
|
||||||
|
sudo nft add rule nat postroute ip saddr 10.10.0.0/24 oifname "eth0" masquerade
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
### Server
|
### Server
|
||||||
|
|
||||||
"**server_config**" is a file that contains the server configuration, **one variable per line**. These are the current configuration available variables:
|
"**server_config**" is a file that contains the server configuration, **one variable per line**. These are the current configuration available variables:
|
||||||
|
|
||||||
- **SERVER_PUBLIC_KEY** (Hex String): The public key to be used
|
- **SERVER_PUBLIC_KEY** (Hex String): The public key to be used - Used for verification
|
||||||
- **SERVER_PRIVATE_KEY** (Hex String): The private key to be used
|
- **SERVER_PRIVATE_KEY** (Hex String): The private key seed to be used
|
||||||
- **NETWORK** (IPv4 Format): The network IPv4 to be used (Server Interface still needs to be configured manually)
|
- **NETWORK** (IPv4 Format): The network IPv4 to be used (Server Interface still needs to be configured manually)
|
||||||
- **SUBNET_MASK** (Integer): The subnet mask to be used (ensure proper length, it will not be checked)
|
- **SUBNET_MASK** (Integer): The subnet mask to be used (ensure proper length, it will not be checked)
|
||||||
|
|
||||||
**Example:**
|
**Example:**
|
||||||
|
|
||||||
```
|
```
|
||||||
SERVER_PUBLIC_KEY=787B648046F10DDD0B77A6303BE42D859AA65C52F5708CC3C58EB5691F217C7B
|
SERVER_PUBLIC_KEY=1c9d4f7a3b2e8a6d0f5c9b1e4d8a7f3c6e2b1a9d5f4c8e0a7b3d6c9f2e
|
||||||
SERVER_PRIVATE_KEY=778604245F57B847E63BD85DE8208FF1A127FB559895195928C3987E246B77B8787B648046F10DDD0B77A6303BE42D859AA65C52F5708CC3C58EB5691F217C7B
|
SERVER_PRIVATE_KEY=9f3a2b6c0f8e4d1a7c3e9a4b5d2f8c6e1a9d0b7e3f4c2a8e6d5b1f0a3c4e
|
||||||
NETWORK=10.10.0.0
|
NETWORK=10.10.0.0
|
||||||
SUBNET_MASK=24
|
SUBNET_MASK=24
|
||||||
```
|
```
|
||||||
@@ -53,14 +186,14 @@ SUBNET_MASK=24
|
|||||||
|
|
||||||
"**client_config**" is a file that contains the client configuration, **one variable per line**. These are the current configuration available variables:
|
"**client_config**" is a file that contains the client configuration, **one variable per line**. These are the current configuration available variables:
|
||||||
|
|
||||||
- **CLIENT_PUBLIC_KEY** (Hex String): The public key to be used
|
- **CLIENT_PUBLIC_KEY** (Hex String): The public key to be used - Used for verification
|
||||||
- **CLIENT_PRIVATE_KEY** (Hex String): The private key to be used
|
- **CLIENT_PRIVATE_KEY** (Hex String): The private key seed to be used
|
||||||
|
|
||||||
**Example:**
|
**Example:**
|
||||||
|
|
||||||
```
|
```
|
||||||
CLIENT_PUBLIC_KEY=8CC8BE1A9D24639D0492EF143E84E2BD4C757C9B3B687E7035173EBFCA8FEDDA
|
CLIENT_PUBLIC_KEY=1c9d4f7a3b2e8a6d0f5c9b1e4d8a7f3c6e2b1a9d5f4c8e0a7b3d6c9f2e
|
||||||
CLIENT_PRIVATE_KEY=9B486A5B1509FA216F9EEFED85CACF2384E9D902A76CC979BFA143C18B869F5C8CC8BE1A9D24639D0492EF143E84E2BD4C757C9B3B687E7035173EBFCA8FEDDA
|
CLIENT_PRIVATE_KEY=9f3a2b6c0f8e4d1a7c3e9a4b5d2f8c6e1a9d0b7e3f4c2a8e6d5b1f0a3c4e
|
||||||
```
|
```
|
||||||
|
|
||||||
<hr></hr>
|
<hr></hr>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// tcp_client.hpp - TCP Client for ColumnLynx
|
// tcp_client.hpp - TCP Client for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
@@ -14,6 +14,7 @@
|
|||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
|
#include <string>
|
||||||
#include <columnlynx/common/net/protocol_structs.hpp>
|
#include <columnlynx/common/net/protocol_structs.hpp>
|
||||||
#include <columnlynx/common/net/virtual_interface.hpp>
|
#include <columnlynx/common/net/virtual_interface.hpp>
|
||||||
|
|
||||||
@@ -29,6 +30,7 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
std::shared_ptr<std::array<uint8_t, 32>> aesKey,
|
std::shared_ptr<std::array<uint8_t, 32>> aesKey,
|
||||||
std::shared_ptr<uint64_t> sessionIDRef,
|
std::shared_ptr<uint64_t> sessionIDRef,
|
||||||
bool insecureMode,
|
bool insecureMode,
|
||||||
|
std::string& configPath,
|
||||||
std::shared_ptr<VirtualInterface> tun = nullptr)
|
std::shared_ptr<VirtualInterface> tun = nullptr)
|
||||||
:
|
:
|
||||||
mResolver(ioContext),
|
mResolver(ioContext),
|
||||||
@@ -42,10 +44,11 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
mHeartbeatTimer(mSocket.get_executor()),
|
mHeartbeatTimer(mSocket.get_executor()),
|
||||||
mLastHeartbeatReceived(std::chrono::steady_clock::now()),
|
mLastHeartbeatReceived(std::chrono::steady_clock::now()),
|
||||||
mLastHeartbeatSent(std::chrono::steady_clock::now()),
|
mLastHeartbeatSent(std::chrono::steady_clock::now()),
|
||||||
mTun(tun)
|
mTun(tun),
|
||||||
|
mConfigDirPath(configPath)
|
||||||
{
|
{
|
||||||
// Preload the config map
|
// Preload the config map
|
||||||
mRawClientConfig = Utils::getConfigMap("client_config");
|
mRawClientConfig = Utils::getConfigMap(configPath + "client_config");
|
||||||
|
|
||||||
auto itPubkey = mRawClientConfig.find("CLIENT_PUBLIC_KEY");
|
auto itPubkey = mRawClientConfig.find("CLIENT_PUBLIC_KEY");
|
||||||
auto itPrivkey = mRawClientConfig.find("CLIENT_PRIVATE_KEY");
|
auto itPrivkey = mRawClientConfig.find("CLIENT_PRIVATE_KEY");
|
||||||
@@ -54,16 +57,22 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
Utils::log("Loading keypair from config file.");
|
Utils::log("Loading keypair from config file.");
|
||||||
|
|
||||||
PublicKey pk;
|
PublicKey pk;
|
||||||
PrivateKey sk;
|
PrivateSeed seed;
|
||||||
|
|
||||||
std::copy_n(Utils::hexStringToBytes(itPrivkey->second).begin(), sk.size(), sk.begin()); // This is extremely stupid, but the C++ compiler has forced my hand (I would've just used to_array, but fucking asio decls)
|
std::copy_n(Utils::hexStringToBytes(itPrivkey->second).begin(), seed.size(), seed.begin()); // This is extremely stupid, but the C++ compiler has forced my hand (I would've just used to_array, but fucking asio decls)
|
||||||
std::copy_n(Utils::hexStringToBytes(itPubkey->second).begin(), pk.size(), pk.begin());
|
std::copy_n(Utils::hexStringToBytes(itPubkey->second).begin(), pk.size(), pk.begin());
|
||||||
|
|
||||||
mLibSodiumWrapper->setKeys(pk, sk);
|
if (!mLibSodiumWrapper->recomputeKeys(seed, pk)) {
|
||||||
|
throw std::runtime_error("Failed to recompute keypair from config file values!");
|
||||||
|
}
|
||||||
|
|
||||||
Utils::debug("Newly-Loaded Public Key: " + Utils::bytesToHexString(mLibSodiumWrapper->getPublicKey(), 32));
|
Utils::debug("Newly-Loaded Public Key: " + Utils::bytesToHexString(mLibSodiumWrapper->getPublicKey(), 32));
|
||||||
} else {
|
} else {
|
||||||
|
#if defined(DEBUG)
|
||||||
Utils::warn("No keypair found in config file! Using random key.");
|
Utils::warn("No keypair found in config file! Using random key.");
|
||||||
|
#else
|
||||||
|
throw std::runtime_error("No keypair found in config file! Cannot start client without keys.");
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,5 +118,6 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
Protocol::TunConfig mTunConfig;
|
Protocol::TunConfig mTunConfig;
|
||||||
std::shared_ptr<VirtualInterface> mTun = nullptr;
|
std::shared_ptr<VirtualInterface> mTun = nullptr;
|
||||||
std::unordered_map<std::string, std::string> mRawClientConfig;
|
std::unordered_map<std::string, std::string> mRawClientConfig;
|
||||||
|
std::string mConfigDirPath;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
// udp_client.hpp - UDP Client for ColumnLynx
|
// udp_client.hpp - UDP Client for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// libsodium_wrapper.hpp - Libsodium Wrapper for ColumnLynx
|
// libsodium_wrapper.hpp - Libsodium Wrapper for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
@@ -11,16 +11,13 @@
|
|||||||
#include <columnlynx/common/utils.hpp>
|
#include <columnlynx/common/utils.hpp>
|
||||||
#include <array>
|
#include <array>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include <openssl/x509.h>
|
|
||||||
#include <openssl/x509_vfy.h>
|
|
||||||
#include <openssl/pem.h>
|
|
||||||
#include <openssl/x509v3.h>
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
|
|
||||||
namespace ColumnLynx {
|
namespace ColumnLynx {
|
||||||
using PublicKey = std::array<uint8_t, crypto_sign_PUBLICKEYBYTES>; // Ed25519
|
using PublicKey = std::array<uint8_t, crypto_sign_PUBLICKEYBYTES>; // Ed25519
|
||||||
using PrivateKey = std::array<uint8_t, crypto_sign_SECRETKEYBYTES>; // Ed25519
|
using PrivateKey = std::array<uint8_t, crypto_sign_SECRETKEYBYTES>; // Ed25519
|
||||||
|
using PrivateSeed = std::array<uint8_t, crypto_sign_SEEDBYTES>; // 32 bytes
|
||||||
using Signature = std::array<uint8_t, crypto_sign_BYTES>; // 64 bytes
|
using Signature = std::array<uint8_t, crypto_sign_BYTES>; // 64 bytes
|
||||||
using SymmetricKey = std::array<uint8_t, crypto_aead_chacha20poly1305_ietf_KEYBYTES>; // 32 bytes
|
using SymmetricKey = std::array<uint8_t, crypto_aead_chacha20poly1305_ietf_KEYBYTES>; // 32 bytes
|
||||||
using Nonce = std::array<uint8_t, crypto_aead_chacha20poly1305_ietf_NPUBBYTES>; // 12 bytes
|
using Nonce = std::array<uint8_t, crypto_aead_chacha20poly1305_ietf_NPUBBYTES>; // 12 bytes
|
||||||
@@ -57,6 +54,9 @@ namespace ColumnLynx::Utils {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Recompute the keypair from a given private seed; Will return false on failure
|
||||||
|
bool recomputeKeys(PrivateSeed privateSeed, PublicKey storedPubKey);
|
||||||
|
|
||||||
// Helper section
|
// Helper section
|
||||||
|
|
||||||
// Generates a random 256-bit (32-byte) array
|
// Generates a random 256-bit (32-byte) array
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// protocol_structs.hpp - Network Protocol Structures
|
// protocol_structs.hpp - Network Protocol Structures
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// session_registry.hpp - Session Registry for ColumnLynx
|
// session_registry.hpp - Session Registry for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
@@ -10,6 +10,9 @@
|
|||||||
#include <array>
|
#include <array>
|
||||||
#include <cmath>
|
#include <cmath>
|
||||||
#include <sodium.h>
|
#include <sodium.h>
|
||||||
|
#include <mutex>
|
||||||
|
#include <atomic>
|
||||||
|
#include <asio.hpp>
|
||||||
#include <columnlynx/common/utils.hpp>
|
#include <columnlynx/common/utils.hpp>
|
||||||
#include <columnlynx/common/libsodium_wrapper.hpp>
|
#include <columnlynx/common/libsodium_wrapper.hpp>
|
||||||
|
|
||||||
@@ -49,107 +52,36 @@ namespace ColumnLynx::Net {
|
|||||||
static SessionRegistry& getInstance() { static SessionRegistry instance; return instance; }
|
static SessionRegistry& getInstance() { static SessionRegistry instance; return instance; }
|
||||||
|
|
||||||
// Insert or replace a session entry
|
// Insert or replace a session entry
|
||||||
void put(uint64_t sessionID, std::shared_ptr<SessionState> state) {
|
void put(uint64_t sessionID, std::shared_ptr<SessionState> state);
|
||||||
std::unique_lock lock(mMutex);
|
|
||||||
mSessions[sessionID] = std::move(state);
|
|
||||||
mIPSessions[mSessions[sessionID]->clientTunIP] = mSessions[sessionID];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lookup a session entry by session ID
|
// Lookup a session entry by session ID
|
||||||
std::shared_ptr<const SessionState> get(uint64_t sessionID) const {
|
std::shared_ptr<const SessionState> get(uint64_t sessionID) const;
|
||||||
std::shared_lock lock(mMutex);
|
|
||||||
auto it = mSessions.find(sessionID);
|
|
||||||
return (it == mSessions.end()) ? nullptr : it->second;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lookup a session entry by IPv4
|
// Lookup a session entry by IPv4
|
||||||
std::shared_ptr<const SessionState> getByIP(uint32_t ip) const {
|
std::shared_ptr<const SessionState> getByIP(uint32_t ip) const;
|
||||||
std::shared_lock lock(mMutex);
|
|
||||||
auto it = mIPSessions.find(ip);
|
|
||||||
return (it == mIPSessions.end()) ? nullptr : it->second;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get a snapshot of the Session Registry
|
// Get a snapshot of the Session Registry
|
||||||
std::unordered_map<uint64_t, std::shared_ptr<SessionState>> snapshot() const {
|
std::unordered_map<uint64_t, std::shared_ptr<SessionState>> snapshot() const;
|
||||||
std::unordered_map<uint64_t, std::shared_ptr<SessionState>> snap;
|
|
||||||
std::shared_lock lock(mMutex);
|
|
||||||
snap = mSessions;
|
|
||||||
return snap;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove a session by ID
|
// Remove a session by ID
|
||||||
void erase(uint64_t sessionID) {
|
void erase(uint64_t sessionID);
|
||||||
std::unique_lock lock(mMutex);
|
|
||||||
mSessions.erase(sessionID);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cleanup expired sessions
|
// Cleanup expired sessions
|
||||||
void cleanupExpired() {
|
void cleanupExpired();
|
||||||
std::unique_lock lock(mMutex);
|
|
||||||
auto now = std::chrono::steady_clock::now();
|
|
||||||
for (auto it = mSessions.begin(); it != mSessions.end(); ) {
|
|
||||||
if (it->second && it->second->expires <= now) {
|
|
||||||
it = mSessions.erase(it);
|
|
||||||
} else {
|
|
||||||
++it;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (auto it = mIPSessions.begin(); it != mIPSessions.end(); ) {
|
|
||||||
if (it->second && it->second->expires <= now) {
|
|
||||||
it = mIPSessions.erase(it);
|
|
||||||
} else {
|
|
||||||
++it;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the number of registered sessions
|
// Get the number of registered sessions
|
||||||
int size() const {
|
int size() const;
|
||||||
std::shared_lock lock(mMutex);
|
|
||||||
return static_cast<int>(mSessions.size());
|
|
||||||
}
|
|
||||||
|
|
||||||
// IP management
|
// IP management
|
||||||
|
|
||||||
// Get the lowest available IPv4 address; Returns 0 if none available
|
// Get the lowest available IPv4 address; Returns 0 if none available
|
||||||
uint32_t getFirstAvailableIP(uint32_t baseIP, uint8_t mask) const {
|
uint32_t getFirstAvailableIP(uint32_t baseIP, uint8_t mask) const;
|
||||||
std::shared_lock lock(mMutex);
|
|
||||||
|
|
||||||
uint32_t hostCount = (1u << (32 - mask));
|
// Lock IP to session ID; Do NOT call before put() - You will segfault!
|
||||||
uint32_t firstHost = 2;
|
void lockIP(uint64_t sessionID, uint32_t ip);
|
||||||
uint32_t lastHost = hostCount - 2;
|
|
||||||
|
|
||||||
for (uint32_t offset = firstHost; offset <= lastHost; offset++) {
|
// Unlock IP from session ID
|
||||||
uint32_t candidateIP = baseIP + offset;
|
void deallocIP(uint64_t sessionID);
|
||||||
if (mIPSessions.find(candidateIP) == mIPSessions.end()) {
|
|
||||||
return candidateIP;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
void lockIP(uint64_t sessionID, uint32_t ip) {
|
|
||||||
std::unique_lock lock(mMutex);
|
|
||||||
mSessionIPs[sessionID] = ip;
|
|
||||||
|
|
||||||
/*if (mIPSessions.find(sessionID) == mIPSessions.end()) {
|
|
||||||
Utils::debug("yikes");
|
|
||||||
}*/
|
|
||||||
mIPSessions[ip] = mSessions.find(sessionID)->second;
|
|
||||||
}
|
|
||||||
|
|
||||||
void deallocIP(uint64_t sessionID) {
|
|
||||||
std::unique_lock lock(mMutex);
|
|
||||||
|
|
||||||
auto it = mSessionIPs.find(sessionID);
|
|
||||||
if (it != mSessionIPs.end()) {
|
|
||||||
uint32_t ip = it->second;
|
|
||||||
mIPSessions.erase(ip);
|
|
||||||
mSessionIPs.erase(it);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
mutable std::shared_mutex mMutex;
|
mutable std::shared_mutex mMutex;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// net_helper.hpp - Network Helper Functions for ColumnLynx
|
// net_helper.hpp - Network Helper Functions for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// tcp_message_handler.hpp - TCP Message Handler for ColumnLynx
|
// tcp_message_handler.hpp - TCP Message Handler for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// tcp_message_type.hpp - TCP Message Types for ColumnLynx
|
// tcp_message_type.hpp - TCP Message Types for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// udp_message_type.hpp - UDP Message Types for ColumnLynx
|
// udp_message_type.hpp - UDP Message Types for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// virtual_interface.hpp - Virtual Interface for Network Communication
|
// virtual_interface.hpp - Virtual Interface for Network Communication
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
@@ -26,12 +26,22 @@
|
|||||||
#include <sys/ioctl.h>
|
#include <sys/ioctl.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
#include <arpa/inet.h>
|
#include <arpa/inet.h>
|
||||||
|
#include <sys/poll.h>
|
||||||
#elif defined(_WIN32)
|
#elif defined(_WIN32)
|
||||||
|
#define WIN32_LEAN_AND_MEAN
|
||||||
|
#define WINTUN_STATIC
|
||||||
#include <windows.h>
|
#include <windows.h>
|
||||||
#include <ws2tcpip.h>
|
|
||||||
#include <winsock2.h>
|
#include <winsock2.h>
|
||||||
|
#include <ws2tcpip.h>
|
||||||
|
#include <locale>
|
||||||
|
#include <codecvt>
|
||||||
#include <wintun/wintun.h>
|
#include <wintun/wintun.h>
|
||||||
#pragma comment(lib, "advapi32.lib")
|
|
||||||
|
#include <iphlpapi.h>
|
||||||
|
#include <netioapi.h>
|
||||||
|
|
||||||
|
#pragma comment(lib, "iphlpapi.lib")
|
||||||
|
#pragma comment(lib, "ws2_32.lib")
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace ColumnLynx::Net {
|
namespace ColumnLynx::Net {
|
||||||
@@ -43,15 +53,21 @@ namespace ColumnLynx::Net {
|
|||||||
bool configureIP(uint32_t clientIP, uint32_t serverIP,
|
bool configureIP(uint32_t clientIP, uint32_t serverIP,
|
||||||
uint8_t prefixLen, uint16_t mtu);
|
uint8_t prefixLen, uint16_t mtu);
|
||||||
|
|
||||||
|
void resetIP();
|
||||||
|
|
||||||
std::vector<uint8_t> readPacket();
|
std::vector<uint8_t> readPacket();
|
||||||
void writePacket(const std::vector<uint8_t>& packet);
|
void writePacket(const std::vector<uint8_t>& packet);
|
||||||
|
|
||||||
const std::string& getName() const;
|
const std::string& getName() const;
|
||||||
int getFd() const; // For ASIO integration (on POSIX)
|
int getFd() const; // For ASIO integration (on POSIX)
|
||||||
|
|
||||||
static inline std::string ipv4ToString(uint32_t ip) {
|
static inline std::string ipv4ToString(uint32_t ip, bool flip = true) {
|
||||||
struct in_addr addr;
|
struct in_addr addr;
|
||||||
|
|
||||||
|
if (flip)
|
||||||
addr.s_addr = htonl(ip);
|
addr.s_addr = htonl(ip);
|
||||||
|
else
|
||||||
|
addr.s_addr = ip;
|
||||||
|
|
||||||
char buf[INET_ADDRSTRLEN];
|
char buf[INET_ADDRSTRLEN];
|
||||||
if (!inet_ntop(AF_INET, &addr, buf, sizeof(buf)))
|
if (!inet_ntop(AF_INET, &addr, buf, sizeof(buf)))
|
||||||
@@ -70,6 +86,42 @@ namespace ColumnLynx::Net {
|
|||||||
return ntohl(addr.s_addr);
|
return ntohl(addr.s_addr);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static inline std::string ipv6ToString(IPv6Addr &ip,
|
||||||
|
bool flip = false)
|
||||||
|
{
|
||||||
|
struct in6_addr addr;
|
||||||
|
|
||||||
|
if (flip) {
|
||||||
|
IPv6Addr flipped;
|
||||||
|
for (size_t i = 0; i < 16; ++i)
|
||||||
|
flipped[i] = ip[15 - i];
|
||||||
|
memcpy(addr.s6_addr, flipped.data(), 16);
|
||||||
|
} else {
|
||||||
|
memcpy(addr.s6_addr, ip.data(), 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
char buf[INET6_ADDRSTRLEN];
|
||||||
|
if (!inet_ntop(AF_INET6, &addr, buf, sizeof(buf)))
|
||||||
|
return "::"; // Fallback
|
||||||
|
|
||||||
|
return std::string(buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline IPv6Addr stringToIpv6(const std::string &ipStr)
|
||||||
|
{
|
||||||
|
IPv6Addr result{};
|
||||||
|
struct in6_addr addr;
|
||||||
|
|
||||||
|
if (inet_pton(AF_INET6, ipStr.c_str(), &addr) != 1) {
|
||||||
|
// "::"
|
||||||
|
result.fill(0);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
memcpy(result.data(), addr.s6_addr, 16);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
static inline uint32_t prefixLengthToNetmask(uint8_t prefixLen) {
|
static inline uint32_t prefixLengthToNetmask(uint8_t prefixLen) {
|
||||||
if (prefixLen == 0) return 0;
|
if (prefixLen == 0) return 0;
|
||||||
uint32_t mask = (0xFFFFFFFF << (32 - prefixLen)) & 0xFFFFFFFF;
|
uint32_t mask = (0xFFFFFFFF << (32 - prefixLen)) & 0xFFFFFFFF;
|
||||||
@@ -84,7 +136,9 @@ namespace ColumnLynx::Net {
|
|||||||
std::string mIfName;
|
std::string mIfName;
|
||||||
int mFd; // POSIX
|
int mFd; // POSIX
|
||||||
#if defined(_WIN32)
|
#if defined(_WIN32)
|
||||||
HANDLE mHandle; // Windows
|
WINTUN_ADAPTER_HANDLE mAdapter = nullptr;
|
||||||
|
WINTUN_SESSION_HANDLE mSession = nullptr;
|
||||||
|
HANDLE mHandle = nullptr;
|
||||||
#endif
|
#endif
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
// panic_handler.hpp - Panic Handler for ColumnLynx
|
// panic_handler.hpp - Panic Handler for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
@@ -186,7 +186,7 @@ namespace ColumnLynx::Utils {
|
|||||||
|
|
||||||
// Panic the main thread and instantly halt execution. This produces a stack trace dump. Do not use by itself, throw an error instead.
|
// Panic the main thread and instantly halt execution. This produces a stack trace dump. Do not use by itself, throw an error instead.
|
||||||
static void panic(const std::string& reason) {
|
static void panic(const std::string& reason) {
|
||||||
std::cerr << "\n***\033[31m MAIN THREAD PANIC! \033[0m***\n";
|
std::cerr << "\n***\033[31m MASTER THREAD PANIC! \033[0m***\n";
|
||||||
std::cerr << "Reason: " << reason << "\n";
|
std::cerr << "Reason: " << reason << "\n";
|
||||||
std::cerr << "Dumping panic trace...\n";
|
std::cerr << "Dumping panic trace...\n";
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// utils.hpp - Utility functions for ColumnLynx
|
// utils.hpp - Utility functions for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
@@ -29,6 +29,9 @@ namespace ColumnLynx {
|
|||||||
}
|
}
|
||||||
|
|
||||||
namespace ColumnLynx::Utils {
|
namespace ColumnLynx::Utils {
|
||||||
|
// Converts unix milliseconds to a local ISO 8601 formatted string; Defaults to local time; Will use UTC if local is false.
|
||||||
|
std::string unixMillisToISO8601(uint64_t unixMillis, bool local = true);
|
||||||
|
|
||||||
// General log function. Use for logging important information.
|
// General log function. Use for logging important information.
|
||||||
void log(const std::string &msg);
|
void log(const std::string &msg);
|
||||||
// General warning function. Use for logging important warnings.
|
// General warning function. Use for logging important warnings.
|
||||||
@@ -44,7 +47,7 @@ namespace ColumnLynx::Utils {
|
|||||||
std::string getVersion();
|
std::string getVersion();
|
||||||
unsigned short serverPort();
|
unsigned short serverPort();
|
||||||
unsigned char protocolVersion();
|
unsigned char protocolVersion();
|
||||||
std::vector<std::string> getWhitelistedKeys();
|
std::vector<std::string> getWhitelistedKeys(std::string basePath);
|
||||||
|
|
||||||
// Raw byte to hex string conversion helper
|
// Raw byte to hex string conversion helper
|
||||||
std::string bytesToHexString(const uint8_t* bytes, size_t length);
|
std::string bytesToHexString(const uint8_t* bytes, size_t length);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// tcp_connection.hpp - TCP Connection for ColumnLynx
|
// tcp_connection.hpp - TCP Connection for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
@@ -28,9 +28,10 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
asio::ip::tcp::socket socket,
|
asio::ip::tcp::socket socket,
|
||||||
std::shared_ptr<Utils::LibSodiumWrapper> sodiumWrapper,
|
std::shared_ptr<Utils::LibSodiumWrapper> sodiumWrapper,
|
||||||
std::unordered_map<std::string, std::string>* serverConfig,
|
std::unordered_map<std::string, std::string>* serverConfig,
|
||||||
|
std::string configDirPath,
|
||||||
std::function<void(pointer)> onDisconnect)
|
std::function<void(pointer)> onDisconnect)
|
||||||
{
|
{
|
||||||
auto conn = pointer(new TCPConnection(std::move(socket), sodiumWrapper, serverConfig));
|
auto conn = pointer(new TCPConnection(std::move(socket), sodiumWrapper, serverConfig, configDirPath));
|
||||||
conn->mOnDisconnect = std::move(onDisconnect);
|
conn->mOnDisconnect = std::move(onDisconnect);
|
||||||
return conn;
|
return conn;
|
||||||
}
|
}
|
||||||
@@ -42,7 +43,7 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
// Set callback for disconnects
|
// Set callback for disconnects
|
||||||
void setDisconnectCallback(std::function<void(std::shared_ptr<TCPConnection>)> cb);
|
void setDisconnectCallback(std::function<void(std::shared_ptr<TCPConnection>)> cb);
|
||||||
// Disconnect the client
|
// Disconnect the client
|
||||||
void disconnect();
|
void disconnect(bool echo = true);
|
||||||
|
|
||||||
// Get the assigned session ID
|
// Get the assigned session ID
|
||||||
uint64_t getSessionID() const;
|
uint64_t getSessionID() const;
|
||||||
@@ -50,14 +51,15 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
std::array<uint8_t, 32> getAESKey() const;
|
std::array<uint8_t, 32> getAESKey() const;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
TCPConnection(asio::ip::tcp::socket socket, std::shared_ptr<Utils::LibSodiumWrapper> sodiumWrapper, std::unordered_map<std::string, std::string>* serverConfig)
|
TCPConnection(asio::ip::tcp::socket socket, std::shared_ptr<Utils::LibSodiumWrapper> sodiumWrapper, std::unordered_map<std::string, std::string>* serverConfig, std::string configDirPath)
|
||||||
:
|
:
|
||||||
mHandler(std::make_shared<MessageHandler>(std::move(socket))),
|
mHandler(std::make_shared<MessageHandler>(std::move(socket))),
|
||||||
mLibSodiumWrapper(sodiumWrapper),
|
mLibSodiumWrapper(sodiumWrapper),
|
||||||
mRawServerConfig(serverConfig),
|
mRawServerConfig(serverConfig),
|
||||||
mHeartbeatTimer(mHandler->socket().get_executor()),
|
mHeartbeatTimer(mHandler->socket().get_executor()),
|
||||||
mLastHeartbeatReceived(std::chrono::steady_clock::now()),
|
mLastHeartbeatReceived(std::chrono::steady_clock::now()),
|
||||||
mLastHeartbeatSent(std::chrono::steady_clock::now())
|
mLastHeartbeatSent(std::chrono::steady_clock::now()),
|
||||||
|
mConfigDirPath(configDirPath)
|
||||||
{}
|
{}
|
||||||
|
|
||||||
// Start the heartbeat routine
|
// Start the heartbeat routine
|
||||||
@@ -76,5 +78,7 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
std::chrono::steady_clock::time_point mLastHeartbeatReceived;
|
std::chrono::steady_clock::time_point mLastHeartbeatReceived;
|
||||||
std::chrono::steady_clock::time_point mLastHeartbeatSent;
|
std::chrono::steady_clock::time_point mLastHeartbeatSent;
|
||||||
int mMissedHeartbeats = 0;
|
int mMissedHeartbeats = 0;
|
||||||
|
std::string mRemoteIP; // Cached remote IP to avoid calling remote_endpoint() on closed sockets
|
||||||
|
std::string mConfigDirPath;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
// tcp_server.hpp - TCP Server for ColumnLynx
|
// tcp_server.hpp - TCP Server for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
@@ -25,33 +25,45 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
TCPServer(asio::io_context& ioContext,
|
TCPServer(asio::io_context& ioContext,
|
||||||
uint16_t port,
|
uint16_t port,
|
||||||
std::shared_ptr<Utils::LibSodiumWrapper> sodiumWrapper,
|
std::shared_ptr<Utils::LibSodiumWrapper> sodiumWrapper,
|
||||||
std::shared_ptr<bool> hostRunning, bool ipv4Only = false)
|
std::shared_ptr<bool> hostRunning,
|
||||||
|
std::string& configPath,
|
||||||
|
bool ipv4Only = false)
|
||||||
: mIoContext(ioContext),
|
: mIoContext(ioContext),
|
||||||
mAcceptor(ioContext),
|
mAcceptor(ioContext),
|
||||||
mSodiumWrapper(sodiumWrapper),
|
mSodiumWrapper(sodiumWrapper),
|
||||||
mHostRunning(hostRunning)
|
mHostRunning(hostRunning),
|
||||||
|
mConfigDirPath(configPath)
|
||||||
{
|
{
|
||||||
// Preload the config map
|
// Preload the config map
|
||||||
mRawServerConfig = Utils::getConfigMap("server_config", {"NETWORK", "SUBNET_MASK"});
|
mRawServerConfig = Utils::getConfigMap(configPath + "server_config", {"NETWORK", "SUBNET_MASK"});
|
||||||
|
|
||||||
asio::error_code ec;
|
asio::error_code ec_open, ec_v6only, ec_bind;
|
||||||
|
|
||||||
if (!ipv4Only) {
|
if (!ipv4Only) {
|
||||||
// Try IPv6 first (dual-stack check)
|
// Try IPv6 (dual-stack if supported)
|
||||||
asio::ip::tcp::endpoint endpoint_v6(asio::ip::tcp::v6(), port);
|
asio::ip::tcp::endpoint endpoint_v6(asio::ip::tcp::v6(), port);
|
||||||
mAcceptor.open(endpoint_v6.protocol(), ec);
|
|
||||||
if (!ec) {
|
mAcceptor.open(endpoint_v6.protocol(), ec_open);
|
||||||
mAcceptor.set_option(asio::ip::v6_only(false), ec); // Allow dual-stack if possible
|
|
||||||
mAcceptor.bind(endpoint_v6, ec);
|
if (!ec_open) {
|
||||||
|
// Try enabling dual-stack, but DO NOT treat failure as fatal
|
||||||
|
mAcceptor.set_option(asio::ip::v6_only(false), ec_v6only);
|
||||||
|
|
||||||
|
// Try binding IPv6
|
||||||
|
mAcceptor.bind(endpoint_v6, ec_bind);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback to IPv4 if anything failed
|
// If IPv6 bind failed OR IPv6 open failed OR forced IPv4-only
|
||||||
if (ec || ipv4Only) {
|
if (ipv4Only || ec_open || ec_bind) {
|
||||||
Utils::warn("TCP: IPv6 unavailable (" + ec.message() + "), falling back to IPv4 only");
|
if (!ipv4Only)
|
||||||
|
Utils::warn("TCP: IPv6 unavailable (open=" + ec_open.message() +
|
||||||
|
", bind=" + ec_bind.message() +
|
||||||
|
"), falling back to IPv4 only");
|
||||||
|
|
||||||
asio::ip::tcp::endpoint endpoint_v4(asio::ip::tcp::v4(), port);
|
asio::ip::tcp::endpoint endpoint_v4(asio::ip::tcp::v4(), port);
|
||||||
mAcceptor.close(); // ensure clean state
|
|
||||||
|
mAcceptor.close(); // guarantee clean state
|
||||||
mAcceptor.open(endpoint_v4.protocol());
|
mAcceptor.open(endpoint_v4.protocol());
|
||||||
mAcceptor.bind(endpoint_v4);
|
mAcceptor.bind(endpoint_v4);
|
||||||
}
|
}
|
||||||
@@ -75,6 +87,7 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
std::shared_ptr<Utils::LibSodiumWrapper> mSodiumWrapper;
|
std::shared_ptr<Utils::LibSodiumWrapper> mSodiumWrapper;
|
||||||
std::shared_ptr<bool> mHostRunning;
|
std::shared_ptr<bool> mHostRunning;
|
||||||
std::unordered_map<std::string, std::string> mRawServerConfig;
|
std::unordered_map<std::string, std::string> mRawServerConfig;
|
||||||
|
std::string mConfigDirPath;
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
// udp_server.hpp - UDP Server for ColumnLynx
|
// udp_server.hpp - UDP Server for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
@@ -16,24 +16,37 @@ namespace ColumnLynx::Net::UDP {
|
|||||||
UDPServer(asio::io_context& ioContext, uint16_t port, std::shared_ptr<bool> hostRunning, bool ipv4Only = false, std::shared_ptr<VirtualInterface> tun = nullptr)
|
UDPServer(asio::io_context& ioContext, uint16_t port, std::shared_ptr<bool> hostRunning, bool ipv4Only = false, std::shared_ptr<VirtualInterface> tun = nullptr)
|
||||||
: mSocket(ioContext), mHostRunning(hostRunning), mTun(tun)
|
: mSocket(ioContext), mHostRunning(hostRunning), mTun(tun)
|
||||||
{
|
{
|
||||||
asio::error_code ec;
|
asio::error_code ec_open, ec_v6only, ec_bind;
|
||||||
|
|
||||||
if (!ipv4Only) {
|
if (!ipv4Only) {
|
||||||
// Try IPv6 first (dual-stack check)
|
|
||||||
asio::ip::udp::endpoint endpoint_v6(asio::ip::udp::v6(), port);
|
asio::ip::udp::endpoint endpoint_v6(asio::ip::udp::v6(), port);
|
||||||
mSocket.open(endpoint_v6.protocol(), ec);
|
|
||||||
if (!ec) {
|
// Try opening IPv6 socket
|
||||||
mSocket.set_option(asio::ip::v6_only(false), ec); // Allow dual-stack if possible
|
mSocket.open(endpoint_v6.protocol(), ec_open);
|
||||||
mSocket.bind(endpoint_v6, ec);
|
|
||||||
|
if (!ec_open) {
|
||||||
|
// Try enabling dual-stack (non fatal if it fails)
|
||||||
|
mSocket.set_option(asio::ip::v6_only(false), ec_v6only);
|
||||||
|
|
||||||
|
// Attempt bind
|
||||||
|
mSocket.bind(endpoint_v6, ec_bind);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback to IPv4 if anything failed
|
// Fallback to IPv4 if IPv6 is unusable
|
||||||
if (ec || ipv4Only) {
|
if (ipv4Only || ec_open || ec_bind) {
|
||||||
Utils::warn("UDP: IPv6 unavailable (" + ec.message() + "), falling back to IPv4 only");
|
if (!ipv4Only) {
|
||||||
|
Utils::warn(
|
||||||
|
"UDP: IPv6 unavailable (open=" + ec_open.message() +
|
||||||
|
", bind=" + ec_bind.message() +
|
||||||
|
"), falling back to IPv4 only"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
asio::ip::udp::endpoint endpoint_v4(asio::ip::udp::v4(), port);
|
asio::ip::udp::endpoint endpoint_v4(asio::ip::udp::v4(), port);
|
||||||
mSocket.close(); // ensure clean state
|
|
||||||
|
mSocket.close();
|
||||||
|
mSocket = asio::ip::udp::socket(ioContext); // fully reset internal state
|
||||||
mSocket.open(endpoint_v4.protocol());
|
mSocket.open(endpoint_v4.protocol());
|
||||||
mSocket.bind(endpoint_v4);
|
mSocket.bind(endpoint_v4);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// main.cpp - Client entry point for ColumnLynx
|
// main.cpp - Client entry point for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#include <asio.hpp>
|
#include <asio.hpp>
|
||||||
@@ -12,6 +12,10 @@
|
|||||||
#include <cxxopts.hpp>
|
#include <cxxopts.hpp>
|
||||||
#include <columnlynx/common/net/virtual_interface.hpp>
|
#include <columnlynx/common/net/virtual_interface.hpp>
|
||||||
|
|
||||||
|
#if defined(__WIN32__)
|
||||||
|
#include <windows.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
using asio::ip::tcp;
|
using asio::ip::tcp;
|
||||||
using namespace ColumnLynx::Utils;
|
using namespace ColumnLynx::Utils;
|
||||||
using namespace ColumnLynx::Net;
|
using namespace ColumnLynx::Net;
|
||||||
@@ -21,18 +25,19 @@ volatile sig_atomic_t done = 0;
|
|||||||
|
|
||||||
void signalHandler(int signum) {
|
void signalHandler(int signum) {
|
||||||
if (signum == SIGINT || signum == SIGTERM) {
|
if (signum == SIGINT || signum == SIGTERM) {
|
||||||
//log("Received termination signal. Shutting down client.");
|
|
||||||
done = 1;
|
done = 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(int argc, char** argv) {
|
int main(int argc, char** argv) {
|
||||||
// Capture SIGINT and SIGTERM for graceful shutdown
|
// Capture SIGINT and SIGTERM for graceful shutdown
|
||||||
|
#if !defined(_WIN32)
|
||||||
struct sigaction action;
|
struct sigaction action;
|
||||||
memset(&action, 0, sizeof(struct sigaction));
|
memset(&action, 0, sizeof(struct sigaction));
|
||||||
action.sa_handler = signalHandler;
|
action.sa_handler = signalHandler;
|
||||||
sigaction(SIGINT, &action, nullptr);
|
sigaction(SIGINT, &action, nullptr);
|
||||||
sigaction(SIGTERM, &action, nullptr);
|
sigaction(SIGTERM, &action, nullptr);
|
||||||
|
#endif
|
||||||
|
|
||||||
PanicHandler::init();
|
PanicHandler::init();
|
||||||
|
|
||||||
@@ -47,15 +52,23 @@ int main(int argc, char** argv) {
|
|||||||
#else
|
#else
|
||||||
("i,interface", "Override used interface", cxxopts::value<std::string>()->default_value("lynx0"))
|
("i,interface", "Override used interface", cxxopts::value<std::string>()->default_value("lynx0"))
|
||||||
#endif
|
#endif
|
||||||
("allow-selfsigned", "Allow self-signed certificates", cxxopts::value<bool>()->default_value("false"));
|
("ignore-whitelist", "Ignore if server is not in whitelisted_keys", cxxopts::value<bool>()->default_value("false"))
|
||||||
|
#if defined(__WIN32__)
|
||||||
|
/* Get config dir in LOCALAPPDATA\ColumnLynx\ */
|
||||||
|
("config-dir", "Override config dir path", cxxopts::value<std::string>()->default_value(std::string((std::getenv("LOCALAPPDATA") ? std::getenv("LOCALAPPDATA") : "C:\\ProgramData")) + "\\ColumnLynx\\"));
|
||||||
|
#elif defined(__APPLE__)
|
||||||
|
("config-dir", "Override config dir path", cxxopts::value<std::string>()->default_value(std::string((std::getenv("HOME") ? std::getenv("HOME") : "")) + "/Library/Application Support/ColumnLynx/"));
|
||||||
|
#else
|
||||||
|
("config-dir", "Override config dir path", cxxopts::value<std::string>()->default_value(std::string((std::getenv("SUDO_USER") ? "/home/" + std::string(std::getenv("SUDO_USER")) : (std::getenv("HOME") ? std::getenv("HOME") : ""))) + "/.config/columnlynx/"));
|
||||||
|
#endif
|
||||||
|
|
||||||
bool insecureMode = options.parse(argc, argv).count("allow-selfsigned") > 0;
|
bool insecureMode = options.parse(argc, argv).count("ignore-whitelist") > 0;
|
||||||
|
|
||||||
auto optionsObj = options.parse(argc, argv);
|
auto optionsObj = options.parse(argc, argv);
|
||||||
if (optionsObj.count("help")) {
|
if (optionsObj.count("help")) {
|
||||||
std::cout << options.help() << std::endl;
|
std::cout << options.help() << std::endl;
|
||||||
std::cout << "This software is licensed under the GPLv2-only license OR the GPLv3 license.\n";
|
std::cout << "This software is licensed under the GPLv2-only license OR the GPLv3 license.\n";
|
||||||
std::cout << "Copyright (C) 2025, The ColumnLynx Contributors.\n";
|
std::cout << "Copyright (C) 2026, The ColumnLynx Contributors.\n";
|
||||||
std::cout << "This software is provided under ABSOLUTELY NO WARRANTY, to the extent permitted by law.\n";
|
std::cout << "This software is provided under ABSOLUTELY NO WARRANTY, to the extent permitted by law.\n";
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -68,9 +81,24 @@ int main(int argc, char** argv) {
|
|||||||
log("This software is licensed under the GPLv2 only OR the GPLv3. See LICENSES/ for details.");
|
log("This software is licensed under the GPLv2 only OR the GPLv3. See LICENSES/ for details.");
|
||||||
|
|
||||||
#if defined(__WIN32__)
|
#if defined(__WIN32__)
|
||||||
WintunInitialize();
|
//WintunInitialize();
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
// Get the config path, ENV > CLI > /etc/columnlynx
|
||||||
|
std::string configPath = optionsObj["config-dir"].as<std::string>();
|
||||||
|
const char* envConfigPath = std::getenv("COLUMNLYNX_CONFIG_DIR");
|
||||||
|
if (envConfigPath != nullptr) {
|
||||||
|
configPath = std::string(envConfigPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (configPath.back() != '/' && configPath.back() != '\\') {
|
||||||
|
#if defined(__WIN32__)
|
||||||
|
configPath += "\\";
|
||||||
|
#else
|
||||||
|
configPath += "/";
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
std::shared_ptr<VirtualInterface> tun = std::make_shared<VirtualInterface>(optionsObj["interface"].as<std::string>());
|
std::shared_ptr<VirtualInterface> tun = std::make_shared<VirtualInterface>(optionsObj["interface"].as<std::string>());
|
||||||
log("Using virtual interface: " + tun->getName());
|
log("Using virtual interface: " + tun->getName());
|
||||||
|
|
||||||
@@ -82,8 +110,12 @@ int main(int argc, char** argv) {
|
|||||||
aesKey->fill(0); // Defualt zeroed state until modified by handshake
|
aesKey->fill(0); // Defualt zeroed state until modified by handshake
|
||||||
std::shared_ptr<uint64_t> sessionID = std::make_shared<uint64_t>(0);
|
std::shared_ptr<uint64_t> sessionID = std::make_shared<uint64_t>(0);
|
||||||
|
|
||||||
|
if (insecureMode) {
|
||||||
|
warn("You have started the client with the --ignore-whitelist. This means that the client will NOT attempt to verify the server's public key. This is INSECURE and SHOULDN'T be used!");
|
||||||
|
}
|
||||||
|
|
||||||
asio::io_context io;
|
asio::io_context io;
|
||||||
auto client = std::make_shared<ColumnLynx::Net::TCP::TCPClient>(io, host, port, sodiumWrapper, aesKey, sessionID, insecureMode, tun);
|
auto client = std::make_shared<ColumnLynx::Net::TCP::TCPClient>(io, host, port, sodiumWrapper, aesKey, sessionID, insecureMode, configPath, tun);
|
||||||
auto udpClient = std::make_shared<ColumnLynx::Net::UDP::UDPClient>(io, host, port, aesKey, sessionID, tun);
|
auto udpClient = std::make_shared<ColumnLynx::Net::UDP::UDPClient>(io, host, port, aesKey, sessionID, tun);
|
||||||
|
|
||||||
client->start();
|
client->start();
|
||||||
@@ -95,14 +127,18 @@ int main(int argc, char** argv) {
|
|||||||
});
|
});
|
||||||
//ioThread.join();
|
//ioThread.join();
|
||||||
|
|
||||||
log("Client connected to " + host + ":" + port);
|
log("Attempting connection to " + host + ":" + port);
|
||||||
|
debug("Client connection flag: " + std::to_string(client->isConnected()));
|
||||||
|
debug("Client handshake flag: " + std::to_string(client->isHandshakeComplete()));
|
||||||
|
debug("isDone flag: " + std::to_string(done));
|
||||||
|
|
||||||
// Client is running
|
// Client is running
|
||||||
while ((client->isConnected() || !client->isHandshakeComplete()) && !done) {
|
while ((client->isConnected() || !client->isHandshakeComplete()) && !done) {
|
||||||
|
//debug("Client connection flag: " + std::to_string(client->isConnected()));
|
||||||
auto packet = tun->readPacket();
|
auto packet = tun->readPacket();
|
||||||
if (!client->isConnected() || done) {
|
/*if (!client->isConnected() || done) {
|
||||||
break; // Bail out if connection died or signal set while blocked
|
break; // Bail out if connection died or signal set while blocked
|
||||||
}
|
}*/
|
||||||
|
|
||||||
if (packet.empty()) {
|
if (packet.empty()) {
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
// tcp_client.cpp - TCP Client for ColumnLynx
|
// tcp_client.cpp - TCP Client for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#include <columnlynx/client/net/tcp/tcp_client.hpp>
|
#include <columnlynx/client/net/tcp/tcp_client.hpp>
|
||||||
#include <arpa/inet.h>
|
//#include <arpa/inet.h>
|
||||||
|
|
||||||
namespace ColumnLynx::Net::TCP {
|
namespace ColumnLynx::Net::TCP {
|
||||||
void TCPClient::start() {
|
void TCPClient::start() {
|
||||||
@@ -13,22 +13,35 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
if (!ec) {
|
if (!ec) {
|
||||||
asio::async_connect(mSocket, endpoints,
|
asio::async_connect(mSocket, endpoints,
|
||||||
[this, self](asio::error_code ec, const tcp::endpoint&) {
|
[this, self](asio::error_code ec, const tcp::endpoint&) {
|
||||||
if (!NetHelper::isExpectedDisconnect(ec)) {
|
if (!ec) {
|
||||||
mConnected = true;
|
mConnected = true;
|
||||||
Utils::log("Client connected.");
|
Utils::log("Client connected.");
|
||||||
mHandler = std::make_shared<MessageHandler>(std::move(mSocket));
|
mHandler = std::make_shared<MessageHandler>(std::move(mSocket));
|
||||||
mHandler->onMessage([this](AnyMessageType type, const std::string& data) {
|
mHandler->onMessage([this](AnyMessageType type, const std::string& data) {
|
||||||
mHandleMessage(static_cast<ServerMessageType>(MessageHandler::toUint8(type)), data);
|
mHandleMessage(static_cast<ServerMessageType>(MessageHandler::toUint8(type)), data);
|
||||||
});
|
});
|
||||||
|
// Close only after peer FIN to avoid RSTs
|
||||||
|
mHandler->onDisconnect([this](const asio::error_code& ec) {
|
||||||
|
asio::error_code ec2;
|
||||||
|
if (mHandler) {
|
||||||
|
mHandler->socket().close(ec2);
|
||||||
|
}
|
||||||
|
mConnected = false;
|
||||||
|
Utils::log(std::string("Server disconnected: ") + ec.message());
|
||||||
|
});
|
||||||
mHandler->start();
|
mHandler->start();
|
||||||
|
|
||||||
// Init connection handshake
|
// Init connection handshake
|
||||||
Utils::log("Sending handshake init to server.");
|
Utils::log("Sending handshake init to server.");
|
||||||
|
|
||||||
// Check if hostname or IPv4/IPv6
|
// Check if hostname or IPv4/IPv6
|
||||||
sockaddr_in addr4{};
|
try {
|
||||||
sockaddr_in6 addr6{};
|
asio::ip::make_address(mHost);
|
||||||
self->mIsHostDomain = inet_pton(AF_INET, mHost.c_str(), (void*)(&addr4)) != 1 && inet_pton(AF_INET6, mHost.c_str(), (void*)(&addr6)) != 1; // Voodoo black magic
|
self->mIsHostDomain = false; // IPv4 or IPv6 literal
|
||||||
|
} catch (const asio::system_error&) {
|
||||||
|
self->mIsHostDomain = true; // hostname / domain
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
std::vector<uint8_t> payload;
|
std::vector<uint8_t> payload;
|
||||||
payload.reserve(1 + crypto_box_PUBLICKEYBYTES);
|
payload.reserve(1 + crypto_box_PUBLICKEYBYTES);
|
||||||
@@ -46,8 +59,10 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
|
|
||||||
mStartHeartbeat();
|
mStartHeartbeat();
|
||||||
} else {
|
} else {
|
||||||
|
if (!NetHelper::isExpectedDisconnect(ec)) {
|
||||||
Utils::error("Client connect failed: " + ec.message());
|
Utils::error("Client connect failed: " + ec.message());
|
||||||
}
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
Utils::error("Client resolve failed: " + ec.message());
|
Utils::error("Client resolve failed: " + ec.message());
|
||||||
@@ -77,18 +92,14 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
asio::error_code ec;
|
asio::error_code ec;
|
||||||
mHeartbeatTimer.cancel();
|
mHeartbeatTimer.cancel();
|
||||||
|
|
||||||
mHandler->socket().shutdown(tcp::socket::shutdown_both, ec);
|
// Half-close: stop sending, keep reading until peer FIN
|
||||||
|
mHandler->socket().shutdown(tcp::socket::shutdown_send, ec);
|
||||||
if (ec) {
|
if (ec) {
|
||||||
Utils::error("Error during socket shutdown: " + ec.message());
|
Utils::error("Error during socket shutdown: " + ec.message());
|
||||||
}
|
}
|
||||||
|
|
||||||
mHandler->socket().close(ec);
|
// Do not close immediately; rely on onDisconnect to finalize
|
||||||
if (ec) {
|
Utils::log("Client initiated graceful disconnect (half-close).");
|
||||||
Utils::error("Error during socket close: " + ec.message());
|
|
||||||
}
|
|
||||||
|
|
||||||
mConnected = false;
|
|
||||||
Utils::log("Client disconnected.");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,11 +150,12 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
void TCPClient::mHandleMessage(ServerMessageType type, const std::string& data) {
|
void TCPClient::mHandleMessage(ServerMessageType type, const std::string& data) {
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case ServerMessageType::HANDSHAKE_IDENTIFY: {
|
case ServerMessageType::HANDSHAKE_IDENTIFY: {
|
||||||
Utils::log("Received server identity: " + data);
|
|
||||||
std::memcpy(mServerPublicKey, data.data(), std::min(data.size(), sizeof(mServerPublicKey)));
|
std::memcpy(mServerPublicKey, data.data(), std::min(data.size(), sizeof(mServerPublicKey)));
|
||||||
|
std::string hexServerPub = Utils::bytesToHexString(mServerPublicKey, 32);
|
||||||
|
Utils::log("Received server identity. Public Key: " + hexServerPub);
|
||||||
|
|
||||||
// Verify pubkey against whitelisted_keys
|
// Verify pubkey against whitelisted_keys
|
||||||
std::vector<std::string> whitelistedKeys = Utils::getWhitelistedKeys();
|
std::vector<std::string> whitelistedKeys = Utils::getWhitelistedKeys(mConfigDirPath);
|
||||||
if (std::find(whitelistedKeys.begin(), whitelistedKeys.end(), Utils::bytesToHexString(mServerPublicKey, 32)) == whitelistedKeys.end()) { // Key verification is handled in later steps of the handshake
|
if (std::find(whitelistedKeys.begin(), whitelistedKeys.end(), Utils::bytesToHexString(mServerPublicKey, 32)) == whitelistedKeys.end()) { // Key verification is handled in later steps of the handshake
|
||||||
if (!mInsecureMode) {
|
if (!mInsecureMode) {
|
||||||
Utils::error("Server public key not in whitelisted_keys. Terminating connection.");
|
Utils::error("Server public key not in whitelisted_keys. Terminating connection.");
|
||||||
@@ -269,6 +281,12 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
disconnect(false);
|
disconnect(false);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
case ServerMessageType::KILL_CONNECTION:
|
||||||
|
Utils::warn("Server is killing the connection: " + data);
|
||||||
|
if (mConnected) {
|
||||||
|
disconnect(false);
|
||||||
|
}
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
Utils::log("Received unknown message type from server.");
|
Utils::log("Received unknown message type from server.");
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -1,15 +1,46 @@
|
|||||||
// udp_client.cpp - UDP Client for ColumnLynx
|
// udp_client.cpp - UDP Client for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#include <columnlynx/client/net/udp/udp_client.hpp>
|
#include <columnlynx/client/net/udp/udp_client.hpp>
|
||||||
|
|
||||||
namespace ColumnLynx::Net::UDP {
|
namespace ColumnLynx::Net::UDP {
|
||||||
void UDPClient::start() {
|
void UDPClient::start() {
|
||||||
// TODO: Add IPv6
|
asio::error_code ec;
|
||||||
auto endpoints = mResolver.resolve(asio::ip::udp::v4(), mHost, mPort);
|
|
||||||
|
// Resolve using an unspecified protocol (allows both IPv4 and IPv6)
|
||||||
|
auto endpoints = mResolver.resolve(
|
||||||
|
asio::ip::udp::v6(), // Try IPv6 first (dual-stack with v4)
|
||||||
|
mHost,
|
||||||
|
mPort,
|
||||||
|
ec
|
||||||
|
);
|
||||||
|
|
||||||
|
if (ec) {
|
||||||
|
// If IPv6 fails (host has no AAAA), try IPv4
|
||||||
|
endpoints = mResolver.resolve(
|
||||||
|
asio::ip::udp::v4(),
|
||||||
|
mHost,
|
||||||
|
mPort,
|
||||||
|
ec
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ec) {
|
||||||
|
Utils::error("UDP resolve failed: " + ec.message());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use whichever endpoint resolved
|
||||||
mRemoteEndpoint = *endpoints.begin();
|
mRemoteEndpoint = *endpoints.begin();
|
||||||
mSocket.open(asio::ip::udp::v4());
|
|
||||||
|
// Open socket using the resolved endpoint's protocol
|
||||||
|
mSocket.open(mRemoteEndpoint.protocol(), ec);
|
||||||
|
if (ec) {
|
||||||
|
Utils::error("UDP socket open failed: " + ec.message());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
Utils::log("UDP Client ready to send to " + mRemoteEndpoint.address().to_string() + ":" + std::to_string(mRemoteEndpoint.port()));
|
Utils::log("UDP Client ready to send to " + mRemoteEndpoint.address().to_string() + ":" + std::to_string(mRemoteEndpoint.port()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// libsodium_wrapper.cpp - Libsodium Wrapper for ColumnLynx
|
// libsodium_wrapper.cpp - Libsodium Wrapper for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#include <columnlynx/common/libsodium_wrapper.hpp>
|
#include <columnlynx/common/libsodium_wrapper.hpp>
|
||||||
@@ -41,4 +41,27 @@ namespace ColumnLynx::Utils {
|
|||||||
randombytes_buf(randbytes.data(), randbytes.size());
|
randombytes_buf(randbytes.data(), randbytes.size());
|
||||||
return randbytes;
|
return randbytes;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool LibSodiumWrapper::recomputeKeys(PrivateSeed privateSeed, PublicKey storedPubKey) {
|
||||||
|
int res = crypto_sign_seed_keypair(mPublicKey.data(), mPrivateKey.data(), privateSeed.data());
|
||||||
|
|
||||||
|
if (res != 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert to Curve25519 keys for encryption
|
||||||
|
res = crypto_sign_ed25519_pk_to_curve25519(mXPublicKey.data(), mPublicKey.data());
|
||||||
|
res = crypto_sign_ed25519_sk_to_curve25519(mXPrivateKey.data(), mPrivateKey.data());
|
||||||
|
|
||||||
|
if (res != 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compare to stored for verification
|
||||||
|
if (sodium_memcmp(mPublicKey.data(), storedPubKey.data(), crypto_sign_PUBLICKEYBYTES) != 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
100
src/common/session_registry.cpp
Normal file
100
src/common/session_registry.cpp
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
// session_registry.cpp - Session Registry for ColumnLynx
|
||||||
|
// Copyright (C) 2026 DcruBro
|
||||||
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
|
#include <columnlynx/common/net/session_registry.hpp>
|
||||||
|
|
||||||
|
namespace ColumnLynx::Net {
|
||||||
|
void SessionRegistry::put(uint64_t sessionID, std::shared_ptr<SessionState> state) {
|
||||||
|
std::unique_lock lock(mMutex);
|
||||||
|
mSessions[sessionID] = std::move(state);
|
||||||
|
mIPSessions[mSessions[sessionID]->clientTunIP] = mSessions[sessionID];
|
||||||
|
}
|
||||||
|
|
||||||
|
std::shared_ptr<const SessionState> SessionRegistry::get(uint64_t sessionID) const {
|
||||||
|
std::shared_lock lock(mMutex);
|
||||||
|
auto it = mSessions.find(sessionID);
|
||||||
|
return (it == mSessions.end()) ? nullptr : it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::shared_ptr<const SessionState> SessionRegistry::getByIP(uint32_t ip) const {
|
||||||
|
std::shared_lock lock(mMutex);
|
||||||
|
auto it = mIPSessions.find(ip);
|
||||||
|
return (it == mIPSessions.end()) ? nullptr : it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::unordered_map<uint64_t, std::shared_ptr<SessionState>> SessionRegistry::snapshot() const {
|
||||||
|
std::unordered_map<uint64_t, std::shared_ptr<SessionState>> snap;
|
||||||
|
std::shared_lock lock(mMutex);
|
||||||
|
snap = mSessions;
|
||||||
|
return snap;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SessionRegistry::erase(uint64_t sessionID) {
|
||||||
|
std::unique_lock lock(mMutex);
|
||||||
|
mSessions.erase(sessionID);
|
||||||
|
}
|
||||||
|
|
||||||
|
void SessionRegistry::cleanupExpired() {
|
||||||
|
std::unique_lock lock(mMutex);
|
||||||
|
auto now = std::chrono::steady_clock::now();
|
||||||
|
for (auto it = mSessions.begin(); it != mSessions.end(); ) {
|
||||||
|
if (it->second && it->second->expires <= now) {
|
||||||
|
it = mSessions.erase(it);
|
||||||
|
} else {
|
||||||
|
++it;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (auto it = mIPSessions.begin(); it != mIPSessions.end(); ) {
|
||||||
|
if (it->second && it->second->expires <= now) {
|
||||||
|
it = mIPSessions.erase(it);
|
||||||
|
} else {
|
||||||
|
++it;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int SessionRegistry::size() const {
|
||||||
|
std::shared_lock lock(mMutex);
|
||||||
|
return static_cast<int>(mSessions.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t SessionRegistry::getFirstAvailableIP(uint32_t baseIP, uint8_t mask) const {
|
||||||
|
std::shared_lock lock(mMutex);
|
||||||
|
|
||||||
|
uint32_t hostCount = (1u << (32 - mask));
|
||||||
|
uint32_t firstHost = 2;
|
||||||
|
uint32_t lastHost = hostCount - 2;
|
||||||
|
|
||||||
|
for (uint32_t offset = firstHost; offset <= lastHost; offset++) {
|
||||||
|
uint32_t candidateIP = baseIP + offset;
|
||||||
|
if (mIPSessions.find(candidateIP) == mIPSessions.end()) {
|
||||||
|
return candidateIP;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SessionRegistry::lockIP(uint64_t sessionID, uint32_t ip) {
|
||||||
|
std::unique_lock lock(mMutex);
|
||||||
|
mSessionIPs[sessionID] = ip;
|
||||||
|
|
||||||
|
/*if (mIPSessions.find(sessionID) == mIPSessions.end()) {
|
||||||
|
Utils::debug("yikes");
|
||||||
|
}*/
|
||||||
|
mIPSessions[ip] = mSessions.find(sessionID)->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SessionRegistry::deallocIP(uint64_t sessionID) {
|
||||||
|
std::unique_lock lock(mMutex);
|
||||||
|
|
||||||
|
auto it = mSessionIPs.find(sessionID);
|
||||||
|
if (it != mSessionIPs.end()) {
|
||||||
|
uint32_t ip = it->second;
|
||||||
|
mIPSessions.erase(ip);
|
||||||
|
mSessionIPs.erase(it);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
// tcp_message_handler.cpp - TCP Message Handler for ColumnLynx
|
// tcp_message_handler.cpp - TCP Message Handler for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#include <columnlynx/common/net/tcp/tcp_message_handler.hpp>
|
#include <columnlynx/common/net/tcp/tcp_message_handler.hpp>
|
||||||
@@ -43,14 +43,20 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
auto self = shared_from_this();
|
auto self = shared_from_this();
|
||||||
asio::async_read(mSocket, asio::buffer(mHeader),
|
asio::async_read(mSocket, asio::buffer(mHeader),
|
||||||
[this, self](asio::error_code ec, std::size_t) {
|
[this, self](asio::error_code ec, std::size_t) {
|
||||||
if (!NetHelper::isExpectedDisconnect(ec)) {
|
if (!ec) {
|
||||||
mCurrentType = decodeMessageType(mHeader[0]);
|
mCurrentType = decodeMessageType(mHeader[0]);
|
||||||
|
|
||||||
uint16_t len = (mHeader[1] << 8) | mHeader[2];
|
uint16_t len = (mHeader[1] << 8) | mHeader[2];
|
||||||
mReadBody(len);
|
mReadBody(len);
|
||||||
} else {
|
} else {
|
||||||
|
if (!NetHelper::isExpectedDisconnect(ec)) {
|
||||||
Utils::error("Header read failed: " + ec.message());
|
Utils::error("Header read failed: " + ec.message());
|
||||||
}
|
}
|
||||||
|
// Connection closed, trigger disconnect handler
|
||||||
|
if (mOnDisconnect) {
|
||||||
|
mOnDisconnect(ec);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -61,7 +67,7 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
|
|
||||||
asio::async_read(mSocket, asio::buffer(mBody),
|
asio::async_read(mSocket, asio::buffer(mBody),
|
||||||
[this, self](asio::error_code ec, std::size_t) {
|
[this, self](asio::error_code ec, std::size_t) {
|
||||||
if (!NetHelper::isExpectedDisconnect(ec)) {
|
if (!ec) {
|
||||||
std::string payload(mBody.begin(), mBody.end());
|
std::string payload(mBody.begin(), mBody.end());
|
||||||
|
|
||||||
// Dispatch based on message type
|
// Dispatch based on message type
|
||||||
@@ -71,8 +77,10 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
|
|
||||||
mReadHeader(); // Keep listening
|
mReadHeader(); // Keep listening
|
||||||
} else {
|
} else {
|
||||||
|
if (!NetHelper::isExpectedDisconnect(ec)) {
|
||||||
Utils::error("Body read failed: " + ec.message());
|
Utils::error("Body read failed: " + ec.message());
|
||||||
|
}
|
||||||
|
// Connection closed, trigger disconnect handler
|
||||||
if (mOnDisconnect) {
|
if (mOnDisconnect) {
|
||||||
mOnDisconnect(ec);
|
mOnDisconnect(ec);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +1,65 @@
|
|||||||
// utils.cpp - Utility functions for ColumnLynx
|
// utils.cpp - Utility functions for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#include <columnlynx/common/utils.hpp>
|
#include <columnlynx/common/utils.hpp>
|
||||||
|
|
||||||
namespace ColumnLynx::Utils {
|
namespace ColumnLynx::Utils {
|
||||||
|
std::string unixMillisToISO8601(uint64_t unixMillis, bool local) {
|
||||||
|
using namespace std::chrono;
|
||||||
|
|
||||||
|
// Convert milliseconds since epoch to system_clock::time_point
|
||||||
|
system_clock::time_point tp = system_clock::time_point(milliseconds(unixMillis));
|
||||||
|
|
||||||
|
// Convert to time_t for localtime conversion
|
||||||
|
std::time_t tt = system_clock::to_time_t(tp);
|
||||||
|
std::tm localTm;
|
||||||
|
|
||||||
|
if (local) {
|
||||||
|
#ifdef _WIN32
|
||||||
|
localtime_s(&localTm, &tt);
|
||||||
|
#else
|
||||||
|
localtime_r(&tt, &localTm);
|
||||||
|
#endif
|
||||||
|
} else {
|
||||||
|
#ifdef _WIN32
|
||||||
|
gmtime_s(&localTm, &tt);
|
||||||
|
#else
|
||||||
|
gmtime_r(&tt, &localTm);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
// Format the time to ISO 8601
|
||||||
|
char buffer[30];
|
||||||
|
std::strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%S", &localTm);
|
||||||
|
|
||||||
|
// Append milliseconds
|
||||||
|
auto ms = duration_cast<milliseconds>(tp.time_since_epoch()) % 1000;
|
||||||
|
char iso8601[34];
|
||||||
|
std::snprintf(iso8601, sizeof(iso8601), "%s.%03lld", buffer, static_cast<long long>(ms.count()));
|
||||||
|
|
||||||
|
return std::string(iso8601);
|
||||||
|
}
|
||||||
|
|
||||||
void log(const std::string &msg) {
|
void log(const std::string &msg) {
|
||||||
uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
|
uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
|
||||||
std::cout << "\033[0m[" << std::to_string(now) << " LOG] " << msg << std::endl;
|
std::cout << "\033[0m[" << unixMillisToISO8601(now) << " LOG] " << msg << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void warn(const std::string &msg) {
|
void warn(const std::string &msg) {
|
||||||
uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
|
uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
|
||||||
std::cerr << "\033[33m[" << std::to_string(now) << " WARN] " << msg << "\033[0m" << std::endl;
|
std::cerr << "\033[33m[" << unixMillisToISO8601(now) << " WARN] " << msg << "\033[0m" << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void error(const std::string &msg) {
|
void error(const std::string &msg) {
|
||||||
uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
|
uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
|
||||||
std::cerr << "\033[31m[" << std::to_string(now) << " ERROR] " << msg << "\033[0m" << std::endl;
|
std::cerr << "\033[31m[" << unixMillisToISO8601(now) << " ERROR] " << msg << "\033[0m" << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void debug(const std::string &msg) {
|
void debug(const std::string &msg) {
|
||||||
#if DEBUG || _DEBUG
|
#if DEBUG || _DEBUG
|
||||||
uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
|
uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
|
||||||
std::cerr << "\033[95m[" << std::to_string(now) << " DEBUG] " << msg << "\033[0m" << std::endl;
|
std::cerr << "\033[95m[" << unixMillisToISO8601(now) << " DEBUG] " << msg << "\033[0m" << std::endl;
|
||||||
#else
|
#else
|
||||||
return;
|
return;
|
||||||
#endif
|
#endif
|
||||||
@@ -49,7 +85,7 @@ namespace ColumnLynx::Utils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::string getVersion() {
|
std::string getVersion() {
|
||||||
return "a0.6";
|
return "1.0.1";
|
||||||
}
|
}
|
||||||
|
|
||||||
unsigned short serverPort() {
|
unsigned short serverPort() {
|
||||||
@@ -101,14 +137,19 @@ namespace ColumnLynx::Utils {
|
|||||||
return bytes;
|
return bytes;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<std::string> getWhitelistedKeys() {
|
std::vector<std::string> getWhitelistedKeys(std::string basePath) {
|
||||||
// Currently re-reads the file every time, should be fine.
|
// Currently re-reads the file every time, should be fine.
|
||||||
// Advantage of it is that you don't need to reload the server binary after adding/removing keys. Disadvantage is re-reading the file every time.
|
// Advantage of it is that you don't need to reload the server binary after adding/removing keys. Disadvantage is re-reading the file every time.
|
||||||
// I might redo this part.
|
// I might redo this part.
|
||||||
|
|
||||||
std::vector<std::string> out;
|
std::vector<std::string> out;
|
||||||
|
|
||||||
std::ifstream file("whitelisted_keys"); // TODO: This is hardcoded for now, make dynamic
|
std::ifstream file(basePath + "whitelisted_keys");
|
||||||
|
if (!file.is_open()) {
|
||||||
|
warn("Failed to open whitelisted_keys file at path: " + basePath + "whitelisted_keys");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
std::string line;
|
std::string line;
|
||||||
|
|
||||||
while (std::getline(file, line)) {
|
while (std::getline(file, line)) {
|
||||||
@@ -123,6 +164,10 @@ namespace ColumnLynx::Utils {
|
|||||||
std::vector<std::string> readLines;
|
std::vector<std::string> readLines;
|
||||||
|
|
||||||
std::ifstream file(path);
|
std::ifstream file(path);
|
||||||
|
if (!file.is_open()) {
|
||||||
|
throw std::runtime_error("Failed to open config file at path: " + path);
|
||||||
|
}
|
||||||
|
|
||||||
std::string line;
|
std::string line;
|
||||||
|
|
||||||
while (std::getline(file, line)) {
|
while (std::getline(file, line)) {
|
||||||
|
|||||||
@@ -1,11 +1,60 @@
|
|||||||
// virtual_interface.cpp - Virtual Interface for Network Communication
|
// virtual_interface.cpp - Virtual Interface for Network Communication
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#include <columnlynx/common/net/virtual_interface.hpp>
|
#include <columnlynx/common/net/virtual_interface.hpp>
|
||||||
|
|
||||||
// This is all fucking voodoo dark magic.
|
// This is all fucking voodoo dark magic.
|
||||||
|
|
||||||
|
#if defined(_WIN32)
|
||||||
|
|
||||||
|
static HMODULE gWintun = nullptr;
|
||||||
|
|
||||||
|
static WINTUN_OPEN_ADAPTER_FUNC* pWintunOpenAdapter;
|
||||||
|
static WINTUN_START_SESSION_FUNC* pWintunStartSession;
|
||||||
|
static WINTUN_END_SESSION_FUNC* pWintunEndSession;
|
||||||
|
static WINTUN_GET_READ_WAIT_EVENT_FUNC* pWintunGetReadWaitEvent;
|
||||||
|
static WINTUN_RECEIVE_PACKET_FUNC* pWintunReceivePacket;
|
||||||
|
static WINTUN_RELEASE_RECEIVE_PACKET_FUNC* pWintunReleaseReceivePacket;
|
||||||
|
static WINTUN_ALLOCATE_SEND_PACKET_FUNC* pWintunAllocateSendPacket;
|
||||||
|
static WINTUN_SEND_PACKET_FUNC* pWintunSendPacket;
|
||||||
|
static WINTUN_CREATE_ADAPTER_FUNC* pWintunCreateAdapter;
|
||||||
|
|
||||||
|
static void InitializeWintun()
|
||||||
|
{
|
||||||
|
if (gWintun)
|
||||||
|
return;
|
||||||
|
|
||||||
|
gWintun = LoadLibraryExW(
|
||||||
|
L"wintun.dll",
|
||||||
|
nullptr,
|
||||||
|
LOAD_LIBRARY_SEARCH_APPLICATION_DIR
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!gWintun)
|
||||||
|
throw std::runtime_error("Failed to load wintun.dll");
|
||||||
|
|
||||||
|
#define RESOLVE(name, type) \
|
||||||
|
p##name = reinterpret_cast<type*>( \
|
||||||
|
GetProcAddress(gWintun, #name)); \
|
||||||
|
if (!p##name) \
|
||||||
|
throw std::runtime_error("Missing Wintun symbol: " #name);
|
||||||
|
|
||||||
|
RESOLVE(WintunOpenAdapter, WINTUN_OPEN_ADAPTER_FUNC)
|
||||||
|
RESOLVE(WintunStartSession, WINTUN_START_SESSION_FUNC)
|
||||||
|
RESOLVE(WintunEndSession, WINTUN_END_SESSION_FUNC)
|
||||||
|
RESOLVE(WintunGetReadWaitEvent, WINTUN_GET_READ_WAIT_EVENT_FUNC)
|
||||||
|
RESOLVE(WintunReceivePacket, WINTUN_RECEIVE_PACKET_FUNC)
|
||||||
|
RESOLVE(WintunReleaseReceivePacket, WINTUN_RELEASE_RECEIVE_PACKET_FUNC)
|
||||||
|
RESOLVE(WintunAllocateSendPacket, WINTUN_ALLOCATE_SEND_PACKET_FUNC)
|
||||||
|
RESOLVE(WintunSendPacket, WINTUN_SEND_PACKET_FUNC)
|
||||||
|
RESOLVE(WintunCreateAdapter, WINTUN_CREATE_ADAPTER_FUNC)
|
||||||
|
|
||||||
|
#undef RESOLVE
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif // _WIN32
|
||||||
|
|
||||||
namespace ColumnLynx::Net {
|
namespace ColumnLynx::Net {
|
||||||
// ------------------------------ Constructor ------------------------------
|
// ------------------------------ Constructor ------------------------------
|
||||||
VirtualInterface::VirtualInterface(const std::string& ifName)
|
VirtualInterface::VirtualInterface(const std::string& ifName)
|
||||||
@@ -23,11 +72,12 @@ namespace ColumnLynx::Net {
|
|||||||
|
|
||||||
if (ioctl(mFd, TUNSETIFF, &ifr) < 0) {
|
if (ioctl(mFd, TUNSETIFF, &ifr) < 0) {
|
||||||
close(mFd);
|
close(mFd);
|
||||||
throw std::runtime_error("TUNSETIFF failed: " + std::string(strerror(errno)));
|
throw std::runtime_error("TUNSETIFF failed (try running with sudo): " + std::string(strerror(errno)));
|
||||||
}
|
}
|
||||||
|
|
||||||
#elif defined(__APPLE__)
|
#elif defined(__APPLE__)
|
||||||
// ---- macOS: UTUN (system control socket) ----
|
// ---- macOS: UTUN (system control socket) ----
|
||||||
|
// TL;DR: macOS doesn't really have a "device file" for TUN/TAP like Linux. Instead we have to request a "system control socket" from the kernel.
|
||||||
mFd = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
|
mFd = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
|
||||||
if (mFd < 0)
|
if (mFd < 0)
|
||||||
throw std::runtime_error("socket(PF_SYSTEM) failed: " + std::string(strerror(errno)));
|
throw std::runtime_error("socket(PF_SYSTEM) failed: " + std::string(strerror(errno)));
|
||||||
@@ -42,39 +92,53 @@ namespace ColumnLynx::Net {
|
|||||||
sc.sc_family = AF_SYSTEM;
|
sc.sc_family = AF_SYSTEM;
|
||||||
sc.ss_sysaddr = AF_SYS_CONTROL;
|
sc.ss_sysaddr = AF_SYS_CONTROL;
|
||||||
sc.sc_id = ctlInfo.ctl_id;
|
sc.sc_id = ctlInfo.ctl_id;
|
||||||
sc.sc_unit = 0; // lynx0 (0 = auto-assign)
|
sc.sc_unit = 0; // 0 = auto-assign next utunX
|
||||||
|
|
||||||
if (connect(mFd, (struct sockaddr*)&sc, sizeof(sc)) < 0) {
|
if (connect(mFd, (struct sockaddr*)&sc, sizeof(sc)) < 0) {
|
||||||
if (errno == EPERM)
|
if (errno == EPERM)
|
||||||
throw std::runtime_error("connect(AF_SYS_CONTROL) failed: Insufficient permissions (try running as root)");
|
throw std::runtime_error("connect(AF_SYS_CONTROL) failed: Insufficient permissions (try running with sudo)");
|
||||||
throw std::runtime_error("connect(AF_SYS_CONTROL) failed: " + std::string(strerror(errno)));
|
throw std::runtime_error("connect(AF_SYS_CONTROL) failed: " + std::string(strerror(errno)));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Retrieve actual utun device name
|
// Retrieve actual utun device name via UTUN_OPT_IFNAME
|
||||||
struct sockaddr_storage addr;
|
char ifname[IFNAMSIZ];
|
||||||
socklen_t addrlen = sizeof(addr);
|
socklen_t ifname_len = sizeof(ifname);
|
||||||
if (getsockname(mFd, (struct sockaddr*)&addr, &addrlen) == 0) {
|
if (getsockopt(mFd, SYSPROTO_CONTROL, UTUN_OPT_IFNAME, ifname, &ifname_len) == 0) {
|
||||||
const struct sockaddr_ctl* addr_ctl = (const struct sockaddr_ctl*)&addr;
|
mIfName = ifname; // Update to actual assigned name
|
||||||
mIfName = "utun" + std::to_string(addr_ctl->sc_unit - 1);
|
|
||||||
} else {
|
} else {
|
||||||
mIfName = "utunX";
|
mIfName = "utun0"; // Fallback (should not happen)
|
||||||
}
|
}
|
||||||
|
|
||||||
#elif defined(_WIN32)
|
Utils::log("VirtualInterface: opened macOS UTUN: " + mIfName);
|
||||||
// ---- Windows: Wintun (WireGuard virtual adapter) ----
|
|
||||||
WINTUN_ADAPTER_HANDLE adapter =
|
|
||||||
WintunOpenAdapter(L"ColumnLynx", std::wstring(ifName.begin(), ifName.end()).c_str());
|
|
||||||
if (!adapter)
|
|
||||||
throw std::runtime_error("Wintun adapter not found or not installed");
|
|
||||||
|
|
||||||
WINTUN_SESSION_HANDLE session =
|
#elif defined(_WIN32)
|
||||||
WintunStartSession(adapter, 0x200000); // ring buffer size
|
|
||||||
if (!session)
|
// Convert to Windows' wchar_t* thingy
|
||||||
|
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
|
||||||
|
std::wstring wide_string = converter.from_bytes(mIfName);
|
||||||
|
const wchar_t* wide_c_str = wide_string.c_str();
|
||||||
|
|
||||||
|
InitializeWintun();
|
||||||
|
|
||||||
|
mAdapter = pWintunOpenAdapter(wide_c_str);
|
||||||
|
|
||||||
|
if (!mAdapter) {
|
||||||
|
mAdapter = pWintunCreateAdapter(
|
||||||
|
wide_c_str,
|
||||||
|
L"ColumnLynx",
|
||||||
|
nullptr
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mAdapter)
|
||||||
|
throw std::runtime_error("Failed to open or create Wintun adapter (run running as admin)");
|
||||||
|
|
||||||
|
mSession = pWintunStartSession(mAdapter, 0x200000);
|
||||||
|
if (!mSession)
|
||||||
throw std::runtime_error("Failed to start Wintun session");
|
throw std::runtime_error("Failed to start Wintun session");
|
||||||
|
|
||||||
mHandle = WintunGetReadWaitEvent(session);
|
mHandle = pWintunGetReadWaitEvent(mSession);
|
||||||
mFd = -1; // not used on Windows
|
mFd = -1;
|
||||||
mIfName = ifName;
|
|
||||||
|
|
||||||
#else
|
#else
|
||||||
throw std::runtime_error("Unsupported platform");
|
throw std::runtime_error("Unsupported platform");
|
||||||
@@ -87,32 +151,82 @@ namespace ColumnLynx::Net {
|
|||||||
if (mFd >= 0)
|
if (mFd >= 0)
|
||||||
close(mFd);
|
close(mFd);
|
||||||
#elif defined(_WIN32)
|
#elif defined(_WIN32)
|
||||||
// Wintun sessions need explicit stop
|
if (mSession)
|
||||||
// (assuming you stored the session handle as member)
|
pWintunEndSession(mSession);
|
||||||
// WintunEndSession(mSession);
|
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------ Read ------------------------------
|
// ------------------------------ Read ------------------------------
|
||||||
std::vector<uint8_t> VirtualInterface::readPacket() {
|
std::vector<uint8_t> VirtualInterface::readPacket() {
|
||||||
#if defined(__linux__) || defined(__APPLE__)
|
#if defined(__linux__)
|
||||||
|
|
||||||
|
// Linux TUN: blocking read is fine, unblocks on fd close / EINTR
|
||||||
std::vector<uint8_t> buf(4096);
|
std::vector<uint8_t> buf(4096);
|
||||||
ssize_t n = read(mFd, buf.data(), buf.size());
|
ssize_t n = read(mFd, buf.data(), buf.size());
|
||||||
if (n < 0) {
|
if (n < 0) {
|
||||||
if (errno == EINTR) {
|
if (errno == EINTR) {
|
||||||
return {}; // Interrupted, return empty
|
return {}; // Interrupted, just return empty
|
||||||
}
|
}
|
||||||
throw std::runtime_error("read() failed: " + std::string(strerror(errno)));
|
throw std::runtime_error("read() failed: " + std::string(strerror(errno)));
|
||||||
}
|
}
|
||||||
buf.resize(n);
|
buf.resize(n);
|
||||||
return buf;
|
return buf;
|
||||||
|
|
||||||
#elif defined(_WIN32)
|
#elif defined(__APPLE__)
|
||||||
WINTUN_PACKET* packet = WintunReceivePacket(mSession, nullptr);
|
|
||||||
if (!packet) return {};
|
// macOS utun: must poll, or read() can block forever
|
||||||
std::vector<uint8_t> buf(packet->Data, packet->Data + packet->Length);
|
std::vector<uint8_t> buf(4096);
|
||||||
WintunReleaseReceivePacket(mSession, packet);
|
|
||||||
|
struct pollfd pfd;
|
||||||
|
pfd.fd = mFd;
|
||||||
|
pfd.events = POLLIN;
|
||||||
|
|
||||||
|
// timeout in ms; keep it small so shutdown is responsive
|
||||||
|
int ret = poll(&pfd, 1, 200);
|
||||||
|
|
||||||
|
if (ret == 0) {
|
||||||
|
// No data yet
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ret < 0) {
|
||||||
|
if (errno == EINTR) {
|
||||||
|
return {}; // Interrupted by signal
|
||||||
|
}
|
||||||
|
throw std::runtime_error("poll() failed: " + std::string(strerror(errno)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!(pfd.revents & POLLIN)) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize_t n = read(mFd, buf.data(), buf.size());
|
||||||
|
if (n <= 0) {
|
||||||
|
// 0 or -1: treat as EOF or transient; you can decide how aggressive to be
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (n > 4) {
|
||||||
|
// Drop macOS UTUN header (4 bytes)
|
||||||
|
std::memmove(buf.data(), buf.data() + 4, n - 4);
|
||||||
|
buf.resize(n - 4);
|
||||||
|
} else {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
return buf;
|
return buf;
|
||||||
|
|
||||||
|
#elif defined(_WIN32)
|
||||||
|
|
||||||
|
DWORD size = 0;
|
||||||
|
BYTE* packet = pWintunReceivePacket(mSession, &size);
|
||||||
|
if (!packet)
|
||||||
|
return {};
|
||||||
|
|
||||||
|
std::vector<uint8_t> buf(packet, packet + size);
|
||||||
|
pWintunReleaseReceivePacket(mSession, packet);
|
||||||
|
return buf;
|
||||||
|
|
||||||
#else
|
#else
|
||||||
return {};
|
return {};
|
||||||
#endif
|
#endif
|
||||||
@@ -120,16 +234,52 @@ namespace ColumnLynx::Net {
|
|||||||
|
|
||||||
// ------------------------------ Write ------------------------------
|
// ------------------------------ Write ------------------------------
|
||||||
void VirtualInterface::writePacket(const std::vector<uint8_t>& packet) {
|
void VirtualInterface::writePacket(const std::vector<uint8_t>& packet) {
|
||||||
#if defined(__linux__) || defined(__APPLE__)
|
#if defined(__linux__)
|
||||||
|
|
||||||
|
// Linux TUN expects raw IP packet
|
||||||
ssize_t n = write(mFd, packet.data(), packet.size());
|
ssize_t n = write(mFd, packet.data(), packet.size());
|
||||||
if (n < 0)
|
if (n < 0)
|
||||||
throw std::runtime_error("write() failed: " + std::string(strerror(errno)));
|
throw std::runtime_error("write() failed: " + std::string(strerror(errno)));
|
||||||
|
|
||||||
|
#elif defined(__APPLE__)
|
||||||
|
|
||||||
|
if (packet.empty())
|
||||||
|
return;
|
||||||
|
|
||||||
|
// Detect IPv4 or IPv6
|
||||||
|
uint8_t version = packet[0] >> 4;
|
||||||
|
uint32_t af;
|
||||||
|
|
||||||
|
if (version == 4) {
|
||||||
|
af = htonl(AF_INET);
|
||||||
|
} else if (version == 6) {
|
||||||
|
af = htonl(AF_INET6);
|
||||||
|
} else {
|
||||||
|
throw std::runtime_error("writePacket(): unknown IP version");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prepend 4-byte AF header
|
||||||
|
std::vector<uint8_t> out(packet.size() + 4);
|
||||||
|
memcpy(out.data(), &af, 4);
|
||||||
|
memcpy(out.data() + 4, packet.data(), packet.size());
|
||||||
|
|
||||||
|
ssize_t n = write(mFd, out.data(), out.size());
|
||||||
|
if (n < 0)
|
||||||
|
throw std::runtime_error("utun write() failed: " + std::string(strerror(errno)));
|
||||||
|
|
||||||
#elif defined(_WIN32)
|
#elif defined(_WIN32)
|
||||||
WINTUN_PACKET* tx = WintunAllocateSendPacket(mSession, (DWORD)packet.size());
|
|
||||||
if (!tx) throw std::runtime_error("WintunAllocateSendPacket failed");
|
BYTE* tx = pWintunAllocateSendPacket(
|
||||||
memcpy(tx->Data, packet.data(), packet.size());
|
mSession,
|
||||||
WintunSendPacket(mSession, tx);
|
static_cast<DWORD>(packet.size())
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!tx)
|
||||||
|
throw std::runtime_error("WintunAllocateSendPacket failed");
|
||||||
|
|
||||||
|
memcpy(tx, packet.data(), packet.size());
|
||||||
|
pWintunSendPacket(mSession, tx);
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,6 +305,52 @@ namespace ColumnLynx::Net {
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void VirtualInterface::resetIP() {
|
||||||
|
#if defined(__linux__)
|
||||||
|
char cmd[512];
|
||||||
|
snprintf(cmd, sizeof(cmd),
|
||||||
|
"ip addr flush dev %s",
|
||||||
|
mIfName.c_str()
|
||||||
|
);
|
||||||
|
system(cmd);
|
||||||
|
#elif defined(__APPLE__)
|
||||||
|
char cmd[512];
|
||||||
|
snprintf(cmd, sizeof(cmd),
|
||||||
|
"ifconfig %s inet 0.0.0.0 delete",
|
||||||
|
mIfName.c_str()
|
||||||
|
);
|
||||||
|
system(cmd);
|
||||||
|
|
||||||
|
snprintf(cmd, sizeof(cmd),
|
||||||
|
"ifconfig %s inet6 :: delete",
|
||||||
|
mIfName.c_str()
|
||||||
|
);
|
||||||
|
system(cmd);
|
||||||
|
|
||||||
|
// Wipe old routes
|
||||||
|
//snprintf(cmd, sizeof(cmd),
|
||||||
|
// "route -n delete -net %s",
|
||||||
|
// mIfName.c_str()
|
||||||
|
//);
|
||||||
|
//system(cmd);
|
||||||
|
#elif defined(_WIN32)
|
||||||
|
char cmd[512];
|
||||||
|
// Remove any persistent routes associated with this interface
|
||||||
|
snprintf(cmd, sizeof(cmd),
|
||||||
|
"netsh routing ip delete persistentroute all name=\"%s\"",
|
||||||
|
mIfName.c_str()
|
||||||
|
);
|
||||||
|
system(cmd);
|
||||||
|
|
||||||
|
// Reset to DHCP
|
||||||
|
snprintf(cmd, sizeof(cmd),
|
||||||
|
"netsh interface ip set address name=\"%s\" dhcp",
|
||||||
|
mIfName.c_str()
|
||||||
|
);
|
||||||
|
system(cmd);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
// Linux
|
// Linux
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
@@ -195,7 +391,8 @@ namespace ColumnLynx::Net {
|
|||||||
|
|
||||||
std::string ipStr = ipv4ToString(clientIP);
|
std::string ipStr = ipv4ToString(clientIP);
|
||||||
std::string peerStr = ipv4ToString(serverIP);
|
std::string peerStr = ipv4ToString(serverIP);
|
||||||
std::string prefixStr = ipv4ToString(prefixLen);
|
std::string prefixStr = ipv4ToString(prefixLengthToNetmask(prefixLen), false);
|
||||||
|
Utils::debug("Prefix string: " + prefixStr);
|
||||||
|
|
||||||
// Reset
|
// Reset
|
||||||
snprintf(cmd, sizeof(cmd),
|
snprintf(cmd, sizeof(cmd),
|
||||||
@@ -212,10 +409,16 @@ namespace ColumnLynx::Net {
|
|||||||
|
|
||||||
// Set
|
// Set
|
||||||
snprintf(cmd, sizeof(cmd),
|
snprintf(cmd, sizeof(cmd),
|
||||||
"ifconfig %s %s %s mtu %d netmask %s up",
|
"ifconfig %s inet %s %s mtu %d netmask %s up",
|
||||||
mIfName.c_str(), ipStr.c_str(), peerStr.c_str(), mtu, prefixStr.c_str());
|
mIfName.c_str(), ipStr.c_str(), peerStr.c_str(), mtu, prefixStr.c_str());
|
||||||
system(cmd);
|
system(cmd);
|
||||||
|
|
||||||
|
// Host bits are auto-normalized by the kernel on macOS, so we don't need to worry about them not being zeroed out.
|
||||||
|
snprintf(cmd, sizeof(cmd),
|
||||||
|
"route -n add -net %s/%d -interface %s",
|
||||||
|
ipStr.c_str(), prefixLen, mIfName.c_str());
|
||||||
|
system(cmd);
|
||||||
|
|
||||||
Utils::log("Executed command: " + std::string(cmd));
|
Utils::log("Executed command: " + std::string(cmd));
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
@@ -230,29 +433,66 @@ namespace ColumnLynx::Net {
|
|||||||
uint16_t mtu)
|
uint16_t mtu)
|
||||||
{
|
{
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
std::string ip = ipv4ToString(clientIP);
|
// Interface alias → LUID → Index
|
||||||
std::string gw = ipv4ToString(serverIP);
|
std::wstring ifAlias(mIfName.begin(), mIfName.end());
|
||||||
std::string mask;
|
|
||||||
|
|
||||||
// Convert prefixLen → subnet mask
|
NET_LUID luid;
|
||||||
uint32_t maskInt = (prefixLen == 0) ? 0 : (0xFFFFFFFF << (32 - prefixLen));
|
if (ConvertInterfaceAliasToLuid(ifAlias.c_str(), &luid) != NO_ERROR)
|
||||||
mask = ipv4ToString(maskInt);
|
return false;
|
||||||
|
|
||||||
char cmd[256];
|
NET_IFINDEX ifIndex;
|
||||||
|
if (ConvertInterfaceLuidToIndex(&luid, &ifIndex) != NO_ERROR)
|
||||||
|
return false;
|
||||||
|
|
||||||
// 1. Set the static IP + mask + gateway
|
// ssign IPv4 address + prefix
|
||||||
snprintf(cmd, sizeof(cmd),
|
MIB_UNICASTIPADDRESS_ROW addr;
|
||||||
"netsh interface ip set address name=\"%s\" static %s %s %s",
|
InitializeUnicastIpAddressEntry(&addr);
|
||||||
mIfName.c_str(), ip.c_str(), mask.c_str(), gw.c_str()
|
|
||||||
);
|
|
||||||
system(cmd);
|
|
||||||
|
|
||||||
// 2. Set MTU (separate command)
|
addr.InterfaceIndex = ifIndex;
|
||||||
snprintf(cmd, sizeof(cmd),
|
addr.Address.si_family = AF_INET;
|
||||||
"netsh interface ipv4 set subinterface \"%s\" mtu=%u store=persistent",
|
addr.Address.Ipv4.sin_addr.s_addr = htonl(clientIP);
|
||||||
mIfName.c_str(), mtu
|
addr.OnLinkPrefixLength = prefixLen;
|
||||||
);
|
addr.DadState = IpDadStatePreferred;
|
||||||
system(cmd);
|
|
||||||
|
if (CreateUnicastIpAddressEntry(&addr) != NO_ERROR)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
// Set MTU
|
||||||
|
MIB_IFROW ifRow;
|
||||||
|
ifRow.dwIndex = ifIndex;
|
||||||
|
|
||||||
|
if (GetIfEntry(&ifRow) != NO_ERROR)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
ifRow.dwMtu = mtu;
|
||||||
|
|
||||||
|
if (SetIfEntry(&ifRow) != NO_ERROR)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
// Add persistent route for VPN network via this interface
|
||||||
|
uint32_t mask =
|
||||||
|
(prefixLen == 0) ? 0 : (0xFFFFFFFFu << (32 - prefixLen));
|
||||||
|
uint32_t network = clientIP & mask;
|
||||||
|
|
||||||
|
MIB_IPFORWARD_ROW2 route;
|
||||||
|
InitializeIpForwardEntry(&route);
|
||||||
|
|
||||||
|
route.InterfaceIndex = ifIndex;
|
||||||
|
route.DestinationPrefix.Prefix.si_family = AF_INET;
|
||||||
|
route.DestinationPrefix.Prefix.Ipv4.sin_addr.s_addr = htonl(network);
|
||||||
|
route.DestinationPrefix.PrefixLength = prefixLen;
|
||||||
|
|
||||||
|
route.NextHop.si_family = AF_INET;
|
||||||
|
route.NextHop.Ipv4.sin_addr.s_addr = 0;
|
||||||
|
|
||||||
|
route.Metric = 1;
|
||||||
|
route.Protocol = static_cast<NL_ROUTE_PROTOCOL>(MIB_IPPROTO_NETMGMT);
|
||||||
|
route.ValidLifetime = 0xFFFFFFFF;
|
||||||
|
route.PreferredLifetime = 0xFFFFFFFF;
|
||||||
|
|
||||||
|
DWORD r = CreateIpForwardEntry2(&route);
|
||||||
|
if (r != NO_ERROR && r != ERROR_OBJECT_ALREADY_EXISTS)
|
||||||
|
return false;
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
#else
|
#else
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
// main.cpp - Server entry point for ColumnLynx
|
// main.cpp - Server entry point for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#include <asio.hpp>
|
#include <asio.hpp>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
#include <thread>
|
||||||
|
#include <chrono>
|
||||||
#include <columnlynx/common/utils.hpp>
|
#include <columnlynx/common/utils.hpp>
|
||||||
#include <columnlynx/common/panic_handler.hpp>
|
#include <columnlynx/common/panic_handler.hpp>
|
||||||
#include <columnlynx/server/net/tcp/tcp_server.hpp>
|
#include <columnlynx/server/net/tcp/tcp_server.hpp>
|
||||||
@@ -14,6 +16,10 @@
|
|||||||
#include <cxxopts.hpp>
|
#include <cxxopts.hpp>
|
||||||
#include <columnlynx/common/net/virtual_interface.hpp>
|
#include <columnlynx/common/net/virtual_interface.hpp>
|
||||||
|
|
||||||
|
#if defined(__WIN32__)
|
||||||
|
#include <windows.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
using asio::ip::tcp;
|
using asio::ip::tcp;
|
||||||
using namespace ColumnLynx::Utils;
|
using namespace ColumnLynx::Utils;
|
||||||
using namespace ColumnLynx::Net::TCP;
|
using namespace ColumnLynx::Net::TCP;
|
||||||
@@ -23,20 +29,7 @@ using namespace ColumnLynx;
|
|||||||
|
|
||||||
volatile sig_atomic_t done = 0;
|
volatile sig_atomic_t done = 0;
|
||||||
|
|
||||||
void signalHandler(int signum) {
|
|
||||||
if (signum == SIGINT || signum == SIGTERM) {
|
|
||||||
log("Received termination signal. Shutting down server gracefully.");
|
|
||||||
done = 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int main(int argc, char** argv) {
|
int main(int argc, char** argv) {
|
||||||
// Capture SIGINT and SIGTERM for graceful shutdown
|
|
||||||
struct sigaction action;
|
|
||||||
memset(&action, 0, sizeof(struct sigaction));
|
|
||||||
action.sa_handler = signalHandler;
|
|
||||||
sigaction(SIGINT, &action, nullptr);
|
|
||||||
sigaction(SIGTERM, &action, nullptr);
|
|
||||||
|
|
||||||
cxxopts::Options options("columnlynx_server", "ColumnLynx Server Application");
|
cxxopts::Options options("columnlynx_server", "ColumnLynx Server Application");
|
||||||
|
|
||||||
@@ -48,7 +41,12 @@ int main(int argc, char** argv) {
|
|||||||
#else
|
#else
|
||||||
("i,interface", "Override used interface", cxxopts::value<std::string>()->default_value("lynx0"))
|
("i,interface", "Override used interface", cxxopts::value<std::string>()->default_value("lynx0"))
|
||||||
#endif
|
#endif
|
||||||
("config", "Override config file path", cxxopts::value<std::string>()->default_value("./server_config"));
|
#if defined(__WIN32__)
|
||||||
|
/* Get config dir in LOCALAPPDATA\ColumnLynx\ */
|
||||||
|
("config-dir", "Override config dir path", cxxopts::value<std::string>()->default_value("C:\\ProgramData\\ColumnLynx\\"));
|
||||||
|
#else
|
||||||
|
("config-dir", "Override config dir path", cxxopts::value<std::string>()->default_value("/etc/columnlynx"));
|
||||||
|
#endif
|
||||||
|
|
||||||
PanicHandler::init();
|
PanicHandler::init();
|
||||||
|
|
||||||
@@ -57,7 +55,7 @@ int main(int argc, char** argv) {
|
|||||||
if (optionsObj.count("help")) {
|
if (optionsObj.count("help")) {
|
||||||
std::cout << options.help() << std::endl;
|
std::cout << options.help() << std::endl;
|
||||||
std::cout << "This software is licensed under the GPLv2-only license OR the GPLv3 license.\n";
|
std::cout << "This software is licensed under the GPLv2-only license OR the GPLv3 license.\n";
|
||||||
std::cout << "Copyright (C) 2025, The ColumnLynx Contributors.\n";
|
std::cout << "Copyright (C) 2026, The ColumnLynx Contributors.\n";
|
||||||
std::cout << "This software is provided under ABSOLUTELY NO WARRANTY, to the extent permitted by law.\n";
|
std::cout << "This software is provided under ABSOLUTELY NO WARRANTY, to the extent permitted by law.\n";
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -68,10 +66,25 @@ int main(int argc, char** argv) {
|
|||||||
log("This software is licensed under the GPLv2 only OR the GPLv3. See LICENSES/ for details.");
|
log("This software is licensed under the GPLv2 only OR the GPLv3. See LICENSES/ for details.");
|
||||||
|
|
||||||
#if defined(__WIN32__)
|
#if defined(__WIN32__)
|
||||||
WintunInitialize();
|
//WintunInitialize();
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
std::unordered_map<std::string, std::string> config = Utils::getConfigMap(optionsObj["config"].as<std::string>());
|
// Get the config path, ENV > CLI > /etc/columnlynx
|
||||||
|
std::string configPath = optionsObj["config-dir"].as<std::string>();
|
||||||
|
const char* envConfigPath = std::getenv("COLUMNLYNX_CONFIG_DIR");
|
||||||
|
if (envConfigPath != nullptr) {
|
||||||
|
configPath = std::string(envConfigPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (configPath.back() != '/' && configPath.back() != '\\') {
|
||||||
|
#if defined(__WIN32__)
|
||||||
|
configPath += "\\";
|
||||||
|
#else
|
||||||
|
configPath += "/";
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
std::unordered_map<std::string, std::string> config = Utils::getConfigMap(configPath + "server_config");
|
||||||
|
|
||||||
std::shared_ptr<VirtualInterface> tun = std::make_shared<VirtualInterface>(optionsObj["interface"].as<std::string>());
|
std::shared_ptr<VirtualInterface> tun = std::make_shared<VirtualInterface>(optionsObj["interface"].as<std::string>());
|
||||||
log("Using virtual interface: " + tun->getName());
|
log("Using virtual interface: " + tun->getName());
|
||||||
@@ -86,14 +99,20 @@ int main(int argc, char** argv) {
|
|||||||
log("Loading keypair from config file.");
|
log("Loading keypair from config file.");
|
||||||
|
|
||||||
PublicKey pk;
|
PublicKey pk;
|
||||||
PrivateKey sk;
|
PrivateSeed seed;
|
||||||
|
|
||||||
std::copy_n(Utils::hexStringToBytes(itPrivkey->second).begin(), sk.size(), sk.begin());
|
std::copy_n(Utils::hexStringToBytes(itPrivkey->second).begin(), seed.size(), seed.begin());
|
||||||
std::copy_n(Utils::hexStringToBytes(itPubkey->second).begin(), pk.size(), pk.begin());
|
std::copy_n(Utils::hexStringToBytes(itPubkey->second).begin(), pk.size(), pk.begin());
|
||||||
|
|
||||||
sodiumWrapper->setKeys(pk, sk);
|
if (!sodiumWrapper->recomputeKeys(seed, pk)) {
|
||||||
|
throw std::runtime_error("Failed to recompute keypair from config file values!");
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
|
#if defined(DEBUG)
|
||||||
warn("No keypair found in config file! Using random key.");
|
warn("No keypair found in config file! Using random key.");
|
||||||
|
#else
|
||||||
|
throw std::runtime_error("No keypair found in config file! Cannot start server without keys.");
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
log("Server public key: " + bytesToHexString(sodiumWrapper->getPublicKey(), crypto_sign_PUBLICKEYBYTES));
|
log("Server public key: " + bytesToHexString(sodiumWrapper->getPublicKey(), crypto_sign_PUBLICKEYBYTES));
|
||||||
@@ -102,7 +121,7 @@ int main(int argc, char** argv) {
|
|||||||
|
|
||||||
asio::io_context io;
|
asio::io_context io;
|
||||||
|
|
||||||
auto server = std::make_shared<TCPServer>(io, serverPort(), sodiumWrapper, hostRunning, ipv4Only);
|
auto server = std::make_shared<TCPServer>(io, serverPort(), sodiumWrapper, hostRunning, configPath, ipv4Only);
|
||||||
auto udpServer = std::make_shared<UDPServer>(io, serverPort(), hostRunning, ipv4Only, tun);
|
auto udpServer = std::make_shared<UDPServer>(io, serverPort(), hostRunning, ipv4Only, tun);
|
||||||
|
|
||||||
asio::signal_set signals(io, SIGINT, SIGTERM);
|
asio::signal_set signals(io, SIGINT, SIGTERM);
|
||||||
@@ -128,19 +147,34 @@ int main(int argc, char** argv) {
|
|||||||
while (!done) {
|
while (!done) {
|
||||||
auto packet = tun->readPacket();
|
auto packet = tun->readPacket();
|
||||||
if (packet.empty()) {
|
if (packet.empty()) {
|
||||||
|
// Small sleep to avoid busy-waiting and to allow signal processing
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const uint8_t* ip = packet.data();
|
const uint8_t* ip = packet.data();
|
||||||
uint32_t dstIP = ntohl(*(uint32_t*)(ip + 16)); // IPv4 destination address offset in IPv6-mapped header
|
uint32_t srcIP = ntohl(*(uint32_t*)(ip + 12)); // IPv4 source address offset
|
||||||
|
uint32_t dstIP = ntohl(*(uint32_t*)(ip + 16)); // IPv4 destination address offset
|
||||||
|
|
||||||
auto session = SessionRegistry::getInstance().getByIP(dstIP);
|
// First, check if destination IP is a registered client (e.g., server responding to client or client-to-client)
|
||||||
if (!session) {
|
auto dstSession = SessionRegistry::getInstance().getByIP(dstIP);
|
||||||
Utils::warn("TUN: No session found for destination IP " + VirtualInterface::ipv4ToString(dstIP));
|
if (dstSession) {
|
||||||
|
// Destination is a registered client, forward to that client's session
|
||||||
|
udpServer->sendData(dstSession->sessionID, std::string(packet.begin(), packet.end()));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
udpServer->sendData(session->sessionID, std::string(packet.begin(), packet.end()));
|
// Destination is not a registered client, check if source is (for external routing)
|
||||||
|
auto srcSession = SessionRegistry::getInstance().getByIP(srcIP);
|
||||||
|
if (srcSession) {
|
||||||
|
// Source is a registered client, write to TUN interface to forward to external destination
|
||||||
|
tun->writePacket(packet);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Neither source nor destination is registered, drop the packet
|
||||||
|
Utils::warn("TUN: No session found for source IP " + VirtualInterface::ipv4ToString(srcIP) +
|
||||||
|
" or destination IP " + VirtualInterface::ipv4ToString(dstIP));
|
||||||
}
|
}
|
||||||
|
|
||||||
log("Shutting down server...");
|
log("Shutting down server...");
|
||||||
|
|||||||
@@ -1,25 +1,44 @@
|
|||||||
// tcp_connection.cpp - TCP Connection for ColumnLynx
|
// tcp_connection.cpp - TCP Connection for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#include <columnlynx/server/net/tcp/tcp_connection.hpp>
|
#include <columnlynx/server/net/tcp/tcp_connection.hpp>
|
||||||
|
|
||||||
namespace ColumnLynx::Net::TCP {
|
namespace ColumnLynx::Net::TCP {
|
||||||
void TCPConnection::start() {
|
void TCPConnection::start() {
|
||||||
|
try {
|
||||||
|
// Cache the remote IP early to avoid calling remote_endpoint() on closed sockets later
|
||||||
|
mRemoteIP = mHandler->socket().remote_endpoint().address().to_string();
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
mRemoteIP = "unknown";
|
||||||
|
Utils::warn("Failed to get remote endpoint: " + std::string(e.what()));
|
||||||
|
}
|
||||||
|
|
||||||
mHandler->onMessage([this](AnyMessageType type, const std::string& data) {
|
mHandler->onMessage([this](AnyMessageType type, const std::string& data) {
|
||||||
mHandleMessage(static_cast<ClientMessageType>(MessageHandler::toUint8(type)), data);
|
mHandleMessage(static_cast<ClientMessageType>(MessageHandler::toUint8(type)), data);
|
||||||
});
|
});
|
||||||
|
|
||||||
mHandler->onDisconnect([this](const asio::error_code& ec) {
|
mHandler->onDisconnect([this](const asio::error_code& ec) {
|
||||||
Utils::log("Client disconnected: " + mHandler->socket().remote_endpoint().address().to_string() + " - " + ec.message());
|
// Peer has closed; finalize locally without sending RST
|
||||||
disconnect();
|
Utils::log("Client disconnected: " + mRemoteIP + " - " + ec.message());
|
||||||
|
asio::error_code ec2;
|
||||||
|
mHandler->socket().close(ec2);
|
||||||
|
|
||||||
|
SessionRegistry::getInstance().erase(mConnectionSessionID);
|
||||||
|
SessionRegistry::getInstance().deallocIP(mConnectionSessionID);
|
||||||
|
|
||||||
|
Utils::log("Closed connection to " + mRemoteIP);
|
||||||
|
|
||||||
|
if (mOnDisconnect) {
|
||||||
|
mOnDisconnect(shared_from_this());
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
mHandler->start();
|
mHandler->start();
|
||||||
mStartHeartbeat();
|
mStartHeartbeat();
|
||||||
|
|
||||||
// Placeholder for message handling setup
|
// Placeholder for message handling setup
|
||||||
Utils::log("Client connected: " + mHandler->socket().remote_endpoint().address().to_string());
|
Utils::log("Client connected: " + mRemoteIP);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TCPConnection::sendMessage(ServerMessageType type, const std::string& data) {
|
void TCPConnection::sendMessage(ServerMessageType type, const std::string& data) {
|
||||||
@@ -32,23 +51,19 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
mOnDisconnect = std::move(cb);
|
mOnDisconnect = std::move(cb);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TCPConnection::disconnect() {
|
void TCPConnection::disconnect(bool echo) {
|
||||||
std::string ip = mHandler->socket().remote_endpoint().address().to_string();
|
if (echo) {
|
||||||
|
|
||||||
mHandler->sendMessage(ServerMessageType::GRACEFUL_DISCONNECT, "Server initiated disconnect.");
|
mHandler->sendMessage(ServerMessageType::GRACEFUL_DISCONNECT, "Server initiated disconnect.");
|
||||||
|
}
|
||||||
mHeartbeatTimer.cancel();
|
mHeartbeatTimer.cancel();
|
||||||
asio::error_code ec;
|
asio::error_code ec;
|
||||||
mHandler->socket().shutdown(asio::ip::tcp::socket::shutdown_both, ec);
|
// Half-close: stop sending, keep reading until peer FIN
|
||||||
mHandler->socket().close(ec);
|
mHandler->socket().shutdown(asio::ip::tcp::socket::shutdown_send, ec);
|
||||||
|
if (ec) {
|
||||||
SessionRegistry::getInstance().erase(mConnectionSessionID);
|
Utils::error("Error during socket shutdown: " + ec.message());
|
||||||
SessionRegistry::getInstance().deallocIP(mConnectionSessionID);
|
|
||||||
|
|
||||||
Utils::log("Closed connection to " + ip);
|
|
||||||
|
|
||||||
if (mOnDisconnect) {
|
|
||||||
mOnDisconnect(shared_from_this());
|
|
||||||
}
|
}
|
||||||
|
// Do not close immediately; final cleanup happens in onDisconnect
|
||||||
|
Utils::log("Initiated graceful disconnect (half-close) to " + mRemoteIP);
|
||||||
}
|
}
|
||||||
|
|
||||||
uint64_t TCPConnection::getSessionID() const {
|
uint64_t TCPConnection::getSessionID() const {
|
||||||
@@ -92,7 +107,7 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TCPConnection::mHandleMessage(ClientMessageType type, const std::string& data) {
|
void TCPConnection::mHandleMessage(ClientMessageType type, const std::string& data) {
|
||||||
std::string reqAddr = mHandler->socket().remote_endpoint().address().to_string();
|
std::string& reqAddr = mRemoteIP;
|
||||||
|
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case ClientMessageType::HANDSHAKE_INIT: {
|
case ClientMessageType::HANDSHAKE_INIT: {
|
||||||
@@ -130,7 +145,7 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
|
|
||||||
Utils::debug("Key attempted connect: " + Utils::bytesToHexString(signPk.data(), signPk.size()));
|
Utils::debug("Key attempted connect: " + Utils::bytesToHexString(signPk.data(), signPk.size()));
|
||||||
|
|
||||||
std::vector<std::string> whitelistedKeys = Utils::getWhitelistedKeys();
|
std::vector<std::string> whitelistedKeys = Utils::getWhitelistedKeys(mConfigDirPath);
|
||||||
|
|
||||||
if (std::find(whitelistedKeys.begin(), whitelistedKeys.end(), Utils::bytesToHexString(signPk.data(), signPk.size())) == whitelistedKeys.end()) {
|
if (std::find(whitelistedKeys.begin(), whitelistedKeys.end(), Utils::bytesToHexString(signPk.data(), signPk.size())) == whitelistedKeys.end()) {
|
||||||
Utils::warn("Non-whitelisted client attempted to connect, terminating. Client IP: " + reqAddr);
|
Utils::warn("Non-whitelisted client attempted to connect, terminating. Client IP: " + reqAddr);
|
||||||
@@ -272,6 +287,11 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
disconnect();
|
disconnect();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
case ClientMessageType::KILL_CONNECTION: {
|
||||||
|
Utils::warn("Received KILL_CONNECTION from " + reqAddr + ": " + data);
|
||||||
|
disconnect();
|
||||||
|
break;
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
Utils::warn("Unhandled message type from " + reqAddr);
|
Utils::warn("Unhandled message type from " + reqAddr);
|
||||||
break;
|
break;
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
// tcp_server.cpp - TCP Server for ColumnLynx
|
// tcp_server.cpp - TCP Server for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#include <columnlynx/server/net/tcp/tcp_server.hpp>
|
#include <columnlynx/server/net/tcp/tcp_server.hpp>
|
||||||
@@ -36,6 +36,7 @@ namespace ColumnLynx::Net::TCP {
|
|||||||
std::move(socket),
|
std::move(socket),
|
||||||
mSodiumWrapper,
|
mSodiumWrapper,
|
||||||
&mRawServerConfig,
|
&mRawServerConfig,
|
||||||
|
mConfigDirPath,
|
||||||
[this](std::shared_ptr<TCPConnection> c) {
|
[this](std::shared_ptr<TCPConnection> c) {
|
||||||
mClients.erase(c);
|
mClients.erase(c);
|
||||||
Utils::log("Client removed.");
|
Utils::log("Client removed.");
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
// udp_server.cpp - UDP Server for ColumnLynx
|
// udp_server.cpp - UDP Server for ColumnLynx
|
||||||
// Copyright (C) 2025 DcruBro
|
// Copyright (C) 2026 DcruBro
|
||||||
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
// Distributed under the terms of the GNU General Public License, either version 2 only or version 3. See LICENSES/ for details.
|
||||||
|
|
||||||
#include <columnlynx/server/net/udp/udp_server.hpp>
|
#include <columnlynx/server/net/udp/udp_server.hpp>
|
||||||
Reference in New Issue
Block a user