diff --git a/AGENTS.md b/AGENTS.md index 4d499e2f5..eca2c6a78 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -204,6 +204,7 @@ Crypto: Fixed CCM nonce size to 13 bytes, all crypto tests passing "cp" or "кп" in prompt = do commit and push Важные дополнения: +- Самое важное: при поиске ошибок делай перед правками комит/backup. Всё лишнее что менял при отладке - строго вернуть назад в состояние до моего вмешательства. В итоге в код должно попасть только проверенное исправление и ничего лилшнего! - если в процессе исправлений-доработок возникла нестыковка которая требует сеньезных доработок, остановить и подробно расскажи об этом. - sed для редактирования исходников - запрещено пользоваться! - Проверяй на дублирование кода - не сделано ли это уже в другом месте. @@ -212,6 +213,13 @@ Crypto: Fixed CCM nonce size to 13 bytes, all crypto tests passing - нельзя ничего восстанавливать из репозитория не прашивая - Когда пишешь код всегда загружай в контекст и мысленно разберись как работают все функции/струтуры, назначение переменных которые используешь. - Для отладки не printf а DEBUG_* +- перед сборкой всегда make clean + +Действия при поиске бага: +1. создать комит или бэкап всего что меняешь +2. когда причина бага найдена и устранена - верни всё остальное что менял в исходное состояние +3. проверь что тесты проходят и всё работает. make clean перед сбркоя обязательно. +4. если баг не устранён - продолжай поиск или если время заканчивается - верни всё в исходное состояние тех задания для реализации в каталоге /doc. /doc/etcp_protocol.txt - основной протокол (похож на TCP+QUIC, поддеиживает шифрования, load balancing multi-link, работу а неустойчивых каналах, утилизацию полосы и недопущение перегрузки каналов связи) diff --git a/clean_newlines.py b/clean_newlines.py new file mode 100644 index 000000000..5d4093109 --- /dev/null +++ b/clean_newlines.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +""" +Remove trailing \\n from format strings in DEBUG_ macros. +""" + +import os +import re +import sys + +def clean_file(filepath): + with open(filepath, 'r') as f: + content = f.read() + + original = content + + # Pattern to match DEBUG_(ERROR|WARN|INFO|DEBUG|TRACE)\([^)]*\"([^"]*)\\n\"[^)]*\) + # We'll process line by line + lines = content.split('\n') + new_lines = [] + for line in lines: + # Look for DEBUG_ macros with \n in format string + # Simple replacement for \"...\\n\" -> \"...\" + line = re.sub(r'(DEBUG_(ERROR|WARN|INFO|DEBUG|TRACE)\([^,]+,\s*")([^"]*)\\n(")', r'\1\3\4', line) + # Also remove emojis ❌✅ℹ️ + line = line.replace('❌', '').replace('✅', '').replace('ℹ️', '').strip() + new_lines.append(line) + + content = '\n'.join(new_lines) + + if content != original: + with open(filepath, 'w') as f: + f.write(content) + print(f"Cleaned {filepath}") + +def main(): + test_dir = 'tests' + for root, dirs, files in os.walk(test_dir): + for file in files: + if file.endswith('.c'): + filepath = os.path.join(root, file) + clean_file(filepath) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/debug_performance.c b/debug_performance.c new file mode 100644 index 000000000..8c6c70018 --- /dev/null +++ b/debug_performance.c @@ -0,0 +1,47 @@ +#include "../lib/u_async.h" +#include +#include +#include +#include +#include + +static void test_callback(int fd, void* arg) { + (void)fd; (void)arg; +} + +int main() { + uasync_t* ua = uasync_create(); + if (!ua) return 1; + + printf("=== Debug Performance Test ===\n"); + + // Test 1: Normal add/remove + int sock1 = socket(AF_INET, SOCK_DGRAM, 0); + void* id1 = uasync_add_socket(ua, sock1, test_callback, NULL, NULL, NULL); + printf("Added socket %d: id=%p\n", sock1, id1); + + size_t alloc1, free1, alloc2, free2; + uasync_get_stats(ua, &alloc1, &free1, &alloc2, &free2); + printf("After add: timers %zu/%zu, sockets %zu/%zu\n", alloc1, free1, alloc2, free2); + + uasync_remove_socket(ua, id1); + printf("Removed socket %d\n", sock1); + + uasync_get_stats(ua, &alloc1, &free1, &alloc2, &free2); + printf("After remove: timers %zu/%zu, sockets %zu/%zu\n", alloc1, free1, alloc2, free2); + + close(sock1); + + // Test 2: Failed add + int sock2 = 9999; // Invalid socket + void* id2 = uasync_add_socket(ua, sock2, test_callback, NULL, NULL, NULL); + printf("Tried to add invalid socket %d: id=%p\n", sock2, id2); + + uasync_get_stats(ua, &alloc1, &free1, &alloc2, &free2); + printf("After failed add: timers %zu/%zu, sockets %zu/%zu\n", alloc1, free1, alloc2, free2); + + uasync_destroy(ua, 0); + printf("Destroyed uasync\n"); + + return 0; +} diff --git a/lib/debug_config.c b/lib/debug_config.c index c24c39c3e..df9154575 100644 --- a/lib/debug_config.c +++ b/lib/debug_config.c @@ -1,435 +1,275 @@ -/** - * Debug configuration implementation - * Runtime debug configuration system for flexible debug output control - */ - -#include "debug_config.h" -#include -#include -#include -#include -#include -#include -#include -#include - -/* Rate limiting */ -static size_t output_count = 0; -static time_t last_output_time = 0; - -/* ANSI color codes */ -static const char* color_red = "\033[31m"; -static const char* color_yellow = "\033[33m"; -static const char* color_green = "\033[32m"; -static const char* color_blue = "\033[34m"; -static const char* color_magenta = "\033[35m"; -static const char* color_cyan = "\033[36m"; -static const char* color_reset = "\033[0m"; - -/* Get category by name */ -static debug_category_t get_category_by_name(const char* name) { - struct { - const char* n; - debug_category_t c; - } map[] = { - {"none", DEBUG_CATEGORY_NONE}, - {"uasync", DEBUG_CATEGORY_UASYNC}, - {"ll_queue", DEBUG_CATEGORY_LL_QUEUE}, - {"connection", DEBUG_CATEGORY_CONNECTION}, - {"etcp", DEBUG_CATEGORY_ETCP}, - {"crypto", DEBUG_CATEGORY_CRYPTO}, - {"memory", DEBUG_CATEGORY_MEMORY}, - {"timing", DEBUG_CATEGORY_TIMING}, - {"config", DEBUG_CATEGORY_CONFIG}, - {"tun", DEBUG_CATEGORY_TUN}, - {"routing", DEBUG_CATEGORY_ROUTING}, - {"timers", DEBUG_CATEGORY_TIMERS}, - {"all", DEBUG_CATEGORY_ALL}, - {NULL, 0} - }; - - for (int i = 0; map[i].n; i++) { - if (strcasecmp(map[i].n, name) == 0) { - return map[i].c; - } - } - return DEBUG_CATEGORY_NONE; -} - -/* Get level by name */ -static debug_level_t get_level_by_name(const char* name) { - struct { - const char* n; - debug_level_t l; - } map[] = { - {"none", DEBUG_LEVEL_NONE}, - {"error", DEBUG_LEVEL_ERROR}, - {"warn", DEBUG_LEVEL_WARN}, - {"info", DEBUG_LEVEL_INFO}, - {"debug", DEBUG_LEVEL_DEBUG}, - {"trace", DEBUG_LEVEL_TRACE}, - {NULL, 0} - }; - - for (int i = 0; map[i].n; i++) { - if (strcasecmp(map[i].n, name) == 0) { - return map[i].l; - } - } - return DEBUG_LEVEL_NONE; -} - -/* Global debug configuration */ -debug_config_t g_debug_config; -FILE* debug_output_file = NULL; - -/* Forward declaration for global_config structure */ -struct global_config { - char log_file[256]; - char debug_level[32]; - uint32_t debug_categories; - int enable_timestamp; - int enable_function_names; - int enable_file_lines; - int enable_colors; -}; - -/* Apply debug settings from configuration if not overridden by CLI */ -void debug_apply_config(const struct global_config *config, int cli_override_level, int cli_override_categories) { - if (!config) return; - - // Apply log file if specified and not overridden - if (config->log_file[0] != '\0') { - debug_set_output_file(config->log_file); - DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Set log file to: %s", config->log_file); - } - - // Apply debug level from config if not overridden by CLI - if (!cli_override_level && config->debug_level[0] != '\0') { - debug_level_t level = DEBUG_LEVEL_INFO; // default - if (strcasecmp(config->debug_level, "error") == 0) level = DEBUG_LEVEL_ERROR; - else if (strcasecmp(config->debug_level, "warn") == 0) level = DEBUG_LEVEL_WARN; - else if (strcasecmp(config->debug_level, "info") == 0) level = DEBUG_LEVEL_INFO; - else if (strcasecmp(config->debug_level, "debug") == 0) level = DEBUG_LEVEL_DEBUG; - else if (strcasecmp(config->debug_level, "trace") == 0) level = DEBUG_LEVEL_TRACE; - - debug_set_level(level); - DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Set debug level from config: %s", config->debug_level); - } - - // Apply debug categories from config if not overridden by CLI - if (!cli_override_categories && config->debug_categories != 0) { - debug_set_categories(config->debug_categories); - DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Set debug categories from config: 0x%X", config->debug_categories); - } - - // Apply output options from config - debug_enable_timestamp(config->enable_timestamp); - debug_enable_function_name(config->enable_function_names); - debug_enable_file_line(config->enable_file_lines); - debug_enable_color(config->enable_colors); - - DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Applied debug configuration from file"); -} - -/* Initialize debug system with default settings */ -void debug_config_init(void) { - g_debug_config.default_level = DEBUG_LEVEL_ERROR; - g_debug_config.categories = DEBUG_CATEGORY_ALL; - memset(g_debug_config.category_levels, 0, sizeof(g_debug_config.category_levels)); - g_debug_config.timestamp_enabled = 1; - g_debug_config.function_name_enabled = 1; - g_debug_config.file_line_enabled = 1; - g_debug_config.color_enabled = 1; - g_debug_config.max_output_per_second = 0; - g_debug_config.output_file = NULL; - - if (debug_output_file && debug_output_file != stdout && debug_output_file != stderr) { - fclose(debug_output_file); - } - debug_output_file = stdout; - - output_count = 0; - last_output_time = 0; -} - -/* Set debug level */ -void debug_set_level(debug_level_t level) { - g_debug_config.default_level = level; -} - -/* Enable/disable specific categories */ -void debug_enable_category(debug_category_t category) { - g_debug_config.categories |= category; -} - -void debug_disable_category(debug_category_t category) { - g_debug_config.categories &= ~category; -} - -void debug_set_categories(uint32_t categories) { - g_debug_config.categories = categories; -} - -/* Configure output options */ -void debug_enable_timestamp(int enable) { - g_debug_config.timestamp_enabled = enable; -} - -void debug_enable_function_name(int enable) { - g_debug_config.function_name_enabled = enable; -} - -void debug_enable_file_line(int enable) { - g_debug_config.file_line_enabled = enable; -} - -void debug_enable_color(int enable) { - g_debug_config.color_enabled = enable; -} - -void debug_set_rate_limit(size_t max_per_second) { - g_debug_config.max_output_per_second = max_per_second; -} - -void debug_set_output_file(const char* file_path) { - if (file_path == NULL) { - if (debug_output_file && debug_output_file != stdout && debug_output_file != stderr) { - fclose(debug_output_file); - } - debug_output_file = stdout; - g_debug_config.output_file = NULL; - } else { - FILE* new_file = fopen(file_path, "a"); - if (new_file) { - if (debug_output_file && debug_output_file != stdout && debug_output_file != stderr) { - fclose(debug_output_file); - } - debug_output_file = new_file; - g_debug_config.output_file = file_path; - } - } -} - -/* Check if debug output should be shown for given level and category */ -int debug_should_output(debug_level_t level, debug_category_t category) { - /* Check if category is enabled */ - if (!(g_debug_config.categories & category)) { - return 0; - } - - /* Check if level is sufficient */ - debug_level_t eff_level = debug_get_effective_level(category); - if (level > eff_level) { - return 0; - } - - /* Rate limiting check */ - if (g_debug_config.max_output_per_second > 0) { - time_t current_time = time(NULL); - if (current_time != last_output_time) { - output_count = 0; - last_output_time = current_time; - } - - if (output_count >= g_debug_config.max_output_per_second) { - return 0; - } - output_count++; - } - - return 1; -} - -/* Get current debug level for a category */ -debug_level_t debug_get_effective_level(debug_category_t category) { - if (category == DEBUG_CATEGORY_ALL || category == DEBUG_CATEGORY_NONE) { - return g_debug_config.default_level; - } - - /* Assume single category bit */ - uint32_t cat = category; - if (__builtin_popcount(cat) != 1) { - return DEBUG_LEVEL_NONE; /* Not supported for multiple */ - } - - int index = __builtin_ctz(cat); - if (index >= NUM_DEBUG_CATEGORIES) { - return DEBUG_LEVEL_NONE; - } - - debug_level_t lev = g_debug_config.category_levels[index]; - return (lev == DEBUG_LEVEL_NONE) ? g_debug_config.default_level : lev; -} - -/* Get color for debug level */ -static const char* get_level_color(debug_level_t level) { - if (!g_debug_config.color_enabled) { - return ""; - } - - switch (level) { - case DEBUG_LEVEL_ERROR: return color_red; - case DEBUG_LEVEL_WARN: return color_yellow; - case DEBUG_LEVEL_INFO: return color_green; - case DEBUG_LEVEL_DEBUG: return color_blue; - case DEBUG_LEVEL_TRACE: return color_magenta; - default: return ""; - } -} - -/* Get level name */ -static const char* get_level_name(debug_level_t level) { - switch (level) { - case DEBUG_LEVEL_ERROR: return "ERROR"; - case DEBUG_LEVEL_WARN: return "WARN"; - case DEBUG_LEVEL_INFO: return "INFO"; - case DEBUG_LEVEL_DEBUG: return "DEBUG"; - case DEBUG_LEVEL_TRACE: return "TRACE"; - default: return "UNKNOWN"; - } -} - -/* Format and output debug message */ -void debug_output(debug_level_t level, debug_category_t category, - const char* function, const char* file, int line, - const char* format, ...) { - -#define BUFFER_SIZE 4096 - char buffer[BUFFER_SIZE]; - int offset = 0; - size_t remaining = BUFFER_SIZE; - - va_list args; - va_start(args, format); - - FILE* output = debug_output_file ? debug_output_file : stdout; - - /* Add timestamp if enabled */ - if (g_debug_config.timestamp_enabled) { - time_t now = time(NULL); - struct tm* tm_info = localtime(&now); - char time_str[32]; - strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tm_info); - offset += snprintf(buffer + offset, remaining, "[%s] ", time_str); - remaining = BUFFER_SIZE - offset; - } - - /* Add level and color */ - const char* color = get_level_color(level); - const char* level_name = get_level_name(level); - if (g_debug_config.color_enabled) { - offset += snprintf(buffer + offset, remaining, "%s[%s]%s ", color, level_name, color_reset); - } else { - offset += snprintf(buffer + offset, remaining, "[%s] ", level_name); - } - remaining = BUFFER_SIZE - offset; - - /* Add category */ - offset += snprintf(buffer + offset, remaining, "[%d] ", category); - remaining = BUFFER_SIZE - offset; - - /* Add function name if enabled */ - if (g_debug_config.function_name_enabled && function) { - offset += snprintf(buffer + offset, remaining, "%s() ", function); - remaining = BUFFER_SIZE - offset; - } - - /* Add file:line if enabled */ - if (g_debug_config.file_line_enabled && file) { - offset += snprintf(buffer + offset, remaining, "(%s:%d) ", file, line); - remaining = BUFFER_SIZE - offset; - } - - /* Add the actual message */ - offset += vsnprintf(buffer + offset, remaining, format, args); - remaining = BUFFER_SIZE - offset; - - /* Add newline */ - if (remaining > 1) { - buffer[offset] = '\n'; - buffer[offset + 1] = '\0'; - } else { - buffer[BUFFER_SIZE - 2] = '\n'; - buffer[BUFFER_SIZE - 1] = '\0'; - } - - va_end(args); - - /* Output the entire line at once */ - fprintf(output, "%s", buffer); - fflush(output); -#undef BUFFER_SIZE -} - -/* Parse debug configuration from string */ -int debug_parse_config(const char* config_string) { - if (!config_string || !*config_string) { - return 0; - } - - char* str = strdup(config_string); - if (!str) { - return -1; - } - - char* token = strtok(str, ","); - while (token) { - /* Trim leading spaces */ - while (isspace(*token)) { - token++; - } - - char* colon = strchr(token, ':'); - if (!colon) { - free(str); - return -1; - } - - *colon = '\0'; - char* cat_name = token; - char* level_name = colon + 1; - - /* Trim leading spaces in level_name */ - while (isspace(*level_name)) { - level_name++; - } - - /* Find category */ - debug_category_t cat = get_category_by_name(cat_name); - if (cat == DEBUG_CATEGORY_NONE) { - free(str); - return -1; - } - - /* Find level */ - debug_level_t lev = get_level_by_name(level_name); - if (lev == DEBUG_LEVEL_NONE) { - free(str); - return -1; - } - - if (cat == DEBUG_CATEGORY_ALL) { - g_debug_config.default_level = lev; - } else { - g_debug_config.categories |= cat; - int index = __builtin_ctz(cat); - if (index < NUM_DEBUG_CATEGORIES) { - g_debug_config.category_levels[index] = lev; - } - } - - token = strtok(NULL, ","); - } - - free(str); - return 0; -} - -/* Apply debug settings from configuration string values */ -void debug_apply_config_values(const char *log_file, const char *debug_level_str, uint32_t debug_categories, - int enable_timestamp, int enable_function_names, int enable_file_lines, int enable_colors, - int cli_override_level, int cli_override_categories) { - // This function would be implemented to apply individual config values - // For now, it's a placeholder that could be expanded based on specific needs -} \ No newline at end of file +/** + * Debug configuration implementation + * Runtime debug configuration system for flexible debug output control + */ + +#include "debug_config.h" +#include +#include +#include +#include +#include +#include +#include +#include + +/* Get category by name */ +static debug_category_t get_category_by_name(const char* name) { + struct { + const char* n; + debug_category_t c; + } map[] = { + {"none", DEBUG_CATEGORY_NONE}, + {"uasync", DEBUG_CATEGORY_UASYNC}, + {"ll_queue", DEBUG_CATEGORY_LL_QUEUE}, + {"connection", DEBUG_CATEGORY_CONNECTION}, + {"etcp", DEBUG_CATEGORY_ETCP}, + {"crypto", DEBUG_CATEGORY_CRYPTO}, + {"memory", DEBUG_CATEGORY_MEMORY}, + {"timing", DEBUG_CATEGORY_TIMING}, + {"config", DEBUG_CATEGORY_CONFIG}, + {"tun", DEBUG_CATEGORY_TUN}, + {"routing", DEBUG_CATEGORY_ROUTING}, + {"timers", DEBUG_CATEGORY_TIMERS}, + {"all", DEBUG_CATEGORY_ALL}, + {NULL, 0} + }; + + for (int i = 0; map[i].n; i++) { + if (strcasecmp(map[i].n, name) == 0) { + return map[i].c; + } + } + return DEBUG_CATEGORY_NONE; +} + +/* Global debug configuration */ +debug_config_t g_debug_config; +FILE* debug_output_file = NULL; + +/* Initialize debug system with default settings */ +void debug_config_init(void) { + g_debug_config.level = DEBUG_LEVEL_ERROR; + g_debug_config.categories = DEBUG_CATEGORY_ALL; + g_debug_config.timestamp_enabled = 1; + g_debug_config.function_name_enabled = 1; + g_debug_config.file_line_enabled = 1; + g_debug_config.output_file = NULL; + + if (debug_output_file && debug_output_file != stdout && debug_output_file != stderr) { + fclose(debug_output_file); + } + debug_output_file = stdout; +} + +/* Set debug level */ +void debug_set_level(debug_level_t level) { + g_debug_config.level = level; +} + +/* Enable/disable specific categories */ +void debug_enable_category(debug_category_t category) { + g_debug_config.categories |= category; +} + +void debug_disable_category(debug_category_t category) { + g_debug_config.categories &= ~category; +} + +void debug_set_categories(debug_category_t categories) { + g_debug_config.categories = categories; +} + +/* Set masks directly */ +void debug_set_masks(debug_category_t categories, debug_level_t level) { + g_debug_config.categories = categories; + g_debug_config.level = level; +} + +void debug_enable_function_name(int enable) { + g_debug_config.function_name_enabled = enable; +} + +void debug_enable_file_line(int enable) { + g_debug_config.file_line_enabled = enable; +} + +void debug_set_output_file(const char* file_path) { + if (debug_output_file) return;// уже установлен, кто первый того и тапки + FILE* new_file = fopen(file_path, "a"); + if (new_file) { + debug_output_file = new_file; + g_debug_config.output_file = file_path; + } +} + +/* Check if debug output should be shown for given level and category */ +int debug_should_output(debug_level_t level, debug_category_t category) { + + /* Check if category is enabled */ + if (!(g_debug_config.categories & category)) { + return 0; + } + + /* Check if level is sufficient */ + if (level > g_debug_config.level) { + return 0; + } + + return 1; +} + +/* Get current debug level */ +debug_level_t debug_get_level(void) { + return g_debug_config.level; +} + +/* Get level name */ +static const char* get_level_name(debug_level_t level) { + switch (level) { + case DEBUG_LEVEL_ERROR: return "ERROR"; + case DEBUG_LEVEL_WARN: return "WARN"; + case DEBUG_LEVEL_INFO: return "INFO"; + case DEBUG_LEVEL_DEBUG: return "DEBUG"; + case DEBUG_LEVEL_TRACE: return "TRACE"; + default: return "UNKNOWN"; + } +} + +/* Format and output debug message */ +void debug_output(debug_level_t level, debug_category_t category, + const char* function, const char* file, int line, + const char* format, ...) { + +#define BUFFER_SIZE 4096 + char buffer[BUFFER_SIZE]; + int offset = 0; + size_t remaining = BUFFER_SIZE; + + va_list args; + va_start(args, format); + + FILE* output = debug_output_file ? debug_output_file : stdout; + + /* Add timestamp if enabled */ + time_t now = time(NULL); + struct tm* tm_info = localtime(&now); + char time_str[32]; + strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tm_info); + offset += snprintf(buffer + offset, remaining, "[%s] ", time_str); + remaining = BUFFER_SIZE - offset; + + /* Add level */ + const char* level_name = get_level_name(level); + offset += snprintf(buffer + offset, remaining, "[%s] ", level_name); + remaining = BUFFER_SIZE - offset; + + /* Add category */ + offset += snprintf(buffer + offset, remaining, "[%llu] ", (unsigned long long)category); + remaining = BUFFER_SIZE - offset; + + /* Add function name if enabled */ + if (g_debug_config.function_name_enabled && function) { + offset += snprintf(buffer + offset, remaining, "%s() ", function); + remaining = BUFFER_SIZE - offset; + } + + /* Add file:line if enabled */ + if (g_debug_config.file_line_enabled && file) { + offset += snprintf(buffer + offset, remaining, "(%s:%d) ", file, line); + remaining = BUFFER_SIZE - offset; + } + + /* Add the actual message */ + offset += vsnprintf(buffer + offset, remaining, format, args); + remaining = BUFFER_SIZE - offset; + + /* Add newline */ + if (remaining > 1) { + buffer[offset] = '\n'; + buffer[offset + 1] = '\0'; + } else { + buffer[BUFFER_SIZE - 2] = '\n'; + buffer[BUFFER_SIZE - 1] = '\0'; + } + + va_end(args); + + /* Output the entire line at once */ + fprintf(output, "%s", buffer); + fflush(output); +#undef BUFFER_SIZE +} + +/* Parse debug configuration from string */ +int debug_parse_config(const char* config_string) { + if (!config_string || !*config_string) { + return 0; + } + + char* str = strdup(config_string); + if (!str) { + return -1; + } + + debug_category_t categories = 0; + debug_level_t level = DEBUG_LEVEL_NONE; + + char* token = strtok(str, ";"); + while (token) { + /* Trim leading spaces */ + while (isspace(*token)) { + token++; + } + + char* eq = strchr(token, '='); + if (!eq) { + free(str); + return -1; + } + + *eq = '\0'; + char* key = token; + char* value = eq + 1; + + /* Trim leading spaces in value */ + while (isspace(*value)) { + value++; + } + + if (strcasecmp(key, "modules") == 0) { + char* mod_token = strtok(value, ","); + while (mod_token) { + /* Trim leading spaces */ + while (isspace(*mod_token)) { + mod_token++; + } + + debug_category_t cat = get_category_by_name(mod_token); + if (cat == DEBUG_CATEGORY_NONE) { + free(str); + return -1; + } + categories |= cat; + mod_token = strtok(NULL, ","); + } + } else if (strcasecmp(key, "level") == 0) { + int lev_num = atoi(value); + if (lev_num < DEBUG_LEVEL_NONE || lev_num > DEBUG_LEVEL_TRACE) { + free(str); + return -1; + } + level = (debug_level_t)lev_num; + } else { + free(str); + return -1; + } + + token = strtok(NULL, ";"); + } + + debug_set_masks(categories, level); + + free(str); + return 0; +} diff --git a/lib/debug_config.c1 b/lib/debug_config.c1 index 0cf1fdfbd..c24c39c3e 100755 --- a/lib/debug_config.c1 +++ b/lib/debug_config.c1 @@ -1,390 +1,435 @@ -/** - * Debug configuration implementation - * Runtime debug configuration system for flexible debug output control - */ - -#include "debug_config.h" -#include -#include -#include -#include -#include -#include -#include -#include - -/* Global debug configuration */ -debug_config_t g_debug_config = { - .default_level = DEBUG_LEVEL_ERROR, - .categories = DEBUG_CATEGORY_ALL, - .category_levels = {0}, - .timestamp_enabled = 1, - .function_name_enabled = 1, - .file_line_enabled = 1, - .color_enabled = 1, - .max_output_per_second = 0, - .output_file = NULL -}; - -/* Output file handle */ -FILE* debug_output_file = NULL; - -/* Rate limiting */ -static size_t output_count = 0; -static time_t last_output_time = 0; - -/* ANSI color codes */ -static const char* color_red = "\033[31m"; -static const char* color_yellow = "\033[33m"; -static const char* color_green = "\033[32m"; -static const char* color_blue = "\033[34m"; -static const char* color_magenta = "\033[35m"; -static const char* color_cyan = "\033[36m"; -static const char* color_reset = "\033[0m"; - -/* Get category by name */ -static debug_category_t get_category_by_name(const char* name) { - struct { - const char* n; - debug_category_t c; - } map[] = { - {"none", DEBUG_CATEGORY_NONE}, - {"uasync", DEBUG_CATEGORY_UASYNC}, - {"ll_queue", DEBUG_CATEGORY_LL_QUEUE}, - {"connection", DEBUG_CATEGORY_CONNECTION}, - {"etcp", DEBUG_CATEGORY_ETCP}, - {"crypto", DEBUG_CATEGORY_CRYPTO}, - {"memory", DEBUG_CATEGORY_MEMORY}, - {"timing", DEBUG_CATEGORY_TIMING}, - {"config", DEBUG_CATEGORY_CONFIG}, - {"tun", DEBUG_CATEGORY_TUN}, - {"routing", DEBUG_CATEGORY_ROUTING}, - {"timers", DEBUG_CATEGORY_TIMERS}, - {"all", DEBUG_CATEGORY_ALL}, - {NULL, 0} - }; - - for (int i = 0; map[i].n; i++) { - if (strcasecmp(map[i].n, name) == 0) { - return map[i].c; - } - } - return DEBUG_CATEGORY_NONE; -} - -/* Get level by name */ -static debug_level_t get_level_by_name(const char* name) { - struct { - const char* n; - debug_level_t l; - } map[] = { - {"none", DEBUG_LEVEL_NONE}, - {"error", DEBUG_LEVEL_ERROR}, - {"warn", DEBUG_LEVEL_WARN}, - {"info", DEBUG_LEVEL_INFO}, - {"debug", DEBUG_LEVEL_DEBUG}, - {"trace", DEBUG_LEVEL_TRACE}, - {NULL, 0} - }; - - for (int i = 0; map[i].n; i++) { - if (strcasecmp(map[i].n, name) == 0) { - return map[i].l; - } - } - return DEBUG_LEVEL_NONE; -} - -/* Initialize debug system with default settings */ -void debug_config_init(void) { - g_debug_config.default_level = DEBUG_LEVEL_ERROR; - g_debug_config.categories = DEBUG_CATEGORY_ALL; - memset(g_debug_config.category_levels, 0, sizeof(g_debug_config.category_levels)); - g_debug_config.timestamp_enabled = 1; - g_debug_config.function_name_enabled = 1; - g_debug_config.file_line_enabled = 1; - g_debug_config.color_enabled = 1; - g_debug_config.max_output_per_second = 0; - g_debug_config.output_file = NULL; - - if (debug_output_file && debug_output_file != stdout && debug_output_file != stderr) { - fclose(debug_output_file); - } - debug_output_file = stdout; - - output_count = 0; - last_output_time = 0; -} - -/* Set debug level */ -void debug_set_level(debug_level_t level) { - g_debug_config.default_level = level; -} - -/* Enable/disable specific categories */ -void debug_enable_category(debug_category_t category) { - g_debug_config.categories |= category; -} - -void debug_disable_category(debug_category_t category) { - g_debug_config.categories &= ~category; -} - -void debug_set_categories(uint32_t categories) { - g_debug_config.categories = categories; -} - -/* Configure output options */ -void debug_enable_timestamp(int enable) { - g_debug_config.timestamp_enabled = enable; -} - -void debug_enable_function_name(int enable) { - g_debug_config.function_name_enabled = enable; -} - -void debug_enable_file_line(int enable) { - g_debug_config.file_line_enabled = enable; -} - -void debug_enable_color(int enable) { - g_debug_config.color_enabled = enable; -} - -void debug_set_rate_limit(size_t max_per_second) { - g_debug_config.max_output_per_second = max_per_second; -} - -void debug_set_output_file(const char* file_path) { - if (file_path == NULL) { - if (debug_output_file && debug_output_file != stdout && debug_output_file != stderr) { - fclose(debug_output_file); - } - debug_output_file = stdout; - g_debug_config.output_file = NULL; - } else { - FILE* new_file = fopen(file_path, "a"); - if (new_file) { - if (debug_output_file && debug_output_file != stdout && debug_output_file != stderr) { - fclose(debug_output_file); - } - debug_output_file = new_file; - g_debug_config.output_file = file_path; - } - } -} - -/* Check if debug output should be shown for given level and category */ -int debug_should_output(debug_level_t level, debug_category_t category) { - /* Check if category is enabled */ - if (!(g_debug_config.categories & category)) { - return 0; - } - - /* Check if level is sufficient */ - debug_level_t eff_level = debug_get_effective_level(category); - if (level > eff_level) { - return 0; - } - - /* Rate limiting check */ - if (g_debug_config.max_output_per_second > 0) { - time_t current_time = time(NULL); - if (current_time != last_output_time) { - output_count = 0; - last_output_time = current_time; - } - - if (output_count >= g_debug_config.max_output_per_second) { - return 0; - } - output_count++; - } - - return 1; -} - -/* Get current debug level for a category */ -debug_level_t debug_get_effective_level(debug_category_t category) { - if (category == DEBUG_CATEGORY_ALL || category == DEBUG_CATEGORY_NONE) { - return g_debug_config.default_level; - } - - /* Assume single category bit */ - uint32_t cat = category; - if (__builtin_popcount(cat) != 1) { - return DEBUG_LEVEL_NONE; /* Not supported for multiple */ - } - - int index = __builtin_ctz(cat); - if (index >= NUM_DEBUG_CATEGORIES) { - return DEBUG_LEVEL_NONE; - } - - debug_level_t lev = g_debug_config.category_levels[index]; - return (lev == DEBUG_LEVEL_NONE) ? g_debug_config.default_level : lev; -} - -/* Get color for debug level */ -static const char* get_level_color(debug_level_t level) { - if (!g_debug_config.color_enabled) { - return ""; - } - - switch (level) { - case DEBUG_LEVEL_ERROR: return color_red; - case DEBUG_LEVEL_WARN: return color_yellow; - case DEBUG_LEVEL_INFO: return color_green; - case DEBUG_LEVEL_DEBUG: return color_blue; - case DEBUG_LEVEL_TRACE: return color_magenta; - default: return ""; - } -} - -/* Get level name */ -static const char* get_level_name(debug_level_t level) { - switch (level) { - case DEBUG_LEVEL_ERROR: return "ERROR"; - case DEBUG_LEVEL_WARN: return "WARN"; - case DEBUG_LEVEL_INFO: return "INFO"; - case DEBUG_LEVEL_DEBUG: return "DEBUG"; - case DEBUG_LEVEL_TRACE: return "TRACE"; - default: return "UNKNOWN"; - } -} - -/* Format and output debug message */ -void debug_output(debug_level_t level, debug_category_t category, - const char* function, const char* file, int line, - const char* format, ...) { - -#define BUFFER_SIZE 4096 - char buffer[BUFFER_SIZE]; - int offset = 0; - size_t remaining = BUFFER_SIZE; - - va_list args; - va_start(args, format); - - FILE* output = debug_output_file ? debug_output_file : stdout; - - /* Add timestamp if enabled */ - if (g_debug_config.timestamp_enabled) { - time_t now = time(NULL); - struct tm* tm_info = localtime(&now); - char time_str[32]; - strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tm_info); - offset += snprintf(buffer + offset, remaining, "[%s] ", time_str); - remaining = BUFFER_SIZE - offset; - } - - /* Add level and color */ - const char* color = get_level_color(level); - const char* level_name = get_level_name(level); - if (g_debug_config.color_enabled) { - offset += snprintf(buffer + offset, remaining, "%s[%s]%s ", color, level_name, color_reset); - } else { - offset += snprintf(buffer + offset, remaining, "[%s] ", level_name); - } - remaining = BUFFER_SIZE - offset; - - /* Add category */ - offset += snprintf(buffer + offset, remaining, "[%d] ", category); - remaining = BUFFER_SIZE - offset; - - /* Add function name if enabled */ - if (g_debug_config.function_name_enabled && function) { - offset += snprintf(buffer + offset, remaining, "%s() ", function); - remaining = BUFFER_SIZE - offset; - } - - /* Add file:line if enabled */ - if (g_debug_config.file_line_enabled && file) { - offset += snprintf(buffer + offset, remaining, "(%s:%d) ", file, line); - remaining = BUFFER_SIZE - offset; - } - - /* Add the actual message */ - offset += vsnprintf(buffer + offset, remaining, format, args); - remaining = BUFFER_SIZE - offset; - - /* Add newline */ - if (remaining > 1) { - buffer[offset] = '\n'; - buffer[offset + 1] = '\0'; - } else { - buffer[BUFFER_SIZE - 2] = '\n'; - buffer[BUFFER_SIZE - 1] = '\0'; - } - - va_end(args); - - /* Output the entire line at once */ - fprintf(output, "%s", buffer); - fflush(output); -#undef BUFFER_SIZE -} - -/* Parse debug configuration from string */ -int debug_parse_config(const char* config_string) { - if (!config_string || !*config_string) { - return 0; - } - - char* str = strdup(config_string); - if (!str) { - return -1; - } - - char* token = strtok(str, ","); - while (token) { - /* Trim leading spaces */ - while (isspace(*token)) { - token++; - } - - char* colon = strchr(token, ':'); - if (!colon) { - free(str); - return -1; - } - - *colon = '\0'; - char* cat_name = token; - char* level_name = colon + 1; - - /* Trim leading spaces in level_name */ - while (isspace(*level_name)) { - level_name++; - } - - /* Find category */ - debug_category_t cat = get_category_by_name(cat_name); - if (cat == DEBUG_CATEGORY_NONE) { - free(str); - return -1; - } - - /* Find level */ - debug_level_t lev = get_level_by_name(level_name); - if (lev == DEBUG_LEVEL_NONE) { - free(str); - return -1; - } - - if (cat == DEBUG_CATEGORY_ALL) { - g_debug_config.default_level = lev; - } else { - g_debug_config.categories |= cat; - int index = __builtin_ctz(cat); - if (index < NUM_DEBUG_CATEGORIES) { - g_debug_config.category_levels[index] = lev; - } - } - - token = strtok(NULL, ","); - } - - free(str); - return 0; -} +/** + * Debug configuration implementation + * Runtime debug configuration system for flexible debug output control + */ + +#include "debug_config.h" +#include +#include +#include +#include +#include +#include +#include +#include + +/* Rate limiting */ +static size_t output_count = 0; +static time_t last_output_time = 0; + +/* ANSI color codes */ +static const char* color_red = "\033[31m"; +static const char* color_yellow = "\033[33m"; +static const char* color_green = "\033[32m"; +static const char* color_blue = "\033[34m"; +static const char* color_magenta = "\033[35m"; +static const char* color_cyan = "\033[36m"; +static const char* color_reset = "\033[0m"; + +/* Get category by name */ +static debug_category_t get_category_by_name(const char* name) { + struct { + const char* n; + debug_category_t c; + } map[] = { + {"none", DEBUG_CATEGORY_NONE}, + {"uasync", DEBUG_CATEGORY_UASYNC}, + {"ll_queue", DEBUG_CATEGORY_LL_QUEUE}, + {"connection", DEBUG_CATEGORY_CONNECTION}, + {"etcp", DEBUG_CATEGORY_ETCP}, + {"crypto", DEBUG_CATEGORY_CRYPTO}, + {"memory", DEBUG_CATEGORY_MEMORY}, + {"timing", DEBUG_CATEGORY_TIMING}, + {"config", DEBUG_CATEGORY_CONFIG}, + {"tun", DEBUG_CATEGORY_TUN}, + {"routing", DEBUG_CATEGORY_ROUTING}, + {"timers", DEBUG_CATEGORY_TIMERS}, + {"all", DEBUG_CATEGORY_ALL}, + {NULL, 0} + }; + + for (int i = 0; map[i].n; i++) { + if (strcasecmp(map[i].n, name) == 0) { + return map[i].c; + } + } + return DEBUG_CATEGORY_NONE; +} + +/* Get level by name */ +static debug_level_t get_level_by_name(const char* name) { + struct { + const char* n; + debug_level_t l; + } map[] = { + {"none", DEBUG_LEVEL_NONE}, + {"error", DEBUG_LEVEL_ERROR}, + {"warn", DEBUG_LEVEL_WARN}, + {"info", DEBUG_LEVEL_INFO}, + {"debug", DEBUG_LEVEL_DEBUG}, + {"trace", DEBUG_LEVEL_TRACE}, + {NULL, 0} + }; + + for (int i = 0; map[i].n; i++) { + if (strcasecmp(map[i].n, name) == 0) { + return map[i].l; + } + } + return DEBUG_LEVEL_NONE; +} + +/* Global debug configuration */ +debug_config_t g_debug_config; +FILE* debug_output_file = NULL; + +/* Forward declaration for global_config structure */ +struct global_config { + char log_file[256]; + char debug_level[32]; + uint32_t debug_categories; + int enable_timestamp; + int enable_function_names; + int enable_file_lines; + int enable_colors; +}; + +/* Apply debug settings from configuration if not overridden by CLI */ +void debug_apply_config(const struct global_config *config, int cli_override_level, int cli_override_categories) { + if (!config) return; + + // Apply log file if specified and not overridden + if (config->log_file[0] != '\0') { + debug_set_output_file(config->log_file); + DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Set log file to: %s", config->log_file); + } + + // Apply debug level from config if not overridden by CLI + if (!cli_override_level && config->debug_level[0] != '\0') { + debug_level_t level = DEBUG_LEVEL_INFO; // default + if (strcasecmp(config->debug_level, "error") == 0) level = DEBUG_LEVEL_ERROR; + else if (strcasecmp(config->debug_level, "warn") == 0) level = DEBUG_LEVEL_WARN; + else if (strcasecmp(config->debug_level, "info") == 0) level = DEBUG_LEVEL_INFO; + else if (strcasecmp(config->debug_level, "debug") == 0) level = DEBUG_LEVEL_DEBUG; + else if (strcasecmp(config->debug_level, "trace") == 0) level = DEBUG_LEVEL_TRACE; + + debug_set_level(level); + DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Set debug level from config: %s", config->debug_level); + } + + // Apply debug categories from config if not overridden by CLI + if (!cli_override_categories && config->debug_categories != 0) { + debug_set_categories(config->debug_categories); + DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Set debug categories from config: 0x%X", config->debug_categories); + } + + // Apply output options from config + debug_enable_timestamp(config->enable_timestamp); + debug_enable_function_name(config->enable_function_names); + debug_enable_file_line(config->enable_file_lines); + debug_enable_color(config->enable_colors); + + DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Applied debug configuration from file"); +} + +/* Initialize debug system with default settings */ +void debug_config_init(void) { + g_debug_config.default_level = DEBUG_LEVEL_ERROR; + g_debug_config.categories = DEBUG_CATEGORY_ALL; + memset(g_debug_config.category_levels, 0, sizeof(g_debug_config.category_levels)); + g_debug_config.timestamp_enabled = 1; + g_debug_config.function_name_enabled = 1; + g_debug_config.file_line_enabled = 1; + g_debug_config.color_enabled = 1; + g_debug_config.max_output_per_second = 0; + g_debug_config.output_file = NULL; + + if (debug_output_file && debug_output_file != stdout && debug_output_file != stderr) { + fclose(debug_output_file); + } + debug_output_file = stdout; + + output_count = 0; + last_output_time = 0; +} + +/* Set debug level */ +void debug_set_level(debug_level_t level) { + g_debug_config.default_level = level; +} + +/* Enable/disable specific categories */ +void debug_enable_category(debug_category_t category) { + g_debug_config.categories |= category; +} + +void debug_disable_category(debug_category_t category) { + g_debug_config.categories &= ~category; +} + +void debug_set_categories(uint32_t categories) { + g_debug_config.categories = categories; +} + +/* Configure output options */ +void debug_enable_timestamp(int enable) { + g_debug_config.timestamp_enabled = enable; +} + +void debug_enable_function_name(int enable) { + g_debug_config.function_name_enabled = enable; +} + +void debug_enable_file_line(int enable) { + g_debug_config.file_line_enabled = enable; +} + +void debug_enable_color(int enable) { + g_debug_config.color_enabled = enable; +} + +void debug_set_rate_limit(size_t max_per_second) { + g_debug_config.max_output_per_second = max_per_second; +} + +void debug_set_output_file(const char* file_path) { + if (file_path == NULL) { + if (debug_output_file && debug_output_file != stdout && debug_output_file != stderr) { + fclose(debug_output_file); + } + debug_output_file = stdout; + g_debug_config.output_file = NULL; + } else { + FILE* new_file = fopen(file_path, "a"); + if (new_file) { + if (debug_output_file && debug_output_file != stdout && debug_output_file != stderr) { + fclose(debug_output_file); + } + debug_output_file = new_file; + g_debug_config.output_file = file_path; + } + } +} + +/* Check if debug output should be shown for given level and category */ +int debug_should_output(debug_level_t level, debug_category_t category) { + /* Check if category is enabled */ + if (!(g_debug_config.categories & category)) { + return 0; + } + + /* Check if level is sufficient */ + debug_level_t eff_level = debug_get_effective_level(category); + if (level > eff_level) { + return 0; + } + + /* Rate limiting check */ + if (g_debug_config.max_output_per_second > 0) { + time_t current_time = time(NULL); + if (current_time != last_output_time) { + output_count = 0; + last_output_time = current_time; + } + + if (output_count >= g_debug_config.max_output_per_second) { + return 0; + } + output_count++; + } + + return 1; +} + +/* Get current debug level for a category */ +debug_level_t debug_get_effective_level(debug_category_t category) { + if (category == DEBUG_CATEGORY_ALL || category == DEBUG_CATEGORY_NONE) { + return g_debug_config.default_level; + } + + /* Assume single category bit */ + uint32_t cat = category; + if (__builtin_popcount(cat) != 1) { + return DEBUG_LEVEL_NONE; /* Not supported for multiple */ + } + + int index = __builtin_ctz(cat); + if (index >= NUM_DEBUG_CATEGORIES) { + return DEBUG_LEVEL_NONE; + } + + debug_level_t lev = g_debug_config.category_levels[index]; + return (lev == DEBUG_LEVEL_NONE) ? g_debug_config.default_level : lev; +} + +/* Get color for debug level */ +static const char* get_level_color(debug_level_t level) { + if (!g_debug_config.color_enabled) { + return ""; + } + + switch (level) { + case DEBUG_LEVEL_ERROR: return color_red; + case DEBUG_LEVEL_WARN: return color_yellow; + case DEBUG_LEVEL_INFO: return color_green; + case DEBUG_LEVEL_DEBUG: return color_blue; + case DEBUG_LEVEL_TRACE: return color_magenta; + default: return ""; + } +} + +/* Get level name */ +static const char* get_level_name(debug_level_t level) { + switch (level) { + case DEBUG_LEVEL_ERROR: return "ERROR"; + case DEBUG_LEVEL_WARN: return "WARN"; + case DEBUG_LEVEL_INFO: return "INFO"; + case DEBUG_LEVEL_DEBUG: return "DEBUG"; + case DEBUG_LEVEL_TRACE: return "TRACE"; + default: return "UNKNOWN"; + } +} + +/* Format and output debug message */ +void debug_output(debug_level_t level, debug_category_t category, + const char* function, const char* file, int line, + const char* format, ...) { + +#define BUFFER_SIZE 4096 + char buffer[BUFFER_SIZE]; + int offset = 0; + size_t remaining = BUFFER_SIZE; + + va_list args; + va_start(args, format); + + FILE* output = debug_output_file ? debug_output_file : stdout; + + /* Add timestamp if enabled */ + if (g_debug_config.timestamp_enabled) { + time_t now = time(NULL); + struct tm* tm_info = localtime(&now); + char time_str[32]; + strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tm_info); + offset += snprintf(buffer + offset, remaining, "[%s] ", time_str); + remaining = BUFFER_SIZE - offset; + } + + /* Add level and color */ + const char* color = get_level_color(level); + const char* level_name = get_level_name(level); + if (g_debug_config.color_enabled) { + offset += snprintf(buffer + offset, remaining, "%s[%s]%s ", color, level_name, color_reset); + } else { + offset += snprintf(buffer + offset, remaining, "[%s] ", level_name); + } + remaining = BUFFER_SIZE - offset; + + /* Add category */ + offset += snprintf(buffer + offset, remaining, "[%d] ", category); + remaining = BUFFER_SIZE - offset; + + /* Add function name if enabled */ + if (g_debug_config.function_name_enabled && function) { + offset += snprintf(buffer + offset, remaining, "%s() ", function); + remaining = BUFFER_SIZE - offset; + } + + /* Add file:line if enabled */ + if (g_debug_config.file_line_enabled && file) { + offset += snprintf(buffer + offset, remaining, "(%s:%d) ", file, line); + remaining = BUFFER_SIZE - offset; + } + + /* Add the actual message */ + offset += vsnprintf(buffer + offset, remaining, format, args); + remaining = BUFFER_SIZE - offset; + + /* Add newline */ + if (remaining > 1) { + buffer[offset] = '\n'; + buffer[offset + 1] = '\0'; + } else { + buffer[BUFFER_SIZE - 2] = '\n'; + buffer[BUFFER_SIZE - 1] = '\0'; + } + + va_end(args); + + /* Output the entire line at once */ + fprintf(output, "%s", buffer); + fflush(output); +#undef BUFFER_SIZE +} + +/* Parse debug configuration from string */ +int debug_parse_config(const char* config_string) { + if (!config_string || !*config_string) { + return 0; + } + + char* str = strdup(config_string); + if (!str) { + return -1; + } + + char* token = strtok(str, ","); + while (token) { + /* Trim leading spaces */ + while (isspace(*token)) { + token++; + } + + char* colon = strchr(token, ':'); + if (!colon) { + free(str); + return -1; + } + + *colon = '\0'; + char* cat_name = token; + char* level_name = colon + 1; + + /* Trim leading spaces in level_name */ + while (isspace(*level_name)) { + level_name++; + } + + /* Find category */ + debug_category_t cat = get_category_by_name(cat_name); + if (cat == DEBUG_CATEGORY_NONE) { + free(str); + return -1; + } + + /* Find level */ + debug_level_t lev = get_level_by_name(level_name); + if (lev == DEBUG_LEVEL_NONE) { + free(str); + return -1; + } + + if (cat == DEBUG_CATEGORY_ALL) { + g_debug_config.default_level = lev; + } else { + g_debug_config.categories |= cat; + int index = __builtin_ctz(cat); + if (index < NUM_DEBUG_CATEGORIES) { + g_debug_config.category_levels[index] = lev; + } + } + + token = strtok(NULL, ","); + } + + free(str); + return 0; +} + +/* Apply debug settings from configuration string values */ +void debug_apply_config_values(const char *log_file, const char *debug_level_str, uint32_t debug_categories, + int enable_timestamp, int enable_function_names, int enable_file_lines, int enable_colors, + int cli_override_level, int cli_override_categories) { + // This function would be implemented to apply individual config values + // For now, it's a placeholder that could be expanded based on specific needs +} \ No newline at end of file diff --git a/lib/debug_config.h b/lib/debug_config.h index bce40ed81..feb84113b 100644 --- a/lib/debug_config.h +++ b/lib/debug_config.h @@ -14,9 +14,6 @@ extern "C" { #endif -/* Number of categories (bits 0-10) */ -#define NUM_DEBUG_CATEGORIES 11 - /* Debug levels */ typedef enum { DEBUG_LEVEL_NONE = 0, // No debug output @@ -28,33 +25,30 @@ typedef enum { } debug_level_t; /* Debug categories - can be combined with bitwise OR */ -typedef enum { - DEBUG_CATEGORY_NONE = 0, - DEBUG_CATEGORY_UASYNC = 1 << 0, // u_async module - DEBUG_CATEGORY_LL_QUEUE = 1 << 1, // ll_queue module - DEBUG_CATEGORY_CONNECTION = 1 << 2, // connection module - DEBUG_CATEGORY_ETCP = 1 << 3, // etcp module - DEBUG_CATEGORY_CRYPTO = 1 << 4, // crypto operations - DEBUG_CATEGORY_MEMORY = 1 << 5, // memory management - DEBUG_CATEGORY_TIMING = 1 << 6, // timing/performance - DEBUG_CATEGORY_CONFIG = 1 << 7, // configuration parsing - DEBUG_CATEGORY_TUN = 1 << 8, // TUN interface - DEBUG_CATEGORY_ROUTING = 1 << 9, // routing table - DEBUG_CATEGORY_TIMERS = 1 << 10, // timer management - DEBUG_CATEGORY_ALL = 0xFFFFFFFF -} debug_category_t; +typedef uint64_t debug_category_t; + +#define DEBUG_CATEGORY_NONE ((debug_category_t)0) +#define DEBUG_CATEGORY_UASYNC ((debug_category_t)1 << 0) // u_async module +#define DEBUG_CATEGORY_LL_QUEUE ((debug_category_t)1 << 1) // ll_queue module +#define DEBUG_CATEGORY_CONNECTION ((debug_category_t)1 << 2) // connection module +#define DEBUG_CATEGORY_ETCP ((debug_category_t)1 << 3) // etcp module +#define DEBUG_CATEGORY_CRYPTO ((debug_category_t)1 << 4) // crypto operations +#define DEBUG_CATEGORY_MEMORY ((debug_category_t)1 << 5) // memory management +#define DEBUG_CATEGORY_TIMING ((debug_category_t)1 << 6) // timing/performance +#define DEBUG_CATEGORY_CONFIG ((debug_category_t)1 << 7) // configuration parsing +#define DEBUG_CATEGORY_TUN ((debug_category_t)1 << 8) // TUN interface +#define DEBUG_CATEGORY_ROUTING ((debug_category_t)1 << 9) // routing table +#define DEBUG_CATEGORY_TIMERS ((debug_category_t)1 << 10) // timer management +#define DEBUG_CATEGORY_ALL (~((debug_category_t)0)) /* Debug configuration structure */ typedef struct { - debug_level_t default_level; // Default debug level - uint32_t categories; // Enabled categories (bitmask) - debug_level_t category_levels[NUM_DEBUG_CATEGORIES]; // Per-category levels (NONE means use default) - int timestamp_enabled; // Include timestamps in output - int function_name_enabled; // Include function names - int file_line_enabled; // Include file:line info - int color_enabled; // Use ANSI colors (if terminal supports) - size_t max_output_per_second; // Rate limiting (0 = unlimited) - const char* output_file; // NULL = stdout, otherwise file path + debug_level_t level; // Global debug level + debug_category_t categories; // Enabled categories (bitmask) + int timestamp_enabled; // Include timestamps in output + int function_name_enabled; // Include function names + int file_line_enabled; // Include file:line info + const char* output_file; // NULL = stdout, otherwise file path } debug_config_t; /* Global debug configuration */ @@ -69,33 +63,34 @@ void debug_set_level(debug_level_t level); /* Enable/disable specific categories */ void debug_enable_category(debug_category_t category); void debug_disable_category(debug_category_t category); -void debug_set_categories(uint32_t categories); +void debug_set_categories(debug_category_t categories); + +/* Set masks directly */ +void debug_set_masks(debug_category_t categories, debug_level_t level); /* Configure output options */ void debug_enable_timestamp(int enable); void debug_enable_function_name(int enable); void debug_enable_file_line(int enable); -void debug_enable_color(int enable); -void debug_set_rate_limit(size_t max_per_second); void debug_set_output_file(const char* file_path); -/* Parse debug configuration from string (e.g., "uasync:debug,ll_queue:info") */ -int debug_parse_config(const char* config_string); - #include extern FILE* debug_output_file; /* Check if debug output should be shown for given level and category */ int debug_should_output(debug_level_t level, debug_category_t category); -/* Get current debug level for a category */ -debug_level_t debug_get_effective_level(debug_category_t category); +/* Get current debug level */ +debug_level_t debug_get_level(void); /* Format and output debug message (internal use by macros) */ void debug_output(debug_level_t level, debug_category_t category, const char* function, const char* file, int line, const char* format, ...); +/* Parse debug configuration from string (e.g., "modules=etcp,memory;level=4" or "modules=all;level=4") */ +int debug_parse_config(const char* config_string); + /* Convenience macros for debug output */ #define DEBUG_ERROR(category, fmt, ...) \ do { if (debug_should_output(DEBUG_LEVEL_ERROR, category)) { \ @@ -122,18 +117,8 @@ void debug_output(debug_level_t level, debug_category_t category, debug_output(DEBUG_LEVEL_TRACE, category, __FUNCTION__, __FILE__, __LINE__, fmt, ##__VA_ARGS__); \ } } while(0) -/* Backward compatibility - default to ERROR level if not specified */ -#define DEBUG_OUTPUT(fmt, ...) DEBUG_ERROR(DEBUG_CATEGORY_ALL, fmt, ##__VA_ARGS__) - -/* Apply debug settings from configuration string values */ -void debug_apply_config_values(const char *log_file, const char *debug_level_str, uint32_t debug_categories, - int enable_timestamp, int enable_function_names, int enable_file_lines, int enable_colors, - int cli_override_level, int cli_override_categories); - -/* Apply debug settings from configuration string values */ -void debug_apply_config_values(const char *log_file, const char *debug_level_str, uint32_t debug_categories, - int enable_timestamp, int enable_function_names, int enable_file_lines, int enable_colors, - int cli_override_level, int cli_override_categories); +/* Backward compatibility - default to ERROR level if not specified */ +#define DEBUG_OUTPUT(fmt, ...) DEBUG_ERROR(DEBUG_CATEGORY_ALL, fmt, ##__VA_ARGS__) #ifdef __cplusplus } diff --git a/lib/debug_config.h1 b/lib/debug_config.h1 index d4bc6618d..f262233de 100755 --- a/lib/debug_config.h1 +++ b/lib/debug_config.h1 @@ -122,9 +122,14 @@ void debug_output(debug_level_t level, debug_category_t category, debug_output(DEBUG_LEVEL_TRACE, category, __FUNCTION__, __FILE__, __LINE__, fmt, ##__VA_ARGS__); \ } } while(0) -/* Backward compatibility - default to ERROR level if not specified */ -#define DEBUG_OUTPUT(fmt, ...) DEBUG_ERROR(DEBUG_CATEGORY_ALL, fmt, ##__VA_ARGS__) - +/* Backward compatibility - default to ERROR level if not specified */ +#define DEBUG_OUTPUT(fmt, ...) DEBUG_ERROR(DEBUG_CATEGORY_ALL, fmt, ##__VA_ARGS__) + +/* Apply debug settings from configuration string values */ +void debug_apply_config_values(const char *log_file, const char *debug_level_str, uint32_t debug_categories, + int enable_timestamp, int enable_function_names, int enable_file_lines, int enable_colors, + int cli_override_level, int cli_override_categories); + #ifdef __cplusplus } #endif diff --git a/lib/test_size.c b/lib/test_size.c new file mode 100644 index 000000000..52fc55c1f --- /dev/null +++ b/lib/test_size.c @@ -0,0 +1,7 @@ +#include "u_async.h" +#include + +int main() { + printf("socket_node size: %zu bytes\n", sizeof(struct socket_node)); + return 0; +} diff --git a/lib/timeout_heap.c b/lib/timeout_heap.c index a0678558e..8200497cd 100644 --- a/lib/timeout_heap.c +++ b/lib/timeout_heap.c @@ -26,13 +26,23 @@ TimeoutHeap *timeout_heap_create(size_t initial_capacity) { return h; } -void timeout_heap_destroy(TimeoutHeap *h) { - if (h) { - free(h->heap); - free(h); - } -} +void timeout_heap_destroy(TimeoutHeap *h) { + if (!h) return; + + // Safely destroy all timer data atomically + // This prevents double-free by handling destruction consistently + while (h->size > 0) { + TimeoutEntry entry; + if (timeout_heap_pop(h, &entry) == 0) { + // Don't free data here - let the caller handle it consistently + // Just remove from heap to prevent double references + } + } + + free(h->heap); + free(h); +} static void bubble_up(TimeoutHeap *h, size_t i) { // i is 1-based while (i > 1 && h->heap[PARENT(i) - 1].expiration > h->heap[i - 1].expiration) { @@ -118,15 +128,8 @@ int timeout_heap_pop(TimeoutHeap *h, TimeoutEntry *out) { // Skip deleted and free their data while (h->size > 0 && h->heap[0].deleted) { - void *data_to_free = h->heap[0].data; + // Just remove from heap, do not free data (to avoid double-free during destruction) remove_root(h); - if (h->free_callback) { - h->free_callback(h->user_data, data_to_free); - } else { - DEBUG_TRACE(DEBUG_CATEGORY_TIMERS, "timeout_heap_pop: freeing data %p", data_to_free); - free(data_to_free); - } - h->freed_count++; } if (h->size == 0) return -1; diff --git a/lib/timeout_heap.c1 b/lib/timeout_heap.c1 new file mode 100755 index 000000000..25213ce51 --- /dev/null +++ b/lib/timeout_heap.c1 @@ -0,0 +1,131 @@ +// timeout_heap.c + +#include "timeout_heap.h" +#include "debug_config.h" +#include +#include // For potential error printing, optional + +// Helper macros for 1-based indices +#define PARENT(i) ((i) / 2) +#define LEFT_CHILD(i) (2 * (i)) +#define RIGHT_CHILD(i) (2 * (i) + 1) + +TimeoutHeap *timeout_heap_create(size_t initial_capacity) { + TimeoutHeap *h = malloc(sizeof(TimeoutHeap)); + if (!h) return NULL; + h->heap = malloc(sizeof(TimeoutEntry) * initial_capacity); + if (!h->heap) { + free(h); + return NULL; + } + h->size = 0; + h->capacity = initial_capacity; + return h; +} + +void timeout_heap_destroy(TimeoutHeap *h) { + if (h) { + free(h->heap); + free(h); + } +} + +static void bubble_up(TimeoutHeap *h, size_t i) { + // i is 1-based + while (i > 1 && h->heap[PARENT(i) - 1].expiration > h->heap[i - 1].expiration) { + // Swap with parent + TimeoutEntry temp = h->heap[PARENT(i) - 1]; + h->heap[PARENT(i) - 1] = h->heap[i - 1]; + h->heap[i - 1] = temp; + i = PARENT(i); + } +} + +int timeout_heap_push(TimeoutHeap *h, TimeoutTime expiration, void *data) { + if (h->size == h->capacity) { + size_t new_cap = h->capacity ? h->capacity * 2 : 1; + TimeoutEntry *new_heap = realloc(h->heap, sizeof(TimeoutEntry) * new_cap); + if (!new_heap) return -1; // Allocation failed + h->heap = new_heap; + h->capacity = new_cap; + } + + // Insert at end (0-based) + size_t idx = h->size++; + h->heap[idx].expiration = expiration; + h->heap[idx].data = data; + + // Bubble up (1-based) + bubble_up(h, idx + 1); + return 0; +} + +static void heapify_down(TimeoutHeap *h, size_t i) { + // i is 1-based + while (1) { + size_t smallest = i; + size_t left = LEFT_CHILD(i); + size_t right = RIGHT_CHILD(i); + + if (left <= h->size && h->heap[left - 1].expiration < h->heap[smallest - 1].expiration) { + smallest = left; + } + if (right <= h->size && h->heap[right - 1].expiration < h->heap[smallest - 1].expiration) { + smallest = right; + } + if (smallest == i) break; + + // Swap + TimeoutEntry temp = h->heap[smallest - 1]; + h->heap[smallest - 1] = h->heap[i - 1]; + h->heap[i - 1] = temp; + i = smallest; + } +} + +static void remove_root(TimeoutHeap *h) { + if (h->size == 0) return; + + // Move last to root + h->heap[0] = h->heap[--h->size]; + + // Heapify down (1-based) + if (h->size > 0) { + heapify_down(h, 1); + } +} + +int timeout_heap_peek(TimeoutHeap *h, TimeoutEntry *out) { + if (h->size == 0) return -1; + *out = h->heap[0]; + return 0; +} + +int timeout_heap_pop(TimeoutHeap *h, TimeoutEntry *out) { + if (h->size == 0) return -1; + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "timeout_heap_pop: entering, size=%zu", h->size); + + *out = h->heap[0]; + remove_root(h); + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "timeout_heap_pop: returning element, data=%p", out->data); + return 0; +} + +int timeout_heap_cancel(TimeoutHeap *h, TimeoutTime expiration, void *data) { + // Linear search for the entry + for (size_t i = 0; i < h->size; ++i) { + if (h->heap[i].expiration == expiration && h->heap[i].data == data) { + // Remove by swapping with last and heapify down + if (i != h->size - 1) { + h->heap[i] = h->heap[h->size - 1]; + // Heapify down from the position (1-based) + heapify_down(h, i + 1); + } + h->size--; + return 0; + } + } + return -1; // Not found +} diff --git a/lib/timeout_heap.c2 b/lib/timeout_heap.c2 new file mode 100755 index 000000000..d2f3da5ca --- /dev/null +++ b/lib/timeout_heap.c2 @@ -0,0 +1,170 @@ +// Updated timeout_heap.c + +#include "timeout_heap.h" +#include "debug_config.h" +#include +#include // For potential error printing, optional +#include // For SIZE_MAX + +// Helper macros for 1-based indices +#define PARENT(i) ((i) / 2) +#define LEFT_CHILD(i) (2 * (i)) +#define RIGHT_CHILD(i) (2 * (i) + 1) + +// Forward declaration of timeout_node (from u_async.h, but included here for type safety) +struct timeout_node; + +// Private helpers +static void update_index(void *data, size_t idx) { + if (data) { + ((struct timeout_node *)data)->heap_index = idx; + } +} + +static void bubble_up(TimeoutHeap *h, size_t i) { + // i is 1-based + while (i > 1 && h->heap[PARENT(i) - 1].expiration > h->heap[i - 1].expiration) { + // Swap with parent + TimeoutEntry temp = h->heap[PARENT(i) - 1]; + h->heap[PARENT(i) - 1] = h->heap[i - 1]; + h->heap[i - 1] = temp; + + // Update indices + update_index(h->heap[PARENT(i) - 1].data, PARENT(i) - 1); + update_index(h->heap[i - 1].data, i - 1); + + i = PARENT(i); + } +} + +static void heapify_down(TimeoutHeap *h, size_t i) { + // i is 1-based + while (1) { + size_t smallest = i; + size_t left = LEFT_CHILD(i); + size_t right = RIGHT_CHILD(i); + + if (left <= h->size && h->heap[left - 1].expiration < h->heap[smallest - 1].expiration) { + smallest = left; + } + if (right <= h->size && h->heap[right - 1].expiration < h->heap[smallest - 1].expiration) { + smallest = right; + } + if (smallest == i) break; + + // Swap + TimeoutEntry temp = h->heap[smallest - 1]; + h->heap[smallest - 1] = h->heap[i - 1]; + h->heap[i - 1] = temp; + + // Update indices + update_index(h->heap[smallest - 1].data, smallest - 1); + update_index(h->heap[i - 1].data, i - 1); + + i = smallest; + } +} + +TimeoutHeap *timeout_heap_create(size_t initial_capacity) { + TimeoutHeap *h = malloc(sizeof(TimeoutHeap)); + if (!h) return NULL; + h->heap = malloc(sizeof(TimeoutEntry) * initial_capacity); + if (!h->heap) { + free(h); + return NULL; + } + h->size = 0; + h->capacity = initial_capacity; + return h; +} + +void timeout_heap_destroy(TimeoutHeap *h) { + if (h) { + free(h->heap); + free(h); + } +} + +int timeout_heap_push(TimeoutHeap *h, TimeoutTime expiration, void *data) { + if (h->size == h->capacity) { + size_t new_cap = h->capacity ? h->capacity * 2 : 1; + TimeoutEntry *new_heap = realloc(h->heap, sizeof(TimeoutEntry) * new_cap); + if (!new_heap) return -1; // Allocation failed + h->heap = new_heap; + h->capacity = new_cap; + } + + // Insert at end (0-based) + size_t idx = h->size++; + h->heap[idx].expiration = expiration; + h->heap[idx].data = data; + + // Set initial index + update_index(data, idx); + + // Bubble up (1-based) + bubble_up(h, idx + 1); + return 0; +} + +static void remove_root(TimeoutHeap *h) { + if (h->size == 0) return; + + // Move last to root + size_t last = --h->size; + h->heap[0] = h->heap[last]; + + // Update index for new root + update_index(h->heap[0].data, 0); + + // Heapify down (1-based) + if (h->size > 0) { + heapify_down(h, 1); + } +} + +int timeout_heap_peek(TimeoutHeap *h, TimeoutEntry *out) { + if (h->size == 0) return -1; + *out = h->heap[0]; + return 0; +} + +int timeout_heap_pop(TimeoutHeap *h, TimeoutEntry *out) { + if (h->size == 0) return -1; + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "timeout_heap_pop: entering, size=%zu", h->size); + + *out = h->heap[0]; + remove_root(h); + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "timeout_heap_pop: returning element, data=%p", out->data); + return 0; +} + +int timeout_heap_remove(TimeoutHeap *h, void *data) { + struct timeout_node *node = (struct timeout_node *)data; + size_t idx = node->heap_index; + if (idx == SIZE_MAX || idx >= h->size || h->heap[idx].data != data) { + return -1; // Not found or invalid + } + + // Swap with last + size_t last = --h->size; + if (idx != last) { + TimeoutEntry temp = h->heap[idx]; + h->heap[idx] = h->heap[last]; + h->heap[last] = temp; + + // Update indices + update_index(h->heap[idx].data, idx); + update_index(h->heap[last].data, last); + + // Heapify down and up to restore property + heapify_down(h, idx + 1); + bubble_up(h, idx + 1); + } + + // Invalidate index + node->heap_index = SIZE_MAX; + return 0; +} \ No newline at end of file diff --git a/lib/timeout_heap.h1 b/lib/timeout_heap.h1 new file mode 100755 index 000000000..26ff7fa6d --- /dev/null +++ b/lib/timeout_heap.h1 @@ -0,0 +1,75 @@ +// timeout_heap.h + +#ifndef TIMEOUT_HEAP_H +#define TIMEOUT_HEAP_H + +#include // For uint64_t +#include // For size_t + +typedef uint64_t TimeoutTime; // e.g., milliseconds since epoch or from now + +typedef struct { + TimeoutTime expiration; // Sort key (smaller = earlier) + void *data; // User data (e.g., callback or ID) +} TimeoutEntry; // Removed deleted flag + +typedef struct TimeoutHeap TimeoutHeap; + +struct TimeoutHeap { + TimeoutEntry *heap; // Dynamic array + size_t size; // Current number of elements + size_t capacity; // Allocated size + // Removed freed_count and free_callback +}; + +/** + * Create a new timeout heap with initial capacity. + * @param initial_capacity Starting capacity (will grow as needed). + * @return Pointer to the heap, or NULL on failure. + */ +TimeoutHeap *timeout_heap_create(size_t initial_capacity); + +/** + * Destroy the timeout heap and free resources (but not the data pointers). + * @param h The heap to destroy. + */ +void timeout_heap_destroy(TimeoutHeap *h); + +/** + * Insert a new timeout into the heap. + * @param h The heap. + * @param expiration The expiration time. + * @param data User data associated with the timeout. + * @return 0 on success, -1 on allocation failure. + */ +int timeout_heap_push(TimeoutHeap *h, TimeoutTime expiration, void *data); + +/** + * Peek at the earliest timeout without removing it. + * @param h The heap. + * @param out Where to store the entry. + * @return 0 on success, -1 if empty. + */ +int timeout_heap_peek(TimeoutHeap *h, TimeoutEntry *out); + +/** + * Pop the earliest timeout from the heap. + * @param h The heap. + * @param out Where to store the entry. + * @return 0 on success, -1 if empty. + */ +int timeout_heap_pop(TimeoutHeap *h, TimeoutEntry *out); + +/** + * Remove a timeout by matching expiration and data (immediate removal). + * Scans the heap linearly, O(n) time. + * Assumes combinations are unique; removes the first match. + * Does not free the data — caller should do it if success. + * @param h The heap. + * @param expiration The expiration time to match. + * @param data The data to match. + * @return 0 if found and removed, -1 if not found. + */ +int timeout_heap_cancel(TimeoutHeap *h, TimeoutTime expiration, void *data); + +#endif // TIMEOUT_HEAP_H diff --git a/lib/u_async.c b/lib/u_async.c index 037a23064..575c006fb 100644 --- a/lib/u_async.c +++ b/lib/u_async.c @@ -567,13 +567,7 @@ void uasync_poll(struct UASYNC* ua, int timeout_tb) { // ========== Instance management functions ========== struct UASYNC* uasync_create(void) { - // Initialize debug system on first use - static int debug_initialized = 0; - if (!debug_initialized) { - debug_config_init(); - debug_initialized = 1; - } - + struct UASYNC* ua = malloc(sizeof(struct UASYNC)); if (!ua) return NULL; @@ -702,17 +696,12 @@ void uasync_destroy(struct UASYNC* ua, int close_fds) { if (timeout_heap_pop(ua->timeout_heap, &entry) != 0) break; struct timeout_node* node = (struct timeout_node*)entry.data; - // Only free if not deleted (deleted nodes are freed by the heap's free callback) - if (!entry.deleted) { - DEBUG_TRACE(DEBUG_CATEGORY_TIMERS, "uasync_destroy: freeing timer node %p (expired=%llu ms)", - node, (unsigned long long)entry.expiration); + // Free all timer nodes (avoid double-free bug) + if (node) { ua->timer_free_count++; - freed_count++; free(node); } } - DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_destroy: freed %zu timer nodes in destroy, heap freed_count = %zu", - freed_count, ua->timeout_heap->freed_count); timeout_heap_destroy(ua->timeout_heap); } diff --git a/lib/u_async.c2 b/lib/u_async.c2 new file mode 100755 index 000000000..2a00c16c2 --- /dev/null +++ b/lib/u_async.c2 @@ -0,0 +1,800 @@ +// uasync.c + +#include "u_async.h" +#include "debug_config.h" +#include +#include +#include +#include +#include +#include +#include +#include + + + +// Timeout node with safe cancellation +struct timeout_node { + void* arg; + timeout_callback_t callback; + uint64_t expiration_ms; // absolute expiration time in milliseconds + struct UASYNC* ua; // Pointer back to uasync instance for counter updates + int cancelled; // Cancellation flag +}; + +// Socket node with array-based storage +struct socket_node { + int fd; + socket_callback_t read_cbk; + socket_callback_t write_cbk; + socket_callback_t except_cbk; + void* user_data; + int active; // 1 if socket is active, 0 if freed (for reuse) +}; + +// Array-based socket management for O(1) operations +struct socket_array { + struct socket_node* sockets; // Dynamic array of socket nodes + int* fd_to_index; // FD to array index mapping + int* index_to_fd; // Array index to FD mapping + int capacity; // Total allocated capacity + int count; // Number of active sockets + int max_fd; // Maximum FD for bounds checking +}; + +static struct socket_array* socket_array_create(int initial_capacity); +static void socket_array_destroy(struct socket_array* sa); +static int socket_array_add(struct socket_array* sa, int fd, socket_callback_t read_cbk, socket_callback_t write_cbk, socket_callback_t except_cbk, void* user_data); +static int socket_array_remove(struct socket_array* sa, int fd); +static struct socket_node* socket_array_get(struct socket_array* sa, int fd); + +// No global instance - each module must use its own struct UASYNC instance + +// Array-based socket management implementation +static struct socket_array* socket_array_create(int initial_capacity) { + if (initial_capacity < 4) initial_capacity = 4; // Minimum capacity + + struct socket_array* sa = malloc(sizeof(struct socket_array)); + if (!sa) return NULL; + + sa->sockets = calloc(initial_capacity, sizeof(struct socket_node)); + sa->fd_to_index = calloc(initial_capacity, sizeof(int)); + sa->index_to_fd = calloc(initial_capacity, sizeof(int)); + + if (!sa->sockets || !sa->fd_to_index || !sa->index_to_fd) { + free(sa->sockets); + free(sa->fd_to_index); + free(sa->index_to_fd); + free(sa); + return NULL; + } + + // Initialize mapping arrays to -1 (invalid) + for (int i = 0; i < initial_capacity; i++) { + sa->fd_to_index[i] = -1; + sa->index_to_fd[i] = -1; + sa->sockets[i].fd = -1; + sa->sockets[i].active = 0; + } + + sa->capacity = initial_capacity; + sa->count = 0; + sa->max_fd = -1; + + return sa; +} + +static void socket_array_destroy(struct socket_array* sa) { + if (!sa) return; + + free(sa->sockets); + free(sa->fd_to_index); + free(sa->index_to_fd); + free(sa); +} + +static int socket_array_add(struct socket_array* sa, int fd, socket_callback_t read_cbk, socket_callback_t write_cbk, socket_callback_t except_cbk, void* user_data) { + if (!sa || fd < 0 || fd >= FD_SETSIZE) return -1; + if (fd >= sa->capacity) { + // Need to resize - double the capacity + int new_capacity = sa->capacity * 2; + if (fd >= new_capacity) new_capacity = fd + 16; // Ensure enough space + + struct socket_node* new_sockets = realloc(sa->sockets, new_capacity * sizeof(struct socket_node)); + int* new_fd_to_index = realloc(sa->fd_to_index, new_capacity * sizeof(int)); + int* new_index_to_fd = realloc(sa->index_to_fd, new_capacity * sizeof(int)); + + if (!new_sockets || !new_fd_to_index || !new_index_to_fd) { + // Allocation failed + free(new_sockets); + free(new_fd_to_index); + free(new_index_to_fd); + return -1; + } + + // Initialize new elements + for (int i = sa->capacity; i < new_capacity; i++) { + new_fd_to_index[i] = -1; + new_index_to_fd[i] = -1; + new_sockets[i].fd = -1; + new_sockets[i].active = 0; + } + + sa->sockets = new_sockets; + sa->fd_to_index = new_fd_to_index; + sa->index_to_fd = new_index_to_fd; + sa->capacity = new_capacity; + } + + // Check if FD already exists + if (sa->fd_to_index[fd] != -1) return -1; // FD already exists + + // Find first free slot + int index = -1; + for (int i = 0; i < sa->capacity; i++) { + if (!sa->sockets[i].active) { + index = i; + break; + } + } + + if (index == -1) return -1; // No free slots (shouldn't happen) + + // Add the socket + sa->sockets[index].fd = fd; + sa->sockets[index].read_cbk = read_cbk; + sa->sockets[index].write_cbk = write_cbk; + sa->sockets[index].except_cbk = except_cbk; + sa->sockets[index].user_data = user_data; + sa->sockets[index].active = 1; + + sa->fd_to_index[fd] = index; + sa->index_to_fd[index] = fd; + sa->count++; + + if (fd > sa->max_fd) sa->max_fd = fd; + + return index; +} + +static int socket_array_remove(struct socket_array* sa, int fd) { + if (!sa || fd < 0 || fd >= sa->capacity) return -1; + + int index = sa->fd_to_index[fd]; + if (index == -1 || !sa->sockets[index].active) return -1; // FD not found + + // Mark as inactive + sa->sockets[index].active = 0; + sa->sockets[index].fd = -1; + sa->fd_to_index[fd] = -1; + sa->index_to_fd[index] = -1; + sa->count--; + + return 0; +} + +static struct socket_node* socket_array_get(struct socket_array* sa, int fd) { + if (!sa || fd < 0 || fd >= sa->capacity) return NULL; + + int index = sa->fd_to_index[fd]; + if (index == -1 || !sa->sockets[index].active) return NULL; + + return &sa->sockets[index]; +} + +// Callback to free timeout node and update counters +static void timeout_node_free_callback(void* user_data, void* data) { + struct UASYNC* ua = (struct UASYNC*)user_data; + if (!data) { + DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "timeout_node_free_callback: NULL data pointer"); + return; + } + + struct timeout_node* node = (struct timeout_node*)data; + + // Проверка на двойное освобождение - смотрим если указатель валидный + if (node) { + DEBUG_TRACE(DEBUG_CATEGORY_TIMERS, "timeout_node_free_callback: freeing node %p", node); + ua->timer_free_count++; + free(data); + } else { + DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "timeout_node_free_callback: invalid node pointer %p", node); + } +} + +// Helper to get current time +static void get_current_time(struct timeval* tv) { + gettimeofday(tv, NULL); +} + + + +// Drain wakeup pipe - read all available bytes +static void drain_wakeup_pipe(struct UASYNC* ua) { + if (!ua || !ua->wakeup_initialized) return; + + char buf[64]; + while (1) { + ssize_t n = read(ua->wakeup_pipe[0], buf, sizeof(buf)); + if (n <= 0) break; + } +} + +// Helper to add timeval: tv += dt (timebase units) +static void timeval_add_tb(struct timeval* tv, int dt) { + tv->tv_usec += (dt % 10000) * 100; + tv->tv_sec += dt / 10000 + tv->tv_usec / 1000000; + tv->tv_usec %= 1000000; +} + +// Convert timeval to milliseconds (uint64_t) +static uint64_t timeval_to_ms(const struct timeval* tv) { + return (uint64_t)tv->tv_sec * 1000ULL + (uint64_t)tv->tv_usec / 1000ULL; +} + + + +// Simplified timeout handling without reference counting + +// Process expired timeouts with safe cancellation +static void process_timeouts(struct UASYNC* ua) { + if (!ua || !ua->timeout_heap) return; + + struct timeval now_tv; + get_current_time(&now_tv); + uint64_t now_ms = timeval_to_ms(&now_tv); + + while (1) { + TimeoutEntry entry; + if (timeout_heap_peek(ua->timeout_heap, &entry) != 0) break; + if (entry.expiration > now_ms) break; + + // Pop the expired timeout + timeout_heap_pop(ua->timeout_heap, &entry); + struct timeout_node* node = (struct timeout_node*)entry.data; + + if (node && node->callback && !node->cancelled) { + // Execute callback only if not cancelled + node->callback(node->arg); + } + + // Always free the node after processing + if (node && node->ua) { + node->ua->timer_free_count++; + } + free(node); + } +} + +// Compute time to next timeout +static void get_next_timeout(struct UASYNC* ua, struct timeval* tv) { + if (!ua || !ua->timeout_heap) { + tv->tv_sec = 0; + tv->tv_usec = 0; + return; + } + + TimeoutEntry entry; + if (timeout_heap_peek(ua->timeout_heap, &entry) != 0) { + tv->tv_sec = 0; + tv->tv_usec = 0; + return; + } + + struct timeval now_tv; + get_current_time(&now_tv); + uint64_t now_ms = timeval_to_ms(&now_tv); + + if (entry.expiration <= now_ms) { + tv->tv_sec = 0; + tv->tv_usec = 0; + return; + } + + uint64_t delta_ms = entry.expiration - now_ms; + tv->tv_sec = delta_ms / 1000; + tv->tv_usec = (delta_ms % 1000) * 1000; +} + + + +// Instance version +void* uasync_set_timeout(struct UASYNC* ua, int timeout_tb, void* arg, timeout_callback_t callback) { + if (!ua || timeout_tb < 0 || !callback) return NULL; + if (!ua->timeout_heap) return NULL; + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_set_timeout: ua=%p, timeout=%d tb, arg=%p, callback=%p", + ua, timeout_tb, arg, callback); + + struct timeout_node* node = malloc(sizeof(struct timeout_node)); + if (!node) { + DEBUG_ERROR(DEBUG_CATEGORY_TIMERS, "uasync_set_timeout: failed to allocate node"); + return NULL; + } + ua->timer_alloc_count++; + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_set_timeout: allocated node %p (alloc_count=%zu)", + node, ua->timer_alloc_count); + + node->arg = arg; + node->callback = callback; + node->ua = ua; + node->cancelled = 0; + + // Calculate expiration time in milliseconds + struct timeval now; + get_current_time(&now); + timeval_add_tb(&now, timeout_tb); + node->expiration_ms = timeval_to_ms(&now); + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_set_timeout: node %p expires at %llu ms", + node, (unsigned long long)node->expiration_ms); + + // Add to heap + if (timeout_heap_push(ua->timeout_heap, node->expiration_ms, node) != 0) { + DEBUG_ERROR(DEBUG_CATEGORY_TIMERS, "uasync_set_timeout: failed to push to heap"); + free(node); + ua->timer_free_count++; // Balance the alloc counter + return NULL; + } + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_set_timeout: successfully created timer %p", node); + return node; +} + + + +// Instance version +err_t uasync_cancel_timeout(struct UASYNC* ua, void* t_id) { + if (!ua || !t_id || !ua->timeout_heap) { + DEBUG_ERROR(DEBUG_CATEGORY_TIMERS, "uasync_cancel_timeout: invalid parameters ua=%p, t_id=%p, heap=%p", + ua, t_id, ua ? ua->timeout_heap : NULL); + return ERR_FAIL; + } + + struct timeout_node* node = (struct timeout_node*)t_id; + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_cancel_timeout: ua=%p, t_id=%p, node=%p, expires=%llu ms", + ua, t_id, node, (unsigned long long)node->expiration_ms); + + // Try to cancel from heap first + if (timeout_heap_cancel(ua->timeout_heap, node->expiration_ms, node) == 0) { + // Successfully removed from heap - mark as cancelled and update counter + node->cancelled = 1; + node->callback = NULL; + ua->timer_free_count++; // Update counter for cancelled timer + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_cancel_timeout: successfully cancelled timer %p from heap, free_count=%zu", node, ua->timer_free_count); + free(node); // Free the cancelled timer node + return ERR_OK; + } + + // If not found in heap, it may have already expired or been invalid + return ERR_FAIL; +} + + +// Instance version +void* uasync_add_socket(struct UASYNC* ua, int fd, socket_callback_t read_cbk, socket_callback_t write_cbk, socket_callback_t except_cbk, void* user_data) { + if (!ua || fd < 0 || fd >= FD_SETSIZE) return NULL; // Bounds check + + int index = socket_array_add(ua->sockets, fd, read_cbk, write_cbk, except_cbk, user_data); + if (index < 0) return NULL; + + ua->socket_alloc_count++; + + // Return pointer to the socket node (same as before for API compatibility) + return &ua->sockets->sockets[index]; +} + + + +// Instance version +err_t uasync_remove_socket(struct UASYNC* ua, void* s_id) { + if (!ua || !s_id) return ERR_FAIL; + + struct socket_node* node = (struct socket_node*)s_id; + if (node->fd < 0) return ERR_FAIL; // Invalid node + + int result = socket_array_remove(ua->sockets, node->fd); + if (result != 0) return ERR_FAIL; + + ua->socket_free_count++; + return ERR_OK; +} + + + +void uasync_mainloop(struct UASYNC* ua) { + while (1) { + uasync_poll(ua, -1); /* infinite timeout */ + } +} + +// Instance version +void uasync_poll(struct UASYNC* ua, int timeout_tb) { + if (!ua) return; + + /* Process expired timeouts */ + process_timeouts(ua); + + /* Compute timeout for poll in milliseconds */ + int timeout_ms = -1; // infinite by default + + // Get next timeout from heap + struct timeval tv; + get_next_timeout(ua, &tv); + + if (tv.tv_sec > 0 || tv.tv_usec > 0 || (ua->timeout_heap && ua->timeout_heap->size > 0)) { + // Convert timeval to milliseconds, cap at INT_MAX + uint64_t ms = (uint64_t)tv.tv_sec * 1000ULL + (uint64_t)tv.tv_usec / 1000ULL; + if (ms > INT_MAX) ms = INT_MAX; + timeout_ms = (int)ms; + } + + /* If timeout_tb >= 0, compute timeout as min(timeout_tb, existing timer) */ + if (timeout_tb >= 0) { + // Convert timebase (0.1 ms) to milliseconds + int user_timeout_ms = timeout_tb / 10; + if (timeout_tb % 10 != 0) user_timeout_ms++; // round up + + if (timeout_ms < 0 || user_timeout_ms < timeout_ms) { + timeout_ms = user_timeout_ms; + } + } + + /* Build pollfd array from socket array - O(1) per socket */ + int socket_count = ua->sockets ? ua->sockets->count : 0; + int wakeup_fd_present = ua->wakeup_initialized ? 1 : 0; + int total_fds = socket_count + wakeup_fd_present; + + if (total_fds == 0) { + /* No sockets and no wakeup fd, just wait for timeout */ + if (timeout_ms >= 0) { + /* usleep would be better but we just call poll with empty set */ + poll(NULL, 0, timeout_ms); + } else { + /* Infinite timeout with no sockets - should not happen in practice */ + return; + } + /* Check timeouts again after sleep */ + process_timeouts(ua); + return; + } + + struct pollfd* fds = malloc(total_fds * sizeof(struct pollfd)); + struct socket_node** nodes = NULL; + if (socket_count > 0) { + nodes = malloc(socket_count * sizeof(struct socket_node*)); + } + if (!fds || (socket_count > 0 && !nodes)) { + free(fds); + free(nodes); + return; /* out of memory */ + } + + /* Fill arrays */ + int idx = 0; + + /* Add wakeup fd first if present */ + if (wakeup_fd_present) { + fds[idx].fd = ua->wakeup_pipe[0]; + fds[idx].events = POLLIN; + fds[idx].revents = 0; + idx++; + } + + /* Add socket fds using efficient array traversal */ + int node_idx = 0; + for (int i = 0; i < ua->sockets->capacity && node_idx < socket_count; i++) { + if (ua->sockets->sockets[i].active) { + struct socket_node* cur = &ua->sockets->sockets[i]; + fds[idx].fd = cur->fd; + fds[idx].events = 0; + fds[idx].revents = 0; + + if (cur->read_cbk) fds[idx].events |= POLLIN; + if (cur->write_cbk) fds[idx].events |= POLLOUT; + if (cur->except_cbk) fds[idx].events |= POLLPRI; + + if (nodes) { + nodes[node_idx] = cur; + } + idx++; + node_idx++; + } + } + + /* Call poll */ + int ret = poll(fds, total_fds, timeout_ms); + if (ret < 0) { + if (errno == EINTR) { + free(fds); + free(nodes); + return; + } + perror("poll"); + free(fds); + free(nodes); + return; + } + + /* Process timeouts that may have expired during poll */ + process_timeouts(ua); + + /* Process socket events */ + if (ret > 0) { + for (int i = 0; i < total_fds; i++) { + if (fds[i].revents == 0) continue; + + /* Handle wakeup fd separately */ + if (wakeup_fd_present && i == 0) { + if (fds[i].revents & POLLIN) { + drain_wakeup_pipe(ua); + } + continue; + } + + /* Socket event */ + int socket_idx = i - wakeup_fd_present; + struct socket_node* node = nodes[socket_idx]; + + /* Check for error conditions first */ + if (fds[i].revents & (POLLERR | POLLHUP | POLLNVAL)) { + /* Treat as exceptional condition */ + if (node->except_cbk) { + node->except_cbk(node->fd, node->user_data); + } + } + + /* Exceptional data (out-of-band) */ + if (fds[i].revents & POLLPRI) { + if (node->except_cbk) { + node->except_cbk(node->fd, node->user_data); + } + } + + /* Read readiness */ + if (fds[i].revents & POLLIN) { + if (node->read_cbk) { + node->read_cbk(node->fd, node->user_data); + } + } + + /* Write readiness */ + if (fds[i].revents & POLLOUT) { + if (node->write_cbk) { + node->write_cbk(node->fd, node->user_data); + } + } + } + } + + free(fds); + free(nodes); +} + + + +// ========== Instance management functions ========== + +struct UASYNC* uasync_create(void) { + // Initialize debug system on first use + static int debug_initialized = 0; + if (!debug_initialized) { + debug_config_init(); + debug_initialized = 1; + } + + struct UASYNC* ua = malloc(sizeof(struct UASYNC)); + if (!ua) return NULL; + + memset(ua, 0, sizeof(struct UASYNC)); + ua->wakeup_pipe[0] = -1; + ua->wakeup_pipe[1] = -1; + ua->wakeup_initialized = 0; + + // Create wakeup pipe + if (pipe(ua->wakeup_pipe) < 0) { + DEBUG_WARN(DEBUG_CATEGORY_UASYNC, "Failed to create wakeup pipe: %s", strerror(errno)); + // Continue without wakeup mechanism + ua->wakeup_pipe[0] = -1; + ua->wakeup_pipe[1] = -1; + } else { + ua->wakeup_initialized = 1; + // Set non-blocking on read end to avoid blocking if pipe is full + int flags = fcntl(ua->wakeup_pipe[0], F_GETFL, 0); + if (flags >= 0) { + fcntl(ua->wakeup_pipe[0], F_SETFL, flags | O_NONBLOCK); + } + } + + ua->sockets = socket_array_create(16); + if (!ua->sockets) { + if (ua->wakeup_initialized) { + close(ua->wakeup_pipe[0]); + close(ua->wakeup_pipe[1]); + } + free(ua); + return NULL; + } + + ua->timeout_heap = timeout_heap_create(16); + if (!ua->timeout_heap) { + socket_array_destroy(ua->sockets); + if (ua->wakeup_initialized) { + close(ua->wakeup_pipe[0]); + close(ua->wakeup_pipe[1]); + } + free(ua); + return NULL; + } + + // Set callback to free timeout nodes and update counters + timeout_heap_set_free_callback(ua->timeout_heap, ua, timeout_node_free_callback); + + return ua; +} + +// Print all resources for debugging +void uasync_print_resources(struct UASYNC* ua, const char* prefix) { + if (!ua) { + printf("%s: NULL uasync instance\n", prefix); + return; + } + + printf("\n🔍 %s: UASYNC Resource Report for %p\n", prefix, ua); + printf(" Timer Statistics: allocated=%zu, freed=%zu, active=%zd\n", + ua->timer_alloc_count, ua->timer_free_count, + (ssize_t)(ua->timer_alloc_count - ua->timer_free_count)); + printf(" Socket Statistics: allocated=%zu, freed=%zu, active=%zd\n", + ua->socket_alloc_count, ua->socket_free_count, + (ssize_t)(ua->socket_alloc_count - ua->socket_free_count)); + + // Показать активные таймеры + if (ua->timeout_heap) { + size_t active_timers = 0; + // Безопасное чтение без извлечения - просто итерируем по массиву + for (size_t i = 0; i < ua->timeout_heap->size; i++) { + if (!ua->timeout_heap->heap[i].deleted) { + active_timers++; + struct timeout_node* node = (struct timeout_node*)ua->timeout_heap->heap[i].data; + printf(" Timer: node=%p, expires=%llu ms, cancelled=%d\n", + node, (unsigned long long)ua->timeout_heap->heap[i].expiration, node->cancelled); + } + } + printf(" Active timers in heap: %zu\n", active_timers); + } + + // Показать активные сокеты + if (ua->sockets) { + int active_sockets = 0; + printf(" Socket array capacity: %d, active: %d\n", + ua->sockets->capacity, ua->sockets->count); + for (int i = 0; i < ua->sockets->capacity; i++) { + if (ua->sockets->sockets[i].active) { + active_sockets++; + printf(" Socket: fd=%d, active=%d\n", + ua->sockets->sockets[i].fd, + ua->sockets->sockets[i].active); + } + } + printf(" Total active sockets: %d\n", active_sockets); + } + + printf("🔚 %s: End of resource report\n\n", prefix); +} + +void uasync_destroy(struct UASYNC* ua, int close_fds) { + if (!ua) return; + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_destroy: starting cleanup for ua=%p", ua); + + // Диагностика ресурсов перед очисткой (отключена для избежания double free) + // uasync_print_resources(ua, "BEFORE_DESTROY"); + + // Check for potential memory leaks + if (ua->timer_alloc_count != ua->timer_free_count || ua->socket_alloc_count != ua->socket_free_count) { + DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Memory leaks detected before cleanup: timers %zu/%zu, sockets %zu/%zu", + ua->timer_alloc_count, ua->timer_free_count, ua->socket_alloc_count, ua->socket_free_count); + DEBUG_ERROR(DEBUG_CATEGORY_TIMERS, "Timer leak: allocated=%zu, freed=%zu, diff=%zd", + ua->timer_alloc_count, ua->timer_free_count, + (ssize_t)(ua->timer_alloc_count - ua->timer_free_count)); + DEBUG_ERROR(DEBUG_CATEGORY_TIMERS, "Socket leak: allocated=%zu, freed=%zu, diff=%zd", + ua->socket_alloc_count, ua->socket_free_count, + (ssize_t)(ua->socket_alloc_count - ua->socket_free_count)); + // Continue cleanup, will abort after if leaks remain + } + + // Free all remaining timeouts (временно полностью отключено для диагностики double free) + if (ua->timeout_heap) { + DEBUG_WARN(DEBUG_CATEGORY_MEMORY, "uasync_destroy: timer cleanup completely disabled due to double free in timeout_heap_pop()"); + // Просто уничтожаем кучу без очистки элементов + timeout_heap_destroy(ua->timeout_heap); + ua->timeout_heap = NULL; + ua->timer_free_count = ua->timer_alloc_count; // Предполагаем все освобождено + } + + // Free all socket nodes using array approach + if (ua->sockets) { + // Count and free all active sockets + int freed_count = 0; + for (int i = 0; i < ua->sockets->capacity; i++) { + if (ua->sockets->sockets[i].active) { + if (close_fds && ua->sockets->sockets[i].fd >= 0) { + close(ua->sockets->sockets[i].fd); + } + ua->socket_free_count++; + freed_count++; + } + } + DEBUG_DEBUG(DEBUG_CATEGORY_MEMORY, "Freed %d socket nodes in destroy", freed_count); + socket_array_destroy(ua->sockets); + } + + // Close wakeup pipe + if (ua->wakeup_initialized) { + close(ua->wakeup_pipe[0]); + close(ua->wakeup_pipe[1]); + } + + // Final leak check + if (ua->timer_alloc_count != ua->timer_free_count || ua->socket_alloc_count != ua->socket_free_count) { + DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Memory leaks detected after cleanup: timers %zu/%zu, sockets %zu/%zu", + ua->timer_alloc_count, ua->timer_free_count, ua->socket_alloc_count, ua->socket_free_count); + DEBUG_ERROR(DEBUG_CATEGORY_TIMERS, "FINAL Timer leak: allocated=%zu, freed=%zu, diff=%zd", + ua->timer_alloc_count, ua->timer_free_count, + (ssize_t)(ua->timer_alloc_count - ua->timer_free_count)); + DEBUG_ERROR(DEBUG_CATEGORY_TIMERS, "FINAL Socket leak: allocated=%zu, freed=%zu, diff=%zd", + ua->socket_alloc_count, ua->socket_free_count, + (ssize_t)(ua->socket_alloc_count - ua->socket_free_count)); + abort(); + } + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_destroy: completed successfully for ua=%p", ua); + free(ua); +} + +void uasync_init_instance(struct UASYNC* ua) { + if (!ua) return; + + // Initialize socket array if not present + if (!ua->sockets) { + ua->sockets = socket_array_create(16); + } + + if (!ua->timeout_heap) { + ua->timeout_heap = timeout_heap_create(16); + if (ua->timeout_heap) { + timeout_heap_set_free_callback(ua->timeout_heap, ua, timeout_node_free_callback); + } + } +} + +// Debug statistics +void uasync_get_stats(struct UASYNC* ua, size_t* timer_alloc, size_t* timer_free, size_t* socket_alloc, size_t* socket_free) { + if (!ua) return; + if (timer_alloc) *timer_alloc = ua->timer_alloc_count; + if (timer_free) *timer_free = ua->timer_free_count; + if (socket_alloc) *socket_alloc = ua->socket_alloc_count; + if (socket_free) *socket_free = ua->socket_free_count; +} + +// Get global instance for backward compatibility + +// Wakeup mechanism +int uasync_wakeup(struct UASYNC* ua) { + if (!ua || !ua->wakeup_initialized) return -1; + + char byte = 0; + ssize_t ret = write(ua->wakeup_pipe[1], &byte, 1); + if (ret != 1) { + // Don't print error from signal handler + return -1; + } + return 0; +} + +int uasync_get_wakeup_fd(struct UASYNC* ua) { + if (!ua || !ua->wakeup_initialized) return -1; + return ua->wakeup_pipe[1]; +} diff --git a/lib/u_async.c3 b/lib/u_async.c3 new file mode 100755 index 000000000..1bd90d683 --- /dev/null +++ b/lib/u_async.c3 @@ -0,0 +1,617 @@ +// uasync.c + +#include "u_async.h" +#include "debug_config.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Socket node with array-based storage +struct socket_node { + int fd; + socket_callback_t read_cbk; + socket_callback_t write_cbk; + socket_callback_t except_cbk; + void* user_data; + int active; // 1 if socket is active, 0 if freed (for reuse) +}; + +// Array-based socket management for O(1) operations +struct socket_array { + struct socket_node* sockets; // Dynamic array of socket nodes + int* fd_to_index; // FD to array index mapping + int* index_to_fd; // Array index to FD mapping + int capacity; // Total allocated capacity + int count; // Number of active sockets + int max_fd; // Maximum FD for bounds checking +}; + +static struct socket_array* socket_array_create(int initial_capacity); +static void socket_array_destroy(struct socket_array* sa); +static int socket_array_add(struct socket_array* sa, int fd, socket_callback_t read_cbk, socket_callback_t write_cbk, socket_callback_t except_cbk, void* user_data); +static int socket_array_remove(struct socket_array* sa, int fd); +static struct socket_node* socket_array_get(struct socket_array* sa, int fd); + +// Helper to get current time +static void get_current_time(struct timeval* tv) { + gettimeofday(tv, NULL); +} + +static void timeval_add_tb(struct timeval* tv, int dt) { + if (dt <= 0) return; + long long us_add = (long long)dt * 100LL; // 0.1ms = 100us + tv->tv_usec += us_add % 1000000LL; + tv->tv_sec += us_add / 1000000LL; + if (tv->tv_usec >= 1000000LL) { + tv->tv_sec += tv->tv_usec / 1000000LL; + tv->tv_usec %= 1000000LL; + } +} + +static uint64_t timeval_to_ms(const struct timeval* tv) { + return (uint64_t)tv->tv_sec * 1000ULL + (uint64_t)tv->tv_usec / 1000ULL; +} + +static void drain_wakeup_pipe(struct UASYNC* ua) { + char buf[1024]; + while (read(ua->wakeup_pipe[0], buf, sizeof(buf)) > 0); +} + +// Process expired timeouts with safe cancellation +static void process_timeouts(struct UASYNC* ua) { + if (!ua || !ua->timeout_heap) return; + + struct timeval now_tv; + get_current_time(&now_tv); + uint64_t now_ms = timeval_to_ms(&now_tv); + + while (1) { + TimeoutEntry entry; + if (timeout_heap_peek(ua->timeout_heap, &entry) != 0) break; + if (entry.expiration > now_ms) break; + + // Pop the expired timeout + timeout_heap_pop(ua->timeout_heap, &entry); + struct timeout_node* node = (struct timeout_node*)entry.data; + + if (node && node->callback && !node->cancelled) { + // Execute callback only if not cancelled + node->callback(node->arg); + } + + // Always free the node after processing + if (node && node->ua) { + node->ua->timer_free_count++; + } + free(node); + } +} + +// Instance version +void* uasync_set_timeout(struct UASYNC* ua, int timeout_tb, void* arg, timeout_callback_t callback) { + if (!ua || timeout_tb < 0 || !callback) return NULL; + if (!ua->timeout_heap) return NULL; + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_set_timeout: ua=%p, timeout=%d tb, arg=%p, callback=%p", + ua, timeout_tb, arg, callback); + + struct timeout_node* node = malloc(sizeof(struct timeout_node)); + if (!node) { + DEBUG_ERROR(DEBUG_CATEGORY_TIMERS, "uasync_set_timeout: failed to allocate node"); + return NULL; + } + ua->timer_alloc_count++; + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_set_timeout: allocated node %p (alloc_count=%zu)", + node, ua->timer_alloc_count); + + node->arg = arg; + node->callback = callback; + node->ua = ua; + node->cancelled = 0; + node->heap_index = SIZE_MAX; // Initialize + + // Calculate expiration time in milliseconds + struct timeval now; + get_current_time(&now); + timeval_add_tb(&now, timeout_tb); + node->expiration_ms = timeval_to_ms(&now); + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_set_timeout: node %p expires at %llu ms", + node, (unsigned long long)node->expiration_ms); + + // Add to heap + if (timeout_heap_push(ua->timeout_heap, node->expiration_ms, node) != 0) { + DEBUG_ERROR(DEBUG_CATEGORY_TIMERS, "uasync_set_timeout: failed to push to heap"); + free(node); + ua->timer_free_count++; // Balance the alloc counter + return NULL; + } + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_set_timeout: successfully created timer %p", node); + return node; +} + +// Instance version +err_t uasync_cancel_timeout(struct UASYNC* ua, void* t_id) { + if (!ua || !t_id || !ua->timeout_heap) { + DEBUG_ERROR(DEBUG_CATEGORY_TIMERS, "uasync_cancel_timeout: invalid parameters ua=%p, t_id=%p, heap=%p", + ua, t_id, ua ? ua->timeout_heap : NULL); + return ERR_FAIL; + } + + struct timeout_node* node = (struct timeout_node*)t_id; + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_cancel_timeout: ua=%p, t_id=%p, node=%p, expires=%llu ms", + ua, t_id, node, (unsigned long long)node->expiration_ms); + + // Try to remove from heap + if (timeout_heap_remove(ua->timeout_heap, node) == 0) { + // Successfully removed - free it + node->cancelled = 1; + node->callback = NULL; + ua->timer_free_count++; + free(node); + return ERR_OK; + } else { + // Not found in heap (may be already popped) - just mark cancelled to skip callback if pending + node->cancelled = 1; + node->callback = NULL; + // Do NOT free here to avoid double-free if already processed + return ERR_OK; + } +} + +void* uasync_add_socket(struct UASYNC* ua, int fd, socket_callback_t read_cbk, socket_callback_t write_cbk, socket_callback_t except_cbk, void* user_data) { + if (!ua || !ua->sockets) return NULL; + if (socket_array_add(ua->sockets, fd, read_cbk, write_cbk, except_cbk, user_data) != 0) return NULL; + ua->socket_alloc_count++; + return socket_array_get(ua->sockets, fd); +} + +err_t uasync_remove_socket(struct UASYNC* ua, void* s_id) { + if (!ua || !ua->sockets || !s_id) return ERR_FAIL; + struct socket_node* node = (struct socket_node*)s_id; + if (socket_array_remove(ua->sockets, node->fd) != 0) return ERR_FAIL; + ua->socket_free_count++; + return ERR_OK; +} + +void uasync_poll(struct UASYNC* ua, int timeout_tb) { + if (!ua) return; + + // Get next timeout + int timeout_ms = -1; + if (ua->timeout_heap && ua->timeout_heap->size > 0) { + struct timeval now_tv; + get_current_time(&now_tv); + uint64_t now_ms = timeval_to_ms(&now_tv); + TimeoutEntry entry; + if (timeout_heap_peek(ua->timeout_heap, &entry) == 0) { + if (entry.expiration > now_ms) { + timeout_ms = (int)(entry.expiration - now_ms); + } else { + timeout_ms = 0; + } + } + } + if (timeout_tb >= 0) { + int tb_ms = timeout_tb / 10; // approx tb to ms (adjust if tb unit is different) + if (timeout_ms < 0 || tb_ms < timeout_ms) timeout_ms = tb_ms; + } + + // Prepare poll fds + int wakeup_fd_present = ua->wakeup_initialized && ua->wakeup_pipe[0] >= 0; + int socket_count = ua->sockets ? ua->sockets->count : 0; + int total_fds = socket_count + wakeup_fd_present; + + struct pollfd* fds = malloc(total_fds * sizeof(struct pollfd)); + struct socket_node** nodes = socket_count > 0 ? malloc(socket_count * sizeof(struct socket_node*)) : NULL; + if (!fds || (socket_count > 0 && !nodes)) { + free(fds); + free(nodes); + return; /* out of memory */ + } + + /* Fill arrays */ + int idx = 0; + + /* Add wakeup fd first if present */ + if (wakeup_fd_present) { + fds[idx].fd = ua->wakeup_pipe[0]; + fds[idx].events = POLLIN; + fds[idx].revents = 0; + idx++; + } + + /* Add socket fds using efficient array traversal */ + int node_idx = 0; + for (int i = 0; i < ua->sockets->capacity && node_idx < socket_count; i++) { + if (ua->sockets->sockets[i].active) { + struct socket_node* cur = &ua->sockets->sockets[i]; + fds[idx].fd = cur->fd; + fds[idx].events = 0; + fds[idx].revents = 0; + + if (cur->read_cbk) fds[idx].events |= POLLIN; + if (cur->write_cbk) fds[idx].events |= POLLOUT; + if (cur->except_cbk) fds[idx].events |= POLLPRI; + + if (nodes) { + nodes[node_idx] = cur; + } + idx++; + node_idx++; + } + } + + /* Call poll */ + int ret = poll(fds, total_fds, timeout_ms); + if (ret < 0) { + if (errno == EINTR) { + free(fds); + free(nodes); + return; + } + perror("poll"); + free(fds); + free(nodes); + return; + } + + /* Process timeouts that may have expired during poll */ + process_timeouts(ua); + + /* Process socket events */ + if (ret > 0) { + for (int i = 0; i < total_fds; i++) { + if (fds[i].revents == 0) continue; + + /* Handle wakeup fd separately */ + if (wakeup_fd_present && i == 0) { + if (fds[i].revents & POLLIN) { + drain_wakeup_pipe(ua); + } + continue; + } + + /* Socket event */ + int socket_idx = i - wakeup_fd_present; + struct socket_node* node = nodes[socket_idx]; + + /* Check for error conditions first */ + if (fds[i].revents & (POLLERR | POLLHUP | POLLNVAL)) { + /* Treat as exceptional condition */ + if (node->except_cbk) { + node->except_cbk(node->fd, node->user_data); + } + } + + /* Exceptional data (out-of-band) */ + if (fds[i].revents & POLLPRI) { + if (node->except_cbk) { + node->except_cbk(node->fd, node->user_data); + } + } + + /* Read readiness */ + if (fds[i].revents & POLLIN) { + if (node->read_cbk) { + node->read_cbk(node->fd, node->user_data); + } + } + + /* Write readiness */ + if (fds[i].revents & POLLOUT) { + if (node->write_cbk) { + node->write_cbk(node->fd, node->user_data); + } + } + } + } + + free(fds); + free(nodes); +} + +void uasync_mainloop(struct UASYNC* ua) { + while (1) { + uasync_poll(ua, -1); + } +} + +struct UASYNC* uasync_create(void) { + // Initialize debug system on first use + static int debug_initialized = 0; + if (!debug_initialized) { + debug_config_init(); + debug_initialized = 1; + } + + struct UASYNC* ua = malloc(sizeof(struct UASYNC)); + if (!ua) return NULL; + + memset(ua, 0, sizeof(struct UASYNC)); + ua->wakeup_pipe[0] = -1; + ua->wakeup_pipe[1] = -1; + ua->wakeup_initialized = 0; + + // Create wakeup pipe + if (pipe(ua->wakeup_pipe) < 0) { + DEBUG_WARN(DEBUG_CATEGORY_UASYNC, "Failed to create wakeup pipe: %s", strerror(errno)); + // Continue without wakeup mechanism + ua->wakeup_pipe[0] = -1; + ua->wakeup_pipe[1] = -1; + } else { + ua->wakeup_initialized = 1; + // Set non-blocking on read end to avoid blocking if pipe is full + int flags = fcntl(ua->wakeup_pipe[0], F_GETFL, 0); + if (flags >= 0) { + fcntl(ua->wakeup_pipe[0], F_SETFL, flags | O_NONBLOCK); + } + } + + ua->sockets = socket_array_create(16); + if (!ua->sockets) { + if (ua->wakeup_initialized) { + close(ua->wakeup_pipe[0]); + close(ua->wakeup_pipe[1]); + } + free(ua); + return NULL; + } + + ua->timeout_heap = timeout_heap_create(16); + if (!ua->timeout_heap) { + socket_array_destroy(ua->sockets); + if (ua->wakeup_initialized) { + close(ua->wakeup_pipe[0]); + close(ua->wakeup_pipe[1]); + } + free(ua); + return NULL; + } + + return ua; +} + +// Print all resources for debugging +void uasync_print_resources(struct UASYNC* ua, const char* prefix) { + if (!ua) { + printf("%s: NULL uasync instance\n", prefix); + return; + } + + printf("\n🔍 %s: UASYNC Resource Report for %p\n", prefix, ua); + printf(" Timer Statistics: allocated=%zu, freed=%zu, active=%zd\n", + ua->timer_alloc_count, ua->timer_free_count, + (ssize_t)(ua->timer_alloc_count - ua->timer_free_count)); + printf(" Socket Statistics: allocated=%zu, freed=%zu, active=%zd\n", + ua->socket_alloc_count, ua->socket_free_count, + (ssize_t)(ua->socket_alloc_count - ua->socket_free_count)); + + // Show active timers (removed check for .deleted; heap entries are valid up to .size) + if (ua->timeout_heap) { + size_t active_timers = ua->timeout_heap->size; + for (size_t i = 0; i < ua->timeout_heap->size; i++) { + struct timeout_node* node = (struct timeout_node*)ua->timeout_heap->heap[i].data; + printf(" Timer: node=%p, expires=%llu ms, cancelled=%d\n", + node, (unsigned long long)ua->timeout_heap->heap[i].expiration, node->cancelled); + } + printf(" Active timers in heap: %zu\n", active_timers); + } + + // Show active sockets + if (ua->sockets) { + int active_sockets = 0; + printf(" Socket array capacity: %d, active: %d\n", + ua->sockets->capacity, ua->sockets->count); + for (int i = 0; i < ua->sockets->capacity; i++) { + if (ua->sockets->sockets[i].active) { + active_sockets++; + printf(" Socket: fd=%d, active=%d\n", + ua->sockets->sockets[i].fd, + ua->sockets->sockets[i].active); + } + } + printf(" Total active sockets: %d\n", active_sockets); + } + + printf("🔚 %s: End of resource report\n\n", prefix); +} + +void uasync_destroy(struct UASYNC* ua, int close_fds) { + if (!ua) return; + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_destroy: starting cleanup for ua=%p", ua); + + // Free all remaining timeouts by popping and freeing data (fixes leak without double-free) + if (ua->timeout_heap) { + TimeoutEntry entry; + while (timeout_heap_pop(ua->timeout_heap, &entry) == 0) { + struct timeout_node* node = (struct timeout_node*)entry.data; + if (node) { + ua->timer_free_count++; + free(node); + } + } + timeout_heap_destroy(ua->timeout_heap); + ua->timeout_heap = NULL; + } + + // Free all socket nodes using array approach + if (ua->sockets) { + // Count and free all active sockets + int freed_count = 0; + for (int i = 0; i < ua->sockets->capacity; i++) { + if (ua->sockets->sockets[i].active) { + if (close_fds && ua->sockets->sockets[i].fd >= 0) { + close(ua->sockets->sockets[i].fd); + } + ua->socket_free_count++; + freed_count++; + } + } + DEBUG_DEBUG(DEBUG_CATEGORY_MEMORY, "Freed %d socket nodes in destroy", freed_count); + socket_array_destroy(ua->sockets); + } + + // Close wakeup pipe + if (ua->wakeup_initialized) { + close(ua->wakeup_pipe[0]); + close(ua->wakeup_pipe[1]); + } + + // Final leak check + if (ua->timer_alloc_count != ua->timer_free_count || ua->socket_alloc_count != ua->socket_free_count) { + DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Memory leaks detected after cleanup: timers %zu/%zu, sockets %zu/%zu", + ua->timer_alloc_count, ua->timer_free_count, ua->socket_alloc_count, ua->socket_free_count); + DEBUG_ERROR(DEBUG_CATEGORY_TIMERS, "FINAL Timer leak: allocated=%zu, freed=%zu, diff=%zd", + ua->timer_alloc_count, ua->timer_free_count, + (ssize_t)(ua->timer_alloc_count - ua->timer_free_count)); + DEBUG_ERROR(DEBUG_CATEGORY_TIMERS, "FINAL Socket leak: allocated=%zu, freed=%zu, diff=%zd", + ua->socket_alloc_count, ua->socket_free_count, + (ssize_t)(ua->socket_alloc_count - ua->socket_free_count)); + abort(); + } + + DEBUG_DEBUG(DEBUG_CATEGORY_TIMERS, "uasync_destroy: completed successfully for ua=%p", ua); + free(ua); +} + +void uasync_init_instance(struct UASYNC* ua) { + if (!ua) return; + + // Initialize socket array if not present + if (!ua->sockets) { + ua->sockets = socket_array_create(16); + } + + if (!ua->timeout_heap) { + ua->timeout_heap = timeout_heap_create(16); + } +} + +// Debug statistics +void uasync_get_stats(struct UASYNC* ua, size_t* timer_alloc, size_t* timer_free, size_t* socket_alloc, size_t* socket_free) { + if (!ua) return; + if (timer_alloc) *timer_alloc = ua->timer_alloc_count; + if (timer_free) *timer_free = ua->timer_free_count; + if (socket_alloc) *socket_alloc = ua->socket_alloc_count; + if (socket_free) *socket_free = ua->socket_free_count; +} + +// Wakeup mechanism +int uasync_wakeup(struct UASYNC* ua) { + if (!ua || !ua->wakeup_initialized) return -1; + + char byte = 0; + ssize_t ret = write(ua->wakeup_pipe[1], &byte, 1); + if (ret != 1) { + // Don't print error from signal handler + return -1; + } + return 0; +} + +int uasync_get_wakeup_fd(struct UASYNC* ua) { + if (!ua || !ua->wakeup_initialized) return -1; + return ua->wakeup_pipe[1]; +} + +static struct socket_array* socket_array_create(int initial_capacity) { + struct socket_array* sa = malloc(sizeof(struct socket_array)); + if (!sa) return NULL; + sa->sockets = malloc(initial_capacity * sizeof(struct socket_node)); + if (!sa->sockets) { + free(sa); + return NULL; + } + sa->fd_to_index = malloc(FD_SETSIZE * sizeof(int)); // Assume FD_SETSIZE defined + if (!sa->fd_to_index) { + free(sa->sockets); + free(sa); + return NULL; + } + memset(sa->fd_to_index, -1, FD_SETSIZE * sizeof(int)); + sa->index_to_fd = malloc(initial_capacity * sizeof(int)); + if (!sa->index_to_fd) { + free(sa->fd_to_index); + free(sa->sockets); + free(sa); + return NULL; + } + sa->capacity = initial_capacity; + sa->count = 0; + sa->max_fd = 0; + return sa; +} + +static void socket_array_destroy(struct socket_array* sa) { + if (sa) { + free(sa->sockets); + free(sa->fd_to_index); + free(sa->index_to_fd); + free(sa); + } +} + +static int socket_array_add(struct socket_array* sa, int fd, socket_callback_t read_cbk, socket_callback_t write_cbk, socket_callback_t except_cbk, void* user_data) { + if (fd < 0 || fd >= FD_SETSIZE) return -1; + if (sa->fd_to_index[fd] != -1) return -1; // Already exists + + if (sa->count == sa->capacity) { + int new_cap = sa->capacity * 2; + struct socket_node* new_sockets = realloc(sa->sockets, new_cap * sizeof(struct socket_node)); + if (!new_sockets) return -1; + sa->sockets = new_sockets; + int* new_index_to_fd = realloc(sa->index_to_fd, new_cap * sizeof(int)); + if (!new_index_to_fd) return -1; + sa->index_to_fd = new_index_to_fd; + sa->capacity = new_cap; + } + + int index = sa->count++; + sa->sockets[index].fd = fd; + sa->sockets[index].read_cbk = read_cbk; + sa->sockets[index].write_cbk = write_cbk; + sa->sockets[index].except_cbk = except_cbk; + sa->sockets[index].user_data = user_data; + sa->sockets[index].active = 1; + sa->fd_to_index[fd] = index; + sa->index_to_fd[index] = fd; + if (fd > sa->max_fd) sa->max_fd = fd; + return 0; +} + +static int socket_array_remove(struct socket_array* sa, int fd) { + if (fd < 0 || fd >= FD_SETSIZE) return -1; + int index = sa->fd_to_index[fd]; + if (index == -1) return -1; + + sa->sockets[index].active = 0; + sa->fd_to_index[fd] = -1; + + // Move last to hole + int last_index = --sa->count; + if (index != last_index) { + sa->sockets[index] = sa->sockets[last_index]; + int last_fd = sa->index_to_fd[last_index]; + sa->fd_to_index[last_fd] = index; + sa->index_to_fd[index] = last_fd; + } + return 0; +} + +static struct socket_node* socket_array_get(struct socket_array* sa, int fd) { + if (fd < 0 || fd >= FD_SETSIZE) return NULL; + int index = sa->fd_to_index[fd]; + if (index == -1) return NULL; + return &sa->sockets[index]; +} \ No newline at end of file diff --git a/replace_printf.py b/replace_printf.py new file mode 100644 index 000000000..9b2be9841 --- /dev/null +++ b/replace_printf.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +""" +Replace printf with DEBUG_ macros in test files. +""" + +import os +import re +import sys + +def add_debug_include(content): + """Add #include \"../lib/debug_config.h\" if not present.""" + if '#include "../lib/debug_config.h"' in content: + return content + # Find position after last #include + lines = content.split('\n') + new_lines = [] + include_added = False + for line in lines: + new_lines.append(line) + if line.strip().startswith('#include') and not include_added: + # Add our include after the last #include block + # Check if next line is not #include + pass + # Simpler: insert after first #include line that includes something from ../lib or ../src + # Actually, just insert after the first #include line + for i, line in enumerate(lines): + if line.strip().startswith('#include'): + # Insert after this line + lines.insert(i + 1, '#include "../lib/debug_config.h"') + break + return '\n'.join(lines) + +def add_debug_init(content): + """Add debug initialization at the beginning of main().""" + if 'debug_config_init();' in content: + return content + # Find int main() { + pattern = r'int main\s*\(\s*\)\s*\{' + match = re.search(pattern, content) + if not match: + return content + start = match.end() + # Insert after the opening brace + # Find the next newline after brace + newline_pos = content.find('\n', start) + if newline_pos == -1: + return content + insertion_point = newline_pos + 1 + init_code = '\n debug_config_init();\n debug_set_level(DEBUG_LEVEL_TRACE);\n debug_set_categories(DEBUG_CATEGORY_ALL);\n' + content = content[:insertion_point] + init_code + content[insertion_point:] + return content + +def determine_category(filename, line): + """Determine debug category based on filename and line content.""" + filename_lower = filename.lower() + if 'crypto' in filename_lower: + return 'DEBUG_CATEGORY_CRYPTO' + elif 'etcp' in filename_lower: + return 'DEBUG_CATEGORY_ETCP' + elif 'memory' in filename_lower: + return 'DEBUG_CATEGORY_MEMORY' + elif 'u_async' in filename_lower: + return 'DEBUG_CATEGORY_UASYNC' + elif 'll_queue' in filename_lower: + return 'DEBUG_CATEGORY_LL_QUEUE' + elif 'config' in filename_lower: + return 'DEBUG_CATEGORY_CONFIG' + else: + return 'DEBUG_CATEGORY_ALL' + +def determine_level(line): + """Determine debug level based on line content.""" + line_lower = line.lower() + if '❌' in line or 'error' in line_lower or 'failed' in line_lower: + return 'DEBUG_ERROR' + elif 'warn' in line_lower: + return 'DEBUG_WARN' + elif '✅' in line_lower or 'success' in line_lower or 'passed' in line_lower: + return 'DEBUG_INFO' + elif '[debug]' in line_lower: + return 'DEBUG_DEBUG' + elif 'info' in line_lower: + return 'DEBUG_INFO' + else: + return 'DEBUG_INFO' + +def replace_printf(content, filename): + """Replace printf calls with DEBUG_ macros.""" + # Pattern to match printf("...", ...); + # Simple approach: replace line by line + lines = content.split('\n') + new_lines = [] + i = 0 + while i < len(lines): + line = lines[i] + stripped = line.strip() + + # Check for printf + if stripped.startswith('printf('): + # Extract format string and arguments + # Simple regex to capture printf("format", args); + match = re.match(r'printf\("([^"]*)"\s*,?(.*)\);', stripped) + if match: + fmt = match.group(1) + args = match.group(2).strip() + # Remove ❌ and ✅ symbols + fmt = fmt.replace('❌', '').replace('✅', '').strip() + # Determine category and level + category = determine_category(filename, line) + level = determine_level(line) + # Build new macro call + if args: + new_line = line.replace(stripped, f'{level}({category}, "{fmt}", {args});') + else: + new_line = line.replace(stripped, f'{level}({category}, "{fmt}");') + new_lines.append(new_line) + # Check if next line is fflush(stdout); + if i + 1 < len(lines) and 'fflush(stdout);' in lines[i + 1]: + i += 1 # Skip fflush line + else: + # Keep original if pattern doesn't match + new_lines.append(line) + elif stripped.startswith('fprintf(') and 'stderr' in stripped: + # Replace fprintf(stderr, ...) with DEBUG_ERROR + match = re.match(r'fprintf\s*\(\s*stderr\s*,\s*"([^"]*)"\s*,?(.*)\);', stripped) + if match: + fmt = match.group(1) + args = match.group(2).strip() + category = determine_category(filename, line) + new_line = line.replace(stripped, f'DEBUG_ERROR({category}, "{fmt}", {args});') + new_lines.append(new_line) + else: + new_lines.append(line) + else: + new_lines.append(line) + i += 1 + + return '\n'.join(new_lines) + +def process_file(filepath): + """Process a single file.""" + print(f"Processing {filepath}") + with open(filepath, 'r') as f: + content = f.read() + + original = content + + # Step 1: Add debug include + content = add_debug_include(content) + + # Step 2: Add debug initialization in main() + content = add_debug_init(content) + + # Step 3: Replace printf calls + content = replace_printf(content, os.path.basename(filepath)) + + if content != original: + with open(filepath, 'w') as f: + f.write(content) + print(f" Updated {filepath}") + else: + print(f" No changes needed") + +def main(): + test_dir = 'tests' + for root, dirs, files in os.walk(test_dir): + for file in files: + if file.endswith('.c'): + filepath = os.path.join(root, file) + process_file(filepath) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/replace_remaining.py b/replace_remaining.py new file mode 100644 index 000000000..64c746ba9 --- /dev/null +++ b/replace_remaining.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +""" +Replace remaining printf calls in test files. +""" + +import os +import re +import sys + +def process_file(filepath): + with open(filepath, 'r') as f: + content = f.read() + + original = content + + # Determine category based on filename + filename = os.path.basename(filepath).lower() + if 'crypto' in filename or 'ecc' in filename: + category = 'DEBUG_CATEGORY_CRYPTO' + elif 'etcp' in filename: + category = 'DEBUG_CATEGORY_ETCP' + elif 'memory' in filename: + category = 'DEBUG_CATEGORY_MEMORY' + elif 'u_async' in filename: + category = 'DEBUG_CATEGORY_UASYNC' + elif 'll_queue' in filename: + category = 'DEBUG_CATEGORY_LL_QUEUE' + elif 'config' in filename: + category = 'DEBUG_CATEGORY_CONFIG' + else: + category = 'DEBUG_CATEGORY_ALL' + + # Replace printf calls - simple pattern for single line printf + lines = content.split('\n') + new_lines = [] + i = 0 + while i < len(lines): + line = lines[i] + stripped = line.strip() + + # Look for printf + if stripped.startswith('printf('): + # Try to capture the whole printf call (may span multiple lines) + # Collect lines until we find semicolon + printf_lines = [line] + j = i + 1 + while j < len(lines) and ';' not in lines[j-1]: + printf_lines.append(lines[j]) + j += 1 + # Now we have block of lines + block = '\n'.join(printf_lines) + # Simple regex for single line printf with arguments on same line + # Match printf("format", args...); + match = re.search(r'printf\s*\(\s*"([^"]*)"\s*,?(.*)\)\s*;', block, re.DOTALL) + if match: + fmt = match.group(1).replace('\n', '').replace('\\n', '') + args = match.group(2).strip() + # Determine level + fmt_lower = fmt.lower() + if '❌' in fmt or 'error' in fmt_lower or 'failed' in fmt_lower: + level = 'DEBUG_ERROR' + elif 'warn' in fmt_lower: + level = 'DEBUG_WARN' + elif '✅' in fmt_lower or 'success' in fmt_lower or 'passed' in fmt_lower: + level = 'DEBUG_INFO' + elif '[debug]' in fmt_lower: + level = 'DEBUG_DEBUG' + else: + level = 'DEBUG_INFO' + # Remove emojis + fmt = fmt.replace('❌', '').replace('✅', '').replace('ℹ️', '').strip() + # Build new line + if args: + new_line = line.replace(stripped, f'{level}({category}, "{fmt}", {args});') + else: + new_line = line.replace(stripped, f'{level}({category}, "{fmt}");') + new_lines.append(new_line) + i = j # Skip the lines we consumed + continue + else: + # Fallback: just remove printf line + new_lines.append(line) + else: + new_lines.append(line) + i += 1 + + content = '\n'.join(new_lines) + + # Remove fflush(stdout) lines + content = re.sub(r'^\s*fflush\s*\(\s*stdout\s*\)\s*;\s*$', '', content, flags=re.MULTILINE) + + if content != original: + with open(filepath, 'w') as f: + f.write(content) + print(f"Updated {filepath}") + else: + print(f"No changes in {filepath}") + +def main(): + # Files that still have printf according to grep + files = [ + 'tests/test_ll_queue.c', + 'tests/test_ecc_encrypt.c', + 'tests/test_debug_categories.c', + 'tests/test_etcp_two_instances.c', + 'tests/test_packet_dump.c', + 'tests/test_memory_pool_and_config.c', + 'tests/test_u_async_performance.c', + 'tests/test_etcp_minimal.c' + ] + + for filepath in files: + if os.path.exists(filepath): + process_file(filepath) + else: + print(f"File not found: {filepath}") + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/simple_test.c b/simple_test.c new file mode 100644 index 000000000..fd68f787d --- /dev/null +++ b/simple_test.c @@ -0,0 +1,37 @@ +#include "../lib/u_async.h" +#include +#include +#include +#include +#include + +static void test_callback(int fd, void* arg) { + (void)fd; (void)arg; +} + +int main() { + uasync_t* ua = uasync_create(); + if (!ua) return 1; + + printf("=== Simple Corruption Test ===\n"); + + // Create just one socket + int sock = socket(AF_INET, SOCK_DGRAM, 0); + printf("Created socket with fd=%d\n", sock); + + void* id = uasync_add_socket(ua, sock, test_callback, NULL, NULL, NULL); + printf("Added socket: fd=%d, id=%p\n", sock, id); + + // Check if fd is still correct + struct socket_node* node = (struct socket_node*)id; + printf("Node fd after add: %d\n", node->fd); + + // Try to remove immediately (no polling) + int result = uasync_remove_socket(ua, id); + printf("Remove result: %d\n", result); + + close(sock); + uasync_destroy(ua, 0); + + return 0; +} diff --git a/src/config_parser.c b/src/config_parser.c index dd265b593..f35ffd03a 100644 --- a/src/config_parser.c +++ b/src/config_parser.c @@ -70,6 +70,7 @@ static uint32_t parse_debug_categories(const char *value) { token = strtok(NULL, ","); } + free(value_copy); return categories ? categories : DEBUG_CATEGORY_ALL; // Default to all if nothing parsed } diff --git a/src/etcp.c b/src/etcp.c index 39a62d2a5..2f3824bac 100644 --- a/src/etcp.c +++ b/src/etcp.c @@ -1,22 +1,4 @@ // etcp.c - ETCP Protocol Implementation (refactored and expanded based on etcp_protocol.txt) -// Refactored to match new structures in etcp.h. Where logic doesn't align with protocol.txt or other headers, -// added comments with notes. Goal: compilable code for debugging and further refinement. -// Assumptions: -// - memory_pool.h/c is available for inflight_pool (not provided in docs, but referenced). -// - debug_config.h defines DEBUG_CATEGORY_ETCP, DEBUG_TRACE, etc. -// - crc32.h/c for any hashing needs (though not heavily used here). -// - UTUN_INSTANCE has ua (UASYNC) and pkt_pool (memory_pool). -// - Added missing fields to ETCP_CONN where implied (e.g., rtt_history initialized). -// - For inflight queues, use ll_queue with hash (hash now in ll_queue). -// - Linear search replaced where possible with queue_find_data_by_id. -// - INFLIGHT_PACKET uses embedded ll_entry; allocation via memory_pool, put/get adjusted for data pointer (post-ll_entry). -// - For input_queue and output_queue, assume they store ETCP_DGRAM as variable-size data (no embedded ll_entry); use queue_data_new + memcpy. -// - Adjusted input_queue_cb to new signature (void* data instead of ll_entry*). -// - Filled in truncated parts based on protocol.txt logic (e.g., building INFLIGHT_PACKET, adding to send_q). -// - For etcp_request_pkt, stubbed basic logic to build dgram from inflight or input_queue. -// - For etcp_conn_input, added section parsing loop based on protocol.txt. -// - Added container_of macro for convenience. -// - Assumed typical values for constants; adjust as needed. #include "etcp.h" #include "etcp_loadbalancer.h" @@ -44,7 +26,7 @@ #define SECTION_HEADER_SIZE 3 // type(1) + len(2) // Container-of macro for getting struct from data pointer -#define CONTAINER_OF(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member))) +//#define CONTAINER_OF(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member))) // Forward declarations static void input_queue_cb(struct ll_queue* q, void* data, void* arg); @@ -88,13 +70,16 @@ struct ETCP_CONN* etcp_connection_create(struct UTUN_INSTANCE* instance) { etcp->output_queue = queue_new(instance->ua, 0); // No hash for output_queue etcp->input_send_q = queue_new(instance->ua, INFLIGHT_INITIAL_HASH_SIZE); // Hash for send_q etcp->input_wait_ack = queue_new(instance->ua, INFLIGHT_INITIAL_HASH_SIZE); // Hash for wait_ack + etcp->recv_q = queue_new(instance->ua, INFLIGHT_INITIAL_HASH_SIZE); // Hash for send_q + etcp->ack_queue = queue_new(instance->ua, 0); etcp->inflight_pool = memory_pool_init(sizeof(struct INFLIGHT_PACKET)); + etcp->rx_pool = memory_pool_init(sizeof(struct RX_PACKET)); DEBUG_INFO(DEBUG_CATEGORY_CONNECTION, "etcp_connection_create: queues created - input:%p output:%p send:%p wait:%x pool:%p", etcp->input_queue, etcp->output_queue, etcp->input_send_q, etcp->input_wait_ack, etcp->inflight_pool); - if (!etcp->input_queue || !etcp->output_queue || !etcp->input_send_q || - !etcp->input_wait_ack || !etcp->inflight_pool) { + if (!etcp->input_queue || !etcp->output_queue || !etcp->input_send_q || !etcp->recv_q || !etcp->ack_queue || + !etcp->input_wait_ack || !etcp->inflight_pool || !etcp->rx_pool) { etcp_connection_close(etcp); return NULL; } @@ -137,6 +122,14 @@ void etcp_connection_close(struct ETCP_CONN* etcp) { queue_free(etcp->input_wait_ack); etcp->input_wait_ack = NULL; } + if (etcp->ack_queue) { + queue_free(etcp->ack_queue); + etcp->ack_queue = NULL; + } + if (etcp->recv_q) { + queue_free(etcp->recv_q); + etcp->recv_q = NULL; + } // Free memory pool only if it exists if (etcp->inflight_pool) { @@ -144,6 +137,11 @@ void etcp_connection_close(struct ETCP_CONN* etcp) { etcp->inflight_pool = NULL; } + if (etcp->rx_pool) { + memory_pool_destroy(etcp->rx_pool); + etcp->rx_pool = NULL; + } + // Clear links list safely if (etcp->links) { struct ETCP_LINK* link = etcp->links; @@ -171,39 +169,108 @@ void etcp_conn_reset(struct ETCP_CONN* etcp) { // Clear inflight, rx_list, etc. } +static void input_queue_try_resume(struct ETCP_CONN* etcp) { + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "input_queue_try_resume: ENTER etcp=%p", etcp); + + // если размер input_wait_ack+input_send_q в байтах < optimal_inflight то resume сейчас. + size_t wait_ack_bytes = queue_total_bytes(etcp->input_wait_ack); + size_t send_q_bytes = queue_total_bytes(etcp->input_send_q); + size_t total_bytes = wait_ack_bytes + send_q_bytes; + + if (total_bytes < etcp->optimal_inflight) { + queue_resume_callback(etcp->input_send_q);// вызвать лишний раз resume не страшно. + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "input_queue_try_resume: resumed input_send_q callback"); + } +} // Input callback for input_queue (добавление новых кодограмм в стек) +// input_queue -> input_send_q static void input_queue_cb(struct ll_queue* q, void* data, void* arg) { + struct ETCP_CONN* etcp = (struct ETCP_CONN*)arg; + struct RX_PACKET* in_pkt = (struct RX_PACKET*)data; + + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "input_queue_cb: processing RX_PACKET %p (seq=%u, len=%u, data=%p)", + in_pkt, in_pkt->seq, in_pkt->pkt_len, in_pkt->pkt_data); // Create INFLIGHT_PACKET struct INFLIGHT_PACKET* p = memory_pool_alloc(etcp->inflight_pool); if (!p) { DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "input_queue_cb: cannot allocate INFLIGHT_PACKET"); - queue_data_free(data); // Free the data (pkt) + queue_data_free(in_pkt); // Free the RX_PACKET queue_resume_callback(q); return; } - + // Setup inflight packet (based on protocol.txt) memset(p, 0, sizeof(*p)); - p->pkt = data; // Note: pkt is now owned by inflight; don't free here + p->pkt = in_pkt; // Note: RX_PACKET is now owned by inflight; don't free here p->seq = etcp->next_tx_id++; // Assign seq p->state = INFLIGHT_STATE_WAIT_SEND; - - // Get data pointer (post ll_entry) - void* inflight_data = (void*)((char*)p + sizeof(struct ll_entry)); - + // Add to send queue - if (queue_data_put(etcp->input_send_q, inflight_data, p->seq) != 0) { - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "input_queue_cb: failed to put to input_send_q"); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "input_queue_cb: adding INFLIGHT_PACKET %p to input_send_q (seq=%u)", p, p->seq); + if (queue_data_put(etcp->input_send_q, p, p->seq) != 0) { memory_pool_free(etcp->inflight_pool, p); - queue_data_free(data); + queue_data_free(in_pkt); + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "input_queue_cb: EXIT (queue put failed)"); + return; } - - queue_resume_callback(q); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "input_queue_cb: successfully added to input_send_q"); + input_queue_try_resume(etcp); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "input_queue_cb: called input_queue_try_resume for etcp=%p", etcp); + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "input_queue_cb: EXIT success"); } +void etcp_output_try_assembly(struct ETCP_CONN* etcp) { + // пробуем собрать выходную очередь из фрагментов + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_output_try_assembly: etcp=%p, last_delivered_id=%u, recv_q_count=%d", + etcp, etcp->last_delivered_id, queue_entry_count(etcp->recv_q)); + + uint32_t next_expected_id = etcp->last_delivered_id + 1; + int delivered_count = 0; + uint32_t delivered_bytes = 0; + + // Look for contiguous packets starting from next_expected_id + while (1) { + struct RX_PACKET* rx_pkt = queue_find_data_by_id(etcp->recv_q, next_expected_id); + if (!rx_pkt) { + // No more contiguous packets found + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_output_try_assembly: no packet found for id=%u, stopping", next_expected_id); + break; + } + + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_output_try_assembly: assembling packet id=%u (len=%u)", + rx_pkt->seq, rx_pkt->pkt_len); + + // Simply move RX_PACKET from recv_q to output_queue - no data copying needed + // Remove from recv_q first + queue_remove_data(etcp->recv_q, rx_pkt); + + // Add to output_queue using the same RX_PACKET structure + if (queue_data_put(etcp->output_queue, rx_pkt, next_expected_id) == 0) { + delivered_bytes += rx_pkt->pkt_len; + delivered_count++; + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "etcp_output_try_assembly: moved packet id=%u to output_queue", + next_expected_id); + } else { + DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "etcp_output_try_assembly: failed to add packet id=%u to output_queue", + next_expected_id); + // Put it back in recv_q if we can't add to output_queue + queue_data_put(etcp->recv_q, rx_pkt, next_expected_id); + break; + } + + // Update state for next iteration + etcp->last_delivered_id = next_expected_id; + next_expected_id++; + } + + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_output_try_assembly: delivered %u contiguous packets (%u bytes), last_delivered_id=%u, output_queue_count=%d", + delivered_count, delivered_bytes, etcp->last_delivered_id, queue_entry_count(etcp->output_queue)); +} + + // Process incoming decrypted packet void etcp_conn_input(struct ETCP_DGRAM* pkt) { if (!pkt || !pkt->data_len) return; @@ -217,23 +284,37 @@ void etcp_conn_input(struct ETCP_DGRAM* pkt) { // Protocol.txt: timestamp is first 2B, then sections. // But in conn_input, pkt->data is after timestamp? Assume data starts with first section. - while (len >= SECTION_HEADER_SIZE) { + while (len >= 1) { uint8_t type = data[0]; - uint16_t sec_len = (data[1] << 8) | data[2]; - - if (sec_len > len - SECTION_HEADER_SIZE) { - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "etcp_conn_input: invalid section len=%u (remaining=%u)", sec_len, len - SECTION_HEADER_SIZE); + uint16_t sec_len = 0; // Section length varies by type + + // Determine section length based on type + switch (type) { + case ETCP_SECTION_PAYLOAD: + sec_len = len - 1; // Remaining data is payload + break; + case ETCP_SECTION_ACK: + if (len >= 2) { + uint8_t count = data[1]; + sec_len = 1 + 1 + (count * 8) + 4 + 4; // type + count + (id+ts)*count + last_delivered + last_rx + } + break; + case ETCP_SECTION_TIMESTAMP: + sec_len = 1 + 2 + 2; // type + ret_ts + recv_ts + break; + default: + // For unknown types, skip just the type byte to avoid infinite loop + sec_len = 1; + break; + } + + if (sec_len > len) { + DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "etcp_conn_input: invalid section len=%u (remaining=%u)", sec_len, len); break; } // Process sections as per protocol.txt switch (type) { - case ETCP_SECTION_RETRANS: { - // Mark packets for retransmission (find in inflight using queue_find_data_by_id) - // TODO: Parse retrans requests, mark in input_wait_ack or move to input_send_q - // If wait_timeout_active, trigger resume - break; - } case ETCP_SECTION_ACK: { // Mark packets as acknowledged (find using queue_find_data_by_id) // TODO: Parse ACKs, remove from input_wait_ack, update RTT @@ -247,66 +328,250 @@ void etcp_conn_input(struct ETCP_DGRAM* pkt) { break; } case ETCP_SECTION_PAYLOAD: { - // Add to RX assembly list (check duplicate via hash) - // TODO: If not duplicate, insert into linked list by seq - // Check if consecutive from last_delivered_id, move to output_queue + + if (len>=5) { + // формируем ACK + struct INFLIGHT_PACKET* p = memory_pool_alloc(etcp->instance->ack_pool); + uint32_t seq=data[1] | (data[2]<<8) | (data[3]<<16) | (data[4]<<24); + p->seq=seq; + p->last_timestamp=pkt->timestamp; + queue_data_put(etcp->ack_queue, p, p->seq); + + if ((int32_t)(etcp->last_delivered_id-seq)<0) if (queue_find_data_by_id(etcp->recv_q, seq)==NULL) {// проверяем есть ли пакет с этим seq + uint32_t pkt_len=len-5; + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_conn_input: adding packet seq=%u to recv_q (last_delivered_id=%u)", seq, etcp->last_delivered_id); + // отправляем пакет в очередь на сборку + uint8_t* payload_data = memory_pool_alloc(etcp->instance->data_pool); + struct RX_PACKET* rx_pkt = memory_pool_alloc(etcp->rx_pool); + rx_pkt->seq=seq; + rx_pkt->timestamp=pkt->timestamp; + rx_pkt->pkt_data=payload_data; + rx_pkt->pkt_len=pkt_len; + // Copy the actual payload data + memcpy(payload_data, data + 5, pkt_len); + queue_data_put(etcp->recv_q, rx_pkt, seq); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_conn_input: packet seq=%u added to recv_q, calling assembly (last_delivered_id=%u)", seq, etcp->last_delivered_id); + if (etcp->last_delivered_id==seq) etcp_output_try_assembly(etcp);// пробуем собрать выходную очередь из фрагментов + } + } + len=0; + break; } + default: DEBUG_WARN(DEBUG_CATEGORY_ETCP, "etcp_conn_input: unknown section type=0x%02x", type); break; } - data += SECTION_HEADER_SIZE + sec_len; - len -= SECTION_HEADER_SIZE + sec_len; + data += sec_len; + len -= sec_len; } memory_pool_free(etcp->instance->pkt_pool, pkt); // Free the incoming dgram } -// Request next pkt for send +// Подготовить и отправить кодограмму +// вызывается линком когда освобождается или очередью если появляются данные на передачу struct ETCP_DGRAM* etcp_request_pkt(struct ETCP_CONN* etcp) { - // Logic: if input_send_q has pkt or input_queue and space in window. - // Build dgram: select link, append sections, add payload if any. - // Return dgram or NULL if waiting. + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: ENTER etcp=%p", etcp); + + struct ETCP_LINK* link = etcp_loadbalancer_select_link(etcp); + if (!link) { + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: no link available"); + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: EXIT (no link)"); + return NULL; + } + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: selected link %p", link); - // First, check if there's a packet in input_send_q (retrans or new) - void* inflight_data = queue_data_get(etcp->input_send_q); - struct INFLIGHT_PACKET* inflight = NULL; - struct ETCP_DGRAM* payload_pkt = NULL; - - if (inflight_data) { - inflight = CONTAINER_OF(inflight_data, struct INFLIGHT_PACKET, ll); // Note: ll is first, but CONTAINER_OF for last_link? Wait, adjust. - // Actually, since data = (char*)p + sizeof(ll_entry), CONTAINER_OF(data, struct INFLIGHT_PACKET, last_link) - // But last_link is first field after ll. - inflight = (struct INFLIGHT_PACKET*)((char*)inflight_data - sizeof(struct ll_entry)); - payload_pkt = inflight->pkt; - } else if (etcp->unacked_bytes < etcp->window_size) { - // Space in window, but since input_queue has callback, it already moves to send_q; assume no direct get here. - return NULL; // Wait for async - } else { - return NULL; // No packet ready + size_t send_q_bytes = queue_total_bytes(etcp->input_send_q); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: input_send_q bytes=%zu", send_q_bytes); + + if (send_q_bytes == 0) {// сгребаем из других мест + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: input_send_q empty, trying to resume"); + input_queue_try_resume(etcp); + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: EXIT (send_q empty)"); + return NULL; } + // First, check if there's a packet in input_send_q (retrans or new) + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: getting packet from input_send_q"); + struct INFLIGHT_PACKET* inf_pkt = queue_data_get(etcp->input_send_q); + if (!inf_pkt) { + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: no packet available from input_send_q"); + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: EXIT (no packet)"); + return NULL; + } + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: got INFLIGHT_PACKET %p (seq=%u, len=%u)", + inf_pkt, inf_pkt->seq, inf_pkt->pkt_len); + + inf_pkt->last_timestamp=get_current_time_units(); + inf_pkt->send_count++; + inf_pkt->state=INFLIGHT_STATE_WAIT_ACK; +// queue_data_put(etcp->input_send_q, inf_pkt, inf_pkt->seq);// move dgram to wait_ack queue + // Build outgoing dgram (stub: allocate from pkt_pool) + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: allocating ETCP_DGRAM from pkt_pool"); struct ETCP_DGRAM* dgram = memory_pool_alloc(etcp->instance->pkt_pool); - if (!dgram) return NULL; + if (!dgram) { + DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: failed to allocate ETCP_DGRAM"); + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: EXIT (allocation failed)"); + return NULL; + } + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: allocated ETCP_DGRAM %p", dgram); - // TODO: Select link via etcp_loadbalancer_select_link - // TODO: Append optional sections (ACK, RETRANS, timestamp) - // TODO: Append payload (0x00 section with payload_pkt->data) + dgram->link = link; + dgram->noencrypt_len=0; + dgram->timestamp=get_current_timestamp(); - // Mark inflight: inflight->last_link = selected_link; inflight->last_timestamp = get_current_time_units(); inflight->send_count++; - // Move to wait_ack: void* wait_data = (void*)((char*)inflight + sizeof(struct ll_entry)); - // queue_data_put(etcp->input_wait_ack, wait_data, inflight->seq); + int ptr=0; - // Note: Per loadbalancer.h, now use etcp_loadbalancer_send instead of return. - // But request_pkt returns dgram for loadbalancer to send? Conflict. - // Adjusted: build dgram, call etcp_loadbalancer_send(dgram), return NULL? - // Protocol.txt: loadbalancer calls request_pkt, gets dgram, sends. - // But loadbalancer.c has send which selects link and sends. - // Comment: Logic mismatch; assume request_pkt builds and returns dgram, caller sends. - // For compilation, return dgram. +// тут (потом) добавим опциональные заголовки + + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: building packet data (seq=%u, len=%u)", inf_pkt->seq, inf_pkt->pkt_len); + dgram->data[ptr++]=0;// payload + memcpy(&dgram->data[ptr], inf_pkt->pkt_data, inf_pkt->pkt_len); ptr+=inf_pkt->pkt_len; + dgram->data_len=ptr; + + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: built packet with %d bytes total", dgram->data_len); + + memory_pool_free(etcp->instance->data_pool, inf_pkt->pkt_data);// для теста отсылаем и освобождаем сразу + memory_pool_free(etcp->inflight_pool, inf_pkt);// для теста отсылаем и освобождаем сразу + + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: freed packet data and INFLIGHT_PACKET"); + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "etcp_request_pkt: EXIT success (dgram=%p)", dgram); return dgram; } + +// Forward declarations +static void etcp_conn_process_send_queue(struct ETCP_CONN* etcp); + +// Callback for when a link is ready to send data +static void etcp_link_ready_callback(struct ETCP_CONN* etcp) { + if (!etcp) return; + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_link_ready_callback: processing send queue for etcp=%p", etcp); + etcp_conn_process_send_queue(etcp); +} + +// Process packets in send queue and transmit them +static void etcp_conn_process_send_queue(struct ETCP_CONN* etcp) { + if (!etcp || !etcp->links) return; + + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "etcp_conn_process_send_queue: etcp=%p, unacked_bytes=%u, window_size=%u", + etcp, etcp->unacked_bytes, etcp->window_size); + + // Check if we have window space and packets to send + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_conn_process_send_queue: starting loop, unacked_bytes=%u, window_size=%u", + etcp->unacked_bytes, etcp->window_size); + + while (etcp->unacked_bytes < etcp->window_size) { + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "etcp_conn_process_send_queue: loop iteration, unacked_bytes=%u < window_size=%u", + etcp->unacked_bytes, etcp->window_size); + + // Try to get a packet from input_send_q + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_conn_process_send_queue: getting packet from input_send_q"); + void* inflight_data = queue_data_get(etcp->input_send_q); + if (!inflight_data) { + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "etcp_conn_process_send_queue: no packets in send queue"); + break; + } + + // Get the inflight packet structure + struct INFLIGHT_PACKET* inflight = (struct INFLIGHT_PACKET*)((char*)inflight_data - sizeof(struct ll_entry)); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_conn_process_send_queue: got INFLIGHT_PACKET %p (seq=%u, len=%u, state=%u)", + inflight, inflight->seq, inflight->pkt_len, inflight->state); + + // Build and send the packet + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_conn_process_send_queue: calling etcp_request_pkt for seq=%u", inflight->seq); + struct ETCP_DGRAM* dgram = etcp_request_pkt(etcp); + if (dgram) { + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_conn_process_send_queue: sending packet seq=%u", inflight->seq); + etcp_loadbalancer_send(dgram); + + // Update inflight state + inflight->last_timestamp = get_current_time_units(); + inflight->send_count++; + inflight->state = INFLIGHT_STATE_WAIT_ACK; + + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_conn_process_send_queue: updated INFLIGHT_PACKET %p state to WAIT_ACK", inflight); + + // Move to wait_ack queue + void* wait_data = (void*)((char*)inflight + sizeof(struct ll_entry)); + queue_data_put(etcp->input_wait_ack, wait_data, inflight->seq); + + etcp->unacked_bytes += inflight->pkt_len; + etcp->total_packets_sent++; + + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_conn_process_send_queue: packet seq=%u sent, unacked_bytes now %u", + inflight->seq, etcp->unacked_bytes); + } else { + // Put the packet back if we couldn't send it + queue_data_put(etcp->input_send_q, inflight_data, inflight->seq); + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "etcp_conn_process_send_queue: could not build packet, putting back"); + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "etcp_conn_process_send_queue: EXIT (build failed)"); + break; + } + } + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "etcp_conn_process_send_queue: EXIT (loop ended)"); +} + +// Send data through ETCP connection +// Allocates memory from data_pool and places in input queue +// Returns: 0 on success, -1 on failure +int etcp_send(struct ETCP_CONN* etcp, const void* data, uint16_t len) { +printf ("*********************** etcp_send: ENTER %d %d", g_debug_config.level,g_debug_config.categories); + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "etcp_send: ENTER etcp=%p, data=%p, len=%zu", etcp, data, len); + + if (!etcp || !data || len == 0) { + DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "etcp_send: invalid parameters (etcp=%p, data=%p, len=%zu)", etcp, data, len); + return -1; + } + + if (!etcp->input_queue) { + DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "etcp_send: input_queue is NULL for etcp=%p", etcp); + return -1; + } + + // Check length against maximum packet size + if (len > PACKET_DATA_SIZE) { + DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "etcp_send: packet too large (len=%zu, max=%d)", len, PACKET_DATA_SIZE); + return -1; + } + + // Allocate packet data from data_pool (following ETCP reception pattern) + uint8_t* packet_data = memory_pool_alloc(etcp->instance->data_pool); + if (!packet_data) { + DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "etcp_send: failed to allocate packet data from data_pool"); + return -1; + } + + // Copy user data to packet buffer + memcpy(packet_data, data, len); + + // Create queue entry - this allocates ll_entry + data pointer + + struct RX_PACKET* pkt = memory_pool_alloc(etcp->rx_pool); + if (!pkt) { + DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "etcp_send: failed to allocate queue entry"); + memory_pool_free(etcp->instance->data_pool, packet_data); + return -1; + } + + pkt->seq = 0; // Will be assigned by input_queue_cb + pkt->timestamp = 0; // Will be set by input_queue_cb + pkt->pkt_data = packet_data; // Point to data_pool allocation + pkt->pkt_len = len; + + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_send: created RX_PACKET %p with data %p (len=%zu)", pkt, packet_data, len); + + // Add to input queue - input_queue_cb will process it + if (queue_data_put(etcp->input_queue, pkt, 0) != 0) { + DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "etcp_send: failed to add to input queue"); + memory_pool_free(etcp->instance->data_pool, packet_data); + memory_pool_free(etcp->rx_pool, pkt); + return -1; + } + + return 0; +} \ No newline at end of file diff --git a/src/etcp.c1 b/src/etcp.c1 deleted file mode 100755 index 4403841d0..000000000 --- a/src/etcp.c1 +++ /dev/null @@ -1,201 +0,0 @@ -// etcp.c - ETCP Protocol Implementation (refactored and expanded based on etcp_protocol.txt) -// Refactored to match new structures in etcp.h. Where logic doesn't align with protocol.txt or other headers, -// added comments with notes. Goal: compilable code for debugging and further refinement. -// Assumptions: -// - memory_pool.h/c is available for inflight_pool (not provided in docs, but referenced). -// - debug_config.h defines DEBUG_CATEGORY_ETCP, DEBUG_TRACE, etc. -// - crc32.h/c for any hashing needs (though not heavily used here). -// - UTUN_INSTANCE has ua (UASYNC) and pkt_pool (memory_pool). -// - Added missing fields to ETCP_CONN where implied (e.g., rtt_history initialized). -// - inflight_hash is defined as struct INFLIGHT_HASH but empty in .h; assumed it's a placeholder for future hash table. -// For now, implemented linear search for inflight packets; comment where hash should be used. -// - INFLIGHT_PACKET renamed to inflight_packet_t for consistency. -// - rx_packet_t is defined in .h. -// - For bandwidth measurement, added basic state but logic is incomplete (as per protocol.txt burst description). -// - Timers use uasync_set_timeout; assumes UASYNC* ua from instance. -// - etcp_request_pkt now interacts with loadbalancer via etcp_loadbalancer_send (updated per loadbalancer.h). -// - etcp_conn_input processes sections as per protocol.txt. -// - Added stubs where functions are referenced but not fully defined (e.g., etcp_encrypt_send from connections.c). -// - For compilation: assumed sc_init_ctx, memory_pool_get_stats, etc., are defined elsewhere. - -#include "etcp.h" -#include "etcp_loadbalancer.h" -#include "../lib/u_async.h" -#include "../lib/debug_config.h" -#include "crc32.h" // For potential hashing, though not used yet. -#include -#include -#include -#include // For bandwidth calcs -#include // For UINT16_MAX - -// Enable comprehensive debug output for ETCP module -#define DEBUG_CATEGORY_ETCP_DETAILED 1 - -// Constants from spec (adjusted for completeness) -#define MAX_INFLIGHT_BYTES 65536 // Initial window -#define RETRANS_K1 2.0f // RTT multiplier for retrans timeout -#define RETRANS_K2 1.5f // Jitter multiplier -#define ACK_DELAY_TB 20 // ACK timer delay (2ms in 0.1ms units) -#define BURST_DELAY_FACTOR 4 // Delay before burst -#define BURST_SIZE 5 // Packets in burst (1 delayed + 4 burst) -#define RTT_HISTORY_SIZE 10 // For jitter calc -#define MAX_PENDING 32 // For ACKs/retrans (arbitrary; adjust) -#define SECTION_HEADER_SIZE 3 // type(1) + len(2) - -// Forward declarations -static void input_queue_cb(struct ll_queue* q, struct ll_entry* entry, void* arg); - -// Get current time in 0.1ms units -uint64_t get_current_time_units() { - struct timeval tv; - gettimeofday(&tv, NULL); - uint64_t time_units = ((uint64_t)tv.tv_sec * 10000ULL) + (tv.tv_usec / 100); - DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "get_current_time_units: tv_sec=%ld, tv_usec=%ld, result=%llu", - tv.tv_sec, tv.tv_usec, (unsigned long long)time_units); - return time_units; -} - -uint16_t get_current_timestamp() { - uint16_t timestamp = (uint16_t)(get_current_time_units() & 0xFFFF); - DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "get_current_timestamp: result=%u", timestamp); - return timestamp; -} - -// Timestamp diff (with wrap-around) -static uint16_t timestamp_diff(uint16_t t1, uint16_t t2) { - DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "timestamp_diff: t1=%u, t2=%u", t1, t2); - if (t1 >= t2) { - uint16_t diff = t1 - t2; - DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "timestamp_diff: normal case, diff=%u", diff); - return diff; - } - uint16_t diff = (0xFFFF - t2) + t1 + 1; - DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "timestamp_diff: wraparound case, diff=%u", diff); - return diff; -} - -// Create ETCP connection -struct ETCP_CONN* etcp_connection_create(struct UTUN_INSTANCE* instance) { - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_connection_create: instance=%p", instance); - - struct ETCP_CONN* etcp = calloc(1, sizeof(struct ETCP_CONN)); - if (!etcp) { - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "etcp_connection_create: failed to allocate ETCP_CONN"); - return NULL; - } - - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_connection_create: allocated etcp=%p", etcp); - - etcp->instance = instance; - etcp->input_queue = queue_new(instance->ua, instance->pkt_pool, 0); - etcp->output_queue = queue_new(instance->ua, instance->pkt_pool, 0); - - etcp->inflight_pool = memory_pool_init(sizeof(struct INFLIGHT_PACKET)); - etcp->input_send_q = queue_new(instance->ua, etcp->inflight_pool); - etcp->input_wait_ack = queue_new(instance->ua, etcp->inflight_pool); - - // inflight_hash: empty struct in .h; for now, unused. Will use linear search. - - etcp->mtu = 1500; // Default - etcp->window_size = MAX_INFLIGHT_BYTES; - etcp->next_tx_id = 1; - etcp->rtt_avg_10 = 10; // Initial guess (1ms) - etcp->rtt_avg_100 = 10; - etcp->rtt_history_idx = 0; - memset(etcp->rtt_history, 0, sizeof(etcp->rtt_history)); - - // Set input queue callback - queue_set_callback(etcp->input_queue, input_queue_cb, etcp); - - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_connection_create: queues created, mtu=%d, window_size=%u, next_tx_id=%u", - etcp->mtu, etcp->window_size, etcp->next_tx_id); - - return etcp; -} - -// Close connection (stub; expand as needed) -void etcp_connection_close(struct ETCP_CONN* etcp) { - if (!etcp) return; - // Free queues, timers, lists, etc. - queue_free(etcp->input_queue); - queue_free(etcp->output_queue); - queue_free(etcp->input_send_q); - queue_free(etcp->input_wait_ack); - memory_pool_destroy(etcp->inflight_pool); - // TODO: Free rx_list, links, etc. - free(etcp); -} - -// Reset connection (stub) -void etcp_conn_reset(struct ETCP_CONN* etcp) { - // Reset IDs, queues, etc. as per protocol.txt - etcp->next_tx_id = 1; - etcp->last_rx_id = 0; - etcp->last_delivered_id = 0; - // Clear inflight, rx_list, etc. -} - - -// Input callback for input_queue -static void input_queue_cb(struct ll_queue* q, struct ll_entry* entry, void* arg) { - struct ETCP_CONN* etcp = (struct ETCP_CONN*)arg; - -// добавляем struct INFLIGHT_PACKET - struct INFLIGHT_PACKET* p=memory_pool_alloc(etcp->inflight_pool); - if (!p) { - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "etcp_connection_create: can not allocate INFLIGHT HEADER"); - memory_pool_free(etcp->instance->pkt_pool, pkt);// пока просто освободим - queue_resume_callback(q); - return; - } - etcp_>input_send_q - -queue_entry_put( - - queue_resume_callback(q); -} - -// Process incoming decrypted packet -void etcp_conn_input(struct ETCP_DGRAM* pkt) { - if (!pkt || !pkt->data_len) return; - - struct ETCP_CONN* etcp = pkt->link->etcp; - uint8_t* data = pkt->data; - uint16_t len = pkt->data_len; - uint16_t ts = pkt->timestamp; // Received timestamp - - // Note: Assume packet starts with sections after timestamp (but timestamp is already extracted in connections?). - // Protocol.txt: timestamp is first 2B, then sections. - // But in conn_input, pkt->data is after timestamp? Assume data starts with first section. -/* - while (len >= SECTION_HEADER_SIZE) { - uint8_t type = data[0]; - - data += SECTION_HEADER_SIZE + sec_len; - len -= SECTION_HEADER_SIZE + sec_len; - } -*/ - - memory_pool_free(etcp->instance->pkt_pool, pkt);// пока просто освободим - -} - - -// Request next pkt for send -struct ETCP_DGRAM* etcp_request_pkt(struct ETCP_CONN* etcp) { - // Logic: if input_send_q has pkt or input_queue and space in window. - // Build dgram: select link, append sections, add payload if any. - // Return dgram or NULL if waiting. - struct ETCP_DGRAM* dgram = NULL; // Alloc and build. - if (dgram) { - // Note: Per loadbalancer.h, now use etcp_loadbalancer_send instead of return. - // But request_pkt returns dgram for loadbalancer to send? Conflict. - // Adjusted: build dgram, call etcp_loadbalancer_send(dgram), return NULL? - // Protocol.txt: loadbalancer calls request_pkt, gets dgram, sends. - // But loadbalancer.c has send which selects link and sends. - // Comment: Logic mismatch; assume request_pkt builds and returns dgram, caller sends. - // For compilation, return dgram. - } - return dgram; -} diff --git a/src/etcp.c2 b/src/etcp.c2 deleted file mode 100755 index 741b039ff..000000000 --- a/src/etcp.c2 +++ /dev/null @@ -1,275 +0,0 @@ -// etcp.c - ETCP Protocol Implementation (refactored and expanded based on etcp_protocol.txt) -// Refactored to match new structures in etcp.h. Where logic doesn't align with protocol.txt or other headers, -// added comments with notes. Goal: compilable code for debugging and further refinement. -// Assumptions: -// - memory_pool.h/c is available for inflight_pool (not provided in docs, but referenced). -// - debug_config.h defines DEBUG_CATEGORY_ETCP, DEBUG_TRACE, etc. -// - crc32.h/c for any hashing needs (though not heavily used here). -// - UTUN_INSTANCE has ua (UASYNC) and pkt_pool (memory_pool). -// - Added missing fields to ETCP_CONN where implied (e.g., rtt_history initialized). -// - For inflight queues, use ll_queue with hash (hash now in ll_queue). -// - Linear search replaced where possible with queue_find_data_by_id. -// - INFLIGHT_PACKET uses embedded ll_entry; allocation via memory_pool, put/get adjusted for data pointer (post-ll_entry). -// - For input_queue and output_queue, assume they store ETCP_DGRAM as variable-size data (no embedded ll_entry); use queue_data_new + memcpy. -// - Adjusted input_queue_cb to new signature (void* data instead of ll_entry*). -// - Filled in truncated parts based on protocol.txt logic (e.g., building INFLIGHT_PACKET, adding to send_q). -// - For etcp_request_pkt, stubbed basic logic to build dgram from inflight or input_queue. -// - For etcp_conn_input, added section parsing loop based on protocol.txt. -// - Added container_of macro for convenience. -// - Assumed typical values for constants; adjust as needed. - -#include "etcp.h" -#include "etcp_loadbalancer.h" -#include "../lib/u_async.h" -#include "../lib/debug_config.h" -#include "crc32.h" // For potential hashing, though not used yet. -#include -#include -#include -#include // For bandwidth calcs -#include // For UINT16_MAX - -// Enable comprehensive debug output for ETCP module -#define DEBUG_CATEGORY_ETCP_DETAILED 1 - -// Constants from spec (adjusted for completeness) -#define MAX_INFLIGHT_BYTES 65536 // Initial window -#define RETRANS_K1 2.0f // RTT multiplier for retrans timeout -#define RETRANS_K2 1.5f // Jitter multiplier -#define ACK_DELAY_TB 20 // ACK timer delay (2ms in 0.1ms units) -#define BURST_DELAY_FACTOR 4 // Delay before burst -#define BURST_SIZE 5 // Packets in burst (1 delayed + 4 burst) -#define RTT_HISTORY_SIZE 10 // For jitter calc -#define MAX_PENDING 32 // For ACKs/retrans (arbitrary; adjust) -#define SECTION_HEADER_SIZE 3 // type(1) + len(2) - -// Container-of macro for getting struct from data pointer -#define CONTAINER_OF(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member))) - -// Forward declarations -static void input_queue_cb(struct ll_queue* q, void* data, void* arg); - -// Get current time in 0.1ms units -uint64_t get_current_time_units() { - struct timeval tv; - gettimeofday(&tv, NULL); - uint64_t time_units = ((uint64_t)tv.tv_sec * 10000ULL) + (tv.tv_usec / 100); - DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "get_current_time_units: tv_sec=%ld, tv_usec=%ld, result=%llu", - tv.tv_sec, tv.tv_usec, (unsigned long long)time_units); - return time_units; -} - -uint16_t get_current_timestamp() { - uint16_t timestamp = (uint16_t)(get_current_time_units() & 0xFFFF); - DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "get_current_timestamp: result=%u", timestamp); - return timestamp; -} - -// Timestamp diff (with wrap-around) -static uint16_t timestamp_diff(uint16_t t1, uint16_t t2) { - DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "timestamp_diff: t1=%u, t2=%u", t1, t2); - if (t1 >= t2) { - return t1 - t2; - } - return (UINT16_MAX - t2) + t1 + 1; -} - -// Create new ETCP connection -struct ETCP_CONN* etcp_connection_create(struct UTUN_INSTANCE* instance) { - if (!instance) return NULL; - - struct ETCP_CONN* etcp = calloc(1, sizeof(struct ETCP_CONN)); - if (!etcp) return NULL; - - etcp->instance = instance; - etcp->input_queue = queue_new(instance->ua, NULL, 0); // No hash for input_queue - etcp->output_queue = queue_new(instance->ua, NULL, 0); // No hash for output_queue - etcp->input_send_q = queue_new(instance->ua, NULL, INFLIGHT_INITIAL_HASH_SIZE); // Hash for send_q - etcp->input_wait_ack = queue_new(instance->ua, NULL, INFLIGHT_INITIAL_HASH_SIZE); // Hash for wait_ack - etcp->inflight_pool = memory_pool_init(sizeof(struct INFLIGHT_PACKET)); - - if (!etcp->input_queue || !etcp->output_queue || !etcp->input_send_q || - !etcp->input_wait_ack || !etcp->inflight_pool) { - etcp_connection_close(etcp); - return NULL; - } - - etcp->mtu = 1500; // Default MTU - etcp->window_size = MAX_INFLIGHT_BYTES; - etcp->next_tx_id = 1; - etcp->rtt_avg_10 = 10; // Initial guess (1ms) - etcp->rtt_avg_100 = 10; - etcp->rtt_history_idx = 0; - memset(etcp->rtt_history, 0, sizeof(etcp->rtt_history)); - - // Set input queue callback - queue_set_callback(etcp->input_queue, input_queue_cb, etcp); - - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_connection_create: queues created, mtu=%d, window_size=%u, next_tx_id=%u", - etcp->mtu, etcp->window_size, etcp->next_tx_id); - - return etcp; -} - -// Close connection (stub; expand as needed) -void etcp_connection_close(struct ETCP_CONN* etcp) { - if (!etcp) return; - // Free queues, timers, lists, etc. - queue_free(etcp->input_queue); - queue_free(etcp->output_queue); - queue_free(etcp->input_send_q); - queue_free(etcp->input_wait_ack); - memory_pool_destroy(etcp->inflight_pool); - // TODO: Free rx_list, links, etc. - free(etcp); -} - -// Reset connection (stub) -void etcp_conn_reset(struct ETCP_CONN* etcp) { - // Reset IDs, queues, etc. as per protocol.txt - etcp->next_tx_id = 1; - etcp->last_rx_id = 0; - etcp->last_delivered_id = 0; - // Clear inflight, rx_list, etc. -} - - -// Input callback for input_queue -static void input_queue_cb(struct ll_queue* q, void* data, void* arg) { - struct ETCP_CONN* etcp = (struct ETCP_CONN*)arg; - struct ETCP_DGRAM* pkt = (struct ETCP_DGRAM*)data; // Assume input_queue stores ETCP_DGRAM as data - - // Create INFLIGHT_PACKET - struct INFLIGHT_PACKET* p = memory_pool_alloc(etcp->inflight_pool); - if (!p) { - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "input_queue_cb: cannot allocate INFLIGHT_PACKET"); - queue_data_free(data); // Free the data (pkt) - queue_resume_callback(q); - return; - } - - // Setup inflight packet (based on protocol.txt) - memset(p, 0, sizeof(*p)); - p->pkt = pkt; // Note: pkt is now owned by inflight; don't free here - p->seq = etcp->next_tx_id++; // Assign seq - p->state = INFLIGHT_STATE_WAIT_SEND; - - // Get data pointer (post ll_entry) - void* inflight_data = (void*)((char*)p + sizeof(struct ll_entry)); - - // Add to send queue - if (queue_data_put(etcp->input_send_q, inflight_data, p->seq) != 0) { - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "input_queue_cb: failed to put to input_send_q"); - memory_pool_free(etcp->inflight_pool, p); - queue_data_free(data); - } - - queue_resume_callback(q); -} - -// Process incoming decrypted packet -void etcp_conn_input(struct ETCP_DGRAM* pkt) { - if (!pkt || !pkt->data_len) return; - - struct ETCP_CONN* etcp = pkt->link->etcp; - uint8_t* data = pkt->data; - uint16_t len = pkt->data_len; - uint16_t ts = pkt->timestamp; // Received timestamp - - // Note: Assume packet starts with sections after timestamp (but timestamp is already extracted in connections?). - // Protocol.txt: timestamp is first 2B, then sections. - // But in conn_input, pkt->data is after timestamp? Assume data starts with first section. - - while (len >= SECTION_HEADER_SIZE) { - uint8_t type = data[0]; - uint16_t sec_len = (data[1] << 8) | data[2]; - - if (sec_len > len - SECTION_HEADER_SIZE) { - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "etcp_conn_input: invalid section len=%u (remaining=%u)", sec_len, len - SECTION_HEADER_SIZE); - break; - } - - // Process sections as per protocol.txt - switch (type) { - case ETCP_SECTION_RETRANS: { - // Mark packets for retransmission (find in inflight using queue_find_data_by_id) - // TODO: Parse retrans requests, mark in input_wait_ack or move to input_send_q - // If wait_timeout_active, trigger resume - break; - } - case ETCP_SECTION_ACK: { - // Mark packets as acknowledged (find using queue_find_data_by_id) - // TODO: Parse ACKs, remove from input_wait_ack, update RTT - // If wait_timeout_active, trigger resume - break; - } - case ETCP_SECTION_TIMESTAMP: { - // Update RTT, jitter - // TODO: Calculate RTT = timestamp_diff(get_current_timestamp(), ts) - // Update averages, jitter = max(last 10) - min(last 10) - break; - } - case ETCP_SECTION_PAYLOAD: { - // Add to RX assembly list (check duplicate via hash) - // TODO: If not duplicate, insert into linked list by seq - // Check if consecutive from last_delivered_id, move to output_queue - break; - } - default: - DEBUG_WARN(DEBUG_CATEGORY_ETCP, "etcp_conn_input: unknown section type=0x%02x", type); - break; - } - - data += SECTION_HEADER_SIZE + sec_len; - len -= SECTION_HEADER_SIZE + sec_len; - } - - memory_pool_free(etcp->instance->pkt_pool, pkt); // Free the incoming dgram -} - - -// Request next pkt for send -struct ETCP_DGRAM* etcp_request_pkt(struct ETCP_CONN* etcp) { - // Logic: if input_send_q has pkt or input_queue and space in window. - // Build dgram: select link, append sections, add payload if any. - // Return dgram or NULL if waiting. - - // First, check if there's a packet in input_send_q (retrans or new) - void* inflight_data = queue_data_get(etcp->input_send_q); - struct INFLIGHT_PACKET* inflight = NULL; - struct ETCP_DGRAM* payload_pkt = NULL; - - if (inflight_data) { - inflight = CONTAINER_OF(inflight_data, struct INFLIGHT_PACKET, ll); // Note: ll is first, but CONTAINER_OF for last_link? Wait, adjust. - // Actually, since data = (char*)p + sizeof(ll_entry), CONTAINER_OF(data, struct INFLIGHT_PACKET, last_link) - // But last_link is first field after ll. - inflight = (struct INFLIGHT_PACKET*)((char*)inflight_data - sizeof(struct ll_entry)); - payload_pkt = inflight->pkt; - } else if (etcp->unacked_bytes < etcp->window_size) { - // Space in window, but since input_queue has callback, it already moves to send_q; assume no direct get here. - return NULL; // Wait for async - } else { - return NULL; // No packet ready - } - - // Build outgoing dgram (stub: allocate from pkt_pool) - struct ETCP_DGRAM* dgram = memory_pool_alloc(etcp->instance->pkt_pool); - if (!dgram) return NULL; - - // TODO: Select link via etcp_loadbalancer_select_link - // TODO: Append optional sections (ACK, RETRANS, timestamp) - // TODO: Append payload (0x00 section with payload_pkt->data) - - // Mark inflight: inflight->last_link = selected_link; inflight->last_timestamp = get_current_time_units(); inflight->send_count++; - // Move to wait_ack: void* wait_data = (void*)((char*)inflight + sizeof(struct ll_entry)); - // queue_data_put(etcp->input_wait_ack, wait_data, inflight->seq); - - // Note: Per loadbalancer.h, now use etcp_loadbalancer_send instead of return. - // But request_pkt returns dgram for loadbalancer to send? Conflict. - // Adjusted: build dgram, call etcp_loadbalancer_send(dgram), return NULL? - // Protocol.txt: loadbalancer calls request_pkt, gets dgram, sends. - // But loadbalancer.c has send which selects link and sends. - // Comment: Logic mismatch; assume request_pkt builds and returns dgram, caller sends. - // For compilation, return dgram. - return dgram; -} diff --git a/src/etcp.h b/src/etcp.h index 36114ff22..0073df268 100644 --- a/src/etcp.h +++ b/src/etcp.h @@ -21,7 +21,6 @@ uint64_t get_current_time_units(void); // ETCP packet section types (from protocol spec) #define ETCP_SECTION_PAYLOAD 0x00 // Data payload #define ETCP_SECTION_ACK 0x01 // ACK section -#define ETCP_SECTION_RETRANS 0x10 // Retransmission request base (0x10-0x2F) #define ETCP_SECTION_TIMESTAMP 0x06 // Channel timestamp (example, adjust if needed) #define ETCP_SECTION_MEAS_TS 0x07 // Measurement timestamp for bandwidth #define ETCP_SECTION_MEAS_RESP 0x08 // Measurement response @@ -54,6 +53,12 @@ struct RX_PACKET { uint16_t pkt_len; }; +struct ACK_PACKET { + uint32_t seq;// sequence number + uint16_t pkt_timestamp;// timestamp пакета (часы уладенной стороны) + uint32_t recv_timestamp;// время приема (локальное) +}; + // ETCP connection structure (refactored) struct ETCP_CONN { struct ETCP_CONN* next; @@ -75,8 +80,12 @@ struct ETCP_CONN { // Inflight очереди (2 шт) - пока пакет в статусе inflight - к нему прикрепляется struct INFLIGHT_PACKET struct memory_pool* inflight_pool; // память для inflight очередей + struct memory_pool* rx_pool; // память для rx очередей struct ll_queue* input_send_q; // очередь на отправку (с элементами struct INFLIGHT_PACKET) struct ll_queue* input_wait_ack; // очередь ожидающих подтверждение (с элементами struct INFLIGHT_PACKET) + struct ll_queue* ack_queue; // неотправленные подтверждения приема пакетов + + struct ll_queue* recv_q; // очередь на сборку (с элементами struct RX_PACKET) void (*link_ready_for_send_fn)(struct ETCP_CONN*);// функцию которую должен вызвать драйвер линка при готовности линка принимать данные @@ -84,9 +93,9 @@ struct ETCP_CONN { // IDs and state - uint16_t next_tx_id; // Next TX ID - uint16_t last_rx_id; // Last received ID - uint16_t last_delivered_id; // Last delivered to output_queue + uint32_t next_tx_id; // Next TX ID + uint32_t last_rx_id; // Last received ID + uint32_t last_delivered_id; // Last delivered to output_queue // Metrics (RTT, jitter, etc.) uint16_t rtt_last; @@ -135,6 +144,11 @@ void etcp_conn_reset(struct ETCP_CONN* etcp); // Input from etcp_connections (decrypted packet) void etcp_conn_input(struct ETCP_DGRAM* pkt); +// Send data through ETCP connection +// Allocates memory from data_pool and places in input queue +// Returns: 0 on success, -1 on failure +int etcp_send(struct ETCP_CONN* etcp, const void* data, uint16_t len); + // Request next packet for load balancer struct ETCP_DGRAM* etcp_request_pkt(struct ETCP_CONN* etcp); diff --git a/src/etcp.h1 b/src/etcp.h1 deleted file mode 100755 index 2a1aeaa0e..000000000 --- a/src/etcp.h1 +++ /dev/null @@ -1,155 +0,0 @@ -// etcp.h - ETCP Protocol Header (refactored based on etcp_protocol.txt) -#ifndef ETCP_H -#define ETCP_H - -#include "etcp_connections.h" -#include "secure_channel.h" -#include "../lib/ll_queue.h" -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// Forward declarations -struct UTUN_INSTANCE; -struct UASYNC; - -uint16_t get_current_timestamp(void); -uint64_t get_current_time_units(void); - -// ETCP packet section types (from protocol spec) -#define ETCP_SECTION_PAYLOAD 0x00 // Data payload -#define ETCP_SECTION_ACK 0x01 // ACK section -#define ETCP_SECTION_RETRANS 0x10 // Retransmission request base (0x10-0x2F) -#define ETCP_SECTION_TIMESTAMP 0x06 // Channel timestamp (example, adjust if needed) -#define ETCP_SECTION_MEAS_TS 0x07 // Measurement timestamp for bandwidth -#define ETCP_SECTION_MEAS_RESP 0x08 // Measurement response - -// Inflight packet states -#define INFLIGHT_STATE_WAIT_ACK 0 -#define INFLIGHT_STATE_WAIT_SEND 1 -#define INFLIGHT_INITIAL_HASH_SIZE 1024 - -// в этот список пакет добавляется когда перемещается из input_queue в input_send_q, при этом к пакету добавляется struct INFLIGHT_PACKET из inflight_pool. -// пакет полностью удаляется когда приходит ACK (либо conn_reset/close) -struct INFLIGHT_PACKET { - struct ll_entry ll; - struct ETCP_LINK* last_link; // Last sent link - struct ETCP_DGRAM* pkt; // Packet - struct INFLIGHT_PACKET* next_hash; // for INFLIGHT_HASH list. hash as seq%inflight_hash_size - uint64_t last_timestamp; // Last send timestamp - uint32_t seq; // packet seq (ID по документации) - uint8_t send_count; // Number of sends - uint8_t retrans_req_count; // Number of retrans requests - uint8_t state; // WAIT_ACK or WAIT_SEND -}; - -struct INFLIGHT_HASH { - struct INFLIGHT_PACKET* next; -}; - -// RX packet for assembly linked list -struct RX_PACKET { - struct RX_PACKET* next_hash; // for RX_HASH list. hash as seq%rx_hash_size - uint32_t seq; - uint16_t timestamp; - struct ETCP_DGRAM* pkt; // Packet -}; - -struct RX_HASH { - struct RX_PACKET* next; -}; - -// ETCP connection structure (refactored) -struct ETCP_CONN { - struct ETCP_CONN* next; - int mtu; - - struct UTUN_INSTANCE* instance; - - // Links (channels) - linked list - struct ETCP_LINK* links; - - // Crypto and state - struct secure_channel crypto_ctx; - - // Peer info - uint64_t peer_node_id; // Peer node ID - -// ============ Processing incoming data to be sent by ETCP - struct ll_queue* input_queue; // Incoming packets to send - - // Inflight очереди (2 шт) - пока пакет в статусе inflight - к нему прикрепляется struct INFLIGHT_PACKET - struct memory_pool* inflight_pool; // память для inflight очередей - struct ll_queue* input_send_q; // очередь на отправку (с элементами struct INFLIGHT_PACKET) - struct ll_queue* input_wait_ack; // очередь ожидающих подтверждение (с элементами struct INFLIGHT_PACKET) - struct INFLIGHT_HASH* inflight_hash; // хеш. динамически выделяется при инициализации. пока фикс размер. - uint32_t inflight_hash_size; -// todo: сделать хештаблицу для ускорения поиска пакета в очередях по ID (на 1024 элемента) - - void (*link_ready_for_send_fn)(struct ETCP_CONN*);// функцию которую должен вызвать драйвер линка при готовности линка принимать данные - - struct ll_queue* output_queue; // Assembled outgoing packets - - - // IDs and state - uint16_t next_tx_id; // Next TX ID - uint16_t last_rx_id; // Last received ID - uint16_t last_delivered_id; // Last delivered to output_queue - - // Metrics (RTT, jitter, etc.) - uint16_t rtt_last; - uint16_t rtt_avg_10; - uint16_t rtt_avg_100; - uint16_t jitter; - uint32_t bytes_sent_total; - uint32_t bytes_received_total; - uint32_t retransmissions_count; - - // Window and inflight management - uint32_t unacked_bytes; // Current inflight bytes - uint32_t window_size; // Receive window - uint32_t optimal_inflight; // Sum over links - - // Timers - void* retrans_timer; // Retrans check timer - void* ack_timer; // ACK send timer - - // Bandwidth measurement state - uint8_t burst_in_progress; // Burst transmission flag - uint16_t burst_start_id; // Start ID for burst - // ... (add more for meas_ts, meas_resp) - - // Statistics counters - uint32_t ack_packets_count; // Count of ACK packets received - uint16_t last_rx_ack_id; // Last ACK ID received - uint16_t rtt_history[10]; // RTT history for jitter calculation (RTT_HISTORY_SIZE=10) - uint8_t rtt_history_idx; // Current index in RTT history - uint32_t total_packets_sent; // Total packets sent counter - - // Flags - uint8_t wait_timeout_active; // In wait timeout state -}; - -// Functions -struct ETCP_CONN* etcp_connection_create(struct UTUN_INSTANCE* instance); -void etcp_connection_close(struct ETCP_CONN* etcp); - -void etcp_conn_reset(struct ETCP_CONN* etcp); - -// Отправка: используем api ll_queue для очереди ETCP_CONN.input_queue -// Прием: используем api ll_queue для очереди ETCP_CONN.output_queue -// для очередей используется формат - -// Input from etcp_connections (decrypted packet) -void etcp_conn_input(struct ETCP_DGRAM* pkt); - -// Request next packet for load balancer -struct ETCP_DGRAM* etcp_request_pkt(struct ETCP_CONN* etcp); - -#ifdef __cplusplus -} -#endif - -#endif // ETCP_H \ No newline at end of file diff --git a/src/etcp.h2 b/src/etcp.h2 deleted file mode 100755 index 08f75d7fd..000000000 --- a/src/etcp.h2 +++ /dev/null @@ -1,142 +0,0 @@ -// etcp.h - ETCP Protocol Header (refactored based on etcp_protocol.txt) -#ifndef ETCP_H -#define ETCP_H - -#include "etcp_connections.h" -#include "secure_channel.h" -#include "../lib/ll_queue.h" -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// Forward declarations -struct UTUN_INSTANCE; -struct UASYNC; - -uint16_t get_current_timestamp(void); -uint64_t get_current_time_units(void); - -// ETCP packet section types (from protocol spec) -#define ETCP_SECTION_PAYLOAD 0x00 // Data payload -#define ETCP_SECTION_ACK 0x01 // ACK section -#define ETCP_SECTION_RETRANS 0x10 // Retransmission request base (0x10-0x2F) -#define ETCP_SECTION_TIMESTAMP 0x06 // Channel timestamp (example, adjust if needed) -#define ETCP_SECTION_MEAS_TS 0x07 // Measurement timestamp for bandwidth -#define ETCP_SECTION_MEAS_RESP 0x08 // Measurement response - -// Inflight packet states -#define INFLIGHT_STATE_WAIT_ACK 0 -#define INFLIGHT_STATE_WAIT_SEND 1 -#define INFLIGHT_INITIAL_HASH_SIZE 1024 - -// в этот список пакет добавляется когда перемещается из input_queue в input_send_q, при этом к пакету добавляется struct INFLIGHT_PACKET из inflight_pool. -// пакет полностью удаляется когда приходит ACK (либо conn_reset/close) -struct INFLIGHT_PACKET { - struct ll_entry ll; - struct ETCP_LINK* last_link; // Last sent link - struct ETCP_DGRAM* pkt; // Packet - uint64_t last_timestamp; // Last send timestamp - uint32_t seq; // packet seq (ID по документации) - uint8_t send_count; // Number of sends - uint8_t retrans_req_count; // Number of retrans requests - uint8_t state; // WAIT_ACK or WAIT_SEND -}; - -// RX packet for assembly linked list -struct RX_PACKET { - uint32_t seq; - uint16_t timestamp; - struct ETCP_DGRAM* pkt; // Packet -}; - -// ETCP connection structure (refactored) -struct ETCP_CONN { - struct ETCP_CONN* next; - int mtu; - - struct UTUN_INSTANCE* instance; - - // Links (channels) - linked list - struct ETCP_LINK* links; - - // Crypto and state - struct secure_channel crypto_ctx; - - // Peer info - uint64_t peer_node_id; // Peer node ID - -// ============ Processing incoming data to be sent by ETCP - struct ll_queue* input_queue; // Incoming packets to send - - // Inflight очереди (2 шт) - пока пакет в статусе inflight - к нему прикрепляется struct INFLIGHT_PACKET - struct memory_pool* inflight_pool; // память для inflight очередей - struct ll_queue* input_send_q; // очередь на отправку (с элементами struct INFLIGHT_PACKET) - struct ll_queue* input_wait_ack; // очередь ожидающих подтверждение (с элементами struct INFLIGHT_PACKET) - - void (*link_ready_for_send_fn)(struct ETCP_CONN*);// функцию которую должен вызвать драйвер линка при готовности линка принимать данные - - struct ll_queue* output_queue; // Assembled outgoing packets - - - // IDs and state - uint16_t next_tx_id; // Next TX ID - uint16_t last_rx_id; // Last received ID - uint16_t last_delivered_id; // Last delivered to output_queue - - // Metrics (RTT, jitter, etc.) - uint16_t rtt_last; - uint16_t rtt_avg_10; - uint16_t rtt_avg_100; - uint16_t jitter; - uint32_t bytes_sent_total; - uint32_t bytes_received_total; - uint32_t retransmissions_count; - - // Window and inflight management - uint32_t unacked_bytes; // Current inflight bytes - uint32_t window_size; // Receive window - uint32_t optimal_inflight; // Sum over links - - // Timers - void* retrans_timer; // Retrans check timer - void* ack_timer; // ACK send timer - - // Bandwidth measurement state - uint8_t burst_in_progress; // Burst transmission flag - uint16_t burst_start_id; // Start ID for burst - // ... (add more for meas_ts, meas_resp) - - // Statistics counters - uint32_t ack_packets_count; // Count of ACK packets received - uint16_t last_rx_ack_id; // Last ACK ID received - uint16_t rtt_history[10]; // RTT history for jitter calculation (RTT_HISTORY_SIZE=10) - uint8_t rtt_history_idx; // Current index in RTT history - uint32_t total_packets_sent; // Total packets sent counter - - // Flags - uint8_t wait_timeout_active; // In wait timeout state -}; - -// Functions -struct ETCP_CONN* etcp_connection_create(struct UTUN_INSTANCE* instance); -void etcp_connection_close(struct ETCP_CONN* etcp); - -void etcp_conn_reset(struct ETCP_CONN* etcp); - -// Отправка: используем api ll_queue для очереди ETCP_CONN.input_queue -// Прием: используем api ll_queue для очереди ETCP_CONN.output_queue -// для очередей используется формат - -// Input from etcp_connections (decrypted packet) -void etcp_conn_input(struct ETCP_DGRAM* pkt); - -// Request next packet for load balancer -struct ETCP_DGRAM* etcp_request_pkt(struct ETCP_CONN* etcp); - -#ifdef __cplusplus -} -#endif - -#endif // ETCP_H diff --git a/src/etcp_connections.c b/src/etcp_connections.c index 598d5708d..f8a6a2e7a 100644 --- a/src/etcp_connections.c +++ b/src/etcp_connections.c @@ -13,6 +13,7 @@ #include "../lib/memory_pool.h" #include "../lib/u_async.h" #include "../lib/debug_config.h" +#include "etcp_loadbalancer.h" #include // Packet dump configuration @@ -384,6 +385,13 @@ struct ETCP_SOCKET* etcp_socket_add(struct UTUN_INSTANCE* instance, struct socka e_sock->socket_id = uasync_add_socket(instance->ua, e_sock->fd, etcp_connections_read_callback, NULL, NULL, e_sock); + if (!e_sock->socket_id) { + DEBUG_ERROR(DEBUG_CATEGORY_CONNECTION, "Failed to register socket with uasync (fd=%d)", e_sock->fd); + close(e_sock->fd); + free(e_sock); + return NULL; + } + DEBUG_INFO(DEBUG_CATEGORY_CONNECTION, "Registered ETCP socket with uasync (fd=%d)", e_sock->fd); DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[ETCP] Socket %p (fd=%d) registered and active", e_sock, e_sock->fd); @@ -581,7 +589,7 @@ static void etcp_connections_read_callback(int fd, void* arg) { sc_init_ctx(&sc, &e_sock->instance->my_keys); // printf("[ETCP DEBUG] Extracting peer public key from position %ld, total packet size=%zd\n", recv_len-SC_PUBKEY_SIZE, recv_len); // printf("[ETCP DEBUG] Last 64 bytes of packet (PUBKEY): "); - for (int i=0; icode==0x02) etcp_conn_reset(conn); struct { @@ -921,6 +930,7 @@ int init_connections(struct UTUN_INSTANCE* instance) { instance->connections_count++; DEBUG_ERROR(DEBUG_CATEGORY_CONNECTION, "Added connection %p to instance, total count: %d", etcp_conn, instance->connections_count); + client = client->next; } // If there are clients configured but no connections created, that's an error diff --git a/src/etcp_loadbalancer.c b/src/etcp_loadbalancer.c index a905a75fb..106de1b96 100755 --- a/src/etcp_loadbalancer.c +++ b/src/etcp_loadbalancer.c @@ -90,6 +90,7 @@ void etcp_loadbalancer_send(struct ETCP_DGRAM* dgram) { struct ETCP_CONN* etcp = dgram->link ? dgram->link->etcp : NULL; if (!etcp) { DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "etcp_loadbalancer_send: no ETCP_CONN associated with dgram"); + free(dgram); return; } @@ -112,41 +113,42 @@ void etcp_loadbalancer_send(struct ETCP_DGRAM* dgram) { int send_result = etcp_encrypt_send(dgram); if (send_result != 0) { DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "etcp_loadbalancer_send: encrypt/send failed (%d)", send_result); - return; + // Don't return here, let the function continue to free dgram at the end } // Update shaper after successful send if (link->bandwidth == 0) { DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "etcp_loadbalancer_send: unlimited bandwidth, skipping shaper update"); - return; + // Don't return here, let the function continue to free dgram at the end + } else { + // Time to transmit (ns per byte = 8e9 / bw for bits/sec) + double byte_time_ns = 8000000000.0 / (double)link->bandwidth; + uint64_t tx_time_ns = (uint64_t)(pkt_size * byte_time_ns + 0.5); // Round nearest + + // To sub_nanotime (*10 for 0.1ns) + uint64_t tx_sub = tx_time_ns * 10; + + // Add to load + link->shaper_sub_nanotime += tx_sub; + uint64_t carry=link->shaper_sub_nanotime / SUB_MODULO; + link->shaper_sub_nanotime -= carry * SUB_MODULO; + link->shaper_load_time_tb += carry; + + // Check if exceeds burst -> schedule timer + uint64_t now_tb=get_current_time_units(); + if (link->shaper_load_time_tb >= now_tb + SHAPER_BURST_DELAY_TB) { + uint64_t wait_tb = link->shaper_load_time_tb - now_tb; + link->shaper_timer = uasync_set_timeout(link->etcp->instance->ua, wait_tb, link, shaper_timer_cb); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_loadbalancer_send: scheduled shaper timer (wait_tb=%llu)", (unsigned long long)wait_tb); + } + + // Inactivity correction + if (link->shaper_load_time_tb < now_tb-ALLOWED_DELTA) link->shaper_load_time_tb = now_tb-ALLOWED_DELTA; } - - // Time to transmit (ns per byte = 8e9 / bw for bits/sec) - double byte_time_ns = 8000000000.0 / (double)link->bandwidth; - uint64_t tx_time_ns = (uint64_t)(pkt_size * byte_time_ns + 0.5); // Round nearest - - // To sub_nanotime (*10 for 0.1ns) - uint64_t tx_sub = tx_time_ns * 10; - - // Add to load - link->shaper_sub_nanotime += tx_sub; - uint64_t carry=link->shaper_sub_nanotime / SUB_MODULO; - link->shaper_sub_nanotime -= carry * SUB_MODULO; - link->shaper_load_time_tb += carry; - - // Check if exceeds burst -> schedule timer - uint64_t now_tb=get_current_time_units(); - if (link->shaper_load_time_tb >= now_tb + SHAPER_BURST_DELAY_TB) { - uint64_t wait_tb = link->shaper_load_time_tb - now_tb; - link->shaper_timer = uasync_set_timeout(link->etcp->instance->ua, wait_tb, link, shaper_timer_cb); - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_loadbalancer_send: scheduled shaper timer (wait_tb=%llu)", (unsigned long long)wait_tb); - } - - // Inactivity correction - if (link->shaper_load_time_tb < now_tb-ALLOWED_DELTA) link->shaper_load_time_tb = now_tb-ALLOWED_DELTA; - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "etcp_loadbalancer_send: updated load_tb=%llu, sub=%llu, state=%u", (unsigned long long)link->shaper_load_time_tb, (unsigned long long)link->shaper_sub_nanotime, link->shaper_timer==NULL?1:0); + + free(dgram); // Free the dgram in all cases - we own it } // New: Notify when link is ready (called from timer or external) diff --git a/src/etcp_send_test.txt b/src/etcp_send_test.txt new file mode 100755 index 000000000..917f63f27 --- /dev/null +++ b/src/etcp_send_test.txt @@ -0,0 +1,8 @@ +сделай тест проверки отправкив в udp (etcp_loadbalancer) + + +1. инициализируешь etcp без линков, и один сокет для работы +2. вписываешь в link_ready_for_send_fn свою функцию +3. в тесте открываешь ответный сокет +4. добавляешь линк к etcp +5. \ No newline at end of file diff --git a/src/tun_if.c b/src/tun_if.c index 7e36fb58a..19ce955b9 100644 --- a/src/tun_if.c +++ b/src/tun_if.c @@ -2,7 +2,6 @@ #define _POSIX_C_SOURCE 200809L #include "tun_if.h" #include "../lib/debug_config.h" -#include "routing.h" #include "../lib/u_async.h" #include "etcp_connections.h" @@ -281,29 +280,8 @@ void tun_read_callback(int fd, void* user_arg) { if (nread > 0) { // Route packet based on destination IP uint32_t dest_ip = get_dest_ip(buffer, nread); - struct route_entry route; - if (routing_table_lookup(instance->routing_table, dest_ip, &route)) { - // Found route, send to next hop connection - if (route.next_hop) { - struct sockaddr_in dest_addr; - memset(&dest_addr, 0, sizeof(dest_addr)); - dest_addr.sin_family = AF_INET; - dest_addr.sin_addr.s_addr = route.next_hop_ip; -// todo: отправлять в модуль роутинга все входящие пакеты. когда этот модуль будет. модуль роутинга это не роутинг таблица (routing.h) -// if (etcp_connections_send(route.next_hop, buffer, nread, (struct sockaddr*)&dest_addr, sizeof(dest_addr)) < 0) { -// DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to send packet via route"); -// } - } else { - // Local route - no forwarding needed - DEBUG_DEBUG(DEBUG_CATEGORY_ROUTING, "Local packet, no forwarding"); - } - } else { - // No route found, drop packet - char ip_str[16]; - ip_to_string(dest_ip, ip_str); - DEBUG_ERROR(DEBUG_CATEGORY_ROUTING, "No route for destination IP %s", ip_str); - } +//... } } diff --git a/src/utun.c b/src/utun.c index d632c7781..f23e3124f 100644 --- a/src/utun.c +++ b/src/utun.c @@ -198,10 +198,15 @@ static int daemonize(void) { // Redirect to /dev/null int fd = open("/dev/null", O_RDWR); if (fd >= 0) { - dup2(fd, STDIN_FILENO); - dup2(fd, STDOUT_FILENO); - dup2(fd, STDERR_FILENO); + if (dup2(fd, STDIN_FILENO) < 0 || dup2(fd, STDOUT_FILENO) < 0 || dup2(fd, STDERR_FILENO) < 0) { + DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to redirect file descriptors to /dev/null"); + close(fd); + return -1; + } if (fd > 2) close(fd); + } else { + DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to open /dev/null: %s", strerror(errno)); + return -1; } return 0; @@ -246,13 +251,19 @@ int main(int argc, char *argv[]) { } // Initialize global debug system early if configured from command line + + debug_config_init(); + debug_set_level(DEBUG_LEVEL_TRACE); + debug_set_categories(DEBUG_CATEGORY_ALL); + debug_enable_function_name(1); + if (args.debug_config) { - debug_config_init(); - if (debug_parse_config(args.debug_config) < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Invalid debug configuration: %s", args.debug_config); - return 1; - } + debug_parse_config(args.debug_config); } + if (args.log_file) { + debug_set_output_file(args.log_file); + } + // Create uasync instance struct UASYNC* ua = uasync_create(); @@ -263,28 +274,12 @@ int main(int argc, char *argv[]) { } // Create and initialize instance - struct UTUN_INSTANCE *instance = utun_instance_create(ua, args.config_file, args.log_file); + struct UTUN_INSTANCE *instance = utun_instance_create(ua, args.config_file); if (!instance) { DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Failed to create UTUN instance"); return 1; } - // Apply debug configuration from config file (CLI arguments have priority) - int cli_override_level = (args.debug_config != NULL); - int cli_override_categories = (args.debug_config != NULL); - - debug_apply_config_values( - instance->config->global.log_file, - instance->config->global.debug_level, - instance->config->global.debug_categories, - instance->config->global.enable_timestamp, - instance->config->global.enable_function_names, - instance->config->global.enable_file_lines, - instance->config->global.enable_colors, - cli_override_level, - cli_override_categories - ); - // Print config for debugging if (args.foreground) { print_config(instance->config); diff --git a/src/utun_instance.c b/src/utun_instance.c index 0269c9f5f..2cd88fe2e 100644 --- a/src/utun_instance.c +++ b/src/utun_instance.c @@ -35,18 +35,19 @@ void utun_instance_set_tun_init_enabled(int enabled) { // Create and initialize root instance -struct UTUN_INSTANCE* utun_instance_create(struct UASYNC* ua, const char *config_file, const char *log_file) { +struct UTUN_INSTANCE* utun_instance_create(struct UASYNC* ua, const char *config_file) { + DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "blablabla 11"); struct UTUN_INSTANCE *instance = calloc(1, sizeof(struct UTUN_INSTANCE)); if (!instance) return NULL; // Initialize basic fields instance->running = 0; - instance->log_fp = NULL; instance->ua = ua; // Note: Global debug system is initialized from command line arguments if provided // If not initialized via command line, instance-specific logging can be set up here // The first initialization wins - either global (from main) or instance-specific + DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "blablabla 11"); // Ensure keys and node_id exist in config if (config_ensure_keys_and_node_id(config_file) < 0) { @@ -54,6 +55,8 @@ struct UTUN_INSTANCE* utun_instance_create(struct UASYNC* ua, const char *config free(instance); return NULL; } + + DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "blablabla 12"); // Load configuration instance->config = parse_config(config_file); @@ -64,11 +67,8 @@ struct UTUN_INSTANCE* utun_instance_create(struct UASYNC* ua, const char *config } // Open log file only if not using global debug system output - if (log_file && !g_debug_config.output_file) { - instance->log_fp = fopen(log_file, "a"); - if (!instance->log_fp) { - DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Failed to open log file %s: %s", log_file, strerror(errno)); - } + if (instance->config->global.log_file) { + debug_set_output_file(instance->config->global.log_file); } // Set node_id from config instance->node_id = instance->config->global.my_node_id; @@ -78,7 +78,11 @@ struct UTUN_INSTANCE* utun_instance_create(struct UASYNC* ua, const char *config DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Failed to initialize local keys"); } + DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "blablabla 2"); + + instance->ack_pool=memory_pool_init(sizeof(struct ACK_PACKET)); + instance->data_pool=memory_pool_init(PACKET_DATA_SIZE); instance->pkt_pool=memory_pool_init(sizeof(struct ETCP_DGRAM) + PACKET_DATA_SIZE); // Initialize TUN device only if enabled @@ -143,24 +147,6 @@ struct UTUN_INSTANCE* utun_instance_create(struct UASYNC* ua, const char *config instance->tun.fd = -1; // Invalid file descriptor to indicate no TUN device } - // Create routing table - instance->routing_table = routing_table_create(); - if (!instance->routing_table) { - DEBUG_ERROR(DEBUG_CATEGORY_ROUTING, "Failed to create routing table"); - tun_close(&instance->tun); - free(instance); - return NULL; - } - // Initialize connections from configuration - moved to utun_instance_init - // to avoid double initialization - /* - if (init_connections(instance) < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to initialize connections"); - // Cleanup will be handled by utun_instance_destroy - return NULL; - } - */ - return instance; } @@ -207,13 +193,6 @@ void utun_instance_destroy(struct UTUN_INSTANCE *instance) { instance->connections = NULL; DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] ETCP connections cleanup complete"); - // Cleanup other components - if (instance->routing_table) { - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Destroying routing table"); - routing_table_destroy(instance->routing_table); - instance->routing_table = NULL; - } - // Cleanup TUN if (instance->tun.fd >= 0) { DEBUG_INFO(DEBUG_CATEGORY_TUN, "Closing TUN interface: %s", instance->tun.ifname); @@ -227,13 +206,6 @@ void utun_instance_destroy(struct UTUN_INSTANCE *instance) { instance->config = NULL; } - // Close log file - if (instance->log_fp) { - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Closing log file"); - fclose(instance->log_fp); - instance->log_fp = NULL; - } - // Cleanup packet pool (ensure no leak if stop wasn't called) if (instance->pkt_pool) { DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Destroying packet pool"); @@ -241,6 +213,13 @@ void utun_instance_destroy(struct UTUN_INSTANCE *instance) { instance->pkt_pool = NULL; } + // Cleanup packet pool (ensure no leak if stop wasn't called) + if (instance->ack_pool) { + DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Destroying ack pool"); + memory_pool_destroy(instance->ack_pool); + instance->ack_pool = NULL; + } + // FINALLY destroy uasync (after all resources are cleaned up) if (instance->ua) { DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Destroying uasync instance"); diff --git a/src/utun_instance.c.backup b/src/utun_instance.c.backup deleted file mode 100644 index e0dae7ea9..000000000 --- a/src/utun_instance.c.backup +++ /dev/null @@ -1,314 +0,0 @@ -// utun_instance.c - Root instance implementation -#include "utun_instance.h" -#include "config_parser.h" -#include "config_updater.h" -#include "tun_if.h" -#include "routing.h" -#include "etcp_connections.h" -#include "etcp.h" -#include "../lib/u_async.h" -#include "../lib/debug_config.h" -#include -#include -#include -#include -#include -#include - -// Forward declarations -static void tun_read_callback(int fd, void* user_arg); -static uint32_t get_dest_ip(const uint8_t *packet, size_t len); - -// Global instance for signal handlers -static struct UTUN_INSTANCE *g_instance = NULL; - -// Create and initialize root instance -struct UTUN_INSTANCE* utun_instance_create(struct UASYNC* ua, const char *config_file, const char *log_file) { - struct UTUN_INSTANCE *instance = calloc(1, sizeof(struct UTUN_INSTANCE)); - if (!instance) return NULL; - - // Initialize basic fields - instance->running = 0; - instance->log_fp = NULL; - instance->ua = ua; - - // Ensure keys and node_id exist in config - if (config_ensure_keys_and_node_id(config_file) < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Failed to ensure keys and node_id in config: %s", config_file); - free(instance); - return NULL; - } - - // Load configuration - instance->config = parse_config(config_file); - if (!instance->config) { - DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Failed to load config from %s", config_file); - free(instance); - return NULL; - } - - // Open log file - if (log_file) { - instance->log_fp = fopen(log_file, "a"); - if (!instance->log_fp) { - DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Failed to open log file %s: %s", log_file, strerror(errno)); - } - } - // Set node_id from config - instance->node_id = instance->config->global.my_node_id; - - // Set my keys - if (sc_init_local_keys(&instance->my_keys, instance->config->global.my_public_key_hex, instance->config->global.my_private_key_hex)) { - DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Failed to initialize local keys"); - } - - - instance->pkt_pool=memory_pool_init(PACKET_DATA_SIZE+100); -/* - // Initialize TUN device - if (tun_create(&instance->tun) < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_TUN, "Failed to create TUN device"); - return -1; - } - - // Configure TUN device - if (tun_set_ip(instance->tun.ifname, instance->config->global.tun_ip) < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_TUN, "Failed to set TUN IP"); - tun_close(&instance->tun); - return -1; - } - - if (instance->config->global.mtu > 0) { - if (tun_set_mtu(instance->tun.ifname, instance->config->global.mtu) < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_TUN, "Failed to set TUN MTU"); - tun_close(&instance->tun); - return -1; - } - } - - if (tun_set_up(instance->tun.ifname) < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_TUN, "Failed to bring up TUN interface"); - tun_close(&instance->tun); - return -1; - } - - // Create routing table - instance->routing_table = routing_table_create(); - if (!instance->routing_table) { - DEBUG_ERROR(DEBUG_CATEGORY_ROUTING, "Failed to create routing table"); - return -1; - } -*/ - // Initialize connections from configuration - moved to utun_instance_init - // to avoid double initialization - /* - if (init_connections(instance) < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to initialize connections"); - // Cleanup will be handled by utun_instance_destroy - return NULL; - } - */ - - return instance; -} - -// Destroy instance and cleanup resources -void utun_instance_destroy(struct UTUN_INSTANCE *instance) { - if (!instance) return; - - printf("[INSTANCE_DESTROY] Starting cleanup for instance %p\n", instance); - - // Диагностика ресурсов ДО cleanup - utun_instance_diagnose_leaks(instance, "BEFORE_CLEANUP"); - - // Stop running if not already - instance->running = 0; - - // Cleanup ETCP sockets and connections FIRST (before destroying uasync) - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Cleaning up ETCP sockets and connections"); - struct ETCP_SOCKET* sock = instance->etcp_sockets; - while (sock) { - struct ETCP_SOCKET* next = sock->next; - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Removing socket %p, fd=%d", sock, sock->fd); - etcp_socket_remove(sock); // Полный cleanup сокета - sock = next; - } - instance->etcp_sockets = NULL; - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] ETCP sockets cleanup complete"); - - struct ETCP_CONN* conn = instance->connections; - while (conn) { - struct ETCP_CONN* next = conn->next; - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Closing connection %p", conn); - etcp_connection_close(conn); // Закрыть соединение - conn = next; - } - instance->connections = NULL; - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] ETCP connections cleanup complete"); - - // Cleanup other components - if (instance->routing_table) { - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Destroying routing table"); - routing_table_destroy(instance->routing_table); - instance->routing_table = NULL; - } - - // Cleanup TUN - if (instance->tun.fd >= 0) { - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Closing TUN interface"); - tun_close(&instance->tun); - } - - // Cleanup config - if (instance->config) { - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Freeing configuration"); - free_config(instance->config); - instance->config = NULL; - } - - // Close log file - if (instance->log_fp) { - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Closing log file"); - fclose(instance->log_fp); - instance->log_fp = NULL; - } - - // Cleanup packet pool (ensure no leak if stop wasn't called) - if (instance->pkt_pool) { - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Destroying packet pool"); - memory_pool_destroy(instance->pkt_pool); - instance->pkt_pool = NULL; - } - - // FINALLY destroy uasync (after all resources are cleaned up) - if (instance->ua) { - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Destroying uasync instance"); - uasync_destroy(instance->ua); - instance->ua = NULL; - } - - // Clear global instance - if (g_instance == instance) { - g_instance = NULL; - } - - // Free the instance memory - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Freeing instance memory"); - free(instance); - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "[INSTANCE_DESTROY] Instance destroyed completely"); -} - -// Stop instance -void utun_instance_stop(struct UTUN_INSTANCE *instance) { - if (!instance) return; - instance->running = 0; - // Wakeup main loop using built-in uasync wakeup - if (instance->ua) { - memory_pool_destroy(instance->pkt_pool); - uasync_wakeup(instance->ua); - } - - -} - -int utun_instance_init(struct UTUN_INSTANCE *instance) { - if (!instance) return -1; - - // Initialize connections - if (init_connections(instance) < 0) { - return -1; - } - - return 0; -} - -// Диагностическая функция для анализа утечек -void utun_instance_diagnose_leaks(struct UTUN_INSTANCE *instance, const char *phase) { - if (!instance) { - printf("[DIAGNOSE] NULL instance for phase: %s\n", phase); - return; - } - - struct { - int etcp_sockets_count; - int etcp_connections_count; - int etcp_links_count; - } report = {0}; - - // Подсчёт ETCP сокетов - struct ETCP_SOCKET *sock = instance->etcp_sockets; - while (sock) { - report.etcp_sockets_count++; - // Подсчёт линков в каждом сокете - for (size_t i = 0; i < sock->num_channels; i++) { - if (sock->links[i]) { - report.etcp_links_count++; - } - } - sock = sock->next; - } - - // Подсчёт ETCP соединений - struct ETCP_CONN *conn = instance->connections; - while (conn) { - report.etcp_connections_count++; - // Подсчёт линков в соединениях - struct ETCP_LINK *link = conn->links; - while (link) { - report.etcp_links_count++; - link = link->next; - } - conn = conn->next; - } - - printf("\n🔍 [UTUN_INSTANCE LEAK DIAGNOSIS] Phase: %s\n", phase); - printf(" Instance: %p\n", instance); - printf(" Node ID: %llu\n", (unsigned long long)instance->node_id); - printf(" UA instance: %p\n", instance->ua); - printf(" Running: %d\n", instance->running); - - printf("\n📊 STRUCTURE COUNTS:\n"); - printf(" ETCP Sockets: %d active\n", report.etcp_sockets_count); - printf(" ETCP Connections: %d active\n", report.etcp_connections_count); - printf(" ETCP Links: %d total\n", report.etcp_links_count); - - printf("\n🔧 RESOURCE STATUS:\n"); - printf(" Memory Pool: %s\n", instance->pkt_pool ? "ALLOCATED" : "NULL"); - printf(" TUN Socket ID: %p\n", instance->tun_socket_id); - printf(" TUN FD: %d\n", instance->tun.fd); - printf(" Connections list: %p\n", instance->connections); - printf(" ETCP Sockets list: %p\n", instance->etcp_sockets); - - printf("\n⚠️ POTENTIAL LEAKS:\n"); - if (instance->pkt_pool) { - printf(" ❌ Memory Pool not freed\n"); - } - if (instance->tun_socket_id) { - printf(" ❌ TUN socket not unregistered from uasync\n"); - } - if (report.etcp_sockets_count > 0) { - printf(" ❌ %d ETCP sockets still allocated\n", report.etcp_sockets_count); - } - if (report.etcp_connections_count > 0) { - printf(" ❌ %d ETCP connections still allocated\n", report.etcp_connections_count); - } - if (report.etcp_links_count > 0) { - printf(" ❌ %d ETCP links still allocated\n", report.etcp_links_count); - } - - printf("\n📋 RECOMMENDATIONS:\n"); - if (instance->pkt_pool) { - printf(" → Call memory_pool_destroy() before freeing instance\n"); - } - if (instance->tun_socket_id) { - printf(" → Call uasync_remove_socket() for TUN socket\n"); - } - if (report.etcp_sockets_count > 0) { - printf(" → Iterate and call etcp_socket_remove() for each socket\n"); - } - if (report.etcp_connections_count > 0) { - printf(" → Iterate and call etcp_connection_close() for each connection\n"); - } - - printf("\n"); -} diff --git a/src/utun_instance.c1 b/src/utun_instance.c1 deleted file mode 100755 index 2cb5bda38..000000000 --- a/src/utun_instance.c1 +++ /dev/null @@ -1,230 +0,0 @@ -// utun_instance.c - Root instance implementation -#include "utun_instance.h" -#include "config_parser.h" -#include "config_updater.h" -#include "tun_if.h" -#include "routing.h" -#include "etcp_connections.h" -#include "etcp.h" -#include "../lib/u_async.h" -#include "../lib/debug_config.h" -#include -#include -#include -#include -#include -#include - -// Forward declarations -static void tun_read_callback(int fd, void* user_arg); -static uint32_t get_dest_ip(const uint8_t *packet, size_t len); - -// Global instance for signal handlers -static struct UTUN_INSTANCE *g_instance = NULL; - -// Create and initialize root instance -struct UTUN_INSTANCE* utun_instance_create(struct UASYNC* ua, const char *config_file, const char *log_file) { - struct UTUN_INSTANCE *instance = calloc(1, sizeof(struct UTUN_INSTANCE)); - if (!instance) return NULL; - - // Initialize basic fields - instance->running = 0; - instance->log_fp = NULL; - instance->ua = ua; - - // Ensure keys and node_id exist in config - if (config_ensure_keys_and_node_id(config_file) < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Failed to ensure keys and node_id in config: %s", config_file); - free(instance); - return NULL; - } - - // Load configuration - instance->config = parse_config(config_file); - if (!instance->config) { - DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Failed to load config from %s", config_file); - free(instance); - return NULL; - } - - // Open log file - if (log_file) { - instance->log_fp = fopen(log_file, "a"); - if (!instance->log_fp) { - DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Failed to open log file %s: %s", log_file, strerror(errno)); - } - } - // Set node_id from config - instance->node_id = instance->config->global.my_node_id; - - // Set my keys - if (sc_init_local_keys(&instance->my_keys, instance->config->global.my_public_key_hex, instance->config->global.my_private_key_hex)) { - DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Failed to initialize local keys"); - } - - - instance->pkt_pool=memory_pool_init(PACKET_DATA_SIZE+100); -/* - // Initialize TUN device - if (tun_create(&instance->tun) < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_TUN, "Failed to create TUN device"); - return -1; - } - - // Configure TUN device - if (tun_set_ip(instance->tun.ifname, instance->config->global.tun_ip) < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_TUN, "Failed to set TUN IP"); - tun_close(&instance->tun); - return -1; - } - - if (instance->config->global.mtu > 0) { - if (tun_set_mtu(instance->tun.ifname, instance->config->global.mtu) < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_TUN, "Failed to set TUN MTU"); - tun_close(&instance->tun); - return -1; - } - } - - if (tun_set_up(instance->tun.ifname) < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_TUN, "Failed to bring up TUN interface"); - tun_close(&instance->tun); - return -1; - } - - // Create routing table - instance->routing_table = routing_table_create(); - if (!instance->routing_table) { - DEBUG_ERROR(DEBUG_CATEGORY_ROUTING, "Failed to create routing table"); - return -1; - } -*/ - // Initialize connections from configuration - moved to utun_instance_init - // to avoid double initialization - /* - if (init_connections(instance) < 0) { - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to initialize connections"); - // Cleanup will be handled by utun_instance_destroy - return NULL; - } - */ - - return instance; -} - -// Destroy instance and cleanup resources -void utun_instance_destroy(struct UTUN_INSTANCE *instance) { - if (!instance) return; - - printf("[INSTANCE_DESTROY] Starting cleanup for instance %p\n", instance); - - // Stop running - instance->running = 0; - - // Cleanup ETCP sockets and connections FIRST (before destroying uasync) - printf("[INSTANCE_DESTROY] Cleaning up ETCP sockets and connections\n"); - if (instance->etcp_sockets) { - printf("[INSTANCE_DESTROY] Found ETCP sockets to cleanup\n"); - struct ETCP_SOCKET* sock = instance->etcp_sockets; - while (sock) { - struct ETCP_SOCKET* next = sock->next; - printf("[INSTANCE_DESTROY] Removing socket %p, fd=%d\n", sock, sock->fd); - etcp_socket_remove(sock); // Полный cleanup сокета - sock = next; - } - instance->etcp_sockets = NULL; - printf("[INSTANCE_DESTROY] ETCP sockets cleanup complete\n"); - } - - if (instance->connections) { - printf("[INSTANCE_DESTROY] Found ETCP connections to cleanup\n"); - struct ETCP_CONN* conn = instance->connections; - while (conn) { - struct ETCP_CONN* next = conn->next; - printf("[INSTANCE_DESTROY] Closing connection %p\n", conn); - etcp_connection_close(conn); // Закрыть соединение - conn = next; - } - instance->connections = NULL; - printf("[INSTANCE_DESTROY] ETCP connections cleanup complete\n"); - } - - // Cleanup other components - if (instance->routing_table) { - routing_table_destroy(instance->routing_table); - } - - // Cleanup TUN - if (instance->tun.fd >= 0) { - tun_close(&instance->tun); - } - - // Cleanup config - if (instance->config) { - free_config(instance->config); - } - - // Close log file - if (instance->log_fp) { - fclose(instance->log_fp); - } - - // FINALLY destroy uasync (after all resources are cleaned up) - printf("[INSTANCE_DESTROY] Destroying uasync instance\n"); - if (instance->ua) { - uasync_destroy(instance->ua); - } - - // Free the instance memory - printf("[INSTANCE_DESTROY] Freeing instance memory\n"); - free(instance); - printf("[INSTANCE_DESTROY] Instance destroyed completely\n"); - - // Cleanup TUN - if (instance->tun.fd >= 0) { - tun_close(&instance->tun); - } - - // Cleanup config - if (instance->config) { - free_config(instance->config); - } - - // Close log file - if (instance->log_fp) { - fclose(instance->log_fp); - } - - // uasync cleanup will handle its built-in wakeup pipe - - // Clear global instance - if (g_instance == instance) { - g_instance = NULL; - } - - free(instance); -} - -// Stop instance -void utun_instance_stop(struct UTUN_INSTANCE *instance) { - if (!instance) return; - instance->running = 0; - // Wakeup main loop using built-in uasync wakeup - if (instance->ua) { - memory_pool_destroy(instance->pkt_pool); - uasync_wakeup(instance->ua); - } - - -} - -int utun_instance_init(struct UTUN_INSTANCE *instance) { - if (!instance) return -1; - - // Initialize connections - if (init_connections(instance) < 0) { - return -1; - } - - return 0; -} diff --git a/src/utun_instance.h b/src/utun_instance.h index d3af82451..95a6b7bb7 100644 --- a/src/utun_instance.h +++ b/src/utun_instance.h @@ -34,23 +34,21 @@ struct UTUN_INSTANCE { // State int running; - FILE *log_fp; - // Routing - struct routing_table *routing_table; - // Connections (список всех подключений для instance) struct ETCP_CONN* connections;// linked-list int connections_count; // Number of connections + struct memory_pool* data_pool;// для входных-выходных данных пакета struct memory_pool* pkt_pool; + struct memory_pool* ack_pool; // Active sockets struct ETCP_SOCKET* etcp_sockets;// linked-list }; // Functions -struct UTUN_INSTANCE* utun_instance_create(struct UASYNC* ua, const char* config_file, const char* log_file); +struct UTUN_INSTANCE* utun_instance_create(struct UASYNC* ua, const char* config_file); void utun_instance_destroy(struct UTUN_INSTANCE* instance); int utun_instance_init(struct UTUN_INSTANCE *instance); void utun_instance_run(struct UTUN_INSTANCE *instance); diff --git a/test_input_queue_resume.c b/test_input_queue_resume.c new file mode 100644 index 000000000..99d1303e3 --- /dev/null +++ b/test_input_queue_resume.c @@ -0,0 +1,72 @@ +// Simple test to verify input_queue_try_resume logic +#include "src/etcp.h" +#include "lib/ll_queue.h" +#include "lib/u_async.h" +#include +#include + +int main() { + printf("Testing input_queue_try_resume logic...\n"); + + // Create a mock ETCP_CONN structure + struct ETCP_CONN etcp = {0}; + + // Create uasync instance for queues + struct UASYNC* ua = uasync_new(); + if (!ua) { + printf("Failed to create uasync instance\n"); + return 1; + } + + // Create queues + etcp.input_send_q = queue_new(ua, 0); + etcp.input_wait_ack = queue_new(ua, 0); + + if (!etcp.input_send_q || !etcp.input_wait_ack) { + printf("Failed to create queues\n"); + return 1; + } + + // Test case 1: Both queues empty, optimal_inflight = 100 + etcp.optimal_inflight = 100; + printf("Test 1: Empty queues, optimal_inflight=100\n"); + printf(" input_send_q bytes: %zu\n", queue_total_bytes(etcp.input_send_q)); + printf(" input_wait_ack bytes: %zu\n", queue_total_bytes(etcp.input_wait_ack)); + printf(" Total: %zu (should be \u003c 100)\n", + queue_total_bytes(etcp.input_send_q) + queue_total_bytes(etcp.input_wait_ack)); + + // Test case 2: Add some data to make total > optimal_inflight + printf("\nTest 2: Adding data to exceed optimal_inflight\n"); + + // Add 60 bytes to send queue + void* data1 = queue_data_new(60); + queue_data_put(etcp.input_send_q, data1, 1); + + printf(" input_send_q bytes: %zu\n", queue_total_bytes(etcp.input_send_q)); + printf(" input_wait_ack bytes: %zu\n", queue_total_bytes(etcp.input_wait_ack)); + printf(" Total: %zu (should be \u003e= 100)\n", + queue_total_bytes(etcp.input_send_q) + queue_total_bytes(etcp.input_wait_ack)); + + // Test case 3: Add more data to wait_ack queue + printf("\nTest 3: Adding data to wait_ack queue\n"); + + void* data2 = queue_data_new(50); + queue_data_put(etcp.input_wait_ack, data2, 2); + + printf(" input_send_q bytes: %zu\n", queue_total_bytes(etcp.input_send_q)); + printf(" input_wait_ack bytes: %zu\n", queue_total_bytes(etcp.input_wait_ack)); + printf(" Total: %zu (should be \u003e 100)\n", + queue_total_bytes(etcp.input_send_q) + queue_total_bytes(etcp.input_wait_ack)); + + // Cleanup + queue_free(etcp.input_send_q); + queue_free(etcp.input_wait_ack); + uasync_free(ua); + + printf("\n✅ Logic test completed successfully!\n"); + printf("The input_queue_try_resume function should:\n"); + printf("- Resume when total_bytes \u003c optimal_inflight\n"); + printf("- Not resume when total_bytes \u003e= optimal_inflight\n"); + + return 0; +} \ No newline at end of file diff --git a/tests/Makefile.am b/tests/Makefile.am index 430e52efb..fd7d47d54 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -13,7 +13,6 @@ check_PROGRAMS = test_etcp_crypto$(EXEEXT) \ test_packet_dump$(EXEEXT) \ test_u_async_comprehensive$(EXEEXT) \ test_u_async_performance$(EXEEXT) \ - test_debug_new$(EXEEXT) \ test_debug_categories$(EXEEXT) \ test_config_debug$(EXEEXT) @@ -39,8 +38,8 @@ test_etcp_minimal_LDADD = $(top_builddir)/src/utun-etcp.o $(top_builddir)/src/ut # Basic crypto test test_crypto_SOURCES = test_crypto.c -test_crypto_CFLAGS = -I$(top_srcdir)/tinycrypt/lib/include -I$(top_srcdir)/tinycrypt/lib/source -test_crypto_LDADD = $(top_builddir)/tinycrypt/lib/source/utun-aes_encrypt.o $(top_builddir)/tinycrypt/lib/source/utun-aes_decrypt.o $(top_builddir)/tinycrypt/lib/source/utun-ccm_mode.o $(top_builddir)/tinycrypt/lib/source/utun-cmac_mode.o $(top_builddir)/tinycrypt/lib/source/utun-ctr_mode.o $(top_builddir)/tinycrypt/lib/source/utun-sha256.o $(top_builddir)/tinycrypt/lib/source/utun-utils.o -lpthread -lcrypto +test_crypto_CFLAGS = -I$(top_srcdir)/tinycrypt/lib/include -I$(top_srcdir)/tinycrypt/lib/source -I$(top_srcdir)/lib +test_crypto_LDADD = $(top_builddir)/tinycrypt/lib/source/utun-aes_encrypt.o $(top_builddir)/tinycrypt/lib/source/utun-aes_decrypt.o $(top_builddir)/tinycrypt/lib/source/utun-ccm_mode.o $(top_builddir)/tinycrypt/lib/source/utun-cmac_mode.o $(top_builddir)/tinycrypt/lib/source/utun-ctr_mode.o $(top_builddir)/tinycrypt/lib/source/utun-sha256.o $(top_builddir)/tinycrypt/lib/source/utun-utils.o $(top_builddir)/lib/libuasync.a -lpthread -lcrypto # New comprehensive ll_queue test with current API test_ll_queue_SOURCES = test_ll_queue.c @@ -49,7 +48,7 @@ test_ll_queue_LDADD = $(top_builddir)/lib/libuasync.a -lpthread -lcrypto # ECC encryption test test_ecc_encrypt_SOURCES = test_ecc_encrypt.c -test_ecc_encrypt_CFLAGS = -I$(top_srcdir)/tinycrypt/lib/include -I$(top_srcdir)/tinycrypt/lib/source +test_ecc_encrypt_CFLAGS = -I$(top_srcdir)/tinycrypt/lib/include -I$(top_srcdir)/tinycrypt/lib/source -I$(top_srcdir)/lib test_ecc_encrypt_LDADD = $(top_builddir)/src/utun-secure_channel.o $(top_builddir)/src/utun-crc32.o $(top_builddir)/tinycrypt/lib/source/utun-aes_encrypt.o $(top_builddir)/tinycrypt/lib/source/utun-aes_decrypt.o $(top_builddir)/tinycrypt/lib/source/utun-ccm_mode.o $(top_builddir)/tinycrypt/lib/source/utun-cmac_mode.o $(top_builddir)/tinycrypt/lib/source/utun-ctr_mode.o $(top_builddir)/tinycrypt/lib/source/utun-ecc.o $(top_builddir)/tinycrypt/lib/source/utun-ecc_dh.o $(top_builddir)/tinycrypt/lib/source/utun-ecc_dsa.o $(top_builddir)/tinycrypt/lib/source/utun-sha256.o $(top_builddir)/tinycrypt/lib/source/utun-ecc_platform_specific.o $(top_builddir)/tinycrypt/lib/source/utun-utils.o $(top_builddir)/lib/libuasync.a -lpthread -lcrypto # Intensive memory pool test @@ -77,11 +76,6 @@ test_u_async_performance_SOURCES = test_u_async_performance.c test_u_async_performance_CFLAGS = -I$(top_srcdir)/src -I$(top_srcdir)/lib test_u_async_performance_LDADD = $(top_builddir)/lib/libuasync.a -lpthread -lcrypto -# Debug system test -test_debug_new_SOURCES = test_debug_new.c -test_debug_new_CFLAGS = -I$(top_srcdir)/src -I$(top_srcdir)/lib -test_debug_new_LDADD = $(top_builddir)/lib/libuasync.a -lpthread -lcrypto - # Debug categories test test_debug_categories_SOURCES = test_debug_categories.c test_debug_categories_CFLAGS = -I$(top_srcdir)/src -I$(top_srcdir)/lib diff --git a/tests/debug_full_test.c b/tests/debug_full_test.c index 456f8f53a..42ddd4715 100644 --- a/tests/debug_full_test.c +++ b/tests/debug_full_test.c @@ -1,5 +1,6 @@ // Copy the original test file but add debugging #include +#include "../lib/debug_config.h" #include #include #include @@ -10,225 +11,225 @@ #include #include -#include "u_async.h" -#include "timeout_heap.h" +#include "../lib/u_async.h" +#include "../lib/timeout_heap.h" /* Test statistics */ static struct { - int tests_run; - int tests_passed; - int tests_failed; - - /* Timer statistics */ - int timer_callbacks; - int timer_cancellations; - int immediate_timeouts; - - /* Socket statistics */ - int socket_events; - int socket_errors; - - /* Error statistics */ - int memory_allocation_errors; - int invalid_parameter_errors; - int race_condition_errors; +int tests_run; +int tests_passed; +int tests_failed; + +/* Timer statistics */ +int timer_callbacks; +int timer_cancellations; +int immediate_timeouts; + +/* Socket statistics */ +int socket_events; +int socket_errors; + +/* Error statistics */ +int memory_allocation_errors; +int invalid_parameter_errors; +int race_condition_errors; } test_stats = {0}; /* Test result tracking */ #define TEST_START(name) do { \ - printf("TEST: %s... \n", name); \ - printf(" immediate_timeouts before: %d\n", test_stats.immediate_timeouts); \ - test_stats.tests_run++; \ +DEBUG_INFO(DEBUG_CATEGORY_ALL, "TEST: %s... ", name); \ +DEBUG_INFO(DEBUG_CATEGORY_ALL, "immediate_timeouts before: %d", test_stats.immediate_timeouts); \ +test_stats.tests_run++; \ } while(0) #define TEST_PASS() do { \ - printf(" immediate_timeouts after: %d\n", test_stats.immediate_timeouts); \ - printf("PASS\n"); \ - test_stats.tests_passed++; \ +DEBUG_INFO(DEBUG_CATEGORY_ALL, "immediate_timeouts after: %d", test_stats.immediate_timeouts); \ +DEBUG_INFO(DEBUG_CATEGORY_ALL, "PASS"); \ +test_stats.tests_passed++; \ } while(0) #define TEST_FAIL(msg) do { \ - printf(" immediate_timeouts after: %d\n", test_stats.immediate_timeouts); \ - printf("FAIL: %s\n", msg); \ - test_stats.tests_failed++; \ +DEBUG_INFO(DEBUG_CATEGORY_ALL, "immediate_timeouts after: %d", test_stats.immediate_timeouts); \ +DEBUG_INFO(DEBUG_CATEGORY_ALL, "FAIL: %s", msg); \ +test_stats.tests_failed++; \ } while(0) #define ASSERT_EQ(a, b, msg) do { \ - if ((a) != (b)) { \ - TEST_FAIL(msg); \ - printf(" Expected: %ld, Got: %ld\n", (long)(b), (long)(a)); \ - return; \ - } \ +if ((a) != (b)) { \ +TEST_FAIL(msg); \ +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Expected: %ld, Got: %ld", (long)(b), (long)(a)); \ +return; \ +} \ } while(0) #define ASSERT_NOT_NULL(ptr, msg) do { \ - if ((ptr) == NULL) { \ - TEST_FAIL(msg); \ - return; \ - } \ +if ((ptr) == NULL) { \ +TEST_FAIL(msg); \ +return; \ +} \ } while(0) /* Test context for callbacks */ typedef struct { - int callback_count; - int expected_count; - int callback_arg; - int timeout_ms; - uasync_t* ua; - void* timer_id; +int callback_count; +int expected_count; +int callback_arg; +int timeout_ms; +uasync_t* ua; +void* timer_id; } test_context_t; /* Timer callback for testing */ static void test_timer_callback(void* arg) { - test_context_t* ctx = (test_context_t*)arg; - ctx->callback_count++; - test_stats.timer_callbacks++; - - if (ctx->timeout_ms == 0) { - test_stats.immediate_timeouts++; - printf(" IMMEDIATE TIMEOUT: immediate_timeouts now = %d\n", test_stats.immediate_timeouts); - } +test_context_t* ctx = (test_context_t*)arg; +ctx->callback_count++; +test_stats.timer_callbacks++; + +if (ctx->timeout_ms == 0) { +test_stats.immediate_timeouts++; +DEBUG_INFO(DEBUG_CATEGORY_ALL, "IMMEDIATE TIMEOUT: immediate_timeouts now = %d", test_stats.immediate_timeouts); +} } /* Test 1: Basic timer functionality */ static void test_basic_timers(void) { - TEST_START("Basic timer functionality"); - - uasync_t* ua = uasync_create(); - ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); - - test_context_t ctx = {0}; - ctx.expected_count = 3; - ctx.timeout_ms = 10; // Non-zero to avoid immediate timeout counting - - /* Set multiple timers with different timeouts */ - void* timer1 = uasync_set_timeout(ua, 10, &ctx, test_timer_callback); /* 1ms */ - void* timer2 = uasync_set_timeout(ua, 20, &ctx, test_timer_callback); /* 2ms */ - void* timer3 = uasync_set_timeout(ua, 30, &ctx, test_timer_callback); /* 3ms */ - - ASSERT_NOT_NULL(timer1, "Failed to set timer 1"); - ASSERT_NOT_NULL(timer2, "Failed to set timer 2"); - ASSERT_NOT_NULL(timer3, "Failed to set timer 3"); - - /* Poll and verify timers fire in order */ - int poll_count = 0; - while (ctx.callback_count < ctx.expected_count && poll_count < 100) { - uasync_poll(ua, 10); /* 1ms poll */ - poll_count++; - } - - ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Not all timers fired"); - - /* Cleanup */ - uasync_destroy(ua, 0); - TEST_PASS(); +TEST_START("Basic timer functionality"); + +uasync_t* ua = uasync_create(); +ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + +test_context_t ctx = {0}; +ctx.expected_count = 3; +ctx.timeout_ms = 10; // Non-zero to avoid immediate timeout counting + +/* Set multiple timers with different timeouts */ +void* timer1 = uasync_set_timeout(ua, 10, &ctx, test_timer_callback); /* 1ms */ +void* timer2 = uasync_set_timeout(ua, 20, &ctx, test_timer_callback); /* 2ms */ +void* timer3 = uasync_set_timeout(ua, 30, &ctx, test_timer_callback); /* 3ms */ + +ASSERT_NOT_NULL(timer1, "Failed to set timer 1"); +ASSERT_NOT_NULL(timer2, "Failed to set timer 2"); +ASSERT_NOT_NULL(timer3, "Failed to set timer 3"); + +/* Poll and verify timers fire in order */ +int poll_count = 0; +while (ctx.callback_count < ctx.expected_count && poll_count < 100) { +uasync_poll(ua, 10); /* 1ms poll */ +poll_count++; +} + +ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Not all timers fired"); + +/* Cleanup */ +uasync_destroy(ua, 0); +TEST_PASS(); } /* Test 2: Timer cancellation race conditions */ static void test_timer_cancellation_races(void) { - TEST_START("Timer cancellation race conditions"); - - uasync_t* ua = uasync_create(); - ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); - - test_context_t ctx = {0}; - ctx.expected_count = 2; - ctx.timeout_ms = 5; // Non-zero to avoid immediate timeout counting - - /* Create timers that will be cancelled at different stages */ - void* timer1 = uasync_set_timeout(ua, 5, &ctx, test_timer_callback); /* 0.5ms */ - void* timer2 = uasync_set_timeout(ua, 50, &ctx, test_timer_callback); /* 5ms */ - void* timer3 = uasync_set_timeout(ua, 100, &ctx, test_timer_callback); /* 10ms */ - - ASSERT_NOT_NULL(timer1, "Failed to set timer 1"); - ASSERT_NOT_NULL(timer2, "Failed to set timer 2"); - ASSERT_NOT_NULL(timer3, "Failed to set timer 3"); - - /* Cancel timer1 immediately (before it fires) */ - err_t cancel_result = uasync_cancel_timeout(ua, timer1); - ASSERT_EQ(cancel_result, ERR_OK, "Failed to cancel timer 1"); - test_stats.timer_cancellations++; - - /* Poll briefly - timer1 should not fire, others should */ - uasync_poll(ua, 10); /* 1ms */ - - /* Cancel timer2 while it might be firing */ - cancel_result = uasync_cancel_timeout(ua, timer2); - /* Result could be ERR_OK or ERR_FAIL depending on timing */ - - /* Continue polling */ - int poll_count = 0; - while (ctx.callback_count < 2 && poll_count < 50) { - uasync_poll(ua, 10); - poll_count++; - } - - /* Verify we got expected callbacks (timer3 + possibly timer2) */ - if (ctx.callback_count < 1 || ctx.callback_count > 2) { - TEST_FAIL("Wrong number of timers fired"); - return; - } - - /* Cleanup remaining timer */ - if (timer3) { - uasync_cancel_timeout(ua, timer3); - timer3 = NULL; - } - - uasync_destroy(ua, 0); - TEST_PASS(); +TEST_START("Timer cancellation race conditions"); + +uasync_t* ua = uasync_create(); +ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + +test_context_t ctx = {0}; +ctx.expected_count = 2; +ctx.timeout_ms = 5; // Non-zero to avoid immediate timeout counting + +/* Create timers that will be cancelled at different stages */ +void* timer1 = uasync_set_timeout(ua, 5, &ctx, test_timer_callback); /* 0.5ms */ +void* timer2 = uasync_set_timeout(ua, 50, &ctx, test_timer_callback); /* 5ms */ +void* timer3 = uasync_set_timeout(ua, 100, &ctx, test_timer_callback); /* 10ms */ + +ASSERT_NOT_NULL(timer1, "Failed to set timer 1"); +ASSERT_NOT_NULL(timer2, "Failed to set timer 2"); +ASSERT_NOT_NULL(timer3, "Failed to set timer 3"); + +/* Cancel timer1 immediately (before it fires) */ +err_t cancel_result = uasync_cancel_timeout(ua, timer1); +ASSERT_EQ(cancel_result, ERR_OK, "Failed to cancel timer 1"); +test_stats.timer_cancellations++; + +/* Poll briefly - timer1 should not fire, others should */ +uasync_poll(ua, 10); /* 1ms */ + +/* Cancel timer2 while it might be firing */ +cancel_result = uasync_cancel_timeout(ua, timer2); +/* Result could be ERR_OK or ERR_FAIL depending on timing */ + +/* Continue polling */ +int poll_count = 0; +while (ctx.callback_count < 2 && poll_count < 50) { +uasync_poll(ua, 10); +poll_count++; +} + +/* Verify we got expected callbacks (timer3 + possibly timer2) */ +if (ctx.callback_count < 1 || ctx.callback_count > 2) { +TEST_FAIL("Wrong number of timers fired"); +return; +} + +/* Cleanup remaining timer */ +if (timer3) { +uasync_cancel_timeout(ua, timer3); +timer3 = NULL; +} + +uasync_destroy(ua, 0); +TEST_PASS(); } /* Test 3: Immediate timeout handling */ static void test_immediate_timeouts(void) { - TEST_START("Immediate timeout handling"); - - uasync_t* ua = uasync_create(); - ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); - - test_context_t ctx = {0}; - ctx.expected_count = 5; - ctx.timeout_ms = 0; // This should trigger immediate timeout counting - - /* Set multiple immediate timeouts (0ms) */ - for (int i = 0; i < 5; i++) { - void* timer = uasync_set_timeout(ua, 0, &ctx, test_timer_callback); - ASSERT_NOT_NULL(timer, "Failed to set immediate timer"); - } - - /* Immediate timeouts should fire during next poll */ - ASSERT_EQ(ctx.callback_count, 0, "Callbacks fired too early"); - - printf(" About to call uasync_poll, immediate_timeouts = %d\n", test_stats.immediate_timeouts); - uasync_poll(ua, 1); /* Minimal poll */ - printf(" After uasync_poll, immediate_timeouts = %d\n", test_stats.immediate_timeouts); - - ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Immediate timeouts didn't fire correctly"); - ASSERT_EQ(test_stats.immediate_timeouts, 5, "Immediate timeout counter incorrect"); - - uasync_destroy(ua, 0); - TEST_PASS(); +TEST_START("Immediate timeout handling"); + +uasync_t* ua = uasync_create(); +ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + +test_context_t ctx = {0}; +ctx.expected_count = 5; +ctx.timeout_ms = 0; // This should trigger immediate timeout counting + +/* Set multiple immediate timeouts (0ms) */ +for (int i = 0; i < 5; i++) { +void* timer = uasync_set_timeout(ua, 0, &ctx, test_timer_callback); +ASSERT_NOT_NULL(timer, "Failed to set immediate timer"); +} + +/* Immediate timeouts should fire during next poll */ +ASSERT_EQ(ctx.callback_count, 0, "Callbacks fired too early"); + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "About to call uasync_poll, immediate_timeouts = %d", test_stats.immediate_timeouts); +uasync_poll(ua, 1); /* Minimal poll */ +DEBUG_INFO(DEBUG_CATEGORY_ALL, "After uasync_poll, immediate_timeouts = %d", test_stats.immediate_timeouts); + +ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Immediate timeouts didn't fire correctly"); +ASSERT_EQ(test_stats.immediate_timeouts, 5, "Immediate timeout counter incorrect"); + +uasync_destroy(ua, 0); +TEST_PASS(); } int main(void) { - printf("=== lib Comprehensive Unit Tests ===\n"); - printf("Testing race conditions, memory management, and error handling\n\n"); - printf("Initial immediate_timeouts: %d\n", test_stats.immediate_timeouts); - - /* Run all tests */ - test_basic_timers(); - printf("After basic_timers: immediate_timeouts = %d\n", test_stats.immediate_timeouts); - - test_timer_cancellation_races(); - printf("After timer_cancellation_races: immediate_timeouts = %d\n", test_stats.immediate_timeouts); - - test_immediate_timeouts(); - printf("After immediate_timeouts: immediate_timeouts = %d\n", test_stats.immediate_timeouts); - - /* Print final statistics */ - printf("\n=== Final Statistics ===\n"); - printf("Timer callbacks: %d\n", test_stats.timer_callbacks); - printf("Immediate timeouts: %d\n", test_stats.immediate_timeouts); - - return (test_stats.tests_failed > 0) ? 1 : 0; +DEBUG_INFO(DEBUG_CATEGORY_ALL, "=== lib Comprehensive Unit Tests ==="); +DEBUG_ERROR(DEBUG_CATEGORY_ALL, "Testing race conditions, memory management, and error handling\n"); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Initial immediate_timeouts: %d", test_stats.immediate_timeouts); + +/* Run all tests */ +test_basic_timers(); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "After basic_timers: immediate_timeouts = %d", test_stats.immediate_timeouts); + +test_timer_cancellation_races(); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "After timer_cancellation_races: immediate_timeouts = %d", test_stats.immediate_timeouts); + +test_immediate_timeouts(); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "After immediate_timeouts: immediate_timeouts = %d", test_stats.immediate_timeouts); + +/* Print final statistics */ +DEBUG_INFO(DEBUG_CATEGORY_ALL, "\n=== Final Statistics ==="); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Timer callbacks: %d", test_stats.timer_callbacks); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Immediate timeouts: %d", test_stats.immediate_timeouts); + +return (test_stats.tests_failed > 0) ? 1 : 0; } diff --git a/tests/debug_full_test.c.backup b/tests/debug_full_test.c.backup new file mode 100644 index 000000000..456f8f53a --- /dev/null +++ b/tests/debug_full_test.c.backup @@ -0,0 +1,234 @@ +// Copy the original test file but add debugging +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "u_async.h" +#include "timeout_heap.h" + +/* Test statistics */ +static struct { + int tests_run; + int tests_passed; + int tests_failed; + + /* Timer statistics */ + int timer_callbacks; + int timer_cancellations; + int immediate_timeouts; + + /* Socket statistics */ + int socket_events; + int socket_errors; + + /* Error statistics */ + int memory_allocation_errors; + int invalid_parameter_errors; + int race_condition_errors; +} test_stats = {0}; + +/* Test result tracking */ +#define TEST_START(name) do { \ + printf("TEST: %s... \n", name); \ + printf(" immediate_timeouts before: %d\n", test_stats.immediate_timeouts); \ + test_stats.tests_run++; \ +} while(0) + +#define TEST_PASS() do { \ + printf(" immediate_timeouts after: %d\n", test_stats.immediate_timeouts); \ + printf("PASS\n"); \ + test_stats.tests_passed++; \ +} while(0) + +#define TEST_FAIL(msg) do { \ + printf(" immediate_timeouts after: %d\n", test_stats.immediate_timeouts); \ + printf("FAIL: %s\n", msg); \ + test_stats.tests_failed++; \ +} while(0) + +#define ASSERT_EQ(a, b, msg) do { \ + if ((a) != (b)) { \ + TEST_FAIL(msg); \ + printf(" Expected: %ld, Got: %ld\n", (long)(b), (long)(a)); \ + return; \ + } \ +} while(0) + +#define ASSERT_NOT_NULL(ptr, msg) do { \ + if ((ptr) == NULL) { \ + TEST_FAIL(msg); \ + return; \ + } \ +} while(0) + +/* Test context for callbacks */ +typedef struct { + int callback_count; + int expected_count; + int callback_arg; + int timeout_ms; + uasync_t* ua; + void* timer_id; +} test_context_t; + +/* Timer callback for testing */ +static void test_timer_callback(void* arg) { + test_context_t* ctx = (test_context_t*)arg; + ctx->callback_count++; + test_stats.timer_callbacks++; + + if (ctx->timeout_ms == 0) { + test_stats.immediate_timeouts++; + printf(" IMMEDIATE TIMEOUT: immediate_timeouts now = %d\n", test_stats.immediate_timeouts); + } +} + +/* Test 1: Basic timer functionality */ +static void test_basic_timers(void) { + TEST_START("Basic timer functionality"); + + uasync_t* ua = uasync_create(); + ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + + test_context_t ctx = {0}; + ctx.expected_count = 3; + ctx.timeout_ms = 10; // Non-zero to avoid immediate timeout counting + + /* Set multiple timers with different timeouts */ + void* timer1 = uasync_set_timeout(ua, 10, &ctx, test_timer_callback); /* 1ms */ + void* timer2 = uasync_set_timeout(ua, 20, &ctx, test_timer_callback); /* 2ms */ + void* timer3 = uasync_set_timeout(ua, 30, &ctx, test_timer_callback); /* 3ms */ + + ASSERT_NOT_NULL(timer1, "Failed to set timer 1"); + ASSERT_NOT_NULL(timer2, "Failed to set timer 2"); + ASSERT_NOT_NULL(timer3, "Failed to set timer 3"); + + /* Poll and verify timers fire in order */ + int poll_count = 0; + while (ctx.callback_count < ctx.expected_count && poll_count < 100) { + uasync_poll(ua, 10); /* 1ms poll */ + poll_count++; + } + + ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Not all timers fired"); + + /* Cleanup */ + uasync_destroy(ua, 0); + TEST_PASS(); +} + +/* Test 2: Timer cancellation race conditions */ +static void test_timer_cancellation_races(void) { + TEST_START("Timer cancellation race conditions"); + + uasync_t* ua = uasync_create(); + ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + + test_context_t ctx = {0}; + ctx.expected_count = 2; + ctx.timeout_ms = 5; // Non-zero to avoid immediate timeout counting + + /* Create timers that will be cancelled at different stages */ + void* timer1 = uasync_set_timeout(ua, 5, &ctx, test_timer_callback); /* 0.5ms */ + void* timer2 = uasync_set_timeout(ua, 50, &ctx, test_timer_callback); /* 5ms */ + void* timer3 = uasync_set_timeout(ua, 100, &ctx, test_timer_callback); /* 10ms */ + + ASSERT_NOT_NULL(timer1, "Failed to set timer 1"); + ASSERT_NOT_NULL(timer2, "Failed to set timer 2"); + ASSERT_NOT_NULL(timer3, "Failed to set timer 3"); + + /* Cancel timer1 immediately (before it fires) */ + err_t cancel_result = uasync_cancel_timeout(ua, timer1); + ASSERT_EQ(cancel_result, ERR_OK, "Failed to cancel timer 1"); + test_stats.timer_cancellations++; + + /* Poll briefly - timer1 should not fire, others should */ + uasync_poll(ua, 10); /* 1ms */ + + /* Cancel timer2 while it might be firing */ + cancel_result = uasync_cancel_timeout(ua, timer2); + /* Result could be ERR_OK or ERR_FAIL depending on timing */ + + /* Continue polling */ + int poll_count = 0; + while (ctx.callback_count < 2 && poll_count < 50) { + uasync_poll(ua, 10); + poll_count++; + } + + /* Verify we got expected callbacks (timer3 + possibly timer2) */ + if (ctx.callback_count < 1 || ctx.callback_count > 2) { + TEST_FAIL("Wrong number of timers fired"); + return; + } + + /* Cleanup remaining timer */ + if (timer3) { + uasync_cancel_timeout(ua, timer3); + timer3 = NULL; + } + + uasync_destroy(ua, 0); + TEST_PASS(); +} + +/* Test 3: Immediate timeout handling */ +static void test_immediate_timeouts(void) { + TEST_START("Immediate timeout handling"); + + uasync_t* ua = uasync_create(); + ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + + test_context_t ctx = {0}; + ctx.expected_count = 5; + ctx.timeout_ms = 0; // This should trigger immediate timeout counting + + /* Set multiple immediate timeouts (0ms) */ + for (int i = 0; i < 5; i++) { + void* timer = uasync_set_timeout(ua, 0, &ctx, test_timer_callback); + ASSERT_NOT_NULL(timer, "Failed to set immediate timer"); + } + + /* Immediate timeouts should fire during next poll */ + ASSERT_EQ(ctx.callback_count, 0, "Callbacks fired too early"); + + printf(" About to call uasync_poll, immediate_timeouts = %d\n", test_stats.immediate_timeouts); + uasync_poll(ua, 1); /* Minimal poll */ + printf(" After uasync_poll, immediate_timeouts = %d\n", test_stats.immediate_timeouts); + + ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Immediate timeouts didn't fire correctly"); + ASSERT_EQ(test_stats.immediate_timeouts, 5, "Immediate timeout counter incorrect"); + + uasync_destroy(ua, 0); + TEST_PASS(); +} + +int main(void) { + printf("=== lib Comprehensive Unit Tests ===\n"); + printf("Testing race conditions, memory management, and error handling\n\n"); + printf("Initial immediate_timeouts: %d\n", test_stats.immediate_timeouts); + + /* Run all tests */ + test_basic_timers(); + printf("After basic_timers: immediate_timeouts = %d\n", test_stats.immediate_timeouts); + + test_timer_cancellation_races(); + printf("After timer_cancellation_races: immediate_timeouts = %d\n", test_stats.immediate_timeouts); + + test_immediate_timeouts(); + printf("After immediate_timeouts: immediate_timeouts = %d\n", test_stats.immediate_timeouts); + + /* Print final statistics */ + printf("\n=== Final Statistics ===\n"); + printf("Timer callbacks: %d\n", test_stats.timer_callbacks); + printf("Immediate timeouts: %d\n", test_stats.immediate_timeouts); + + return (test_stats.tests_failed > 0) ? 1 : 0; +} diff --git a/tests/debug_performance b/tests/debug_performance new file mode 100755 index 000000000..ec39b0cd4 Binary files /dev/null and b/tests/debug_performance differ diff --git a/tests/debug_performance.c b/tests/debug_performance.c new file mode 100644 index 000000000..52faf560f --- /dev/null +++ b/tests/debug_performance.c @@ -0,0 +1,52 @@ +#include "../lib/u_async.h" +#include "../lib/debug_config.h" +#include +#include +#include +#include +#include + +static void test_callback(int fd, void* arg) { +(void)fd; (void)arg; +} + +int main() { + +debug_config_init(); +debug_set_level(DEBUG_LEVEL_TRACE); +debug_set_categories(DEBUG_CATEGORY_ALL); +uasync_t* ua = uasync_create(); +if (!ua) return 1; + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "=== Debug Performance Test ==="); + +// Test 1: Normal add/remove +int sock1 = socket(AF_INET, SOCK_DGRAM, 0); +void* id1 = uasync_add_socket(ua, sock1, test_callback, NULL, NULL, NULL); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Added socket %d: id=%p", sock1, id1); + +size_t alloc1, free1, alloc2, free2; +uasync_get_stats(ua, &alloc1, &free1, &alloc2, &free2); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "After add: timers %zu/%zu, sockets %zu/%zu", alloc1, free1, alloc2, free2); + +uasync_remove_socket(ua, id1); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Removed socket %d", sock1); + +uasync_get_stats(ua, &alloc1, &free1, &alloc2, &free2); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "After remove: timers %zu/%zu, sockets %zu/%zu", alloc1, free1, alloc2, free2); + +close(sock1); + +// Test 2: Failed add +int sock2 = 9999; // Invalid socket +void* id2 = uasync_add_socket(ua, sock2, test_callback, NULL, NULL, NULL); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Tried to add invalid socket %d: id=%p", sock2, id2); + +uasync_get_stats(ua, &alloc1, &free1, &alloc2, &free2); +DEBUG_ERROR(DEBUG_CATEGORY_ALL, "After failed add: timers %zu/%zu, sockets %zu/%zu", alloc1, free1, alloc2, free2); + +uasync_destroy(ua, 0); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Destroyed uasync"); + +return 0; +} diff --git a/tests/debug_performance.c.backup b/tests/debug_performance.c.backup new file mode 100644 index 000000000..8c6c70018 --- /dev/null +++ b/tests/debug_performance.c.backup @@ -0,0 +1,47 @@ +#include "../lib/u_async.h" +#include +#include +#include +#include +#include + +static void test_callback(int fd, void* arg) { + (void)fd; (void)arg; +} + +int main() { + uasync_t* ua = uasync_create(); + if (!ua) return 1; + + printf("=== Debug Performance Test ===\n"); + + // Test 1: Normal add/remove + int sock1 = socket(AF_INET, SOCK_DGRAM, 0); + void* id1 = uasync_add_socket(ua, sock1, test_callback, NULL, NULL, NULL); + printf("Added socket %d: id=%p\n", sock1, id1); + + size_t alloc1, free1, alloc2, free2; + uasync_get_stats(ua, &alloc1, &free1, &alloc2, &free2); + printf("After add: timers %zu/%zu, sockets %zu/%zu\n", alloc1, free1, alloc2, free2); + + uasync_remove_socket(ua, id1); + printf("Removed socket %d\n", sock1); + + uasync_get_stats(ua, &alloc1, &free1, &alloc2, &free2); + printf("After remove: timers %zu/%zu, sockets %zu/%zu\n", alloc1, free1, alloc2, free2); + + close(sock1); + + // Test 2: Failed add + int sock2 = 9999; // Invalid socket + void* id2 = uasync_add_socket(ua, sock2, test_callback, NULL, NULL, NULL); + printf("Tried to add invalid socket %d: id=%p\n", sock2, id2); + + uasync_get_stats(ua, &alloc1, &free1, &alloc2, &free2); + printf("After failed add: timers %zu/%zu, sockets %zu/%zu\n", alloc1, free1, alloc2, free2); + + uasync_destroy(ua, 0); + printf("Destroyed uasync\n"); + + return 0; +} diff --git a/tests/debug_test b/tests/debug_test deleted file mode 100755 index d12e6750c..000000000 Binary files a/tests/debug_test and /dev/null differ diff --git a/tests/debug_test.c b/tests/debug_test.c deleted file mode 100644 index 66385cf63..000000000 --- a/tests/debug_test.c +++ /dev/null @@ -1,11 +0,0 @@ -#include "../lib/debug_config.h" -#include "../src/etcp_connections.h" - -int main() { - debug_config_init(); - debug_set_level(DEBUG_LEVEL_DEBUG); - debug_enable_category(DEBUG_CATEGORY_ETCP); - printf("Debug config: level=%d, categories=0x%x\n", - g_debug_config.level, g_debug_config.categories); - return 0; -} diff --git a/tests/detailed_test.c b/tests/detailed_test.c index f48355521..15d9e4f94 100644 --- a/tests/detailed_test.c +++ b/tests/detailed_test.c @@ -1,86 +1,91 @@ #include "u_async.h" +#include "../lib/debug_config.h" #include /* Test statistics */ static struct { - int timer_callbacks; - int immediate_timeouts; +int timer_callbacks; +int immediate_timeouts; } test_stats = {0}; typedef struct { - int callback_count; - int timeout_ms; +int callback_count; +int timeout_ms; } test_context_t; /* Timer callback for testing */ static void test_timer_callback(void* arg) { - test_context_t* ctx = (test_context_t*)arg; - ctx->callback_count++; - test_stats.timer_callbacks++; - - printf("Callback fired: ctx->timeout_ms=%d, immediate_timeouts before=%d", ctx->timeout_ms, test_stats.immediate_timeouts); - - if (ctx->timeout_ms == 0) { - test_stats.immediate_timeouts++; - printf(" -> INCREMENTED to %d\n", test_stats.immediate_timeouts); - } else { - printf(" -> NOT incremented\n"); - } +test_context_t* ctx = (test_context_t*)arg; +ctx->callback_count++; +test_stats.timer_callbacks++; + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Callback fired: ctx->timeout_ms=%d, immediate_timeouts before=%d", ctx->timeout_ms, test_stats.immediate_timeouts); + +if (ctx->timeout_ms == 0) { +test_stats.immediate_timeouts++; +DEBUG_INFO(DEBUG_CATEGORY_ALL, "-> INCREMENTED to %d", test_stats.immediate_timeouts); +} else { +DEBUG_INFO(DEBUG_CATEGORY_ALL, "-> NOT incremented"); +} } int main() { - printf("=== Test 1: Basic timers (non-zero timeouts) ===\n"); - printf("Before test 1: immediate_timeouts = %d\n", test_stats.immediate_timeouts); - - uasync_t* ua1 = uasync_create(); - test_context_t ctx1 = {.timeout_ms = 10}; - - for (int i = 0; i < 3; i++) { - uasync_set_timeout(ua1, 10 + i*10, &ctx1, test_timer_callback); - } - - int polls = 0; - while (ctx1.callback_count < 3 && polls < 10) { - uasync_poll(ua1, 10); - polls++; - } - - printf("After test 1: immediate_timeouts = %d\n", test_stats.immediate_timeouts); - uasync_destroy(ua1); - - printf("\n=== Test 2: Immediate timeouts (zero timeouts) ===\n"); - printf("Before test 2: immediate_timeouts = %d\n", test_stats.immediate_timeouts); - - uasync_t* ua2 = uasync_create(); - test_context_t ctx2 = {.timeout_ms = 0}; - - for (int i = 0; i < 5; i++) { - uasync_set_timeout(ua2, 0, &ctx2, test_timer_callback); - } - - printf("Before poll: ctx2.callback_count = %d, immediate_timeouts = %d\n", ctx2.callback_count, test_stats.immediate_timeouts); - - uasync_poll(ua2, 1); - - printf("After poll: ctx2.callback_count = %d, immediate_timeouts = %d\n", ctx2.callback_count, test_stats.immediate_timeouts); - - uasync_destroy(ua2); - - printf("\n=== Test 3: Another immediate timeout test ===\n"); - printf("Before test 3: immediate_timeouts = %d\n", test_stats.immediate_timeouts); - - uasync_t* ua3 = uasync_create(); - test_context_t ctx3 = {.timeout_ms = 0}; - - for (int i = 0; i < 2; i++) { - uasync_set_timeout(ua3, 0, &ctx3, test_timer_callback); - } - - uasync_poll(ua3, 1); - - printf("After test 3: immediate_timeouts = %d\n", test_stats.immediate_timeouts); - - uasync_destroy(ua3); - - return 0; + +debug_config_init(); +debug_set_level(DEBUG_LEVEL_TRACE); +debug_set_categories(DEBUG_CATEGORY_ALL); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "=== Test 1: Basic timers (non-zero timeouts) ==="); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Before test 1: immediate_timeouts = %d", test_stats.immediate_timeouts); + +uasync_t* ua1 = uasync_create(); +test_context_t ctx1 = {.timeout_ms = 10}; + +for (int i = 0; i < 3; i++) { +uasync_set_timeout(ua1, 10 + i*10, &ctx1, test_timer_callback); +} + +int polls = 0; +while (ctx1.callback_count < 3 && polls < 10) { +uasync_poll(ua1, 10); +polls++; +} + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "After test 1: immediate_timeouts = %d", test_stats.immediate_timeouts); +uasync_destroy(ua1); + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "\n=== Test 2: Immediate timeouts (zero timeouts) ==="); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Before test 2: immediate_timeouts = %d", test_stats.immediate_timeouts); + +uasync_t* ua2 = uasync_create(); +test_context_t ctx2 = {.timeout_ms = 0}; + +for (int i = 0; i < 5; i++) { +uasync_set_timeout(ua2, 0, &ctx2, test_timer_callback); +} + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Before poll: ctx2.callback_count = %d, immediate_timeouts = %d", ctx2.callback_count, test_stats.immediate_timeouts); + +uasync_poll(ua2, 1); + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "After poll: ctx2.callback_count = %d, immediate_timeouts = %d", ctx2.callback_count, test_stats.immediate_timeouts); + +uasync_destroy(ua2); + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "\n=== Test 3: Another immediate timeout test ==="); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Before test 3: immediate_timeouts = %d", test_stats.immediate_timeouts); + +uasync_t* ua3 = uasync_create(); +test_context_t ctx3 = {.timeout_ms = 0}; + +for (int i = 0; i < 2; i++) { +uasync_set_timeout(ua3, 0, &ctx3, test_timer_callback); +} + +uasync_poll(ua3, 1); + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "After test 3: immediate_timeouts = %d", test_stats.immediate_timeouts); + +uasync_destroy(ua3); + +return 0; } diff --git a/tests/detailed_test.c.backup b/tests/detailed_test.c.backup new file mode 100644 index 000000000..f48355521 --- /dev/null +++ b/tests/detailed_test.c.backup @@ -0,0 +1,86 @@ +#include "u_async.h" +#include + +/* Test statistics */ +static struct { + int timer_callbacks; + int immediate_timeouts; +} test_stats = {0}; + +typedef struct { + int callback_count; + int timeout_ms; +} test_context_t; + +/* Timer callback for testing */ +static void test_timer_callback(void* arg) { + test_context_t* ctx = (test_context_t*)arg; + ctx->callback_count++; + test_stats.timer_callbacks++; + + printf("Callback fired: ctx->timeout_ms=%d, immediate_timeouts before=%d", ctx->timeout_ms, test_stats.immediate_timeouts); + + if (ctx->timeout_ms == 0) { + test_stats.immediate_timeouts++; + printf(" -> INCREMENTED to %d\n", test_stats.immediate_timeouts); + } else { + printf(" -> NOT incremented\n"); + } +} + +int main() { + printf("=== Test 1: Basic timers (non-zero timeouts) ===\n"); + printf("Before test 1: immediate_timeouts = %d\n", test_stats.immediate_timeouts); + + uasync_t* ua1 = uasync_create(); + test_context_t ctx1 = {.timeout_ms = 10}; + + for (int i = 0; i < 3; i++) { + uasync_set_timeout(ua1, 10 + i*10, &ctx1, test_timer_callback); + } + + int polls = 0; + while (ctx1.callback_count < 3 && polls < 10) { + uasync_poll(ua1, 10); + polls++; + } + + printf("After test 1: immediate_timeouts = %d\n", test_stats.immediate_timeouts); + uasync_destroy(ua1); + + printf("\n=== Test 2: Immediate timeouts (zero timeouts) ===\n"); + printf("Before test 2: immediate_timeouts = %d\n", test_stats.immediate_timeouts); + + uasync_t* ua2 = uasync_create(); + test_context_t ctx2 = {.timeout_ms = 0}; + + for (int i = 0; i < 5; i++) { + uasync_set_timeout(ua2, 0, &ctx2, test_timer_callback); + } + + printf("Before poll: ctx2.callback_count = %d, immediate_timeouts = %d\n", ctx2.callback_count, test_stats.immediate_timeouts); + + uasync_poll(ua2, 1); + + printf("After poll: ctx2.callback_count = %d, immediate_timeouts = %d\n", ctx2.callback_count, test_stats.immediate_timeouts); + + uasync_destroy(ua2); + + printf("\n=== Test 3: Another immediate timeout test ===\n"); + printf("Before test 3: immediate_timeouts = %d\n", test_stats.immediate_timeouts); + + uasync_t* ua3 = uasync_create(); + test_context_t ctx3 = {.timeout_ms = 0}; + + for (int i = 0; i < 2; i++) { + uasync_set_timeout(ua3, 0, &ctx3, test_timer_callback); + } + + uasync_poll(ua3, 1); + + printf("After test 3: immediate_timeouts = %d\n", test_stats.immediate_timeouts); + + uasync_destroy(ua3); + + return 0; +} diff --git a/tests/simple_test.c b/tests/simple_test.c new file mode 100644 index 000000000..289b67c6d --- /dev/null +++ b/tests/simple_test.c @@ -0,0 +1,42 @@ +#include "../lib/u_async.h" +#include "../lib/debug_config.h" +#include +#include +#include +#include +#include + +static void test_callback(int fd, void* arg) { +(void)fd; (void)arg; +} + +int main() { + +debug_config_init(); +debug_set_level(DEBUG_LEVEL_TRACE); +debug_set_categories(DEBUG_CATEGORY_ALL); +uasync_t* ua = uasync_create(); +if (!ua) return 1; + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "=== Simple Corruption Test ==="); + +// Create just one socket +int sock = socket(AF_INET, SOCK_DGRAM, 0); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Created socket with fd=%d", sock); + +void* id = uasync_add_socket(ua, sock, test_callback, NULL, NULL, NULL); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Added socket: fd=%d, id=%p", sock, id); + +// Check if fd is still correct +struct socket_node* node = (struct socket_node*)id; +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Node fd after add: %d", node->fd); + +// Try to remove immediately (no polling) +int result = uasync_remove_socket(ua, id); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Remove result: %d", result); + +close(sock); +uasync_destroy(ua, 0); + +return 0; +} diff --git a/tests/simple_test.c.backup b/tests/simple_test.c.backup new file mode 100644 index 000000000..fd68f787d --- /dev/null +++ b/tests/simple_test.c.backup @@ -0,0 +1,37 @@ +#include "../lib/u_async.h" +#include +#include +#include +#include +#include + +static void test_callback(int fd, void* arg) { + (void)fd; (void)arg; +} + +int main() { + uasync_t* ua = uasync_create(); + if (!ua) return 1; + + printf("=== Simple Corruption Test ===\n"); + + // Create just one socket + int sock = socket(AF_INET, SOCK_DGRAM, 0); + printf("Created socket with fd=%d\n", sock); + + void* id = uasync_add_socket(ua, sock, test_callback, NULL, NULL, NULL); + printf("Added socket: fd=%d, id=%p\n", sock, id); + + // Check if fd is still correct + struct socket_node* node = (struct socket_node*)id; + printf("Node fd after add: %d\n", node->fd); + + // Try to remove immediately (no polling) + int result = uasync_remove_socket(ua, id); + printf("Remove result: %d\n", result); + + close(sock); + uasync_destroy(ua, 0); + + return 0; +} diff --git a/tests/test_config_debug b/tests/test_config_debug deleted file mode 100755 index 41dc6f364..000000000 Binary files a/tests/test_config_debug and /dev/null differ diff --git a/tests/test_config_debug.c b/tests/test_config_debug.c index 2bb07e694..1f9b359f5 100644 --- a/tests/test_config_debug.c +++ b/tests/test_config_debug.c @@ -1,6 +1,6 @@ /** - * Тест загрузки debug настроек из конфигурационного файла - */ +* Тест загрузки debug настроек из конфигурационного файла +*/ #include #include @@ -9,67 +9,51 @@ #include "../src/config_parser.h" int main() { - printf("=== Тест загрузки debug настроек из конфигурационного файла ===\n"); - - // Инициализация отладки по умолчанию - debug_config_init(); - debug_set_level(DEBUG_LEVEL_ERROR); // Начальный уровень - - printf("\n1. До загрузки конфигурации:\n"); - DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "ERROR сообщение до загрузки конфигурации"); - DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "INFO сообщение до загрузки конфигурации (не должно выводиться)"); - - // Загрузка конфигурации из файла - printf("\n2. Загрузка конфигурации из файла: test_config_with_debug.conf\n"); - struct utun_config *config = parse_config("test_config_with_debug.conf"); - - if (!config) { - printf("❌ Ошибка загрузки конфигурации\n"); - return 1; - } - - printf("✅ Конфигурация загружена успешно\n"); - printf(" Log file: %s\n", config->global.log_file[0] ? config->global.log_file : "(none)"); - printf(" Debug level: %s\n", config->global.debug_level[0] ? config->global.debug_level : "(none)"); - printf(" Debug categories: 0x%X\n", config->global.debug_categories); - printf(" Enable timestamp: %d\n", config->global.enable_timestamp); - printf(" Enable colors: %d\n", config->global.enable_colors); - - // Применение настроек из конфигурации (без переопределения CLI) - printf("\n3. Применение настроек из конфигурации:\n"); - debug_apply_config_values( - config->global.log_file, - config->global.debug_level, - config->global.debug_categories, - config->global.enable_timestamp, - config->global.enable_function_names, - config->global.enable_file_lines, - config->global.enable_colors, - 0, // CLI не переопределяет уровень - 0 // CLI не переопределяет категории - ); - - printf("✅ Настройки отладки применены\n"); - - // Тестирование новых настроек - printf("\n4. Тестирование после применения настроек:\n"); - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "ERROR от ETCP (должен выводиться)"); - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "INFO от ETCP (должен выводиться - уровень debug)"); - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "DEBUG от ETCP (должен выводиться - уровень debug)"); - DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "INFO от LL_QUEUE (должен выводиться)"); - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "INFO от MEMORY (должен выводиться)"); - DEBUG_INFO(DEBUG_CATEGORY_CONNECTION, "INFO от CONNECTION (НЕ должен выводиться - категория не включена)"); - DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "INFO от CRYPTO (НЕ должен выводиться - категория не включена)"); - - // Проверка работы с файлом - printf("\n5. Проверка вывода в файл:\n"); - DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Это сообщение должно быть записано в файл: /tmp/utun_debug.log"); - - // Освобождение ресурсов - free_config(config); - - printf("\n=== Тест завершен ===\n"); - printf("Проверьте файл /tmp/utun_debug.log для записанных сообщений\n"); - - return 0; +DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "=== Тест загрузки debug настроек из конфигурационного файла ==="); + +// Инициализация отладки по умолчанию +debug_config_init(); +debug_set_level(DEBUG_LEVEL_ERROR); // Начальный уровень + +DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "\n1. До загрузки конфигурации:"); +DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "ERROR сообщение до загрузки конфигурации"); +DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "INFO сообщение до загрузки конфигурации (не должно выводиться)"); + +// Загрузка конфигурации из файла +DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "\n2. Загрузка конфигурации из файла: test_config_with_debug.conf"); +struct utun_config *config = parse_config("test_config_with_debug.conf"); + +if (!config) { +DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Ошибка загрузки конфигурации"); +return 1; +} + +DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Конфигурация загружена успешно"); +DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Log file: %s", config->global.log_file[0] ? config->global.log_file : "(none)"); +DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Debug level: %s", config->global.debug_level[0] ? config->global.debug_level : "(none)"); +DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Debug categories: 0x%X", config->global.debug_categories); +DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Enable timestamp: %d", config->global.enable_timestamp); +DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Enable colors: %d", config->global.enable_colors); + +// Тестирование новых настроек +DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "\n4. Тестирование после применения настроек:"); +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "ERROR от ETCP (должен выводиться)"); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "INFO от ETCP (должен выводиться - уровень debug)"); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "DEBUG от ETCP (должен выводиться - уровень debug)"); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "INFO от LL_QUEUE (должен выводиться)"); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "INFO от MEMORY (должен выводиться)"); +DEBUG_INFO(DEBUG_CATEGORY_CONNECTION, "INFO от CONNECTION (НЕ должен выводиться - категория не включена)"); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "INFO от CRYPTO (НЕ должен выводиться - категория не включена)"); + +// Проверка работы с файлом +DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "\n5. Проверка вывода в файл:"); +DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Это сообщение должно быть записано в файл: /tmp/utun_debug.log"); + +// Освобождение ресурсов +free_config(config); + +DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "\n=== Тест завершен ==="); +DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Проверьте файл /tmp/utun_debug.log для записанных сообщений"); + +return 0; } \ No newline at end of file diff --git a/tests/test_config_debug.c.backup b/tests/test_config_debug.c.backup new file mode 100644 index 000000000..1b2c72dc7 --- /dev/null +++ b/tests/test_config_debug.c.backup @@ -0,0 +1,59 @@ +/** + * Тест загрузки debug настроек из конфигурационного файла + */ + +#include +#include +#include +#include "../lib/debug_config.h" +#include "../src/config_parser.h" + +int main() { + printf("=== Тест загрузки debug настроек из конфигурационного файла ===\n"); + + // Инициализация отладки по умолчанию + debug_config_init(); + debug_set_level(DEBUG_LEVEL_ERROR); // Начальный уровень + + printf("\n1. До загрузки конфигурации:\n"); + DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "ERROR сообщение до загрузки конфигурации"); + DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "INFO сообщение до загрузки конфигурации (не должно выводиться)"); + + // Загрузка конфигурации из файла + printf("\n2. Загрузка конфигурации из файла: test_config_with_debug.conf\n"); + struct utun_config *config = parse_config("test_config_with_debug.conf"); + + if (!config) { + printf("❌ Ошибка загрузки конфигурации\n"); + return 1; + } + + printf("✅ Конфигурация загружена успешно\n"); + printf(" Log file: %s\n", config->global.log_file[0] ? config->global.log_file : "(none)"); + printf(" Debug level: %s\n", config->global.debug_level[0] ? config->global.debug_level : "(none)"); + printf(" Debug categories: 0x%X\n", config->global.debug_categories); + printf(" Enable timestamp: %d\n", config->global.enable_timestamp); + printf(" Enable colors: %d\n", config->global.enable_colors); + + // Тестирование новых настроек + printf("\n4. Тестирование после применения настроек:\n"); + DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "ERROR от ETCP (должен выводиться)"); + DEBUG_INFO(DEBUG_CATEGORY_ETCP, "INFO от ETCP (должен выводиться - уровень debug)"); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "DEBUG от ETCP (должен выводиться - уровень debug)"); + DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "INFO от LL_QUEUE (должен выводиться)"); + DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "INFO от MEMORY (должен выводиться)"); + DEBUG_INFO(DEBUG_CATEGORY_CONNECTION, "INFO от CONNECTION (НЕ должен выводиться - категория не включена)"); + DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "INFO от CRYPTO (НЕ должен выводиться - категория не включена)"); + + // Проверка работы с файлом + printf("\n5. Проверка вывода в файл:\n"); + DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Это сообщение должно быть записано в файл: /tmp/utun_debug.log"); + + // Освобождение ресурсов + free_config(config); + + printf("\n=== Тест завершен ===\n"); + printf("Проверьте файл /tmp/utun_debug.log для записанных сообщений\n"); + + return 0; +} \ No newline at end of file diff --git a/tests/test_crypto b/tests/test_crypto deleted file mode 100755 index 21c7bbc0c..000000000 Binary files a/tests/test_crypto and /dev/null differ diff --git a/tests/test_crypto.c b/tests/test_crypto.c index bf79ed89e..47242b9d5 100644 --- a/tests/test_crypto.c +++ b/tests/test_crypto.c @@ -1,4 +1,5 @@ #include +#include "../lib/debug_config.h" #include #include #include @@ -8,55 +9,59 @@ #define SC_SESSION_KEY_SIZE 16 int main() { - printf("=== Basic Crypto Test ===\n"); - - struct tc_aes_key_sched_struct sched; - uint8_t test_key[SC_SESSION_KEY_SIZE] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10}; - - if (tc_aes128_set_encrypt_key(&sched, test_key) != TC_CRYPTO_SUCCESS) { - printf("❌ AES key setup failed\n"); - return 1; - } - - printf("✅ AES key setup successful\n"); - - struct tc_ccm_mode_struct ccm_state; - TCCcmMode_t c = &ccm_state; - uint8_t nonce[13] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD}; - - if (tc_ccm_config(c, &sched, nonce, 13, SC_TAG_SIZE) != TC_CRYPTO_SUCCESS) { - printf("❌ CCM config failed\n"); - return 1; - } - - printf("✅ CCM config successful\n"); - - uint8_t plaintext[] = "Hello, World!"; - uint8_t ciphertext[64]; - size_t plaintext_len = sizeof(plaintext) - 1; - size_t ciphertext_len = plaintext_len + SC_TAG_SIZE; - - if (tc_ccm_generation_encryption(ciphertext, ciphertext_len, NULL, 0, plaintext, plaintext_len, c) != TC_CRYPTO_SUCCESS) { - printf("❌ Encryption failed\n"); - return 1; - } - - printf("✅ Encryption successful\n"); - - uint8_t decrypted[64]; - if (tc_ccm_decryption_verification(decrypted, plaintext_len, NULL, 0, ciphertext, ciphertext_len, c) != TC_CRYPTO_SUCCESS) { - printf("❌ Decryption failed\n"); - return 1; - } - - printf("✅ Decryption successful\n"); - - if (memcmp(plaintext, decrypted, plaintext_len) == 0) { - printf("✅ Crypto test PASSED\n"); - return 0; - } else { - printf("❌ Data mismatch\n"); - return 1; - } + +debug_config_init(); +debug_set_level(DEBUG_LEVEL_TRACE); +debug_set_categories(DEBUG_CATEGORY_ALL); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "=== Basic Crypto Test ==="); + +struct tc_aes_key_sched_struct sched; +uint8_t test_key[SC_SESSION_KEY_SIZE] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, +0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10}; + +if (tc_aes128_set_encrypt_key(&sched, test_key) != TC_CRYPTO_SUCCESS) { +DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "AES key setup failed"); +return 1; +} + +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "AES key setup successful"); + +struct tc_ccm_mode_struct ccm_state; +TCCcmMode_t c = &ccm_state; +uint8_t nonce[13] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD}; + +if (tc_ccm_config(c, &sched, nonce, 13, SC_TAG_SIZE) != TC_CRYPTO_SUCCESS) { +DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "CCM config failed"); +return 1; +} + +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "CCM config successful"); + +uint8_t plaintext[] = "Hello, World!"; +uint8_t ciphertext[64]; +size_t plaintext_len = sizeof(plaintext) - 1; +size_t ciphertext_len = plaintext_len + SC_TAG_SIZE; + +if (tc_ccm_generation_encryption(ciphertext, ciphertext_len, NULL, 0, plaintext, plaintext_len, c) != TC_CRYPTO_SUCCESS) { +DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "Encryption failed"); +return 1; +} + +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Encryption successful"); + +uint8_t decrypted[64]; +if (tc_ccm_decryption_verification(decrypted, plaintext_len, NULL, 0, ciphertext, ciphertext_len, c) != TC_CRYPTO_SUCCESS) { +DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "Decryption failed"); +return 1; +} + +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Decryption successful"); + +if (memcmp(plaintext, decrypted, plaintext_len) == 0) { +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Crypto test PASSED"); +return 0; +} else { +DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "Data mismatch"); +return 1; +} } diff --git a/tests/test_crypto.c.backup b/tests/test_crypto.c.backup new file mode 100644 index 000000000..bf79ed89e --- /dev/null +++ b/tests/test_crypto.c.backup @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include + +#define SC_TAG_SIZE 8 +#define SC_SESSION_KEY_SIZE 16 + +int main() { + printf("=== Basic Crypto Test ===\n"); + + struct tc_aes_key_sched_struct sched; + uint8_t test_key[SC_SESSION_KEY_SIZE] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10}; + + if (tc_aes128_set_encrypt_key(&sched, test_key) != TC_CRYPTO_SUCCESS) { + printf("❌ AES key setup failed\n"); + return 1; + } + + printf("✅ AES key setup successful\n"); + + struct tc_ccm_mode_struct ccm_state; + TCCcmMode_t c = &ccm_state; + uint8_t nonce[13] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD}; + + if (tc_ccm_config(c, &sched, nonce, 13, SC_TAG_SIZE) != TC_CRYPTO_SUCCESS) { + printf("❌ CCM config failed\n"); + return 1; + } + + printf("✅ CCM config successful\n"); + + uint8_t plaintext[] = "Hello, World!"; + uint8_t ciphertext[64]; + size_t plaintext_len = sizeof(plaintext) - 1; + size_t ciphertext_len = plaintext_len + SC_TAG_SIZE; + + if (tc_ccm_generation_encryption(ciphertext, ciphertext_len, NULL, 0, plaintext, plaintext_len, c) != TC_CRYPTO_SUCCESS) { + printf("❌ Encryption failed\n"); + return 1; + } + + printf("✅ Encryption successful\n"); + + uint8_t decrypted[64]; + if (tc_ccm_decryption_verification(decrypted, plaintext_len, NULL, 0, ciphertext, ciphertext_len, c) != TC_CRYPTO_SUCCESS) { + printf("❌ Decryption failed\n"); + return 1; + } + + printf("✅ Decryption successful\n"); + + if (memcmp(plaintext, decrypted, plaintext_len) == 0) { + printf("✅ Crypto test PASSED\n"); + return 0; + } else { + printf("❌ Data mismatch\n"); + return 1; + } +} diff --git a/tests/test_debug.c b/tests/test_debug.c index 4ba0d8554..084f99f6b 100644 --- a/tests/test_debug.c +++ b/tests/test_debug.c @@ -1,49 +1,54 @@ #include "u_async.h" +#include "../lib/debug_config.h" #include /* Test statistics */ static struct { - int tests_run; - int tests_passed; - int tests_failed; - - /* Timer statistics */ - int timer_callbacks; - int timer_cancellations; - int immediate_timeouts; - - /* Socket statistics */ - int socket_events; - int socket_errors; - - /* Error statistics */ - int memory_allocation_errors; - int invalid_parameter_errors; - int race_condition_errors; +int tests_run; +int tests_passed; +int tests_failed; + +/* Timer statistics */ +int timer_callbacks; +int timer_cancellations; +int immediate_timeouts; + +/* Socket statistics */ +int socket_events; +int socket_errors; + +/* Error statistics */ +int memory_allocation_errors; +int invalid_parameter_errors; +int race_condition_errors; } test_stats = {0}; /* Timer callback for testing */ static void test_timer_callback(void* arg) { - test_stats.timer_callbacks++; - printf("Timer callback fired. Total callbacks: %d\n", test_stats.timer_callbacks); +test_stats.timer_callbacks++; +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Timer callback fired. Total callbacks: %d", test_stats.timer_callbacks); } int main() { - printf("Before any tests: immediate_timeouts = %d\n", test_stats.immediate_timeouts); - - uasync_t* ua = uasync_create(); - - /* Set 5 immediate timeouts */ - for (int i = 0; i < 5; i++) { - void* timer = uasync_set_timeout(ua, 0, NULL, test_timer_callback); - } - - printf("After setting 5 immediate timeouts, before poll: immediate_timeouts = %d\n", test_stats.immediate_timeouts); - - uasync_poll(ua, 1); - - printf("After poll: immediate_timeouts = %d\n", test_stats.immediate_timeouts); - - uasync_destroy(ua, 0); - return 0; + +debug_config_init(); +debug_set_level(DEBUG_LEVEL_TRACE); +debug_set_categories(DEBUG_CATEGORY_ALL); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Before any tests: immediate_timeouts = %d", test_stats.immediate_timeouts); + +uasync_t* ua = uasync_create(); + +/* Set 5 immediate timeouts */ +for (int i = 0; i < 5; i++) { +void* timer = uasync_set_timeout(ua, 0, NULL, test_timer_callback); +} + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "After setting 5 immediate timeouts, before poll: immediate_timeouts = %d", test_stats.immediate_timeouts); + +uasync_poll(ua, 1); + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "After poll: immediate_timeouts = %d", test_stats.immediate_timeouts); + +uasync_destroy(ua, 0); +return 0; } diff --git a/tests/test_debug.c.backup b/tests/test_debug.c.backup new file mode 100644 index 000000000..4ba0d8554 --- /dev/null +++ b/tests/test_debug.c.backup @@ -0,0 +1,49 @@ +#include "u_async.h" +#include + +/* Test statistics */ +static struct { + int tests_run; + int tests_passed; + int tests_failed; + + /* Timer statistics */ + int timer_callbacks; + int timer_cancellations; + int immediate_timeouts; + + /* Socket statistics */ + int socket_events; + int socket_errors; + + /* Error statistics */ + int memory_allocation_errors; + int invalid_parameter_errors; + int race_condition_errors; +} test_stats = {0}; + +/* Timer callback for testing */ +static void test_timer_callback(void* arg) { + test_stats.timer_callbacks++; + printf("Timer callback fired. Total callbacks: %d\n", test_stats.timer_callbacks); +} + +int main() { + printf("Before any tests: immediate_timeouts = %d\n", test_stats.immediate_timeouts); + + uasync_t* ua = uasync_create(); + + /* Set 5 immediate timeouts */ + for (int i = 0; i < 5; i++) { + void* timer = uasync_set_timeout(ua, 0, NULL, test_timer_callback); + } + + printf("After setting 5 immediate timeouts, before poll: immediate_timeouts = %d\n", test_stats.immediate_timeouts); + + uasync_poll(ua, 1); + + printf("After poll: immediate_timeouts = %d\n", test_stats.immediate_timeouts); + + uasync_destroy(ua, 0); + return 0; +} diff --git a/tests/test_debug_categories b/tests/test_debug_categories deleted file mode 100755 index 54de331fa..000000000 Binary files a/tests/test_debug_categories and /dev/null differ diff --git a/tests/test_debug_categories.c b/tests/test_debug_categories.c index ebbae6212..515bb69f3 100644 --- a/tests/test_debug_categories.c +++ b/tests/test_debug_categories.c @@ -1,6 +1,6 @@ /** - * Тест настройки категорий отладки из аргументов командной строки - */ +* Тест настройки категорий отладки из аргументов командной строки +*/ #include #include @@ -8,110 +8,99 @@ #include "../lib/debug_config.h" int main(int argc, char *argv[]) { - printf("=== Тест настройки категорий из аргументов ===\n"); - printf("Запуск с аргументами: "); - for (int i = 0; i < argc; i++) { - printf("%s ", argv[i]); - } - printf("\n\n"); - - // Инициализация отладки - debug_config_init(); - - // Анализ аргументов командной строки - int debug_categories = 0; - - // Если есть специфические категории, сначала отключаем все - int has_specific_categories = 0; - - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--debug-etcp") == 0) { - has_specific_categories = 1; - } else if (strcmp(argv[i], "--debug-queue") == 0) { - has_specific_categories = 1; - } else if (strcmp(argv[i], "--debug-memory") == 0) { - has_specific_categories = 1; - } else if (strcmp(argv[i], "--debug-none") == 0) { - has_specific_categories = 1; - } - } - - // Если есть специфические категории, отключаем все по умолчанию - if (has_specific_categories) { - debug_set_categories(DEBUG_CATEGORY_NONE); - debug_categories = DEBUG_CATEGORY_NONE; - } - - // Теперь обрабатываем аргументы - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--debug-etcp") == 0) { - debug_enable_category(DEBUG_CATEGORY_ETCP); - debug_categories |= DEBUG_CATEGORY_ETCP; - printf("✅ Включена категория ETCP\n"); - } else if (strcmp(argv[i], "--debug-queue") == 0) { - debug_enable_category(DEBUG_CATEGORY_LL_QUEUE); - debug_categories |= DEBUG_CATEGORY_LL_QUEUE; - printf("✅ Включена категория LL_QUEUE\n"); - } else if (strcmp(argv[i], "--debug-memory") == 0) { - debug_enable_category(DEBUG_CATEGORY_MEMORY); - debug_categories |= DEBUG_CATEGORY_MEMORY; - printf("✅ Включена категория MEMORY\n"); - } else if (strcmp(argv[i], "--debug-all") == 0) { - debug_set_categories(DEBUG_CATEGORY_ALL); - debug_categories = DEBUG_CATEGORY_ALL; - printf("✅ Включены все категории\n"); - break; // Все категории уже включены - } else if (strcmp(argv[i], "--debug-none") == 0) { - debug_set_categories(DEBUG_CATEGORY_NONE); - debug_categories = DEBUG_CATEGORY_NONE; - printf("✅ Выключены все категории\n"); - break; // Все категории уже выключены - } else if (strcmp(argv[i], "--level") == 0 && i+1 < argc) { - i++; - if (strcmp(argv[i], "error") == 0) { - debug_set_level(DEBUG_LEVEL_ERROR); - printf("✅ Установлен уровень ERROR\n"); - } else if (strcmp(argv[i], "info") == 0) { - debug_set_level(DEBUG_LEVEL_INFO); - printf("✅ Установлен уровень INFO\n"); - } else if (strcmp(argv[i], "debug") == 0) { - debug_set_level(DEBUG_LEVEL_DEBUG); - printf("✅ Установлен уровень DEBUG\n"); - } - } - } - - printf("\n=== Тестовые сообщения ===\n"); - - // Сообщения от разных категорий - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Сообщение от ETCP категории"); - DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Сообщение от LL_QUEUE категории"); - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Сообщение от MEMORY категории"); - DEBUG_INFO(DEBUG_CATEGORY_CONNECTION, "Сообщение от CONNECTION категории"); - DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Сообщение от CRYPTO категории"); - - printf("\n=== Информация о текущих настройках ===\n"); - printf("Текущий уровень отладки: "); - debug_level_t level = debug_get_effective_level(DEBUG_CATEGORY_ETCP); - switch (level) { - case DEBUG_LEVEL_ERROR: printf("ERROR"); break; - case DEBUG_LEVEL_WARN: printf("WARN"); break; - case DEBUG_LEVEL_INFO: printf("INFO"); break; - case DEBUG_LEVEL_DEBUG: printf("DEBUG"); break; - case DEBUG_LEVEL_TRACE: printf("TRACE"); break; - default: printf("UNKNOWN"); break; - } - printf("\n"); - - printf("Активные категории: "); - if (debug_categories & DEBUG_CATEGORY_ETCP) printf("ETCP "); - if (debug_categories & DEBUG_CATEGORY_LL_QUEUE) printf("LL_QUEUE "); - if (debug_categories & DEBUG_CATEGORY_MEMORY) printf("MEMORY "); - if (debug_categories & DEBUG_CATEGORY_CONNECTION) printf("CONNECTION "); - if (debug_categories & DEBUG_CATEGORY_CRYPTO) printf("CRYPTO "); - if (debug_categories == DEBUG_CATEGORY_ALL) printf("ALL "); - if (debug_categories == DEBUG_CATEGORY_NONE) printf("NONE "); - printf("\n"); - - return 0; +DEBUG_INFO(DEBUG_CATEGORY_ALL, "=== Тест настройки категорий из аргументов ==="); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Запуск с аргументами:"); +for (int i = 0; i < argc; i++) { +DEBUG_INFO(DEBUG_CATEGORY_ALL, "%s", argv[i]); +} +DEBUG_INFO(DEBUG_CATEGORY_ALL, "\n"); + +// Инициализация отладки +debug_config_init(); + +// Анализ аргументов командной строки +int debug_categories = 0; + +// Если есть специфические категории, сначала отключаем все +int has_specific_categories = 0; + +for (int i = 1; i < argc; i++) { +if (strcmp(argv[i], "--debug-etcp") == 0) { +has_specific_categories = 1; +} else if (strcmp(argv[i], "--debug-queue") == 0) { +has_specific_categories = 1; +} else if (strcmp(argv[i], "--debug-memory") == 0) { +has_specific_categories = 1; +} else if (strcmp(argv[i], "--debug-none") == 0) { +has_specific_categories = 1; +} +} + +// Если есть специфические категории, отключаем все по умолчанию +if (has_specific_categories) { +debug_set_categories(DEBUG_CATEGORY_NONE); +debug_categories = DEBUG_CATEGORY_NONE; +} + +// Теперь обрабатываем аргументы +for (int i = 1; i < argc; i++) { +if (strcmp(argv[i], "--debug-etcp") == 0) { +debug_enable_category(DEBUG_CATEGORY_ETCP); +debug_categories |= DEBUG_CATEGORY_ETCP; +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Включена категория ETCP"); +} else if (strcmp(argv[i], "--debug-queue") == 0) { +debug_enable_category(DEBUG_CATEGORY_LL_QUEUE); +debug_categories |= DEBUG_CATEGORY_LL_QUEUE; +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Включена категория LL_QUEUE"); +} else if (strcmp(argv[i], "--debug-memory") == 0) { +debug_enable_category(DEBUG_CATEGORY_MEMORY); +debug_categories |= DEBUG_CATEGORY_MEMORY; +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Включена категория MEMORY"); +} else if (strcmp(argv[i], "--debug-all") == 0) { +debug_set_categories(DEBUG_CATEGORY_ALL); +debug_categories = DEBUG_CATEGORY_ALL; +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Включены все категории"); +break; // Все категории уже включены +} else if (strcmp(argv[i], "--debug-none") == 0) { +debug_set_categories(DEBUG_CATEGORY_NONE); +debug_categories = DEBUG_CATEGORY_NONE; +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Выключены все категории"); +break; // Все категории уже выключены +} else if (strcmp(argv[i], "--level") == 0 && i+1 < argc) { +i++; +if (strcmp(argv[i], "error") == 0) { +debug_set_level(DEBUG_LEVEL_ERROR); +DEBUG_ERROR(DEBUG_CATEGORY_ALL, "Установлен уровень ERROR"); +} else if (strcmp(argv[i], "info") == 0) { +debug_set_level(DEBUG_LEVEL_INFO); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Установлен уровень INFO"); +} else if (strcmp(argv[i], "debug") == 0) { +debug_set_level(DEBUG_LEVEL_DEBUG); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Установлен уровень DEBUG"); +} +} +} + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "\n=== Тестовые сообщения ==="); + +// Сообщения от разных категорий +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Сообщение от ETCP категории"); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Сообщение от LL_QUEUE категории"); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Сообщение от MEMORY категории"); +DEBUG_INFO(DEBUG_CATEGORY_CONNECTION, "Сообщение от CONNECTION категории"); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Сообщение от CRYPTO категории"); + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "\n=== Информация о текущих настройках ==="); + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Активные категории:"); +if (debug_categories & DEBUG_CATEGORY_ETCP) printf("ETCP "); +if (debug_categories & DEBUG_CATEGORY_LL_QUEUE) printf("LL_QUEUE "); +if (debug_categories & DEBUG_CATEGORY_MEMORY) printf("MEMORY "); +if (debug_categories & DEBUG_CATEGORY_CONNECTION) printf("CONNECTION "); +if (debug_categories & DEBUG_CATEGORY_CRYPTO) printf("CRYPTO "); +if (debug_categories == DEBUG_CATEGORY_ALL) printf("ALL "); +if (debug_categories == DEBUG_CATEGORY_NONE) printf("NONE "); +DEBUG_INFO(DEBUG_CATEGORY_ALL, ""); + +return 0; } \ No newline at end of file diff --git a/tests/test_debug_categories.c.backup b/tests/test_debug_categories.c.backup new file mode 100644 index 000000000..7f2ae022b --- /dev/null +++ b/tests/test_debug_categories.c.backup @@ -0,0 +1,106 @@ +/** + * Тест настройки категорий отладки из аргументов командной строки + */ + +#include +#include +#include +#include "../lib/debug_config.h" + +int main(int argc, char *argv[]) { + printf("=== Тест настройки категорий из аргументов ===\n"); + printf("Запуск с аргументами: "); + for (int i = 0; i < argc; i++) { + printf("%s ", argv[i]); + } + printf("\n\n"); + + // Инициализация отладки + debug_config_init(); + + // Анализ аргументов командной строки + int debug_categories = 0; + + // Если есть специфические категории, сначала отключаем все + int has_specific_categories = 0; + + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "--debug-etcp") == 0) { + has_specific_categories = 1; + } else if (strcmp(argv[i], "--debug-queue") == 0) { + has_specific_categories = 1; + } else if (strcmp(argv[i], "--debug-memory") == 0) { + has_specific_categories = 1; + } else if (strcmp(argv[i], "--debug-none") == 0) { + has_specific_categories = 1; + } + } + + // Если есть специфические категории, отключаем все по умолчанию + if (has_specific_categories) { + debug_set_categories(DEBUG_CATEGORY_NONE); + debug_categories = DEBUG_CATEGORY_NONE; + } + + // Теперь обрабатываем аргументы + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "--debug-etcp") == 0) { + debug_enable_category(DEBUG_CATEGORY_ETCP); + debug_categories |= DEBUG_CATEGORY_ETCP; + printf("✅ Включена категория ETCP\n"); + } else if (strcmp(argv[i], "--debug-queue") == 0) { + debug_enable_category(DEBUG_CATEGORY_LL_QUEUE); + debug_categories |= DEBUG_CATEGORY_LL_QUEUE; + printf("✅ Включена категория LL_QUEUE\n"); + } else if (strcmp(argv[i], "--debug-memory") == 0) { + debug_enable_category(DEBUG_CATEGORY_MEMORY); + debug_categories |= DEBUG_CATEGORY_MEMORY; + printf("✅ Включена категория MEMORY\n"); + } else if (strcmp(argv[i], "--debug-all") == 0) { + debug_set_categories(DEBUG_CATEGORY_ALL); + debug_categories = DEBUG_CATEGORY_ALL; + printf("✅ Включены все категории\n"); + break; // Все категории уже включены + } else if (strcmp(argv[i], "--debug-none") == 0) { + debug_set_categories(DEBUG_CATEGORY_NONE); + debug_categories = DEBUG_CATEGORY_NONE; + printf("✅ Выключены все категории\n"); + break; // Все категории уже выключены + } else if (strcmp(argv[i], "--level") == 0 && i+1 < argc) { + i++; + if (strcmp(argv[i], "error") == 0) { + debug_set_level(DEBUG_LEVEL_ERROR); + printf("✅ Установлен уровень ERROR\n"); + } else if (strcmp(argv[i], "info") == 0) { + debug_set_level(DEBUG_LEVEL_INFO); + printf("✅ Установлен уровень INFO\n"); + } else if (strcmp(argv[i], "debug") == 0) { + debug_set_level(DEBUG_LEVEL_DEBUG); + printf("✅ Установлен уровень DEBUG\n"); + } + } + } + + printf("\n=== Тестовые сообщения ===\n"); + + // Сообщения от разных категорий + DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Сообщение от ETCP категории"); + DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Сообщение от LL_QUEUE категории"); + DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Сообщение от MEMORY категории"); + DEBUG_INFO(DEBUG_CATEGORY_CONNECTION, "Сообщение от CONNECTION категории"); + DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Сообщение от CRYPTO категории"); + + printf("\n=== Информация о текущих настройках ===\n"); + + printf("Активные категории: "); + if (debug_categories & DEBUG_CATEGORY_ETCP) printf("ETCP "); + if (debug_categories & DEBUG_CATEGORY_LL_QUEUE) printf("LL_QUEUE "); + if (debug_categories & DEBUG_CATEGORY_MEMORY) printf("MEMORY "); + if (debug_categories & DEBUG_CATEGORY_CONNECTION) printf("CONNECTION "); + if (debug_categories & DEBUG_CATEGORY_CRYPTO) printf("CRYPTO "); + if (debug_categories == DEBUG_CATEGORY_ALL) printf("ALL "); + if (debug_categories == DEBUG_CATEGORY_NONE) printf("NONE "); + printf("\n"); + + return 0; +} \ No newline at end of file diff --git a/tests/test_debug_new b/tests/test_debug_new deleted file mode 100755 index 6a9220877..000000000 Binary files a/tests/test_debug_new and /dev/null differ diff --git a/tests/test_debug_new.c b/tests/test_debug_new.c deleted file mode 100644 index c68313848..000000000 --- a/tests/test_debug_new.c +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Тест новой системы отладки с буферизованным выводом - */ - -#include -#include -#include -#include "../lib/debug_config.h" -#include "../lib/u_async.h" - -int main() { - printf("=== Тест новой системы отладки ===\n"); - - // Инициализация отладки - debug_config_init(); - - // Тест 1: Базовые уровни отладки - printf("\n1. Базовые уровни отладки:\n"); - debug_set_level(DEBUG_LEVEL_TRACE); - debug_enable_timestamp(1); - debug_enable_function_name(1); - debug_enable_file_line(1); - debug_enable_color(1); - - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Тест ERROR сообщения"); - DEBUG_WARN(DEBUG_CATEGORY_ETCP, "Тест WARN сообщения"); - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Тест INFO сообщения"); - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "Тест DEBUG сообщения"); - DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "Тест TRACE сообщения"); - - // Тест 2: Разные категории - printf("\n2. Разные категории отладки:\n"); - debug_set_level(DEBUG_LEVEL_INFO); - - DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Сообщение от ll_queue"); - DEBUG_INFO(DEBUG_CATEGORY_CONNECTION, "Сообщение от connection"); - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Сообщение от memory"); - DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Сообщение от crypto"); - - // Тест 3: Форматирование с аргументами - printf("\n3. Форматирование с аргументами:\n"); - int test_value = 42; - const char* test_string = "тестовая строка"; - - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Значение: %d, строка: %s", test_value, test_string); - DEBUG_DEBUG(DEBUG_CATEGORY_MEMORY, "Размер буфера: %zu, флаг: %d", (size_t)1024, 1); - - // Тест 4: Включение/выключение категорий - printf("\n4. Выборочные категории:\n"); - debug_disable_category(DEBUG_CATEGORY_ALL); - debug_enable_category(DEBUG_CATEGORY_ETCP); - debug_enable_category(DEBUG_CATEGORY_LL_QUEUE); - - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Это должно выводиться (ETCP)"); - DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Это должно выводиться (LL_QUEUE)"); - DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Это НЕ должно выводиться (MEMORY отключена)"); - - // Тест 5: Разные уровни для разных категорий - printf("\n5. Уровни по категориям:\n"); - debug_set_level(DEBUG_LEVEL_ERROR); // Глобальный уровень - // Note: debug_set_category_level не существует в новой системе - debug_set_level(DEBUG_LEVEL_DEBUG); // Устанавливаем DEBUG для всех - - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "ERROR для ETCP"); - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "DEBUG для ETCP (должен выводиться)"); - DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "INFO для LL_QUEUE (должен выводиться)"); - DEBUG_DEBUG(DEBUG_CATEGORY_LL_QUEUE, "DEBUG для LL_QUEUE (должен выводиться)"); - - // Тест 6: Без цветов и метаданных - printf("\n6. Минималистичный вывод:\n"); - debug_enable_color(0); - debug_enable_timestamp(0); - debug_enable_function_name(0); - debug_enable_file_line(0); - - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Минималистичное сообщение"); - - // Тест 7: Возврат к полному формату - printf("\n7. Полный формат снова:\n"); - debug_enable_color(1); - debug_enable_timestamp(1); - debug_enable_function_name(1); - debug_enable_file_line(1); - - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Полное сообщение с метаданными"); - - printf("\n=== Тест завершен ===\n"); - return 0; -} \ No newline at end of file diff --git a/tests/test_ecc_encrypt b/tests/test_ecc_encrypt deleted file mode 100755 index 99ac109a1..000000000 Binary files a/tests/test_ecc_encrypt and /dev/null differ diff --git a/tests/test_ecc_encrypt.c b/tests/test_ecc_encrypt.c index 1b0987054..5874578f4 100644 --- a/tests/test_ecc_encrypt.c +++ b/tests/test_ecc_encrypt.c @@ -1,36 +1,37 @@ /* test_ecc_encrypt.c - TinyCrypt test for client-server key exchange and encryption */ /* - * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Intel Corporation nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ +* Copyright (C) 2017 by Intel Corporation, All Rights Reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* - Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* +* - Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* +* - Neither the name of Intel Corporation nor the names of its contributors +* may be used to endorse or promote products derived from this software +* without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +*/ #include +#include "../lib/debug_config.h" #include #include #include @@ -45,135 +46,135 @@ #define TC_PASS 0 #define TC_FAIL 1 -#define TC_PRINT printf -#define TC_ERROR(...) do { printf("ERROR: " __VA_ARGS__); } while(0) -#define TC_START(name) printf("Starting test: %s\n", name) -#define TC_END_RESULT(result) printf("Result: %s\n", (result) == TC_PASS ? "PASS" : "FAIL") -#define TC_END_REPORT(result) printf("Test %s\n", (result) == TC_PASS ? "SUCCESSFUL" : "FAILED") +#define TC_PRINT(...) DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, __VA_ARGS__) +#define TC_ERROR(...) do { DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, __VA_ARGS__); } while(0) +#define TC_START(name) DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Starting test: %s", name) +#define TC_END_RESULT(result) DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Result: %s", (result) == TC_PASS ? "PASS" : "FAIL") +#define TC_END_REPORT(result) DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Test %s", (result) == TC_PASS ? "SUCCESSFUL" : "FAILED") static void show_str(const char *label, const uint8_t *s, size_t len) { - unsigned int i; - printf("%s = ", label); - for (i = 0; i < (unsigned int) len; ++i) { - printf("%02x", s[i]); - } - printf("\n"); +unsigned int i; +DEBUG_INFO(DEBUG_CATEGORY_ALL, "%s =", label); +for (i = 0; i < (unsigned int) len; ++i) { +DEBUG_INFO(DEBUG_CATEGORY_ALL, "%02x", s[i]); +} +DEBUG_INFO(DEBUG_CATEGORY_ALL, ""); } static int test_key_exchange_and_encrypt(void) { - const struct uECC_Curve_t *curve = uECC_secp256r1(); +const struct uECC_Curve_t *curve = uECC_secp256r1(); - /* Client key pair */ - uint8_t client_private[NUM_ECC_BYTES]; - uint8_t client_public[2 * NUM_ECC_BYTES]; +/* Client key pair */ +uint8_t client_private[NUM_ECC_BYTES]; +uint8_t client_public[2 * NUM_ECC_BYTES]; - /* Server key pair */ - uint8_t server_private[NUM_ECC_BYTES]; - uint8_t server_public[2 * NUM_ECC_BYTES]; +/* Server key pair */ +uint8_t server_private[NUM_ECC_BYTES]; +uint8_t server_public[2 * NUM_ECC_BYTES]; - /* Shared secrets */ - uint8_t client_secret[NUM_ECC_BYTES]; - uint8_t server_secret[NUM_ECC_BYTES]; +/* Shared secrets */ +uint8_t client_secret[NUM_ECC_BYTES]; +uint8_t server_secret[NUM_ECC_BYTES]; - TC_PRINT("Generating client key pair...\n"); - if (!uECC_make_key(client_public, client_private, curve)) { - TC_ERROR("Failed to generate client key pair\n"); - return TC_FAIL; - } +TC_PRINT("Generating client key pair...\n"); +if (!uECC_make_key(client_public, client_private, curve)) { +TC_ERROR("Failed to generate client key pair\n"); +return TC_FAIL; +} - TC_PRINT("Generating server key pair...\n"); - if (!uECC_make_key(server_public, server_private, curve)) { - TC_ERROR("Failed to generate server key pair\n"); - return TC_FAIL; - } +TC_PRINT("Generating server key pair...\n"); +if (!uECC_make_key(server_public, server_private, curve)) { +TC_ERROR("Failed to generate server key pair\n"); +return TC_FAIL; +} - /* Compute shared secret on client side */ - TC_PRINT("Computing shared secret on client side...\n"); - if (!uECC_shared_secret(server_public, client_private, client_secret, curve)) { - TC_ERROR("Failed to compute client shared secret\n"); - return TC_FAIL; - } +/* Compute shared secret on client side */ +TC_PRINT("Computing shared secret on client side...\n"); +if (!uECC_shared_secret(server_public, client_private, client_secret, curve)) { +TC_ERROR("Failed to compute client shared secret\n"); +return TC_FAIL; +} - /* Compute shared secret on server side */ - TC_PRINT("Computing shared secret on server side...\n"); - if (!uECC_shared_secret(client_public, server_private, server_secret, curve)) { - TC_ERROR("Failed to compute server shared secret\n"); - return TC_FAIL; - } +/* Compute shared secret on server side */ +TC_PRINT("Computing shared secret on server side...\n"); +if (!uECC_shared_secret(client_public, server_private, server_secret, curve)) { +TC_ERROR("Failed to compute server shared secret\n"); +return TC_FAIL; +} - /* Verify that both shared secrets match */ - if (memcmp(client_secret, server_secret, NUM_ECC_BYTES) != 0) { - TC_ERROR("Shared secrets do not match\n"); - show_str("Client secret", client_secret, NUM_ECC_BYTES); - show_str("Server secret", server_secret, NUM_ECC_BYTES); - return TC_FAIL; - } - TC_PRINT("Shared secrets match.\n"); +/* Verify that both shared secrets match */ +if (memcmp(client_secret, server_secret, NUM_ECC_BYTES) != 0) { +TC_ERROR("Shared secrets do not match\n"); +show_str("Client secret", client_secret, NUM_ECC_BYTES); +show_str("Server secret", server_secret, NUM_ECC_BYTES); +return TC_FAIL; +} +TC_PRINT("Shared secrets match.\n"); - /* Derive AES key from shared secret (first 16 bytes) */ - uint8_t aes_key[TC_AES_KEY_SIZE]; - memcpy(aes_key, client_secret, TC_AES_KEY_SIZE); +/* Derive AES key from shared secret (first 16 bytes) */ +uint8_t aes_key[TC_AES_KEY_SIZE]; +memcpy(aes_key, client_secret, TC_AES_KEY_SIZE); - /* Prepare test data */ - const char *plaintext = "Hello, secure world!"; - size_t plaintext_len = strlen(plaintext) + 1; /* include null terminator */ - uint8_t ciphertext[plaintext_len]; - uint8_t decrypted[plaintext_len]; +/* Prepare test data */ +const char *plaintext = "Hello, secure world!"; +size_t plaintext_len = strlen(plaintext) + 1; /* include null terminator */ +uint8_t ciphertext[plaintext_len]; +uint8_t decrypted[plaintext_len]; - /* Initialize AES key schedule */ - struct tc_aes_key_sched_struct sched; - if (tc_aes128_set_encrypt_key(&sched, aes_key) != TC_CRYPTO_SUCCESS) { - TC_ERROR("Failed to set AES encryption key\n"); - return TC_FAIL; - } +/* Initialize AES key schedule */ +struct tc_aes_key_sched_struct sched; +if (tc_aes128_set_encrypt_key(&sched, aes_key) != TC_CRYPTO_SUCCESS) { +TC_ERROR("Failed to set AES encryption key\n"); +return TC_FAIL; +} - /* Initialize counter (little-endian 32-bit) */ - uint8_t ctr[TC_AES_BLOCK_SIZE] = {0}; /* zero-initialized counter */ +/* Initialize counter (little-endian 32-bit) */ +uint8_t ctr[TC_AES_BLOCK_SIZE] = {0}; /* zero-initialized counter */ - TC_PRINT("Encrypting plaintext...\n"); - if (tc_ctr_mode(ciphertext, plaintext_len, (const uint8_t *)plaintext, - plaintext_len, ctr, &sched) != TC_CRYPTO_SUCCESS) { - TC_ERROR("Encryption failed\n"); - return TC_FAIL; - } +TC_PRINT("Encrypting plaintext...\n"); +if (tc_ctr_mode(ciphertext, plaintext_len, (const uint8_t *)plaintext, +plaintext_len, ctr, &sched) != TC_CRYPTO_SUCCESS) { +TC_ERROR("Encryption failed\n"); +return TC_FAIL; +} - /* Reset counter for decryption (CTR mode uses same counter sequence) */ - memset(ctr, 0, TC_AES_BLOCK_SIZE); +/* Reset counter for decryption (CTR mode uses same counter sequence) */ +memset(ctr, 0, TC_AES_BLOCK_SIZE); - TC_PRINT("Decrypting ciphertext...\n"); - if (tc_ctr_mode(decrypted, plaintext_len, ciphertext, - plaintext_len, ctr, &sched) != TC_CRYPTO_SUCCESS) { - TC_ERROR("Decryption failed\n"); - return TC_FAIL; - } +TC_PRINT("Decrypting ciphertext...\n"); +if (tc_ctr_mode(decrypted, plaintext_len, ciphertext, +plaintext_len, ctr, &sched) != TC_CRYPTO_SUCCESS) { +TC_ERROR("Decryption failed\n"); +return TC_FAIL; +} - /* Verify decrypted matches original */ - if (memcmp(plaintext, decrypted, plaintext_len) != 0) { - TC_ERROR("Decrypted text does not match original\n"); - show_str("Original", (const uint8_t *)plaintext, plaintext_len); - show_str("Decrypted", decrypted, plaintext_len); - return TC_FAIL; - } - TC_PRINT("Decryption successful. Test passed.\n"); +/* Verify decrypted matches original */ +if (memcmp(plaintext, decrypted, plaintext_len) != 0) { +TC_ERROR("Decrypted text does not match original\n"); +show_str("Original", (const uint8_t *)plaintext, plaintext_len); +show_str("Decrypted", decrypted, plaintext_len); +return TC_FAIL; +} +TC_PRINT("Decryption successful. Test passed.\n"); - return TC_PASS; +return TC_PASS; } int main(void) { - unsigned int result = TC_PASS; +unsigned int result = TC_PASS; - TC_START("Performing client-server key exchange and encryption test:"); +TC_START("Performing client-server key exchange and encryption test:"); - /* Setup cryptographically secure PRNG */ - uECC_set_rng(&default_CSPRNG); +/* Setup cryptographically secure PRNG */ +uECC_set_rng(&default_CSPRNG); - result = test_key_exchange_and_encrypt(); +result = test_key_exchange_and_encrypt(); - TC_END_RESULT(result); - TC_END_REPORT(result); +TC_END_RESULT(result); +TC_END_REPORT(result); - return result; +return result; } \ No newline at end of file diff --git a/tests/test_ecc_encrypt.c.backup b/tests/test_ecc_encrypt.c.backup new file mode 100644 index 000000000..1b0987054 --- /dev/null +++ b/tests/test_ecc_encrypt.c.backup @@ -0,0 +1,179 @@ +/* test_ecc_encrypt.c - TinyCrypt test for client-server key exchange and encryption */ + +/* + * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Intel Corporation nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#define TC_PASS 0 +#define TC_FAIL 1 + +#define TC_PRINT printf +#define TC_ERROR(...) do { printf("ERROR: " __VA_ARGS__); } while(0) +#define TC_START(name) printf("Starting test: %s\n", name) +#define TC_END_RESULT(result) printf("Result: %s\n", (result) == TC_PASS ? "PASS" : "FAIL") +#define TC_END_REPORT(result) printf("Test %s\n", (result) == TC_PASS ? "SUCCESSFUL" : "FAILED") + +static void show_str(const char *label, const uint8_t *s, size_t len) +{ + unsigned int i; + printf("%s = ", label); + for (i = 0; i < (unsigned int) len; ++i) { + printf("%02x", s[i]); + } + printf("\n"); +} + +static int test_key_exchange_and_encrypt(void) +{ + const struct uECC_Curve_t *curve = uECC_secp256r1(); + + /* Client key pair */ + uint8_t client_private[NUM_ECC_BYTES]; + uint8_t client_public[2 * NUM_ECC_BYTES]; + + /* Server key pair */ + uint8_t server_private[NUM_ECC_BYTES]; + uint8_t server_public[2 * NUM_ECC_BYTES]; + + /* Shared secrets */ + uint8_t client_secret[NUM_ECC_BYTES]; + uint8_t server_secret[NUM_ECC_BYTES]; + + TC_PRINT("Generating client key pair...\n"); + if (!uECC_make_key(client_public, client_private, curve)) { + TC_ERROR("Failed to generate client key pair\n"); + return TC_FAIL; + } + + TC_PRINT("Generating server key pair...\n"); + if (!uECC_make_key(server_public, server_private, curve)) { + TC_ERROR("Failed to generate server key pair\n"); + return TC_FAIL; + } + + /* Compute shared secret on client side */ + TC_PRINT("Computing shared secret on client side...\n"); + if (!uECC_shared_secret(server_public, client_private, client_secret, curve)) { + TC_ERROR("Failed to compute client shared secret\n"); + return TC_FAIL; + } + + /* Compute shared secret on server side */ + TC_PRINT("Computing shared secret on server side...\n"); + if (!uECC_shared_secret(client_public, server_private, server_secret, curve)) { + TC_ERROR("Failed to compute server shared secret\n"); + return TC_FAIL; + } + + /* Verify that both shared secrets match */ + if (memcmp(client_secret, server_secret, NUM_ECC_BYTES) != 0) { + TC_ERROR("Shared secrets do not match\n"); + show_str("Client secret", client_secret, NUM_ECC_BYTES); + show_str("Server secret", server_secret, NUM_ECC_BYTES); + return TC_FAIL; + } + TC_PRINT("Shared secrets match.\n"); + + /* Derive AES key from shared secret (first 16 bytes) */ + uint8_t aes_key[TC_AES_KEY_SIZE]; + memcpy(aes_key, client_secret, TC_AES_KEY_SIZE); + + /* Prepare test data */ + const char *plaintext = "Hello, secure world!"; + size_t plaintext_len = strlen(plaintext) + 1; /* include null terminator */ + uint8_t ciphertext[plaintext_len]; + uint8_t decrypted[plaintext_len]; + + /* Initialize AES key schedule */ + struct tc_aes_key_sched_struct sched; + if (tc_aes128_set_encrypt_key(&sched, aes_key) != TC_CRYPTO_SUCCESS) { + TC_ERROR("Failed to set AES encryption key\n"); + return TC_FAIL; + } + + /* Initialize counter (little-endian 32-bit) */ + uint8_t ctr[TC_AES_BLOCK_SIZE] = {0}; /* zero-initialized counter */ + + TC_PRINT("Encrypting plaintext...\n"); + if (tc_ctr_mode(ciphertext, plaintext_len, (const uint8_t *)plaintext, + plaintext_len, ctr, &sched) != TC_CRYPTO_SUCCESS) { + TC_ERROR("Encryption failed\n"); + return TC_FAIL; + } + + /* Reset counter for decryption (CTR mode uses same counter sequence) */ + memset(ctr, 0, TC_AES_BLOCK_SIZE); + + TC_PRINT("Decrypting ciphertext...\n"); + if (tc_ctr_mode(decrypted, plaintext_len, ciphertext, + plaintext_len, ctr, &sched) != TC_CRYPTO_SUCCESS) { + TC_ERROR("Decryption failed\n"); + return TC_FAIL; + } + + /* Verify decrypted matches original */ + if (memcmp(plaintext, decrypted, plaintext_len) != 0) { + TC_ERROR("Decrypted text does not match original\n"); + show_str("Original", (const uint8_t *)plaintext, plaintext_len); + show_str("Decrypted", decrypted, plaintext_len); + return TC_FAIL; + } + TC_PRINT("Decryption successful. Test passed.\n"); + + return TC_PASS; +} + +int main(void) +{ + unsigned int result = TC_PASS; + + TC_START("Performing client-server key exchange and encryption test:"); + + /* Setup cryptographically secure PRNG */ + uECC_set_rng(&default_CSPRNG); + + result = test_key_exchange_and_encrypt(); + + TC_END_RESULT(result); + TC_END_REPORT(result); + + return result; +} \ No newline at end of file diff --git a/tests/test_etcp_crypto b/tests/test_etcp_crypto deleted file mode 100755 index f38c07c2d..000000000 Binary files a/tests/test_etcp_crypto and /dev/null differ diff --git a/tests/test_etcp_crypto.c b/tests/test_etcp_crypto.c index a870f0d3c..fbcef523f 100644 --- a/tests/test_etcp_crypto.c +++ b/tests/test_etcp_crypto.c @@ -1,5 +1,6 @@ // test_etcp_crypto.c - ETCP encryption/decryption test #include "../src/secure_channel.h" +#include "../lib/debug_config.h" #include #include #include @@ -9,67 +10,70 @@ #define TEST_DATA_LEN 28 int main() { - printf("=== ETCP Crypto Test ===\n"); - - // Create test keys - struct SC_MYKEYS server_keys, client_keys; - - for (int i = 0; i < SC_PRIVKEY_SIZE; i++) { - server_keys.private_key[i] = i & 0xFF; - client_keys.private_key[i] = (i + 128) & 0xFF; - } - - for (int i = 0; i < SC_PUBKEY_SIZE; i++) { - server_keys.public_key[i] = (i * 2) & 0xFF; - client_keys.public_key[i] = (i * 2 + 1) & 0xFF; - } - - // Initialize contexts - sc_context_t server_ctx, client_ctx; - if (sc_init_ctx(&server_ctx, &server_keys) != SC_OK || sc_init_ctx(&client_ctx, &client_keys) != SC_OK) { - printf("❌ Failed to initialize crypto contexts\n"); - return 1; - } - - // Initialize ECC system (may fail with test keys, but needed for RNG) - sc_set_peer_public_key(&client_ctx, (const char*)server_keys.public_key, 0); - sc_set_peer_public_key(&server_ctx, (const char*)client_keys.public_key, 0); - - // Manual setup for test keys - memcpy(client_ctx.peer_public_key, server_keys.public_key, SC_PUBKEY_SIZE); - memcpy(server_ctx.peer_public_key, client_keys.public_key, SC_PUBKEY_SIZE); - client_ctx.peer_key_set = 1; client_ctx.session_ready = 1; - server_ctx.peer_key_set = 1; server_ctx.session_ready = 1; - - uint8_t test_session_key[SC_SESSION_KEY_SIZE]; - for (int i = 0; i < SC_SESSION_KEY_SIZE; i++) test_session_key[i] = i + 100; - memcpy(client_ctx.session_key, test_session_key, SC_SESSION_KEY_SIZE); - memcpy(server_ctx.session_key, test_session_key, SC_SESSION_KEY_SIZE); - - printf("✅ Crypto contexts initialized\n"); - - // Test encryption/decryption - uint8_t plaintext[] = TEST_DATA; - uint8_t ciphertext[256], decrypted[256]; - size_t ciphertext_len, decrypted_len; - - // Client -> Server - if (sc_encrypt(&client_ctx, plaintext, TEST_DATA_LEN, ciphertext, &ciphertext_len) != SC_OK) { - printf("❌ Encryption failed\n"); - return 1; - } - - if (sc_decrypt(&server_ctx, ciphertext, ciphertext_len, decrypted, &decrypted_len) != SC_OK) { - printf("❌ Decryption failed\n"); - return 1; - } - - if (decrypted_len != TEST_DATA_LEN || memcmp(plaintext, decrypted, TEST_DATA_LEN) != 0) { - printf("❌ Data mismatch\n"); - return 1; - } - - printf("✅ Client->Server encryption/decryption: PASSED\n"); - printf("✅ ETCP crypto test PASSED\n"); - return 0; +debug_config_init(); +debug_set_level(DEBUG_LEVEL_TRACE); +debug_set_categories(DEBUG_CATEGORY_ALL); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "=== ETCP Crypto Test ==="); + +// Create test keys +struct SC_MYKEYS server_keys, client_keys; + +for (int i = 0; i < SC_PRIVKEY_SIZE; i++) { +server_keys.private_key[i] = i & 0xFF; +client_keys.private_key[i] = (i + 128) & 0xFF; +} + +for (int i = 0; i < SC_PUBKEY_SIZE; i++) { +server_keys.public_key[i] = (i * 2) & 0xFF; +client_keys.public_key[i] = (i * 2 + 1) & 0xFF; +} + +// Initialize contexts +sc_context_t server_ctx, client_ctx; +if (sc_init_ctx(&server_ctx, &server_keys) != SC_OK || sc_init_ctx(&client_ctx, &client_keys) != SC_OK) { +DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "Failed to initialize crypto contexts"); +return 1; +} + +// Initialize ECC system (may fail with test keys, but needed for RNG) +sc_set_peer_public_key(&client_ctx, (const char*)server_keys.public_key, 0); +sc_set_peer_public_key(&server_ctx, (const char*)client_keys.public_key, 0); + +// Manual setup for test keys +memcpy(client_ctx.peer_public_key, server_keys.public_key, SC_PUBKEY_SIZE); +memcpy(server_ctx.peer_public_key, client_keys.public_key, SC_PUBKEY_SIZE); +client_ctx.peer_key_set = 1; client_ctx.session_ready = 1; +server_ctx.peer_key_set = 1; server_ctx.session_ready = 1; + +uint8_t test_session_key[SC_SESSION_KEY_SIZE]; +for (int i = 0; i < SC_SESSION_KEY_SIZE; i++) test_session_key[i] = i + 100; +memcpy(client_ctx.session_key, test_session_key, SC_SESSION_KEY_SIZE); +memcpy(server_ctx.session_key, test_session_key, SC_SESSION_KEY_SIZE); + +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Crypto contexts initialized"); + +// Test encryption/decryption +uint8_t plaintext[] = TEST_DATA; +uint8_t ciphertext[256], decrypted[256]; +size_t ciphertext_len, decrypted_len; + +// Client -> Server +if (sc_encrypt(&client_ctx, plaintext, TEST_DATA_LEN, ciphertext, &ciphertext_len) != SC_OK) { +DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "Encryption failed"); +return 1; +} + +if (sc_decrypt(&server_ctx, ciphertext, ciphertext_len, decrypted, &decrypted_len) != SC_OK) { +DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "Decryption failed"); +return 1; +} + +if (decrypted_len != TEST_DATA_LEN || memcmp(plaintext, decrypted, TEST_DATA_LEN) != 0) { +DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "Data mismatch"); +return 1; +} + +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Client->Server encryption/decryption: PASSED"); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "ETCP crypto test PASSED"); +return 0; } diff --git a/tests/test_etcp_crypto.c.backup b/tests/test_etcp_crypto.c.backup new file mode 100644 index 000000000..394d915a3 --- /dev/null +++ b/tests/test_etcp_crypto.c.backup @@ -0,0 +1,79 @@ +// test_etcp_crypto.c - ETCP encryption/decryption test +#include "../src/secure_channel.h" +#include "../lib/debug_config.h" +#include +#include +#include +#include + +#define TEST_DATA "Hello, ETCP encrypted world!" +#define TEST_DATA_LEN 28 + +int main() { + debug_config_init(); + debug_set_level(DEBUG_LEVEL_TRACE); + debug_set_categories(DEBUG_CATEGORY_ALL); + DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "=== ETCP Crypto Test ==="); + + // Create test keys + struct SC_MYKEYS server_keys, client_keys; + + for (int i = 0; i < SC_PRIVKEY_SIZE; i++) { + server_keys.private_key[i] = i & 0xFF; + client_keys.private_key[i] = (i + 128) & 0xFF; + } + + for (int i = 0; i < SC_PUBKEY_SIZE; i++) { + server_keys.public_key[i] = (i * 2) & 0xFF; + client_keys.public_key[i] = (i * 2 + 1) & 0xFF; + } + + // Initialize contexts + sc_context_t server_ctx, client_ctx; + if (sc_init_ctx(&server_ctx, &server_keys) != SC_OK || sc_init_ctx(&client_ctx, &client_keys) != SC_OK) { + DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "Failed to initialize crypto contexts"); + return 1; + } + + // Initialize ECC system (may fail with test keys, but needed for RNG) + sc_set_peer_public_key(&client_ctx, (const char*)server_keys.public_key, 0); + sc_set_peer_public_key(&server_ctx, (const char*)client_keys.public_key, 0); + + // Manual setup for test keys + memcpy(client_ctx.peer_public_key, server_keys.public_key, SC_PUBKEY_SIZE); + memcpy(server_ctx.peer_public_key, client_keys.public_key, SC_PUBKEY_SIZE); + client_ctx.peer_key_set = 1; client_ctx.session_ready = 1; + server_ctx.peer_key_set = 1; server_ctx.session_ready = 1; + + uint8_t test_session_key[SC_SESSION_KEY_SIZE]; + for (int i = 0; i < SC_SESSION_KEY_SIZE; i++) test_session_key[i] = i + 100; + memcpy(client_ctx.session_key, test_session_key, SC_SESSION_KEY_SIZE); + memcpy(server_ctx.session_key, test_session_key, SC_SESSION_KEY_SIZE); + + DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Crypto contexts initialized"); + + // Test encryption/decryption + uint8_t plaintext[] = TEST_DATA; + uint8_t ciphertext[256], decrypted[256]; + size_t ciphertext_len, decrypted_len; + + // Client -> Server + if (sc_encrypt(&client_ctx, plaintext, TEST_DATA_LEN, ciphertext, &ciphertext_len) != SC_OK) { + DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "Encryption failed"); + return 1; + } + + if (sc_decrypt(&server_ctx, ciphertext, ciphertext_len, decrypted, &decrypted_len) != SC_OK) { + DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "Decryption failed"); + return 1; + } + + if (decrypted_len != TEST_DATA_LEN || memcmp(plaintext, decrypted, TEST_DATA_LEN) != 0) { + DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "Data mismatch"); + return 1; + } + + DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Client->Server encryption/decryption: PASSED"); + DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "ETCP crypto test PASSED"); + return 0; +} diff --git a/tests/test_etcp_minimal b/tests/test_etcp_minimal deleted file mode 100755 index e67723a2e..000000000 Binary files a/tests/test_etcp_minimal and /dev/null differ diff --git a/tests/test_etcp_minimal.c b/tests/test_etcp_minimal.c index d7838a466..3de80abe5 100644 --- a/tests/test_etcp_minimal.c +++ b/tests/test_etcp_minimal.c @@ -9,200 +9,199 @@ // Test basic packet analysis static void test_packet_analysis() { - printf("=== Testing Basic Packet Analysis ===\n"); - - // Simple test packet with one section - uint8_t test_packet[] = { - 0x00, // ETCP_SECTION_PAYLOAD - 0x00, 0x06, // Length: 6 bytes - 0x00, 0x01, // Packet ID: 1 - 0x48, 0x65, 0x6C, 0x6C, 0x6F // "Hello" - }; - - printf("Test packet: "); - for (int i = 0; i < sizeof(test_packet); i++) { - printf("%02X ", test_packet[i]); - } - printf("\n"); - - // Manual section parsing - if (sizeof(test_packet) >= 3) { - uint8_t section_type = test_packet[0]; - uint16_t section_len = (test_packet[1] << 8) | test_packet[2]; - - printf("Section type: 0x%02X\n", section_type); - printf("Section length: %u\n", section_len); - printf("Total packet size: %zu\n", sizeof(test_packet)); - - if (section_type == 0x00) { // PAYLOAD - printf("This is a PAYLOAD section\n"); - if (section_len >= 2 && section_len + 3 <= sizeof(test_packet)) { - uint16_t packet_id = (test_packet[3] << 8) | test_packet[4]; - printf("Packet ID: %u\n", packet_id); - printf("Payload size: %u bytes\n", section_len - 2); - - printf("Payload data: "); - for (int i = 0; i < section_len - 2; i++) { - printf("%02X ", test_packet[5 + i]); - } - printf("\n"); - - printf("Payload as text: "); - for (int i = 0; i < section_len - 2; i++) { - printf("%c", test_packet[5 + i]); - } - printf("\n"); - } - } - } +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "=== Testing Basic Packet Analysis ==="); + +// Simple test packet with one section +uint8_t test_packet[] = { +0x00, // ETCP_SECTION_PAYLOAD +0x00, 0x06, // Length: 6 bytes +0x00, 0x01, // Packet ID: 1 +0x48, 0x65, 0x6C, 0x6C, 0x6F // "Hello" +}; + +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Test packet:"); +for (int i = 0; i < sizeof(test_packet); i++) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "%02X", test_packet[i]); +} +DEBUG_INFO(DEBUG_CATEGORY_ETCP, ""); + +// Manual section parsing +if (sizeof(test_packet) >= 3) { +uint8_t section_type = test_packet[0]; +uint16_t section_len = (test_packet[1] << 8) | test_packet[2]; + +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Section type: 0x%02X", section_type); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Section length: %u", section_len); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Total packet size: %zu", sizeof(test_packet)); + +if (section_type == 0x00) { // PAYLOAD +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "This is a PAYLOAD section"); +if (section_len >= 2 && section_len + 3 <= sizeof(test_packet)) { +uint16_t packet_id = (test_packet[3] << 8) | test_packet[4]; +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Packet ID: %u", packet_id); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Payload size: %u bytes", section_len - 2); + +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Payload data:"); +for (int i = 0; i < section_len - 2; i++) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "%02X", test_packet[5 + i]); +} +DEBUG_INFO(DEBUG_CATEGORY_ETCP, ""); + +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Payload as text:"); +for (int i = 0; i < section_len - 2; i++) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "%c", test_packet[5 + i]); +} +DEBUG_INFO(DEBUG_CATEGORY_ETCP, ""); +} +} +} } // Test multiple sections static void test_multi_section_packet() { - printf("\n=== Testing Multi-Section Packet ===\n"); - - // Packet with TIMESTAMP + ACK + PAYLOAD sections - uint8_t multi_packet[] = { - // TIMESTAMP section - 0x06, 0x00, 0x02, 0x12, 0x34, - // ACK section - 0x01, 0x00, 0x09, 0x02, 0x00, 0x01, 0x56, 0x78, 0x00, 0x02, 0x56, 0x79, - // PAYLOAD section - 0x00, 0x00, 0x08, 0x00, 0x03, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x21 // "Hello!" - }; - - printf("Multi-section packet: "); - for (int i = 0; i < sizeof(multi_packet); i++) { - printf("%02X ", multi_packet[i]); - } - printf("\n"); - - // Parse each section - int pos = 0; - int section_count = 0; - - while (pos < sizeof(multi_packet) - 2) { - if (pos + 3 > sizeof(multi_packet)) break; - - uint8_t section_type = multi_packet[pos]; - uint16_t section_len = (multi_packet[pos+1] << 8) | multi_packet[pos+2]; - - printf("\nSection %d at position %d:\n", section_count, pos); - printf(" Type: 0x%02X ", section_type); - - switch (section_type) { - case 0x00: printf("(PAYLOAD)"); break; - case 0x01: printf("(ACK)"); break; - case 0x06: printf("(TIMESTAMP)"); break; - default: printf("(UNKNOWN)"); break; - } - printf("\n"); - printf(" Length: %u bytes\n", section_len); - - if (pos + 3 + section_len > sizeof(multi_packet)) { - printf(" ERROR: Section extends beyond packet boundary\n"); - break; - } - - // Section-specific analysis - uint8_t* section_data = multi_packet + pos + 3; - - switch (section_type) { - case 0x00: { // PAYLOAD - if (section_len >= 2) { - uint16_t packet_id = (section_data[0] << 8) | section_data[1]; - printf(" Packet ID: %u\n", packet_id); - printf(" Payload: "); - for (int i = 2; i < section_len; i++) { - printf("%c", section_data[i]); - } - printf("\n"); - } - break; - } - case 0x01: { // ACK - if (section_len >= 1) { - uint8_t ack_count = section_data[0]; - printf(" ACK count: %u\n", ack_count); - for (int i = 0; i < ack_count && i*4+5 <= section_len; i++) { - uint16_t ack_id = (section_data[1+i*4] << 8) | section_data[2+i*4]; - uint16_t ack_ts = (section_data[3+i*4] << 8) | section_data[4+i*4]; - printf(" ACK[%d]: id=%u, ts=%u\n", i, ack_id, ack_ts); - } - } - break; - } - case 0x06: { // TIMESTAMP - if (section_len == 2) { - uint16_t ts = (section_data[0] << 8) | section_data[1]; - printf(" Timestamp: %u\n", ts); - } - break; - } - } - - pos += 3 + section_len; - section_count++; - } - - printf("\nTotal sections parsed: %d\n", section_count); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\n=== Testing Multi-Section Packet ==="); + +// Packet with TIMESTAMP + ACK + PAYLOAD sections +uint8_t multi_packet[] = { +// TIMESTAMP section +0x06, 0x00, 0x02, 0x12, 0x34, +// ACK section +0x01, 0x00, 0x09, 0x02, 0x00, 0x01, 0x56, 0x78, 0x00, 0x02, 0x56, 0x79, +// PAYLOAD section +0x00, 0x00, 0x08, 0x00, 0x03, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x21 // "Hello!" +}; + +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Multi-section packet:"); +for (int i = 0; i < sizeof(multi_packet); i++) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "%02X", multi_packet[i]); +} +DEBUG_INFO(DEBUG_CATEGORY_ETCP, ""); + +// Parse each section +int pos = 0; +int section_count = 0; + +while (pos < sizeof(multi_packet) - 2) { +if (pos + 3 > sizeof(multi_packet)) break; + +uint8_t section_type = multi_packet[pos]; +uint16_t section_len = (multi_packet[pos+1] << 8) | multi_packet[pos+2]; + +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\nSection %d at position %d:", section_count, pos); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Type: 0x%02X", section_type); + +switch (section_type) { +case 0x00: printf("(PAYLOAD)"); break; +case 0x01: printf("(ACK)"); break; +case 0x06: printf("(TIMESTAMP)"); break; +default: printf("(UNKNOWN)"); break; +} +DEBUG_INFO(DEBUG_CATEGORY_ETCP, ""); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Length: %u bytes", section_len); + +if (pos + 3 + section_len > sizeof(multi_packet)) { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "ERROR: Section extends beyond packet boundary"); +break; +} + +// Section-specific analysis +uint8_t* section_data = multi_packet + pos + 3; + +switch (section_type) { +case 0x00: { // PAYLOAD +if (section_len >= 2) { +uint16_t packet_id = (section_data[0] << 8) | section_data[1]; +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Packet ID: %u", packet_id); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Payload:"); +for (int i = 2; i < section_len; i++) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "%c", section_data[i]); +} +DEBUG_INFO(DEBUG_CATEGORY_ETCP, ""); +} +break; +} +case 0x01: { // ACK +if (section_len >= 1) { +uint8_t ack_count = section_data[0]; +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "ACK count: %u", ack_count); +for (int i = 0; i < ack_count && i*4+5 <= section_len; i++) { +uint16_t ack_id = (section_data[1+i*4] << 8) | section_data[2+i*4]; +uint16_t ack_ts = (section_data[3+i*4] << 8) | section_data[4+i*4]; +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "ACK[%d]: id=%u, ts=%u", i, ack_id, ack_ts); +} +} +break; +} +case 0x06: { // TIMESTAMP +if (section_len == 2) { +uint16_t ts = (section_data[0] << 8) | section_data[1]; +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Timestamp: %u", ts); +} +break; +} +} + +pos += 3 + section_len; +section_count++; +} + +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\nTotal sections parsed: %d", section_count); } // Test connection establishment packets static void test_connection_packets() { - printf("\n=== Testing Connection Establishment Packets ===\n"); - - // INIT_REQUEST packet - uint8_t init_request[] = { - ETCP_INIT_REQUEST, // 0x02 - 0x00, 0x14, // 20 bytes - // Node ID - 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, - // MTU - 0x05, 0xDC, - // Keepalive - 0x00, 0x64, - // Fake public key (8 bytes) - 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x11, 0x22 - }; - - printf("INIT_REQUEST packet:\n"); - printf(" Node ID: 0x"); - for (int i = 0; i < 8; i++) printf("%02X", init_request[3+i]); - printf("\n"); - printf(" MTU: %u\n", (init_request[11] << 8) | init_request[12]); - printf(" Keepalive: %u\n", (init_request[13] << 8) | init_request[14]); - - // INIT_RESPONSE packet - uint8_t init_response[] = { - ETCP_INIT_RESPONSE, // 0x03 - 0x00, 0x0A, // 10 bytes - // Node ID - 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, - // MTU - 0x05, 0xDC - }; - - printf("\nINIT_RESPONSE packet:\n"); - printf(" Node ID: 0x"); - for (int i = 0; i < 8; i++) printf("%02X", init_response[3+i]); - printf("\n"); - printf(" MTU: %u\n", (init_response[11] << 8) | init_response[12]); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\n=== Testing Connection Establishment Packets ==="); + +// INIT_REQUEST packet +uint8_t init_request[] = { +ETCP_INIT_REQUEST, // 0x02 +0x00, 0x14, // 20 bytes +// Node ID +0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, +// MTU +0x05, 0xDC, +// Keepalive +0x00, 0x64, +// Fake public key (8 bytes) +0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x11, 0x22 +}; + +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "INIT_REQUEST packet:"); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Node ID: 0x"); +for (int i = 0; i < 8; i++) printf("%02X", init_request[3+i]); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, ""); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "MTU: %u", (init_request[11] << 8) | init_request[12]); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Keepalive: %u", (init_request[13] << 8) | init_request[14]); + +// INIT_RESPONSE packet +uint8_t init_response[] = { +ETCP_INIT_RESPONSE, // 0x03 +0x00, 0x0A, // 10 bytes +// Node ID +0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, +// MTU +0x05, 0xDC +}; + +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\nINIT_RESPONSE packet:"); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Node ID: 0x"); +for (int i = 0; i < 8; i++) printf("%02X", init_response[3+i]); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, ""); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "MTU: %u", (init_response[11] << 8) | init_response[12]); } int main() { - printf("=== Minimal ETCP Traffic Flow Debugging ===\n"); - - debug_config_init(); - debug_set_level(DEBUG_LEVEL_DEBUG); - debug_enable_category(DEBUG_CATEGORY_ETCP); - debug_enable_timestamp(1); - debug_enable_function_name(1); - - test_packet_analysis(); - test_multi_section_packet(); - test_connection_packets(); - - printf("\n=== Test completed ===\n"); - return 0; +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "=== Minimal ETCP Traffic Flow Debugging ==="); + +debug_config_init(); +debug_set_level(DEBUG_LEVEL_DEBUG); +debug_enable_category(DEBUG_CATEGORY_ETCP); +debug_enable_function_name(1); + +test_packet_analysis(); +test_multi_section_packet(); +test_connection_packets(); + +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\n=== Test completed ==="); +return 0; } \ No newline at end of file diff --git a/tests/test_etcp_minimal.c.backup b/tests/test_etcp_minimal.c.backup new file mode 100644 index 000000000..0911b84d6 --- /dev/null +++ b/tests/test_etcp_minimal.c.backup @@ -0,0 +1,207 @@ +// test_etcp_minimal.c - Minimal ETCP traffic debugging test +// This is the most basic test to verify ETCP packet processing works + +#include "../src/etcp.h" +#include "../lib/debug_config.h" +#include +#include +#include + +// Test basic packet analysis +static void test_packet_analysis() { + printf("=== Testing Basic Packet Analysis ===\n"); + + // Simple test packet with one section + uint8_t test_packet[] = { + 0x00, // ETCP_SECTION_PAYLOAD + 0x00, 0x06, // Length: 6 bytes + 0x00, 0x01, // Packet ID: 1 + 0x48, 0x65, 0x6C, 0x6C, 0x6F // "Hello" + }; + + printf("Test packet: "); + for (int i = 0; i < sizeof(test_packet); i++) { + printf("%02X ", test_packet[i]); + } + printf("\n"); + + // Manual section parsing + if (sizeof(test_packet) >= 3) { + uint8_t section_type = test_packet[0]; + uint16_t section_len = (test_packet[1] << 8) | test_packet[2]; + + printf("Section type: 0x%02X\n", section_type); + printf("Section length: %u\n", section_len); + printf("Total packet size: %zu\n", sizeof(test_packet)); + + if (section_type == 0x00) { // PAYLOAD + printf("This is a PAYLOAD section\n"); + if (section_len >= 2 && section_len + 3 <= sizeof(test_packet)) { + uint16_t packet_id = (test_packet[3] << 8) | test_packet[4]; + printf("Packet ID: %u\n", packet_id); + printf("Payload size: %u bytes\n", section_len - 2); + + printf("Payload data: "); + for (int i = 0; i < section_len - 2; i++) { + printf("%02X ", test_packet[5 + i]); + } + printf("\n"); + + printf("Payload as text: "); + for (int i = 0; i < section_len - 2; i++) { + printf("%c", test_packet[5 + i]); + } + printf("\n"); + } + } + } +} + +// Test multiple sections +static void test_multi_section_packet() { + printf("\n=== Testing Multi-Section Packet ===\n"); + + // Packet with TIMESTAMP + ACK + PAYLOAD sections + uint8_t multi_packet[] = { + // TIMESTAMP section + 0x06, 0x00, 0x02, 0x12, 0x34, + // ACK section + 0x01, 0x00, 0x09, 0x02, 0x00, 0x01, 0x56, 0x78, 0x00, 0x02, 0x56, 0x79, + // PAYLOAD section + 0x00, 0x00, 0x08, 0x00, 0x03, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x21 // "Hello!" + }; + + printf("Multi-section packet: "); + for (int i = 0; i < sizeof(multi_packet); i++) { + printf("%02X ", multi_packet[i]); + } + printf("\n"); + + // Parse each section + int pos = 0; + int section_count = 0; + + while (pos < sizeof(multi_packet) - 2) { + if (pos + 3 > sizeof(multi_packet)) break; + + uint8_t section_type = multi_packet[pos]; + uint16_t section_len = (multi_packet[pos+1] << 8) | multi_packet[pos+2]; + + printf("\nSection %d at position %d:\n", section_count, pos); + printf(" Type: 0x%02X ", section_type); + + switch (section_type) { + case 0x00: printf("(PAYLOAD)"); break; + case 0x01: printf("(ACK)"); break; + case 0x06: printf("(TIMESTAMP)"); break; + default: printf("(UNKNOWN)"); break; + } + printf("\n"); + printf(" Length: %u bytes\n", section_len); + + if (pos + 3 + section_len > sizeof(multi_packet)) { + printf(" ERROR: Section extends beyond packet boundary\n"); + break; + } + + // Section-specific analysis + uint8_t* section_data = multi_packet + pos + 3; + + switch (section_type) { + case 0x00: { // PAYLOAD + if (section_len >= 2) { + uint16_t packet_id = (section_data[0] << 8) | section_data[1]; + printf(" Packet ID: %u\n", packet_id); + printf(" Payload: "); + for (int i = 2; i < section_len; i++) { + printf("%c", section_data[i]); + } + printf("\n"); + } + break; + } + case 0x01: { // ACK + if (section_len >= 1) { + uint8_t ack_count = section_data[0]; + printf(" ACK count: %u\n", ack_count); + for (int i = 0; i < ack_count && i*4+5 <= section_len; i++) { + uint16_t ack_id = (section_data[1+i*4] << 8) | section_data[2+i*4]; + uint16_t ack_ts = (section_data[3+i*4] << 8) | section_data[4+i*4]; + printf(" ACK[%d]: id=%u, ts=%u\n", i, ack_id, ack_ts); + } + } + break; + } + case 0x06: { // TIMESTAMP + if (section_len == 2) { + uint16_t ts = (section_data[0] << 8) | section_data[1]; + printf(" Timestamp: %u\n", ts); + } + break; + } + } + + pos += 3 + section_len; + section_count++; + } + + printf("\nTotal sections parsed: %d\n", section_count); +} + +// Test connection establishment packets +static void test_connection_packets() { + printf("\n=== Testing Connection Establishment Packets ===\n"); + + // INIT_REQUEST packet + uint8_t init_request[] = { + ETCP_INIT_REQUEST, // 0x02 + 0x00, 0x14, // 20 bytes + // Node ID + 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, + // MTU + 0x05, 0xDC, + // Keepalive + 0x00, 0x64, + // Fake public key (8 bytes) + 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x11, 0x22 + }; + + printf("INIT_REQUEST packet:\n"); + printf(" Node ID: 0x"); + for (int i = 0; i < 8; i++) printf("%02X", init_request[3+i]); + printf("\n"); + printf(" MTU: %u\n", (init_request[11] << 8) | init_request[12]); + printf(" Keepalive: %u\n", (init_request[13] << 8) | init_request[14]); + + // INIT_RESPONSE packet + uint8_t init_response[] = { + ETCP_INIT_RESPONSE, // 0x03 + 0x00, 0x0A, // 10 bytes + // Node ID + 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, + // MTU + 0x05, 0xDC + }; + + printf("\nINIT_RESPONSE packet:\n"); + printf(" Node ID: 0x"); + for (int i = 0; i < 8; i++) printf("%02X", init_response[3+i]); + printf("\n"); + printf(" MTU: %u\n", (init_response[11] << 8) | init_response[12]); +} + +int main() { + printf("=== Minimal ETCP Traffic Flow Debugging ===\n"); + + debug_config_init(); + debug_set_level(DEBUG_LEVEL_DEBUG); + debug_enable_category(DEBUG_CATEGORY_ETCP); + debug_enable_function_name(1); + + test_packet_analysis(); + test_multi_section_packet(); + test_connection_packets(); + + printf("\n=== Test completed ===\n"); + return 0; +} \ No newline at end of file diff --git a/tests/test_etcp_simple_traffic b/tests/test_etcp_simple_traffic index 4299d2fb7..8dd3a600b 100755 Binary files a/tests/test_etcp_simple_traffic and b/tests/test_etcp_simple_traffic differ diff --git a/tests/test_etcp_simple_traffic.c b/tests/test_etcp_simple_traffic.c index f49128b41..596bd5526 100644 --- a/tests/test_etcp_simple_traffic.c +++ b/tests/test_etcp_simple_traffic.c @@ -28,332 +28,392 @@ static uint8_t test_packet_data[PACKET_SIZE]; static int packet_sent = 0; static int packet_received = 0; -// Function to check if connection is established +// Function to check if connection is established - UPDATED WITH DEBUG static int is_connection_established(struct UTUN_INSTANCE* inst) { - if (!inst) return 0; - - struct ETCP_CONN* conn = inst->connections; - while (conn) { - struct ETCP_LINK* link = conn->links; - while (link) { - if (link->initialized) { - return 1; - } - link = link->next; - } - conn = conn->next; - } - return 0; + +DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "is_connection_established: Checking instance %p", inst); + +if (!inst) { +DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "is_connection_established: Instance is NULL"); +return 0; +} + + +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "is_connection_established: Instance has %d connections", inst->connections_count); + +struct ETCP_CONN* conn = inst->connections; +while (conn) { +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "[DEBUG] is_connection_established: Checking connection %p", conn); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "is_connection_established: Checking connection %p", conn); +struct ETCP_LINK* link = conn->links; +while (link) { + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "is_connection_established: Link %p - initialized=%d, is_server=%d", + link, link->initialized, link->is_server); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "is_connection_established: Link %p - initialized=%d, is_server=%d", +link, link->initialized, link->is_server); +if (link->initialized) { +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "[DEBUG] is_connection_established: FOUND initialized link!"); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "is_connection_established: FOUND initialized link!"); +return 1; +} +link = link->next; +} +conn = conn->next; +} + +DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "is_connection_established: No initialized links found"); +return 0; } // Function to send test packet to client's input queue static void send_test_packet(void) { - if (!client_instance || packet_sent) return; - - struct ETCP_CONN* conn = client_instance->connections; - if (!conn) { - printf("No ETCP connection found on client\n"); - return; - } - - if (!conn->input_queue) { - printf("Client input queue is NULL\n"); - return; - } - - // Create test packet data - for (int i = 0; i < PACKET_SIZE; i++) { - test_packet_data[i] = (uint8_t)(i % 256); - } - - // Create queue data - void* data = queue_data_new(PACKET_SIZE); - if (!data) { - printf("Failed to create queue data\n"); - return; - } - - // Copy test data - memcpy(data, test_packet_data, PACKET_SIZE); - - // Put data into input queue - if (queue_data_put(conn->input_queue, data, 0) < 0) { - printf("Failed to put packet into input queue\n"); - queue_data_free(data); - return; - } - - packet_sent = 1; - printf("Test packet sent to client input queue (%d bytes)\n", PACKET_SIZE); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "[DEBUG] send_test_packet: ENTERING"); +DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "send_test_packet: ENTERING"); + +if (!client_instance || packet_sent) { +DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "send_test_packet: SKIPPING (client_instance=%p, packet_sent=%d)", client_instance, packet_sent); +return; +} + +struct ETCP_CONN* conn = client_instance->connections; +if (!conn) { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "send_test_packet: No ETCP connection found on client"); +return; +} + +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "[DEBUG] send_test_packet: Found connection %p", conn); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "send_test_packet: Found connection %p", conn); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "[DEBUG] send_test_packet: connection input_queue=%p", conn->input_queue); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "send_test_packet: connection input_queue=%p", conn->input_queue); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "[DEBUG] send_test_packet: connection output_queue=%p", conn->output_queue); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "send_test_packet: connection output_queue=%p", conn->output_queue); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "[DEBUG] send_test_packet: connection next_tx_id=%u", conn->next_tx_id); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "send_test_packet: connection next_tx_id=%u", conn->next_tx_id); + +if (!conn->input_queue) { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "send_test_packet: Client input queue is NULL"); +return; +} + +// Create test packet data +for (int i = 0; i < PACKET_SIZE; i++) { +test_packet_data[i] = (uint8_t)(i % 256); +} + +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "send_test_packet: Created test data, first byte=%02X, last byte=%02X", +test_packet_data[0], test_packet_data[PACKET_SIZE-1]); + +// Use new etcp_send function - much simpler API +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "[DEBUG] send_test_packet: Calling etcp_send with len=%d", PACKET_SIZE); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "send_test_packet: Calling etcp_send with len=%d", PACKET_SIZE); +int result = etcp_send(conn, test_packet_data, PACKET_SIZE); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "[DEBUG] send_test_packet: etcp_send returned %d", result); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "send_test_packet: etcp_send returned %d", result); + +if (result != 0) { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "send_test_packet: Failed to send packet via etcp_send"); +return; +} + +packet_sent = 1; +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "send_test_packet: SUCCESS - Test packet sent via etcp_send (%d bytes)", PACKET_SIZE); } // Function to check if packet received in server's output queue static void check_packet_received(void) { - if (!server_instance || packet_received) return; - - struct ETCP_CONN* conn = server_instance->connections; - if (!conn) return; - - if (!conn->output_queue) return; - - // Check if there's any packet in output queue - void* data = queue_data_get(conn->output_queue); - if (data) { - // В новом API размер данных нужно получать из структуры - struct ll_entry* entry = (struct ll_entry*)data - 1; - size_t size = entry->size; - - if (size == PACKET_SIZE && memcmp(data, test_packet_data, PACKET_SIZE) == 0) { - packet_received = 1; - printf("Packet received in server output queue (%zu bytes), data matches\n", size); - } else { - printf("Packet received but size mismatch or data differs (expected %d, got %zu)\n", PACKET_SIZE, size); - } - queue_data_free(data); - } +DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "check_packet_received: ENTERING"); + +if (!server_instance || packet_received) { +DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "check_packet_received: SKIPPING (server_instance=%p, packet_received=%d)", server_instance, packet_received); +return; +} + +struct ETCP_CONN* conn = server_instance->connections; +if (!conn) { +DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "check_packet_received: No connection on server"); +return; +} + +if (!conn->output_queue) { +DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "check_packet_received: No output_queue on server connection"); +return; +} + +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "check_packet_received: Checking server connection %p", conn); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "check_packet_received: Server output_queue count: %d", queue_entry_count(conn->output_queue)); + +// Check if there's any packet in output queue +void* data = queue_data_get(conn->output_queue); +if (data) { +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "check_packet_received: Found packet in output queue"); + +// В новом API размер данных нужно получать из структуры +struct ll_entry* entry = (struct ll_entry*)data - 1; +size_t size = entry->size; + +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "check_packet_received: Packet size=%zu, expected=%d", size, PACKET_SIZE); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "check_packet_received: First byte received=%02X, expected=%02X", +((uint8_t*)data)[0], test_packet_data[0]); + +if (size == PACKET_SIZE && memcmp(data, test_packet_data, PACKET_SIZE) == 0) { +packet_received = 1; +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "check_packet_received: SUCCESS - Packet received in server output queue (%zu bytes), data matches", size); +} else { +DEBUG_WARN(DEBUG_CATEGORY_ETCP, "check_packet_received: Packet received but size mismatch or data differs (expected %d, got %zu)", PACKET_SIZE, size); +} +queue_data_free(data); +} else { +DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "check_packet_received: No packet found in output queue"); +} } // Monitor connection and send packet when ready static void monitor_and_send(void* arg) { - (void)arg; - - if (test_completed) { - packet_timeout_id = NULL; - return; - } - - static int connection_checked = 0; - static int packet_sent_flag = 0; - - // Check connection - if (!connection_checked) { - int server_ready = is_connection_established(server_instance); - int client_ready = is_connection_established(client_instance); - - // We only need client link initialized to send packet - // Server will accept packets via its socket - if (client_ready) { - printf("Client link initialized, ready to send packet (server=%d, client=%d)\n", server_ready, client_ready); - connection_checked = 1; - } else { - printf("Waiting for connection... (server=%d, client=%d)\n", server_ready, client_ready); - } - } - - // Send packet once connection is ready - if (connection_checked && !packet_sent_flag) { - send_test_packet(); - packet_sent_flag = 1; - } - - // Check for received packet - if (packet_sent_flag) { - check_packet_received(); - if (packet_received) { - test_completed = 1; // Success - printf("\n=== SUCCESS: Packet transmitted successfully! ===\n"); - if (packet_timeout_id) { - uasync_cancel_timeout(server_instance->ua, packet_timeout_id); - packet_timeout_id = NULL; - } - return; - } - } - - // Schedule next check - if (!test_completed) { - packet_timeout_id = uasync_set_timeout(server_instance->ua, 100, NULL, monitor_and_send); - } +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "[DEBUG] monitor_and_send: ENTERING (arg=%p)", arg); +DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "monitor_and_send: ENTERING (arg=%p)", arg); +(void)arg; + +if (test_completed) { +packet_timeout_id = NULL; +return; +} + +static int connection_checked = 0; +static int packet_sent_flag = 0; + +// Check connection +if (!connection_checked) { +int server_ready = is_connection_established(server_instance); +int client_ready = is_connection_established(client_instance); + +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "[DEBUG] monitor_and_send: Connection check - server=%d, client=%d", server_ready, client_ready); +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "monitor_and_send: Connection check - server=%d, client=%d", server_ready, client_ready); + +// We only need client link initialized to send packet +// Server will accept packets via its socket +if (client_ready) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "monitor_and_send: Client link initialized, ready to send packet (server=%d, client=%d)", server_ready, client_ready); +connection_checked = 1; +} else { +DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "monitor_and_send: Waiting for connection... (server=%d, client=%d)", server_ready, client_ready); +} +} + +// Send packet once connection is ready +if (connection_checked && !packet_sent_flag) { +send_test_packet(); +packet_sent_flag = 1; +} + +// Check for received packet +if (packet_sent_flag) { +check_packet_received(); +if (packet_received) { +test_completed = 1; // Success +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\n=== SUCCESS: Packet transmitted successfully! ==="); +if (packet_timeout_id) { +uasync_cancel_timeout(server_instance->ua, packet_timeout_id); +packet_timeout_id = NULL; +} +return; +} +} + +// Schedule next check +if (!test_completed) { +packet_timeout_id = uasync_set_timeout(server_instance->ua, 100, NULL, monitor_and_send); +} } // Timeout handler static void test_timeout(void* arg) { - (void)arg; - if (!test_completed) { - printf("\n=== TIMEOUT: Packet not received within %d seconds ===\n", TEST_TIMEOUT_MS/1000); - test_completed = 2; // Timeout/failure - if (packet_timeout_id) { - uasync_cancel_timeout(server_instance->ua, packet_timeout_id); - packet_timeout_id = NULL; - } - } +(void)arg; +if (!test_completed) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\n=== TIMEOUT: Packet not received within %d seconds ===", TEST_TIMEOUT_MS/1000); +test_completed = 2; // Timeout/failure +if (packet_timeout_id) { +uasync_cancel_timeout(server_instance->ua, packet_timeout_id); +packet_timeout_id = NULL; +} +} } int main() { - printf("=== ETCP Simple Traffic Test (Queue-based) ===\n\n"); - - // Enable debug output - debug_config_init(); - debug_set_level(DEBUG_LEVEL_TRACE); - debug_set_categories(DEBUG_CATEGORY_ALL); - debug_enable_timestamp(1); - debug_enable_function_name(1); - - // Explicitly disable TUN initialization for this test - utun_instance_set_tun_init_enabled(0); - - // Create server instance - printf("Creating server instance...\n"); - struct UASYNC* server_ua = uasync_create(); - server_instance = utun_instance_create(server_ua, "test_server.conf", NULL); - if (!server_instance) { - printf("Failed to create server instance\n"); - return 1; - } - - // Initialize connections and register sockets regardless of TUN state - if (server_instance->tun.fd < 0) { - printf("ℹ️ Server TUN disabled - initializing connections only\n"); - } - - // Initialize ETCP connections (creates sockets and links) - if (init_connections(server_instance) < 0) { - printf("Failed to initialize server connections\n"); - utun_instance_destroy(server_instance); - return 1; - } else { - printf("Server connections initialized: sockets=%p, connections=%p\n", - server_instance->etcp_sockets, server_instance->connections); - } - +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "=== ETCP Simple Traffic Test (Queue-based) ===\n"); - - printf("✅ Server instance initialized successfully (node_id=%llx)\n", (unsigned long long)server_instance->node_id); - printf("Server instance ready (node_id=%llx)\n\n", (unsigned long long)server_instance->node_id); - - // Create client instance - printf("Creating client instance...\n"); - struct UASYNC* client_ua = uasync_create(); - client_instance = utun_instance_create(client_ua, "test_client.conf", NULL); - if (!client_instance) { - printf("Failed to create client instance\n"); - utun_instance_destroy(server_instance); - return 1; - } - - // Initialize connections and register sockets regardless of TUN state - if (client_instance->tun.fd < 0) { - printf("ℹ️ Client TUN disabled - initializing connections only\n"); - } - - // Initialize ETCP connections (creates sockets and links) - printf("About to call init_connections() for client instance\n"); - fflush(stdout); - - int conn_result = init_connections(client_instance); - printf("init_connections() returned: %d\n", conn_result); - fflush(stdout); - - if (conn_result < 0) { - printf("Failed to initialize client connections (result=%d)\n", conn_result); - printf("But continuing test to analyze the issue...\n"); - fflush(stdout); - // Don't return error - continue to analyze - } else { - printf("Client connections initialized: sockets=%p, connections=%p, count=%d\n", +// Enable debug output - MAXIMUM DEBUGGING +debug_config_init(); +debug_set_level(DEBUG_LEVEL_TRACE); +debug_set_categories(DEBUG_CATEGORY_ALL); +debug_enable_function_name(1); + +DEBUG_TRACE(DEBUG_CATEGORY_MEMORY, "*************1"); + + +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Function names enabled: YES"); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "===========================\n"); + +// Explicitly disable TUN initialization for this test +utun_instance_set_tun_init_enabled(0); + +// Create server instance +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Creating server instance..."); +struct UASYNC* server_ua = uasync_create(); +server_instance = utun_instance_create(server_ua, "test_server.conf"); +if (!server_instance) { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to create server instance"); +return 1; +} + +// Initialize connections and register sockets regardless of TUN state +if (server_instance->tun.fd < 0) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, " Server TUN disabled - initializing connections only"); +} + +// Initialize ETCP connections (creates sockets and links) +if (init_connections(server_instance) < 0) { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to initialize server connections"); +utun_instance_destroy(server_instance); +return 1; +} else { + DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Server connections initialized: sockets=%p, connections=%p", + server_instance->etcp_sockets, server_instance->connections); +} + + + +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Server instance initialized successfully (node_id=%llx)", (unsigned long long)server_instance->node_id); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Server instance ready (node_id=%llx)\n", (unsigned long long)server_instance->node_id); + +// Create client instance +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Creating client instance..."); +struct UASYNC* client_ua = uasync_create(); +client_instance = utun_instance_create(client_ua, "test_client.conf"); +if (!client_instance) { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to create client instance"); +utun_instance_destroy(server_instance); +return 1; +} + +// Initialize connections and register sockets regardless of TUN state +if (client_instance->tun.fd < 0) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, " Client TUN disabled - initializing connections only"); +} + +// Initialize ETCP connections (creates sockets and links) +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "About to call init_connections() for client instance"); + +int conn_result = init_connections(client_instance); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "init_connections() returned: %d", conn_result); + +if (conn_result < 0) { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to initialize client connections (result=%d)", conn_result); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "But continuing test to analyze the issue..."); +// Don't return error - continue to analyze +} else { + DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Client connections initialized: sockets=%p, connections=%p, count=%d", client_instance->etcp_sockets, client_instance->connections, client_instance ? client_instance->connections_count : -1); - fflush(stdout); - } - +} - - printf("✅ Client instance initialized successfully (node_id=%llx)\n", (unsigned long long)client_instance->node_id); - printf("Client instance ready (node_id=%llx)\n\n", (unsigned long long)client_instance->node_id); - - // Debug: print connection and link info - printf("\n=== Connection Debug ===\n"); - struct ETCP_CONN* conn = client_instance->connections; - while (conn) { - printf("Client connection %p: peer_node_id=%llx\n", conn, (unsigned long long)conn->peer_node_id); - struct ETCP_LINK* link = conn->links; - while (link) { - printf(" Link %p: initialized=%d, is_server=%d, remote_addr family=%d, conn->fd=%d\n", + + +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Client instance initialized successfully (node_id=%llx)", (unsigned long long)client_instance->node_id); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Client instance ready (node_id=%llx)\n", (unsigned long long)client_instance->node_id); + +// Debug: print connection and link info +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\n=== Connection Debug ==="); +struct ETCP_CONN* conn = client_instance->connections; +while (conn) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Client connection %p: peer_node_id=%llx", conn, (unsigned long long)conn->peer_node_id); +struct ETCP_LINK* link = conn->links; +while (link) { + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, " Link %p: initialized=%d, is_server=%d, remote_addr family=%d, conn->fd=%d", link, link->initialized, link->is_server, link->remote_addr.ss_family, link->conn ? link->conn->fd : -1); - link = link->next; - } - conn = conn->next; - } - conn = server_instance->connections; - while (conn) { - printf("Server connection %p: peer_node_id=%llx\n", conn, (unsigned long long)conn->peer_node_id); - struct ETCP_LINK* link = conn->links; - while (link) { - printf(" Link %p: initialized=%d, is_server=%d\n", link, link->initialized, link->is_server); - link = link->next; - } - conn = conn->next; - } - printf("=== End Debug ===\n\n"); - - // Start monitoring and packet transmission - printf("Starting packet transmission test...\n"); - packet_timeout_id = uasync_set_timeout(server_ua, 500, NULL, monitor_and_send); - void* global_timeout_id = uasync_set_timeout(server_ua, TEST_TIMEOUT_MS, NULL, test_timeout); - - // Main event loop - printf("Running event loop...\n\n"); - - // Give instances time to initialize - printf("Waiting 0.5 seconds for instances initialization...\n"); - for (int i = 0; i < 50; i++) { - if (server_ua) uasync_poll(server_ua, 10); - if (client_ua) uasync_poll(client_ua, 10); - usleep(10000); - } - printf("Starting connection and packet transmission...\n"); - - int elapsed = 0; - int poll_interval = 5; - while (!test_completed && elapsed < TEST_TIMEOUT_MS + 1000) { - if (server_ua) uasync_poll(server_ua, poll_interval); - if (client_ua) uasync_poll(client_ua, poll_interval); - - usleep(poll_interval * 1000); - elapsed += poll_interval; - - // Quick exit if packet received - if (test_completed == 1) { - printf("[TEST] Packet received, exiting early after %d ms\n", elapsed); - break; - } - } - - // Cleanup - printf("\nCleaning up...\n"); - - // Cancel timeouts - if (packet_timeout_id) { - uasync_cancel_timeout(server_ua, packet_timeout_id); - packet_timeout_id = NULL; - } - if (global_timeout_id) { - uasync_cancel_timeout(server_ua, global_timeout_id); - } - - // Destroy instances - if (server_instance) { - server_instance->running = 0; - utun_instance_destroy(server_instance); - } - if (client_instance) { - client_instance->running = 0; - utun_instance_destroy(client_instance); - } - - // Evaluate test result - if (test_completed == 1) { - printf("\n=== TEST PASSED ===\n"); - printf("✅ Packet successfully transmitted from client input queue to server output queue\n"); - printf("✅ ETCP connection and queue mechanisms verified\n"); - return 0; - } else if (test_completed == 2) { - printf("\n=== TEST FAILED: Packet not received within timeout ===\n"); - printf("❌ Connection may not have been established\n"); - printf("❌ Check if UDP sockets were created and bound correctly\n"); - return 1; - } else { - printf("\n=== TEST FAILED: Unknown error ===\n"); - return 1; - } +link = link->next; +} +conn = conn->next; +} +conn = server_instance->connections; +while (conn) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Server connection %p: peer_node_id=%llx", conn, (unsigned long long)conn->peer_node_id); +struct ETCP_LINK* link = conn->links; +while (link) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Link %p: initialized=%d, is_server=%d", link, link->initialized, link->is_server); +link = link->next; +} +conn = conn->next; +} +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "=== End Debug ===\n"); + +// Start monitoring and packet transmission +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Starting packet transmission test..."); +packet_timeout_id = uasync_set_timeout(server_ua, 500, NULL, monitor_and_send); +void* global_timeout_id = uasync_set_timeout(server_ua, TEST_TIMEOUT_MS, NULL, test_timeout); + +// Main event loop +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Running event loop...\n"); + +// Give instances time to initialize +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Waiting 0.5 seconds for instances initialization..."); +for (int i = 0; i < 50; i++) { +if (server_ua) uasync_poll(server_ua, 10); +if (client_ua) uasync_poll(client_ua, 10); +usleep(10000); +} +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Starting connection and packet transmission..."); + +int elapsed = 0; +int poll_interval = 5; +while (!test_completed && elapsed < TEST_TIMEOUT_MS + 1000) { +if (server_ua) uasync_poll(server_ua, poll_interval); +if (client_ua) uasync_poll(client_ua, poll_interval); + +usleep(poll_interval * 1000); +elapsed += poll_interval; + +// Quick exit if packet received +if (test_completed == 1) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[TEST] Packet received, exiting early after %d ms", elapsed); +break; +} +} + +// Cleanup +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\nCleaning up..."); + +// Cancel timeouts +if (packet_timeout_id) { +uasync_cancel_timeout(server_ua, packet_timeout_id); +packet_timeout_id = NULL; +} +if (global_timeout_id) { +uasync_cancel_timeout(server_ua, global_timeout_id); +} + +// Destroy instances +if (server_instance) { +server_instance->running = 0; +utun_instance_destroy(server_instance); +} +if (client_instance) { +client_instance->running = 0; +utun_instance_destroy(client_instance); +} + +// Evaluate test result +if (test_completed == 1) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\n=== TEST PASSED ==="); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Packet successfully transmitted from client input queue to server output queue"); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "ETCP connection and queue mechanisms verified"); +return 0; +} else if (test_completed == 2) { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "\n=== TEST FAILED: Packet not received within timeout ==="); +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Connection may not have been established"); +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Check if UDP sockets were created and bound correctly"); +return 1; +} else { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "\n=== TEST FAILED: Unknown error ==="); +return 1; +} } \ No newline at end of file diff --git a/tests/test_etcp_simple_traffic.c.backup b/tests/test_etcp_simple_traffic.c.backup index 7cc4d6539..a83939c7b 100644 --- a/tests/test_etcp_simple_traffic.c.backup +++ b/tests/test_etcp_simple_traffic.c.backup @@ -1,491 +1,435 @@ -// test_etcp_simple_traffic.c - Simplified ETCP traffic flow debugging without sockets -// This test focuses purely on ETCP protocol traffic analysis using direct packet injection - -#include "../src/etcp.h" -#include "../src/etcp_connections.h" -#include "../src/etcp_loadbalancer.h" -#include "../lib/u_async.h" -#include "../lib/debug_config.h" -#include "../lib/memory_pool.h" -#include "../lib/ll_queue.h" -#include "../src/secure_channel.h" -#include "../src/crc32.h" #include #include #include #include -#include #include -#include -// Simplified traffic analysis - focus on ETCP protocol packets only -typedef struct { - uint64_t timestamp; - uint16_t packet_id; - uint8_t packet_type; - uint16_t data_len; - uint8_t data[1500]; // Copy of packet data for analysis -} packet_capture_t; +#include "../src/etcp.h" +#include "../src/etcp_connections.h" +#include "../src/config_parser.h" +#include "../src/utun_instance.h" +#include "../src/routing.h" +#include "../src/tun_if.h" +#include "../src/secure_channel.h" +#include "../lib/u_async.h" +#include "../lib/ll_queue.h" +#include "../lib/debug_config.h" -typedef struct { - packet_capture_t captures[1000]; - size_t capture_count; - pthread_mutex_t lock; -} traffic_analyzer_t; +#define TEST_TIMEOUT_MS 5000 // 5 seconds for packet transmission +#define PACKET_SIZE 100 // Test packet size -// Test instance - simplified version without actual sockets -typedef struct { - struct UTUN_INSTANCE* instance; - struct ETCP_CONN* etcp_conn; - traffic_analyzer_t* analyzer; - uint64_t node_id; - int is_server; - int running; -} test_instance_t; +static struct UTUN_INSTANCE* server_instance = NULL; +static struct UTUN_INSTANCE* client_instance = NULL; +static int test_completed = 0; // 0 = running, 1 = success, 2 = timeout/failure +static void* packet_timeout_id = NULL; -// Global test state -static test_instance_t* server_instance = NULL; -static test_instance_t* client_instance = NULL; +// Test packet data +static uint8_t test_packet_data[PACKET_SIZE]; +static int packet_sent = 0; +static int packet_received = 0; -// Enhanced packet analysis function -static void analyze_etcp_packet(struct ETCP_CONN* etcp, uint8_t* data, uint16_t len, const char* direction) { - if (!etcp || !data || len == 0) { - DEBUG_WARN(DEBUG_CATEGORY_ETCP, "analyze_etcp_packet: invalid parameters (etcp=%p, data=%p, len=%u)", - etcp, data, len); +// Function to check if connection is established - UPDATED WITH DEBUG +static int is_connection_established(struct UTUN_INSTANCE* inst) { + + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "is_connection_established: Checking instance %p", inst); + + if (!inst) { + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "is_connection_established: Instance is NULL"); + return 0; + } + + + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "is_connection_established: Instance has %d connections", inst->connections_count); + + struct ETCP_CONN* conn = inst->connections; + while (conn) { + printf("[DEBUG] is_connection_established: Checking connection %p\n", conn); + fflush(stdout); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "is_connection_established: Checking connection %p", conn); + struct ETCP_LINK* link = conn->links; + while (link) { + printf("[DEBUG] is_connection_established: Link %p - initialized=%d, is_server=%d\n", + link, link->initialized, link->is_server); + fflush(stdout); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "is_connection_established: Link %p - initialized=%d, is_server=%d", + link, link->initialized, link->is_server); + if (link->initialized) { + printf("[DEBUG] is_connection_established: FOUND initialized link!\n"); + fflush(stdout); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "is_connection_established: FOUND initialized link!"); + return 1; + } + link = link->next; + } + conn = conn->next; + } + + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "is_connection_established: No initialized links found"); + return 0; +} + +// Function to send test packet to client's input queue +static void send_test_packet(void) { + printf("[DEBUG] send_test_packet: ENTERING\n"); + fflush(stdout); + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "send_test_packet: ENTERING"); + + if (!client_instance || packet_sent) { + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "send_test_packet: SKIPPING (client_instance=%p, packet_sent=%d)", client_instance, packet_sent); return; } - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "PACKET %s: etcp=%p, len=%u, first_byte=0x%02x", - direction, etcp, len, data[0]); - - // Parse ETCP sections - uint16_t pos = 0; - int section_count = 0; - - while (pos < len) { - if (pos + 3 > len) { - DEBUG_WARN(DEBUG_CATEGORY_ETCP, "Invalid section header at pos %u (need 3 bytes, have %u)", - pos, len - pos); - break; - } - - uint8_t section_type = data[pos]; - uint16_t section_len = (data[pos+1] << 8) | data[pos+2]; - - DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "Section %d: type=0x%02x, len=%u at pos=%u", - section_count, section_type, section_len, pos); - - if (pos + 3 + section_len > len || section_len > 1500) { - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Section length %u exceeds packet boundary (pos=%u, total=%u) or max size", - section_len, pos, len); - break; - } - - // Analyze specific section types - uint8_t* section_data = data + pos + 3; - - switch (section_type) { - case ETCP_SECTION_PAYLOAD: { - if (section_len >= 2) { - uint16_t packet_id = (section_data[0] << 8) | section_data[1]; - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, " PAYLOAD: packet_id=%u, payload_len=%u", - packet_id, section_len - 2); - } - break; - } - case ETCP_SECTION_ACK: { - if (section_len >= 1) { - uint8_t ack_count = section_data[0]; - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, " ACK: count=%u", ack_count); - for (int i = 0; i < ack_count && i*4+5 <= section_len; i++) { - uint16_t ack_id = (section_data[1+i*4] << 8) | section_data[2+i*4]; - uint16_t ack_ts = (section_data[3+i*4] << 8) | section_data[4+i*4]; - DEBUG_TRACE(DEBUG_CATEGORY_ETCP, " ACK[%d]: id=%u, ts=%u", i, ack_id, ack_ts); - } - } - break; - } - case ETCP_SECTION_TIMESTAMP: { - if (section_len == 2) { - uint16_t ts = (section_data[0] << 8) | section_data[1]; - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, " TIMESTAMP: ts=%u", ts); - } - break; - } - case ETCP_INIT_REQUEST: { - if (section_len >= 76) { // node_id(8) + mtu(2) + keepalive(2) + pubkey(64) - uint64_t node_id = 0; - for (int i = 0; i < 8; i++) { - node_id = (node_id << 8) | section_data[i]; - } - uint16_t mtu = (section_data[8] << 8) | section_data[9]; - uint16_t keepalive = (section_data[10] << 8) | section_data[11]; - DEBUG_INFO(DEBUG_CATEGORY_ETCP, " INIT_REQUEST: node_id=%llu, mtu=%u, keepalive=%u", - (unsigned long long)node_id, mtu, keepalive); - } - break; - } - case ETCP_INIT_RESPONSE: { - if (section_len >= 10) { // node_id(8) + mtu(2) - uint64_t node_id = 0; - for (int i = 0; i < 8; i++) { - node_id = (node_id << 8) | section_data[i]; - } - uint16_t mtu = (section_data[8] << 8) | section_data[9]; - DEBUG_INFO(DEBUG_CATEGORY_ETCP, " INIT_RESPONSE: node_id=%llu, mtu=%u", - (unsigned long long)node_id, mtu); - } - break; - } - default: { - if (section_type >= ETCP_SECTION_RETRANS && section_type <= ETCP_SECTION_RETRANS + 0x1F) { - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, " RETRANS: base_id=%u", section_type - ETCP_SECTION_RETRANS); - // Parse retransmission requests - for (int i = 0; i < section_len; i += 2) { - if (i+1 < section_len) { - uint16_t req_id = (section_data[i] << 8) | section_data[i+1]; - DEBUG_TRACE(DEBUG_CATEGORY_ETCP, " RETRANS_REQ: id=%u", req_id); - } - } - } else { - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, " UNKNOWN: type=0x%02x, len=%u", section_type, section_len); - } - break; - } - } - - pos += 3 + section_len; - section_count++; + struct ETCP_CONN* conn = client_instance->connections; + if (!conn) { + DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "send_test_packet: No ETCP connection found on client"); + return; } - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "Packet analysis complete: %d sections processed", section_count); -} - -// Simulate packet reception for analysis -static void simulate_packet_rx(test_instance_t* inst, uint8_t* data, uint16_t len) { - if (!inst || !inst->etcp_conn || !data) return; + printf("[DEBUG] send_test_packet: Found connection %p\n", conn); + fflush(stdout); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "send_test_packet: Found connection %p", conn); + printf("[DEBUG] send_test_packet: connection input_queue=%p\n", conn->input_queue); + fflush(stdout); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "send_test_packet: connection input_queue=%p", conn->input_queue); + printf("[DEBUG] send_test_packet: connection output_queue=%p\n", conn->output_queue); + fflush(stdout); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "send_test_packet: connection output_queue=%p", conn->output_queue); + printf("[DEBUG] send_test_packet: connection next_tx_id=%u\n", conn->next_tx_id); + fflush(stdout); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "send_test_packet: connection next_tx_id=%u", conn->next_tx_id); - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "SIMULATE RX: inst=%s, len=%u", - inst->is_server ? "server" : "client", len); - - // Analyze the packet first - analyze_etcp_packet(inst->etcp_conn, data, len, "SIM_RX"); - - // Create a mock ETCP_DGRAM for processing - struct ETCP_DGRAM mock_dgram; - memset(&mock_dgram, 0, sizeof(mock_dgram)); - mock_dgram.link = NULL; // Will be set by connection processing - mock_dgram.data_len = len > 1500 ? 1500 : len; - mock_dgram.timestamp = get_current_timestamp(); - if (mock_dgram.data_len > 0) { - memcpy(mock_dgram.data, data, mock_dgram.data_len); + if (!conn->input_queue) { + DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "send_test_packet: Client input queue is NULL"); + return; } - // Process through ETCP input - etcp_conn_input(&mock_dgram); + // Create test packet data + for (int i = 0; i < PACKET_SIZE; i++) { + test_packet_data[i] = (uint8_t)(i % 256); + } + + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "send_test_packet: Created test data, first byte=%02X, last byte=%02X", + test_packet_data[0], test_packet_data[PACKET_SIZE-1]); + + // Use new etcp_send function - much simpler API + printf("[DEBUG] send_test_packet: Calling etcp_send with len=%d\n", PACKET_SIZE); + fflush(stdout); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "send_test_packet: Calling etcp_send with len=%d", PACKET_SIZE); + int result = etcp_send(conn, test_packet_data, PACKET_SIZE); + printf("[DEBUG] send_test_packet: etcp_send returned %d\n", result); + fflush(stdout); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "send_test_packet: etcp_send returned %d", result); + + if (result != 0) { + DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "send_test_packet: Failed to send packet via etcp_send"); + return; + } + + packet_sent = 1; + DEBUG_INFO(DEBUG_CATEGORY_ETCP, "send_test_packet: SUCCESS - Test packet sent via etcp_send (%d bytes)", PACKET_SIZE); } -// Simulate packet transmission for analysis -static void simulate_packet_tx(test_instance_t* inst) { - if (!inst || !inst->etcp_conn) return; +// Function to check if packet received in server's output queue +static void check_packet_received(void) { + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "check_packet_received: ENTERING"); - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "SIMULATE TX: inst=%s", - inst->is_server ? "server" : "client"); + if (!server_instance || packet_received) { + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "check_packet_received: SKIPPING (server_instance=%p, packet_received=%d)", server_instance, packet_received); + return; + } - struct ETCP_DGRAM* dgram = etcp_request_pkt(inst->etcp_conn); - if (dgram) { - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "Generated packet: len=%u", dgram->data_len); - analyze_etcp_packet(inst->etcp_conn, dgram->data, dgram->data_len, "SIM_TX"); + struct ETCP_CONN* conn = server_instance->connections; + if (!conn) { + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "check_packet_received: No connection on server"); + return; + } + + if (!conn->output_queue) { + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "check_packet_received: No output_queue on server connection"); + return; + } + + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "check_packet_received: Checking server connection %p", conn); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "check_packet_received: Server output_queue count: %d", queue_entry_count(conn->output_queue)); + + // Check if there's any packet in output queue + void* data = queue_data_get(conn->output_queue); + if (data) { + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "check_packet_received: Found packet in output queue"); - // In a real scenario, this would be sent over the network - // For now, we just analyze it and free it - DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "Would send %u bytes to peer", dgram->data_len); + // В новом API размер данных нужно получать из структуры + struct ll_entry* entry = (struct ll_entry*)data - 1; + size_t size = entry->size; + + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "check_packet_received: Packet size=%zu, expected=%d", size, PACKET_SIZE); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "check_packet_received: First byte received=%02X, expected=%02X", + ((uint8_t*)data)[0], test_packet_data[0]); + + if (size == PACKET_SIZE && memcmp(data, test_packet_data, PACKET_SIZE) == 0) { + packet_received = 1; + DEBUG_INFO(DEBUG_CATEGORY_ETCP, "check_packet_received: SUCCESS - Packet received in server output queue (%zu bytes), data matches", size); + } else { + DEBUG_WARN(DEBUG_CATEGORY_ETCP, "check_packet_received: Packet received but size mismatch or data differs (expected %d, got %zu)", PACKET_SIZE, size); + } + queue_data_free(data); } else { - DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "No packets available to send"); + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "check_packet_received: No packet found in output queue"); } } -// Create simplified test instance -static test_instance_t* create_simple_instance(uint64_t node_id, int is_server) { - test_instance_t* inst = calloc(1, sizeof(test_instance_t)); - if (!inst) return NULL; +// Monitor connection and send packet when ready +static void monitor_and_send(void* arg) { + printf("[DEBUG] monitor_and_send: ENTERING (arg=%p)\n", arg); + fflush(stdout); + DEBUG_TRACE(DEBUG_CATEGORY_ETCP, "monitor_and_send: ENTERING (arg=%p)", arg); + (void)arg; - inst->node_id = node_id; - inst->is_server = is_server; - inst->running = 1; - - // Create traffic analyzer - inst->analyzer = calloc(1, sizeof(traffic_analyzer_t)); - if (inst->analyzer) { - pthread_mutex_init(&inst->analyzer->lock, NULL); + if (test_completed) { + packet_timeout_id = NULL; + return; } - // Create UTUN instance directly without TUN device - inst->instance = calloc(1, sizeof(struct UTUN_INSTANCE)); - if (!inst->instance) { - free(inst->analyzer); - free(inst); - return NULL; - } + static int connection_checked = 0; + static int packet_sent_flag = 0; - // Initialize the instance manually - inst->instance->node_id = node_id; - inst->instance->running = 1; - inst->instance->log_fp = stderr; - - // Initialize crypto keys (hardcoded for test) - const char* priv_key_hex = "67b705a92b41bcaae105af2d6a17743faa7b26ccebba8b3b9b0af05e9cd1d5fb"; - const char* pub_key_hex = "1c55e4ccae7c4470707759086738b10681bf88b81f198cc2ab54a647d1556e17c65e6b1833e0c771e5a39382c03067c388915a4c732191bc130480f20f8e00b9"; - - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "Parsing crypto keys: priv_len=%zu, pub_len=%zu", - strlen(priv_key_hex), strlen(pub_key_hex)); - - // Parse keys - for (int i = 0; i < 32; i++) { - if (sscanf(&priv_key_hex[i*2], "%2hhx", &inst->instance->my_keys.private_key[i]) != 1) { - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to parse private key byte %d", i); - } - } - for (int i = 0; i < 64; i++) { - if (sscanf(&pub_key_hex[i*2], "%2hhx", &inst->instance->my_keys.public_key[i]) != 1) { - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to parse public key byte %d", i); + // Check connection + if (!connection_checked) { + int server_ready = is_connection_established(server_instance); + int client_ready = is_connection_established(client_instance); + + printf("[DEBUG] monitor_and_send: Connection check - server=%d, client=%d\n", server_ready, client_ready); + fflush(stdout); + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "monitor_and_send: Connection check - server=%d, client=%d", server_ready, client_ready); + + // We only need client link initialized to send packet + // Server will accept packets via its socket + if (client_ready) { + DEBUG_INFO(DEBUG_CATEGORY_ETCP, "monitor_and_send: Client link initialized, ready to send packet (server=%d, client=%d)", server_ready, client_ready); + connection_checked = 1; + } else { + DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "monitor_and_send: Waiting for connection... (server=%d, client=%d)", server_ready, client_ready); } } - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "Keys parsed successfully"); - - // Create uasync context - inst->instance->ua = uasync_create(); - if (!inst->instance->ua) { - free(inst->instance); - free(inst->analyzer); - free(inst); - return NULL; - } - uasync_init_instance(inst->instance->ua); - - // Create packet pool - inst->instance->pkt_pool = memory_pool_init(1600); // 1600 byte packets - if (!inst->instance->pkt_pool) { - uasync_destroy(inst->instance->ua); - free(inst->instance); - free(inst->analyzer); - free(inst); - return NULL; + // Send packet once connection is ready + if (connection_checked && !packet_sent_flag) { + send_test_packet(); + packet_sent_flag = 1; } - // Create ETCP connection - inst->etcp_conn = etcp_connection_create(inst->instance); - if (!inst->etcp_conn) { - memory_pool_destroy(inst->instance->pkt_pool); - uasync_destroy(inst->instance->ua); - free(inst->instance); - free(inst->analyzer); - free(inst); - return NULL; - } - - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Created %s instance (node_id=%llu)", - is_server ? "server" : "client", (unsigned long long)node_id); - - return inst; -} - -// Cleanup simplified test instance -static void destroy_simple_instance(test_instance_t* inst) { - if (!inst) return; - - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Destroying %s instance", inst->is_server ? "server" : "client"); - - if (inst->etcp_conn) { - etcp_connection_close(inst->etcp_conn); - } - - if (inst->instance) { - if (inst->instance->pkt_pool) { - memory_pool_destroy(inst->instance->pkt_pool); - } - if (inst->instance->ua) { - uasync_destroy(inst->instance->ua); - } - free(inst->instance); - } - - if (inst->analyzer) { - pthread_mutex_destroy(&inst->analyzer->lock); - free(inst->analyzer); - } - - free(inst); -} - -// Generate test packets manually -static void generate_test_packets(test_instance_t* inst, int count) { - if (!inst || !inst->etcp_conn) return; - - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Generating %d test packets for %s instance", - count, inst->is_server ? "server" : "client"); - - for (int i = 0; i < count; i++) { - struct ll_entry* entry = queue_entry_new(100); // 100 byte packets - if (entry) { - // Fill with test data - uint8_t* data = (uint8_t*)ll_entry_data(entry); - for (int j = 0; j < 100; j++) { - data[j] = (uint8_t)((i+1) * 10 + j); // Pattern data + // Check for received packet + if (packet_sent_flag) { + check_packet_received(); + if (packet_received) { + test_completed = 1; // Success + printf("\n=== SUCCESS: Packet transmitted successfully! ===\n"); + if (packet_timeout_id) { + uasync_cancel_timeout(server_instance->ua, packet_timeout_id); + packet_timeout_id = NULL; } - queue_entry_put(inst->etcp_conn->input_queue, entry); - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "Queued test packet %d for %s", - i+1, inst->is_server ? "server" : "client"); + return; + } + } + + // Schedule next check + if (!test_completed) { + packet_timeout_id = uasync_set_timeout(server_instance->ua, 100, NULL, monitor_and_send); + } +} + +// Timeout handler +static void test_timeout(void* arg) { + (void)arg; + if (!test_completed) { + printf("\n=== TIMEOUT: Packet not received within %d seconds ===\n", TEST_TIMEOUT_MS/1000); + test_completed = 2; // Timeout/failure + if (packet_timeout_id) { + uasync_cancel_timeout(server_instance->ua, packet_timeout_id); + packet_timeout_id = NULL; } } } -// Main test function -int main(int argc, char* argv[]) { - printf("=== ETCP Traffic Flow Debugging Test (Simplified) ===\n"); +int main() { + printf("=== ETCP Simple Traffic Test (Queue-based) ===\n\n"); - // Initialize debug system + // Enable debug output - MAXIMUM DEBUGGING debug_config_init(); - debug_set_level(DEBUG_LEVEL_DEBUG); - debug_enable_category(DEBUG_CATEGORY_ETCP); - debug_enable_timestamp(1); + debug_set_level(DEBUG_LEVEL_TRACE); + debug_set_categories(DEBUG_CATEGORY_ALL); debug_enable_function_name(1); + + DEBUG_TRACE(DEBUG_CATEGORY_MEMORY, "*************1"); + - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Starting simplified ETCP traffic flow debugging test"); + printf("Function names enabled: YES\n"); + printf("===========================\n\n"); + // Explicitly disable TUN initialization for this test + utun_instance_set_tun_init_enabled(0); + // Create server instance - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Creating server instance..."); - server_instance = create_simple_instance(0x1111111111111111ULL, 1); + printf("Creating server instance...\n"); + struct UASYNC* server_ua = uasync_create(); + server_instance = utun_instance_create(server_ua, "test_server.conf"); if (!server_instance) { - fprintf(stderr, "Failed to create server instance\n"); + printf("Failed to create server instance\n"); return 1; } + + // Initialize connections and register sockets regardless of TUN state + if (server_instance->tun.fd < 0) { + printf("ℹ️ Server TUN disabled - initializing connections only\n"); + } + + // Initialize ETCP connections (creates sockets and links) + if (init_connections(server_instance) < 0) { + printf("Failed to initialize server connections\n"); + utun_instance_destroy(server_instance); + return 1; + } else { + printf("Server connections initialized: sockets=%p, connections=%p\n", + server_instance->etcp_sockets, server_instance->connections); + } + + + + printf("✅ Server instance initialized successfully (node_id=%llx)\n", (unsigned long long)server_instance->node_id); + printf("Server instance ready (node_id=%llx)\n\n", (unsigned long long)server_instance->node_id); // Create client instance - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Creating client instance..."); - client_instance = create_simple_instance(0x2222222222222222ULL, 0); + printf("Creating client instance...\n"); + struct UASYNC* client_ua = uasync_create(); + client_instance = utun_instance_create(client_ua, "test_client.conf"); if (!client_instance) { - fprintf(stderr, "Failed to create client instance\n"); - destroy_simple_instance(server_instance); + printf("Failed to create client instance\n"); + utun_instance_destroy(server_instance); return 1; } - // Phase 1: Test basic packet generation and analysis - printf("\n=== Phase 1: Basic Packet Generation ===\n"); - - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Generating test packets..."); - generate_test_packets(server_instance, 5); - generate_test_packets(client_instance, 5); - - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Simulating packet transmission..."); - - // Let server generate some packets - for (int i = 0; i < 3; i++) { - simulate_packet_tx(server_instance); - usleep(10000); // 1ms delay + // Initialize connections and register sockets regardless of TUN state + if (client_instance->tun.fd < 0) { + printf("ℹ️ Client TUN disabled - initializing connections only\n"); } - // Let client generate some packets - for (int i = 0; i < 3; i++) { - simulate_packet_tx(client_instance); - usleep(10000); // 1ms delay + // Initialize ETCP connections (creates sockets and links) + printf("About to call init_connections() for client instance\n"); + fflush(stdout); + + int conn_result = init_connections(client_instance); + printf("init_connections() returned: %d\n", conn_result); + fflush(stdout); + + if (conn_result < 0) { + printf("Failed to initialize client connections (result=%d)\n", conn_result); + printf("But continuing test to analyze the issue...\n"); + fflush(stdout); + // Don't return error - continue to analyze + } else { + printf("Client connections initialized: sockets=%p, connections=%p, count=%d\n", + client_instance->etcp_sockets, client_instance->connections, + client_instance ? client_instance->connections_count : -1); + fflush(stdout); } - // Phase 2: Test connection establishment simulation - printf("\n=== Phase 2: Connection Establishment Simulation ===\n"); + - // Simulate INIT_REQUEST from client - smaller version for testing - uint8_t init_request[] = { - ETCP_INIT_REQUEST, // Section type - 0x00, 0x14, // Section length (20 bytes) - smaller for test - // Node ID (8 bytes) - 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, - // MTU (2 bytes) - 0x05, 0xDC, // 1500 - // Keepalive (2 bytes) - 0x00, 0x64, // 100 - // Fake public key (8 bytes) - just for testing - 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x11, 0x22 - }; - // Total: 3 + 20 = 23 bytes + printf("✅ Client instance initialized successfully (node_id=%llx)\n", (unsigned long long)client_instance->node_id); + printf("Client instance ready (node_id=%llx)\n\n", (unsigned long long)client_instance->node_id); - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Simulating INIT_REQUEST from client..."); - simulate_packet_rx(server_instance, init_request, sizeof(init_request)); - - // Simulate INIT_RESPONSE from server - uint8_t init_response[] = { - ETCP_INIT_RESPONSE, // Section type - 0x00, 0x0A, // Section length (10 bytes) - // Node ID (8 bytes) - 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, - // MTU (2 bytes) - 0x05, 0xDC // 1500 - }; - // Total: 3 + 10 = 13 bytes - - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Simulating INIT_RESPONSE from server..."); - simulate_packet_rx(client_instance, init_response, sizeof(init_response)); - - // Phase 3: Test mixed traffic with ACKs and timestamps - printf("\n=== Phase 3: Mixed Traffic Simulation ===\n"); - - // Generate more traffic - generate_test_packets(server_instance, 3); - generate_test_packets(client_instance, 3); - - // Simulate some packets with multiple sections - uint8_t complex_packet[] = { - // TIMESTAMP section: 3 bytes header + 2 bytes data = 5 bytes - ETCP_SECTION_TIMESTAMP, 0x00, 0x02, 0x12, 0x34, - // ACK section with 2 ACKs: 3 bytes header + 1 byte count + 2*4 bytes = 12 bytes total - ETCP_SECTION_ACK, 0x00, 0x09, 0x02, 0x00, 0x01, 0x12, 0x34, 0x00, 0x02, 0x12, 0x35, - // PAYLOAD section: 3 bytes header + 2 bytes ID + 5 bytes data = 10 bytes total - ETCP_SECTION_PAYLOAD, 0x00, 0x08, 0x00, 0x05, 0x48, 0x65, 0x6C, 0x6C, 0x6F // "Hello" - }; - // Total: 5 + 12 + 10 = 27 bytes - - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Simulating complex packet with multiple sections..."); - simulate_packet_rx(server_instance, complex_packet, sizeof(complex_packet)); - - // Phase 4: Test retransmission requests - printf("\n=== Phase 4: Retransmission Testing ===\n"); - - uint8_t retrans_request[] = { - ETCP_SECTION_RETRANS + 0x02, // RETRANS section with base ID 2 - 0x00, 0x04, // Section length (4 bytes) - 0x00, 0x03, // Request retransmission of packet ID 3 - 0x00, 0x04 // Request retransmission of packet ID 4 - }; - // Total: 3 + 4 = 7 bytes - - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Simulating retransmission request..."); - simulate_packet_rx(client_instance, retrans_request, sizeof(retrans_request)); - - // Final packet generation - printf("\n=== Final Phase: Additional Traffic ===\n"); - - // Generate final packets - for (int i = 0; i < 5; i++) { - simulate_packet_tx(server_instance); - simulate_packet_tx(client_instance); - usleep(5000); // 0.5ms delay + // Debug: print connection and link info + printf("\n=== Connection Debug ===\n"); + struct ETCP_CONN* conn = client_instance->connections; + while (conn) { + printf("Client connection %p: peer_node_id=%llx\n", conn, (unsigned long long)conn->peer_node_id); + struct ETCP_LINK* link = conn->links; + while (link) { + printf(" Link %p: initialized=%d, is_server=%d, remote_addr family=%d, conn->fd=%d\n", + link, link->initialized, link->is_server, link->remote_addr.ss_family, link->conn ? link->conn->fd : -1); + link = link->next; + } + conn = conn->next; } + conn = server_instance->connections; + while (conn) { + printf("Server connection %p: peer_node_id=%llx\n", conn, (unsigned long long)conn->peer_node_id); + struct ETCP_LINK* link = conn->links; + while (link) { + printf(" Link %p: initialized=%d, is_server=%d\n", link, link->initialized, link->is_server); + link = link->next; + } + conn = conn->next; + } + printf("=== End Debug ===\n\n"); - // Print summary - printf("\n=== Traffic Analysis Summary ===\n"); - printf("Server instance: processed packets with detailed section analysis\n"); - printf("Client instance: processed packets with detailed section analysis\n"); - printf("Connection establishment: INIT handshake simulated\n"); - printf("Mixed traffic: ACK, TIMESTAMP, PAYLOAD sections processed\n"); - printf("Retransmission: RETRANS requests processed\n"); + // Start monitoring and packet transmission + printf("Starting packet transmission test...\n"); + packet_timeout_id = uasync_set_timeout(server_ua, 500, NULL, monitor_and_send); + void* global_timeout_id = uasync_set_timeout(server_ua, TEST_TIMEOUT_MS, NULL, test_timeout); + + // Main event loop + printf("Running event loop...\n\n"); + + // Give instances time to initialize + printf("Waiting 0.5 seconds for instances initialization...\n"); + for (int i = 0; i < 50; i++) { + if (server_ua) uasync_poll(server_ua, 10); + if (client_ua) uasync_poll(client_ua, 10); + usleep(10000); + } + printf("Starting connection and packet transmission...\n"); + + int elapsed = 0; + int poll_interval = 5; + while (!test_completed && elapsed < TEST_TIMEOUT_MS + 1000) { + if (server_ua) uasync_poll(server_ua, poll_interval); + if (client_ua) uasync_poll(client_ua, poll_interval); + + usleep(poll_interval * 1000); + elapsed += poll_interval; + + // Quick exit if packet received + if (test_completed == 1) { + printf("[TEST] Packet received, exiting early after %d ms\n", elapsed); + break; + } + } // Cleanup - destroy_simple_instance(server_instance); - destroy_simple_instance(client_instance); + printf("\nCleaning up...\n"); - DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Test completed"); - printf("\n=== Test completed successfully ===\n"); + // Cancel timeouts + if (packet_timeout_id) { + uasync_cancel_timeout(server_ua, packet_timeout_id); + packet_timeout_id = NULL; + } + if (global_timeout_id) { + uasync_cancel_timeout(server_ua, global_timeout_id); + } - return 0; + // Destroy instances + if (server_instance) { + server_instance->running = 0; + utun_instance_destroy(server_instance); + } + if (client_instance) { + client_instance->running = 0; + utun_instance_destroy(client_instance); + } + + // Evaluate test result + if (test_completed == 1) { + printf("\n=== TEST PASSED ===\n"); + printf("✅ Packet successfully transmitted from client input queue to server output queue\n"); + printf("✅ ETCP connection and queue mechanisms verified\n"); + return 0; + } else if (test_completed == 2) { + printf("\n=== TEST FAILED: Packet not received within timeout ===\n"); + printf("❌ Connection may not have been established\n"); + printf("❌ Check if UDP sockets were created and bound correctly\n"); + return 1; + } else { + printf("\n=== TEST FAILED: Unknown error ===\n"); + return 1; + } } \ No newline at end of file diff --git a/tests/test_etcp_two_instances b/tests/test_etcp_two_instances deleted file mode 100755 index a4975a727..000000000 Binary files a/tests/test_etcp_two_instances and /dev/null differ diff --git a/tests/test_etcp_two_instances.c b/tests/test_etcp_two_instances.c index 2003fd002..8bb783681 100644 --- a/tests/test_etcp_two_instances.c +++ b/tests/test_etcp_two_instances.c @@ -12,6 +12,7 @@ #include "../src/tun_if.h" #include "../src/secure_channel.h" #include "../lib/u_async.h" +#include "../lib/debug_config.h" #define TEST_TIMEOUT_MS 3000 // Reduced to 3 seconds for faster testing @@ -26,265 +27,265 @@ extern void etcp_connections_read_callback(int fd, void* arg); extern int etcp_encrypt_send(struct ETCP_DGRAM* dgram); static void monitor_connections(void* arg) { - (void)arg; - - if (test_completed) { - // НЕ перезапускать таймер если тест завершен - printf("[MONITOR] Test completed, stopping monitor timer\n"); - monitor_timeout_id = NULL; - return; - } - - // Быстрый выход если уже есть подключение - int server_links = 0; - int client_links = 0; - int client_initialized = 0; - - // Check server - if (server_instance) { - struct ETCP_CONN* conn = server_instance->connections; - while (conn) { - struct ETCP_LINK* link = conn->links; - while (link) { - server_links++; - printf("[SERVER] Link: peer=%llx initialized=%d type=%s\n", - (unsigned long long)conn->peer_node_id, - link->initialized, - link->is_server ? "server" : "client"); - link = link->next; - } - conn = conn->next; - } - } - - // Check client - if (client_instance) { - struct ETCP_CONN* conn = client_instance->connections; - while (conn) { - struct ETCP_LINK* link = conn->links; - while (link) { - client_links++; - if (link->is_server == 0) { // client link - printf("[CLIENT] Link: peer=%llx initialized=%d timer=%s retry=%d\n", - (unsigned long long)conn->peer_node_id, - link->initialized, - link->init_timer ? "active" : "null", - link->init_retry_count); - if (link->initialized) { - client_initialized = 1; - } - } - link = link->next; - } - conn = conn->next; - } - } - - // Check if connection established - if (client_initialized) { - printf("\n=== SUCCESS: Client connection established! ===\n"); - test_completed = 1; // Success - // Отменить таймаут теста для быстрого завершения - if (test_timeout_id) { - printf("[TEST] Cancelling test timeout for immediate exit\n"); - uasync_cancel_timeout(server_instance->ua, test_timeout_id); - test_timeout_id = NULL; - } - return; - } - - printf("[MONITOR] Server links: %d, Client links: %d, Status: %s\n", - server_links, client_links, - client_initialized ? "CONNECTED" : "connecting..."); - - // Schedule next check - if (!test_completed) { - monitor_timeout_id = uasync_set_timeout(server_instance->ua, 200, NULL, monitor_connections); // Check every 200ms for faster detection - } +(void)arg; + +if (test_completed) { +// НЕ перезапускать таймер если тест завершен +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[MONITOR] Test completed, stopping monitor timer"); +monitor_timeout_id = NULL; +return; +} + +// Быстрый выход если уже есть подключение +int server_links = 0; +int client_links = 0; +int client_initialized = 0; + +// Check server +if (server_instance) { +struct ETCP_CONN* conn = server_instance->connections; +while (conn) { +struct ETCP_LINK* link = conn->links; +while (link) { +server_links++; +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[SERVER] Link: peer=%llx initialized=%d type=%s", (unsigned long long)conn->peer_node_id, +link->initialized, +link->is_server ? "server" : "client"); +link = link->next; +} +conn = conn->next; +} +} + +// Check client +if (client_instance) { +struct ETCP_CONN* conn = client_instance->connections; +while (conn) { +struct ETCP_LINK* link = conn->links; +while (link) { +client_links++; +if (link->is_server == 0) { // client link +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[CLIENT] Link: peer=%llx initialized=%d timer=%s retry=%d", (unsigned long long)conn->peer_node_id, +link->initialized, +link->init_timer ? "active" : "null", +link->init_retry_count); +if (link->initialized) { +client_initialized = 1; +} +} +link = link->next; +} +conn = conn->next; +} +} + +// Check if connection established +if (client_initialized) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\n=== SUCCESS: Client connection established! ==="); +test_completed = 1; // Success +// Отменить таймаут теста для быстрого завершения +if (test_timeout_id) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[TEST] Cancelling test timeout for immediate exit"); +uasync_cancel_timeout(server_instance->ua, test_timeout_id); +test_timeout_id = NULL; +} +return; +} + +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[MONITOR] Server links: %d, Client links: %d, Status: %s", server_links, client_links, +client_initialized ? "CONNECTED" : "connecting..."); + +// Schedule next check +if (!test_completed) { +monitor_timeout_id = uasync_set_timeout(server_instance->ua, 200, NULL, monitor_connections); // Check every 200ms for faster detection +} } static void test_timeout(void* arg) { - (void)arg; - if (!test_completed) { - printf("\n=== TIMEOUT: Connection not established in %d seconds ===\n", TEST_TIMEOUT_MS/1000); - test_completed = 2; // Timeout/failure - // Cancel the monitoring timeout since we're done - if (monitor_timeout_id) { - uasync_cancel_timeout(server_instance->ua, monitor_timeout_id); - monitor_timeout_id = NULL; - } - } +(void)arg; +if (!test_completed) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\n=== TIMEOUT: Connection not established in %d seconds ===", TEST_TIMEOUT_MS/1000); +test_completed = 2; // Timeout/failure +// Cancel the monitoring timeout since we're done +if (monitor_timeout_id) { +uasync_cancel_timeout(server_instance->ua, monitor_timeout_id); +monitor_timeout_id = NULL; +} +} } int main() { - printf("=== ETCP Two-Instance Connection Test ===\n\n"); - - // Explicitly disable TUN initialization for this test - utun_instance_set_tun_init_enabled(0); - - // Create server instance - printf("Creating server instance...\n"); - struct UASYNC* server_ua = uasync_create(); - server_instance = utun_instance_create(server_ua, "test_server.conf", NULL); - if (!server_instance) { - printf("Failed to create server instance\n"); - return 1; - } - - // Check if TUN is disabled and handle accordingly - if (server_instance->tun.fd < 0) { - printf("ℹ️ Server TUN disabled - skipping full initialization\n"); - printf("✅ Server instance created successfully (node_id=%llx)\n", (unsigned long long)server_instance->node_id); - // Skip to client creation - } else { - // Normal initialization for TUN-enabled mode - if (utun_instance_init(server_instance) < 0) { - printf("Failed to initialize server instance\n"); - utun_instance_destroy(server_instance); - return 1; - } - - if (utun_instance_register_sockets(server_instance) < 0) { - printf("Failed to register server sockets\n"); - utun_instance_destroy(server_instance); - return 1; - } - } - printf("Server instance ready (node_id=%llx)\n\n", (unsigned long long)server_instance->node_id); - - // Create client instance - printf("Creating client instance...\n"); - struct UASYNC* client_ua = uasync_create(); - client_instance = utun_instance_create(client_ua, "test_client.conf", NULL); - if (!client_instance) { - printf("Failed to create client instance\n"); - utun_instance_destroy(server_instance); - return 1; - } - - // Check if TUN is disabled and handle accordingly - if (client_instance->tun.fd < 0) { - printf("ℹ️ Client TUN disabled - skipping full initialization\n"); - printf("✅ Client instance created successfully (node_id=%llx)\n", (unsigned long long)client_instance->node_id); - // Skip to test execution - } else { - // Normal initialization for TUN-enabled mode - if (utun_instance_init(client_instance) < 0) { - printf("Failed to initialize client instance\n"); - utun_instance_destroy(server_instance); - utun_instance_destroy(client_instance); - return 1; - } - - if (utun_instance_register_sockets(client_instance) < 0) { - printf("Failed to register client sockets\n"); - utun_instance_destroy(server_instance); - utun_instance_destroy(client_instance); - return 1; - } - } - printf("Client instance ready (node_id=%llx)\n\n", (unsigned long long)client_instance->node_id); - - // Start monitoring - printf("Starting connection monitoring...\n"); - monitor_timeout_id = uasync_set_timeout(server_ua, 1000, NULL, monitor_connections); - test_timeout_id = uasync_set_timeout(server_ua, TEST_TIMEOUT_MS, NULL, test_timeout); - - // Main event loop - printf("Running event loop...\n\n"); - - // Give server time to fully initialize before client starts sending - printf("Waiting 0.5 seconds for server initialization...\n"); - for (int i = 0; i < 50; i++) { // Reduced from 200 to 50 iterations (0.5 seconds) - if (server_ua) uasync_poll(server_ua, 10); - if (client_ua) uasync_poll(client_ua, 10); - usleep(10000); // 10ms - } - printf("Starting connection attempts...\n"); - - int elapsed = 0; - int poll_interval = 5; // Reduced from 10ms to 5ms for faster response - while (!test_completed && elapsed < TEST_TIMEOUT_MS + 500) { - if (server_ua) uasync_poll(server_ua, poll_interval); - if (client_ua) uasync_poll(client_ua, poll_interval); - - usleep(poll_interval * 1000); // microseconds - elapsed += poll_interval; - - // Быстрый выход если подключение установлено - if (test_completed == 1) { - printf("[TEST] Connection established, exiting early after %d ms\n", elapsed); - break; - } - } - - // Cleanup - printf("\nCleaning up...\n"); - printf("[CLEANUP] server_ua=%p, client_ua=%p\n", server_ua, client_ua); - printf("[CLEANUP] server_instance=%p, client_instance=%p\n", server_instance, client_instance); - printf("[CLEANUP] monitor_timeout_id=%p, test_timeout_id=%p\n", monitor_timeout_id, test_timeout_id); - - // СНАЧАЛА отменить таймеры пока uasync ещё жив - if (monitor_timeout_id) { - printf("[CLEANUP] Canceling monitor timeout on valid uasync\n"); - uasync_cancel_timeout(server_ua, monitor_timeout_id); - monitor_timeout_id = NULL; - } - if (test_timeout_id) { - printf("[CLEANUP] Canceling test timeout on valid uasync\n"); - uasync_cancel_timeout(server_ua, test_timeout_id); - test_timeout_id = NULL; - } - printf("[CLEANUP] Timeouts canceled\n"); - - // Диагностика ресурсов перед cleanup - if (server_ua) { - printf("[CLEANUP] Server resources before destroy:\n"); - uasync_print_resources(server_ua, "SERVER"); - } - if (client_ua) { - printf("[CLEANUP] Client resources before destroy:\n"); - uasync_print_resources(client_ua, "CLIENT"); - } - - // ПОТОМ уничтожить instances - if (server_instance) { - server_instance->running = 0; - printf("[CLEANUP] Destroying server instance %p\n", server_instance); - utun_instance_destroy(server_instance); - } - if (client_instance) { - client_instance->running = 0; - printf("[CLEANUP] Destroying client instance %p\n", client_instance); - utun_instance_destroy(client_instance); - } - - // Cleanup uasync objects - НЕ НУЖНО, так как utun_instance_destroy уже вызывает uasync_destroy - // if (server_ua) uasync_destroy(server_ua); - // if (client_ua) uasync_destroy(client_ua); - - if (test_completed == 1) { - printf("\n=== TEST PASSED ===\n"); - // Check if TUN was disabled and add note - if (server_instance->tun.fd < 0 || client_instance->tun.fd < 0) { - printf("✅ ETCP connection test successful with TUN disabled\n"); - printf("✅ Core ETCP protocol functionality verified\n"); - } - return 0; - } else if (test_completed == 2) { - // Check if TUN was disabled - if so, timeout is expected and acceptable - if (server_instance->tun.fd < 0 || client_instance->tun.fd < 0) { - printf("\n=== TEST PASSED ===\n"); - printf("ℹ️ Connection timeout expected with TUN disabled\n"); - printf("✅ ETCP core infrastructure verified successfully\n"); - printf("✅ Instance creation and configuration works with TUN disabled\n"); - printf("✅ All core components initialized correctly\n"); - return 0; - } - printf("\n=== TEST FAILED: Connection timeout ===\n"); - return 1; - } else { - printf("\n=== TEST FAILED: Unknown error ===\n"); - return 1; - } +debug_config_init(); +debug_set_level(DEBUG_LEVEL_TRACE); +debug_set_categories(DEBUG_CATEGORY_ALL); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "=== ETCP Two-Instance Connection Test ==="); + +// Explicitly disable TUN initialization for this test +utun_instance_set_tun_init_enabled(0); + +// Create server instance +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Creating server instance..."); +struct UASYNC* server_ua = uasync_create(); +server_instance = utun_instance_create(server_ua, "test_server.conf"); +if (!server_instance) { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to create server instance"); +return 1; +} + +// Check if TUN is disabled and handle accordingly +if (server_instance->tun.fd < 0) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, " Server TUN disabled - skipping full initialization"); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Server instance created successfully (node_id=%llx)", (unsigned long long)server_instance->node_id); +// Skip to client creation +} else { +// Normal initialization for TUN-enabled mode +if (utun_instance_init(server_instance) < 0) { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to initialize server instance"); +utun_instance_destroy(server_instance); +return 1; +} + +if (utun_instance_register_sockets(server_instance) < 0) { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to register server sockets"); +utun_instance_destroy(server_instance); +return 1; +} +} +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Server instance ready (node_id=%llx)\n", (unsigned long long)server_instance->node_id); + +// Create client instance +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Creating client instance..."); +struct UASYNC* client_ua = uasync_create(); +client_instance = utun_instance_create(client_ua, "test_client.conf"); +if (!client_instance) { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to create client instance"); +utun_instance_destroy(server_instance); +return 1; +} + +// Check if TUN is disabled and handle accordingly +if (client_instance->tun.fd < 0) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, " Client TUN disabled - skipping full initialization"); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Client instance created successfully (node_id=%llx)", (unsigned long long)client_instance->node_id); +// Skip to test execution +} else { +// Normal initialization for TUN-enabled mode +if (utun_instance_init(client_instance) < 0) { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to initialize client instance"); +utun_instance_destroy(server_instance); +utun_instance_destroy(client_instance); +return 1; +} + +if (utun_instance_register_sockets(client_instance) < 0) { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to register client sockets"); +utun_instance_destroy(server_instance); +utun_instance_destroy(client_instance); +return 1; +} +} +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Client instance ready (node_id=%llx)\n", (unsigned long long)client_instance->node_id); + +// Start monitoring +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Starting connection monitoring..."); +monitor_timeout_id = uasync_set_timeout(server_ua, 1000, NULL, monitor_connections); +test_timeout_id = uasync_set_timeout(server_ua, TEST_TIMEOUT_MS, NULL, test_timeout); + +// Main event loop +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Running event loop...\n"); + +// Give server time to fully initialize before client starts sending +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Waiting 0.5 seconds for server initialization..."); +for (int i = 0; i < 50; i++) { // Reduced from 200 to 50 iterations (0.5 seconds) +if (server_ua) uasync_poll(server_ua, 10); +if (client_ua) uasync_poll(client_ua, 10); +usleep(10000); // 10ms +} +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Starting connection attempts..."); + +int elapsed = 0; +int poll_interval = 5; // Reduced from 10ms to 5ms for faster response +while (!test_completed && elapsed < TEST_TIMEOUT_MS + 500) { +if (server_ua) uasync_poll(server_ua, poll_interval); +if (client_ua) uasync_poll(client_ua, poll_interval); + +usleep(poll_interval * 1000); // microseconds +elapsed += poll_interval; + +// Быстрый выход если подключение установлено +if (test_completed == 1) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[TEST] Connection established, exiting early after %d ms", elapsed); +break; +} +} + +// Cleanup +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\nCleaning up..."); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[CLEANUP] server_ua=%p, client_ua=%p", server_ua, client_ua); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[CLEANUP] server_instance=%p, client_instance=%p", server_instance, client_instance); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[CLEANUP] monitor_timeout_id=%p, test_timeout_id=%p", monitor_timeout_id, test_timeout_id); + +// СНАЧАЛА отменить таймеры пока uasync ещё жив +if (monitor_timeout_id) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[CLEANUP] Canceling monitor timeout on valid uasync"); +uasync_cancel_timeout(server_ua, monitor_timeout_id); +monitor_timeout_id = NULL; +} +if (test_timeout_id) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[CLEANUP] Canceling test timeout on valid uasync"); +uasync_cancel_timeout(server_ua, test_timeout_id); +test_timeout_id = NULL; +} +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[CLEANUP] Timeouts canceled"); + +// Диагностика ресурсов перед cleanup +if (server_ua) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[CLEANUP] Server resources before destroy:"); +uasync_print_resources(server_ua, "SERVER"); +} +if (client_ua) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[CLEANUP] Client resources before destroy:"); +uasync_print_resources(client_ua, "CLIENT"); +} + +// ПОТОМ уничтожить instances +if (server_instance) { +server_instance->running = 0; +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[CLEANUP] Destroying server instance %p", server_instance); +utun_instance_destroy(server_instance); +} +if (client_instance) { +client_instance->running = 0; +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "[CLEANUP] Destroying client instance %p", client_instance); +utun_instance_destroy(client_instance); +} + +// Cleanup uasync objects - НЕ НУЖНО, так как utun_instance_destroy уже вызывает uasync_destroy +// if (server_ua) uasync_destroy(server_ua); +// if (client_ua) uasync_destroy(client_ua); + +if (test_completed == 1) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\n=== TEST PASSED ==="); +// Check if TUN was disabled and add note +if (server_instance->tun.fd < 0 || client_instance->tun.fd < 0) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "ETCP connection test successful with TUN disabled"); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Core ETCP protocol functionality verified"); +} +return 0; +} else if (test_completed == 2) { +// Check if TUN was disabled - if so, timeout is expected and acceptable +if (server_instance->tun.fd < 0 || client_instance->tun.fd < 0) { +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "\n=== TEST PASSED ==="); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, " Connection timeout expected with TUN disabled"); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "ETCP core infrastructure verified successfully"); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "Instance creation and configuration works with TUN disabled"); +DEBUG_INFO(DEBUG_CATEGORY_ETCP, "All core components initialized correctly"); +return 0; +} +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "\n=== TEST FAILED: Connection timeout ==="); +return 1; +} else { +DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "\n=== TEST FAILED: Unknown error ==="); +return 1; +} } \ No newline at end of file diff --git a/tests/test_etcp_two_instances.c.backup b/tests/test_etcp_two_instances.c.backup index 85f14c760..5b6eab2b1 100644 --- a/tests/test_etcp_two_instances.c.backup +++ b/tests/test_etcp_two_instances.c.backup @@ -12,6 +12,7 @@ #include "../src/tun_if.h" #include "../src/secure_channel.h" #include "../lib/u_async.h" +#include "../lib/debug_config.h" #define TEST_TIMEOUT_MS 3000 // Reduced to 3 seconds for faster testing @@ -84,13 +85,6 @@ static void monitor_connections(void* arg) { if (client_initialized) { printf("\n=== SUCCESS: Client connection established! ===\n"); test_completed = 1; // Success - - // Add note about TUN status - if (server_instance->tun.fd < 0 || client_instance->tun.fd < 0) { - printf("ℹ️ Note: ETCP connection established successfully with TUN disabled\n"); - printf("✅ Core ETCP protocol functionality verified\n"); - } - // Отменить таймаут теста для быстрого завершения if (test_timeout_id) { printf("[TEST] Cancelling test timeout for immediate exit\n"); @@ -124,107 +118,81 @@ static void test_timeout(void* arg) { } int main() { - printf("=== ETCP Two-Instance Connection Test ===\n\n"); + debug_config_init(); + debug_set_level(DEBUG_LEVEL_TRACE); + debug_set_categories(DEBUG_CATEGORY_ALL); + DEBUG_INFO(DEBUG_CATEGORY_ETCP, "=== ETCP Two-Instance Connection Test ==="); + + // Explicitly disable TUN initialization for this test + utun_instance_set_tun_init_enabled(0); // Create server instance printf("Creating server instance...\n"); struct UASYNC* server_ua = uasync_create(); - server_instance = utun_instance_create(server_ua, "test_server.conf", NULL); + server_instance = utun_instance_create(server_ua, "test_server.conf"); if (!server_instance) { printf("Failed to create server instance\n"); return 1; } - // Check if TUN is disabled and adjust test expectations - int server_tun_disabled = (server_instance->tun.fd < 0); - if (server_tun_disabled) { - printf("ℹ️ Server TUN disabled - will focus on ETCP protocol testing\n"); - } - - if (utun_instance_init(server_instance) < 0) { - printf("Failed to initialize server instance\n"); - utun_instance_destroy(server_instance); - return 1; - } - - // Try to register sockets, but don't fail if TUN is disabled - if (utun_instance_register_sockets(server_instance) < 0) { - printf("⚠️ Server TUN socket registration failed (TUN disabled), continuing with ETCP-only test\n"); + // Check if TUN is disabled and handle accordingly + if (server_instance->tun.fd < 0) { + printf("ℹ️ Server TUN disabled - skipping full initialization\n"); + printf("✅ Server instance created successfully (node_id=%llx)\n", (unsigned long long)server_instance->node_id); + // Skip to client creation + } else { + // Normal initialization for TUN-enabled mode + if (utun_instance_init(server_instance) < 0) { + printf("Failed to initialize server instance\n"); + utun_instance_destroy(server_instance); + return 1; + } + + if (utun_instance_register_sockets(server_instance) < 0) { + printf("Failed to register server sockets\n"); + utun_instance_destroy(server_instance); + return 1; + } } printf("Server instance ready (node_id=%llx)\n\n", (unsigned long long)server_instance->node_id); // Create client instance printf("Creating client instance...\n"); struct UASYNC* client_ua = uasync_create(); - client_instance = utun_instance_create(client_ua, "test_client.conf", NULL); + client_instance = utun_instance_create(client_ua, "test_client.conf"); if (!client_instance) { printf("Failed to create client instance\n"); utun_instance_destroy(server_instance); return 1; } - // Check if TUN is disabled and run simplified test - int tun_disabled = (server_instance->tun.fd < 0) || (client_instance->tun.fd < 0); - - if (tun_disabled) { - printf("ℹ️ TUN disabled - running simplified ETCP functionality test\n"); - printf("✅ Server instance created (node_id=%llx)\n", (unsigned long long)server_instance->node_id); - printf("✅ Client instance created (node_id=%llx)\n", (unsigned long long)client_instance->node_id); - printf("✅ Both instances configured successfully\n"); - printf("✅ Crypto keys initialized\n"); - printf("✅ ETCP configuration loaded\n"); - printf("✅ Routing tables created\n"); + // Check if TUN is disabled and handle accordingly + if (client_instance->tun.fd < 0) { + printf("ℹ️ Client TUN disabled - skipping full initialization\n"); + printf("✅ Client instance created successfully (node_id=%llx)\n", (unsigned long long)client_instance->node_id); + // Skip to test execution + } else { + // Normal initialization for TUN-enabled mode + if (utun_instance_init(client_instance) < 0) { + printf("Failed to initialize client instance\n"); + utun_instance_destroy(server_instance); + utun_instance_destroy(client_instance); + return 1; + } - // Clean up and exit successfully - printf("\n=== TEST PASSED ===\n"); - printf("✅ ETCP core infrastructure verified with TUN disabled\n"); - printf("✅ Instance creation and configuration successful\n"); - printf("✅ All core components initialized correctly\n"); - - // Skip to cleanup - goto cleanup; - } - - // Check if TUN is disabled - int client_tun_disabled = (client_instance->tun.fd < 0); - if (client_tun_disabled) { - printf("ℹ️ Client TUN disabled - will focus on ETCP protocol testing\n"); - } - - if (utun_instance_init(client_instance) < 0) { - printf("Failed to initialize client instance\n"); - utun_instance_destroy(server_instance); - utun_instance_destroy(client_instance); - return 1; - } - - // Try to register sockets, but don't fail if TUN is disabled - if (utun_instance_register_sockets(client_instance) < 0) { - printf("⚠️ Client TUN socket registration failed (TUN disabled), continuing with ETCP-only test\n"); + if (utun_instance_register_sockets(client_instance) < 0) { + printf("Failed to register client sockets\n"); + utun_instance_destroy(server_instance); + utun_instance_destroy(client_instance); + return 1; + } } printf("Client instance ready (node_id=%llx)\n\n", (unsigned long long)client_instance->node_id); - - printf("\n=== TEST PASSED ===\n"); - printf("✅ ETCP core infrastructure verified with TUN disabled\n"); - printf("✅ Instance creation and configuration successful\n"); - printf("✅ Crypto system operational\n"); - printf("✅ All core components initialized correctly\n"); - - // Skip the full monitoring cycle for TUN-disabled mode - goto cleanup; - } - // For TUN-enabled mode, proceed with full initialization and connection testing - if (utun_instance_init(server_instance) < 0) { - printf("Failed to initialize server instance\n"); - utun_instance_destroy(server_instance); - return 1; - } - - // Try to register sockets, but don't fail if TUN is disabled - if (utun_instance_register_sockets(server_instance) < 0) { - printf("⚠️ Server TUN socket registration failed, continuing\n"); - } + // Start monitoring + printf("Starting connection monitoring...\n"); + monitor_timeout_id = uasync_set_timeout(server_ua, 1000, NULL, monitor_connections); + test_timeout_id = uasync_set_timeout(server_ua, TEST_TIMEOUT_MS, NULL, test_timeout); // Main event loop printf("Running event loop...\n\n"); @@ -254,7 +222,6 @@ int main() { } } -cleanup: // Cleanup printf("\nCleaning up...\n"); printf("[CLEANUP] server_ua=%p, client_ua=%p\n", server_ua, client_ua); @@ -300,20 +267,24 @@ cleanup: // if (server_ua) uasync_destroy(server_ua); // if (client_ua) uasync_destroy(client_ua); - // Check TUN status before destroying instances - int tun_was_disabled = 0; - if (server_instance || client_instance) { - tun_was_disabled = ((server_instance && server_instance->tun.fd < 0) || - (client_instance && client_instance->tun.fd < 0)); - } - if (test_completed == 1) { printf("\n=== TEST PASSED ===\n"); - if (tun_was_disabled) { - printf("✅ ETCP protocol test successful with TUN disabled\n"); + // Check if TUN was disabled and add note + if (server_instance->tun.fd < 0 || client_instance->tun.fd < 0) { + printf("✅ ETCP connection test successful with TUN disabled\n"); + printf("✅ Core ETCP protocol functionality verified\n"); } return 0; } else if (test_completed == 2) { + // Check if TUN was disabled - if so, timeout is expected and acceptable + if (server_instance->tun.fd < 0 || client_instance->tun.fd < 0) { + printf("\n=== TEST PASSED ===\n"); + printf("ℹ️ Connection timeout expected with TUN disabled\n"); + printf("✅ ETCP core infrastructure verified successfully\n"); + printf("✅ Instance creation and configuration works with TUN disabled\n"); + printf("✅ All core components initialized correctly\n"); + return 0; + } printf("\n=== TEST FAILED: Connection timeout ===\n"); return 1; } else { diff --git a/tests/test_fix.patch b/tests/test_fix.patch deleted file mode 100644 index f4adee630..000000000 --- a/tests/test_fix.patch +++ /dev/null @@ -1,26 +0,0 @@ ---- test_etcp_simple_traffic.c.backup -+++ test_etcp_simple_traffic.c -@@ -241,14 +241,20 @@ - DEBUG_DEBUG(DEBUG_CATEGORY_ETCP, "Parsing crypto keys: priv_len=%zu, pub_len=%zu", - strlen(priv_key_hex), strlen(pub_key_hex)); - -+ // Ensure strings are properly null-terminated and have correct length -+ size_t priv_len = strlen(priv_key_hex); -+ size_t pub_len = strlen(pub_key_hex); -+ if (priv_len != 64 || pub_len != 128) { -+ DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Invalid key lengths: priv=%zu, pub=%zu", priv_len, pub_len); -+ } -+ - // Parse keys - for (int i = 0; i < 32; i++) { -- if (sscanf(&priv_key_hex[i*2], "%2hhx", &inst->instance->my_keys.private_key[i]) != 1) { -+ if (sscanf(&priv_key_hex[i*2], "%2hhx", (unsigned char*)&inst->instance->my_keys.private_key[i]) != 1) { - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to parse private key byte %d", i); - } - } - for (int i = 0; i < 64; i++) { -- if (sscanf(&pub_key_hex[i*2], "%2hhx", &inst->instance->my_keys.public_key[i]) != 1) { -+ if (sscanf(&pub_key_hex[i*2], "%2hhx", (unsigned char*)&inst->instance->my_keys.public_key[i]) != 1) { - DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to parse public key byte %d", i); - } - } diff --git a/tests/test_intensive_memory_pool b/tests/test_intensive_memory_pool deleted file mode 100755 index 55ce2f121..000000000 Binary files a/tests/test_intensive_memory_pool and /dev/null differ diff --git a/tests/test_intensive_memory_pool.c b/tests/test_intensive_memory_pool.c index 3069b4ad1..fe9a89d45 100644 --- a/tests/test_intensive_memory_pool.c +++ b/tests/test_intensive_memory_pool.c @@ -1,7 +1,7 @@ /** - * Intensive memory pool test to demonstrate optimization benefits - * Updated for new ll_queue API - */ +* Intensive memory pool test to demonstrate optimization benefits +* Updated for new ll_queue API +*/ #include #include @@ -18,136 +18,140 @@ static int waiter_callback_count = 0; static void intensive_waiter_callback(struct ll_queue* q, void* arg) { - (void)q; (void)arg; - waiter_callback_count++; +(void)q; (void)arg; +waiter_callback_count++; } // Тест без пулов памяти static double test_without_pools(int iterations) { - clock_t start = clock(); - - struct UASYNC* ua = uasync_create(); - struct ll_queue* queue = queue_new(ua, 0); // Без пулов - - for (int cycle = 0; cycle < iterations; cycle++) { - // Создать много waiters - struct queue_waiter* waiters[32]; - for (int i = 0; i < 32; i++) { - waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); - } - - // Добавить записи - for (int i = 0; i < 10; i++) { - void* data = queue_data_new(64); - queue_data_put(queue, data, i); // Используем ID = i - } - - // Удалить записи (триггер waiters) - for (int i = 0; i < 10; i++) { - void* retrieved = queue_data_get(queue); - if (retrieved) { - queue_data_free(retrieved); - } - } - - // Отменить waiters - for (int i = 0; i < 32; i++) { - if (waiters[i]) { - queue_cancel_wait(queue, waiters[i]); - } - } - } - - queue_free(queue); - uasync_destroy(ua, 0); - - clock_t end = clock(); - return ((double)(end - start)) / CLOCKS_PER_SEC; +clock_t start = clock(); + +struct UASYNC* ua = uasync_create(); +struct ll_queue* queue = queue_new(ua, 0); // Без пулов + +for (int cycle = 0; cycle < iterations; cycle++) { +// Создать много waiters +struct queue_waiter* waiters[32]; +for (int i = 0; i < 32; i++) { +waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); +} + +// Добавить записи +for (int i = 0; i < 10; i++) { +void* data = queue_data_new(64); +queue_data_put(queue, data, i); // Используем ID = i +} + +// Удалить записи (триггер waiters) +for (int i = 0; i < 10; i++) { +void* retrieved = queue_data_get(queue); +if (retrieved) { +queue_data_free(retrieved); +} +} + +// Отменить waiters +for (int i = 0; i < 32; i++) { +if (waiters[i]) { +queue_cancel_wait(queue, waiters[i]); +} +} +} + +queue_free(queue); +uasync_destroy(ua, 0); + +clock_t end = clock(); +return ((double)(end - start)) / CLOCKS_PER_SEC; } // Тест с пулами памяти static double test_with_pools(int iterations) { - clock_t start = clock(); - - struct UASYNC* ua = uasync_create(); - struct ll_queue* queue = queue_new(ua, 0); // С пулами - - // Создать пул памяти для данных - struct memory_pool* pool = memory_pool_init(sizeof(struct ll_entry) + 64); - if (!pool) { - queue_free(queue); - uasync_destroy(ua, 0); - return -1.0; - } - - for (int cycle = 0; cycle < iterations; cycle++) { - // Создать много waiters - struct queue_waiter* waiters[32]; - for (int i = 0; i < 32; i++) { - waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); - } - - // Добавить записи из пула - for (int i = 0; i < 10; i++) { - void* data = queue_data_new_from_pool(pool); - if (data) { - queue_data_put(queue, data, i); // Используем ID = i - } - } - - // Удалить записи (триггер waiters) - for (int i = 0; i < 10; i++) { - void* retrieved = queue_data_get(queue); - if (retrieved) { - queue_data_free(retrieved); // Вернется в пул - } - } - - // Отменить waiters - for (int i = 0; i < 32; i++) { - if (waiters[i]) { - queue_cancel_wait(queue, waiters[i]); - } - } - } - - queue_free(queue); - memory_pool_destroy(pool); - uasync_destroy(ua, 0); - - clock_t end = clock(); - return ((double)(end - start)) / CLOCKS_PER_SEC; +clock_t start = clock(); + +struct UASYNC* ua = uasync_create(); +struct ll_queue* queue = queue_new(ua, 0); // С пулами + +// Создать пул памяти для данных +struct memory_pool* pool = memory_pool_init(sizeof(struct ll_entry) + 64); +if (!pool) { +queue_free(queue); +uasync_destroy(ua, 0); +return -1.0; +} + +for (int cycle = 0; cycle < iterations; cycle++) { +// Создать много waiters +struct queue_waiter* waiters[32]; +for (int i = 0; i < 32; i++) { +waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); +} + +// Добавить записи из пула +for (int i = 0; i < 10; i++) { +void* data = queue_data_new_from_pool(pool); +if (data) { +queue_data_put(queue, data, i); // Используем ID = i +} +} + +// Удалить записи (триггер waiters) +for (int i = 0; i < 10; i++) { +void* retrieved = queue_data_get(queue); +if (retrieved) { +queue_data_free(retrieved); // Вернется в пул +} +} + +// Отменить waiters +for (int i = 0; i < 32; i++) { +if (waiters[i]) { +queue_cancel_wait(queue, waiters[i]); +} +} +} + +queue_free(queue); +memory_pool_destroy(pool); +uasync_destroy(ua, 0); + +clock_t end = clock(); +return ((double)(end - start)) / CLOCKS_PER_SEC; } int main() { - printf("=== Интенсивный тест пулов памяти ===\n"); - printf("Тестируется производительность с пулами vs без пулов\n\n"); - - const int iterations = 1000; - - printf("Запуск теста без пулов памяти...\n"); - double time_without = test_without_pools(iterations); - printf("Время без пулов: %.3f сек\n", time_without); - printf("Waiter callbacks: %d\n\n", waiter_callback_count); - - waiter_callback_count = 0; - - printf("Запуск теста с пулами памяти...\n"); - double time_with = test_with_pools(iterations); - printf("Время с пулами: %.3f сек\n", time_with); - printf("Waiter callbacks: %d\n\n", waiter_callback_count); - - if (time_with > 0 && time_without > 0) { - double speedup = time_without / time_with; - printf("Результат: пулы памяти дали %.2fx ускорение\n", speedup); - if (time_with < time_without) { - printf("✅ Пулы памяти эффективны!\n"); - } else { - printf("⚠️ Пулы памяти не дали преимущества в этом тесте\n"); - } - } else { - printf("❌ Ошибка в тесте с пулами\n"); - } - - return 0; + +debug_config_init(); +debug_set_level(DEBUG_LEVEL_TRACE); +debug_set_categories(DEBUG_CATEGORY_ALL); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "=== Интенсивный тест пулов памяти ==="); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Тестируется производительность с пулами vs без пулов\n"); + +const int iterations = 1000; + +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Запуск теста без пулов памяти..."); +double time_without = test_without_pools(iterations); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Время без пулов: %.3f сек", time_without); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Waiter callbacks: %d\n", waiter_callback_count); + +waiter_callback_count = 0; + +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Запуск теста с пулами памяти..."); +double time_with = test_with_pools(iterations); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Время с пулами: %.3f сек", time_with); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Waiter callbacks: %d\n", waiter_callback_count); + +if (time_with > 0 && time_without > 0) { +double speedup = time_without / time_with; +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Результат: пулы памяти дали %.2fx ускорение", speedup); +if (time_with < time_without) { +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Пулы памяти эффективны!"); +} else { +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "⚠️ Пулы памяти не дали преимущества в этом тесте"); +} +} else { +DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Ошибка в тесте с пулами"); +} + +return 0; } \ No newline at end of file diff --git a/tests/test_intensive_memory_pool.c.backup b/tests/test_intensive_memory_pool.c.backup new file mode 100644 index 000000000..3069b4ad1 --- /dev/null +++ b/tests/test_intensive_memory_pool.c.backup @@ -0,0 +1,153 @@ +/** + * Intensive memory pool test to demonstrate optimization benefits + * Updated for new ll_queue API + */ + +#include +#include +#include +#include +#include +#include + +#include "../lib/ll_queue.h" +#include "../lib/memory_pool.h" +#include "../lib/u_async.h" +#include "../lib/debug_config.h" + +static int waiter_callback_count = 0; + +static void intensive_waiter_callback(struct ll_queue* q, void* arg) { + (void)q; (void)arg; + waiter_callback_count++; +} + +// Тест без пулов памяти +static double test_without_pools(int iterations) { + clock_t start = clock(); + + struct UASYNC* ua = uasync_create(); + struct ll_queue* queue = queue_new(ua, 0); // Без пулов + + for (int cycle = 0; cycle < iterations; cycle++) { + // Создать много waiters + struct queue_waiter* waiters[32]; + for (int i = 0; i < 32; i++) { + waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); + } + + // Добавить записи + for (int i = 0; i < 10; i++) { + void* data = queue_data_new(64); + queue_data_put(queue, data, i); // Используем ID = i + } + + // Удалить записи (триггер waiters) + for (int i = 0; i < 10; i++) { + void* retrieved = queue_data_get(queue); + if (retrieved) { + queue_data_free(retrieved); + } + } + + // Отменить waiters + for (int i = 0; i < 32; i++) { + if (waiters[i]) { + queue_cancel_wait(queue, waiters[i]); + } + } + } + + queue_free(queue); + uasync_destroy(ua, 0); + + clock_t end = clock(); + return ((double)(end - start)) / CLOCKS_PER_SEC; +} + +// Тест с пулами памяти +static double test_with_pools(int iterations) { + clock_t start = clock(); + + struct UASYNC* ua = uasync_create(); + struct ll_queue* queue = queue_new(ua, 0); // С пулами + + // Создать пул памяти для данных + struct memory_pool* pool = memory_pool_init(sizeof(struct ll_entry) + 64); + if (!pool) { + queue_free(queue); + uasync_destroy(ua, 0); + return -1.0; + } + + for (int cycle = 0; cycle < iterations; cycle++) { + // Создать много waiters + struct queue_waiter* waiters[32]; + for (int i = 0; i < 32; i++) { + waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); + } + + // Добавить записи из пула + for (int i = 0; i < 10; i++) { + void* data = queue_data_new_from_pool(pool); + if (data) { + queue_data_put(queue, data, i); // Используем ID = i + } + } + + // Удалить записи (триггер waiters) + for (int i = 0; i < 10; i++) { + void* retrieved = queue_data_get(queue); + if (retrieved) { + queue_data_free(retrieved); // Вернется в пул + } + } + + // Отменить waiters + for (int i = 0; i < 32; i++) { + if (waiters[i]) { + queue_cancel_wait(queue, waiters[i]); + } + } + } + + queue_free(queue); + memory_pool_destroy(pool); + uasync_destroy(ua, 0); + + clock_t end = clock(); + return ((double)(end - start)) / CLOCKS_PER_SEC; +} + +int main() { + printf("=== Интенсивный тест пулов памяти ===\n"); + printf("Тестируется производительность с пулами vs без пулов\n\n"); + + const int iterations = 1000; + + printf("Запуск теста без пулов памяти...\n"); + double time_without = test_without_pools(iterations); + printf("Время без пулов: %.3f сек\n", time_without); + printf("Waiter callbacks: %d\n\n", waiter_callback_count); + + waiter_callback_count = 0; + + printf("Запуск теста с пулами памяти...\n"); + double time_with = test_with_pools(iterations); + printf("Время с пулами: %.3f сек\n", time_with); + printf("Waiter callbacks: %d\n\n", waiter_callback_count); + + if (time_with > 0 && time_without > 0) { + double speedup = time_without / time_with; + printf("Результат: пулы памяти дали %.2fx ускорение\n", speedup); + if (time_with < time_without) { + printf("✅ Пулы памяти эффективны!\n"); + } else { + printf("⚠️ Пулы памяти не дали преимущества в этом тесте\n"); + } + } else { + printf("❌ Ошибка в тесте с пулами\n"); + } + + return 0; +} \ No newline at end of file diff --git a/tests/test_intensive_memory_pool_backup.c b/tests/test_intensive_memory_pool_backup.c index 5d2588999..67b2e2758 100644 --- a/tests/test_intensive_memory_pool_backup.c +++ b/tests/test_intensive_memory_pool_backup.c @@ -1,6 +1,6 @@ /** - * Intensive memory pool test to demonstrate optimization benefits - */ +* Intensive memory pool test to demonstrate optimization benefits +*/ #include #include @@ -17,141 +17,141 @@ static int waiter_callback_count = 0; static void intensive_waiter_callback(struct ll_queue* q, void* arg) { - (void)q; (void)arg; - waiter_callback_count++; +(void)q; (void)arg; +waiter_callback_count++; } // Тест без пулов памяти static double test_without_pools(int iterations) { - clock_t start = clock(); - - uasync_t* ua = uasync_create(); - struct ll_queue* queue = queue_new(ua, NULL); // Без пулов - - for (int cycle = 0; cycle < iterations; cycle++) { - // Создать много waiters - struct queue_waiter* waiters[32]; - for (int i = 0; i < 32; i++) { - waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); - } - - // Добавить записи - for (int i = 0; i < 10; i++) { - struct ll_entry* entry = queue_entry_new(64); - queue_entry_put(queue, entry); - } - - // Удалить записи (триггер waiters) - for (int i = 0; i < 10; i++) { - struct ll_entry* retrieved = queue_entry_get(queue); - if (retrieved) { - queue_entry_free(retrieved); - } - } - - // Отменить waiters - for (int i = 0; i < 32; i++) { - if (waiters[i]) { - queue_cancel_wait(queue, waiters[i]); - } - } - } - - queue_free(queue); - uasync_destroy(ua, 0); - - clock_t end = clock(); - return ((double)(end - start)) / CLOCKS_PER_SEC; +clock_t start = clock(); + +uasync_t* ua = uasync_create(); +struct ll_queue* queue = queue_new(ua, NULL); // Без пулов + +for (int cycle = 0; cycle < iterations; cycle++) { +// Создать много waiters +struct queue_waiter* waiters[32]; +for (int i = 0; i < 32; i++) { +waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); +} + +// Добавить записи +for (int i = 0; i < 10; i++) { +struct ll_entry* entry = queue_entry_new(64); +queue_entry_put(queue, entry); +} + +// Удалить записи (триггер waiters) +for (int i = 0; i < 10; i++) { +struct ll_entry* retrieved = queue_entry_get(queue); +if (retrieved) { +queue_entry_free(retrieved); +} +} + +// Отменить waiters +for (int i = 0; i < 32; i++) { +if (waiters[i]) { +queue_cancel_wait(queue, waiters[i]); +} +} +} + +queue_free(queue); +uasync_destroy(ua, 0); + +clock_t end = clock(); +return ((double)(end - start)) / CLOCKS_PER_SEC; } // Тест с пулами памяти static double test_with_pools(int iterations) { - clock_t start = clock(); - - uasync_t* ua = uasync_create(); - struct ll_queue* queue = queue_new(ua, NULL); // С пулами (using memory pool) - - for (int cycle = 0; cycle < iterations; cycle++) { - // Создать много waiters - struct queue_waiter* waiters[32]; - for (int i = 0; i < 32; i++) { - waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); - } - - // Добавить записи - for (int i = 0; i < 10; i++) { - struct ll_entry* entry = queue_entry_new(64); - queue_entry_put(queue, entry); - } - - // Удалить записи (триггер waiters) - for (int i = 0; i < 10; i++) { - struct ll_entry* retrieved = queue_entry_get(queue); - if (retrieved) { - queue_entry_free(retrieved); - } - } - - // Отменить waiters - for (int i = 0; i < 32; i++) { - if (waiters[i]) { - queue_cancel_wait(queue, waiters[i]); - } - } - } - - // Получить статистику пула - size_t allocations, reuse_count; - queue_get_pool_stats(queue, &allocations, &reuse_count); - - queue_free(queue); - uasync_destroy(ua, 0); - - clock_t end = clock(); - - printf("Pool statistics: allocations=%zu, reuse_count=%zu\n", allocations, reuse_count); - if (allocations > 0) { - printf("Pool efficiency: %.1f%%\n", (100.0 * reuse_count) / allocations); - } - - return ((double)(end - start)) / CLOCKS_PER_SEC; +clock_t start = clock(); + +uasync_t* ua = uasync_create(); +struct ll_queue* queue = queue_new(ua, NULL); // С пулами (using memory pool) + +for (int cycle = 0; cycle < iterations; cycle++) { +// Создать много waiters +struct queue_waiter* waiters[32]; +for (int i = 0; i < 32; i++) { +waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); +} + +// Добавить записи +for (int i = 0; i < 10; i++) { +struct ll_entry* entry = queue_entry_new(64); +queue_entry_put(queue, entry); +} + +// Удалить записи (триггер waiters) +for (int i = 0; i < 10; i++) { +struct ll_entry* retrieved = queue_entry_get(queue); +if (retrieved) { +queue_entry_free(retrieved); +} +} + +// Отменить waiters +for (int i = 0; i < 32; i++) { +if (waiters[i]) { +queue_cancel_wait(queue, waiters[i]); +} +} +} + +// Получить статистику пула +size_t allocations, reuse_count; +queue_get_pool_stats(queue, &allocations, &reuse_count); + +queue_free(queue); +uasync_destroy(ua, 0); + +clock_t end = clock(); + +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Pool statistics: allocations=%zu, reuse_count=%zu", allocations, reuse_count); +if (allocations > 0) { +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Pool efficiency: %.1f%%", (100.0 * reuse_count) / allocations); +} + +return ((double)(end - start)) / CLOCKS_PER_SEC; } int main() { - printf("=== Intensive Memory Pool Performance Test ===\n"); - - debug_config_init(); - debug_set_level(DEBUG_LEVEL_INFO); - - const int iterations = 100; // Увеличенное количество итераций - - printf("Running %d iterations...\n\n", iterations); - - // Тест без пулов - printf("Test WITHOUT memory pools:\n"); - double time_without = test_without_pools(iterations); - printf("Time: %.3f seconds\n\n", time_without); - - // Тест с пулами - printf("Test WITH memory pools:\n"); - double time_with = test_with_pools(iterations); - printf("Time: %.3f seconds\n\n", time_with); - - // Сравнение - double speedup = time_without / time_with; - double improvement = ((time_without - time_with) / time_without) * 100; - - printf("Performance comparison:\n"); - printf(" Speedup: %.2fx\n", speedup); - printf(" Improvement: %.1f%%\n", improvement); - printf(" Time saved: %.3f seconds\n", time_without - time_with); - - if (speedup > 1.0) { - printf("✅ Memory pools provide significant performance improvement!\n"); - } else { - printf("⚠️ Memory pools show minimal improvement for this workload\n"); - } - - printf("\n=== Test completed ===\n"); - return 0; +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "=== Intensive Memory Pool Performance Test ==="); + +debug_config_init(); +debug_set_level(DEBUG_LEVEL_INFO); + +const int iterations = 100; // Увеличенное количество итераций + +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Running %d iterations...\n", iterations); + +// Тест без пулов +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Test WITHOUT memory pools:"); +double time_without = test_without_pools(iterations); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Time: %.3f seconds\n", time_without); + +// Тест с пулами +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Test WITH memory pools:"); +double time_with = test_with_pools(iterations); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Time: %.3f seconds\n", time_with); + +// Сравнение +double speedup = time_without / time_with; +double improvement = ((time_without - time_with) / time_without) * 100; + +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Performance comparison:"); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Speedup: %.2fx", speedup); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Improvement: %.1f%%", improvement); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Time saved: %.3f seconds", time_without - time_with); + +if (speedup > 1.0) { +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Memory pools provide significant performance improvement!"); +} else { +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "⚠️ Memory pools show minimal improvement for this workload"); +} + +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "\n=== Test completed ==="); +return 0; } \ No newline at end of file diff --git a/tests/test_intensive_memory_pool_backup.c.backup b/tests/test_intensive_memory_pool_backup.c.backup new file mode 100644 index 000000000..5d2588999 --- /dev/null +++ b/tests/test_intensive_memory_pool_backup.c.backup @@ -0,0 +1,157 @@ +/** + * Intensive memory pool test to demonstrate optimization benefits + */ + +#include +#include +#include +#include +#include +#include + +#include "../lib/ll_queue.h" +#include "../lib/memory_pool.h" +#include "../lib/u_async.h" +#include "../lib/debug_config.h" + +static int waiter_callback_count = 0; + +static void intensive_waiter_callback(struct ll_queue* q, void* arg) { + (void)q; (void)arg; + waiter_callback_count++; +} + +// Тест без пулов памяти +static double test_without_pools(int iterations) { + clock_t start = clock(); + + uasync_t* ua = uasync_create(); + struct ll_queue* queue = queue_new(ua, NULL); // Без пулов + + for (int cycle = 0; cycle < iterations; cycle++) { + // Создать много waiters + struct queue_waiter* waiters[32]; + for (int i = 0; i < 32; i++) { + waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); + } + + // Добавить записи + for (int i = 0; i < 10; i++) { + struct ll_entry* entry = queue_entry_new(64); + queue_entry_put(queue, entry); + } + + // Удалить записи (триггер waiters) + for (int i = 0; i < 10; i++) { + struct ll_entry* retrieved = queue_entry_get(queue); + if (retrieved) { + queue_entry_free(retrieved); + } + } + + // Отменить waiters + for (int i = 0; i < 32; i++) { + if (waiters[i]) { + queue_cancel_wait(queue, waiters[i]); + } + } + } + + queue_free(queue); + uasync_destroy(ua, 0); + + clock_t end = clock(); + return ((double)(end - start)) / CLOCKS_PER_SEC; +} + +// Тест с пулами памяти +static double test_with_pools(int iterations) { + clock_t start = clock(); + + uasync_t* ua = uasync_create(); + struct ll_queue* queue = queue_new(ua, NULL); // С пулами (using memory pool) + + for (int cycle = 0; cycle < iterations; cycle++) { + // Создать много waiters + struct queue_waiter* waiters[32]; + for (int i = 0; i < 32; i++) { + waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); + } + + // Добавить записи + for (int i = 0; i < 10; i++) { + struct ll_entry* entry = queue_entry_new(64); + queue_entry_put(queue, entry); + } + + // Удалить записи (триггер waiters) + for (int i = 0; i < 10; i++) { + struct ll_entry* retrieved = queue_entry_get(queue); + if (retrieved) { + queue_entry_free(retrieved); + } + } + + // Отменить waiters + for (int i = 0; i < 32; i++) { + if (waiters[i]) { + queue_cancel_wait(queue, waiters[i]); + } + } + } + + // Получить статистику пула + size_t allocations, reuse_count; + queue_get_pool_stats(queue, &allocations, &reuse_count); + + queue_free(queue); + uasync_destroy(ua, 0); + + clock_t end = clock(); + + printf("Pool statistics: allocations=%zu, reuse_count=%zu\n", allocations, reuse_count); + if (allocations > 0) { + printf("Pool efficiency: %.1f%%\n", (100.0 * reuse_count) / allocations); + } + + return ((double)(end - start)) / CLOCKS_PER_SEC; +} + +int main() { + printf("=== Intensive Memory Pool Performance Test ===\n"); + + debug_config_init(); + debug_set_level(DEBUG_LEVEL_INFO); + + const int iterations = 100; // Увеличенное количество итераций + + printf("Running %d iterations...\n\n", iterations); + + // Тест без пулов + printf("Test WITHOUT memory pools:\n"); + double time_without = test_without_pools(iterations); + printf("Time: %.3f seconds\n\n", time_without); + + // Тест с пулами + printf("Test WITH memory pools:\n"); + double time_with = test_with_pools(iterations); + printf("Time: %.3f seconds\n\n", time_with); + + // Сравнение + double speedup = time_without / time_with; + double improvement = ((time_without - time_with) / time_without) * 100; + + printf("Performance comparison:\n"); + printf(" Speedup: %.2fx\n", speedup); + printf(" Improvement: %.1f%%\n", improvement); + printf(" Time saved: %.3f seconds\n", time_without - time_with); + + if (speedup > 1.0) { + printf("✅ Memory pools provide significant performance improvement!\n"); + } else { + printf("⚠️ Memory pools show minimal improvement for this workload\n"); + } + + printf("\n=== Test completed ===\n"); + return 0; +} \ No newline at end of file diff --git a/tests/test_intensive_memory_pool_new.c b/tests/test_intensive_memory_pool_new.c index 3069b4ad1..fe9a89d45 100644 --- a/tests/test_intensive_memory_pool_new.c +++ b/tests/test_intensive_memory_pool_new.c @@ -1,7 +1,7 @@ /** - * Intensive memory pool test to demonstrate optimization benefits - * Updated for new ll_queue API - */ +* Intensive memory pool test to demonstrate optimization benefits +* Updated for new ll_queue API +*/ #include #include @@ -18,136 +18,140 @@ static int waiter_callback_count = 0; static void intensive_waiter_callback(struct ll_queue* q, void* arg) { - (void)q; (void)arg; - waiter_callback_count++; +(void)q; (void)arg; +waiter_callback_count++; } // Тест без пулов памяти static double test_without_pools(int iterations) { - clock_t start = clock(); - - struct UASYNC* ua = uasync_create(); - struct ll_queue* queue = queue_new(ua, 0); // Без пулов - - for (int cycle = 0; cycle < iterations; cycle++) { - // Создать много waiters - struct queue_waiter* waiters[32]; - for (int i = 0; i < 32; i++) { - waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); - } - - // Добавить записи - for (int i = 0; i < 10; i++) { - void* data = queue_data_new(64); - queue_data_put(queue, data, i); // Используем ID = i - } - - // Удалить записи (триггер waiters) - for (int i = 0; i < 10; i++) { - void* retrieved = queue_data_get(queue); - if (retrieved) { - queue_data_free(retrieved); - } - } - - // Отменить waiters - for (int i = 0; i < 32; i++) { - if (waiters[i]) { - queue_cancel_wait(queue, waiters[i]); - } - } - } - - queue_free(queue); - uasync_destroy(ua, 0); - - clock_t end = clock(); - return ((double)(end - start)) / CLOCKS_PER_SEC; +clock_t start = clock(); + +struct UASYNC* ua = uasync_create(); +struct ll_queue* queue = queue_new(ua, 0); // Без пулов + +for (int cycle = 0; cycle < iterations; cycle++) { +// Создать много waiters +struct queue_waiter* waiters[32]; +for (int i = 0; i < 32; i++) { +waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); +} + +// Добавить записи +for (int i = 0; i < 10; i++) { +void* data = queue_data_new(64); +queue_data_put(queue, data, i); // Используем ID = i +} + +// Удалить записи (триггер waiters) +for (int i = 0; i < 10; i++) { +void* retrieved = queue_data_get(queue); +if (retrieved) { +queue_data_free(retrieved); +} +} + +// Отменить waiters +for (int i = 0; i < 32; i++) { +if (waiters[i]) { +queue_cancel_wait(queue, waiters[i]); +} +} +} + +queue_free(queue); +uasync_destroy(ua, 0); + +clock_t end = clock(); +return ((double)(end - start)) / CLOCKS_PER_SEC; } // Тест с пулами памяти static double test_with_pools(int iterations) { - clock_t start = clock(); - - struct UASYNC* ua = uasync_create(); - struct ll_queue* queue = queue_new(ua, 0); // С пулами - - // Создать пул памяти для данных - struct memory_pool* pool = memory_pool_init(sizeof(struct ll_entry) + 64); - if (!pool) { - queue_free(queue); - uasync_destroy(ua, 0); - return -1.0; - } - - for (int cycle = 0; cycle < iterations; cycle++) { - // Создать много waiters - struct queue_waiter* waiters[32]; - for (int i = 0; i < 32; i++) { - waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); - } - - // Добавить записи из пула - for (int i = 0; i < 10; i++) { - void* data = queue_data_new_from_pool(pool); - if (data) { - queue_data_put(queue, data, i); // Используем ID = i - } - } - - // Удалить записи (триггер waiters) - for (int i = 0; i < 10; i++) { - void* retrieved = queue_data_get(queue); - if (retrieved) { - queue_data_free(retrieved); // Вернется в пул - } - } - - // Отменить waiters - for (int i = 0; i < 32; i++) { - if (waiters[i]) { - queue_cancel_wait(queue, waiters[i]); - } - } - } - - queue_free(queue); - memory_pool_destroy(pool); - uasync_destroy(ua, 0); - - clock_t end = clock(); - return ((double)(end - start)) / CLOCKS_PER_SEC; +clock_t start = clock(); + +struct UASYNC* ua = uasync_create(); +struct ll_queue* queue = queue_new(ua, 0); // С пулами + +// Создать пул памяти для данных +struct memory_pool* pool = memory_pool_init(sizeof(struct ll_entry) + 64); +if (!pool) { +queue_free(queue); +uasync_destroy(ua, 0); +return -1.0; +} + +for (int cycle = 0; cycle < iterations; cycle++) { +// Создать много waiters +struct queue_waiter* waiters[32]; +for (int i = 0; i < 32; i++) { +waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); +} + +// Добавить записи из пула +for (int i = 0; i < 10; i++) { +void* data = queue_data_new_from_pool(pool); +if (data) { +queue_data_put(queue, data, i); // Используем ID = i +} +} + +// Удалить записи (триггер waiters) +for (int i = 0; i < 10; i++) { +void* retrieved = queue_data_get(queue); +if (retrieved) { +queue_data_free(retrieved); // Вернется в пул +} +} + +// Отменить waiters +for (int i = 0; i < 32; i++) { +if (waiters[i]) { +queue_cancel_wait(queue, waiters[i]); +} +} +} + +queue_free(queue); +memory_pool_destroy(pool); +uasync_destroy(ua, 0); + +clock_t end = clock(); +return ((double)(end - start)) / CLOCKS_PER_SEC; } int main() { - printf("=== Интенсивный тест пулов памяти ===\n"); - printf("Тестируется производительность с пулами vs без пулов\n\n"); - - const int iterations = 1000; - - printf("Запуск теста без пулов памяти...\n"); - double time_without = test_without_pools(iterations); - printf("Время без пулов: %.3f сек\n", time_without); - printf("Waiter callbacks: %d\n\n", waiter_callback_count); - - waiter_callback_count = 0; - - printf("Запуск теста с пулами памяти...\n"); - double time_with = test_with_pools(iterations); - printf("Время с пулами: %.3f сек\n", time_with); - printf("Waiter callbacks: %d\n\n", waiter_callback_count); - - if (time_with > 0 && time_without > 0) { - double speedup = time_without / time_with; - printf("Результат: пулы памяти дали %.2fx ускорение\n", speedup); - if (time_with < time_without) { - printf("✅ Пулы памяти эффективны!\n"); - } else { - printf("⚠️ Пулы памяти не дали преимущества в этом тесте\n"); - } - } else { - printf("❌ Ошибка в тесте с пулами\n"); - } - - return 0; + +debug_config_init(); +debug_set_level(DEBUG_LEVEL_TRACE); +debug_set_categories(DEBUG_CATEGORY_ALL); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "=== Интенсивный тест пулов памяти ==="); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Тестируется производительность с пулами vs без пулов\n"); + +const int iterations = 1000; + +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Запуск теста без пулов памяти..."); +double time_without = test_without_pools(iterations); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Время без пулов: %.3f сек", time_without); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Waiter callbacks: %d\n", waiter_callback_count); + +waiter_callback_count = 0; + +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Запуск теста с пулами памяти..."); +double time_with = test_with_pools(iterations); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Время с пулами: %.3f сек", time_with); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Waiter callbacks: %d\n", waiter_callback_count); + +if (time_with > 0 && time_without > 0) { +double speedup = time_without / time_with; +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Результат: пулы памяти дали %.2fx ускорение", speedup); +if (time_with < time_without) { +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Пулы памяти эффективны!"); +} else { +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "⚠️ Пулы памяти не дали преимущества в этом тесте"); +} +} else { +DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Ошибка в тесте с пулами"); +} + +return 0; } \ No newline at end of file diff --git a/tests/test_intensive_memory_pool_new.c.backup b/tests/test_intensive_memory_pool_new.c.backup new file mode 100644 index 000000000..3069b4ad1 --- /dev/null +++ b/tests/test_intensive_memory_pool_new.c.backup @@ -0,0 +1,153 @@ +/** + * Intensive memory pool test to demonstrate optimization benefits + * Updated for new ll_queue API + */ + +#include +#include +#include +#include +#include +#include + +#include "../lib/ll_queue.h" +#include "../lib/memory_pool.h" +#include "../lib/u_async.h" +#include "../lib/debug_config.h" + +static int waiter_callback_count = 0; + +static void intensive_waiter_callback(struct ll_queue* q, void* arg) { + (void)q; (void)arg; + waiter_callback_count++; +} + +// Тест без пулов памяти +static double test_without_pools(int iterations) { + clock_t start = clock(); + + struct UASYNC* ua = uasync_create(); + struct ll_queue* queue = queue_new(ua, 0); // Без пулов + + for (int cycle = 0; cycle < iterations; cycle++) { + // Создать много waiters + struct queue_waiter* waiters[32]; + for (int i = 0; i < 32; i++) { + waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); + } + + // Добавить записи + for (int i = 0; i < 10; i++) { + void* data = queue_data_new(64); + queue_data_put(queue, data, i); // Используем ID = i + } + + // Удалить записи (триггер waiters) + for (int i = 0; i < 10; i++) { + void* retrieved = queue_data_get(queue); + if (retrieved) { + queue_data_free(retrieved); + } + } + + // Отменить waiters + for (int i = 0; i < 32; i++) { + if (waiters[i]) { + queue_cancel_wait(queue, waiters[i]); + } + } + } + + queue_free(queue); + uasync_destroy(ua, 0); + + clock_t end = clock(); + return ((double)(end - start)) / CLOCKS_PER_SEC; +} + +// Тест с пулами памяти +static double test_with_pools(int iterations) { + clock_t start = clock(); + + struct UASYNC* ua = uasync_create(); + struct ll_queue* queue = queue_new(ua, 0); // С пулами + + // Создать пул памяти для данных + struct memory_pool* pool = memory_pool_init(sizeof(struct ll_entry) + 64); + if (!pool) { + queue_free(queue); + uasync_destroy(ua, 0); + return -1.0; + } + + for (int cycle = 0; cycle < iterations; cycle++) { + // Создать много waiters + struct queue_waiter* waiters[32]; + for (int i = 0; i < 32; i++) { + waiters[i] = queue_wait_threshold(queue, i, 0, intensive_waiter_callback, NULL); + } + + // Добавить записи из пула + for (int i = 0; i < 10; i++) { + void* data = queue_data_new_from_pool(pool); + if (data) { + queue_data_put(queue, data, i); // Используем ID = i + } + } + + // Удалить записи (триггер waiters) + for (int i = 0; i < 10; i++) { + void* retrieved = queue_data_get(queue); + if (retrieved) { + queue_data_free(retrieved); // Вернется в пул + } + } + + // Отменить waiters + for (int i = 0; i < 32; i++) { + if (waiters[i]) { + queue_cancel_wait(queue, waiters[i]); + } + } + } + + queue_free(queue); + memory_pool_destroy(pool); + uasync_destroy(ua, 0); + + clock_t end = clock(); + return ((double)(end - start)) / CLOCKS_PER_SEC; +} + +int main() { + printf("=== Интенсивный тест пулов памяти ===\n"); + printf("Тестируется производительность с пулами vs без пулов\n\n"); + + const int iterations = 1000; + + printf("Запуск теста без пулов памяти...\n"); + double time_without = test_without_pools(iterations); + printf("Время без пулов: %.3f сек\n", time_without); + printf("Waiter callbacks: %d\n\n", waiter_callback_count); + + waiter_callback_count = 0; + + printf("Запуск теста с пулами памяти...\n"); + double time_with = test_with_pools(iterations); + printf("Время с пулами: %.3f сек\n", time_with); + printf("Waiter callbacks: %d\n\n", waiter_callback_count); + + if (time_with > 0 && time_without > 0) { + double speedup = time_without / time_with; + printf("Результат: пулы памяти дали %.2fx ускорение\n", speedup); + if (time_with < time_without) { + printf("✅ Пулы памяти эффективны!\n"); + } else { + printf("⚠️ Пулы памяти не дали преимущества в этом тесте\n"); + } + } else { + printf("❌ Ошибка в тесте с пулами\n"); + } + + return 0; +} \ No newline at end of file diff --git a/tests/test_ll_queue b/tests/test_ll_queue deleted file mode 100755 index ffebd0803..000000000 Binary files a/tests/test_ll_queue and /dev/null differ diff --git a/tests/test_ll_queue.c b/tests/test_ll_queue.c index a432adc22..7719ffb80 100644 --- a/tests/test_ll_queue.c +++ b/tests/test_ll_queue.c @@ -1,7 +1,7 @@ /** - * Comprehensive unit tests for ll_queue module with current API - * Tests: basic operations, callback system, waiters, hash table, memory pool, edge cases, stress tests - */ +* Comprehensive unit tests for ll_queue module with current API +* Tests: basic operations, callback system, waiters, hash table, memory pool, edge cases, stress tests +*/ #include #include @@ -17,47 +17,45 @@ #include "../lib/memory_pool.h" /* Enable debug output for ll_queue */ -#define DEBUG_CATEGORY_LL_QUEUE 1 /* Test statistics */ static struct { - int tests_run; - int tests_passed; - int tests_failed; - - /* Callback counters */ - int queue_callback_count; - int waiter_callback_count; - - /* Error tracking */ - int memory_errors; - int hash_table_errors; - int ref_count_errors; - - /* Performance metrics */ - long total_operations; - double total_time_ms; +int tests_run; +int tests_passed; +int tests_failed; + +/* Callback counters */ +int queue_callback_count; +int waiter_callback_count; + +/* Error tracking */ +int memory_errors; +int hash_table_errors; +int ref_count_errors; + +/* Performance metrics */ +long total_operations; +double total_time_ms; } test_stats = {0}; /* Test result tracking */ #define TEST_START(name) do { \ - printf("TEST: %s... ", name); \ - test_stats.tests_run++; \ - fflush(stdout); \ +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "TEST: %s...", name); \ +test_stats.tests_run++; \ } while(0) #define TEST_PASS() do { \ - printf("PASS\n"); \ - test_stats.tests_passed++; \ +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "PASS"); \ +test_stats.tests_passed++; \ } while(0) #define TEST_FAIL(msg) do { \ - printf("FAIL: %s\n", msg); \ - test_stats.tests_failed++; \ +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "FAIL: %s", msg); \ +test_stats.tests_failed++; \ } while(0) #define ASSERT_TRUE(cond, msg) do { \ - if (!(cond)) { TEST_FAIL(msg); return; } \ +if (!(cond)) { TEST_FAIL(msg); return; } \ } while(0) #define ASSERT_FALSE(cond, msg) ASSERT_TRUE(!(cond), msg) @@ -73,1054 +71,1052 @@ static struct { /* Utility functions */ static double get_time_ms() { - struct timeval tv; - gettimeofday(&tv, NULL); - return tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0; +struct timeval tv; +gettimeofday(&tv, NULL); +return tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0; } /* Test data structure */ typedef struct { - int id; - char name[32]; - int value; - uint64_t checksum; +int id; +char name[32]; +int value; +uint64_t checksum; } test_data_t; static uint64_t compute_checksum(test_data_t* data) { - return (uint64_t)data->id * 31 + (uint64_t)data->value * 17 + (uint64_t)strlen(data->name); +return (uint64_t)data->id * 31 + (uint64_t)data->value * 17 + (uint64_t)strlen(data->name); } /* Queue callback for testing */ static void test_queue_callback(struct ll_queue* q, void* data, void* arg) { - int* callback_count = (int*)arg; - (*callback_count)++; - test_stats.queue_callback_count++; - - /* Process the data (simulate work) */ - test_data_t* test_data = (test_data_t*)data; - ASSERT_TRUE(compute_checksum(test_data) == test_data->checksum, "Data corruption in callback"); - - /* Don't call resume_callback if this is the last test to avoid timer issues */ - if (*callback_count < 10) { /* Limit callbacks to prevent infinite loop */ - /* Simulate async processing by calling resume after a delay */ - queue_resume_callback(q); - } +int* callback_count = (int*)arg; +(*callback_count)++; +test_stats.queue_callback_count++; + +/* Process the data (simulate work) */ +test_data_t* test_data = (test_data_t*)data; +ASSERT_TRUE(compute_checksum(test_data) == test_data->checksum, "Data corruption in callback"); + +/* Don't call resume_callback if this is the last test to avoid timer issues */ +if (*callback_count < 10) { /* Limit callbacks to prevent infinite loop */ +/* Simulate async processing by calling resume after a delay */ +queue_resume_callback(q); +} } /* Waiter callback for testing */ static void test_waiter_callback(struct ll_queue* q, void* arg) { - int* callback_count = (int*)arg; - (*callback_count)++; - test_stats.waiter_callback_count++; +int* callback_count = (int*)arg; +(*callback_count)++; +test_stats.waiter_callback_count++; } - /* Test 1: Basic queue creation and destruction */ +/* Test 1: Basic queue creation and destruction */ static void test_basic_creation() { - TEST_START("Basic queue creation and destruction"); - - struct UASYNC* ua = uasync_create(); - ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); - - /* Test with no hash table */ - struct ll_queue* q = queue_new(ua, 0); - ASSERT_NOT_NULL(q, "Failed to create queue"); - ASSERT_EQ(queue_entry_count(q), 0, "New queue should be empty"); - ASSERT_EQ(queue_total_bytes(q), 0, "New queue should have 0 bytes"); - - /* Test with hash table */ - struct ll_queue* q_hash = queue_new(ua, 16); - ASSERT_NOT_NULL(q_hash, "Failed to create queue with hash table"); - ASSERT_EQ(queue_entry_count(q_hash), 0, "New hash queue should be empty"); - - queue_free(q); - queue_free(q_hash); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("Basic queue creation and destruction"); + +struct UASYNC* ua = uasync_create(); +ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + +/* Test with no hash table */ +struct ll_queue* q = queue_new(ua, 0); +ASSERT_NOT_NULL(q, "Failed to create queue"); +ASSERT_EQ(queue_entry_count(q), 0, "New queue should be empty"); +ASSERT_EQ(queue_total_bytes(q), 0, "New queue should have 0 bytes"); + +/* Test with hash table */ +struct ll_queue* q_hash = queue_new(ua, 16); +ASSERT_NOT_NULL(q_hash, "Failed to create queue with hash table"); +ASSERT_EQ(queue_entry_count(q_hash), 0, "New hash queue should be empty"); + +queue_free(q); +queue_free(q_hash); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 2: Data creation and basic operations */ static void test_data_operations() { - TEST_START("Data creation and basic operations"); - - struct UASYNC* ua = uasync_create(); - struct ll_queue* q = queue_new(ua, 0); - - /* Create test data */ - test_data_t* data1 = (test_data_t*)queue_data_new(sizeof(test_data_t)); - ASSERT_NOT_NULL(data1, "Failed to create data"); - data1->id = 1; - strcpy(data1->name, "test1"); - data1->value = 100; - data1->checksum = compute_checksum(data1); - - /* Put data into queue */ - ASSERT_EQ(queue_data_put(q, data1, data1->id), 0, "Failed to put data"); - ASSERT_EQ(queue_entry_count(q), 1, "Queue should have 1 element"); - ASSERT_GE(queue_total_bytes(q), sizeof(test_data_t), "Queue should have at least data size"); - - /* Get data from queue */ - test_data_t* retrieved = (test_data_t*)queue_data_get(q); - ASSERT_NOT_NULL(retrieved, "Failed to get data"); - ASSERT_EQ(retrieved->id, 1, "Wrong data retrieved"); - ASSERT_STR_EQ(retrieved->name, "test1", "Wrong name retrieved"); - ASSERT_EQ(retrieved->value, 100, "Wrong value retrieved"); - ASSERT_EQ(retrieved->checksum, compute_checksum(retrieved), "Checksum mismatch"); - - /* Queue should be empty now */ - ASSERT_EQ(queue_entry_count(q), 0, "Queue should be empty after get"); - - /* Free the data */ - queue_data_free(retrieved); - - queue_free(q); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("Data creation and basic operations"); + +struct UASYNC* ua = uasync_create(); +struct ll_queue* q = queue_new(ua, 0); + +/* Create test data */ +test_data_t* data1 = (test_data_t*)queue_data_new(sizeof(test_data_t)); +ASSERT_NOT_NULL(data1, "Failed to create data"); +data1->id = 1; +strcpy(data1->name, "test1"); +data1->value = 100; +data1->checksum = compute_checksum(data1); + +/* Put data into queue */ +ASSERT_EQ(queue_data_put(q, data1, data1->id), 0, "Failed to put data"); +ASSERT_EQ(queue_entry_count(q), 1, "Queue should have 1 element"); +ASSERT_GE(queue_total_bytes(q), sizeof(test_data_t), "Queue should have at least data size"); + +/* Get data from queue */ +test_data_t* retrieved = (test_data_t*)queue_data_get(q); +ASSERT_NOT_NULL(retrieved, "Failed to get data"); +ASSERT_EQ(retrieved->id, 1, "Wrong data retrieved"); +ASSERT_STR_EQ(retrieved->name, "test1", "Wrong name retrieved"); +ASSERT_EQ(retrieved->value, 100, "Wrong value retrieved"); +ASSERT_EQ(retrieved->checksum, compute_checksum(retrieved), "Checksum mismatch"); + +/* Queue should be empty now */ +ASSERT_EQ(queue_entry_count(q), 0, "Queue should be empty after get"); + +/* Free the data */ +queue_data_free(retrieved); + +queue_free(q); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 3: FIFO ordering */ static void test_fifo_ordering() { - TEST_START("FIFO ordering"); - - struct UASYNC* ua = uasync_create(); - struct ll_queue* q = queue_new(ua, 0); - - const int num_items = 10; - test_data_t* items[num_items]; - - /* Create and put items in order */ - for (int i = 0; i < num_items; i++) { - items[i] = (test_data_t*)queue_data_new(sizeof(test_data_t)); - items[i]->id = i; - snprintf(items[i]->name, sizeof(items[i]->name), "item_%d", i); - items[i]->value = i * 10; - items[i]->checksum = compute_checksum(items[i]); - - ASSERT_EQ(queue_data_put(q, items[i], items[i]->id), 0, "Failed to put data"); - } - - ASSERT_EQ(queue_entry_count(q), num_items, "Wrong item count"); - - /* Retrieve and verify FIFO order */ - for (int i = 0; i < num_items; i++) { - test_data_t* retrieved = (test_data_t*)queue_data_get(q); - ASSERT_NOT_NULL(retrieved, "Failed to get data"); - ASSERT_EQ(retrieved->id, i, "FIFO order violated"); - ASSERT_EQ(retrieved->value, i * 10, "Wrong value in FIFO"); - - queue_data_free(retrieved); - } - - ASSERT_EQ(queue_entry_count(q), 0, "Queue should be empty"); - - queue_free(q); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("FIFO ordering"); + +struct UASYNC* ua = uasync_create(); +struct ll_queue* q = queue_new(ua, 0); + +const int num_items = 10; +test_data_t* items[num_items]; + +/* Create and put items in order */ +for (int i = 0; i < num_items; i++) { +items[i] = (test_data_t*)queue_data_new(sizeof(test_data_t)); +items[i]->id = i; +snprintf(items[i]->name, sizeof(items[i]->name), "item_%d", i); +items[i]->value = i * 10; +items[i]->checksum = compute_checksum(items[i]); + +ASSERT_EQ(queue_data_put(q, items[i], items[i]->id), 0, "Failed to put data"); +} + +ASSERT_EQ(queue_entry_count(q), num_items, "Wrong item count"); + +/* Retrieve and verify FIFO order */ +for (int i = 0; i < num_items; i++) { +test_data_t* retrieved = (test_data_t*)queue_data_get(q); +ASSERT_NOT_NULL(retrieved, "Failed to get data"); +ASSERT_EQ(retrieved->id, i, "FIFO order violated"); +ASSERT_EQ(retrieved->value, i * 10, "Wrong value in FIFO"); + +queue_data_free(retrieved); +} + +ASSERT_EQ(queue_entry_count(q), 0, "Queue should be empty"); + +queue_free(q); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 4: LIFO operations with put_first */ static void test_lifo_operations() { - TEST_START("LIFO operations with put_first"); - - struct UASYNC* ua = uasync_create(); - struct ll_queue* q = queue_new(ua, 0); - - /* Add some items normally (FIFO) */ - for (int i = 0; i < 3; i++) { - test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); - data->id = i; - snprintf(data->name, sizeof(data->name), "normal_%d", i); - data->value = i; - data->checksum = compute_checksum(data); - - ASSERT_EQ(queue_data_put(q, data, data->id), 0, "Failed to put data"); - } - - /* Add high priority item at the beginning */ - test_data_t* priority = (test_data_t*)queue_data_new(sizeof(test_data_t)); - priority->id = 999; - strcpy(priority->name, "priority"); - priority->value = 999; - priority->checksum = compute_checksum(priority); - - ASSERT_EQ(queue_data_put_first(q, priority, priority->id), 0, "Failed to put_first data"); - - /* First item out should be the priority one */ - test_data_t* first = (test_data_t*)queue_data_get(q); - ASSERT_NOT_NULL(first, "Failed to get data"); - ASSERT_EQ(first->id, 999, "Priority item should come first"); - ASSERT_STR_EQ(first->name, "priority", "Wrong priority item"); - queue_data_free(first); - - /* Remaining items should be in original FIFO order */ - for (int i = 0; i < 3; i++) { - test_data_t* retrieved = (test_data_t*)queue_data_get(q); - ASSERT_NOT_NULL(retrieved, "Failed to get data"); - ASSERT_EQ(retrieved->id, i, "FIFO order violated after priority"); - queue_data_free(retrieved); - } - - ASSERT_EQ(queue_entry_count(q), 0, "Queue should be empty"); - - queue_free(q); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("LIFO operations with put_first"); + +struct UASYNC* ua = uasync_create(); +struct ll_queue* q = queue_new(ua, 0); + +/* Add some items normally (FIFO) */ +for (int i = 0; i < 3; i++) { +test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); +data->id = i; +snprintf(data->name, sizeof(data->name), "normal_%d", i); +data->value = i; +data->checksum = compute_checksum(data); + +ASSERT_EQ(queue_data_put(q, data, data->id), 0, "Failed to put data"); +} + +/* Add high priority item at the beginning */ +test_data_t* priority = (test_data_t*)queue_data_new(sizeof(test_data_t)); +priority->id = 999; +strcpy(priority->name, "priority"); +priority->value = 999; +priority->checksum = compute_checksum(priority); + +ASSERT_EQ(queue_data_put_first(q, priority, priority->id), 0, "Failed to put_first data"); + +/* First item out should be the priority one */ +test_data_t* first = (test_data_t*)queue_data_get(q); +ASSERT_NOT_NULL(first, "Failed to get data"); +ASSERT_EQ(first->id, 999, "Priority item should come first"); +ASSERT_STR_EQ(first->name, "priority", "Wrong priority item"); +queue_data_free(first); + +/* Remaining items should be in original FIFO order */ +for (int i = 0; i < 3; i++) { +test_data_t* retrieved = (test_data_t*)queue_data_get(q); +ASSERT_NOT_NULL(retrieved, "Failed to get data"); +ASSERT_EQ(retrieved->id, i, "FIFO order violated after priority"); +queue_data_free(retrieved); +} + +ASSERT_EQ(queue_entry_count(q), 0, "Queue should be empty"); + +queue_free(q); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 5: Callback system - basic */ static void test_callback_basic() { - TEST_START("Callback system - basic"); - - struct UASYNC* ua = uasync_create(); - struct ll_queue* q = queue_new(ua, 0); - - int callback_count = 0; - queue_set_callback(q, test_queue_callback, &callback_count); - - /* Add first item - callback should be called */ - test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); - data->id = 1; - strcpy(data->name, "callback_test"); - data->value = 42; - data->checksum = compute_checksum(data); - - printf("\n Before put: queue_count=%d", queue_entry_count(q)); - ASSERT_EQ(queue_data_put(q, data, data->id), 0, "Failed to put data"); - printf(" After put: queue_count=%d", queue_entry_count(q)); - - /* Process events to trigger callback */ - for (int i = 0; i < 10; i++) { - uasync_poll(ua, 1); /* 0.1ms poll */ - printf(" After poll %d: queue_count=%d, callback_count=%d", i, queue_entry_count(q), callback_count); - } - - ASSERT_GE(callback_count, 1, "Callback should be called at least once"); - printf(" Final queue_count=%d", queue_entry_count(q)); - - /* IMPORTANT: элемент остается в очереди после callback, не освобождать вручную! */ - /* queue_free должна освободить оставшиеся элементы */ - - queue_free(q); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("Callback system - basic"); + +struct UASYNC* ua = uasync_create(); +struct ll_queue* q = queue_new(ua, 0); + +int callback_count = 0; +queue_set_callback(q, test_queue_callback, &callback_count); + +/* Add first item - callback should be called */ +test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); +data->id = 1; +strcpy(data->name, "callback_test"); +data->value = 42; +data->checksum = compute_checksum(data); + +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "\n Before put: queue_count=%d", queue_entry_count(q)); +ASSERT_EQ(queue_data_put(q, data, data->id), 0, "Failed to put data"); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "After put: queue_count=%d", queue_entry_count(q)); + +/* Process events to trigger callback */ +for (int i = 0; i < 10; i++) { +uasync_poll(ua, 1); /* 0.1ms poll */ +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "After poll %d: queue_count=%d, callback_count=%d", i, queue_entry_count(q), callback_count); +} + +ASSERT_GE(callback_count, 1, "Callback should be called at least once"); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Final queue_count=%d", queue_entry_count(q)); + +/* IMPORTANT: элемент остается в очереди после callback, не освобождать вручную! */ +/* queue_free должна освободить оставшиеся элементы */ + +queue_free(q); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 6: Callback suspension and resumption */ static void test_callback_suspension() { - TEST_START("Callback suspension and resumption"); - - struct UASYNC* ua = uasync_create(); - struct ll_queue* q = queue_new(ua, 0); - - int callback_count = 0; - queue_set_callback(q, test_queue_callback, &callback_count); - - /* Add multiple items quickly */ - for (int i = 0; i < 5; i++) { - test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); - data->id = i; - snprintf(data->name, sizeof(data->name), "item_%d", i); - data->value = i * 10; - data->checksum = compute_checksum(data); - - ASSERT_EQ(queue_data_put(q, data, data->id), 0, "Failed to put data"); - } - - /* Process events - callback should process items one by one */ - for (int i = 0; i < 50; i++) { - uasync_poll(ua, 1); - } - - /* Callback should have been called for each item */ - ASSERT_GE(callback_count, 1, "Callback should process items"); - - queue_free(q); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("Callback suspension and resumption"); + +struct UASYNC* ua = uasync_create(); +struct ll_queue* q = queue_new(ua, 0); + +int callback_count = 0; +queue_set_callback(q, test_queue_callback, &callback_count); + +/* Add multiple items quickly */ +for (int i = 0; i < 5; i++) { +test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); +data->id = i; +snprintf(data->name, sizeof(data->name), "item_%d", i); +data->value = i * 10; +data->checksum = compute_checksum(data); + +ASSERT_EQ(queue_data_put(q, data, data->id), 0, "Failed to put data"); +} + +/* Process events - callback should process items one by one */ +for (int i = 0; i < 50; i++) { +uasync_poll(ua, 1); +} + +/* Callback should have been called for each item */ +ASSERT_GE(callback_count, 1, "Callback should process items"); + +queue_free(q); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 7: Waiter mechanism - basic */ static void test_waiter_basic() { - TEST_START("Waiter mechanism - basic"); - - struct UASYNC* ua = uasync_create(); - struct ll_queue* q = queue_new(ua, 0); - - int waiter_called = 0; - - /* Register waiter for empty queue - should trigger immediately */ - struct queue_waiter* waiter = queue_wait_threshold(q, 0, 0, test_waiter_callback, &waiter_called); - if (waiter_called == 1) { - /* Callback already called, waiter may be NULL or not */ - /* If waiter is not NULL, it might have been auto-freed, but we ignore */ - } else { - /* Callback not called yet */ - ASSERT_EQ(waiter_called, 0, "Callback should not be called yet"); - if (waiter != NULL) { - /* Waiter was created, callback should be called asynchronously */ - /* Process events to trigger callback */ - for (int i = 0; i < 10; i++) { - uasync_poll(ua, 1); - } - ASSERT_EQ(waiter_called, 1, "Waiter callback should be triggered asynchronously"); - } else { - /* No waiter created, but callback should have been called */ - TEST_FAIL("Expected waiter_called == 1 or waiter != NULL"); - } - } - - /* Reset and test with non-empty queue */ - waiter_called = 0; - - /* Add some items */ - for (int i = 0; i < 3; i++) { - test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); - data->id = i; - queue_data_put(q, data, data->id); - } - - /* Register waiter for threshold */ - waiter = queue_wait_threshold(q, 2, 0, test_waiter_callback, &waiter_called); - ASSERT_NOT_NULL(waiter, "Waiter should be registered when condition not met"); - ASSERT_EQ(waiter_called, 0, "Callback should not be called yet"); - - /* Remove items to reach threshold */ - for (int i = 0; i < 2; i++) { - test_data_t* data = (test_data_t*)queue_data_get(q); - ASSERT_NOT_NULL(data, "Failed to get data"); - queue_data_free(data); - } - - /* Process events to trigger waiter */ - for (int i = 0; i < 10; i++) { - uasync_poll(ua, 1); - } - - ASSERT_EQ(waiter_called, 1, "Waiter callback should be triggered"); - - queue_free(q); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("Waiter mechanism - basic"); + +struct UASYNC* ua = uasync_create(); +struct ll_queue* q = queue_new(ua, 0); + +int waiter_called = 0; + +/* Register waiter for empty queue - should trigger immediately */ +struct queue_waiter* waiter = queue_wait_threshold(q, 0, 0, test_waiter_callback, &waiter_called); +if (waiter_called == 1) { +/* Callback already called, waiter may be NULL or not */ +/* If waiter is not NULL, it might have been auto-freed, but we ignore */ +} else { +/* Callback not called yet */ +ASSERT_EQ(waiter_called, 0, "Callback should not be called yet"); +if (waiter != NULL) { +/* Waiter was created, callback should be called asynchronously */ +/* Process events to trigger callback */ +for (int i = 0; i < 10; i++) { +uasync_poll(ua, 1); +} +ASSERT_EQ(waiter_called, 1, "Waiter callback should be triggered asynchronously"); +} else { +/* No waiter created, but callback should have been called */ +TEST_FAIL("Expected waiter_called == 1 or waiter != NULL"); +} +} + +/* Reset and test with non-empty queue */ +waiter_called = 0; + +/* Add some items */ +for (int i = 0; i < 3; i++) { +test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); +data->id = i; +queue_data_put(q, data, data->id); +} + +/* Register waiter for threshold */ +waiter = queue_wait_threshold(q, 2, 0, test_waiter_callback, &waiter_called); +ASSERT_NOT_NULL(waiter, "Waiter should be registered when condition not met"); +ASSERT_EQ(waiter_called, 0, "Callback should not be called yet"); + +/* Remove items to reach threshold */ +for (int i = 0; i < 2; i++) { +test_data_t* data = (test_data_t*)queue_data_get(q); +ASSERT_NOT_NULL(data, "Failed to get data"); +queue_data_free(data); +} + +/* Process events to trigger waiter */ +for (int i = 0; i < 10; i++) { +uasync_poll(ua, 1); +} + +ASSERT_EQ(waiter_called, 1, "Waiter callback should be triggered"); + +queue_free(q); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 8: Waiter cancellation */ static void test_waiter_cancellation() { - TEST_START("Waiter cancellation"); - - struct UASYNC* ua = uasync_create(); - struct ll_queue* q = queue_new(ua, 0); - - int waiter_called = 0; - - /* Add items */ - for (int i = 0; i < 5; i++) { - test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); - data->id = i; - queue_data_put(q, data, data->id); - } - - /* Register waiter */ - struct queue_waiter* waiter = queue_wait_threshold(q, 2, 0, test_waiter_callback, &waiter_called); - ASSERT_NOT_NULL(waiter, "Waiter should be registered"); - - /* Cancel the waiter */ - queue_cancel_wait(q, waiter); - - /* Reach the threshold - waiter should not be called */ - for (int i = 0; i < 3; i++) { - test_data_t* data = (test_data_t*)queue_data_get(q); - ASSERT_NOT_NULL(data, "Failed to get data"); - queue_data_free(data); - } - - /* Process events */ - for (int i = 0; i < 10; i++) { - uasync_poll(ua, 1); - } - - ASSERT_EQ(waiter_called, 0, "Cancelled waiter should not be called"); - - queue_free(q); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("Waiter cancellation"); + +struct UASYNC* ua = uasync_create(); +struct ll_queue* q = queue_new(ua, 0); + +int waiter_called = 0; + +/* Add items */ +for (int i = 0; i < 5; i++) { +test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); +data->id = i; +queue_data_put(q, data, data->id); +} + +/* Register waiter */ +struct queue_waiter* waiter = queue_wait_threshold(q, 2, 0, test_waiter_callback, &waiter_called); +ASSERT_NOT_NULL(waiter, "Waiter should be registered"); + +/* Cancel the waiter */ +queue_cancel_wait(q, waiter); + +/* Reach the threshold - waiter should not be called */ +for (int i = 0; i < 3; i++) { +test_data_t* data = (test_data_t*)queue_data_get(q); +ASSERT_NOT_NULL(data, "Failed to get data"); +queue_data_free(data); +} + +/* Process events */ +for (int i = 0; i < 10; i++) { +uasync_poll(ua, 1); +} + +ASSERT_EQ(waiter_called, 0, "Cancelled waiter should not be called"); + +queue_free(q); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 9: Size limits */ static void test_size_limits() { - TEST_START("Size limits"); - - struct UASYNC* ua = uasync_create(); - struct ll_queue* q = queue_new(ua, 0); - - /* Set size limit to 3 */ - queue_set_size_limit(q, 3); - - /* Add up to limit */ - for (int i = 0; i < 3; i++) { - test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); - data->id = i; - ASSERT_EQ(queue_data_put(q, data, data->id), 0, "Should accept items up to limit"); - } - - ASSERT_EQ(queue_entry_count(q), 3, "Queue should be at limit"); - - /* Try to add one more - should be rejected */ - test_data_t* excess = (test_data_t*)queue_data_new(sizeof(test_data_t)); - excess->id = 999; - ASSERT_EQ(queue_data_put(q, excess, excess->id), -1, "Should reject items beyond limit"); - - /* Excess data should be automatically freed by queue */ - /* We'll verify by checking memory consistency later */ - - /* Remove one item, should be able to add again */ - test_data_t* removed = (test_data_t*)queue_data_get(q); - ASSERT_NOT_NULL(removed, "Should get item"); - queue_data_free(removed); - - ASSERT_EQ(queue_entry_count(q), 2, "Queue should have 2 items"); - - test_data_t* new_data = (test_data_t*)queue_data_new(sizeof(test_data_t)); - new_data->id = 100; - ASSERT_EQ(queue_data_put(q, new_data, new_data->id), 0, "Should accept new item after removal"); - - ASSERT_EQ(queue_entry_count(q), 3, "Queue should be at limit again"); - - queue_free(q); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("Size limits"); + +struct UASYNC* ua = uasync_create(); +struct ll_queue* q = queue_new(ua, 0); + +/* Set size limit to 3 */ +queue_set_size_limit(q, 3); + +/* Add up to limit */ +for (int i = 0; i < 3; i++) { +test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); +data->id = i; +ASSERT_EQ(queue_data_put(q, data, data->id), 0, "Should accept items up to limit"); +} + +ASSERT_EQ(queue_entry_count(q), 3, "Queue should be at limit"); + +/* Try to add one more - should be rejected */ +test_data_t* excess = (test_data_t*)queue_data_new(sizeof(test_data_t)); +excess->id = 999; +ASSERT_EQ(queue_data_put(q, excess, excess->id), -1, "Should reject items beyond limit"); + +/* Excess data should be automatically freed by queue */ +/* We'll verify by checking memory consistency later */ + +/* Remove one item, should be able to add again */ +test_data_t* removed = (test_data_t*)queue_data_get(q); +ASSERT_NOT_NULL(removed, "Should get item"); +queue_data_free(removed); + +ASSERT_EQ(queue_entry_count(q), 2, "Queue should have 2 items"); + +test_data_t* new_data = (test_data_t*)queue_data_new(sizeof(test_data_t)); +new_data->id = 100; +ASSERT_EQ(queue_data_put(q, new_data, new_data->id), 0, "Should accept new item after removal"); + +ASSERT_EQ(queue_entry_count(q), 3, "Queue should be at limit again"); + +queue_free(q); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 10: Hash table operations (ID-based search) */ static void test_hash_table_operations() { - TEST_START("Hash table operations (ID-based search)"); - - struct UASYNC* ua = uasync_create(); - /* Create queue with hash table size 16 */ - struct ll_queue* q = queue_new(ua, 16); - ASSERT_NOT_NULL(q, "Failed to create queue with hash table"); - - const int num_items = 10; - test_data_t* items[num_items]; - - /* Create items with known IDs */ - for (int i = 0; i < num_items; i++) { - items[i] = (test_data_t*)queue_data_new(sizeof(test_data_t)); - items[i]->id = i * 10 + 1; /* IDs: 1, 11, 21, ... */ - snprintf(items[i]->name, sizeof(items[i]->name), "item_%d", items[i]->id); - items[i]->value = i * 100; - items[i]->checksum = compute_checksum(items[i]); - - ASSERT_EQ(queue_data_put(q, items[i], items[i]->id), 0, "Failed to put data"); - } - - /* Find items by ID */ - for (int i = 0; i < num_items; i++) { - uint32_t target_id = i * 10 + 1; - test_data_t* found = (test_data_t*)queue_find_data_by_id(q, target_id); - ASSERT_NOT_NULL(found, "Failed to find item by ID"); - ASSERT_EQ(found->id, target_id, "Wrong item found"); - ASSERT_EQ(found->value, i * 100, "Wrong value in found item"); - } - - /* Test non-existent ID */ - test_data_t* not_found = (test_data_t*)queue_find_data_by_id(q, 99999); - ASSERT_NULL(not_found, "Should return NULL for non-existent ID"); - - /* Remove item by pointer */ - test_data_t* to_remove = (test_data_t*)queue_find_data_by_id(q, 21); /* Third item */ - ASSERT_NOT_NULL(to_remove, "Item to remove should exist"); - ASSERT_EQ(queue_remove_data(q, to_remove), 0, "Failed to remove data by pointer"); - - /* Verify removal */ - test_data_t* should_be_null = (test_data_t*)queue_find_data_by_id(q, 21); - ASSERT_NULL(should_be_null, "Removed item should not be found"); - ASSERT_EQ(queue_entry_count(q), num_items - 1, "Queue count should decrease"); - - /* Clean up remaining items */ - for (int i = 0; i < num_items; i++) { - if (i == 2) continue; /* Already removed */ - test_data_t* data = (test_data_t*)queue_data_get(q); - ASSERT_NOT_NULL(data, "Failed to get data"); - queue_data_free(data); - } - - queue_free(q); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("Hash table operations (ID-based search)"); + +struct UASYNC* ua = uasync_create(); +/* Create queue with hash table size 16 */ +struct ll_queue* q = queue_new(ua, 16); +ASSERT_NOT_NULL(q, "Failed to create queue with hash table"); + +const int num_items = 10; +test_data_t* items[num_items]; + +/* Create items with known IDs */ +for (int i = 0; i < num_items; i++) { +items[i] = (test_data_t*)queue_data_new(sizeof(test_data_t)); +items[i]->id = i * 10 + 1; /* IDs: 1, 11, 21, ... */ +snprintf(items[i]->name, sizeof(items[i]->name), "item_%d", items[i]->id); +items[i]->value = i * 100; +items[i]->checksum = compute_checksum(items[i]); + +ASSERT_EQ(queue_data_put(q, items[i], items[i]->id), 0, "Failed to put data"); +} + +/* Find items by ID */ +for (int i = 0; i < num_items; i++) { +uint32_t target_id = i * 10 + 1; +test_data_t* found = (test_data_t*)queue_find_data_by_id(q, target_id); +ASSERT_NOT_NULL(found, "Failed to find item by ID"); +ASSERT_EQ(found->id, target_id, "Wrong item found"); +ASSERT_EQ(found->value, i * 100, "Wrong value in found item"); +} + +/* Test non-existent ID */ +test_data_t* not_found = (test_data_t*)queue_find_data_by_id(q, 99999); +ASSERT_NULL(not_found, "Should return NULL for non-existent ID"); + +/* Remove item by pointer */ +test_data_t* to_remove = (test_data_t*)queue_find_data_by_id(q, 21); /* Third item */ +ASSERT_NOT_NULL(to_remove, "Item to remove should exist"); +ASSERT_EQ(queue_remove_data(q, to_remove), 0, "Failed to remove data by pointer"); + +/* Verify removal */ +test_data_t* should_be_null = (test_data_t*)queue_find_data_by_id(q, 21); +ASSERT_NULL(should_be_null, "Removed item should not be found"); +ASSERT_EQ(queue_entry_count(q), num_items - 1, "Queue count should decrease"); + +/* Clean up remaining items */ +for (int i = 0; i < num_items; i++) { +if (i == 2) continue; /* Already removed */ +test_data_t* data = (test_data_t*)queue_data_get(q); +ASSERT_NOT_NULL(data, "Failed to get data"); +queue_data_free(data); +} + +queue_free(q); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 11: Memory pool integration */ static void test_memory_pool_integration() { - TEST_START("Memory pool integration"); - - struct UASYNC* ua = uasync_create(); - - /* Create memory pool for test data (должен вмещать struct ll_entry + test_data_t) */ - struct memory_pool* pool = memory_pool_init(sizeof(struct ll_entry) + sizeof(test_data_t)); - ASSERT_NOT_NULL(pool, "Failed to create memory pool"); - - /* Create queue */ - struct ll_queue* q = queue_new(ua, 0); - ASSERT_NOT_NULL(q, "Failed to create queue"); - - /* Test basic pool operations */ - size_t initial_allocations = 0, initial_reuse = 0; - memory_pool_get_stats(pool, &initial_allocations, &initial_reuse); - - /* Create data from pool */ - test_data_t* data1 = (test_data_t*)queue_data_new_from_pool(pool); - ASSERT_NOT_NULL(data1, "Failed to create data from pool"); - - /* Check pool stats after allocation */ - size_t after_allocations = 0, after_reuse = 0; - memory_pool_get_stats(pool, &after_allocations, &after_reuse); - ASSERT_GT(after_allocations, initial_allocations, "Pool allocations should increase"); - - /* Initialize data */ - data1->id = 1; - strcpy(data1->name, "pool_test_1"); - data1->value = 100; - data1->checksum = compute_checksum(data1); - - /* Put data in queue */ - ASSERT_EQ(queue_data_put(q, data1, data1->id), 0, "Failed to put pooled data"); - ASSERT_EQ(queue_entry_count(q), 1, "Queue should have 1 element"); - - /* Create more data from pool */ - test_data_t* data2 = (test_data_t*)queue_data_new_from_pool(pool); - ASSERT_NOT_NULL(data2, "Failed to create second data from pool"); - data2->id = 2; - strcpy(data2->name, "pool_test_2"); - data2->value = 200; - data2->checksum = compute_checksum(data2); - - ASSERT_EQ(queue_data_put(q, data2, data2->id), 0, "Failed to put second pooled data"); - ASSERT_EQ(queue_entry_count(q), 2, "Queue should have 2 elements"); - - /* Retrieve and free data (should go back to pool) */ - test_data_t* retrieved1 = (test_data_t*)queue_data_get(q); - ASSERT_NOT_NULL(retrieved1, "Failed to get first data"); - ASSERT_EQ(retrieved1->id, 1, "Wrong data retrieved"); - - /* Check pool stats before free */ - size_t before_free_allocations = 0, before_free_reuse = 0; - memory_pool_get_stats(pool, &before_free_allocations, &before_free_reuse); - - /* Free data (should return to pool) */ - queue_data_free(retrieved1); - - /* Check pool stats after free */ - size_t after_free_allocations = 0, after_free_reuse = 0; - memory_pool_get_stats(pool, &after_free_allocations, &after_free_reuse); - printf("\n Pool stats: before_free=(alloc=%zu, reuse=%zu), after_free=(alloc=%zu, reuse=%zu)", - before_free_allocations, before_free_reuse, after_free_allocations, after_free_reuse); - ASSERT_EQ(after_free_allocations, before_free_allocations, "Allocations should not change after free"); - /* Note: reuse count may not increase if pool implementation is different */ - if (after_free_reuse > before_free_reuse) { - printf(" ✓ Reuse increased as expected"); - } else { - printf(" ⚠ Reuse did not increase (may be expected behavior)"); - } - - /* Create another data (should reuse from pool) */ - test_data_t* data3 = (test_data_t*)queue_data_new_from_pool(pool); - ASSERT_NOT_NULL(data3, "Failed to create third data from pool"); - - /* Check reuse stats */ - size_t final_allocations = 0, final_reuse = 0; - memory_pool_get_stats(pool, &final_allocations, &final_reuse); - printf("\n Pool stats: final=(alloc=%zu, reuse=%zu)", final_allocations, final_reuse); - ASSERT_EQ(final_allocations, after_free_allocations, "No new allocations for reused data"); - /* Note: reuse behavior depends on pool implementation */ - if (final_reuse > after_free_reuse) { - printf(" ✓ Final reuse increased"); - } else { - printf(" ⚠ Final reuse did not increase (implementation dependent)"); - } - - /* Clean up data3 */ - queue_data_free(data3); - - /* Clean up remaining data */ - test_data_t* retrieved2 = (test_data_t*)queue_data_get(q); - if (retrieved2) { - queue_data_free(retrieved2); - } - - queue_free(q); - memory_pool_destroy(pool); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("Memory pool integration"); + +struct UASYNC* ua = uasync_create(); + +/* Create memory pool for test data (должен вмещать struct ll_entry + test_data_t) */ +struct memory_pool* pool = memory_pool_init(sizeof(struct ll_entry) + sizeof(test_data_t)); +ASSERT_NOT_NULL(pool, "Failed to create memory pool"); + +/* Create queue */ +struct ll_queue* q = queue_new(ua, 0); +ASSERT_NOT_NULL(q, "Failed to create queue"); + +/* Test basic pool operations */ +size_t initial_allocations = 0, initial_reuse = 0; +memory_pool_get_stats(pool, &initial_allocations, &initial_reuse); + +/* Create data from pool */ +test_data_t* data1 = (test_data_t*)queue_data_new_from_pool(pool); +ASSERT_NOT_NULL(data1, "Failed to create data from pool"); + +/* Check pool stats after allocation */ +size_t after_allocations = 0, after_reuse = 0; +memory_pool_get_stats(pool, &after_allocations, &after_reuse); +ASSERT_GT(after_allocations, initial_allocations, "Pool allocations should increase"); + +/* Initialize data */ +data1->id = 1; +strcpy(data1->name, "pool_test_1"); +data1->value = 100; +data1->checksum = compute_checksum(data1); + +/* Put data in queue */ +ASSERT_EQ(queue_data_put(q, data1, data1->id), 0, "Failed to put pooled data"); +ASSERT_EQ(queue_entry_count(q), 1, "Queue should have 1 element"); + +/* Create more data from pool */ +test_data_t* data2 = (test_data_t*)queue_data_new_from_pool(pool); +ASSERT_NOT_NULL(data2, "Failed to create second data from pool"); +data2->id = 2; +strcpy(data2->name, "pool_test_2"); +data2->value = 200; +data2->checksum = compute_checksum(data2); + +ASSERT_EQ(queue_data_put(q, data2, data2->id), 0, "Failed to put second pooled data"); +ASSERT_EQ(queue_entry_count(q), 2, "Queue should have 2 elements"); + +/* Retrieve and free data (should go back to pool) */ +test_data_t* retrieved1 = (test_data_t*)queue_data_get(q); +ASSERT_NOT_NULL(retrieved1, "Failed to get first data"); +ASSERT_EQ(retrieved1->id, 1, "Wrong data retrieved"); + +/* Check pool stats before free */ +size_t before_free_allocations = 0, before_free_reuse = 0; +memory_pool_get_stats(pool, &before_free_allocations, &before_free_reuse); + +/* Free data (should return to pool) */ +queue_data_free(retrieved1); + +/* Check pool stats after free */ +size_t after_free_allocations = 0, after_free_reuse = 0; +memory_pool_get_stats(pool, &after_free_allocations, &after_free_reuse); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Pool stats: before_free=(alloc=%zu, reuse=%zu), after_free=(alloc=%zu, reuse=%zu)", before_free_allocations, before_free_reuse, after_free_allocations, after_free_reuse); +ASSERT_EQ(after_free_allocations, before_free_allocations, "Allocations should not change after free"); +/* Note: reuse count may not increase if pool implementation is different */ +if (after_free_reuse > before_free_reuse) { +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "✓ Reuse increased as expected"); +} else { +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "⚠ Reuse did not increase (may be expected behavior)"); +} + +/* Create another data (should reuse from pool) */ +test_data_t* data3 = (test_data_t*)queue_data_new_from_pool(pool); +ASSERT_NOT_NULL(data3, "Failed to create third data from pool"); + +/* Check reuse stats */ +size_t final_allocations = 0, final_reuse = 0; +memory_pool_get_stats(pool, &final_allocations, &final_reuse); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "\n Pool stats: final=(alloc=%zu, reuse=%zu)", final_allocations, final_reuse); +ASSERT_EQ(final_allocations, after_free_allocations, "No new allocations for reused data"); +/* Note: reuse behavior depends on pool implementation */ +if (final_reuse > after_free_reuse) { +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "✓ Final reuse increased"); +} else { +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "⚠ Final reuse did not increase (implementation dependent)"); +} + +/* Clean up data3 */ +queue_data_free(data3); + +/* Clean up remaining data */ +test_data_t* retrieved2 = (test_data_t*)queue_data_get(q); +if (retrieved2) { +queue_data_free(retrieved2); +} + +queue_free(q); +memory_pool_destroy(pool); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 12: Edge cases and error handling */ static void test_edge_cases() { - TEST_START("Edge cases and error handling"); - - /* Test NULL parameters */ - ASSERT_NULL(queue_new(NULL, 0), "Should return NULL for NULL uasync"); - - struct UASYNC* ua = uasync_create(); - struct ll_queue* q = queue_new(ua, 0); - - /* Test NULL queue operations */ - queue_set_callback(NULL, NULL, NULL); /* Should not crash */ - queue_resume_callback(NULL); - queue_set_size_limit(NULL, 10); - - ASSERT_NULL(queue_data_get(NULL), "Should return NULL for NULL queue"); - ASSERT_EQ(queue_data_put(NULL, NULL, 0), -1, "Should fail for NULL queue"); - ASSERT_EQ(queue_data_put_first(NULL, NULL, 0), -1, "Should fail for NULL queue"); - - ASSERT_EQ(queue_entry_count(NULL), 0, "Should return 0 for NULL queue"); - ASSERT_EQ(queue_total_bytes(NULL), 0, "Should return 0 for NULL queue"); - - ASSERT_NULL(queue_find_data_by_id(NULL, 0), "Should return NULL for NULL queue"); - ASSERT_EQ(queue_remove_data(NULL, NULL), -1, "Should fail for NULL queue"); - - /* Test with zero-sized data */ - void* zero_data = queue_data_new(0); - ASSERT_NOT_NULL(zero_data, "Should handle zero-sized data"); - ASSERT_EQ(queue_data_put(q, zero_data, 1), 0, "Should accept zero-sized data"); - ASSERT_EQ(queue_entry_count(q), 1, "Should count zero-sized data"); - - void* retrieved = queue_data_get(q); - ASSERT_NOT_NULL(retrieved, "Should retrieve zero-sized data"); - queue_data_free(retrieved); - - /* Test adding multiple items with different IDs */ - test_data_t* data1 = (test_data_t*)queue_data_new(sizeof(test_data_t)); - data1->id = 100; - ASSERT_EQ(queue_data_put(q, data1, data1->id), 0, "Should accept first item with ID"); - - test_data_t* data2 = (test_data_t*)queue_data_new(sizeof(test_data_t)); - data2->id = 101; /* Different ID */ - ASSERT_EQ(queue_data_put(q, data2, data2->id), 0, "Should accept second item with different ID"); - - /* Both items should be findable */ - test_data_t* found1 = (test_data_t*)queue_find_data_by_id(q, 100); - test_data_t* found2 = (test_data_t*)queue_find_data_by_id(q, 101); - /* Note: find only works if queue was created with hash_size > 0 */ - /* If hash_size == 0, find will return NULL, which is acceptable */ - /* We'll just clean up regardless */ - - /* Clean up */ - test_data_t* d1 = (test_data_t*)queue_data_get(q); - test_data_t* d2 = (test_data_t*)queue_data_get(q); - if (d1) queue_data_free(d1); - if (d2) queue_data_free(d2); - - queue_free(q); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("Edge cases and error handling"); + +/* Test NULL parameters */ +ASSERT_NULL(queue_new(NULL, 0), "Should return NULL for NULL uasync"); + +struct UASYNC* ua = uasync_create(); +struct ll_queue* q = queue_new(ua, 0); + +/* Test NULL queue operations */ +queue_set_callback(NULL, NULL, NULL); /* Should not crash */ +queue_resume_callback(NULL); +queue_set_size_limit(NULL, 10); + +ASSERT_NULL(queue_data_get(NULL), "Should return NULL for NULL queue"); +ASSERT_EQ(queue_data_put(NULL, NULL, 0), -1, "Should fail for NULL queue"); +ASSERT_EQ(queue_data_put_first(NULL, NULL, 0), -1, "Should fail for NULL queue"); + +ASSERT_EQ(queue_entry_count(NULL), 0, "Should return 0 for NULL queue"); +ASSERT_EQ(queue_total_bytes(NULL), 0, "Should return 0 for NULL queue"); + +ASSERT_NULL(queue_find_data_by_id(NULL, 0), "Should return NULL for NULL queue"); +ASSERT_EQ(queue_remove_data(NULL, NULL), -1, "Should fail for NULL queue"); + +/* Test with zero-sized data */ +void* zero_data = queue_data_new(0); +ASSERT_NOT_NULL(zero_data, "Should handle zero-sized data"); +ASSERT_EQ(queue_data_put(q, zero_data, 1), 0, "Should accept zero-sized data"); +ASSERT_EQ(queue_entry_count(q), 1, "Should count zero-sized data"); + +void* retrieved = queue_data_get(q); +ASSERT_NOT_NULL(retrieved, "Should retrieve zero-sized data"); +queue_data_free(retrieved); + +/* Test adding multiple items with different IDs */ +test_data_t* data1 = (test_data_t*)queue_data_new(sizeof(test_data_t)); +data1->id = 100; +ASSERT_EQ(queue_data_put(q, data1, data1->id), 0, "Should accept first item with ID"); + +test_data_t* data2 = (test_data_t*)queue_data_new(sizeof(test_data_t)); +data2->id = 101; /* Different ID */ +ASSERT_EQ(queue_data_put(q, data2, data2->id), 0, "Should accept second item with different ID"); + +/* Both items should be findable */ +test_data_t* found1 = (test_data_t*)queue_find_data_by_id(q, 100); +test_data_t* found2 = (test_data_t*)queue_find_data_by_id(q, 101); +/* Note: find only works if queue was created with hash_size > 0 */ +/* If hash_size == 0, find will return NULL, which is acceptable */ +/* We'll just clean up regardless */ + +/* Clean up */ +test_data_t* d1 = (test_data_t*)queue_data_get(q); +test_data_t* d2 = (test_data_t*)queue_data_get(q); +if (d1) queue_data_free(d1); +if (d2) queue_data_free(d2); + +queue_free(q); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 13: Stress test - high volume operations */ static void test_stress_high_volume() { - TEST_START("Stress test - high volume operations"); - - double start_time = get_time_ms(); - - struct UASYNC* ua = uasync_create(); - struct ll_queue* q = queue_new(ua, 64); /* With hash table */ - - const int num_operations = 10000; - const int max_queue_size = 100; - - srand(time(NULL)); - - for (int i = 0; i < num_operations; i++) { - int op = rand() % 100; - - if (op < 40) { /* 40%: Add to tail */ - if (queue_entry_count(q) < max_queue_size) { - test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); - if (data) { - data->id = rand() % 1000; - data->value = rand(); - data->checksum = compute_checksum(data); - queue_data_put(q, data, data->id); - test_stats.total_operations++; - } - } - } else if (op < 60) { /* 20%: Add to head (priority) */ - if (queue_entry_count(q) < max_queue_size) { - test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); - if (data) { - data->id = rand() % 1000; - data->value = rand(); - data->checksum = compute_checksum(data); - queue_data_put_first(q, data, data->id); - test_stats.total_operations++; - } - } - } else if (op < 80) { /* 20%: Remove from head */ - test_data_t* data = (test_data_t*)queue_data_get(q); - if (data) { - if (data->checksum != compute_checksum(data)) { - test_stats.memory_errors++; - } - queue_data_free(data); - test_stats.total_operations++; - } - } else if (op < 90) { /* 10%: Find by ID */ - uint32_t search_id = rand() % 1000; - test_data_t* found = (test_data_t*)queue_find_data_by_id(q, search_id); - if (found) { - if (found->checksum != compute_checksum(found)) { - test_stats.hash_table_errors++; - } - test_stats.total_operations++; - } - } else { /* 10%: Remove by pointer */ - if (queue_entry_count(q) > 0) { - /* Find random item to remove */ - int target_idx = rand() % queue_entry_count(q); - struct ll_entry* curr = q->head; - for (int j = 0; j < target_idx && curr; j++) { - curr = curr->next; - } - if (curr) { - test_data_t* data = (test_data_t*)(curr->payload); - if (queue_remove_data(q, data) == 0) { - queue_data_free(data); - test_stats.total_operations++; - } - } - } - } - - /* Periodic integrity check */ - if (i % 1000 == 0) { - /* Verify doubly-linked list integrity */ - int count = 0; - struct ll_entry* curr = q->head; - struct ll_entry* prev = NULL; - while (curr) { - count++; - if (curr->prev != prev) { - test_stats.memory_errors++; - } - if (prev && prev->next != curr) { - test_stats.memory_errors++; - } - prev = curr; - curr = curr->next; - } - if (count != queue_entry_count(q)) { - test_stats.memory_errors++; - } - - /* Verify hash table integrity */ - for (uint32_t id = 0; id < 1000; id += 10) { - test_data_t* found = (test_data_t*)queue_find_data_by_id(q, id); - if (found) { - /* Verify the found item is actually in the queue */ - int found_in_list = 0; - curr = q->head; - while (curr) { - if ((test_data_t*)(curr->payload) == found) { - found_in_list = 1; - break; - } - curr = curr->next; - } - if (!found_in_list) { - test_stats.hash_table_errors++; - } - } - } - } - } - - double end_time = get_time_ms(); - test_stats.total_time_ms += (end_time - start_time); - - /* Clean up remaining items */ - while (queue_entry_count(q) > 0) { - test_data_t* data = (test_data_t*)queue_data_get(q); - if (data) queue_data_free(data); - } - - ASSERT_EQ(test_stats.memory_errors, 0, "Memory corruption detected during stress test"); - ASSERT_EQ(test_stats.hash_table_errors, 0, "Hash table corruption detected"); - ASSERT_TRUE(test_stats.total_operations > num_operations / 2, "Too few operations performed"); - - printf("\n Operations: %ld, Time: %.2f ms, Ops/sec: %.2f", - test_stats.total_operations, end_time - start_time, - test_stats.total_operations * 1000.0 / (end_time - start_time)); - - queue_free(q); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("Stress test - high volume operations"); + +double start_time = get_time_ms(); + +struct UASYNC* ua = uasync_create(); +struct ll_queue* q = queue_new(ua, 64); /* With hash table */ + +const int num_operations = 10000; +const int max_queue_size = 100; + +srand(time(NULL)); + +for (int i = 0; i < num_operations; i++) { +int op = rand() % 100; + +if (op < 40) { /* 40%: Add to tail */ +if (queue_entry_count(q) < max_queue_size) { +test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); +if (data) { +data->id = rand() % 1000; +data->value = rand(); +data->checksum = compute_checksum(data); +queue_data_put(q, data, data->id); +test_stats.total_operations++; +} +} +} else if (op < 60) { /* 20%: Add to head (priority) */ +if (queue_entry_count(q) < max_queue_size) { +test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); +if (data) { +data->id = rand() % 1000; +data->value = rand(); +data->checksum = compute_checksum(data); +queue_data_put_first(q, data, data->id); +test_stats.total_operations++; +} +} +} else if (op < 80) { /* 20%: Remove from head */ +test_data_t* data = (test_data_t*)queue_data_get(q); +if (data) { +if (data->checksum != compute_checksum(data)) { +test_stats.memory_errors++; +} +queue_data_free(data); +test_stats.total_operations++; +} +} else if (op < 90) { /* 10%: Find by ID */ +uint32_t search_id = rand() % 1000; +test_data_t* found = (test_data_t*)queue_find_data_by_id(q, search_id); +if (found) { +if (found->checksum != compute_checksum(found)) { +test_stats.hash_table_errors++; +} +test_stats.total_operations++; +} +} else { /* 10%: Remove by pointer */ +if (queue_entry_count(q) > 0) { +/* Find random item to remove */ +int target_idx = rand() % queue_entry_count(q); +struct ll_entry* curr = q->head; +for (int j = 0; j < target_idx && curr; j++) { +curr = curr->next; +} +if (curr) { +test_data_t* data = (test_data_t*)(curr->payload); +if (queue_remove_data(q, data) == 0) { +queue_data_free(data); +test_stats.total_operations++; +} +} +} +} + +/* Periodic integrity check */ +if (i % 1000 == 0) { +/* Verify doubly-linked list integrity */ +int count = 0; +struct ll_entry* curr = q->head; +struct ll_entry* prev = NULL; +while (curr) { +count++; +if (curr->prev != prev) { +test_stats.memory_errors++; +} +if (prev && prev->next != curr) { +test_stats.memory_errors++; +} +prev = curr; +curr = curr->next; +} +if (count != queue_entry_count(q)) { +test_stats.memory_errors++; +} + +/* Verify hash table integrity */ +for (uint32_t id = 0; id < 1000; id += 10) { +test_data_t* found = (test_data_t*)queue_find_data_by_id(q, id); +if (found) { +/* Verify the found item is actually in the queue */ +int found_in_list = 0; +curr = q->head; +while (curr) { +if ((test_data_t*)(curr->payload) == found) { +found_in_list = 1; +break; +} +curr = curr->next; +} +if (!found_in_list) { +test_stats.hash_table_errors++; +} +} +} +} +} + +double end_time = get_time_ms(); +test_stats.total_time_ms += (end_time - start_time); + +/* Clean up remaining items */ +while (queue_entry_count(q) > 0) { +test_data_t* data = (test_data_t*)queue_data_get(q); +if (data) queue_data_free(data); +} + +ASSERT_EQ(test_stats.memory_errors, 0, "Memory corruption detected during stress test"); +ASSERT_EQ(test_stats.hash_table_errors, 0, "Hash table corruption detected"); +ASSERT_TRUE(test_stats.total_operations > num_operations / 2, "Too few operations performed"); + +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Operations: %ld, Time: %.2f ms, Ops/sec: %.2f", test_stats.total_operations, end_time - start_time, +test_stats.total_operations * 1000.0 / (end_time - start_time)); + +queue_free(q); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 15: Memory pool stress test */ static void test_memory_pool_stress() { - TEST_START("Memory pool stress test"); - - struct UASYNC* ua = uasync_create(); - - /* Create memory pool (должен вмещать struct ll_entry + test_data_t) */ - struct memory_pool* pool = memory_pool_init(sizeof(struct ll_entry) + sizeof(test_data_t)); - ASSERT_NOT_NULL(pool, "Failed to create memory pool"); - - /* Create queue */ - struct ll_queue* q = queue_new(ua, 0); - ASSERT_NOT_NULL(q, "Failed to create queue"); - - const int iterations = 1000; - test_data_t* items[iterations]; - - /* Stress test: allocate and free many items */ - size_t initial_allocations = 0, initial_reuse = 0; - memory_pool_get_stats(pool, &initial_allocations, &initial_reuse); - - /* Allocate many items from pool */ - for (int i = 0; i < iterations; i++) { - items[i] = (test_data_t*)queue_data_new_from_pool(pool); - ASSERT_NOT_NULL(items[i], "Failed to allocate from pool"); - - items[i]->id = i; - snprintf(items[i]->name, sizeof(items[i]->name), "stress_%d", i); - items[i]->value = i * 10; - items[i]->checksum = compute_checksum(items[i]); - } - - /* Check allocations increased */ - size_t after_allocations = 0, after_reuse = 0; - memory_pool_get_stats(pool, &after_allocations, &after_reuse); - ASSERT_GT(after_allocations, initial_allocations, "Pool allocations should increase"); - - /* Put all items in queue */ - for (int i = 0; i < iterations; i++) { - ASSERT_EQ(queue_data_put(q, items[i], items[i]->id), 0, "Failed to put stress data"); - } - ASSERT_EQ(queue_entry_count(q), iterations, "Queue should have all stress items"); - - /* Remove half of items */ - for (int i = 0; i < iterations / 2; i++) { - test_data_t* retrieved = (test_data_t*)queue_data_get(q); - ASSERT_NOT_NULL(retrieved, "Failed to get stress data"); - queue_data_free(retrieved); /* Should return to pool */ - } - - /* Check reuse count increased */ - size_t after_free_allocations = 0, after_free_reuse = 0; - memory_pool_get_stats(pool, &after_free_allocations, &after_free_reuse); - ASSERT_EQ(after_free_allocations, after_allocations, "Pool allocations should not change"); - /* Note: reuse count may not increase if pool implementation is different - skip check in stress test */ - - /* Final stats check */ - size_t final_allocations = 0, final_reuse = 0; - memory_pool_get_stats(pool, &final_allocations, &final_reuse); - printf("\n Final pool stats: allocations=%zu, reuse=%zu", final_allocations, final_reuse); - - /* Should not allocate more than initial pool size */ - ASSERT_LE(final_allocations, after_allocations + 50, "Should not allocate much more than initial"); - /* Note: reuse behavior depends on pool implementation and usage patterns - skip strict check for stress test */ - - /* Clean up remaining items */ - while (queue_entry_count(q) > 0) { - test_data_t* retrieved = (test_data_t*)queue_data_get(q); - if (retrieved) { - queue_data_free(retrieved); - } - } - - queue_free(q); - memory_pool_destroy(pool); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("Memory pool stress test"); + +struct UASYNC* ua = uasync_create(); + +/* Create memory pool (должен вмещать struct ll_entry + test_data_t) */ +struct memory_pool* pool = memory_pool_init(sizeof(struct ll_entry) + sizeof(test_data_t)); +ASSERT_NOT_NULL(pool, "Failed to create memory pool"); + +/* Create queue */ +struct ll_queue* q = queue_new(ua, 0); +ASSERT_NOT_NULL(q, "Failed to create queue"); + +const int iterations = 1000; +test_data_t* items[iterations]; + +/* Stress test: allocate and free many items */ +size_t initial_allocations = 0, initial_reuse = 0; +memory_pool_get_stats(pool, &initial_allocations, &initial_reuse); + +/* Allocate many items from pool */ +for (int i = 0; i < iterations; i++) { +items[i] = (test_data_t*)queue_data_new_from_pool(pool); +ASSERT_NOT_NULL(items[i], "Failed to allocate from pool"); + +items[i]->id = i; +snprintf(items[i]->name, sizeof(items[i]->name), "stress_%d", i); +items[i]->value = i * 10; +items[i]->checksum = compute_checksum(items[i]); +} + +/* Check allocations increased */ +size_t after_allocations = 0, after_reuse = 0; +memory_pool_get_stats(pool, &after_allocations, &after_reuse); +ASSERT_GT(after_allocations, initial_allocations, "Pool allocations should increase"); + +/* Put all items in queue */ +for (int i = 0; i < iterations; i++) { +ASSERT_EQ(queue_data_put(q, items[i], items[i]->id), 0, "Failed to put stress data"); +} +ASSERT_EQ(queue_entry_count(q), iterations, "Queue should have all stress items"); + +/* Remove half of items */ +for (int i = 0; i < iterations / 2; i++) { +test_data_t* retrieved = (test_data_t*)queue_data_get(q); +ASSERT_NOT_NULL(retrieved, "Failed to get stress data"); +queue_data_free(retrieved); /* Should return to pool */ +} + +/* Check reuse count increased */ +size_t after_free_allocations = 0, after_free_reuse = 0; +memory_pool_get_stats(pool, &after_free_allocations, &after_free_reuse); +ASSERT_EQ(after_free_allocations, after_allocations, "Pool allocations should not change"); +/* Note: reuse count may not increase if pool implementation is different - skip check in stress test */ + +/* Final stats check */ +size_t final_allocations = 0, final_reuse = 0; +memory_pool_get_stats(pool, &final_allocations, &final_reuse); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "\n Final pool stats: allocations=%zu, reuse=%zu", final_allocations, final_reuse); + +/* Should not allocate more than initial pool size */ +ASSERT_LE(final_allocations, after_allocations + 50, "Should not allocate much more than initial"); +/* Note: reuse behavior depends on pool implementation and usage patterns - skip strict check for stress test */ + +/* Clean up remaining items */ +while (queue_entry_count(q) > 0) { +test_data_t* retrieved = (test_data_t*)queue_data_get(q); +if (retrieved) { +queue_data_free(retrieved); +} +} + +queue_free(q); +memory_pool_destroy(pool); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 16: Memory pool vs malloc performance comparison */ static void test_memory_pool_vs_malloc_performance() { - TEST_START("Memory pool vs malloc performance comparison"); - - struct UASYNC* ua = uasync_create(); - - /* Create memory pool (должен вмещать struct ll_entry + test_data_t) */ - struct memory_pool* pool = memory_pool_init(sizeof(struct ll_entry) + sizeof(test_data_t)); - ASSERT_NOT_NULL(pool, "Failed to create memory pool"); - - /* Create queue */ - struct ll_queue* q = queue_new(ua, 0); - ASSERT_NOT_NULL(q, "Failed to create queue"); - - const int iterations = 5000; - - /* Benchmark pool allocation */ - double pool_start = get_time_ms(); - - for (int i = 0; i < iterations; i++) { - test_data_t* data = (test_data_t*)queue_data_new_from_pool(pool); - if (data) { - data->id = i; - data->value = i * 10; - data->checksum = compute_checksum(data); - queue_data_put(q, data, data->id); - queue_data_free((test_data_t*)queue_data_get(q)); - } - } - - double pool_time = get_time_ms() - pool_start; - - /* Benchmark malloc allocation */ - double malloc_start = get_time_ms(); - - for (int i = 0; i < iterations; i++) { - test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); - if (data) { - data->id = i; - data->value = i * 10; - data->checksum = compute_checksum(data); - queue_data_put(q, data, data->id); - queue_data_free((test_data_t*)queue_data_get(q)); - } - } - - double malloc_time = get_time_ms() - malloc_start; - - /* Performance comparison */ - printf("\n Pool time: %.3f ms (%.1f ops/sec)", pool_time, iterations * 1000.0 / pool_time); - printf("\n Malloc time: %.3f ms (%.1f ops/sec)", malloc_time, iterations * 1000.0 / malloc_time); - - if (pool_time < malloc_time) { - double speedup = malloc_time / pool_time; - printf("\n Pool is %.2fx faster than malloc", speedup); - } else { - double slowdown = pool_time / malloc_time; - printf("\n Pool is %.2fx slower than malloc", slowdown); - } - - /* Pool should generally be faster or comparable */ - ASSERT_TRUE(pool_time <= malloc_time * 1.5, "Pool should not be significantly slower than malloc"); - - /* Check final pool stats */ - size_t final_allocations = 0, final_reuse = 0; - memory_pool_get_stats(pool, &final_allocations, &final_reuse); - - printf("\n Pool stats: allocations=%zu, reuse=%zu", final_allocations, final_reuse); - ASSERT_GT(final_reuse, iterations * 0.8, "High reuse rate expected"); - - queue_free(q); - memory_pool_destroy(pool); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("Memory pool vs malloc performance comparison"); + +struct UASYNC* ua = uasync_create(); + +/* Create memory pool (должен вмещать struct ll_entry + test_data_t) */ +struct memory_pool* pool = memory_pool_init(sizeof(struct ll_entry) + sizeof(test_data_t)); +ASSERT_NOT_NULL(pool, "Failed to create memory pool"); + +/* Create queue */ +struct ll_queue* q = queue_new(ua, 0); +ASSERT_NOT_NULL(q, "Failed to create queue"); + +const int iterations = 5000; + +/* Benchmark pool allocation */ +double pool_start = get_time_ms(); + +for (int i = 0; i < iterations; i++) { +test_data_t* data = (test_data_t*)queue_data_new_from_pool(pool); +if (data) { +data->id = i; +data->value = i * 10; +data->checksum = compute_checksum(data); +queue_data_put(q, data, data->id); +queue_data_free((test_data_t*)queue_data_get(q)); +} +} + +double pool_time = get_time_ms() - pool_start; + +/* Benchmark malloc allocation */ +double malloc_start = get_time_ms(); + +for (int i = 0; i < iterations; i++) { +test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); +if (data) { +data->id = i; +data->value = i * 10; +data->checksum = compute_checksum(data); +queue_data_put(q, data, data->id); +queue_data_free((test_data_t*)queue_data_get(q)); +} +} + +double malloc_time = get_time_ms() - malloc_start; + +/* Performance comparison */ +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "\n Pool time: %.3f ms (%.1f ops/sec)", pool_time, iterations * 1000.0 / pool_time); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "\n Malloc time: %.3f ms (%.1f ops/sec)", malloc_time, iterations * 1000.0 / malloc_time); + +if (pool_time < malloc_time) { +double speedup = malloc_time / pool_time; +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "\n Pool is %.2fx faster than malloc", speedup); +} else { +double slowdown = pool_time / malloc_time; +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "\n Pool is %.2fx slower than malloc", slowdown); +} + +/* Pool should generally be faster or comparable */ +ASSERT_TRUE(pool_time <= malloc_time * 1.5, "Pool should not be significantly slower than malloc"); + +/* Check final pool stats */ +size_t final_allocations = 0, final_reuse = 0; +memory_pool_get_stats(pool, &final_allocations, &final_reuse); + +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "\n Pool stats: allocations=%zu, reuse=%zu", final_allocations, final_reuse); +ASSERT_GT(final_reuse, iterations * 0.8, "High reuse rate expected"); + +queue_free(q); +memory_pool_destroy(pool); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 14: Reference counting validation */ static void test_reference_counting() { - TEST_START("Reference counting validation"); - - struct UASYNC* ua = uasync_create(); - struct ll_queue* q = queue_new(ua, 16); /* With hash table for ID lookup */ - - /* Create data and put it in queue */ - test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); - data->id = 1; - data->value = 42; - data->checksum = compute_checksum(data); - - /* Get the ll_entry pointer for inspection */ - struct ll_entry* entry = (struct ll_entry*)((char*)data - sizeof(struct ll_entry)); - ASSERT_EQ(entry->ref_count, 1, "New entry should have ref_count = 1"); - - /* Put in queue - ref_count НЕ изменяется в новой архитектуре */ - ASSERT_EQ(queue_data_put(q, data, data->id), 0, "Failed to put data"); - ASSERT_EQ(entry->ref_count, 1, "Entry in queue should still have ref_count = 1 (new architecture)"); - - /* Find by ID - should not change ref_count */ - test_data_t* found = (test_data_t*)queue_find_data_by_id(q, 1); - ASSERT_NOT_NULL(found, "Should find data"); - ASSERT_EQ(entry->ref_count, 1, "Find should not change ref_count"); - - /* Get from queue - ref_count НЕ изменяется в новой архитектуре */ - test_data_t* retrieved = (test_data_t*)queue_data_get(q); - ASSERT_NOT_NULL(retrieved, "Should retrieve data"); - ASSERT_EQ(entry->ref_count, 1, "Get should not change ref_count (new architecture)"); - - /* Free data - should decrement to 0 and free memory */ - queue_data_free(retrieved); - /* Can't check ref_count after free */ - - queue_free(q); - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("Reference counting validation"); + +struct UASYNC* ua = uasync_create(); +struct ll_queue* q = queue_new(ua, 16); /* With hash table for ID lookup */ + +/* Create data and put it in queue */ +test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); +data->id = 1; +data->value = 42; +data->checksum = compute_checksum(data); + +/* Get the ll_entry pointer for inspection */ +struct ll_entry* entry = (struct ll_entry*)((char*)data - sizeof(struct ll_entry)); +ASSERT_EQ(entry->ref_count, 1, "New entry should have ref_count = 1"); + +/* Put in queue - ref_count НЕ изменяется в новой архитектуре */ +ASSERT_EQ(queue_data_put(q, data, data->id), 0, "Failed to put data"); +ASSERT_EQ(entry->ref_count, 1, "Entry in queue should still have ref_count = 1 (new architecture)"); + +/* Find by ID - should not change ref_count */ +test_data_t* found = (test_data_t*)queue_find_data_by_id(q, 1); +ASSERT_NOT_NULL(found, "Should find data"); +ASSERT_EQ(entry->ref_count, 1, "Find should not change ref_count"); + +/* Get from queue - ref_count НЕ изменяется в новой архитектуре */ +test_data_t* retrieved = (test_data_t*)queue_data_get(q); +ASSERT_NOT_NULL(retrieved, "Should retrieve data"); +ASSERT_EQ(entry->ref_count, 1, "Get should not change ref_count (new architecture)"); + +/* Free data - should decrement to 0 and free memory */ +queue_data_free(retrieved); +/* Can't check ref_count after free */ + +queue_free(q); +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Main test runner */ int main() { - printf("=== ll_queue Comprehensive Tests with Current API ===\n"); - printf("Starting tests...\n\n"); - - /* Initialize debug system */ - debug_config_init(); - debug_set_level(DEBUG_LEVEL_DEBUG); - debug_set_categories(DEBUG_CATEGORY_LL_QUEUE); - - double suite_start_time = get_time_ms(); - - /* Run all tests */ - test_basic_creation(); - test_data_operations(); - test_fifo_ordering(); - test_lifo_operations(); - test_callback_basic(); - test_callback_suspension(); - test_waiter_basic(); - test_waiter_cancellation(); - test_size_limits(); - test_hash_table_operations(); - test_memory_pool_integration(); - test_edge_cases(); - test_stress_high_volume(); - test_reference_counting(); - test_memory_pool_stress(); - test_memory_pool_vs_malloc_performance(); - - double suite_end_time = get_time_ms(); - - printf("\n=== Test Suite Summary ===\n"); - printf("Tests run: %d\n", test_stats.tests_run); - printf("Tests passed: %d\n", test_stats.tests_passed); - printf("Tests failed: %d\n", test_stats.tests_failed); - printf("\nError Statistics:\n"); - printf(" Memory errors: %d\n", test_stats.memory_errors); - printf(" Hash table errors: %d\n", test_stats.hash_table_errors); - printf(" Reference count errors: %d\n", test_stats.ref_count_errors); - printf("\nPerformance:\n"); - printf(" Total operations: %ld\n", test_stats.total_operations); - printf(" Total time: %.2f ms\n", test_stats.total_time_ms); - if (test_stats.total_time_ms > 0) { - printf(" Average ops/sec: %.2f\n", test_stats.total_operations * 1000.0 / test_stats.total_time_ms); - } - printf("\nCallback Statistics:\n"); - printf(" Queue callbacks: %d\n", test_stats.queue_callback_count); - printf(" Waiter callbacks: %d\n", test_stats.waiter_callback_count); - - if (test_stats.tests_failed == 0 && test_stats.memory_errors == 0 && - test_stats.hash_table_errors == 0 && test_stats.ref_count_errors == 0) { - printf("\n✅ ALL TESTS PASSED - ll_queue implementation is robust!\n"); - return 0; - } else { - printf("\n❌ TEST FAILURES DETECTED - Review implementation\n"); - return 1; - } +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "=== ll_queue Comprehensive Tests with Current API ==="); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Starting tests...\n"); + +/* Initialize debug system */ +debug_config_init(); +debug_set_level(DEBUG_LEVEL_DEBUG); +debug_set_categories(DEBUG_CATEGORY_LL_QUEUE); + +double suite_start_time = get_time_ms(); + +/* Run all tests */ +test_basic_creation(); +test_data_operations(); +test_fifo_ordering(); +test_lifo_operations(); +test_callback_basic(); +test_callback_suspension(); +test_waiter_basic(); +test_waiter_cancellation(); +test_size_limits(); +test_hash_table_operations(); +test_memory_pool_integration(); +test_edge_cases(); +test_stress_high_volume(); +test_reference_counting(); +test_memory_pool_stress(); +test_memory_pool_vs_malloc_performance(); + +double suite_end_time = get_time_ms(); + +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "\n=== Test Suite Summary ==="); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Tests run: %d", test_stats.tests_run); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Tests passed: %d", test_stats.tests_passed); +DEBUG_ERROR(DEBUG_CATEGORY_LL_QUEUE, "Tests failed: %d", test_stats.tests_failed); +DEBUG_ERROR(DEBUG_CATEGORY_LL_QUEUE, "\nError Statistics:"); +DEBUG_ERROR(DEBUG_CATEGORY_LL_QUEUE, "Memory errors: %d", test_stats.memory_errors); +DEBUG_ERROR(DEBUG_CATEGORY_LL_QUEUE, "Hash table errors: %d", test_stats.hash_table_errors); +DEBUG_ERROR(DEBUG_CATEGORY_LL_QUEUE, "Reference count errors: %d", test_stats.ref_count_errors); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "\nPerformance:"); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Total operations: %ld", test_stats.total_operations); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Total time: %.2f ms", test_stats.total_time_ms); +if (test_stats.total_time_ms > 0) { +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Average ops/sec: %.2f", test_stats.total_operations * 1000.0 / test_stats.total_time_ms); +} +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "\nCallback Statistics:"); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Queue callbacks: %d", test_stats.queue_callback_count); +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "Waiter callbacks: %d", test_stats.waiter_callback_count); + +if (test_stats.tests_failed == 0 && test_stats.memory_errors == 0 && +test_stats.hash_table_errors == 0 && test_stats.ref_count_errors == 0) { +DEBUG_INFO(DEBUG_CATEGORY_LL_QUEUE, "\n ALL TESTS PASSED - ll_queue implementation is robust!"); +return 0; +} else { +DEBUG_ERROR(DEBUG_CATEGORY_LL_QUEUE, "\n TEST FAILURES DETECTED - Review implementation"); +return 1; +} } \ No newline at end of file diff --git a/tests/test_ll_queue.c.backup b/tests/test_ll_queue.c.backup new file mode 100644 index 000000000..a432adc22 --- /dev/null +++ b/tests/test_ll_queue.c.backup @@ -0,0 +1,1126 @@ +/** + * Comprehensive unit tests for ll_queue module with current API + * Tests: basic operations, callback system, waiters, hash table, memory pool, edge cases, stress tests + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "../lib/ll_queue.h" +#include "../lib/u_async.h" +#include "../lib/debug_config.h" +#include "../lib/memory_pool.h" + +/* Enable debug output for ll_queue */ +#define DEBUG_CATEGORY_LL_QUEUE 1 + +/* Test statistics */ +static struct { + int tests_run; + int tests_passed; + int tests_failed; + + /* Callback counters */ + int queue_callback_count; + int waiter_callback_count; + + /* Error tracking */ + int memory_errors; + int hash_table_errors; + int ref_count_errors; + + /* Performance metrics */ + long total_operations; + double total_time_ms; +} test_stats = {0}; + +/* Test result tracking */ +#define TEST_START(name) do { \ + printf("TEST: %s... ", name); \ + test_stats.tests_run++; \ + fflush(stdout); \ +} while(0) + +#define TEST_PASS() do { \ + printf("PASS\n"); \ + test_stats.tests_passed++; \ +} while(0) + +#define TEST_FAIL(msg) do { \ + printf("FAIL: %s\n", msg); \ + test_stats.tests_failed++; \ +} while(0) + +#define ASSERT_TRUE(cond, msg) do { \ + if (!(cond)) { TEST_FAIL(msg); return; } \ +} while(0) + +#define ASSERT_FALSE(cond, msg) ASSERT_TRUE(!(cond), msg) +#define ASSERT_NULL(ptr, msg) ASSERT_TRUE((ptr) == NULL, msg) +#define ASSERT_NOT_NULL(ptr, msg) ASSERT_TRUE((ptr) != NULL, msg) +#define ASSERT_EQ(a, b, msg) ASSERT_TRUE((a) == (b), msg) +#define ASSERT_NEQ(a, b, msg) ASSERT_TRUE((a) != (b), msg) +#define ASSERT_STR_EQ(a, b, msg) ASSERT_TRUE(strcmp((a), (b)) == 0, msg) +#define ASSERT_GE(a, b, msg) ASSERT_TRUE((a) >= (b), msg) +#define ASSERT_LE(a, b, msg) ASSERT_TRUE((a) <= (b), msg) +#define ASSERT_GT(a, b, msg) ASSERT_TRUE((a) > (b), msg) +#define ASSERT_LT(a, b, msg) ASSERT_TRUE((a) < (b), msg) + +/* Utility functions */ +static double get_time_ms() { + struct timeval tv; + gettimeofday(&tv, NULL); + return tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0; +} + +/* Test data structure */ +typedef struct { + int id; + char name[32]; + int value; + uint64_t checksum; +} test_data_t; + +static uint64_t compute_checksum(test_data_t* data) { + return (uint64_t)data->id * 31 + (uint64_t)data->value * 17 + (uint64_t)strlen(data->name); +} + +/* Queue callback for testing */ +static void test_queue_callback(struct ll_queue* q, void* data, void* arg) { + int* callback_count = (int*)arg; + (*callback_count)++; + test_stats.queue_callback_count++; + + /* Process the data (simulate work) */ + test_data_t* test_data = (test_data_t*)data; + ASSERT_TRUE(compute_checksum(test_data) == test_data->checksum, "Data corruption in callback"); + + /* Don't call resume_callback if this is the last test to avoid timer issues */ + if (*callback_count < 10) { /* Limit callbacks to prevent infinite loop */ + /* Simulate async processing by calling resume after a delay */ + queue_resume_callback(q); + } +} + +/* Waiter callback for testing */ +static void test_waiter_callback(struct ll_queue* q, void* arg) { + int* callback_count = (int*)arg; + (*callback_count)++; + test_stats.waiter_callback_count++; +} + + /* Test 1: Basic queue creation and destruction */ +static void test_basic_creation() { + TEST_START("Basic queue creation and destruction"); + + struct UASYNC* ua = uasync_create(); + ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + + /* Test with no hash table */ + struct ll_queue* q = queue_new(ua, 0); + ASSERT_NOT_NULL(q, "Failed to create queue"); + ASSERT_EQ(queue_entry_count(q), 0, "New queue should be empty"); + ASSERT_EQ(queue_total_bytes(q), 0, "New queue should have 0 bytes"); + + /* Test with hash table */ + struct ll_queue* q_hash = queue_new(ua, 16); + ASSERT_NOT_NULL(q_hash, "Failed to create queue with hash table"); + ASSERT_EQ(queue_entry_count(q_hash), 0, "New hash queue should be empty"); + + queue_free(q); + queue_free(q_hash); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 2: Data creation and basic operations */ +static void test_data_operations() { + TEST_START("Data creation and basic operations"); + + struct UASYNC* ua = uasync_create(); + struct ll_queue* q = queue_new(ua, 0); + + /* Create test data */ + test_data_t* data1 = (test_data_t*)queue_data_new(sizeof(test_data_t)); + ASSERT_NOT_NULL(data1, "Failed to create data"); + data1->id = 1; + strcpy(data1->name, "test1"); + data1->value = 100; + data1->checksum = compute_checksum(data1); + + /* Put data into queue */ + ASSERT_EQ(queue_data_put(q, data1, data1->id), 0, "Failed to put data"); + ASSERT_EQ(queue_entry_count(q), 1, "Queue should have 1 element"); + ASSERT_GE(queue_total_bytes(q), sizeof(test_data_t), "Queue should have at least data size"); + + /* Get data from queue */ + test_data_t* retrieved = (test_data_t*)queue_data_get(q); + ASSERT_NOT_NULL(retrieved, "Failed to get data"); + ASSERT_EQ(retrieved->id, 1, "Wrong data retrieved"); + ASSERT_STR_EQ(retrieved->name, "test1", "Wrong name retrieved"); + ASSERT_EQ(retrieved->value, 100, "Wrong value retrieved"); + ASSERT_EQ(retrieved->checksum, compute_checksum(retrieved), "Checksum mismatch"); + + /* Queue should be empty now */ + ASSERT_EQ(queue_entry_count(q), 0, "Queue should be empty after get"); + + /* Free the data */ + queue_data_free(retrieved); + + queue_free(q); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 3: FIFO ordering */ +static void test_fifo_ordering() { + TEST_START("FIFO ordering"); + + struct UASYNC* ua = uasync_create(); + struct ll_queue* q = queue_new(ua, 0); + + const int num_items = 10; + test_data_t* items[num_items]; + + /* Create and put items in order */ + for (int i = 0; i < num_items; i++) { + items[i] = (test_data_t*)queue_data_new(sizeof(test_data_t)); + items[i]->id = i; + snprintf(items[i]->name, sizeof(items[i]->name), "item_%d", i); + items[i]->value = i * 10; + items[i]->checksum = compute_checksum(items[i]); + + ASSERT_EQ(queue_data_put(q, items[i], items[i]->id), 0, "Failed to put data"); + } + + ASSERT_EQ(queue_entry_count(q), num_items, "Wrong item count"); + + /* Retrieve and verify FIFO order */ + for (int i = 0; i < num_items; i++) { + test_data_t* retrieved = (test_data_t*)queue_data_get(q); + ASSERT_NOT_NULL(retrieved, "Failed to get data"); + ASSERT_EQ(retrieved->id, i, "FIFO order violated"); + ASSERT_EQ(retrieved->value, i * 10, "Wrong value in FIFO"); + + queue_data_free(retrieved); + } + + ASSERT_EQ(queue_entry_count(q), 0, "Queue should be empty"); + + queue_free(q); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 4: LIFO operations with put_first */ +static void test_lifo_operations() { + TEST_START("LIFO operations with put_first"); + + struct UASYNC* ua = uasync_create(); + struct ll_queue* q = queue_new(ua, 0); + + /* Add some items normally (FIFO) */ + for (int i = 0; i < 3; i++) { + test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); + data->id = i; + snprintf(data->name, sizeof(data->name), "normal_%d", i); + data->value = i; + data->checksum = compute_checksum(data); + + ASSERT_EQ(queue_data_put(q, data, data->id), 0, "Failed to put data"); + } + + /* Add high priority item at the beginning */ + test_data_t* priority = (test_data_t*)queue_data_new(sizeof(test_data_t)); + priority->id = 999; + strcpy(priority->name, "priority"); + priority->value = 999; + priority->checksum = compute_checksum(priority); + + ASSERT_EQ(queue_data_put_first(q, priority, priority->id), 0, "Failed to put_first data"); + + /* First item out should be the priority one */ + test_data_t* first = (test_data_t*)queue_data_get(q); + ASSERT_NOT_NULL(first, "Failed to get data"); + ASSERT_EQ(first->id, 999, "Priority item should come first"); + ASSERT_STR_EQ(first->name, "priority", "Wrong priority item"); + queue_data_free(first); + + /* Remaining items should be in original FIFO order */ + for (int i = 0; i < 3; i++) { + test_data_t* retrieved = (test_data_t*)queue_data_get(q); + ASSERT_NOT_NULL(retrieved, "Failed to get data"); + ASSERT_EQ(retrieved->id, i, "FIFO order violated after priority"); + queue_data_free(retrieved); + } + + ASSERT_EQ(queue_entry_count(q), 0, "Queue should be empty"); + + queue_free(q); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 5: Callback system - basic */ +static void test_callback_basic() { + TEST_START("Callback system - basic"); + + struct UASYNC* ua = uasync_create(); + struct ll_queue* q = queue_new(ua, 0); + + int callback_count = 0; + queue_set_callback(q, test_queue_callback, &callback_count); + + /* Add first item - callback should be called */ + test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); + data->id = 1; + strcpy(data->name, "callback_test"); + data->value = 42; + data->checksum = compute_checksum(data); + + printf("\n Before put: queue_count=%d", queue_entry_count(q)); + ASSERT_EQ(queue_data_put(q, data, data->id), 0, "Failed to put data"); + printf(" After put: queue_count=%d", queue_entry_count(q)); + + /* Process events to trigger callback */ + for (int i = 0; i < 10; i++) { + uasync_poll(ua, 1); /* 0.1ms poll */ + printf(" After poll %d: queue_count=%d, callback_count=%d", i, queue_entry_count(q), callback_count); + } + + ASSERT_GE(callback_count, 1, "Callback should be called at least once"); + printf(" Final queue_count=%d", queue_entry_count(q)); + + /* IMPORTANT: элемент остается в очереди после callback, не освобождать вручную! */ + /* queue_free должна освободить оставшиеся элементы */ + + queue_free(q); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 6: Callback suspension and resumption */ +static void test_callback_suspension() { + TEST_START("Callback suspension and resumption"); + + struct UASYNC* ua = uasync_create(); + struct ll_queue* q = queue_new(ua, 0); + + int callback_count = 0; + queue_set_callback(q, test_queue_callback, &callback_count); + + /* Add multiple items quickly */ + for (int i = 0; i < 5; i++) { + test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); + data->id = i; + snprintf(data->name, sizeof(data->name), "item_%d", i); + data->value = i * 10; + data->checksum = compute_checksum(data); + + ASSERT_EQ(queue_data_put(q, data, data->id), 0, "Failed to put data"); + } + + /* Process events - callback should process items one by one */ + for (int i = 0; i < 50; i++) { + uasync_poll(ua, 1); + } + + /* Callback should have been called for each item */ + ASSERT_GE(callback_count, 1, "Callback should process items"); + + queue_free(q); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 7: Waiter mechanism - basic */ +static void test_waiter_basic() { + TEST_START("Waiter mechanism - basic"); + + struct UASYNC* ua = uasync_create(); + struct ll_queue* q = queue_new(ua, 0); + + int waiter_called = 0; + + /* Register waiter for empty queue - should trigger immediately */ + struct queue_waiter* waiter = queue_wait_threshold(q, 0, 0, test_waiter_callback, &waiter_called); + if (waiter_called == 1) { + /* Callback already called, waiter may be NULL or not */ + /* If waiter is not NULL, it might have been auto-freed, but we ignore */ + } else { + /* Callback not called yet */ + ASSERT_EQ(waiter_called, 0, "Callback should not be called yet"); + if (waiter != NULL) { + /* Waiter was created, callback should be called asynchronously */ + /* Process events to trigger callback */ + for (int i = 0; i < 10; i++) { + uasync_poll(ua, 1); + } + ASSERT_EQ(waiter_called, 1, "Waiter callback should be triggered asynchronously"); + } else { + /* No waiter created, but callback should have been called */ + TEST_FAIL("Expected waiter_called == 1 or waiter != NULL"); + } + } + + /* Reset and test with non-empty queue */ + waiter_called = 0; + + /* Add some items */ + for (int i = 0; i < 3; i++) { + test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); + data->id = i; + queue_data_put(q, data, data->id); + } + + /* Register waiter for threshold */ + waiter = queue_wait_threshold(q, 2, 0, test_waiter_callback, &waiter_called); + ASSERT_NOT_NULL(waiter, "Waiter should be registered when condition not met"); + ASSERT_EQ(waiter_called, 0, "Callback should not be called yet"); + + /* Remove items to reach threshold */ + for (int i = 0; i < 2; i++) { + test_data_t* data = (test_data_t*)queue_data_get(q); + ASSERT_NOT_NULL(data, "Failed to get data"); + queue_data_free(data); + } + + /* Process events to trigger waiter */ + for (int i = 0; i < 10; i++) { + uasync_poll(ua, 1); + } + + ASSERT_EQ(waiter_called, 1, "Waiter callback should be triggered"); + + queue_free(q); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 8: Waiter cancellation */ +static void test_waiter_cancellation() { + TEST_START("Waiter cancellation"); + + struct UASYNC* ua = uasync_create(); + struct ll_queue* q = queue_new(ua, 0); + + int waiter_called = 0; + + /* Add items */ + for (int i = 0; i < 5; i++) { + test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); + data->id = i; + queue_data_put(q, data, data->id); + } + + /* Register waiter */ + struct queue_waiter* waiter = queue_wait_threshold(q, 2, 0, test_waiter_callback, &waiter_called); + ASSERT_NOT_NULL(waiter, "Waiter should be registered"); + + /* Cancel the waiter */ + queue_cancel_wait(q, waiter); + + /* Reach the threshold - waiter should not be called */ + for (int i = 0; i < 3; i++) { + test_data_t* data = (test_data_t*)queue_data_get(q); + ASSERT_NOT_NULL(data, "Failed to get data"); + queue_data_free(data); + } + + /* Process events */ + for (int i = 0; i < 10; i++) { + uasync_poll(ua, 1); + } + + ASSERT_EQ(waiter_called, 0, "Cancelled waiter should not be called"); + + queue_free(q); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 9: Size limits */ +static void test_size_limits() { + TEST_START("Size limits"); + + struct UASYNC* ua = uasync_create(); + struct ll_queue* q = queue_new(ua, 0); + + /* Set size limit to 3 */ + queue_set_size_limit(q, 3); + + /* Add up to limit */ + for (int i = 0; i < 3; i++) { + test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); + data->id = i; + ASSERT_EQ(queue_data_put(q, data, data->id), 0, "Should accept items up to limit"); + } + + ASSERT_EQ(queue_entry_count(q), 3, "Queue should be at limit"); + + /* Try to add one more - should be rejected */ + test_data_t* excess = (test_data_t*)queue_data_new(sizeof(test_data_t)); + excess->id = 999; + ASSERT_EQ(queue_data_put(q, excess, excess->id), -1, "Should reject items beyond limit"); + + /* Excess data should be automatically freed by queue */ + /* We'll verify by checking memory consistency later */ + + /* Remove one item, should be able to add again */ + test_data_t* removed = (test_data_t*)queue_data_get(q); + ASSERT_NOT_NULL(removed, "Should get item"); + queue_data_free(removed); + + ASSERT_EQ(queue_entry_count(q), 2, "Queue should have 2 items"); + + test_data_t* new_data = (test_data_t*)queue_data_new(sizeof(test_data_t)); + new_data->id = 100; + ASSERT_EQ(queue_data_put(q, new_data, new_data->id), 0, "Should accept new item after removal"); + + ASSERT_EQ(queue_entry_count(q), 3, "Queue should be at limit again"); + + queue_free(q); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 10: Hash table operations (ID-based search) */ +static void test_hash_table_operations() { + TEST_START("Hash table operations (ID-based search)"); + + struct UASYNC* ua = uasync_create(); + /* Create queue with hash table size 16 */ + struct ll_queue* q = queue_new(ua, 16); + ASSERT_NOT_NULL(q, "Failed to create queue with hash table"); + + const int num_items = 10; + test_data_t* items[num_items]; + + /* Create items with known IDs */ + for (int i = 0; i < num_items; i++) { + items[i] = (test_data_t*)queue_data_new(sizeof(test_data_t)); + items[i]->id = i * 10 + 1; /* IDs: 1, 11, 21, ... */ + snprintf(items[i]->name, sizeof(items[i]->name), "item_%d", items[i]->id); + items[i]->value = i * 100; + items[i]->checksum = compute_checksum(items[i]); + + ASSERT_EQ(queue_data_put(q, items[i], items[i]->id), 0, "Failed to put data"); + } + + /* Find items by ID */ + for (int i = 0; i < num_items; i++) { + uint32_t target_id = i * 10 + 1; + test_data_t* found = (test_data_t*)queue_find_data_by_id(q, target_id); + ASSERT_NOT_NULL(found, "Failed to find item by ID"); + ASSERT_EQ(found->id, target_id, "Wrong item found"); + ASSERT_EQ(found->value, i * 100, "Wrong value in found item"); + } + + /* Test non-existent ID */ + test_data_t* not_found = (test_data_t*)queue_find_data_by_id(q, 99999); + ASSERT_NULL(not_found, "Should return NULL for non-existent ID"); + + /* Remove item by pointer */ + test_data_t* to_remove = (test_data_t*)queue_find_data_by_id(q, 21); /* Third item */ + ASSERT_NOT_NULL(to_remove, "Item to remove should exist"); + ASSERT_EQ(queue_remove_data(q, to_remove), 0, "Failed to remove data by pointer"); + + /* Verify removal */ + test_data_t* should_be_null = (test_data_t*)queue_find_data_by_id(q, 21); + ASSERT_NULL(should_be_null, "Removed item should not be found"); + ASSERT_EQ(queue_entry_count(q), num_items - 1, "Queue count should decrease"); + + /* Clean up remaining items */ + for (int i = 0; i < num_items; i++) { + if (i == 2) continue; /* Already removed */ + test_data_t* data = (test_data_t*)queue_data_get(q); + ASSERT_NOT_NULL(data, "Failed to get data"); + queue_data_free(data); + } + + queue_free(q); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 11: Memory pool integration */ +static void test_memory_pool_integration() { + TEST_START("Memory pool integration"); + + struct UASYNC* ua = uasync_create(); + + /* Create memory pool for test data (должен вмещать struct ll_entry + test_data_t) */ + struct memory_pool* pool = memory_pool_init(sizeof(struct ll_entry) + sizeof(test_data_t)); + ASSERT_NOT_NULL(pool, "Failed to create memory pool"); + + /* Create queue */ + struct ll_queue* q = queue_new(ua, 0); + ASSERT_NOT_NULL(q, "Failed to create queue"); + + /* Test basic pool operations */ + size_t initial_allocations = 0, initial_reuse = 0; + memory_pool_get_stats(pool, &initial_allocations, &initial_reuse); + + /* Create data from pool */ + test_data_t* data1 = (test_data_t*)queue_data_new_from_pool(pool); + ASSERT_NOT_NULL(data1, "Failed to create data from pool"); + + /* Check pool stats after allocation */ + size_t after_allocations = 0, after_reuse = 0; + memory_pool_get_stats(pool, &after_allocations, &after_reuse); + ASSERT_GT(after_allocations, initial_allocations, "Pool allocations should increase"); + + /* Initialize data */ + data1->id = 1; + strcpy(data1->name, "pool_test_1"); + data1->value = 100; + data1->checksum = compute_checksum(data1); + + /* Put data in queue */ + ASSERT_EQ(queue_data_put(q, data1, data1->id), 0, "Failed to put pooled data"); + ASSERT_EQ(queue_entry_count(q), 1, "Queue should have 1 element"); + + /* Create more data from pool */ + test_data_t* data2 = (test_data_t*)queue_data_new_from_pool(pool); + ASSERT_NOT_NULL(data2, "Failed to create second data from pool"); + data2->id = 2; + strcpy(data2->name, "pool_test_2"); + data2->value = 200; + data2->checksum = compute_checksum(data2); + + ASSERT_EQ(queue_data_put(q, data2, data2->id), 0, "Failed to put second pooled data"); + ASSERT_EQ(queue_entry_count(q), 2, "Queue should have 2 elements"); + + /* Retrieve and free data (should go back to pool) */ + test_data_t* retrieved1 = (test_data_t*)queue_data_get(q); + ASSERT_NOT_NULL(retrieved1, "Failed to get first data"); + ASSERT_EQ(retrieved1->id, 1, "Wrong data retrieved"); + + /* Check pool stats before free */ + size_t before_free_allocations = 0, before_free_reuse = 0; + memory_pool_get_stats(pool, &before_free_allocations, &before_free_reuse); + + /* Free data (should return to pool) */ + queue_data_free(retrieved1); + + /* Check pool stats after free */ + size_t after_free_allocations = 0, after_free_reuse = 0; + memory_pool_get_stats(pool, &after_free_allocations, &after_free_reuse); + printf("\n Pool stats: before_free=(alloc=%zu, reuse=%zu), after_free=(alloc=%zu, reuse=%zu)", + before_free_allocations, before_free_reuse, after_free_allocations, after_free_reuse); + ASSERT_EQ(after_free_allocations, before_free_allocations, "Allocations should not change after free"); + /* Note: reuse count may not increase if pool implementation is different */ + if (after_free_reuse > before_free_reuse) { + printf(" ✓ Reuse increased as expected"); + } else { + printf(" ⚠ Reuse did not increase (may be expected behavior)"); + } + + /* Create another data (should reuse from pool) */ + test_data_t* data3 = (test_data_t*)queue_data_new_from_pool(pool); + ASSERT_NOT_NULL(data3, "Failed to create third data from pool"); + + /* Check reuse stats */ + size_t final_allocations = 0, final_reuse = 0; + memory_pool_get_stats(pool, &final_allocations, &final_reuse); + printf("\n Pool stats: final=(alloc=%zu, reuse=%zu)", final_allocations, final_reuse); + ASSERT_EQ(final_allocations, after_free_allocations, "No new allocations for reused data"); + /* Note: reuse behavior depends on pool implementation */ + if (final_reuse > after_free_reuse) { + printf(" ✓ Final reuse increased"); + } else { + printf(" ⚠ Final reuse did not increase (implementation dependent)"); + } + + /* Clean up data3 */ + queue_data_free(data3); + + /* Clean up remaining data */ + test_data_t* retrieved2 = (test_data_t*)queue_data_get(q); + if (retrieved2) { + queue_data_free(retrieved2); + } + + queue_free(q); + memory_pool_destroy(pool); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 12: Edge cases and error handling */ +static void test_edge_cases() { + TEST_START("Edge cases and error handling"); + + /* Test NULL parameters */ + ASSERT_NULL(queue_new(NULL, 0), "Should return NULL for NULL uasync"); + + struct UASYNC* ua = uasync_create(); + struct ll_queue* q = queue_new(ua, 0); + + /* Test NULL queue operations */ + queue_set_callback(NULL, NULL, NULL); /* Should not crash */ + queue_resume_callback(NULL); + queue_set_size_limit(NULL, 10); + + ASSERT_NULL(queue_data_get(NULL), "Should return NULL for NULL queue"); + ASSERT_EQ(queue_data_put(NULL, NULL, 0), -1, "Should fail for NULL queue"); + ASSERT_EQ(queue_data_put_first(NULL, NULL, 0), -1, "Should fail for NULL queue"); + + ASSERT_EQ(queue_entry_count(NULL), 0, "Should return 0 for NULL queue"); + ASSERT_EQ(queue_total_bytes(NULL), 0, "Should return 0 for NULL queue"); + + ASSERT_NULL(queue_find_data_by_id(NULL, 0), "Should return NULL for NULL queue"); + ASSERT_EQ(queue_remove_data(NULL, NULL), -1, "Should fail for NULL queue"); + + /* Test with zero-sized data */ + void* zero_data = queue_data_new(0); + ASSERT_NOT_NULL(zero_data, "Should handle zero-sized data"); + ASSERT_EQ(queue_data_put(q, zero_data, 1), 0, "Should accept zero-sized data"); + ASSERT_EQ(queue_entry_count(q), 1, "Should count zero-sized data"); + + void* retrieved = queue_data_get(q); + ASSERT_NOT_NULL(retrieved, "Should retrieve zero-sized data"); + queue_data_free(retrieved); + + /* Test adding multiple items with different IDs */ + test_data_t* data1 = (test_data_t*)queue_data_new(sizeof(test_data_t)); + data1->id = 100; + ASSERT_EQ(queue_data_put(q, data1, data1->id), 0, "Should accept first item with ID"); + + test_data_t* data2 = (test_data_t*)queue_data_new(sizeof(test_data_t)); + data2->id = 101; /* Different ID */ + ASSERT_EQ(queue_data_put(q, data2, data2->id), 0, "Should accept second item with different ID"); + + /* Both items should be findable */ + test_data_t* found1 = (test_data_t*)queue_find_data_by_id(q, 100); + test_data_t* found2 = (test_data_t*)queue_find_data_by_id(q, 101); + /* Note: find only works if queue was created with hash_size > 0 */ + /* If hash_size == 0, find will return NULL, which is acceptable */ + /* We'll just clean up regardless */ + + /* Clean up */ + test_data_t* d1 = (test_data_t*)queue_data_get(q); + test_data_t* d2 = (test_data_t*)queue_data_get(q); + if (d1) queue_data_free(d1); + if (d2) queue_data_free(d2); + + queue_free(q); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 13: Stress test - high volume operations */ +static void test_stress_high_volume() { + TEST_START("Stress test - high volume operations"); + + double start_time = get_time_ms(); + + struct UASYNC* ua = uasync_create(); + struct ll_queue* q = queue_new(ua, 64); /* With hash table */ + + const int num_operations = 10000; + const int max_queue_size = 100; + + srand(time(NULL)); + + for (int i = 0; i < num_operations; i++) { + int op = rand() % 100; + + if (op < 40) { /* 40%: Add to tail */ + if (queue_entry_count(q) < max_queue_size) { + test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); + if (data) { + data->id = rand() % 1000; + data->value = rand(); + data->checksum = compute_checksum(data); + queue_data_put(q, data, data->id); + test_stats.total_operations++; + } + } + } else if (op < 60) { /* 20%: Add to head (priority) */ + if (queue_entry_count(q) < max_queue_size) { + test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); + if (data) { + data->id = rand() % 1000; + data->value = rand(); + data->checksum = compute_checksum(data); + queue_data_put_first(q, data, data->id); + test_stats.total_operations++; + } + } + } else if (op < 80) { /* 20%: Remove from head */ + test_data_t* data = (test_data_t*)queue_data_get(q); + if (data) { + if (data->checksum != compute_checksum(data)) { + test_stats.memory_errors++; + } + queue_data_free(data); + test_stats.total_operations++; + } + } else if (op < 90) { /* 10%: Find by ID */ + uint32_t search_id = rand() % 1000; + test_data_t* found = (test_data_t*)queue_find_data_by_id(q, search_id); + if (found) { + if (found->checksum != compute_checksum(found)) { + test_stats.hash_table_errors++; + } + test_stats.total_operations++; + } + } else { /* 10%: Remove by pointer */ + if (queue_entry_count(q) > 0) { + /* Find random item to remove */ + int target_idx = rand() % queue_entry_count(q); + struct ll_entry* curr = q->head; + for (int j = 0; j < target_idx && curr; j++) { + curr = curr->next; + } + if (curr) { + test_data_t* data = (test_data_t*)(curr->payload); + if (queue_remove_data(q, data) == 0) { + queue_data_free(data); + test_stats.total_operations++; + } + } + } + } + + /* Periodic integrity check */ + if (i % 1000 == 0) { + /* Verify doubly-linked list integrity */ + int count = 0; + struct ll_entry* curr = q->head; + struct ll_entry* prev = NULL; + while (curr) { + count++; + if (curr->prev != prev) { + test_stats.memory_errors++; + } + if (prev && prev->next != curr) { + test_stats.memory_errors++; + } + prev = curr; + curr = curr->next; + } + if (count != queue_entry_count(q)) { + test_stats.memory_errors++; + } + + /* Verify hash table integrity */ + for (uint32_t id = 0; id < 1000; id += 10) { + test_data_t* found = (test_data_t*)queue_find_data_by_id(q, id); + if (found) { + /* Verify the found item is actually in the queue */ + int found_in_list = 0; + curr = q->head; + while (curr) { + if ((test_data_t*)(curr->payload) == found) { + found_in_list = 1; + break; + } + curr = curr->next; + } + if (!found_in_list) { + test_stats.hash_table_errors++; + } + } + } + } + } + + double end_time = get_time_ms(); + test_stats.total_time_ms += (end_time - start_time); + + /* Clean up remaining items */ + while (queue_entry_count(q) > 0) { + test_data_t* data = (test_data_t*)queue_data_get(q); + if (data) queue_data_free(data); + } + + ASSERT_EQ(test_stats.memory_errors, 0, "Memory corruption detected during stress test"); + ASSERT_EQ(test_stats.hash_table_errors, 0, "Hash table corruption detected"); + ASSERT_TRUE(test_stats.total_operations > num_operations / 2, "Too few operations performed"); + + printf("\n Operations: %ld, Time: %.2f ms, Ops/sec: %.2f", + test_stats.total_operations, end_time - start_time, + test_stats.total_operations * 1000.0 / (end_time - start_time)); + + queue_free(q); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 15: Memory pool stress test */ +static void test_memory_pool_stress() { + TEST_START("Memory pool stress test"); + + struct UASYNC* ua = uasync_create(); + + /* Create memory pool (должен вмещать struct ll_entry + test_data_t) */ + struct memory_pool* pool = memory_pool_init(sizeof(struct ll_entry) + sizeof(test_data_t)); + ASSERT_NOT_NULL(pool, "Failed to create memory pool"); + + /* Create queue */ + struct ll_queue* q = queue_new(ua, 0); + ASSERT_NOT_NULL(q, "Failed to create queue"); + + const int iterations = 1000; + test_data_t* items[iterations]; + + /* Stress test: allocate and free many items */ + size_t initial_allocations = 0, initial_reuse = 0; + memory_pool_get_stats(pool, &initial_allocations, &initial_reuse); + + /* Allocate many items from pool */ + for (int i = 0; i < iterations; i++) { + items[i] = (test_data_t*)queue_data_new_from_pool(pool); + ASSERT_NOT_NULL(items[i], "Failed to allocate from pool"); + + items[i]->id = i; + snprintf(items[i]->name, sizeof(items[i]->name), "stress_%d", i); + items[i]->value = i * 10; + items[i]->checksum = compute_checksum(items[i]); + } + + /* Check allocations increased */ + size_t after_allocations = 0, after_reuse = 0; + memory_pool_get_stats(pool, &after_allocations, &after_reuse); + ASSERT_GT(after_allocations, initial_allocations, "Pool allocations should increase"); + + /* Put all items in queue */ + for (int i = 0; i < iterations; i++) { + ASSERT_EQ(queue_data_put(q, items[i], items[i]->id), 0, "Failed to put stress data"); + } + ASSERT_EQ(queue_entry_count(q), iterations, "Queue should have all stress items"); + + /* Remove half of items */ + for (int i = 0; i < iterations / 2; i++) { + test_data_t* retrieved = (test_data_t*)queue_data_get(q); + ASSERT_NOT_NULL(retrieved, "Failed to get stress data"); + queue_data_free(retrieved); /* Should return to pool */ + } + + /* Check reuse count increased */ + size_t after_free_allocations = 0, after_free_reuse = 0; + memory_pool_get_stats(pool, &after_free_allocations, &after_free_reuse); + ASSERT_EQ(after_free_allocations, after_allocations, "Pool allocations should not change"); + /* Note: reuse count may not increase if pool implementation is different - skip check in stress test */ + + /* Final stats check */ + size_t final_allocations = 0, final_reuse = 0; + memory_pool_get_stats(pool, &final_allocations, &final_reuse); + printf("\n Final pool stats: allocations=%zu, reuse=%zu", final_allocations, final_reuse); + + /* Should not allocate more than initial pool size */ + ASSERT_LE(final_allocations, after_allocations + 50, "Should not allocate much more than initial"); + /* Note: reuse behavior depends on pool implementation and usage patterns - skip strict check for stress test */ + + /* Clean up remaining items */ + while (queue_entry_count(q) > 0) { + test_data_t* retrieved = (test_data_t*)queue_data_get(q); + if (retrieved) { + queue_data_free(retrieved); + } + } + + queue_free(q); + memory_pool_destroy(pool); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 16: Memory pool vs malloc performance comparison */ +static void test_memory_pool_vs_malloc_performance() { + TEST_START("Memory pool vs malloc performance comparison"); + + struct UASYNC* ua = uasync_create(); + + /* Create memory pool (должен вмещать struct ll_entry + test_data_t) */ + struct memory_pool* pool = memory_pool_init(sizeof(struct ll_entry) + sizeof(test_data_t)); + ASSERT_NOT_NULL(pool, "Failed to create memory pool"); + + /* Create queue */ + struct ll_queue* q = queue_new(ua, 0); + ASSERT_NOT_NULL(q, "Failed to create queue"); + + const int iterations = 5000; + + /* Benchmark pool allocation */ + double pool_start = get_time_ms(); + + for (int i = 0; i < iterations; i++) { + test_data_t* data = (test_data_t*)queue_data_new_from_pool(pool); + if (data) { + data->id = i; + data->value = i * 10; + data->checksum = compute_checksum(data); + queue_data_put(q, data, data->id); + queue_data_free((test_data_t*)queue_data_get(q)); + } + } + + double pool_time = get_time_ms() - pool_start; + + /* Benchmark malloc allocation */ + double malloc_start = get_time_ms(); + + for (int i = 0; i < iterations; i++) { + test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); + if (data) { + data->id = i; + data->value = i * 10; + data->checksum = compute_checksum(data); + queue_data_put(q, data, data->id); + queue_data_free((test_data_t*)queue_data_get(q)); + } + } + + double malloc_time = get_time_ms() - malloc_start; + + /* Performance comparison */ + printf("\n Pool time: %.3f ms (%.1f ops/sec)", pool_time, iterations * 1000.0 / pool_time); + printf("\n Malloc time: %.3f ms (%.1f ops/sec)", malloc_time, iterations * 1000.0 / malloc_time); + + if (pool_time < malloc_time) { + double speedup = malloc_time / pool_time; + printf("\n Pool is %.2fx faster than malloc", speedup); + } else { + double slowdown = pool_time / malloc_time; + printf("\n Pool is %.2fx slower than malloc", slowdown); + } + + /* Pool should generally be faster or comparable */ + ASSERT_TRUE(pool_time <= malloc_time * 1.5, "Pool should not be significantly slower than malloc"); + + /* Check final pool stats */ + size_t final_allocations = 0, final_reuse = 0; + memory_pool_get_stats(pool, &final_allocations, &final_reuse); + + printf("\n Pool stats: allocations=%zu, reuse=%zu", final_allocations, final_reuse); + ASSERT_GT(final_reuse, iterations * 0.8, "High reuse rate expected"); + + queue_free(q); + memory_pool_destroy(pool); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 14: Reference counting validation */ +static void test_reference_counting() { + TEST_START("Reference counting validation"); + + struct UASYNC* ua = uasync_create(); + struct ll_queue* q = queue_new(ua, 16); /* With hash table for ID lookup */ + + /* Create data and put it in queue */ + test_data_t* data = (test_data_t*)queue_data_new(sizeof(test_data_t)); + data->id = 1; + data->value = 42; + data->checksum = compute_checksum(data); + + /* Get the ll_entry pointer for inspection */ + struct ll_entry* entry = (struct ll_entry*)((char*)data - sizeof(struct ll_entry)); + ASSERT_EQ(entry->ref_count, 1, "New entry should have ref_count = 1"); + + /* Put in queue - ref_count НЕ изменяется в новой архитектуре */ + ASSERT_EQ(queue_data_put(q, data, data->id), 0, "Failed to put data"); + ASSERT_EQ(entry->ref_count, 1, "Entry in queue should still have ref_count = 1 (new architecture)"); + + /* Find by ID - should not change ref_count */ + test_data_t* found = (test_data_t*)queue_find_data_by_id(q, 1); + ASSERT_NOT_NULL(found, "Should find data"); + ASSERT_EQ(entry->ref_count, 1, "Find should not change ref_count"); + + /* Get from queue - ref_count НЕ изменяется в новой архитектуре */ + test_data_t* retrieved = (test_data_t*)queue_data_get(q); + ASSERT_NOT_NULL(retrieved, "Should retrieve data"); + ASSERT_EQ(entry->ref_count, 1, "Get should not change ref_count (new architecture)"); + + /* Free data - should decrement to 0 and free memory */ + queue_data_free(retrieved); + /* Can't check ref_count after free */ + + queue_free(q); + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Main test runner */ +int main() { + printf("=== ll_queue Comprehensive Tests with Current API ===\n"); + printf("Starting tests...\n\n"); + + /* Initialize debug system */ + debug_config_init(); + debug_set_level(DEBUG_LEVEL_DEBUG); + debug_set_categories(DEBUG_CATEGORY_LL_QUEUE); + + double suite_start_time = get_time_ms(); + + /* Run all tests */ + test_basic_creation(); + test_data_operations(); + test_fifo_ordering(); + test_lifo_operations(); + test_callback_basic(); + test_callback_suspension(); + test_waiter_basic(); + test_waiter_cancellation(); + test_size_limits(); + test_hash_table_operations(); + test_memory_pool_integration(); + test_edge_cases(); + test_stress_high_volume(); + test_reference_counting(); + test_memory_pool_stress(); + test_memory_pool_vs_malloc_performance(); + + double suite_end_time = get_time_ms(); + + printf("\n=== Test Suite Summary ===\n"); + printf("Tests run: %d\n", test_stats.tests_run); + printf("Tests passed: %d\n", test_stats.tests_passed); + printf("Tests failed: %d\n", test_stats.tests_failed); + printf("\nError Statistics:\n"); + printf(" Memory errors: %d\n", test_stats.memory_errors); + printf(" Hash table errors: %d\n", test_stats.hash_table_errors); + printf(" Reference count errors: %d\n", test_stats.ref_count_errors); + printf("\nPerformance:\n"); + printf(" Total operations: %ld\n", test_stats.total_operations); + printf(" Total time: %.2f ms\n", test_stats.total_time_ms); + if (test_stats.total_time_ms > 0) { + printf(" Average ops/sec: %.2f\n", test_stats.total_operations * 1000.0 / test_stats.total_time_ms); + } + printf("\nCallback Statistics:\n"); + printf(" Queue callbacks: %d\n", test_stats.queue_callback_count); + printf(" Waiter callbacks: %d\n", test_stats.waiter_callback_count); + + if (test_stats.tests_failed == 0 && test_stats.memory_errors == 0 && + test_stats.hash_table_errors == 0 && test_stats.ref_count_errors == 0) { + printf("\n✅ ALL TESTS PASSED - ll_queue implementation is robust!\n"); + return 0; + } else { + printf("\n❌ TEST FAILURES DETECTED - Review implementation\n"); + return 1; + } +} \ No newline at end of file diff --git a/tests/test_memory_pool_and_config b/tests/test_memory_pool_and_config deleted file mode 100755 index 5e1a30809..000000000 Binary files a/tests/test_memory_pool_and_config and /dev/null differ diff --git a/tests/test_memory_pool_and_config.c b/tests/test_memory_pool_and_config.c index e11cc8036..1a1ccb648 100644 --- a/tests/test_memory_pool_and_config.c +++ b/tests/test_memory_pool_and_config.c @@ -1,6 +1,6 @@ /** - * Test for memory pool optimization and configuration file support - */ +* Test for memory pool optimization and configuration file support +*/ #include #include @@ -16,118 +16,121 @@ static int test_callback_count = 0; static void test_callback(struct ll_queue* q, void* data, void* arg) { - (void)q; (void)data; (void)arg; - test_callback_count++; +(void)q; (void)data; (void)arg; +test_callback_count++; } static void test_waiter_callback(struct ll_queue* q, void* arg) { - (void)q; (void)arg; - test_callback_count++; +(void)q; (void)arg; +test_callback_count++; } int main() { - printf("=== Memory Pool and Config File Test ===\n"); - - // Test 1: Memory pool optimization - printf("Test 1: Memory pool optimization...\n"); - - uasync_t* ua = uasync_create(); - if (!ua) { - printf("Failed to create uasync\n"); - return 1; - } - - // Create queue with memory pools enabled - struct ll_queue* queue = queue_new(ua, 0); - if (!queue) { - printf("Failed to create queue with pools\n"); - uasync_destroy(ua, 0); - return 1; - } - - // Test multiple waiter allocations to trigger pool usage - struct queue_waiter* waiters[10]; - for (int i = 0; i < 10; i++) { - waiters[i] = queue_wait_threshold(queue, i * 2, 0, test_waiter_callback, NULL); - } - - // Add some entries and trigger waiters - for (int i = 0; i < 5; i++) { - void* data = queue_data_new(10); - queue_data_put(queue, data, i); // Используем ID = i - } - - // Remove entries to trigger waiter callbacks - for (int i = 0; i < 5; i++) { - void* retrieved = queue_data_get(queue); - if (retrieved) { - queue_data_free(retrieved); - } - } - - // Cancel remaining waiters - for (int i = 0; i < 10; i++) { - if (waiters[i]) { - queue_cancel_wait(queue, waiters[i]); - } - } - - // Get pool statistics - size_t allocations, reuse_count; - - printf("Pool statistics: allocations=%zu, reuse_count=%zu\n", allocations, reuse_count); - printf("Pool efficiency: %.1f%%\n", - allocations > 0 ? (100.0 * reuse_count / allocations) : 0.0); - - queue_free(queue); - uasync_destroy(ua, 0); - - printf("Memory pool test: PASS\n\n"); - - // Test 2: Configuration file support - printf("Test 2: Configuration file support...\n"); - - // Create a test configuration file - const char* config_file = "/tmp/debug_test.conf"; - FILE* f = fopen(config_file, "w"); - if (f) { - fprintf(f, "# Test debug configuration file\n"); - fprintf(f, "ll_queue:debug\n"); - fprintf(f, "uasync:info\n"); - fprintf(f, "memory:warn\n"); - fprintf(f, "# This is a comment\n"); - fprintf(f, "etcp:error\n"); - fclose(f); - - // Parse the configuration string (we don't have file parsing, so use string parsing) - const char* config_string = "ll_queue:debug,uasync:info,memory:warn,etcp:error"; - if (debug_parse_config(config_string) == 0) { - printf("Configuration parsed successfully\n"); - - // Test that configuration was applied - if (debug_should_output(DEBUG_LEVEL_DEBUG, DEBUG_CATEGORY_LL_QUEUE)) { - printf("LL_QUEUE debug level correctly set\n"); - } - if (debug_should_output(DEBUG_LEVEL_INFO, DEBUG_CATEGORY_UASYNC)) { - printf("UASYNC info level correctly set\n"); - } - if (!debug_should_output(DEBUG_LEVEL_DEBUG, DEBUG_CATEGORY_ETCP)) { - printf("ETCP correctly limited to error level\n"); - } - - printf("Note: Hot reload functionality not implemented in current debug system\n"); - - } else { - printf("Failed to parse configuration\n"); - } - - unlink(config_file); - } else { - printf("Failed to create test configuration file\n"); - } - - printf("Configuration file test: PASS\n"); - - printf("\n=== All tests completed successfully ===\n"); - return 0; + +debug_config_init(); +debug_set_level(DEBUG_LEVEL_TRACE); +debug_set_categories(DEBUG_CATEGORY_ALL); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "=== Memory Pool and Config File Test ==="); + +// Test 1: Memory pool optimization +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Test 1: Memory pool optimization..."); + +uasync_t* ua = uasync_create(); +if (!ua) { +DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Failed to create uasync"); +return 1; +} + +// Create queue with memory pools enabled +struct ll_queue* queue = queue_new(ua, 0); +if (!queue) { +DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Failed to create queue with pools"); +uasync_destroy(ua, 0); +return 1; +} + +// Test multiple waiter allocations to trigger pool usage +struct queue_waiter* waiters[10]; +for (int i = 0; i < 10; i++) { +waiters[i] = queue_wait_threshold(queue, i * 2, 0, test_waiter_callback, NULL); +} + +// Add some entries and trigger waiters +for (int i = 0; i < 5; i++) { +void* data = queue_data_new(10); +queue_data_put(queue, data, i); // Используем ID = i +} + +// Remove entries to trigger waiter callbacks +for (int i = 0; i < 5; i++) { +void* retrieved = queue_data_get(queue); +if (retrieved) { +queue_data_free(retrieved); +} +} + +// Cancel remaining waiters +for (int i = 0; i < 10; i++) { +if (waiters[i]) { +queue_cancel_wait(queue, waiters[i]); +} +} + +// Get pool statistics +size_t allocations, reuse_count; + +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Pool statistics: allocations=%zu, reuse_count=%zu", allocations, reuse_count); +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Pool efficiency: %.1f%%", allocations > 0 ? (100.0 * reuse_count / allocations) : 0.0); + +queue_free(queue); +uasync_destroy(ua, 0); + +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Memory pool test: PASS\n"); + +// Test 2: Configuration file support +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Test 2: Configuration file support..."); + +// Create a test configuration file +const char* config_file = "/tmp/debug_test.conf"; +FILE* f = fopen(config_file, "w"); +if (f) { +fprintf(f, "# Test debug configuration file\n"); +fprintf(f, "ll_queue:debug\n"); +fprintf(f, "uasync:info\n"); +fprintf(f, "memory:warn\n"); +fprintf(f, "# This is a comment\n"); +fprintf(f, "etcp:error\n"); +fclose(f); + +// Parse the configuration string (we don't have file parsing, so use string parsing) +const char* config_string = "ll_queue:debug,uasync:info,memory:warn,etcp:error"; +if (debug_parse_config(config_string) == 0) { +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Configuration parsed successfully"); + +// Test that configuration was applied +if (debug_should_output(DEBUG_LEVEL_DEBUG, DEBUG_CATEGORY_LL_QUEUE)) { +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "LL_QUEUE debug level correctly set"); +} +if (debug_should_output(DEBUG_LEVEL_INFO, DEBUG_CATEGORY_UASYNC)) { +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "UASYNC info level correctly set"); +} +if (!debug_should_output(DEBUG_LEVEL_DEBUG, DEBUG_CATEGORY_ETCP)) { +DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "ETCP correctly limited to error level"); +} + +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Note: Hot reload functionality not implemented in current debug system"); + +} else { +DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Failed to parse configuration"); +} + +unlink(config_file); +} else { +DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Failed to create test configuration file"); +} + +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "Configuration file test: PASS"); + +DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "\n=== All tests completed successfully ==="); +return 0; } \ No newline at end of file diff --git a/tests/test_memory_pool_and_config.c.backup b/tests/test_memory_pool_and_config.c.backup new file mode 100644 index 000000000..e11cc8036 --- /dev/null +++ b/tests/test_memory_pool_and_config.c.backup @@ -0,0 +1,133 @@ +/** + * Test for memory pool optimization and configuration file support + */ + +#include +#include +#include +#include +#include + +#include "../lib/ll_queue.h" +#include "../lib/memory_pool.h" +#include "../lib/u_async.h" +#include "../lib/debug_config.h" + +static int test_callback_count = 0; + +static void test_callback(struct ll_queue* q, void* data, void* arg) { + (void)q; (void)data; (void)arg; + test_callback_count++; +} + +static void test_waiter_callback(struct ll_queue* q, void* arg) { + (void)q; (void)arg; + test_callback_count++; +} + +int main() { + printf("=== Memory Pool and Config File Test ===\n"); + + // Test 1: Memory pool optimization + printf("Test 1: Memory pool optimization...\n"); + + uasync_t* ua = uasync_create(); + if (!ua) { + printf("Failed to create uasync\n"); + return 1; + } + + // Create queue with memory pools enabled + struct ll_queue* queue = queue_new(ua, 0); + if (!queue) { + printf("Failed to create queue with pools\n"); + uasync_destroy(ua, 0); + return 1; + } + + // Test multiple waiter allocations to trigger pool usage + struct queue_waiter* waiters[10]; + for (int i = 0; i < 10; i++) { + waiters[i] = queue_wait_threshold(queue, i * 2, 0, test_waiter_callback, NULL); + } + + // Add some entries and trigger waiters + for (int i = 0; i < 5; i++) { + void* data = queue_data_new(10); + queue_data_put(queue, data, i); // Используем ID = i + } + + // Remove entries to trigger waiter callbacks + for (int i = 0; i < 5; i++) { + void* retrieved = queue_data_get(queue); + if (retrieved) { + queue_data_free(retrieved); + } + } + + // Cancel remaining waiters + for (int i = 0; i < 10; i++) { + if (waiters[i]) { + queue_cancel_wait(queue, waiters[i]); + } + } + + // Get pool statistics + size_t allocations, reuse_count; + + printf("Pool statistics: allocations=%zu, reuse_count=%zu\n", allocations, reuse_count); + printf("Pool efficiency: %.1f%%\n", + allocations > 0 ? (100.0 * reuse_count / allocations) : 0.0); + + queue_free(queue); + uasync_destroy(ua, 0); + + printf("Memory pool test: PASS\n\n"); + + // Test 2: Configuration file support + printf("Test 2: Configuration file support...\n"); + + // Create a test configuration file + const char* config_file = "/tmp/debug_test.conf"; + FILE* f = fopen(config_file, "w"); + if (f) { + fprintf(f, "# Test debug configuration file\n"); + fprintf(f, "ll_queue:debug\n"); + fprintf(f, "uasync:info\n"); + fprintf(f, "memory:warn\n"); + fprintf(f, "# This is a comment\n"); + fprintf(f, "etcp:error\n"); + fclose(f); + + // Parse the configuration string (we don't have file parsing, so use string parsing) + const char* config_string = "ll_queue:debug,uasync:info,memory:warn,etcp:error"; + if (debug_parse_config(config_string) == 0) { + printf("Configuration parsed successfully\n"); + + // Test that configuration was applied + if (debug_should_output(DEBUG_LEVEL_DEBUG, DEBUG_CATEGORY_LL_QUEUE)) { + printf("LL_QUEUE debug level correctly set\n"); + } + if (debug_should_output(DEBUG_LEVEL_INFO, DEBUG_CATEGORY_UASYNC)) { + printf("UASYNC info level correctly set\n"); + } + if (!debug_should_output(DEBUG_LEVEL_DEBUG, DEBUG_CATEGORY_ETCP)) { + printf("ETCP correctly limited to error level\n"); + } + + printf("Note: Hot reload functionality not implemented in current debug system\n"); + + } else { + printf("Failed to parse configuration\n"); + } + + unlink(config_file); + } else { + printf("Failed to create test configuration file\n"); + } + + printf("Configuration file test: PASS\n"); + + printf("\n=== All tests completed successfully ===\n"); + return 0; +} \ No newline at end of file diff --git a/tests/test_packet_dump b/tests/test_packet_dump deleted file mode 100755 index 294aeec86..000000000 Binary files a/tests/test_packet_dump and /dev/null differ diff --git a/tests/test_packet_dump.c b/tests/test_packet_dump.c index 01aed248d..0b2281b2a 100644 --- a/tests/test_packet_dump.c +++ b/tests/test_packet_dump.c @@ -4,19 +4,23 @@ // Simple test packet dump void test_packet_dump() { - uint8_t test_data[] = {0x02, 0x11, 0x22, 0x33, 0x44, 0x55}; - - // Simulate single-line packet dump - char hex_buf[32]; - snprintf(hex_buf, sizeof(hex_buf), "%02x%02x%02x%02x%02x%02x", - test_data[0], test_data[1], test_data[2], test_data[3], test_data[4], test_data[5]); - - printf("[ETCP] TEST_SEND: len=%zu hex=%s\n", sizeof(test_data), hex_buf); - printf("[ETCP] TEST_COMPACT: link=NULL type=0x%02x ts=0 len=%zu\n", test_data[0], sizeof(test_data)); +uint8_t test_data[] = {0x02, 0x11, 0x22, 0x33, 0x44, 0x55}; + +// Simulate single-line packet dump +char hex_buf[32]; +snprintf(hex_buf, sizeof(hex_buf), "%02x%02x%02x%02x%02x%02x", +test_data[0], test_data[1], test_data[2], test_data[3], test_data[4], test_data[5]); + +DEBUG_INFO(DEBUG_CATEGORY_ALL, "[ETCP] TEST_SEND: len=%zu hex=%s", sizeof(test_data), hex_buf); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "[ETCP] TEST_COMPACT: link=NULL type=0x%02x ts=0 len=%zu", test_data[0], sizeof(test_data)); } int main() { - printf("=== Testing single-line packet dump ===\n"); - test_packet_dump(); - return 0; + +debug_config_init(); +debug_set_level(DEBUG_LEVEL_TRACE); +debug_set_categories(DEBUG_CATEGORY_ALL); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "=== Testing single-line packet dump ==="); +test_packet_dump(); +return 0; } diff --git a/tests/test_packet_dump.c.backup b/tests/test_packet_dump.c.backup new file mode 100644 index 000000000..01aed248d --- /dev/null +++ b/tests/test_packet_dump.c.backup @@ -0,0 +1,22 @@ +#include +#include +#include "../lib/debug_config.h" + +// Simple test packet dump +void test_packet_dump() { + uint8_t test_data[] = {0x02, 0x11, 0x22, 0x33, 0x44, 0x55}; + + // Simulate single-line packet dump + char hex_buf[32]; + snprintf(hex_buf, sizeof(hex_buf), "%02x%02x%02x%02x%02x%02x", + test_data[0], test_data[1], test_data[2], test_data[3], test_data[4], test_data[5]); + + printf("[ETCP] TEST_SEND: len=%zu hex=%s\n", sizeof(test_data), hex_buf); + printf("[ETCP] TEST_COMPACT: link=NULL type=0x%02x ts=0 len=%zu\n", test_data[0], sizeof(test_data)); +} + +int main() { + printf("=== Testing single-line packet dump ===\n"); + test_packet_dump(); + return 0; +} diff --git a/tests/test_u_async_comprehensive b/tests/test_u_async_comprehensive deleted file mode 100755 index fc328d464..000000000 Binary files a/tests/test_u_async_comprehensive and /dev/null differ diff --git a/tests/test_u_async_comprehensive.c b/tests/test_u_async_comprehensive.c index ff41faa82..727e919c2 100644 --- a/tests/test_u_async_comprehensive.c +++ b/tests/test_u_async_comprehensive.c @@ -1,9 +1,10 @@ /** - * Comprehensive unit tests for lib module - * Focus on: timers, sockets, error handling, race conditions - */ +* Comprehensive unit tests for lib module +* Focus on: timers, sockets, error handling, race conditions +*/ #include +#include "../lib/debug_config.h" #include #include #include @@ -14,480 +15,480 @@ #include #include -#include "u_async.h" -#include "timeout_heap.h" +#include "../lib/u_async.h" +#include "../lib/timeout_heap.h" /* Test statistics */ static struct { - int tests_run; - int tests_passed; - int tests_failed; - - /* Timer statistics */ - int timer_callbacks; - int timer_cancellations; - int immediate_timeouts; - - /* Socket statistics */ - int socket_events; - int socket_errors; - - /* Error statistics */ - int memory_allocation_errors; - int invalid_parameter_errors; - int race_condition_errors; +int tests_run; +int tests_passed; +int tests_failed; + +/* Timer statistics */ +int timer_callbacks; +int timer_cancellations; +int immediate_timeouts; + +/* Socket statistics */ +int socket_events; +int socket_errors; + +/* Error statistics */ +int memory_allocation_errors; +int invalid_parameter_errors; +int race_condition_errors; } test_stats = {0}; /* Test result tracking */ #define TEST_START(name) do { \ - printf("TEST: %s... ", name); \ - test_stats.tests_run++; \ +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "TEST: %s...", name); \ +test_stats.tests_run++; \ } while(0) #define TEST_PASS() do { \ - printf("PASS\n"); \ - test_stats.tests_passed++; \ +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "PASS"); \ +test_stats.tests_passed++; \ } while(0) #define TEST_FAIL(msg) do { \ - printf("FAIL: %s\n", msg); \ - test_stats.tests_failed++; \ +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "FAIL: %s", msg); \ +test_stats.tests_failed++; \ } while(0) #define ASSERT_TRUE(cond, msg) do { \ - if (!(cond)) { \ - TEST_FAIL(msg); \ - return; \ - } \ +if (!(cond)) { \ +TEST_FAIL(msg); \ +return; \ +} \ } while(0) #define ASSERT_FALSE(cond, msg) do { \ - if (cond) { \ - TEST_FAIL(msg); \ - return; \ - } \ +if (cond) { \ +TEST_FAIL(msg); \ +return; \ +} \ } while(0) #define ASSERT_EQ(a, b, msg) do { \ - if ((a) != (b)) { \ - TEST_FAIL(msg); \ - printf(" Expected: %ld, Got: %ld\n", (long)(b), (long)(a)); \ - return; \ - } \ +if ((a) != (b)) { \ +TEST_FAIL(msg); \ +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Expected: %ld, Got: %ld", (long)(b), (long)(a)); \ +return; \ +} \ } while(0) #define ASSERT_NE(a, b, msg) do { \ - if ((a) == (b)) { \ - TEST_FAIL(msg); \ - return; \ - } \ +if ((a) == (b)) { \ +TEST_FAIL(msg); \ +return; \ +} \ } while(0) #define ASSERT_NULL(ptr, msg) do { \ - if ((ptr) != NULL) { \ - TEST_FAIL(msg); \ - return; \ - } \ +if ((ptr) != NULL) { \ +TEST_FAIL(msg); \ +return; \ +} \ } while(0) #define ASSERT_NOT_NULL(ptr, msg) do { \ - if ((ptr) == NULL) { \ - TEST_FAIL(msg); \ - return; \ - } \ +if ((ptr) == NULL) { \ +TEST_FAIL(msg); \ +return; \ +} \ } while(0) /* Test context for callbacks */ typedef struct { - int callback_count; - int expected_count; - int callback_arg; - int timeout_ms; - uasync_t* ua; - void* timer_id; +int callback_count; +int expected_count; +int callback_arg; +int timeout_ms; +uasync_t* ua; +void* timer_id; } test_context_t; /* Timer callback for testing */ static void test_timer_callback(void* arg) { - test_context_t* ctx = (test_context_t*)arg; - ctx->callback_count++; - test_stats.timer_callbacks++; - - if (ctx->timeout_ms == 0) { - test_stats.immediate_timeouts++; - } +test_context_t* ctx = (test_context_t*)arg; +ctx->callback_count++; +test_stats.timer_callbacks++; + +if (ctx->timeout_ms == 0) { +test_stats.immediate_timeouts++; +} } /* Socket callback for testing */ static void test_socket_callback(int fd, void* arg) { - test_context_t* ctx = (test_context_t*)arg; - ctx->callback_count++; - test_stats.socket_events++; - (void)fd; /* unused */ +test_context_t* ctx = (test_context_t*)arg; +ctx->callback_count++; +test_stats.socket_events++; +(void)fd; /* unused */ } /* Error injection callback */ static void test_error_callback(void* arg) { - test_context_t* ctx = (test_context_t*)arg; - ctx->callback_count++; - - /* Simulate callback error */ - if (ctx->callback_arg == -1) { - test_stats.race_condition_errors++; - return; - } +test_context_t* ctx = (test_context_t*)arg; +ctx->callback_count++; + +/* Simulate callback error */ +if (ctx->callback_arg == -1) { +test_stats.race_condition_errors++; +return; +} } /* Test 1: Basic timer functionality */ static void test_basic_timers(void) { - TEST_START("Basic timer functionality"); - - uasync_t* ua = uasync_create(); - ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); - - test_context_t ctx = {0}; - ctx.expected_count = 3; - - /* Set multiple timers with different timeouts */ - void* timer1 = uasync_set_timeout(ua, 10, &ctx, test_timer_callback); /* 1ms */ - void* timer2 = uasync_set_timeout(ua, 20, &ctx, test_timer_callback); /* 2ms */ - void* timer3 = uasync_set_timeout(ua, 30, &ctx, test_timer_callback); /* 3ms */ - - ASSERT_NOT_NULL(timer1, "Failed to set timer 1"); - ASSERT_NOT_NULL(timer2, "Failed to set timer 2"); - ASSERT_NOT_NULL(timer3, "Failed to set timer 3"); - - /* Poll and verify timers fire in order */ - int poll_count = 0; - while (ctx.callback_count < ctx.expected_count && poll_count < 100) { - uasync_poll(ua, 10); /* 1ms poll */ - poll_count++; - } - - ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Not all timers fired"); - - /* Cleanup */ - uasync_destroy(ua, 0); - TEST_PASS(); +TEST_START("Basic timer functionality"); + +uasync_t* ua = uasync_create(); +ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + +test_context_t ctx = {0}; +ctx.expected_count = 3; + +/* Set multiple timers with different timeouts */ +void* timer1 = uasync_set_timeout(ua, 10, &ctx, test_timer_callback); /* 1ms */ +void* timer2 = uasync_set_timeout(ua, 20, &ctx, test_timer_callback); /* 2ms */ +void* timer3 = uasync_set_timeout(ua, 30, &ctx, test_timer_callback); /* 3ms */ + +ASSERT_NOT_NULL(timer1, "Failed to set timer 1"); +ASSERT_NOT_NULL(timer2, "Failed to set timer 2"); +ASSERT_NOT_NULL(timer3, "Failed to set timer 3"); + +/* Poll and verify timers fire in order */ +int poll_count = 0; +while (ctx.callback_count < ctx.expected_count && poll_count < 100) { +uasync_poll(ua, 10); /* 1ms poll */ +poll_count++; +} + +ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Not all timers fired"); + +/* Cleanup */ +uasync_destroy(ua, 0); +TEST_PASS(); } /* Test 2: Timer cancellation race conditions */ static void test_timer_cancellation_races(void) { - TEST_START("Timer cancellation race conditions"); - - uasync_t* ua = uasync_create(); - ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); - - test_context_t ctx = {0}; - ctx.expected_count = 2; - - /* Create timers that will be cancelled at different stages */ - void* timer1 = uasync_set_timeout(ua, 5, &ctx, test_timer_callback); /* 0.5ms */ - void* timer2 = uasync_set_timeout(ua, 50, &ctx, test_timer_callback); /* 5ms */ - void* timer3 = uasync_set_timeout(ua, 100, &ctx, test_timer_callback); /* 10ms */ - - ASSERT_NOT_NULL(timer1, "Failed to set timer 1"); - ASSERT_NOT_NULL(timer2, "Failed to set timer 2"); - ASSERT_NOT_NULL(timer3, "Failed to set timer 3"); - - /* Cancel timer1 immediately (before it fires) */ - err_t cancel_result = uasync_cancel_timeout(ua, timer1); - ASSERT_EQ(cancel_result, ERR_OK, "Failed to cancel timer 1"); - test_stats.timer_cancellations++; - - /* Poll briefly - timer1 should not fire, others should */ - uasync_poll(ua, 10); /* 1ms */ - - /* Cancel timer2 while it might be firing */ - cancel_result = uasync_cancel_timeout(ua, timer2); - /* Result could be ERR_OK or ERR_FAIL depending on timing */ - - /* Continue polling */ - int poll_count = 0; - while (ctx.callback_count < 2 && poll_count < 50) { - uasync_poll(ua, 10); - poll_count++; - } - - /* Verify we got expected callbacks (timer3 + possibly timer2) */ - ASSERT_TRUE(ctx.callback_count >= 1, "Too few timers fired"); - ASSERT_TRUE(ctx.callback_count <= 2, "Too many timers fired"); - - /* Cleanup remaining timer */ - if (timer3) { - uasync_cancel_timeout(ua, timer3); - timer3 = NULL; - } - - uasync_destroy(ua, 0); - TEST_PASS(); +TEST_START("Timer cancellation race conditions"); + +uasync_t* ua = uasync_create(); +ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + +test_context_t ctx = {0}; +ctx.expected_count = 2; + +/* Create timers that will be cancelled at different stages */ +void* timer1 = uasync_set_timeout(ua, 5, &ctx, test_timer_callback); /* 0.5ms */ +void* timer2 = uasync_set_timeout(ua, 50, &ctx, test_timer_callback); /* 5ms */ +void* timer3 = uasync_set_timeout(ua, 100, &ctx, test_timer_callback); /* 10ms */ + +ASSERT_NOT_NULL(timer1, "Failed to set timer 1"); +ASSERT_NOT_NULL(timer2, "Failed to set timer 2"); +ASSERT_NOT_NULL(timer3, "Failed to set timer 3"); + +/* Cancel timer1 immediately (before it fires) */ +err_t cancel_result = uasync_cancel_timeout(ua, timer1); +ASSERT_EQ(cancel_result, ERR_OK, "Failed to cancel timer 1"); +test_stats.timer_cancellations++; + +/* Poll briefly - timer1 should not fire, others should */ +uasync_poll(ua, 10); /* 1ms */ + +/* Cancel timer2 while it might be firing */ +cancel_result = uasync_cancel_timeout(ua, timer2); +/* Result could be ERR_OK or ERR_FAIL depending on timing */ + +/* Continue polling */ +int poll_count = 0; +while (ctx.callback_count < 2 && poll_count < 50) { +uasync_poll(ua, 10); +poll_count++; +} + +/* Verify we got expected callbacks (timer3 + possibly timer2) */ +ASSERT_TRUE(ctx.callback_count >= 1, "Too few timers fired"); +ASSERT_TRUE(ctx.callback_count <= 2, "Too many timers fired"); + +/* Cleanup remaining timer */ +if (timer3) { +uasync_cancel_timeout(ua, timer3); +timer3 = NULL; +} + +uasync_destroy(ua, 0); +TEST_PASS(); } /* Test 3: Immediate timeout handling */ static void test_immediate_timeouts(void) { - TEST_START("Immediate timeout handling"); - - uasync_t* ua = uasync_create(); - ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); - - test_context_t ctx = {0}; - ctx.expected_count = 5; - - /* Record initial counter value for isolation */ - int initial_immediate_timeouts = test_stats.immediate_timeouts; - - /* Set multiple immediate timeouts (0ms) */ - for (int i = 0; i < 5; i++) { - void* timer = uasync_set_timeout(ua, 0, &ctx, test_timer_callback); - ASSERT_NOT_NULL(timer, "Failed to set immediate timer"); - } - - /* Immediate timeouts should fire during next poll */ - ASSERT_EQ(ctx.callback_count, 0, "Callbacks fired too early"); - - uasync_poll(ua, 1); /* Minimal poll */ - - ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Immediate timeouts didn't fire correctly"); - - /* Check that exactly 5 new immediate timeouts were recorded */ - int new_immediate_timeouts = test_stats.immediate_timeouts - initial_immediate_timeouts; - ASSERT_EQ(new_immediate_timeouts, 5, "Immediate timeout counter incorrect"); - - uasync_destroy(ua, 0); - TEST_PASS(); +TEST_START("Immediate timeout handling"); + +uasync_t* ua = uasync_create(); +ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + +test_context_t ctx = {0}; +ctx.expected_count = 5; + +/* Record initial counter value for isolation */ +int initial_immediate_timeouts = test_stats.immediate_timeouts; + +/* Set multiple immediate timeouts (0ms) */ +for (int i = 0; i < 5; i++) { +void* timer = uasync_set_timeout(ua, 0, &ctx, test_timer_callback); +ASSERT_NOT_NULL(timer, "Failed to set immediate timer"); +} + +/* Immediate timeouts should fire during next poll */ +ASSERT_EQ(ctx.callback_count, 0, "Callbacks fired too early"); + +uasync_poll(ua, 1); /* Minimal poll */ + +ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Immediate timeouts didn't fire correctly"); + +/* Check that exactly 5 new immediate timeouts were recorded */ +int new_immediate_timeouts = test_stats.immediate_timeouts - initial_immediate_timeouts; +ASSERT_EQ(new_immediate_timeouts, 5, "Immediate timeout counter incorrect"); + +uasync_destroy(ua, 0); +TEST_PASS(); } /* Test 4: Memory leak detection */ static void test_memory_leak_detection(void) { - TEST_START("Memory leak detection"); - - uasync_t* ua = uasync_create(); - ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); - - /* Create and destroy multiple timers without proper cleanup */ - for (int i = 0; i < 10; i++) { - test_context_t timer_ctx = {0}; - timer_ctx.timeout_ms = 100; // Set proper timeout to avoid immediate timeout - void* timer = uasync_set_timeout(ua, 100, &timer_ctx, test_timer_callback); - ASSERT_NOT_NULL(timer, "Failed to set timer"); - - /* Cancel some, leave others to timeout */ - if (i % 2 == 0) { - uasync_cancel_timeout(ua, timer); - } - } - - /* Poll to let some timers expire */ - for (int i = 0; i < 20; i++) { - uasync_poll(ua, 10); - } - - /* Destroy should detect any leaks and abort if found */ - /* This test passes if we don't abort */ - uasync_destroy(ua, 0); - - TEST_PASS(); +TEST_START("Memory leak detection"); + +uasync_t* ua = uasync_create(); +ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + +/* Create and destroy multiple timers without proper cleanup */ +for (int i = 0; i < 10; i++) { +test_context_t timer_ctx = {0}; +timer_ctx.timeout_ms = 100; // Set proper timeout to avoid immediate timeout +void* timer = uasync_set_timeout(ua, 100, &timer_ctx, test_timer_callback); +ASSERT_NOT_NULL(timer, "Failed to set timer"); + +/* Cancel some, leave others to timeout */ +if (i % 2 == 0) { +uasync_cancel_timeout(ua, timer); +} +} + +/* Poll to let some timers expire */ +for (int i = 0; i < 20; i++) { +uasync_poll(ua, 10); +} + +/* Destroy should detect any leaks and abort if found */ +/* This test passes if we don't abort */ +uasync_destroy(ua, 0); + +TEST_PASS(); } /* Test 5: Socket management efficiency */ static void test_socket_management(void) { - TEST_START("Socket management efficiency"); - - uasync_t* ua = uasync_create(); - ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); - - /* Create multiple sockets */ - int sockets[10]; - void* socket_ids[10]; - test_context_t ctx = {0}; - - for (int i = 0; i < 10; i++) { - sockets[i] = socket(AF_INET, SOCK_DGRAM, 0); - ASSERT_TRUE(sockets[i] >= 0, "Failed to create socket"); - - /* Make non-blocking */ - int flags = fcntl(sockets[i], F_GETFL, 0); - fcntl(sockets[i], F_SETFL, flags | O_NONBLOCK); - - /* Add to async */ - socket_ids[i] = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, &ctx); - ASSERT_NOT_NULL(socket_ids[i], "Failed to add socket to async"); - } - - /* Poll and verify all sockets are monitored */ - uasync_poll(ua, 1); - - /* Remove some sockets */ - for (int i = 0; i < 5; i++) { - uasync_remove_socket(ua, socket_ids[i]); - close(sockets[i]); - } - - /* Poll again - should handle removal gracefully */ - uasync_poll(ua, 1); - - /* Cleanup remaining */ - for (int i = 5; i < 10; i++) { - uasync_remove_socket(ua, socket_ids[i]); - close(sockets[i]); - } - - uasync_destroy(ua, 0); - TEST_PASS(); +TEST_START("Socket management efficiency"); + +uasync_t* ua = uasync_create(); +ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + +/* Create multiple sockets */ +int sockets[10]; +void* socket_ids[10]; +test_context_t ctx = {0}; + +for (int i = 0; i < 10; i++) { +sockets[i] = socket(AF_INET, SOCK_DGRAM, 0); +ASSERT_TRUE(sockets[i] >= 0, "Failed to create socket"); + +/* Make non-blocking */ +int flags = fcntl(sockets[i], F_GETFL, 0); +fcntl(sockets[i], F_SETFL, flags | O_NONBLOCK); + +/* Add to async */ +socket_ids[i] = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, &ctx); +ASSERT_NOT_NULL(socket_ids[i], "Failed to add socket to async"); +} + +/* Poll and verify all sockets are monitored */ +uasync_poll(ua, 1); + +/* Remove some sockets */ +for (int i = 0; i < 5; i++) { +uasync_remove_socket(ua, socket_ids[i]); +close(sockets[i]); +} + +/* Poll again - should handle removal gracefully */ +uasync_poll(ua, 1); + +/* Cleanup remaining */ +for (int i = 5; i < 10; i++) { +uasync_remove_socket(ua, socket_ids[i]); +close(sockets[i]); +} + +uasync_destroy(ua, 0); +TEST_PASS(); } /* Test 6: Error injection and handling */ static void test_error_handling(void) { - TEST_START("Error injection and handling"); - - uasync_t* ua = uasync_create(); - ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); - - /* Test invalid parameters */ - void* null_timer = uasync_set_timeout(NULL, 10, NULL, NULL); - ASSERT_NULL(null_timer, "Should fail with NULL uasync"); - - err_t cancel_result = uasync_cancel_timeout(NULL, NULL); - ASSERT_EQ(cancel_result, ERR_FAIL, "Should fail with NULL parameters"); - - /* Test with invalid socket */ - void* socket_result = uasync_add_socket(ua, -1, NULL, NULL, NULL, NULL); - ASSERT_NULL(socket_result, "Should fail with invalid socket"); - - /* Test callback that simulates errors */ - test_context_t ctx = {0}; - ctx.callback_arg = -1; /* Error injection flag */ - - void* error_timer = uasync_set_timeout(ua, 5, &ctx, test_error_callback); - ASSERT_NOT_NULL(error_timer, "Failed to set error timer"); - - uasync_poll(ua, 1); - - /* Verify error was recorded */ - ASSERT_TRUE(test_stats.race_condition_errors > 0, "Error wasn't recorded"); - - /* Cleanup */ - uasync_destroy(ua, 0); - TEST_PASS(); +TEST_START("Error injection and handling"); + +uasync_t* ua = uasync_create(); +ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + +/* Test invalid parameters */ +void* null_timer = uasync_set_timeout(NULL, 10, NULL, NULL); +ASSERT_NULL(null_timer, "Should fail with NULL uasync"); + +err_t cancel_result = uasync_cancel_timeout(NULL, NULL); +ASSERT_EQ(cancel_result, ERR_FAIL, "Should fail with NULL parameters"); + +/* Test with invalid socket */ +void* socket_result = uasync_add_socket(ua, -1, NULL, NULL, NULL, NULL); +ASSERT_NULL(socket_result, "Should fail with invalid socket"); + +/* Test callback that simulates errors */ +test_context_t ctx = {0}; +ctx.callback_arg = -1; /* Error injection flag */ + +void* error_timer = uasync_set_timeout(ua, 5, &ctx, test_error_callback); +ASSERT_NOT_NULL(error_timer, "Failed to set error timer"); + +uasync_poll(ua, 1); + +/* Verify error was recorded */ +ASSERT_TRUE(test_stats.race_condition_errors > 0, "Error wasn't recorded"); + +/* Cleanup */ +uasync_destroy(ua, 0); +TEST_PASS(); } /* Test 7: Concurrent operations stress test */ static void test_concurrent_operations(void) { - TEST_START("Concurrent operations stress test"); - - uasync_t* ua = uasync_create(); - ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); - - test_context_t timer_ctx = {0}; - timer_ctx.timeout_ms = 5; // Set non-zero timeout to avoid being counted as immediate - test_context_t socket_ctx = {0}; - - /* Create socket pair for testing */ - int sockets[2]; - void* socket_ids[2]; - ASSERT_EQ(socketpair(AF_UNIX, SOCK_DGRAM, 0, sockets), 0, "Failed to create socket pair"); - - /* Make non-blocking */ - for (int i = 0; i < 2; i++) { - int flags = fcntl(sockets[i], F_GETFL, 0); - fcntl(sockets[i], F_SETFL, flags | O_NONBLOCK); - socket_ids[i] = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, &socket_ctx); - ASSERT_NOT_NULL(socket_ids[i], "Failed to add socket to async"); - } - - /* Create multiple timers with different timeouts */ - void* timers[10]; - for (int i = 0; i < 10; i++) { - // Use unique contexts to avoid all timers having timeout_ms = 0 - test_context_t* individual_ctx = malloc(sizeof(test_context_t)); - ASSERT_NOT_NULL(individual_ctx, "Failed to allocate timer context"); - individual_ctx->callback_count = 0; - individual_ctx->expected_count = 0; - individual_ctx->timeout_ms = (i + 1) * 5; // Different timeouts: 5, 10, 15, ..., 50ms - individual_ctx->callback_arg = 0; - - timers[i] = uasync_set_timeout(ua, (i + 1) * 5, individual_ctx, test_timer_callback); - ASSERT_NOT_NULL(timers[i], "Failed to set timer"); - } - - /* Stress test: poll while operations are happening */ - for (int cycle = 0; cycle < 50; cycle++) { - /* Cancel some timers randomly */ - if (cycle % 7 == 0) { - int idx = cycle % 10; - if (timers[idx]) { - uasync_cancel_timeout(ua, timers[idx]); - timers[idx] = NULL; - } - } - - /* Write to sockets to generate events */ - if (cycle % 3 == 0) { - char data = 'x'; - write(sockets[0], &data, 1); - } - - /* Poll */ - uasync_poll(ua, 1); - - /* Read from sockets */ - char buffer[10]; - while (read(sockets[1], buffer, sizeof(buffer)) > 0) { - /* Drain socket */ - } - } - - /* Cleanup */ - for (int i = 0; i < 2; i++) { - uasync_remove_socket(ua, socket_ids[i]); - close(sockets[i]); - } - - for (int i = 0; i < 10; i++) { - if (timers[i]) { - // Note: We cannot safely access the context here because the timer might be expired - // The context will be freed by the timeout_heap free callback during uasync_destroy - uasync_cancel_timeout(ua, timers[i]); - timers[i] = NULL; - } - } - - // Free any remaining allocated contexts (for timers that were cancelled) - // This is a simplified approach - in production code, you'd maintain a list of allocated contexts - // For this test, we'll let uasync_destroy handle the cleanup through the timeout heap's free callback - - uasync_destroy(ua, 0); - TEST_PASS(); +TEST_START("Concurrent operations stress test"); + +uasync_t* ua = uasync_create(); +ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + +test_context_t timer_ctx = {0}; +timer_ctx.timeout_ms = 5; // Set non-zero timeout to avoid being counted as immediate +test_context_t socket_ctx = {0}; + +/* Create socket pair for testing */ +int sockets[2]; +void* socket_ids[2]; +ASSERT_EQ(socketpair(AF_UNIX, SOCK_DGRAM, 0, sockets), 0, "Failed to create socket pair"); + +/* Make non-blocking */ +for (int i = 0; i < 2; i++) { +int flags = fcntl(sockets[i], F_GETFL, 0); +fcntl(sockets[i], F_SETFL, flags | O_NONBLOCK); +socket_ids[i] = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, &socket_ctx); +ASSERT_NOT_NULL(socket_ids[i], "Failed to add socket to async"); +} + +/* Create multiple timers with different timeouts */ +void* timers[10]; +for (int i = 0; i < 10; i++) { +// Use unique contexts to avoid all timers having timeout_ms = 0 +test_context_t* individual_ctx = malloc(sizeof(test_context_t)); +ASSERT_NOT_NULL(individual_ctx, "Failed to allocate timer context"); +individual_ctx->callback_count = 0; +individual_ctx->expected_count = 0; +individual_ctx->timeout_ms = (i + 1) * 5; // Different timeouts: 5, 10, 15, ..., 50ms +individual_ctx->callback_arg = 0; + +timers[i] = uasync_set_timeout(ua, (i + 1) * 5, individual_ctx, test_timer_callback); +ASSERT_NOT_NULL(timers[i], "Failed to set timer"); +} + +/* Stress test: poll while operations are happening */ +for (int cycle = 0; cycle < 50; cycle++) { +/* Cancel some timers randomly */ +if (cycle % 7 == 0) { +int idx = cycle % 10; +if (timers[idx]) { +uasync_cancel_timeout(ua, timers[idx]); +timers[idx] = NULL; +} +} + +/* Write to sockets to generate events */ +if (cycle % 3 == 0) { +char data = 'x'; +write(sockets[0], &data, 1); +} + +/* Poll */ +uasync_poll(ua, 1); + +/* Read from sockets */ +char buffer[10]; +while (read(sockets[1], buffer, sizeof(buffer)) > 0) { +/* Drain socket */ +} +} + +/* Cleanup */ +for (int i = 0; i < 2; i++) { +uasync_remove_socket(ua, socket_ids[i]); +close(sockets[i]); +} + +for (int i = 0; i < 10; i++) { +if (timers[i]) { +// Note: We cannot safely access the context here because the timer might be expired +// The context will be freed by the timeout_heap free callback during uasync_destroy +uasync_cancel_timeout(ua, timers[i]); +timers[i] = NULL; +} +} + +// Free any remaining allocated contexts (for timers that were cancelled) +// This is a simplified approach - in production code, you'd maintain a list of allocated contexts +// For this test, we'll let uasync_destroy handle the cleanup through the timeout heap's free callback + +uasync_destroy(ua, 0); +TEST_PASS(); } /* Main test runner */ int main(void) { - printf("=== lib Comprehensive Unit Tests ===\n"); - printf("Testing race conditions, memory management, and error handling\n\n"); - - /* Run all tests */ - test_basic_timers(); - test_timer_cancellation_races(); - test_immediate_timeouts(); - test_memory_leak_detection(); - test_socket_management(); - test_error_handling(); - test_concurrent_operations(); - - /* Print statistics */ - printf("\n=== Test Statistics ===\n"); - printf("Tests run: %d\n", test_stats.tests_run); - printf("Tests passed: %d\n", test_stats.tests_passed); - printf("Tests failed: %d\n", test_stats.tests_failed); - printf("\nTimer callbacks: %d\n", test_stats.timer_callbacks); - printf("Timer cancellations: %d\n", test_stats.timer_cancellations); - printf("Immediate timeouts: %d\n", test_stats.immediate_timeouts); - printf("Socket events: %d\n", test_stats.socket_events); - printf("Race condition errors: %d\n", test_stats.race_condition_errors); - - /* Memory leak detection */ - printf("\n=== Memory Leak Detection ===\n"); - printf("No memory leaks detected during testing\n"); - - return (test_stats.tests_failed > 0) ? 1 : 0; +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "=== lib Comprehensive Unit Tests ==="); +DEBUG_ERROR(DEBUG_CATEGORY_UASYNC, "Testing race conditions, memory management, and error handling\n"); + +/* Run all tests */ +test_basic_timers(); +test_timer_cancellation_races(); +test_immediate_timeouts(); +test_memory_leak_detection(); +test_socket_management(); +test_error_handling(); +test_concurrent_operations(); + +/* Print statistics */ +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "\n=== Test Statistics ==="); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Tests run: %d", test_stats.tests_run); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Tests passed: %d", test_stats.tests_passed); +DEBUG_ERROR(DEBUG_CATEGORY_UASYNC, "Tests failed: %d", test_stats.tests_failed); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "\nTimer callbacks: %d", test_stats.timer_callbacks); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Timer cancellations: %d", test_stats.timer_cancellations); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Immediate timeouts: %d", test_stats.immediate_timeouts); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Socket events: %d", test_stats.socket_events); +DEBUG_ERROR(DEBUG_CATEGORY_UASYNC, "Race condition errors: %d", test_stats.race_condition_errors); + +/* Memory leak detection */ +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "\n=== Memory Leak Detection ==="); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "No memory leaks detected during testing"); + +return (test_stats.tests_failed > 0) ? 1 : 0; } \ No newline at end of file diff --git a/tests/test_u_async_comprehensive.c.backup b/tests/test_u_async_comprehensive.c.backup new file mode 100644 index 000000000..ff41faa82 --- /dev/null +++ b/tests/test_u_async_comprehensive.c.backup @@ -0,0 +1,493 @@ +/** + * Comprehensive unit tests for lib module + * Focus on: timers, sockets, error handling, race conditions + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "u_async.h" +#include "timeout_heap.h" + +/* Test statistics */ +static struct { + int tests_run; + int tests_passed; + int tests_failed; + + /* Timer statistics */ + int timer_callbacks; + int timer_cancellations; + int immediate_timeouts; + + /* Socket statistics */ + int socket_events; + int socket_errors; + + /* Error statistics */ + int memory_allocation_errors; + int invalid_parameter_errors; + int race_condition_errors; +} test_stats = {0}; + +/* Test result tracking */ +#define TEST_START(name) do { \ + printf("TEST: %s... ", name); \ + test_stats.tests_run++; \ +} while(0) + +#define TEST_PASS() do { \ + printf("PASS\n"); \ + test_stats.tests_passed++; \ +} while(0) + +#define TEST_FAIL(msg) do { \ + printf("FAIL: %s\n", msg); \ + test_stats.tests_failed++; \ +} while(0) + +#define ASSERT_TRUE(cond, msg) do { \ + if (!(cond)) { \ + TEST_FAIL(msg); \ + return; \ + } \ +} while(0) + +#define ASSERT_FALSE(cond, msg) do { \ + if (cond) { \ + TEST_FAIL(msg); \ + return; \ + } \ +} while(0) + +#define ASSERT_EQ(a, b, msg) do { \ + if ((a) != (b)) { \ + TEST_FAIL(msg); \ + printf(" Expected: %ld, Got: %ld\n", (long)(b), (long)(a)); \ + return; \ + } \ +} while(0) + +#define ASSERT_NE(a, b, msg) do { \ + if ((a) == (b)) { \ + TEST_FAIL(msg); \ + return; \ + } \ +} while(0) + +#define ASSERT_NULL(ptr, msg) do { \ + if ((ptr) != NULL) { \ + TEST_FAIL(msg); \ + return; \ + } \ +} while(0) + +#define ASSERT_NOT_NULL(ptr, msg) do { \ + if ((ptr) == NULL) { \ + TEST_FAIL(msg); \ + return; \ + } \ +} while(0) + +/* Test context for callbacks */ +typedef struct { + int callback_count; + int expected_count; + int callback_arg; + int timeout_ms; + uasync_t* ua; + void* timer_id; +} test_context_t; + +/* Timer callback for testing */ +static void test_timer_callback(void* arg) { + test_context_t* ctx = (test_context_t*)arg; + ctx->callback_count++; + test_stats.timer_callbacks++; + + if (ctx->timeout_ms == 0) { + test_stats.immediate_timeouts++; + } +} + +/* Socket callback for testing */ +static void test_socket_callback(int fd, void* arg) { + test_context_t* ctx = (test_context_t*)arg; + ctx->callback_count++; + test_stats.socket_events++; + (void)fd; /* unused */ +} + +/* Error injection callback */ +static void test_error_callback(void* arg) { + test_context_t* ctx = (test_context_t*)arg; + ctx->callback_count++; + + /* Simulate callback error */ + if (ctx->callback_arg == -1) { + test_stats.race_condition_errors++; + return; + } +} + +/* Test 1: Basic timer functionality */ +static void test_basic_timers(void) { + TEST_START("Basic timer functionality"); + + uasync_t* ua = uasync_create(); + ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + + test_context_t ctx = {0}; + ctx.expected_count = 3; + + /* Set multiple timers with different timeouts */ + void* timer1 = uasync_set_timeout(ua, 10, &ctx, test_timer_callback); /* 1ms */ + void* timer2 = uasync_set_timeout(ua, 20, &ctx, test_timer_callback); /* 2ms */ + void* timer3 = uasync_set_timeout(ua, 30, &ctx, test_timer_callback); /* 3ms */ + + ASSERT_NOT_NULL(timer1, "Failed to set timer 1"); + ASSERT_NOT_NULL(timer2, "Failed to set timer 2"); + ASSERT_NOT_NULL(timer3, "Failed to set timer 3"); + + /* Poll and verify timers fire in order */ + int poll_count = 0; + while (ctx.callback_count < ctx.expected_count && poll_count < 100) { + uasync_poll(ua, 10); /* 1ms poll */ + poll_count++; + } + + ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Not all timers fired"); + + /* Cleanup */ + uasync_destroy(ua, 0); + TEST_PASS(); +} + +/* Test 2: Timer cancellation race conditions */ +static void test_timer_cancellation_races(void) { + TEST_START("Timer cancellation race conditions"); + + uasync_t* ua = uasync_create(); + ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + + test_context_t ctx = {0}; + ctx.expected_count = 2; + + /* Create timers that will be cancelled at different stages */ + void* timer1 = uasync_set_timeout(ua, 5, &ctx, test_timer_callback); /* 0.5ms */ + void* timer2 = uasync_set_timeout(ua, 50, &ctx, test_timer_callback); /* 5ms */ + void* timer3 = uasync_set_timeout(ua, 100, &ctx, test_timer_callback); /* 10ms */ + + ASSERT_NOT_NULL(timer1, "Failed to set timer 1"); + ASSERT_NOT_NULL(timer2, "Failed to set timer 2"); + ASSERT_NOT_NULL(timer3, "Failed to set timer 3"); + + /* Cancel timer1 immediately (before it fires) */ + err_t cancel_result = uasync_cancel_timeout(ua, timer1); + ASSERT_EQ(cancel_result, ERR_OK, "Failed to cancel timer 1"); + test_stats.timer_cancellations++; + + /* Poll briefly - timer1 should not fire, others should */ + uasync_poll(ua, 10); /* 1ms */ + + /* Cancel timer2 while it might be firing */ + cancel_result = uasync_cancel_timeout(ua, timer2); + /* Result could be ERR_OK or ERR_FAIL depending on timing */ + + /* Continue polling */ + int poll_count = 0; + while (ctx.callback_count < 2 && poll_count < 50) { + uasync_poll(ua, 10); + poll_count++; + } + + /* Verify we got expected callbacks (timer3 + possibly timer2) */ + ASSERT_TRUE(ctx.callback_count >= 1, "Too few timers fired"); + ASSERT_TRUE(ctx.callback_count <= 2, "Too many timers fired"); + + /* Cleanup remaining timer */ + if (timer3) { + uasync_cancel_timeout(ua, timer3); + timer3 = NULL; + } + + uasync_destroy(ua, 0); + TEST_PASS(); +} + +/* Test 3: Immediate timeout handling */ +static void test_immediate_timeouts(void) { + TEST_START("Immediate timeout handling"); + + uasync_t* ua = uasync_create(); + ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + + test_context_t ctx = {0}; + ctx.expected_count = 5; + + /* Record initial counter value for isolation */ + int initial_immediate_timeouts = test_stats.immediate_timeouts; + + /* Set multiple immediate timeouts (0ms) */ + for (int i = 0; i < 5; i++) { + void* timer = uasync_set_timeout(ua, 0, &ctx, test_timer_callback); + ASSERT_NOT_NULL(timer, "Failed to set immediate timer"); + } + + /* Immediate timeouts should fire during next poll */ + ASSERT_EQ(ctx.callback_count, 0, "Callbacks fired too early"); + + uasync_poll(ua, 1); /* Minimal poll */ + + ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Immediate timeouts didn't fire correctly"); + + /* Check that exactly 5 new immediate timeouts were recorded */ + int new_immediate_timeouts = test_stats.immediate_timeouts - initial_immediate_timeouts; + ASSERT_EQ(new_immediate_timeouts, 5, "Immediate timeout counter incorrect"); + + uasync_destroy(ua, 0); + TEST_PASS(); +} + +/* Test 4: Memory leak detection */ +static void test_memory_leak_detection(void) { + TEST_START("Memory leak detection"); + + uasync_t* ua = uasync_create(); + ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + + /* Create and destroy multiple timers without proper cleanup */ + for (int i = 0; i < 10; i++) { + test_context_t timer_ctx = {0}; + timer_ctx.timeout_ms = 100; // Set proper timeout to avoid immediate timeout + void* timer = uasync_set_timeout(ua, 100, &timer_ctx, test_timer_callback); + ASSERT_NOT_NULL(timer, "Failed to set timer"); + + /* Cancel some, leave others to timeout */ + if (i % 2 == 0) { + uasync_cancel_timeout(ua, timer); + } + } + + /* Poll to let some timers expire */ + for (int i = 0; i < 20; i++) { + uasync_poll(ua, 10); + } + + /* Destroy should detect any leaks and abort if found */ + /* This test passes if we don't abort */ + uasync_destroy(ua, 0); + + TEST_PASS(); +} + +/* Test 5: Socket management efficiency */ +static void test_socket_management(void) { + TEST_START("Socket management efficiency"); + + uasync_t* ua = uasync_create(); + ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + + /* Create multiple sockets */ + int sockets[10]; + void* socket_ids[10]; + test_context_t ctx = {0}; + + for (int i = 0; i < 10; i++) { + sockets[i] = socket(AF_INET, SOCK_DGRAM, 0); + ASSERT_TRUE(sockets[i] >= 0, "Failed to create socket"); + + /* Make non-blocking */ + int flags = fcntl(sockets[i], F_GETFL, 0); + fcntl(sockets[i], F_SETFL, flags | O_NONBLOCK); + + /* Add to async */ + socket_ids[i] = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, &ctx); + ASSERT_NOT_NULL(socket_ids[i], "Failed to add socket to async"); + } + + /* Poll and verify all sockets are monitored */ + uasync_poll(ua, 1); + + /* Remove some sockets */ + for (int i = 0; i < 5; i++) { + uasync_remove_socket(ua, socket_ids[i]); + close(sockets[i]); + } + + /* Poll again - should handle removal gracefully */ + uasync_poll(ua, 1); + + /* Cleanup remaining */ + for (int i = 5; i < 10; i++) { + uasync_remove_socket(ua, socket_ids[i]); + close(sockets[i]); + } + + uasync_destroy(ua, 0); + TEST_PASS(); +} + +/* Test 6: Error injection and handling */ +static void test_error_handling(void) { + TEST_START("Error injection and handling"); + + uasync_t* ua = uasync_create(); + ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + + /* Test invalid parameters */ + void* null_timer = uasync_set_timeout(NULL, 10, NULL, NULL); + ASSERT_NULL(null_timer, "Should fail with NULL uasync"); + + err_t cancel_result = uasync_cancel_timeout(NULL, NULL); + ASSERT_EQ(cancel_result, ERR_FAIL, "Should fail with NULL parameters"); + + /* Test with invalid socket */ + void* socket_result = uasync_add_socket(ua, -1, NULL, NULL, NULL, NULL); + ASSERT_NULL(socket_result, "Should fail with invalid socket"); + + /* Test callback that simulates errors */ + test_context_t ctx = {0}; + ctx.callback_arg = -1; /* Error injection flag */ + + void* error_timer = uasync_set_timeout(ua, 5, &ctx, test_error_callback); + ASSERT_NOT_NULL(error_timer, "Failed to set error timer"); + + uasync_poll(ua, 1); + + /* Verify error was recorded */ + ASSERT_TRUE(test_stats.race_condition_errors > 0, "Error wasn't recorded"); + + /* Cleanup */ + uasync_destroy(ua, 0); + TEST_PASS(); +} + +/* Test 7: Concurrent operations stress test */ +static void test_concurrent_operations(void) { + TEST_START("Concurrent operations stress test"); + + uasync_t* ua = uasync_create(); + ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + + test_context_t timer_ctx = {0}; + timer_ctx.timeout_ms = 5; // Set non-zero timeout to avoid being counted as immediate + test_context_t socket_ctx = {0}; + + /* Create socket pair for testing */ + int sockets[2]; + void* socket_ids[2]; + ASSERT_EQ(socketpair(AF_UNIX, SOCK_DGRAM, 0, sockets), 0, "Failed to create socket pair"); + + /* Make non-blocking */ + for (int i = 0; i < 2; i++) { + int flags = fcntl(sockets[i], F_GETFL, 0); + fcntl(sockets[i], F_SETFL, flags | O_NONBLOCK); + socket_ids[i] = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, &socket_ctx); + ASSERT_NOT_NULL(socket_ids[i], "Failed to add socket to async"); + } + + /* Create multiple timers with different timeouts */ + void* timers[10]; + for (int i = 0; i < 10; i++) { + // Use unique contexts to avoid all timers having timeout_ms = 0 + test_context_t* individual_ctx = malloc(sizeof(test_context_t)); + ASSERT_NOT_NULL(individual_ctx, "Failed to allocate timer context"); + individual_ctx->callback_count = 0; + individual_ctx->expected_count = 0; + individual_ctx->timeout_ms = (i + 1) * 5; // Different timeouts: 5, 10, 15, ..., 50ms + individual_ctx->callback_arg = 0; + + timers[i] = uasync_set_timeout(ua, (i + 1) * 5, individual_ctx, test_timer_callback); + ASSERT_NOT_NULL(timers[i], "Failed to set timer"); + } + + /* Stress test: poll while operations are happening */ + for (int cycle = 0; cycle < 50; cycle++) { + /* Cancel some timers randomly */ + if (cycle % 7 == 0) { + int idx = cycle % 10; + if (timers[idx]) { + uasync_cancel_timeout(ua, timers[idx]); + timers[idx] = NULL; + } + } + + /* Write to sockets to generate events */ + if (cycle % 3 == 0) { + char data = 'x'; + write(sockets[0], &data, 1); + } + + /* Poll */ + uasync_poll(ua, 1); + + /* Read from sockets */ + char buffer[10]; + while (read(sockets[1], buffer, sizeof(buffer)) > 0) { + /* Drain socket */ + } + } + + /* Cleanup */ + for (int i = 0; i < 2; i++) { + uasync_remove_socket(ua, socket_ids[i]); + close(sockets[i]); + } + + for (int i = 0; i < 10; i++) { + if (timers[i]) { + // Note: We cannot safely access the context here because the timer might be expired + // The context will be freed by the timeout_heap free callback during uasync_destroy + uasync_cancel_timeout(ua, timers[i]); + timers[i] = NULL; + } + } + + // Free any remaining allocated contexts (for timers that were cancelled) + // This is a simplified approach - in production code, you'd maintain a list of allocated contexts + // For this test, we'll let uasync_destroy handle the cleanup through the timeout heap's free callback + + uasync_destroy(ua, 0); + TEST_PASS(); +} + +/* Main test runner */ +int main(void) { + printf("=== lib Comprehensive Unit Tests ===\n"); + printf("Testing race conditions, memory management, and error handling\n\n"); + + /* Run all tests */ + test_basic_timers(); + test_timer_cancellation_races(); + test_immediate_timeouts(); + test_memory_leak_detection(); + test_socket_management(); + test_error_handling(); + test_concurrent_operations(); + + /* Print statistics */ + printf("\n=== Test Statistics ===\n"); + printf("Tests run: %d\n", test_stats.tests_run); + printf("Tests passed: %d\n", test_stats.tests_passed); + printf("Tests failed: %d\n", test_stats.tests_failed); + printf("\nTimer callbacks: %d\n", test_stats.timer_callbacks); + printf("Timer cancellations: %d\n", test_stats.timer_cancellations); + printf("Immediate timeouts: %d\n", test_stats.immediate_timeouts); + printf("Socket events: %d\n", test_stats.socket_events); + printf("Race condition errors: %d\n", test_stats.race_condition_errors); + + /* Memory leak detection */ + printf("\n=== Memory Leak Detection ===\n"); + printf("No memory leaks detected during testing\n"); + + return (test_stats.tests_failed > 0) ? 1 : 0; +} \ No newline at end of file diff --git a/tests/test_u_async_performance b/tests/test_u_async_performance deleted file mode 100755 index ad06ec230..000000000 Binary files a/tests/test_u_async_performance and /dev/null differ diff --git a/tests/test_u_async_performance.c b/tests/test_u_async_performance.c index 6292509b8..12509cd5f 100644 --- a/tests/test_u_async_performance.c +++ b/tests/test_u_async_performance.c @@ -1,9 +1,10 @@ /** - * Performance benchmark for lib socket management - * Compares array-based vs linked list implementation - */ +* Performance benchmark for lib socket management +* Compares array-based vs linked list implementation +*/ #include +#include "../lib/debug_config.h" #include #include #include @@ -19,272 +20,269 @@ /* Performance measurement */ static uint64_t get_time_us(void) { - struct timeval tv; - gettimeofday(&tv, NULL); - return (uint64_t)tv.tv_sec * 1000000ULL + tv.tv_usec; +struct timeval tv; +gettimeofday(&tv, NULL); +return (uint64_t)tv.tv_sec * 1000000ULL + tv.tv_usec; } static void test_socket_callback(int fd, void* arg) { - (void)fd; - (void)arg; - // Empty callback for testing +(void)fd; +(void)arg; +// Empty callback for testing } - /* Benchmark: Add and remove many sockets */ - static void benchmark_socket_operations(int num_sockets) { - // Test with fewer sockets to isolate buffer overflow - gradually increase - if (num_sockets > 25) { - printf("DEBUG: Reducing num_sockets from %d to 25 for testing\n", num_sockets); - num_sockets = 25; - } - printf("=== Socket Management Benchmark ===\n"); - printf("Testing with %d sockets\n\n", num_sockets); - - uasync_t* ua = uasync_create(); - if (!ua) { - printf("Failed to create uasync\n"); - return; - } - - /* Create socket array */ - int* sockets = malloc(num_sockets * sizeof(int)); - int* socket_fds = malloc(num_sockets * sizeof(int)); // Store FDs instead of pointers - if (!sockets || !socket_fds) { - printf("Memory allocation failed\n"); - free(sockets); - free(socket_fds); - uasync_destroy(ua, 0); - return; - } - - /* Create sockets */ - for (int i = 0; i < num_sockets; i++) { - sockets[i] = socket(AF_INET, SOCK_DGRAM, 0); - if (sockets[i] < 0) { - printf("Failed to create socket %d\n", i); - // Clean up created sockets - for (int j = 0; j < i; j++) { - close(sockets[j]); - } - free(sockets); - free(socket_fds); - uasync_destroy(ua, 0); - return; - } - - /* Make non-blocking */ - int flags = fcntl(sockets[i], F_GETFL, 0); - fcntl(sockets[i], F_SETFL, flags | O_NONBLOCK); - - if (i == 0) { - printf("DEBUG: Socket 0 has fd=%d\n", sockets[i]); - } - } - - printf("Created %d sockets\n", num_sockets); - - /* Benchmark 1: Add all sockets */ - uint64_t start_time = get_time_us(); - int sockets_added = 0; - for (int i = 0; i < num_sockets; i++) { - void* id = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, NULL); - if (!id) { - printf("Failed to add socket %d\n", i); - printf("DEBUG: Only added %d sockets before failure\n", sockets_added); - break; - } - socket_fds[i] = sockets[i]; // Store the file descriptor instead of pointer - sockets_added++; - } - uint64_t add_time = get_time_us() - start_time; - printf("DEBUG: Total sockets added: %d\n", sockets_added); - - printf("Add %d sockets: %llu us (%.2f us per socket)\n", - sockets_added, (unsigned long long)add_time, (double)add_time / sockets_added); - - /* Benchmark 2: Poll multiple times */ - int poll_iterations = 0; // Skip polling to test corruption - uint64_t poll_time = 0; - - printf("SKIPPING POLLING to test corruption\n"); - - /* Benchmark 3: Remove all sockets using lookup function */ - start_time = get_time_us(); - int removed_count = 0; - int failed_count = 0; - - printf("DEBUG: Removing sockets using lookup by FD\n"); - - for (int i = 0; i < sockets_added; i++) { - int fd = socket_fds[i]; - void* id = NULL; - int lookup_result = uasync_lookup_socket(ua, fd, &id); - - if (lookup_result == 0 && id != NULL) { - printf("DEBUG: Attempting to remove socket %d (fd=%d, id=%p)\n", i, fd, id); - int result = uasync_remove_socket(ua, id); - if (result == 0) { - removed_count++; - } else { - failed_count++; - printf("DEBUG: Failed to remove socket %d (fd=%d), result=%d\n", i, fd, result); - } - } else { - printf("DEBUG: Socket %d (fd=%d) lookup failed\n", i, fd); - failed_count++; - } - } - uint64_t remove_time = get_time_us() - start_time; - - printf("DEBUG: Actually removed %d sockets, failed %d\n", removed_count, failed_count); - - printf("Remove %d sockets: %llu us (%.2f us per socket)\n", - sockets_added, (unsigned long long)remove_time, (double)remove_time / sockets_added); - - /* Calculate total time */ - uint64_t total_time = add_time + poll_time + remove_time; - printf("\nTotal time: %llu us\n", (unsigned long long)total_time); - printf("Average per operation: %.2f us\n", (double)total_time / (sockets_added * 2)); - - /* Memory usage - skip to isolate corruption */ - printf("SKIPPING memory stats for corruption testing\n"); - // size_t timer_alloc, timer_free, socket_alloc, socket_free; - // uasync_get_stats(ua, &timer_alloc, &timer_free, &socket_alloc, &socket_free); - // printf("\nMemory stats: timers %zu/%zu, sockets %zu/%zu\n", - // timer_alloc, timer_free, socket_alloc, socket_free); - - /* Cleanup */ - for (int i = 0; i < num_sockets; i++) { - close(sockets[i]); - } - free(sockets); - free(socket_fds); - uasync_destroy(ua, 0); +/* Benchmark: Add and remove many sockets */ +static void benchmark_socket_operations(int num_sockets) { +// Test with fewer sockets to isolate buffer overflow - gradually increase +if (num_sockets > 25) { +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "DEBUG: Reducing num_sockets from %d to 25 for testing", num_sockets); +num_sockets = 25; +} +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "=== Socket Management Benchmark ==="); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Testing with %d sockets\n", num_sockets); + +uasync_t* ua = uasync_create(); +if (!ua) { +DEBUG_ERROR(DEBUG_CATEGORY_UASYNC, "Failed to create uasync"); +return; +} + +/* Create socket array */ +int* sockets = malloc(num_sockets * sizeof(int)); +int* socket_fds = malloc(num_sockets * sizeof(int)); // Store FDs instead of pointers +if (!sockets || !socket_fds) { +DEBUG_ERROR(DEBUG_CATEGORY_UASYNC, "Memory allocation failed"); +free(sockets); +free(socket_fds); +uasync_destroy(ua, 0); +return; +} + +/* Create sockets */ +for (int i = 0; i < num_sockets; i++) { +sockets[i] = socket(AF_INET, SOCK_DGRAM, 0); +if (sockets[i] < 0) { +DEBUG_ERROR(DEBUG_CATEGORY_UASYNC, "Failed to create socket %d", i); +// Clean up created sockets +for (int j = 0; j < i; j++) { +close(sockets[j]); +} +free(sockets); +free(socket_fds); +uasync_destroy(ua, 0); +return; +} + +/* Make non-blocking */ +int flags = fcntl(sockets[i], F_GETFL, 0); +fcntl(sockets[i], F_SETFL, flags | O_NONBLOCK); + +if (i == 0) { +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "DEBUG: Socket 0 has fd=%d", sockets[i]); +} +} + +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Created %d sockets", num_sockets); + +/* Benchmark 1: Add all sockets */ +uint64_t start_time = get_time_us(); +int sockets_added = 0; +for (int i = 0; i < num_sockets; i++) { +void* id = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, NULL); +if (!id) { +DEBUG_ERROR(DEBUG_CATEGORY_UASYNC, "Failed to add socket %d", i); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "DEBUG: Only added %d sockets before failure", sockets_added); +break; +} +socket_fds[i] = sockets[i]; // Store the file descriptor instead of pointer +sockets_added++; +} +uint64_t add_time = get_time_us() - start_time; +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "DEBUG: Total sockets added: %d", sockets_added); + +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Add %d sockets: %llu us (%.2f us per socket)", sockets_added, (unsigned long long)add_time, (double)add_time / sockets_added); + +/* Benchmark 2: Poll multiple times */ +int poll_iterations = 0; // Skip polling to test corruption +uint64_t poll_time = 0; + +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "SKIPPING POLLING to test corruption"); + +/* Benchmark 3: Remove all sockets using lookup function */ +start_time = get_time_us(); +int removed_count = 0; +int failed_count = 0; + +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "DEBUG: Removing sockets using lookup by FD"); + +for (int i = 0; i < sockets_added; i++) { +int fd = socket_fds[i]; +void* id = NULL; +int lookup_result = uasync_lookup_socket(ua, fd, &id); + +if (lookup_result == 0 && id != NULL) { +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "DEBUG: Attempting to remove socket %d (fd=%d, id=%p)", i, fd, id); +int result = uasync_remove_socket(ua, id); +if (result == 0) { +removed_count++; +} else { +failed_count++; +DEBUG_ERROR(DEBUG_CATEGORY_UASYNC, "DEBUG: Failed to remove socket %d (fd=%d), result=%d", i, fd, result); +} +} else { +DEBUG_ERROR(DEBUG_CATEGORY_UASYNC, "DEBUG: Socket %d (fd=%d) lookup failed", i, fd); +failed_count++; +} +} +uint64_t remove_time = get_time_us() - start_time; + +DEBUG_ERROR(DEBUG_CATEGORY_UASYNC, "DEBUG: Actually removed %d sockets, failed %d", removed_count, failed_count); + +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Remove %d sockets: %llu us (%.2f us per socket)", sockets_added, (unsigned long long)remove_time, (double)remove_time / sockets_added); + +/* Calculate total time */ +uint64_t total_time = add_time + poll_time + remove_time; +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "\nTotal time: %llu us", (unsigned long long)total_time); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Average per operation: %.2f us", (double)total_time / (sockets_added * 2)); + +/* Memory usage - skip to isolate corruption */ +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "SKIPPING memory stats for corruption testing"); +// size_t timer_alloc, timer_free, socket_alloc, socket_free; +// uasync_get_stats(ua, &timer_alloc, &timer_free, &socket_alloc, &socket_free); +// printf("\nMemory stats: timers %zu/%zu, sockets %zu/%zu\n", +// timer_alloc, timer_free, socket_alloc, socket_free); + +/* Cleanup */ +for (int i = 0; i < num_sockets; i++) { +close(sockets[i]); +} +free(sockets); +free(socket_fds); +uasync_destroy(ua, 0); } /* Benchmark: High-frequency operations */ static void benchmark_high_frequency(void) { - printf("\n=== High-Frequency Operations Benchmark ===\n"); - - uasync_t* ua = uasync_create(); - if (!ua) { - printf("Failed to create uasync\n"); - return; - } - - /* Create a few sockets for high-frequency operations */ - int num_sockets = 10; - int sockets[num_sockets]; - void* socket_ids[num_sockets]; - - for (int i = 0; i < num_sockets; i++) { - sockets[i] = socket(AF_INET, SOCK_DGRAM, 0); - int flags = fcntl(sockets[i], F_GETFL, 0); - fcntl(sockets[i], F_SETFL, flags | O_NONBLOCK); - - socket_ids[i] = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, NULL); - } - - /* Benchmark: Rapid add/remove cycles */ - int cycles = 10000; - printf("Testing %d rapid add/remove cycles...\n", cycles); - - uint64_t start_time = get_time_us(); - for (int cycle = 0; cycle < cycles; cycle++) { - /* Remove all sockets */ - for (int i = 0; i < num_sockets; i++) { - if (socket_ids[i]) { - uasync_remove_socket(ua, socket_ids[i]); - socket_ids[i] = NULL; - } - } - - /* Add them back */ - for (int i = 0; i < num_sockets; i++) { - socket_ids[i] = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, NULL); - } - - /* Poll once per cycle */ - uasync_poll(ua, 0); - } - uint64_t total_time = get_time_us() - start_time; - - printf("Completed %d cycles in %llu us\n", cycles, (unsigned long long)total_time); - printf("Average time per cycle: %.2f us\n", (double)total_time / cycles); - printf("Operations per second: %.0f\n", (double)(cycles * num_sockets * 2) / (total_time / 1000000.0)); - - /* Cleanup */ - for (int i = 0; i < num_sockets; i++) { - close(sockets[i]); - } - uasync_destroy(ua, 0); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "\n=== High-Frequency Operations Benchmark ==="); + +uasync_t* ua = uasync_create(); +if (!ua) { +DEBUG_ERROR(DEBUG_CATEGORY_UASYNC, "Failed to create uasync"); +return; +} + +/* Create a few sockets for high-frequency operations */ +int num_sockets = 10; +int sockets[num_sockets]; +void* socket_ids[num_sockets]; + +for (int i = 0; i < num_sockets; i++) { +sockets[i] = socket(AF_INET, SOCK_DGRAM, 0); +int flags = fcntl(sockets[i], F_GETFL, 0); +fcntl(sockets[i], F_SETFL, flags | O_NONBLOCK); + +socket_ids[i] = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, NULL); +} + +/* Benchmark: Rapid add/remove cycles */ +int cycles = 10000; +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Testing %d rapid add/remove cycles...", cycles); + +uint64_t start_time = get_time_us(); +for (int cycle = 0; cycle < cycles; cycle++) { +/* Remove all sockets */ +for (int i = 0; i < num_sockets; i++) { +if (socket_ids[i]) { +uasync_remove_socket(ua, socket_ids[i]); +socket_ids[i] = NULL; +} +} + +/* Add them back */ +for (int i = 0; i < num_sockets; i++) { +socket_ids[i] = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, NULL); +} + +/* Poll once per cycle */ +uasync_poll(ua, 0); +} +uint64_t total_time = get_time_us() - start_time; + +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Completed %d cycles in %llu us", cycles, (unsigned long long)total_time); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Average time per cycle: %.2f us", (double)total_time / cycles); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Operations per second: %.0f", (double)(cycles * num_sockets * 2) / (total_time / 1000000.0)); + +/* Cleanup */ +for (int i = 0; i < num_sockets; i++) { +close(sockets[i]); +} +uasync_destroy(ua, 0); } /* Benchmark: Scalability test */ static void benchmark_scalability(void) { - printf("\n=== Scalability Test ===\n"); - - int test_sizes[] = {10, 50, 100, 200, 500, 1000}; - int num_tests = sizeof(test_sizes) / sizeof(test_sizes[0]); - - printf("Testing scalability with different numbers of sockets:\n"); - - for (int test = 0; test < num_tests; test++) { - int num_sockets = test_sizes[test]; - - uasync_t* ua = uasync_create(); - if (!ua) continue; - - /* Create sockets */ - int* sockets = malloc(num_sockets * sizeof(int)); - void** socket_ids = malloc(num_sockets * sizeof(void*)); - - for (int i = 0; i < num_sockets; i++) { - sockets[i] = socket(AF_INET, SOCK_DGRAM, 0); - int flags = fcntl(sockets[i], F_GETFL, 0); - fcntl(sockets[i], F_SETFL, flags | O_NONBLOCK); - - socket_ids[i] = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, NULL); - } - - /* Measure poll time */ - uint64_t start_time = get_time_us(); - for (int iter = 0; iter < 100; iter++) { - uasync_poll(ua, 0); - } - uint64_t poll_time = get_time_us() - start_time; - - printf(" %d sockets: %.2f us per poll (%.2f ns per socket)\n", - num_sockets, (double)poll_time / 100, - ((double)poll_time / 100) * 1000 / num_sockets); - - /* Cleanup */ - for (int i = 0; i < num_sockets; i++) { - close(sockets[i]); - } - free(sockets); - free(socket_ids); - uasync_destroy(ua, 0); - } +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "\n=== Scalability Test ==="); + +int test_sizes[] = {10, 50, 100, 200, 500, 1000}; +int num_tests = sizeof(test_sizes) / sizeof(test_sizes[0]); + +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Testing scalability with different numbers of sockets:"); + +for (int test = 0; test < num_tests; test++) { +int num_sockets = test_sizes[test]; + +uasync_t* ua = uasync_create(); +if (!ua) continue; + +/* Create sockets */ +int* sockets = malloc(num_sockets * sizeof(int)); +void** socket_ids = malloc(num_sockets * sizeof(void*)); + +for (int i = 0; i < num_sockets; i++) { +sockets[i] = socket(AF_INET, SOCK_DGRAM, 0); +int flags = fcntl(sockets[i], F_GETFL, 0); +fcntl(sockets[i], F_SETFL, flags | O_NONBLOCK); + +socket_ids[i] = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, NULL); +} + +/* Measure poll time */ +uint64_t start_time = get_time_us(); +for (int iter = 0; iter < 100; iter++) { +uasync_poll(ua, 0); +} +uint64_t poll_time = get_time_us() - start_time; + +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "%d sockets: %.2f us per poll (%.2f ns per socket)", num_sockets, (double)poll_time / 100, +((double)poll_time / 100) * 1000 / num_sockets); + +/* Cleanup */ +for (int i = 0; i < num_sockets; i++) { +close(sockets[i]); +} +free(sockets); +free(socket_ids); +uasync_destroy(ua, 0); +} } int main(void) { - printf("lib Socket Management Performance Benchmark\n"); - printf("================================================\n\n"); - - /* Run benchmarks */ - benchmark_socket_operations(25); // 25 sockets for testing - // benchmark_socket_operations(100); // 100 sockets - // benchmark_socket_operations(1000); // 1000 sockets - // benchmark_high_frequency(); // High-frequency operations - // benchmark_scalability(); // Scalability test - - printf("\n=== Benchmark Complete ===\n"); - printf("Array-based socket management provides:\n"); - printf("- O(1) add/remove operations (vs O(n) for linked list)\n"); - printf("- Better cache locality for sequential socket processing\n"); - printf("- Direct FD-to-index mapping for fast lookups\n"); - printf("- Reduced memory allocations per operation\n"); - - return 0; +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "lib Socket Management Performance Benchmark"); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "================================================\n"); + +/* Run benchmarks */ +benchmark_socket_operations(25); // 25 sockets for testing +// benchmark_socket_operations(100); // 100 sockets +// benchmark_socket_operations(1000); // 1000 sockets +// benchmark_high_frequency(); // High-frequency operations +// benchmark_scalability(); // Scalability test + +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "\n=== Benchmark Complete ==="); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "Array-based socket management provides:"); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "- O(1) add/remove operations (vs O(n) for linked list)"); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "- Better cache locality for sequential socket processing"); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "- Direct FD-to-index mapping for fast lookups"); +DEBUG_INFO(DEBUG_CATEGORY_UASYNC, "- Reduced memory allocations per operation"); + +return 0; } \ No newline at end of file diff --git a/tests/test_u_async_performance.c.backup b/tests/test_u_async_performance.c.backup new file mode 100644 index 000000000..6292509b8 --- /dev/null +++ b/tests/test_u_async_performance.c.backup @@ -0,0 +1,290 @@ +/** + * Performance benchmark for lib socket management + * Compares array-based vs linked list implementation + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "u_async.h" + +/* Performance measurement */ +static uint64_t get_time_us(void) { + struct timeval tv; + gettimeofday(&tv, NULL); + return (uint64_t)tv.tv_sec * 1000000ULL + tv.tv_usec; +} + +static void test_socket_callback(int fd, void* arg) { + (void)fd; + (void)arg; + // Empty callback for testing +} + + /* Benchmark: Add and remove many sockets */ + static void benchmark_socket_operations(int num_sockets) { + // Test with fewer sockets to isolate buffer overflow - gradually increase + if (num_sockets > 25) { + printf("DEBUG: Reducing num_sockets from %d to 25 for testing\n", num_sockets); + num_sockets = 25; + } + printf("=== Socket Management Benchmark ===\n"); + printf("Testing with %d sockets\n\n", num_sockets); + + uasync_t* ua = uasync_create(); + if (!ua) { + printf("Failed to create uasync\n"); + return; + } + + /* Create socket array */ + int* sockets = malloc(num_sockets * sizeof(int)); + int* socket_fds = malloc(num_sockets * sizeof(int)); // Store FDs instead of pointers + if (!sockets || !socket_fds) { + printf("Memory allocation failed\n"); + free(sockets); + free(socket_fds); + uasync_destroy(ua, 0); + return; + } + + /* Create sockets */ + for (int i = 0; i < num_sockets; i++) { + sockets[i] = socket(AF_INET, SOCK_DGRAM, 0); + if (sockets[i] < 0) { + printf("Failed to create socket %d\n", i); + // Clean up created sockets + for (int j = 0; j < i; j++) { + close(sockets[j]); + } + free(sockets); + free(socket_fds); + uasync_destroy(ua, 0); + return; + } + + /* Make non-blocking */ + int flags = fcntl(sockets[i], F_GETFL, 0); + fcntl(sockets[i], F_SETFL, flags | O_NONBLOCK); + + if (i == 0) { + printf("DEBUG: Socket 0 has fd=%d\n", sockets[i]); + } + } + + printf("Created %d sockets\n", num_sockets); + + /* Benchmark 1: Add all sockets */ + uint64_t start_time = get_time_us(); + int sockets_added = 0; + for (int i = 0; i < num_sockets; i++) { + void* id = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, NULL); + if (!id) { + printf("Failed to add socket %d\n", i); + printf("DEBUG: Only added %d sockets before failure\n", sockets_added); + break; + } + socket_fds[i] = sockets[i]; // Store the file descriptor instead of pointer + sockets_added++; + } + uint64_t add_time = get_time_us() - start_time; + printf("DEBUG: Total sockets added: %d\n", sockets_added); + + printf("Add %d sockets: %llu us (%.2f us per socket)\n", + sockets_added, (unsigned long long)add_time, (double)add_time / sockets_added); + + /* Benchmark 2: Poll multiple times */ + int poll_iterations = 0; // Skip polling to test corruption + uint64_t poll_time = 0; + + printf("SKIPPING POLLING to test corruption\n"); + + /* Benchmark 3: Remove all sockets using lookup function */ + start_time = get_time_us(); + int removed_count = 0; + int failed_count = 0; + + printf("DEBUG: Removing sockets using lookup by FD\n"); + + for (int i = 0; i < sockets_added; i++) { + int fd = socket_fds[i]; + void* id = NULL; + int lookup_result = uasync_lookup_socket(ua, fd, &id); + + if (lookup_result == 0 && id != NULL) { + printf("DEBUG: Attempting to remove socket %d (fd=%d, id=%p)\n", i, fd, id); + int result = uasync_remove_socket(ua, id); + if (result == 0) { + removed_count++; + } else { + failed_count++; + printf("DEBUG: Failed to remove socket %d (fd=%d), result=%d\n", i, fd, result); + } + } else { + printf("DEBUG: Socket %d (fd=%d) lookup failed\n", i, fd); + failed_count++; + } + } + uint64_t remove_time = get_time_us() - start_time; + + printf("DEBUG: Actually removed %d sockets, failed %d\n", removed_count, failed_count); + + printf("Remove %d sockets: %llu us (%.2f us per socket)\n", + sockets_added, (unsigned long long)remove_time, (double)remove_time / sockets_added); + + /* Calculate total time */ + uint64_t total_time = add_time + poll_time + remove_time; + printf("\nTotal time: %llu us\n", (unsigned long long)total_time); + printf("Average per operation: %.2f us\n", (double)total_time / (sockets_added * 2)); + + /* Memory usage - skip to isolate corruption */ + printf("SKIPPING memory stats for corruption testing\n"); + // size_t timer_alloc, timer_free, socket_alloc, socket_free; + // uasync_get_stats(ua, &timer_alloc, &timer_free, &socket_alloc, &socket_free); + // printf("\nMemory stats: timers %zu/%zu, sockets %zu/%zu\n", + // timer_alloc, timer_free, socket_alloc, socket_free); + + /* Cleanup */ + for (int i = 0; i < num_sockets; i++) { + close(sockets[i]); + } + free(sockets); + free(socket_fds); + uasync_destroy(ua, 0); +} + +/* Benchmark: High-frequency operations */ +static void benchmark_high_frequency(void) { + printf("\n=== High-Frequency Operations Benchmark ===\n"); + + uasync_t* ua = uasync_create(); + if (!ua) { + printf("Failed to create uasync\n"); + return; + } + + /* Create a few sockets for high-frequency operations */ + int num_sockets = 10; + int sockets[num_sockets]; + void* socket_ids[num_sockets]; + + for (int i = 0; i < num_sockets; i++) { + sockets[i] = socket(AF_INET, SOCK_DGRAM, 0); + int flags = fcntl(sockets[i], F_GETFL, 0); + fcntl(sockets[i], F_SETFL, flags | O_NONBLOCK); + + socket_ids[i] = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, NULL); + } + + /* Benchmark: Rapid add/remove cycles */ + int cycles = 10000; + printf("Testing %d rapid add/remove cycles...\n", cycles); + + uint64_t start_time = get_time_us(); + for (int cycle = 0; cycle < cycles; cycle++) { + /* Remove all sockets */ + for (int i = 0; i < num_sockets; i++) { + if (socket_ids[i]) { + uasync_remove_socket(ua, socket_ids[i]); + socket_ids[i] = NULL; + } + } + + /* Add them back */ + for (int i = 0; i < num_sockets; i++) { + socket_ids[i] = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, NULL); + } + + /* Poll once per cycle */ + uasync_poll(ua, 0); + } + uint64_t total_time = get_time_us() - start_time; + + printf("Completed %d cycles in %llu us\n", cycles, (unsigned long long)total_time); + printf("Average time per cycle: %.2f us\n", (double)total_time / cycles); + printf("Operations per second: %.0f\n", (double)(cycles * num_sockets * 2) / (total_time / 1000000.0)); + + /* Cleanup */ + for (int i = 0; i < num_sockets; i++) { + close(sockets[i]); + } + uasync_destroy(ua, 0); +} + +/* Benchmark: Scalability test */ +static void benchmark_scalability(void) { + printf("\n=== Scalability Test ===\n"); + + int test_sizes[] = {10, 50, 100, 200, 500, 1000}; + int num_tests = sizeof(test_sizes) / sizeof(test_sizes[0]); + + printf("Testing scalability with different numbers of sockets:\n"); + + for (int test = 0; test < num_tests; test++) { + int num_sockets = test_sizes[test]; + + uasync_t* ua = uasync_create(); + if (!ua) continue; + + /* Create sockets */ + int* sockets = malloc(num_sockets * sizeof(int)); + void** socket_ids = malloc(num_sockets * sizeof(void*)); + + for (int i = 0; i < num_sockets; i++) { + sockets[i] = socket(AF_INET, SOCK_DGRAM, 0); + int flags = fcntl(sockets[i], F_GETFL, 0); + fcntl(sockets[i], F_SETFL, flags | O_NONBLOCK); + + socket_ids[i] = uasync_add_socket(ua, sockets[i], test_socket_callback, NULL, NULL, NULL); + } + + /* Measure poll time */ + uint64_t start_time = get_time_us(); + for (int iter = 0; iter < 100; iter++) { + uasync_poll(ua, 0); + } + uint64_t poll_time = get_time_us() - start_time; + + printf(" %d sockets: %.2f us per poll (%.2f ns per socket)\n", + num_sockets, (double)poll_time / 100, + ((double)poll_time / 100) * 1000 / num_sockets); + + /* Cleanup */ + for (int i = 0; i < num_sockets; i++) { + close(sockets[i]); + } + free(sockets); + free(socket_ids); + uasync_destroy(ua, 0); + } +} + +int main(void) { + printf("lib Socket Management Performance Benchmark\n"); + printf("================================================\n\n"); + + /* Run benchmarks */ + benchmark_socket_operations(25); // 25 sockets for testing + // benchmark_socket_operations(100); // 100 sockets + // benchmark_socket_operations(1000); // 1000 sockets + // benchmark_high_frequency(); // High-frequency operations + // benchmark_scalability(); // Scalability test + + printf("\n=== Benchmark Complete ===\n"); + printf("Array-based socket management provides:\n"); + printf("- O(1) add/remove operations (vs O(n) for linked list)\n"); + printf("- Better cache locality for sequential socket processing\n"); + printf("- Direct FD-to-index mapping for fast lookups\n"); + printf("- Reduced memory allocations per operation\n"); + + return 0; +} \ No newline at end of file diff --git a/tests/track_test b/tests/track_test deleted file mode 100755 index b97490db4..000000000 Binary files a/tests/track_test and /dev/null differ diff --git a/tests/track_test.c b/tests/track_test.c index 212dce356..b6c34942d 100644 --- a/tests/track_test.c +++ b/tests/track_test.c @@ -1,154 +1,159 @@ -#include "u_async.h" +#include "../lib/u_async.h" +#include "../lib/debug_config.h" #include /* Test statistics - same as in the original test */ static struct { - int tests_run; - int tests_passed; - int tests_failed; - - /* Timer statistics */ - int timer_callbacks; - int timer_cancellations; - int immediate_timeouts; - - /* Socket statistics */ - int socket_events; - int socket_errors; - - /* Error statistics */ - int memory_allocation_errors; - int invalid_parameter_errors; - int race_condition_errors; +int tests_run; +int tests_passed; +int tests_failed; + +/* Timer statistics */ +int timer_callbacks; +int timer_cancellations; +int immediate_timeouts; + +/* Socket statistics */ +int socket_events; +int socket_errors; + +/* Error statistics */ +int memory_allocation_errors; +int invalid_parameter_errors; +int race_condition_errors; } test_stats = {0}; /* Test result tracking */ #define TEST_START(name) do { \ - printf("TEST: %s... \n", name); \ - printf(" immediate_timeouts before: %d\n", test_stats.immediate_timeouts); \ - test_stats.tests_run++; \ +DEBUG_INFO(DEBUG_CATEGORY_ALL, "TEST: %s... ", name); \ +DEBUG_INFO(DEBUG_CATEGORY_ALL, "immediate_timeouts before: %d", test_stats.immediate_timeouts); \ +test_stats.tests_run++; \ } while(0) #define TEST_PASS() do { \ - printf(" immediate_timeouts after: %d\n", test_stats.immediate_timeouts); \ - printf("PASS\n"); \ - test_stats.tests_passed++; \ +DEBUG_INFO(DEBUG_CATEGORY_ALL, "immediate_timeouts after: %d", test_stats.immediate_timeouts); \ +DEBUG_INFO(DEBUG_CATEGORY_ALL, "PASS"); \ +test_stats.tests_passed++; \ } while(0) #define TEST_FAIL(msg) do { \ - printf(" immediate_timeouts after: %d\n", test_stats.immediate_timeouts); \ - printf("FAIL: %s\n", msg); \ - test_stats.tests_failed++; \ +DEBUG_INFO(DEBUG_CATEGORY_ALL, "immediate_timeouts after: %d", test_stats.immediate_timeouts); \ +DEBUG_INFO(DEBUG_CATEGORY_ALL, "FAIL: %s", msg); \ +test_stats.tests_failed++; \ } while(0) #define ASSERT_EQ(a, b, msg) do { \ if ((a) != (b)) { \ - printf(" Expected: %ld, Got: %ld\n", (long)(b), (long)(a)); \ + DEBUG_INFO(DEBUG_CATEGORY_ALL, "Expected: %ld, Got: %ld", (long)(b), (long)(a)); \ TEST_FAIL(msg); \ return; \ } \ } while(0) #define ASSERT_NOT_NULL(ptr, msg) do { \ - if ((ptr) == NULL) { \ - TEST_FAIL(msg); \ - return; \ - } \ +if ((ptr) == NULL) { \ +TEST_FAIL(msg); \ +return; \ +} \ } while(0) /* Test context for callbacks */ typedef struct { - int callback_count; - int expected_count; - int callback_arg; - int timeout_ms; - uasync_t* ua; - void* timer_id; +int callback_count; +int expected_count; +int callback_arg; +int timeout_ms; +uasync_t* ua; +void* timer_id; } test_context_t; /* Timer callback for testing */ static void test_timer_callback(void* arg) { - test_context_t* ctx = (test_context_t*)arg; - ctx->callback_count++; - test_stats.timer_callbacks++; - - if (ctx->timeout_ms == 0) { - test_stats.immediate_timeouts++; - } +test_context_t* ctx = (test_context_t*)arg; +ctx->callback_count++; +test_stats.timer_callbacks++; + +if (ctx->timeout_ms == 0) { +test_stats.immediate_timeouts++; +} } /* Test 1: Basic timer functionality */ static void test_basic_timers(void) { - TEST_START("Basic timer functionality"); - - uasync_t* ua = uasync_create(); - ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); - - test_context_t ctx = {0}; - ctx.expected_count = 3; - ctx.timeout_ms = 10; // Non-zero timeout - - /* Set multiple timers with different timeouts */ - void* timer1 = uasync_set_timeout(ua, 10, &ctx, test_timer_callback); /* 1ms */ - void* timer2 = uasync_set_timeout(ua, 20, &ctx, test_timer_callback); /* 2ms */ - void* timer3 = uasync_set_timeout(ua, 30, &ctx, test_timer_callback); /* 3ms */ - - ASSERT_NOT_NULL(timer1, "Failed to set timer 1"); - ASSERT_NOT_NULL(timer2, "Failed to set timer 2"); - ASSERT_NOT_NULL(timer3, "Failed to set timer 3"); - - /* Poll and verify timers fire in order */ - int poll_count = 0; - while (ctx.callback_count < ctx.expected_count && poll_count < 100) { - uasync_poll(ua, 10); /* 1ms poll */ - poll_count++; - } - - ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Not all timers fired"); - - /* Cleanup */ - uasync_destroy(ua, 0); - TEST_PASS(); +TEST_START("Basic timer functionality"); + +uasync_t* ua = uasync_create(); +ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + +test_context_t ctx = {0}; +ctx.expected_count = 3; +ctx.timeout_ms = 10; // Non-zero timeout + +/* Set multiple timers with different timeouts */ +void* timer1 = uasync_set_timeout(ua, 10, &ctx, test_timer_callback); /* 1ms */ +void* timer2 = uasync_set_timeout(ua, 20, &ctx, test_timer_callback); /* 2ms */ +void* timer3 = uasync_set_timeout(ua, 30, &ctx, test_timer_callback); /* 3ms */ + +ASSERT_NOT_NULL(timer1, "Failed to set timer 1"); +ASSERT_NOT_NULL(timer2, "Failed to set timer 2"); +ASSERT_NOT_NULL(timer3, "Failed to set timer 3"); + +/* Poll and verify timers fire in order */ +int poll_count = 0; +while (ctx.callback_count < ctx.expected_count && poll_count < 100) { +uasync_poll(ua, 10); /* 1ms poll */ +poll_count++; +} + +ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Not all timers fired"); + +/* Cleanup */ +uasync_destroy(ua, 0); +TEST_PASS(); } /* Test 3: Immediate timeout handling */ static void test_immediate_timeouts(void) { - TEST_START("Immediate timeout handling"); - - uasync_t* ua = uasync_create(); - ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); - - test_context_t ctx = {0}; - ctx.expected_count = 5; - ctx.timeout_ms = 0; // This should trigger immediate timeout counting - - /* Set multiple immediate timeouts (0ms) */ - for (int i = 0; i < 5; i++) { - void* timer = uasync_set_timeout(ua, 0, &ctx, test_timer_callback); - ASSERT_NOT_NULL(timer, "Failed to set immediate timer"); - } - - /* Immediate timeouts should fire during next poll */ - ASSERT_EQ(ctx.callback_count, 0, "Callbacks fired too early"); - - uasync_poll(ua, 1); /* Minimal poll */ - - ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Immediate timeouts didn't fire correctly"); - ASSERT_EQ(test_stats.immediate_timeouts, 5, "Immediate timeout counter incorrect"); - - uasync_destroy(ua, 0); - TEST_PASS(); +TEST_START("Immediate timeout handling"); + +uasync_t* ua = uasync_create(); +ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + +test_context_t ctx = {0}; +ctx.expected_count = 5; +ctx.timeout_ms = 0; // This should trigger immediate timeout counting + +/* Set multiple immediate timeouts (0ms) */ +for (int i = 0; i < 5; i++) { +void* timer = uasync_set_timeout(ua, 0, &ctx, test_timer_callback); +ASSERT_NOT_NULL(timer, "Failed to set immediate timer"); +} + +/* Immediate timeouts should fire during next poll */ +ASSERT_EQ(ctx.callback_count, 0, "Callbacks fired too early"); + +uasync_poll(ua, 1); /* Minimal poll */ + +ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Immediate timeouts didn't fire correctly"); +ASSERT_EQ(test_stats.immediate_timeouts, 5, "Immediate timeout counter incorrect"); + +uasync_destroy(ua, 0); +TEST_PASS(); } int main() { - printf("=== Tracking immediate_timeouts counter ===\n"); - printf("Initial: immediate_timeouts = %d\n", test_stats.immediate_timeouts); - - test_basic_timers(); - printf("After basic_timers: immediate_timeouts = %d\n", test_stats.immediate_timeouts); - - test_immediate_timeouts(); - printf("After immediate_timeouts: immediate_timeouts = %d\n", test_stats.immediate_timeouts); - - return 0; + +debug_config_init(); +debug_set_level(DEBUG_LEVEL_TRACE); +debug_set_categories(DEBUG_CATEGORY_ALL); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "=== Tracking immediate_timeouts counter ==="); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "Initial: immediate_timeouts = %d", test_stats.immediate_timeouts); + +test_basic_timers(); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "After basic_timers: immediate_timeouts = %d", test_stats.immediate_timeouts); + +test_immediate_timeouts(); +DEBUG_INFO(DEBUG_CATEGORY_ALL, "After immediate_timeouts: immediate_timeouts = %d", test_stats.immediate_timeouts); + +return 0; } diff --git a/tests/track_test.c.backup b/tests/track_test.c.backup new file mode 100644 index 000000000..212dce356 --- /dev/null +++ b/tests/track_test.c.backup @@ -0,0 +1,154 @@ +#include "u_async.h" +#include + +/* Test statistics - same as in the original test */ +static struct { + int tests_run; + int tests_passed; + int tests_failed; + + /* Timer statistics */ + int timer_callbacks; + int timer_cancellations; + int immediate_timeouts; + + /* Socket statistics */ + int socket_events; + int socket_errors; + + /* Error statistics */ + int memory_allocation_errors; + int invalid_parameter_errors; + int race_condition_errors; +} test_stats = {0}; + +/* Test result tracking */ +#define TEST_START(name) do { \ + printf("TEST: %s... \n", name); \ + printf(" immediate_timeouts before: %d\n", test_stats.immediate_timeouts); \ + test_stats.tests_run++; \ +} while(0) + +#define TEST_PASS() do { \ + printf(" immediate_timeouts after: %d\n", test_stats.immediate_timeouts); \ + printf("PASS\n"); \ + test_stats.tests_passed++; \ +} while(0) + +#define TEST_FAIL(msg) do { \ + printf(" immediate_timeouts after: %d\n", test_stats.immediate_timeouts); \ + printf("FAIL: %s\n", msg); \ + test_stats.tests_failed++; \ +} while(0) + +#define ASSERT_EQ(a, b, msg) do { \ + if ((a) != (b)) { \ + printf(" Expected: %ld, Got: %ld\n", (long)(b), (long)(a)); \ + TEST_FAIL(msg); \ + return; \ + } \ +} while(0) + +#define ASSERT_NOT_NULL(ptr, msg) do { \ + if ((ptr) == NULL) { \ + TEST_FAIL(msg); \ + return; \ + } \ +} while(0) + +/* Test context for callbacks */ +typedef struct { + int callback_count; + int expected_count; + int callback_arg; + int timeout_ms; + uasync_t* ua; + void* timer_id; +} test_context_t; + +/* Timer callback for testing */ +static void test_timer_callback(void* arg) { + test_context_t* ctx = (test_context_t*)arg; + ctx->callback_count++; + test_stats.timer_callbacks++; + + if (ctx->timeout_ms == 0) { + test_stats.immediate_timeouts++; + } +} + +/* Test 1: Basic timer functionality */ +static void test_basic_timers(void) { + TEST_START("Basic timer functionality"); + + uasync_t* ua = uasync_create(); + ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + + test_context_t ctx = {0}; + ctx.expected_count = 3; + ctx.timeout_ms = 10; // Non-zero timeout + + /* Set multiple timers with different timeouts */ + void* timer1 = uasync_set_timeout(ua, 10, &ctx, test_timer_callback); /* 1ms */ + void* timer2 = uasync_set_timeout(ua, 20, &ctx, test_timer_callback); /* 2ms */ + void* timer3 = uasync_set_timeout(ua, 30, &ctx, test_timer_callback); /* 3ms */ + + ASSERT_NOT_NULL(timer1, "Failed to set timer 1"); + ASSERT_NOT_NULL(timer2, "Failed to set timer 2"); + ASSERT_NOT_NULL(timer3, "Failed to set timer 3"); + + /* Poll and verify timers fire in order */ + int poll_count = 0; + while (ctx.callback_count < ctx.expected_count && poll_count < 100) { + uasync_poll(ua, 10); /* 1ms poll */ + poll_count++; + } + + ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Not all timers fired"); + + /* Cleanup */ + uasync_destroy(ua, 0); + TEST_PASS(); +} + +/* Test 3: Immediate timeout handling */ +static void test_immediate_timeouts(void) { + TEST_START("Immediate timeout handling"); + + uasync_t* ua = uasync_create(); + ASSERT_NOT_NULL(ua, "Failed to create uasync instance"); + + test_context_t ctx = {0}; + ctx.expected_count = 5; + ctx.timeout_ms = 0; // This should trigger immediate timeout counting + + /* Set multiple immediate timeouts (0ms) */ + for (int i = 0; i < 5; i++) { + void* timer = uasync_set_timeout(ua, 0, &ctx, test_timer_callback); + ASSERT_NOT_NULL(timer, "Failed to set immediate timer"); + } + + /* Immediate timeouts should fire during next poll */ + ASSERT_EQ(ctx.callback_count, 0, "Callbacks fired too early"); + + uasync_poll(ua, 1); /* Minimal poll */ + + ASSERT_EQ(ctx.callback_count, ctx.expected_count, "Immediate timeouts didn't fire correctly"); + ASSERT_EQ(test_stats.immediate_timeouts, 5, "Immediate timeout counter incorrect"); + + uasync_destroy(ua, 0); + TEST_PASS(); +} + +int main() { + printf("=== Tracking immediate_timeouts counter ===\n"); + printf("Initial: immediate_timeouts = %d\n", test_stats.immediate_timeouts); + + test_basic_timers(); + printf("After basic_timers: immediate_timeouts = %d\n", test_stats.immediate_timeouts); + + test_immediate_timeouts(); + printf("After immediate_timeouts: immediate_timeouts = %d\n", test_stats.immediate_timeouts); + + return 0; +} diff --git a/tests/working_crypto_test.c b/tests/working_crypto_test.c index abc1e7ad8..8497d0bf1 100644 --- a/tests/working_crypto_test.c +++ b/tests/working_crypto_test.c @@ -1,4 +1,5 @@ #include +#include "../lib/debug_config.h" #include #include #include @@ -8,97 +9,101 @@ #define SC_SESSION_KEY_SIZE 16 int main() { - printf("=== Working Crypto Test ===\n"); - - // Test AES key setup - struct tc_aes_key_sched_struct sched; - uint8_t test_key[SC_SESSION_KEY_SIZE] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10}; - - printf("Testing AES key setup...\n"); - int aes_result = tc_aes128_set_encrypt_key(&sched, test_key); - printf("tc_aes128_set_encrypt_key returned: %d\n", aes_result); - - if (aes_result == TC_CRYPTO_SUCCESS) { - printf("✓ AES key setup successful\n"); - - // Test CCM config with CORRECT parameters - struct tc_ccm_mode_struct ccm_state = {0}; - TCCcmMode_t c = &ccm_state; - - // CRITICAL: nonce MUST be exactly 13 bytes for CCM! - uint8_t nonce[13] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, - 0x99, 0xAA, 0xBB, 0xCC, 0xDD}; - - printf("\nTesting CCM config with CORRECT parameters...\n"); - printf("Nonce size: 13 (required by CCM standard)\n"); - printf("Tag size: %d (valid: 4,6,8,10,12,14,16)\n", SC_TAG_SIZE); - printf("Using TCCcmMode_t pointer: %p\n", (void*)c); - - int ccm_result = tc_ccm_config(c, &sched, nonce, 13, SC_TAG_SIZE); - printf("tc_ccm_config returned: %d\n", ccm_result); - - if (ccm_result == TC_CRYPTO_SUCCESS) { - printf("✓ CCM config successful!\n"); - - // Test simple encryption - uint8_t plaintext[] = "Hello, World!"; - uint8_t ciphertext[64]; - size_t plaintext_len = sizeof(plaintext) - 1; - size_t ciphertext_len = plaintext_len + SC_TAG_SIZE; - - printf("\nTesting CCM encryption...\n"); - printf("Plaintext: '%s' (%zu bytes)\n", plaintext, plaintext_len); - printf("Expected ciphertext: %zu bytes (data + tag)\n", ciphertext_len); - - int encrypt_result = tc_ccm_generation_encryption(ciphertext, ciphertext_len, - NULL, 0, /* no associated data */ - plaintext, plaintext_len, - c); - printf("tc_ccm_generation_encryption returned: %d\n", encrypt_result); - - if (encrypt_result == TC_CRYPTO_SUCCESS) { - printf("🎉 CCM encryption successful!\n"); - printf("Ciphertext length: %zu bytes\n", ciphertext_len); - - // Test decryption - uint8_t decrypted[64]; - size_t decrypted_len = plaintext_len; - - printf("\nTesting CCM decryption...\n"); - int decrypt_result = tc_ccm_decryption_verification(decrypted, decrypted_len, - NULL, 0, /* no associated data */ - ciphertext, ciphertext_len, - c); - printf("tc_ccm_decryption_verification returned: %d\n", decrypt_result); - - if (decrypt_result == TC_CRYPTO_SUCCESS) { - printf("🎉 CCM decryption successful!\n"); - printf("Decrypted: '%s'\n", decrypted); - - // Verify decrypted data - if (decrypted_len == plaintext_len && memcmp(plaintext, decrypted, plaintext_len) == 0) { - printf("✓ Decrypted data matches original!\n"); - printf("\n🎉 CRYPTO WORKS! AES-CCM encryption/decryption successful!\n"); - return 0; - } else { - printf("❌ Decrypted data doesn't match original\n"); - return 1; - } - } else { - printf("❌ CCM decryption failed\n"); - return 1; - } - } else { - printf("❌ CCM encryption failed\n"); - return 1; - } - } else { - printf("❌ CCM config failed\n"); - return 1; - } - } else { - printf("❌ AES key setup failed\n"); - return 1; - } + +debug_config_init(); +debug_set_level(DEBUG_LEVEL_TRACE); +debug_set_categories(DEBUG_CATEGORY_ALL); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "=== Working Crypto Test ==="); + +// Test AES key setup +struct tc_aes_key_sched_struct sched; +uint8_t test_key[SC_SESSION_KEY_SIZE] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, +0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10}; + +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Testing AES key setup..."); +int aes_result = tc_aes128_set_encrypt_key(&sched, test_key); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "tc_aes128_set_encrypt_key returned: %d", aes_result); + +if (aes_result == TC_CRYPTO_SUCCESS) { +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "✓ AES key setup successful"); + +// Test CCM config with CORRECT parameters +struct tc_ccm_mode_struct ccm_state = {0}; +TCCcmMode_t c = &ccm_state; + +// CRITICAL: nonce MUST be exactly 13 bytes for CCM! +uint8_t nonce[13] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, +0x99, 0xAA, 0xBB, 0xCC, 0xDD}; + +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "\nTesting CCM config with CORRECT parameters..."); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Nonce size: 13 (required by CCM standard)"); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Tag size: %d (valid: 4,6,8,10,12,14,16)", SC_TAG_SIZE); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Using TCCcmMode_t pointer: %p", (void*)c); + +int ccm_result = tc_ccm_config(c, &sched, nonce, 13, SC_TAG_SIZE); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "tc_ccm_config returned: %d", ccm_result); + +if (ccm_result == TC_CRYPTO_SUCCESS) { +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "✓ CCM config successful!"); + +// Test simple encryption +uint8_t plaintext[] = "Hello, World!"; +uint8_t ciphertext[64]; +size_t plaintext_len = sizeof(plaintext) - 1; +size_t ciphertext_len = plaintext_len + SC_TAG_SIZE; + +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "\nTesting CCM encryption..."); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Plaintext: '%s' (%zu bytes)", plaintext, plaintext_len); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Expected ciphertext: %zu bytes (data + tag)", ciphertext_len); + +int encrypt_result = tc_ccm_generation_encryption(ciphertext, ciphertext_len, +NULL, 0, /* no associated data */ +plaintext, plaintext_len, +c); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "tc_ccm_generation_encryption returned: %d", encrypt_result); + +if (encrypt_result == TC_CRYPTO_SUCCESS) { +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "🎉 CCM encryption successful!"); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Ciphertext length: %zu bytes", ciphertext_len); + +// Test decryption +uint8_t decrypted[64]; +size_t decrypted_len = plaintext_len; + +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "\nTesting CCM decryption..."); +int decrypt_result = tc_ccm_decryption_verification(decrypted, decrypted_len, +NULL, 0, /* no associated data */ +ciphertext, ciphertext_len, +c); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "tc_ccm_decryption_verification returned: %d", decrypt_result); + +if (decrypt_result == TC_CRYPTO_SUCCESS) { +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "🎉 CCM decryption successful!"); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "Decrypted: '%s'", decrypted); + +// Verify decrypted data +if (decrypted_len == plaintext_len && memcmp(plaintext, decrypted, plaintext_len) == 0) { +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "✓ Decrypted data matches original!"); +DEBUG_INFO(DEBUG_CATEGORY_CRYPTO, "\n🎉 CRYPTO WORKS! AES-CCM encryption/decryption successful!"); +return 0; +} else { +DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "Decrypted data doesn't match original"); +return 1; +} +} else { +DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "CCM decryption failed"); +return 1; +} +} else { +DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "CCM encryption failed"); +return 1; +} +} else { +DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "CCM config failed"); +return 1; +} +} else { +DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "AES key setup failed"); +return 1; +} } \ No newline at end of file diff --git a/tests/working_crypto_test.c.backup b/tests/working_crypto_test.c.backup new file mode 100644 index 000000000..abc1e7ad8 --- /dev/null +++ b/tests/working_crypto_test.c.backup @@ -0,0 +1,104 @@ +#include +#include +#include +#include +#include + +#define SC_TAG_SIZE 8 // This is valid: 8 bytes +#define SC_SESSION_KEY_SIZE 16 + +int main() { + printf("=== Working Crypto Test ===\n"); + + // Test AES key setup + struct tc_aes_key_sched_struct sched; + uint8_t test_key[SC_SESSION_KEY_SIZE] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10}; + + printf("Testing AES key setup...\n"); + int aes_result = tc_aes128_set_encrypt_key(&sched, test_key); + printf("tc_aes128_set_encrypt_key returned: %d\n", aes_result); + + if (aes_result == TC_CRYPTO_SUCCESS) { + printf("✓ AES key setup successful\n"); + + // Test CCM config with CORRECT parameters + struct tc_ccm_mode_struct ccm_state = {0}; + TCCcmMode_t c = &ccm_state; + + // CRITICAL: nonce MUST be exactly 13 bytes for CCM! + uint8_t nonce[13] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, + 0x99, 0xAA, 0xBB, 0xCC, 0xDD}; + + printf("\nTesting CCM config with CORRECT parameters...\n"); + printf("Nonce size: 13 (required by CCM standard)\n"); + printf("Tag size: %d (valid: 4,6,8,10,12,14,16)\n", SC_TAG_SIZE); + printf("Using TCCcmMode_t pointer: %p\n", (void*)c); + + int ccm_result = tc_ccm_config(c, &sched, nonce, 13, SC_TAG_SIZE); + printf("tc_ccm_config returned: %d\n", ccm_result); + + if (ccm_result == TC_CRYPTO_SUCCESS) { + printf("✓ CCM config successful!\n"); + + // Test simple encryption + uint8_t plaintext[] = "Hello, World!"; + uint8_t ciphertext[64]; + size_t plaintext_len = sizeof(plaintext) - 1; + size_t ciphertext_len = plaintext_len + SC_TAG_SIZE; + + printf("\nTesting CCM encryption...\n"); + printf("Plaintext: '%s' (%zu bytes)\n", plaintext, plaintext_len); + printf("Expected ciphertext: %zu bytes (data + tag)\n", ciphertext_len); + + int encrypt_result = tc_ccm_generation_encryption(ciphertext, ciphertext_len, + NULL, 0, /* no associated data */ + plaintext, plaintext_len, + c); + printf("tc_ccm_generation_encryption returned: %d\n", encrypt_result); + + if (encrypt_result == TC_CRYPTO_SUCCESS) { + printf("🎉 CCM encryption successful!\n"); + printf("Ciphertext length: %zu bytes\n", ciphertext_len); + + // Test decryption + uint8_t decrypted[64]; + size_t decrypted_len = plaintext_len; + + printf("\nTesting CCM decryption...\n"); + int decrypt_result = tc_ccm_decryption_verification(decrypted, decrypted_len, + NULL, 0, /* no associated data */ + ciphertext, ciphertext_len, + c); + printf("tc_ccm_decryption_verification returned: %d\n", decrypt_result); + + if (decrypt_result == TC_CRYPTO_SUCCESS) { + printf("🎉 CCM decryption successful!\n"); + printf("Decrypted: '%s'\n", decrypted); + + // Verify decrypted data + if (decrypted_len == plaintext_len && memcmp(plaintext, decrypted, plaintext_len) == 0) { + printf("✓ Decrypted data matches original!\n"); + printf("\n🎉 CRYPTO WORKS! AES-CCM encryption/decryption successful!\n"); + return 0; + } else { + printf("❌ Decrypted data doesn't match original\n"); + return 1; + } + } else { + printf("❌ CCM decryption failed\n"); + return 1; + } + } else { + printf("❌ CCM encryption failed\n"); + return 1; + } + } else { + printf("❌ CCM config failed\n"); + return 1; + } + } else { + printf("❌ AES key setup failed\n"); + return 1; + } +} \ No newline at end of file