Files
utun2/src/route_lib.c
T
2026-03-10 00:06:46 +03:00

589 lines
22 KiB
C

/**
* @file route_lib.c
* @brief Enhanced routing system with bandwidth support and route types
*/
#include "route_lib.h"
#include "etcp_connections.h"
#include "../lib/u_async.h"
#include "../lib/debug_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../lib/platform_compat.h"
#include <time.h>
#include "../lib/mem.h"
#define INITIAL_ROUTE_CAPACITY 100
#define ROUTE_EXPANSION_FACTOR 2
#define MAX_SUBNET_VALIDATION_RANGES 50
#define ROUTE_CACHE_SIZE 10
// Forward declarations
static const char* route_type_to_string(route_type_t type);
/**
* @brief Структура кеша маршрутов (LRU)
*/
struct ROUTE_CACHE {
struct ROUTE_ARRAY *entries[ROUTE_CACHE_SIZE]; /**< Массив кешированных результатов */
uint32_t keys[ROUTE_CACHE_SIZE]; /**< IP-адреса (ключи) */
uint64_t access_time[ROUTE_CACHE_SIZE]; /**< Время последнего доступа */
int count; /**< Текущее количество записей */
};
static struct ROUTE_CACHE g_route_cache = {0};
/**
* @brief Преобразует IP-адрес в строку
* @param ip IP-адрес (в host byte order)
* @param buffer Буфер для строки (минимум 16 байт)
* @return Указатель на buffer или NULL
*/
static char *ip_to_string(uint32_t ip, char *buffer) {
if (!buffer) return NULL;
struct in_addr addr;
addr.s_addr = htonl(ip);
strncpy(buffer, inet_ntoa(addr), 15);
buffer[15] = '\0';
return buffer;
}
/**
* @brief Парсит строку подсети в сетевой адрес и длину префикса
* @param subnet_str Строка подсети (например, "192.168.1.0/24")
* @param network Указатель для сохранения сетевого адреса
* @param prefix_length Указатель для сохранения длины префикса
* @return 0 при успехе, -1 при ошибке
*/
int parse_subnet(const char *subnet_str, uint32_t *network, uint8_t *prefix_length) {
if (!subnet_str || !network || !prefix_length) return -1;
char ip[64];
int prefix;
if (sscanf(subnet_str, "%[^/]/%d", ip, &prefix) != 2) return -1;
if (prefix < 0 || prefix > 32) return -1;
struct in_addr addr;
if (inet_pton(AF_INET, ip, &addr) != 1) return -1;
*network = ntohl(addr.s_addr);
*prefix_length = (uint8_t)prefix;
return 0;
}
/**
* @brief Создает массив маршрутов
* @param capacity Максимальное количество маршрутов
* @return Указатель на созданный массив или NULL
*/
static struct ROUTE_ARRAY* route_array_create(uint32_t capacity) {
struct ROUTE_ARRAY *array = u_calloc(1, sizeof(struct ROUTE_ARRAY) +
capacity * sizeof(struct ROUTE_ENTRY*));
if (!array) {
DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "route_array_create: failed to allocate memory");
return NULL;
}
array->capacity = capacity;
array->routes = 0;
array->ip = 0;
return array;
}
/**
* @brief Освобождает память массива маршрутов
* @param array Указатель на массив
*/
static void route_array_destroy(struct ROUTE_ARRAY *array) {
if (!array) return;
// entries[] содержит только указатели на ROUTE_ENTRY из таблицы,
// их освобождать не нужно - они принадлежат таблице
u_free(array);
}
/**
* @brief Добавляет маршрут в массив
* @param array Массив маршрутов
* @param entry Указатель на запись маршрута
* @return true при успехе, false если массив полон
*/
static bool route_array_add(struct ROUTE_ARRAY *array, struct ROUTE_ENTRY *entry) {
if (!array || !entry) return false;
if (array->routes >= array->capacity) return false;
array->entries[array->routes++] = entry;
return true;
}
/**
* @brief Пересчитывает метрику quality на основе других метрик
* @param entry Указатель на запись маршрута
* @return true при успехе, false при ошибке
*/
bool route_update_quality(struct ROUTE_ENTRY *entry) {
if (!entry) return false;
// Простая формула: latency * 2 + loss * 10 + hops * 50
// Меньше значение = лучше маршрут
// Используем latency из PEER_INFO (x0.1 ms) -> конвертируем в ms
uint16_t latency_ms = entry->peer_info.latency / 10;
entry->metrics.metric = latency_ms * 2 +
entry->metrics.packet_loss_rate * 10 +
entry->peer_info.hop_count * 50;
return true;
}
/**
* @brief Сравнивает два маршрута для сортировки (лучший маршрут - меньшее значение)
*/
static int compare_routes_by_quality(const void *a, const void *b) {
const struct ROUTE_ENTRY *route_a = *(const struct ROUTE_ENTRY **)a;
const struct ROUTE_ENTRY *route_b = *(const struct ROUTE_ENTRY **)b;
// Сначала сравниваем по quality (меньше - лучше)
if (route_a->metrics.metric != route_b->metrics.metric) {
return (int)(route_a->metrics.metric - route_b->metrics.metric);
}
// Затем по длине префикса (больше - лучше)
if (route_b->peer_info.prefix_length != route_a->peer_info.prefix_length) {
return route_b->peer_info.prefix_length - route_a->peer_info.prefix_length;
}
return 0;
}
/**
* @brief Ищет запись в кеше по IP
*/
static struct ROUTE_ARRAY* route_cache_find(uint32_t ip) {
for (int i = 0; i < g_route_cache.count; i++) {
if (g_route_cache.keys[i] == ip) {
// Update access time
g_route_cache.access_time[i] = get_time_tb();
return g_route_cache.entries[i];
}
}
return NULL;
}
/**
* @brief Добавляет или обновляет запись в кеше
*/
static void route_cache_add(uint32_t ip, struct ROUTE_ARRAY* array) {
if (g_route_cache.count < ROUTE_CACHE_SIZE) {
int idx = g_route_cache.count++;
g_route_cache.keys[idx] = ip;
g_route_cache.entries[idx] = array;
g_route_cache.access_time[idx] = get_time_tb();
} else {
// Find least recently used
int lru_idx = 0;
uint64_t min_time = g_route_cache.access_time[0];
for (int i = 1; i < ROUTE_CACHE_SIZE; i++) {
if (g_route_cache.access_time[i] < min_time) {
min_time = g_route_cache.access_time[i];
lru_idx = i;
}
}
// Replace LRU
route_array_destroy(g_route_cache.entries[lru_idx]);
g_route_cache.keys[lru_idx] = ip;
g_route_cache.entries[lru_idx] = array;
g_route_cache.access_time[lru_idx] = get_time_tb();
}
}
/**
* @brief Очищает глобальный кеш маршрутов
*/
void route_cache_clear(void) {
for (int i = 0; i < g_route_cache.count; i++) {
route_array_destroy(g_route_cache.entries[i]);
g_route_cache.entries[i] = NULL;
}
g_route_cache.count = 0;
}
/**
* @brief Создает новую таблицу маршрутизации
* @return Указатель на созданную таблицу или NULL в случае ошибки
*/
struct ROUTE_TABLE *route_table_create(void) {
struct ROUTE_TABLE *table = u_calloc(1, sizeof(struct ROUTE_TABLE));
if (!table) {
DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "route_table_create: failed to allocate table");
return NULL;
}
table->entries = u_calloc(INITIAL_ROUTE_CAPACITY, sizeof(struct ROUTE_ENTRY));
if (!table->entries) {
u_free(table);
DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "route_table_create: failed to allocate entries");
return NULL;
}
table->capacity = INITIAL_ROUTE_CAPACITY;
table->count = 0;
table->dynamic_subnets = NULL;
table->dynamic_subnet_count = 0;
table->local_subnets = NULL;
table->local_subnet_count = 0;
memset(&table->stats, 0, sizeof(table->stats));
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, "Routing table created with capacity %u", INITIAL_ROUTE_CAPACITY);
return table;
}
/**
* @brief Уничтожает таблицу маршрутизации и освобождает ресурсы
* @param table Указатель на таблицу маршрутизации
*/
void route_table_destroy(struct ROUTE_TABLE *table) {
if (!table) return;
// Free entries
u_free(table->entries);
// Free validation ranges
if (table->dynamic_subnets) u_free(table->dynamic_subnets);
if (table->local_subnets) u_free(table->local_subnets);
u_free(table);
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, "Routing table destroyed");
}
/**
* @brief Вставляет новую запись в таблицу маршрутизации
* @param table Указатель на таблицу маршрутизации
* @param entry Указатель на вставляемую запись маршрута
* @return true если вставка успешна, false иначе
*/
bool route_table_insert(struct ROUTE_TABLE *table, const struct ROUTE_ENTRY *entry) {
if (!table || !entry) return false;
// Check capacity and expand if needed
if (table->count >= table->capacity) {
uint32_t new_capacity = table->capacity * ROUTE_EXPANSION_FACTOR;
struct ROUTE_ENTRY *new_entries = u_realloc(table->entries, new_capacity * sizeof(struct ROUTE_ENTRY));
if (!new_entries) {
DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "route_table_insert: failed to realloc entries");
return false;
}
table->entries = new_entries;
table->capacity = new_capacity;
}
// Copy entry
table->entries[table->count] = *entry;
// Update timestamps
uint64_t now = get_time_tb();
table->entries[table->count].created_time = now;
table->entries[table->count].last_update = now;
table->entries[table->count].metrics.last_updated = now;
// Update quality
route_update_quality(&table->entries[table->count]);
// Update stats
if (entry->type == ROUTE_TYPE_LOCAL) table->stats.local_routes++;
else if (entry->type == ROUTE_TYPE_LEARNED) table->stats.learned_routes++;
table->count++;
// Invalidate cache if needed
route_cache_clear(); // Simple invalidation, can be optimized
// Call change callback if set
if (table->change_callback) {
table->change_callback(table, &table->entries[table->count - 1], 0 /* insert */, table->change_callback_arg);
}
char ip_str[16];
ip_to_string(entry->peer_info.network, ip_str);
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, "Inserted route: %s/%d (type: %d)", ip_str, entry->peer_info.prefix_length, entry->type);
return true;
}
/**
* @brief Удаляет запись из таблицы маршрутизации
* @param table Указатель на таблицу маршрутизации
* @param conn соединение все роуты которого надо удалить
*/
void route_table_delete(struct ROUTE_TABLE *table, struct ETCP_CONN* conn) {
if (!table || !conn) return;
size_t i = 0;
while (i < table->count) {
if (table->entries[i].next_hop == conn) {
// Call change callback before removal
if (table->change_callback) {
table->change_callback(table, &table->entries[i], 2 /* delete */, table->change_callback_arg);
}
// Update stats
if (table->entries[i].type == ROUTE_TYPE_LOCAL) table->stats.local_routes--;
else if (table->entries[i].type == ROUTE_TYPE_LEARNED) table->stats.learned_routes--;
// Shift remaining entries
if (i < table->count - 1) {
memmove(&table->entries[i], &table->entries[i + 1], (table->count - i - 1) * sizeof(struct ROUTE_ENTRY));
}
table->count--;
} else {
i++;
}
}
// Invalidate cache
route_cache_clear();
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, "Deleted routes for connection %p", (void*)conn);
}
/**
* @brief Удаляет конкретный маршрут из таблицы
* @param table Указатель на таблицу маршрутизации
* @param network Сетевой адрес
* @param prefix_length Длина префикса подсети
* @param next_hop Указатель на соединение (NULL = любой next_hop)
* @return true если маршрут найден и удален, false если не найден
*/
bool route_table_delete_entry(struct ROUTE_TABLE *table, uint32_t network,
uint8_t prefix_length, struct ETCP_CONN* next_hop) {
if (!table) return false;
for (size_t i = 0; i < table->count; i++) {
if (table->entries[i].peer_info.network == network &&
table->entries[i].peer_info.prefix_length == prefix_length &&
(next_hop == NULL || table->entries[i].next_hop == next_hop)) {
// Call change callback
if (table->change_callback) {
table->change_callback(table, &table->entries[i], 2 /* delete */, table->change_callback_arg);
}
// Update stats
if (table->entries[i].type == ROUTE_TYPE_LOCAL) table->stats.local_routes--;
else if (table->entries[i].type == ROUTE_TYPE_LEARNED) table->stats.learned_routes--;
// Shift remaining
if (i < table->count - 1) {
memmove(&table->entries[i], &table->entries[i + 1], (table->count - i - 1) * sizeof(struct ROUTE_ENTRY));
}
table->count--;
// Invalidate cache
route_cache_clear();
char ip_str[16];
ip_to_string(network, ip_str);
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, "Deleted specific route: %s/%d", ip_str, prefix_length);
return true;
}
}
return false;
}
/**
* @brief Выполняет поиск доступных маршрутов для заданного IP-адреса, отсортированных по quality
* при поиске ищет готовый результат в кеше или добавляет в кеш новый результат и возвращает запись из кеша
* @param table Указатель на таблицу маршрутизации
* @param dest_ip Целевой IP-адрес
* @return структура с найденными маршрутами
*/
struct ROUTE_ARRAY* route_table_lookup(struct ROUTE_TABLE *table, uint32_t dest_ip) {
if (!table) return NULL;
table->stats.routes_lookup_hits++;
// Check cache first
struct ROUTE_ARRAY* cached = route_cache_find(dest_ip);
if (cached) {
return cached;
}
table->stats.routes_lookup_misses++;
// Create new array (initial capacity = table->count for worst case)
struct ROUTE_ARRAY* result = route_array_create(table->count);
if (!result) return NULL;
result->ip = dest_ip;
// Find matching routes
for (size_t i = 0; i < table->count; i++) {
struct ROUTE_ENTRY* entry = &table->entries[i];
// Calculate netmask
uint32_t netmask = (uint32_t)(~0) << (32 - entry->peer_info.prefix_length);
uint32_t entry_net = entry->peer_info.network & netmask;
uint32_t dest_net = dest_ip & netmask;
if (entry_net == dest_net && (entry->flags & ROUTE_FLAG_ACTIVE)) {
route_array_add(result, entry);
}
}
if (result->routes == 0) {
route_array_destroy(result);
return NULL;
}
// Sort by quality
qsort(result->entries, result->routes, sizeof(struct ROUTE_ENTRY*), compare_routes_by_quality);
// Add to cache
route_cache_add(dest_ip, result);
char ip_str[16];
ip_to_string(dest_ip, ip_str);
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, "Found %u routes for %s (best quality: %u)",
result->routes, ip_str, result->entries[0]->metrics.metric);
return result;
}
/**
* @brief Добавляет диапазон подсетей для валидации (enhanced version)
* @param table таблица
* @param network сеть
* @param prefix_length префикс
* @param ranges указатель на массив (uint32_t[even]: network, odd: prefix)
* @param count указатель на счётчик (pairs * 2)
* @return true при успехе
*/
static bool enhanced_route_add_subnet_range(struct ROUTE_TABLE *table, uint32_t network,
uint8_t prefix_length, uint32_t **ranges, size_t *count) {
if (!table || !ranges || !count) return false;
if (*count >= MAX_SUBNET_VALIDATION_RANGES - 2) return false;
// Expand array if needed
if (*ranges == NULL) {
*ranges = u_calloc(MAX_SUBNET_VALIDATION_RANGES, sizeof(uint32_t));
if (!*ranges) return false;
*count = 0;
}
// Add network and prefix length as a pair
(*ranges)[*count] = network;
(*ranges)[*count + 1] = prefix_length;
*count += 2;
char ip_str[16];
ip_to_string(network, ip_str);
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, "Added subnet validation range: %s/%d", ip_str, prefix_length);
return true;
}
bool route_add_dynamic_subnet(struct ROUTE_TABLE *table, uint32_t network, uint8_t prefix_length) {
return enhanced_route_add_subnet_range(table, network, prefix_length,
&table->dynamic_subnets, &table->dynamic_subnet_count);
}
bool route_add_local_subnet(struct ROUTE_TABLE *table, uint32_t network, uint8_t prefix_length) {
return enhanced_route_add_subnet_range(table, network, prefix_length,
&table->local_subnets, &table->local_subnet_count);
}
bool route_get_all_routes(const struct ROUTE_TABLE *table, uint32_t network, uint8_t prefix_length,
struct ROUTE_ENTRY **routes, size_t *count) {
if (!table || !routes || !count) return false;
*routes = NULL;
*count = 0;
// Count matching routes
for (size_t i = 0; i < table->count; i++) {
if (table->entries[i].peer_info.network == network && table->entries[i].peer_info.prefix_length == prefix_length) {
(*count)++;
}
}
if (*count == 0) return true; // No routes found, but not an error
// Allocate result array
*routes = u_calloc(*count, sizeof(struct ROUTE_ENTRY));
if (!*routes) {
*count = 0;
return false;
}
// Copy matching routes
size_t result_index = 0;
for (size_t i = 0; i < table->count; i++) {
if (table->entries[i].peer_info.network == network && table->entries[i].peer_info.prefix_length == prefix_length) {
(*routes)[result_index] = table->entries[i];
result_index++;
}
}
return true;
}
/**
* @brief Печатает содержимое таблицы маршрутизации
* @param table Указатель на таблицу маршрутизации
*/
void route_table_print(const struct ROUTE_TABLE *table) {
if (!table) return;
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, "=== Routing Table ===");
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, "Total routes: %zu", table->count);
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, "Dynamic subnets: %zu, Local subnets: %zu",
table->dynamic_subnet_count / 2, table->local_subnet_count / 2);
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, "Local routes: %lu, Learned routes: %lu",
table->stats.local_routes, table->stats.learned_routes);
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, "Cache hits: %lu, Misses: %lu",
table->stats.routes_lookup_hits - table->stats.routes_lookup_misses,
table->stats.routes_lookup_misses);
if (table->count > 0) {
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, "Routes:");
for (size_t i = 0; i < table->count; i++) {
const struct ROUTE_ENTRY *entry = &table->entries[i];
char network_str[16];
ip_to_string(entry->peer_info.network, network_str);
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, " %zu: %s/%d -> %p [%s] (quality: %u)",
i + 1, network_str, entry->peer_info.prefix_length,
(void*)entry->next_hop,
route_type_to_string(entry->type),
entry->metrics.metric);
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, " Bandwidth: %uK, Loss: %.2f%%, Latency: %ums, Hops: %d",
entry->metrics.bandwidth_kbps,
entry->metrics.packet_loss_rate / 100.0,
entry->metrics.latency_ms,
entry->peer_info.hop_count);
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, " Flags: %s%s%s%s",
(entry->flags & ROUTE_FLAG_ACTIVE) ? "ACTIVE " : "",
(entry->flags & ROUTE_FLAG_VALIDATED) ? "VALIDATED " : "",
(entry->flags & ROUTE_FLAG_ADVERTISED) ? "ADVERTISED " : "",
(entry->flags & ROUTE_FLAG_LEARNED) ? "LEARNED" : "");
}
} else {
DEBUG_INFO(DEBUG_CATEGORY_ROUTING, "No routes configured.");
}
}
/**
* @brief Преобразует тип маршрута в строку
* @param type Тип маршрута
* @return Строка с названием типа
*/
static const char* route_type_to_string(route_type_t type) {
switch (type) {
case ROUTE_TYPE_STATIC: return "STATIC";
case ROUTE_TYPE_DYNAMIC: return "DYNAMIC";
case ROUTE_TYPE_LOCAL: return "LOCAL";
case ROUTE_TYPE_LEARNED: return "LEARNED";
default: return "UNKNOWN";
}
}