Refresh both AGENTS guides and clarify module purpose, usage, ownership, threading, return values and wire formats in headers. Remove the unused timeout_heap freed_count field and unimplemented getter.
159 lines
5.7 KiB
C
159 lines
5.7 KiB
C
/* Кроссплатформенный TUN: init создаёт интерфейс и очереди, close освобождает их.
|
|
* output_queue несёт TUN → ядро, input_queue — ядро → TUN; формат очереди: префикс(1) + IP-пакет.
|
|
* tun_write принимает тот же префикс и пропускает его при записи; tun_inject_packet принимает чистый IP.
|
|
* Основной API — в uasync; Windows read-thread передаёт пакеты через tun_packet_handler.
|
|
* test_mode использует очереди вместо устройства ОС. */
|
|
#ifndef TUN_IF_H
|
|
#define TUN_IF_H
|
|
|
|
#include <stdint.h>
|
|
#include <stddef.h>
|
|
#include <sys/types.h>
|
|
|
|
#ifdef _WIN32
|
|
#include <windows.h> // для HANDLE и CRITICAL_SECTION
|
|
#endif
|
|
|
|
// Forward declarations
|
|
struct UASYNC;
|
|
struct utun_config;
|
|
struct ll_queue;
|
|
struct ll_entry;
|
|
struct memory_pool;
|
|
//struct ETCP_FRAGMENT; // используется внутри, определён в etcp.h
|
|
|
|
// Структура для передачи данных из TUN потока в main thread
|
|
struct tun_packet_data {
|
|
struct tun_if* tun;
|
|
struct ll_entry* entry;
|
|
};
|
|
|
|
#ifdef __cplusplus
|
|
extern "C" {
|
|
#endif
|
|
|
|
#define TUN_MTU_DEFAULT 1500
|
|
#define TUN_MAX_PACKET_SIZE 1500
|
|
|
|
// ===================================================================
|
|
// TUN interface handle
|
|
// ===================================================================
|
|
struct tun_if {
|
|
char ifname[16]; // "utun", "tun0", "tun_test" и т.д.
|
|
|
|
int fd; // Linux: fd /dev/net/tun, Windows: -1
|
|
void* platform_handle; // Windows: WINTUN_SESSION_HANDLE
|
|
void* adapter_handle; // Windows: WINTUN_ADAPTER_HANDLE
|
|
|
|
struct UASYNC* ua;
|
|
void* socket_id; // uasync socket_id (NULL на Windows)
|
|
|
|
struct memory_pool* pool; // пул для ll_entry
|
|
struct ll_queue* output_queue; // TUN → routing (пакеты из интерфейса)
|
|
struct ll_queue* input_queue; // routing → TUN (пакеты в интерфейс)
|
|
|
|
int test_mode; // 1 = тестовый режим (без реального TUN)
|
|
int test_fd; // в тестовом режиме: вторая сторона socket pair для тестов, -1 иначе
|
|
|
|
// Статистика
|
|
uint64_t bytes_read;
|
|
uint64_t bytes_written;
|
|
uint32_t packets_read;
|
|
uint32_t packets_written;
|
|
uint32_t read_errors;
|
|
uint32_t write_errors;
|
|
|
|
uint32_t ifindex; // интерфейсный индекс
|
|
|
|
#ifdef _WIN32
|
|
HANDLE read_thread;
|
|
HANDLE stop_event;
|
|
volatile int running; // 1 = поток работает
|
|
#endif
|
|
};
|
|
|
|
/**
|
|
* @brief Инициализация TUN интерфейса
|
|
* @param ua экземпляр uasync
|
|
* @param config конфигурация (IP, MTU, test_mode и т.д.)
|
|
* @return указатель на tun_if или NULL при ошибке
|
|
*/
|
|
struct tun_if* tun_init(struct UASYNC* ua, struct utun_config* config);
|
|
|
|
/**
|
|
* @brief Инициализация TUN интерфейса с явными параметрами (для NAT TUN)
|
|
* @param ua экземпляр uasync
|
|
* @param ifname имя интерфейса
|
|
* @param ip_addr IP-адрес (строка, например "10.0.1.1")
|
|
* @param mtu MTU интерфейса
|
|
* @param test_mode тестовый режим
|
|
* @return указатель на tun_if или NULL при ошибке
|
|
*/
|
|
struct tun_if* tun_init_nat(struct UASYNC* ua, const char* ifname, const char* ip_addr, int mtu, int test_mode);
|
|
|
|
/**
|
|
* @brief Закрытие и освобождение всех ресурсов
|
|
*/
|
|
void tun_close(struct tun_if* tun);
|
|
|
|
/**
|
|
* @brief Записать пакет в TUN (из routing)
|
|
*/
|
|
ssize_t tun_write(struct tun_if* tun, const uint8_t* buf, size_t len);
|
|
|
|
/**
|
|
* @brief Получить очередь input (routing → TUN)
|
|
*/
|
|
struct ll_queue* tun_get_input_queue(struct tun_if* tun);
|
|
|
|
/**
|
|
* @brief Получить очередь output (TUN → routing)
|
|
*/
|
|
struct ll_queue* tun_get_output_queue(struct tun_if* tun);
|
|
|
|
/**
|
|
* @brief Проверка режима
|
|
*/
|
|
int tun_is_test_mode(struct tun_if* tun);
|
|
|
|
/**
|
|
* @brief Получить test_fd (вторая сторона socket pair) для тестов
|
|
* @return fd или -1 если не тестовый режим
|
|
*/
|
|
int tun_get_test_fd(struct tun_if* tun);
|
|
|
|
/**
|
|
* @brief Инъекция пакета в output_queue (для тестов и Windows-уведомлений)
|
|
*/
|
|
int tun_inject_packet(struct tun_if* tun, const uint8_t* buf, size_t len);
|
|
|
|
/**
|
|
* @brief Прочитать пакет из input_queue (тестовый helper)
|
|
*/
|
|
ssize_t tun_read_packet(struct tun_if* tun, uint8_t* buf, size_t len);
|
|
|
|
/**
|
|
* @brief Callback для обработки пакетов из TUN в main thread (через uasync_post)
|
|
*/
|
|
void tun_packet_handler(void* arg);
|
|
|
|
// ===================================================================
|
|
// Platform-specific internal functions
|
|
// (реализованы в tun_linux.c / tun_windows.c)
|
|
// ===================================================================
|
|
int tun_platform_init(struct tun_if* tun, const char* ifname, const char* ip_str, int mtu);
|
|
void tun_platform_cleanup(struct tun_if* tun);
|
|
ssize_t tun_platform_read(struct tun_if* tun, uint8_t* buf, size_t len);
|
|
ssize_t tun_platform_write(struct tun_if* tun, const uint8_t* buf, size_t len);
|
|
int tun_platform_get_poll_fd(struct tun_if* tun);
|
|
|
|
#ifdef _WIN32
|
|
DWORD WINAPI tun_read_thread_proc(LPVOID arg);
|
|
#endif
|
|
|
|
#ifdef __cplusplus
|
|
}
|
|
#endif
|
|
|
|
#endif /* TUN_IF_H */
|