Commit Graph
383 Commits
Author SHA1 Message Date
jeka 734851329f Control: Add monitoring server with ETCP protocol support
- Implement control_server.c/h for monitoring and management
- Add Windows-compatible uasync_poll using select() instead of WSAPoll
- Fix Wintun adapter creation to open existing adapters first
- Add debug category for control server operations
- Update build files to include control server in compilation
- Add test_control_server to test suite
2026-02-19 01:24:42 +03:00
Evgeny 96100663e7 Exclude test_dummynet from make check (temporarily disabled due to long execution time) 2026-02-17 21:31:47 +03:00
Evgeny 00e09c767e ETCP: реализация восстановления связи при падении всех линков
- Добавлена функция etcp_loadbalancer_get_link_status() для проверки состояния связи
- Клиент: при падении всех линков запускается отправка ETCP_INIT_REQUEST_NOINIT (0x04)
- Сервер: при приеме NOINIT отвечает ETCP_INIT_RESPONSE_NOINIT (0x05) без сброса если линк initialized
- При приеме любого пакета отменяется таймер восстановления
- ETCP_INIT_RESPONSE (0x03) вызывает сброс всего ETCP_CONN
- Переименованы константы: ETCP_CHANNEL_INIT -> ETCP_INIT_REQUEST_NOINIT,
  ETCP_CHANNEL_RESPONSE -> ETCP_INIT_RESPONSE_NOINIT

Все 23 теста проходят
2026-02-17 01:41:05 +03:00
jeka 79e980c17d 1 2026-02-17 00:53:27 +03:00
jeka 47f2f8a025 Build: Fix Windows build with OpenSSL support
- Added automatic OpenSSL detection for MSYS2 UCRT64 in configure.ac
- Simplified build.sh to use direct build script on Windows
- Added build_direct.sh for bypassing make/autotools issues
- Fixed CFLAGS/LDFLAGS to include OpenSSL paths
- Binary now correctly links with libcrypto-3-x64.dll

Fixes linker errors for uECC_* and tc_* functions when using OpenSSL.
2026-02-17 00:21:39 +03:00
jeka 8a3cdaf759 1 2026-02-16 23:42:28 +03:00
jeka 3ab19094d0 Fix: segfault in ETCP tests and add wintun.dll to gitignore
- Fix segfault in ETCP tests by initializing uECC RNG in sc_init_local_keys()
- Fix segfault during cleanup by adding reference counting to socket_platform_cleanup()
- Add wintun.dll to .gitignore
- Update AGENTS.md and platform compatibility headers

All 19 tests now pass successfully.
2026-02-16 23:36:50 +03:00
Evgeny 7781c4676b Fix: Segfault in test_routing_mesh during cleanup
In pn_deinit(), cancel waiter on etcp->input_queue and clear callback
on etcp->output_queue before freeing PKTNORM structure. This prevents
use-after-free when drain_and_free_fragment_queue() triggers
check_waiters() during etcp_connection_close().
2026-02-16 22:04:03 +03:00
Evgeny a5818d9cc4 Backup before fixing test_routing_mesh segfault 2026-02-16 22:02:57 +03:00
Evgeny 0490c846c2 ETCP: loadbalancer исключает down-линки, link_status=1 при инициализации
- etcp_loadbalancer_select_link() теперь пропускает линки со статусом != 1
- При установке initialized=1 сразу выставляется link_status=1 (up)
- Добавлено логирование при изменении статуса линка на UP
2026-02-16 19:57:20 +03:00
Evgeny bf33ae4e47 ETCP: добавлена проверка keepalive таймаута и статус линка
- Добавлен параметр keepalive_timeout в глобальный конфиг (default: 2000 ms)
- Добавлено поле keepalive_timeout в struct ETCP_LINK
- В keepalive_timer_cb() добавлена проверка таймаута по last_recv_local_time
- Выставление link_status: 1 (up) при получении пакетов, 0 (down) при таймауте
- Инициализация last_recv_local_time при создании линка
- Вывод keepalive_timeout в print_config()
2026-02-16 19:44:27 +03:00
Evgeny 15a9521559 ETCP: реализация keepalive пакетов для каждого линка
- Добавлены поля keepalive_timer и pkt_sent_since_keepalive в struct ETCP_LINK
- Реализована отправка пустых keepalive пакетов (только timestamp) по таймеру
- Keepalive пропускается если был отправлен другой пакет с момента последнего тика
- Таймер запускается после инициализации линка (keepalive_interval из конфига)
- Исправлен тест test_bgp_route_exchange: убран лишний htonl() при проверке маршрутов
2026-02-16 19:17:47 +03:00
Evgeny 232bd49309 config: отключены логи uasync по умолчанию
uasync генерирует слишком много служебных логов.
Теперь по умолчанию включены все категории кроме uasync.

Для включения uasync логов используйте:
  debug_categories=all
или
  debug_categories=uasync,connection,etcp
2026-02-16 18:22:57 +03:00
Evgeny 424e2c6b14 fix: исправлена блокировка при добавлении маршрутов через netlink
Проблема: recv() на netlink сокете блокировал бесконечно,
если ядро не отвечало на сообщение.

Решение:
- Добавлен флаг SOCK_NONBLOCK при создании сокета
- Добавлен poll() с таймаутом 1 секунда перед recv()
- Добавлен заголовок poll.h

Теперь utun не зависает при старте и продолжает инициализацию сокетов.
2026-02-16 18:12:18 +03:00
Evgeny d917b42942 fix: исправлен порядок байт при добавлении маршрутов из конфига
Использован ntohl() для преобразования сетевого адреса из network byte order
в host byte order перед добавлением в таблицу маршрутизации.
Теперь маршруты отображаются корректно (10.23.1.0 вместо 0.1.23.10).
2026-02-16 17:33:33 +03:00
Evgeny 4cd22b1513 feat: переименован allowed_subnet в route_subnet, добавлено управление системными маршрутами
- Переименовано поле allowed_subnets -> route_subnets в конфигурации
- Обновлен парсинг конфига: allowed_subnet -> route_subnet
- Создан новый модуль tun_route для управления системными маршрутами
- Linux: реализация через netlink sockets с fallback на ip route
- Windows: реализация через IP Helper API
- BSD: реализация через routing sockets с fallback на route
- При запуске: автоматическое добавление маршрутов route_subnet на TUN интерфейс
- При завершении: автоматическое удаление всех маршрутов через tun_route_flush
- Обновлены Makefile.am для сборки новых файлов
2026-02-16 17:07:52 +03:00
jeka 4a3c5724b7 Windows: Исправлен запуск utun - TUN, логирование, права администратора
- Добавлен platform_compat.c с кроссплатформенной генерацией случайных чисел
- Исправлена генерация ключей и node_id на Windows (вместо /dev/urandom)
- PID файл отключен по умолчанию на Windows
- Добавлено двойное логирование: файл utun.log + консоль
- Добавлен манифест Windows для запроса прав администратора
- Исправлено завершение программы при ошибках отправки (Network unreachable)
- TUN инициализация включена по умолчанию
- Исправлен main loop (instance->running = 1)
2026-02-16 14:31:16 +03:00
jeka 697f362d54 1 2026-02-16 11:20:14 +03:00
jeka 8a5a5c361f Remove generated Makefile and temp file src/aa from repo (already in .gitignore) 2026-02-16 11:16:14 +03:00
jeka 8263db2726 Remove temp build files (cl, build_win.log) and update .gitignore 2026-02-16 10:44:53 +03:00
jeka 9c768bfd17 Fix timer leaks in ETCP: cancel retrans_timer, ack_resp_timer, and shaper_timer on connection close 2026-02-16 10:39:36 +03:00
jeka a0b02b9812 Fix port conflicts in test_pkt_normalizer_etcp - use unique ports 9041/9042 2026-02-16 10:35:26 +03:00
jeka 78dfdde400 Fix Windows test failures: proper WSAPoll error handling and FD_SETSIZE check 2026-02-16 10:33:43 +03:00
jeka 6dfeac03a8 1 2026-02-16 08:44:05 +03:00
Evgeny 603768052d Debug: Enable crypto packet dumps conditionally based on debug level 2026-02-16 08:15:51 +03:00
Evgeny a73e36b559 Fix mesh topology: try normal decryption first, then INIT
Reversed the decryption order:
1. If link exists with session_ready, try normal decryption first
2. If normal decryption succeeds, process packet normally (goto process_decrypted)
3. If normal decryption fails OR no link OR no session, try INIT decryption
4. If INIT succeeds, create new server-side connection and link

This is more efficient because:
- Most packets are regular data (use normal decryption)
- INIT packets are rare (only during connection setup)
- Works correctly for both standard client-server and mesh topologies

All 23 tests now pass.
2026-02-16 01:02:10 +03:00
Evgeny 27b02cef68 Fix mesh topology handling with fallback to normal decryption
When receiving packets on client links, try INIT decryption first.
If it fails (e.g., for INIT_RESPONSE packets), fallback to normal
decryption using the existing link's crypto context.

This fixes mesh topology where both nodes send INIT simultaneously,
while maintaining compatibility with standard client-server mode where
client links receive INIT_RESPONSE packets.

Changes:
- If link==NULL OR link is client (is_server==0), try INIT decryption
- On any INIT decryption error, if we have an existing link, goto normal_decrypt
- Added normal_decrypt label before standard packet processing
- This allows handling both incoming INIT (create server link) and
  incoming responses (use existing client link) correctly
2026-02-16 00:51:28 +03:00
Evgeny 1cc475e9b0 Rewrite test_routing_mesh to use programmatic config creation
Replaced file-based config creation with direct struct population.
This eliminates temporary files and makes the test cleaner.

Key changes:
- Added helper functions for creating config structures
- Create CFG_SERVER, CFG_CLIENT, CFG_CLIENT_LINK programmatically
- Use utun_instance_create_from_config() instead of file-based creation
- No temp directories or file cleanup needed

The test now builds configs in memory using helper functions like
make_sockaddr(), create_server(), create_client(), etc.
2026-02-15 23:56:18 +03:00
Evgeny 0a4373ffe1 Fix: Treat client links as INIT packets on receive
When receiving an INIT packet, the code was looking up existing links by
address. However, in a mesh topology where each node has both client and
server connections to peers, a client link created during initialization
would be found when receiving an incoming INIT packet from that peer.

This caused the code to try decrypting the INIT packet using the client
link's crypto context, which failed because the session keys weren't
properly established yet.

The fix checks if the found link is a client link (is_server==0) and if
so, treats the packet as a new INIT connection that needs to create a
server-side link instead.

Changed condition from:
  if (link==NULL)
to:
  if (link==NULL || link->is_server==0)
2026-02-15 23:35:23 +03:00
Evgeny f7e1234d3d Mesh test с файлами конфигов - все еще ошибки расшифровки 2026-02-15 21:36:18 +03:00
Evgeny 59f01c6a15 WIP: исправление портов и добавление отладки в mesh test 2026-02-15 21:32:32 +03:00
Evgeny c1e2f061b9 Рефакторинг utun_instance_create - устранено дублирование кода
- Создана общая функция instance_init_common() для инициализации instance
- Упрощены utun_instance_create() и utun_instance_create_from_config()
- Удалено ~90 строк дублирующегося кода
- Обе функции теперь используют общую логику инициализации
2026-02-15 20:44:14 +03:00
Evgeny bee1e41b07 Добавлен тестовый режим для TUN интерфейса и тест роутинга mesh
- Добавлена опция tun_test_mode в конфиг для работы без реального TUN устройства
- Добавлены функции для работы с очередями TUN в тестовом режиме
- Добавлен API для программного создания instance из структуры конфига
- Создан тест test_routing_mesh.c с 3-instance mesh топологией
- Ключи генерируются автоматически и распределяются между instance
2026-02-15 20:37:10 +03:00
Evgeny 602d9174a4 Remove test binaries from git tracking (now ignored) 2026-02-15 18:57:23 +03:00
Evgeny 704554af84 Update .gitignore: add test binaries and all log files 2026-02-15 18:55:53 +03:00
Evgeny eb721be508 Simplify: Extract common crypto logic into helper functions for both OpenSSL and TinyCrypt 2026-02-15 18:47:49 +03:00
Evgeny 25f5b84bf9 Simplify: Remove unreachable duplicate code block in init_connections 2026-02-15 18:40:43 +03:00
Evgeny f4295d962e Simplify: Deduplicate queue cleanup in etcp_connection_close using helper functions 2026-02-15 18:39:03 +03:00
Evgeny ca16d175e6 Backup: before code simplification refactoring 2026-02-15 18:37:23 +03:00
jeka 806226c049 Remove test logs from git and add to .gitignore
- Remove tests/logs/ directory from git tracking
- Add tests/logs/ to .gitignore
2026-02-15 18:05:14 +03:00
jeka 10d6b28090 Update test logs after u_async fixes 2026-02-15 17:56:50 +03:00
jeka c8af35c4b9 Fix u_async: Windows socket registration, timers, and poll issues
- Remove FD_SETSIZE check for Windows sockets (can have any value)
- Fix process_timeouts to handle all expired timers (continue instead of break)
- Handle case when no sockets to poll (sleep instead of calling poll)
- Disable wakeup pipe on Windows (incompatible with WSAPoll)
- Add gettimeofday and ssize_t implementations for Windows
2026-02-15 17:38:45 +03:00
jeka 53c7330a7f Backup before fixing u_async socket registration bug 2026-02-15 17:25:34 +03:00
Evgeny e29ae4dea8 Add check.bat - Windows test runner script 2026-02-15 16:17:00 +03:00
Evgeny 28ff3a4776 Fix test_u_async_comprehensive: add Windows socketpair replacement using UDP sockets 2026-02-15 14:31:31 +03:00
Evgeny 20a3eaf73c Fix remaining test files: replace POSIX headers with platform_compat.h 2026-02-15 13:25:05 +03:00
Evgeny c75ac9d23b Fix test_u_async_comprehensive.c: replace POSIX headers with platform_compat.h 2026-02-15 13:18:34 +03:00
Evgeny 29d26cf139 Force rebuild of utun-ecc_platform_specific.o on every build to ensure platform-specific changes are picked up 2026-02-15 13:09:10 +03:00
Evgeny f510d78bb5 Fix Windows: use sys/time.h for gettimeofday, remove custom implementation 2026-02-15 12:57:53 +03:00
Evgeny 4403c46788 Fix Windows build: skip gettimeofday on MSYS2, force recompile ecc_platform_specific 2026-02-15 12:26:32 +03:00