# Module Service - VPN
## Overview
The VPN Service provides secure virtual private network functionality within the Cellframe SDK. This service implements a complete VPN solution including TUN/TAP interface management, IP address allocation, packet routing, session management, and integrated billing through the Cellframe network infrastructure.
*Based on: `dap_chain_net_srv_vpn.h`, `dap_chain_net_srv_vpn.c`, `dap_stream_ch_vpn.h`, `dap_stream_ch_vpn.c`*
**Service UID:** `DAP_CHAIN_NET_SRV_VPN_ID` (0x01)
## Document Structure
- [[#Overview|Overview]]
- [[#VPN Structures|VPN Structures]]
- [[#dap_stream_ch_vpn_pkt_t|dap_stream_ch_vpn_pkt_t - VPN packet structure]]
- [[#dap_chain_net_srv_vpn_tun_socket_t|dap_chain_net_srv_vpn_tun_socket_t - TUN socket structure]]
- [[#dap_chain_net_srv_ch_vpn_t|dap_chain_net_srv_ch_vpn_t - VPN channel structure]]
- [[#dap_chain_net_srv_ch_vpn_info_t|dap_chain_net_srv_ch_vpn_info_t - VPN client information]]
- [[#dap_chain_net_srv_vpn_item_ipv4_t|dap_chain_net_srv_vpn_item_ipv4_t - IPv4 address pool item]]
- [[#dap_chain_net_srv_vpn_t|dap_chain_net_srv_vpn_t - Main VPN service structure]]
- [[#dap_chain_net_vpn_client_status_t|dap_chain_net_vpn_client_status_t - Client status enumeration]]
- [[#VPN Functions|VPN Functions]]
- [[#Service Management|Service Management Functions]]
- [[#Client Management|Client Management Functions]]
- [[#TUN Interface Management|TUN Interface Management Functions]]
- [[#Typical Examples|Typical Examples]]
## VPN Structures
### dap_stream_ch_vpn_pkt_t
Main VPN packet structure for data transmission between client and server.
```c
typedef struct dap_stream_ch_vpn_pkt {
struct {
int sock_id; // Client's socket identifier
uint32_t op_code; // Operation code
uint32_t usage_id; // Usage ID for multinetworking
union {
struct { // L4 connect operation
uint32_t addr_size;
uint16_t port DAP_ALIGNED(4);
} DAP_PACKED op_connect;
struct { // Data transmission operations
uint32_t data_size DAP_ALIGNED(8);
} DAP_PACKED op_data;
struct { // Problem reporting
uint32_t code DAP_ALIGNED(8);
} DAP_PACKED op_problem;
struct {
uint64_t op_data_raw DAP_ALIGNED(8);
} DAP_PACKED raw; // Raw access to operation bytes
};
} DAP_ALIGN_PACKED header;
byte_t data[]; // Binary data payload
} DAP_ALIGN_PACKED dap_stream_ch_vpn_pkt_t;
```
**Fields:**
- `sock_id` - Client socket identifier for session tracking
- `op_code` - Operation code defining packet type and action
- `usage_id` - Usage identifier for multinetwork support
- `op_connect` - Connection establishment parameters
- `op_data` - Data transmission parameters
- `op_problem` - Error and problem reporting
- `data[]` - Variable-length payload data
### dap_chain_net_srv_ch_vpn_t
VPN channel structure representing individual client connections.
```c
typedef struct dap_chain_net_srv_ch_vpn {
uint32_t usage_id; // Usage identifier
dap_chain_net_srv_t* net_srv; // Network service reference
bool is_allowed; // Connection authorization status
dap_chain_net_srv_vpn_tun_socket_t * tun_socket; // TUN socket reference
struct in_addr addr_ipv4; // Assigned IPv4 address
dap_stream_ch_t * ch; // Stream channel reference
UT_hash_handle hh; // Hash table handle
} dap_chain_net_srv_ch_vpn_t;
```
**Fields:**
- `usage_id` - Unique identifier for this VPN session
- `net_srv` - Pointer to parent network service
- `is_allowed` - Authorization status for connection
- `tun_socket` - Reference to TUN interface socket
- `addr_ipv4` - Assigned IPv4 address for this client
- `ch` - Stream channel for communication
- `hh` - Hash table handle for efficient lookup
### dap_chain_net_srv_vpn_t
Main VPN service structure managing all VPN operations.
```c
typedef struct dap_chain_net_srv_vpn {
dap_chain_net_srv_vpn_item_ipv4_t * ipv4_unleased; // Available IP addresses
dap_chain_net_srv_ch_vpn_t * ch_vpn_ipv4; // Active VPN channels
dap_chain_net_srv_t * parent; // Parent service
} dap_chain_net_srv_vpn_t;
```
### dap_chain_net_srv_vpn_tun_socket_t
TUN socket management structure.
```c
typedef struct dap_chain_net_srv_vpn_tun_socket {
uint8_t worker_id; // Worker thread identifier
dap_worker_t * worker; // Worker thread reference
dap_events_socket_t * es; // Event socket
dap_chain_net_srv_ch_vpn_info_t * clients; // Remote clients list
dap_events_socket_t ** queue_tun_msg_input; // Message input queue
size_t buf_size_aux; // Auxiliary buffer size
} dap_chain_net_srv_vpn_tun_socket_t;
```
### dap_chain_net_srv_ch_vpn_t
VPN channel structure for individual client connections.
```c
typedef struct dap_chain_net_srv_ch_vpn {
uint32_t usage_id; // Usage identifier
dap_chain_net_srv_t *net_srv; // Network service reference
bool is_allowed; // Connection allowed flag
dap_chain_net_srv_vpn_tun_socket_t *tun_socket; // TUN socket reference
struct in_addr addr_ipv4; // Assigned IPv4 address
dap_stream_ch_t *ch; // Stream channel
UT_hash_handle hh; // Hash table handle
} dap_chain_net_srv_ch_vpn_t;
```
### dap_chain_net_srv_ch_vpn_info_t
Extended VPN client information structure.
```c
typedef struct dap_chain_net_srv_ch_vpn_info {
struct in_addr addr_ipv4; // Assigned IPv4 address
bool is_on_this_worker; // Worker location flag
bool is_reassigned_once; // Reassignment prevention flag
uint32_t usage_id; // Usage identifier
dap_chain_net_srv_ch_vpn_t *ch_vpn; // VPN channel reference
uint64_t ch_vpn_uuid; // Channel UUID
dap_events_socket_t *queue_msg; // Message queue socket
dap_worker_t *worker; // Associated worker
dap_events_socket_t *esocket; // Event socket
dap_events_socket_uuid_t esocket_uuid; // Socket UUID
UT_hash_handle hh; // Hash table handle
} dap_chain_net_srv_ch_vpn_info_t;
```
### dap_chain_net_srv_vpn_item_ipv4_t
IPv4 address pool item for VPN address management.
```c
typedef struct dap_chain_net_srv_vpn_item_ipv4 {
struct in_addr addr; // IPv4 address
struct dap_chain_net_srv_vpn_item_ipv4 *next; // Next item in list
} dap_chain_net_srv_vpn_item_ipv4_t;
```
### dap_chain_net_srv_vpn_t
Main VPN service structure managing all VPN operations.
```c
typedef struct dap_chain_net_srv_vpn {
dap_chain_net_srv_vpn_item_ipv4_t *ipv4_unleased; // Available IPv4 addresses
dap_chain_net_srv_ch_vpn_t *ch_vpn_ipv4; // Active VPN channels
dap_chain_net_srv_t *parent; // Parent service reference
} dap_chain_net_srv_vpn_t;
```
### dap_chain_net_vpn_client_status_t
VPN client connection status enumeration.
```c
typedef enum dap_chain_net_vpn_client_status_enum {
VPN_CLIENT_STATUS_NOT_STARTED = 0, // Client not started
VPN_CLIENT_STATUS_STARTED, // Client started and running
VPN_CLIENT_STATUS_STOPPED, // Client stopped
VPN_CLIENT_STATUS_CONN_LOST // Connection lost
} dap_chain_net_vpn_client_status_t;
```
### VPN Operation Codes
Operation codes for VPN packet types.
```c
#define VPN_PACKET_OP_CODE_CONNECTED 0x000000a9
#define VPN_PACKET_OP_CODE_CONNECT 0x000000aa
#define VPN_PACKET_OP_CODE_DISCONNECT 0x000000ab
#define VPN_PACKET_OP_CODE_SEND 0x000000ac
#define VPN_PACKET_OP_CODE_RECV 0x000000ad
#define VPN_PACKET_OP_CODE_PROBLEM 0x000000ae
#define VPN_PACKET_OP_CODE_VPN_ADDR_REQUEST 0x000000b2
#define VPN_PACKET_OP_CODE_VPN_ADDR_REPLY 0x000000b3
#define VPN_PACKET_OP_CODE_VPN_SEND 0x000000bc
#define VPN_PACKET_OP_CODE_VPN_RECV 0x000000bd
#define VPN_PACKET_OP_CODE_PING 0xc0
#define VPN_PACKET_OP_CODE_PONG 0xc1
```
### VPN Problem Codes
Error codes for VPN problem reporting.
```c
#define VPN_PROBLEM_CODE_NO_FREE_ADDR 0x00000001
#define VPN_PROBLEM_CODE_TUNNEL_DOWN 0x00000002
#define VPN_PROBLEM_CODE_PACKET_LOST 0x00000003
#define VPN_PROBLEM_CODE_ALREADY_ASSIGNED_ADDR 0x00000004
```
## VPN Functions
### Service Management
#### `dap_chain_net_srv_vpn_init()`
Initializes the VPN service with configuration parameters.
```c
int dap_chain_net_srv_vpn_init(dap_config_t * g_config);
```
**Parameters:**
- `g_config` (dap_config_t *) - Configuration context
**Returns:**
- `0` - Initialization successful
- `-1` - TUN initialization failed
- `-2` - TUN device creation failed
- `-3` - VPN service creation failed
- `-100` - Server configuration error
**Description:** Initializes the complete VPN service including TUN device setup, service registration, and command interface configuration.
#### `dap_chain_net_srv_vpn_deinit()`
Deinitializes the VPN service and cleans up resources.
```c
void dap_chain_net_srv_vpn_deinit(void);
```
**Description:** Cleans up VPN service resources, closes TUN devices, and frees allocated memory.
#### `dap_chain_net_srv_vpn_pre_init()`
Pre-initializes VPN service for ledger tag registration.
```c
int dap_chain_net_srv_vpn_pre_init();
```
**Returns:**
- `0` - Pre-initialization successful
**Description:** Registers VPN service with the ledger system for transaction tagging and validation.
### Client Management
#### `dap_chain_net_vpn_client_init()`
Initializes VPN client functionality.
```c
int dap_chain_net_vpn_client_init(dap_config_t * g_config);
```
**Parameters:**
- `g_config` (dap_config_t *) - Configuration context
**Returns:**
- `0` - Client initialization successful
- Non-zero - Initialization failed
#### `dap_chain_net_vpn_client_start()`
Starts VPN client connection to specified server.
```c
int dap_chain_net_vpn_client_start(dap_chain_net_t *a_net, const char *a_host, uint16_t a_port);
```
**Parameters:**
- `a_net` (dap_chain_net_t *) - Network context
- `a_host` (const char *) - VPN server hostname or IP
- `a_port` (uint16_t) - VPN server port
**Returns:**
- `0` - Connection successful
- `1` - Already started
- `-1` - Invalid parameters
- `-2` - Connection failed
- `-3` - No response from server
#### `dap_chain_net_vpn_client_stop()`
Stops VPN client connection.
```c
int dap_chain_net_vpn_client_stop(void);
```
**Returns:**
- `0` - Disconnection successful
- Non-zero - Error occurred
#### `dap_chain_net_vpn_client_status()`
Gets current VPN client status.
```c
dap_chain_net_vpn_client_status_t dap_chain_net_vpn_client_status(void);
```
**Returns:**
- `VPN_CLIENT_STATUS_NOT_STARTED` - Client not started
- `VPN_CLIENT_STATUS_STARTED` - Client active and connected
- `VPN_CLIENT_STATUS_STOPPED` - Client stopped
- `VPN_CLIENT_STATUS_CONN_LOST` - Connection lost
#### `dap_chain_net_vpn_client_check()`
Tests VPN server connectivity and performance.
```c
int dap_chain_net_vpn_client_check(
dap_chain_net_t *a_net,
const char *a_host,
uint16_t a_port,
size_t a_data_size_to_send,
size_t a_data_size_to_recv,
int a_timeout_test_ms
);
```
**Parameters:**
- `a_net` (dap_chain_net_t *) - Network context
- `a_host` (const char *) - Server hostname or IP
- `a_port` (uint16_t) - Server port
- `a_data_size_to_send` (size_t) - Test data size to send
- `a_data_size_to_recv` (size_t) - Test data size to receive
- `a_timeout_test_ms` (int) - Test timeout in milliseconds
**Returns:**
- `0` - Server check successful
- `-1` - Invalid parameters
- `-2` - Connection failed
- `-3` - No response within timeout
### TUN Interface Management
#### `dap_chain_net_vpn_client_tun_init()`
Initializes TUN interface for VPN client.
```c
int dap_chain_net_vpn_client_tun_init(const char *a_ipv4_gw_str);
```
**Parameters:**
- `a_ipv4_gw_str` (const char *) - Gateway IP address string
**Returns:**
- `0` - TUN initialization successful
- Non-zero - Initialization failed
#### `dap_chain_net_vpn_client_tun_create()`
Creates TUN interface with specified parameters.
```c
int dap_chain_net_vpn_client_tun_create(const char *a_ipv4_addr_str, const char *a_ipv4_gw_str);
```
**Parameters:**
- `a_ipv4_addr_str` (const char *) - Client IP address
- `a_ipv4_gw_str` (const char *) - Gateway IP address
**Returns:**
- `0` - TUN interface created successfully
- Non-zero - Creation failed
#### `dap_chain_net_vpn_client_tun_delete()`
Deletes TUN interface and cleans up resources.
```c
int dap_chain_net_vpn_client_tun_delete(void);
```
**Returns:**
- `0` - TUN interface deleted successfully
- Non-zero - Deletion failed
#### `dap_chain_net_vpn_client_get_stream_ch()`
Gets VPN client stream channel.
```c
dap_stream_ch_t* dap_chain_net_vpn_client_get_stream_ch(void);
```
**Returns:**
- Pointer to stream channel
- `NULL` if not available
#### `dap_chain_net_vpn_client_get_stream_worker()`
Gets VPN client stream worker.
```c
dap_stream_worker_t* dap_chain_net_vpn_client_get_stream_worker(void);
```
**Returns:**
- Pointer to stream worker
- `NULL` if not available
## Typical Examples
### VPN Service Initialization Example
```c
#include <dap_chain_net_srv_vpn.h>
void vpn_service_initialization_example() {
log_it_info("=== VPN Service Initialization ===");
// Step 1: Load configuration
dap_config_t *config = dap_config_default();
if (!config) {
log_it_error("✗ Failed to load configuration");
return;
}
// Step 2: Pre-initialize VPN service
int pre_init_result = dap_chain_net_srv_vpn_pre_init();
if (pre_init_result != 0) {
log_it_error("✗ VPN service pre-initialization failed: %d", pre_init_result);
return;
}
log_it_info("✓ VPN service pre-initialized successfully");
log_it_info(" Service ID: 0x%016llX", DAP_CHAIN_NET_SRV_VPN_ID);
log_it_info(" Ledger tagging: Enabled");
// Step 3: Initialize full VPN service
int init_result = dap_chain_net_srv_vpn_init(config);
switch (init_result) {
case 0:
log_it_info("✓ VPN service initialized successfully");
log_it_info(" TUN device: Ready");
log_it_info(" Service registration: Complete");
log_it_info(" Command interface: Active");
break;
case -1:
log_it_error("✗ TUN initialization failed");
return;
case -2:
log_it_error("✗ TUN device creation failed");
return;
case -3:
log_it_error("✗ VPN service creation failed");
return;
case -100:
log_it_error("✗ Server configuration error");
return;
default:
log_it_error("✗ Unknown initialization error: %d", init_result);
return;
}
// Step 4: Verify service capabilities
log_it_info("VPN Service Capabilities:");
log_it_info(" • TUN/TAP interface management");
log_it_info(" • Dynamic IP allocation");
log_it_info(" • Encrypted packet routing");
log_it_info(" • Session management");
log_it_info(" • Blockchain billing integration");
log_it_info(" • Cross-platform support");
log_it_info(" • Traffic monitoring");
log_it_info("VPN service is ready for client connections");
log_it_info("VPN service initialization example completed");
}
```
### VPN Client Connection Example
```c
#include <dap_chain_net_srv_vpn.h>
#include <dap_chain_net_vpn_client.h>
void vpn_client_connection_example() {
log_it_info("=== VPN Client Connection Example ===");
// Step 1: Setup network context
dap_chain_net_t *net = dap_chain_net_by_name("backbone");
if (!net) {
log_it_error("✗ Network 'backbone' not found");
return;
}
// Step 2: Configure VPN server details
const char *vpn_server_host = "vpn.example.com";
uint16_t vpn_server_port = 8089;
log_it_info("VPN Connection Parameters:");
log_it_info(" Server: %s:%d", vpn_server_host, vpn_server_port);
log_it_info(" Network: %s", net->pub.name);
// Step 3: Check VPN server availability
log_it_info("--- Server Connectivity Check ---");
int check_result = dap_chain_net_vpn_client_check(
net,
vpn_server_host,
vpn_server_port,
1024, // Send 1KB test data
1024, // Receive 1KB test data
10000 // 10 second timeout
);
switch (check_result) {
case 0:
log_it_info("✓ VPN server connectivity check passed");
break;
case -1:
log_it_error("✗ Invalid parameters for server check");
return;
case -2:
log_it_error("✗ Failed to connect to VPN server");
return;
case -3:
log_it_error("✗ VPN server check timeout");
return;
default:
log_it_error("✗ Server check failed with code: %d", check_result);
return;
}
// Step 4: Check current VPN client status
dap_chain_net_vpn_client_status_t current_status = dap_chain_net_vpn_client_status();
log_it_info("Current VPN client status:");
switch (current_status) {
case VPN_CLIENT_STATUS_NOT_STARTED:
log_it_info(" Status: Not Started");
break;
case VPN_CLIENT_STATUS_STARTED:
log_it_info(" Status: Started and Connected");
log_it_info(" Action: Stopping existing connection first");
dap_chain_net_vpn_client_stop();
break;
case VPN_CLIENT_STATUS_STOPPED:
log_it_info(" Status: Stopped");
break;
case VPN_CLIENT_STATUS_CONN_LOST:
log_it_info(" Status: Connection Lost");
log_it_info(" Action: Cleaning up previous connection");
dap_chain_net_vpn_client_stop();
break;
}
// Step 5: Start VPN connection
log_it_info("--- Starting VPN Connection ---");
int start_result = dap_chain_net_vpn_client_start(net, vpn_server_host, vpn_server_port);
switch (start_result) {
case 0:
log_it_info("✓ VPN client started successfully");
break;
case 1:
log_it_info("VPN client already started");
break;
case -1:
log_it_error("✗ Invalid connection parameters");
return;
case -2:
log_it_error("✗ Failed to connect to VPN server");
return;
case -3:
log_it_error("✗ No response from VPN server");
return;
default:
log_it_error("✗ VPN connection failed: %d", start_result);
return;
}
// Step 6: Verify connection establishment
dap_stream_ch_t *vpn_channel = dap_chain_net_vpn_client_get_stream_ch();
dap_stream_worker_t *vpn_worker = dap_chain_net_vpn_client_get_stream_worker();
if (vpn_channel && vpn_worker) {
log_it_info("✓ VPN connection established");
log_it_info(" Stream channel: Active");
log_it_info(" Worker thread: Assigned");
log_it_info(" Ready for data transmission");
} else {
log_it_error("✗ VPN connection incomplete");
log_it_error(" Channel: %s", vpn_channel ? "OK" : "Missing");
log_it_error(" Worker: %s", vpn_worker ? "OK" : "Missing");
}
// Step 7: Monitor connection status
current_status = dap_chain_net_vpn_client_status();
switch (current_status) {
case VPN_CLIENT_STATUS_STARTED:
log_it_info("✓ VPN client is active and connected");
break;
case VPN_CLIENT_STATUS_CONN_LOST:
log_it_error("✗ VPN connection lost");
break;
default:
log_it_warning("VPN client status: %d", current_status);
break;
}
log_it_info("VPN client connection example completed");
log_it_info("Note: Call dap_chain_net_vpn_client_stop() to disconnect");
}
```
### VPN TUN Interface Management Example
```c
#include <dap_chain_net_vpn_client_tun.h>
void vpn_tun_interface_example() {
log_it_info("=== VPN TUN Interface Management ===");
// Step 1: Setup IP configuration
const char *client_ip = "10.0.1.100";
const char *gateway_ip = "10.0.1.1";
log_it_info("TUN Interface Configuration:");
log_it_info(" Client IP: %s", client_ip);
log_it_info(" Gateway IP: %s", gateway_ip);
// Step 2: Initialize TUN interface
log_it_info("--- TUN Interface Initialization ---");
int init_result = dap_chain_net_vpn_client_tun_init(gateway_ip);
if (init_result == 0) {
log_it_info("✓ TUN interface initialized successfully");
} else {
log_it_error("✗ TUN interface initialization failed: %d", init_result);
return;
}
// Step 3: Create TUN interface
log_it_info("--- TUN Interface Creation ---");
int create_result = dap_chain_net_vpn_client_tun_create(client_ip, gateway_ip);
if (create_result == 0) {
log_it_info("✓ TUN interface created successfully");
log_it_info(" Interface: tun0 (or equivalent)");
log_it_info(" IP Address: %s", client_ip);
log_it_info(" Gateway: %s", gateway_ip);
log_it_info(" Status: Ready for packet routing");
} else {
log_it_error("✗ TUN interface creation failed: %d", create_result);
return;
}
// Step 4: Get TUN event socket
dap_events_socket_t *tun_socket = dap_chain_net_vpn_client_tun_get_esock();
if (tun_socket) {
log_it_info("✓ TUN event socket obtained");
log_it_info(" Socket: Available for packet processing");
log_it_info(" Event handling: Enabled");
} else {
log_it_warning("TUN event socket not available");
}
// Step 5: Check TUN interface status
int status = dap_chain_net_vpn_client_tun_status();
log_it_info("TUN Interface Status:");
switch (status) {
case 0:
log_it_info(" Status: Interface active and operational");
break;
case 1:
log_it_info(" Status: Interface created but not active");
break;
default:
log_it_info(" Status: Unknown or error (%d)", status);
break;
}
// Step 6: Simulate interface usage period
log_it_info("--- Interface Usage Simulation ---");
log_it_info("TUN interface capabilities:");
log_it_info(" • Packet capture from application layer");
log_it_info(" • Packet injection to network stack");
log_it_info(" • IP routing and forwarding");
log_it_info(" • Network isolation and security");
log_it_info(" • Traffic monitoring and statistics");
// Step 7: Cleanup TUN interface
log_it_info("--- TUN Interface Cleanup ---");
int delete_result = dap_chain_net_vpn_client_tun_delete();
if (delete_result == 0) {
log_it_info("✓ TUN interface deleted successfully");
log_it_info(" Interface: Removed from system");
log_it_info(" Resources: Cleaned up");
log_it_info(" Network routes: Restored");
} else {
log_it_error("✗ TUN interface deletion failed: %d", delete_result);
log_it_warning("Manual cleanup may be required");
}
log_it_info("VPN TUN interface management example completed");
}
```
---
*See also: [[Modules/Module Service|Module Service]], [[Modules/Module Chain Network|Module Chain Network]], [[ETC/Services Overview|Services Overview]]*