Commit Graph
223 Commits
Author SHA1 Message Date
Evgeny a36cf652ff Backup before fixing test_routing_mesh segfault 2026-02-16 22:02:57 +03:00
Evgeny 42cd803432 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 da5aedd241 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 5a7b8584c0 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 8c4f21d26c config: отключены логи uasync по умолчанию
uasync генерирует слишком много служебных логов.
Теперь по умолчанию включены все категории кроме uasync.

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

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

Теперь utun не зависает при старте и продолжает инициализацию сокетов.
2026-02-16 18:12:18 +03:00
Evgeny f00d297f14 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 3005086e7e 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 84c9131d53 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 4885414884 Remove generated Makefile and temp file src/aa from repo (already in .gitignore) 2026-02-16 11:16:14 +03:00
jeka 57c935a917 Remove temp build files (cl, build_win.log) and update .gitignore 2026-02-16 10:44:53 +03:00
jeka 1c83fbdcd6 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 7fa00bafa6 Fix port conflicts in test_pkt_normalizer_etcp - use unique ports 9041/9042 2026-02-16 10:35:26 +03:00
jeka d74937e754 Fix Windows test failures: proper WSAPoll error handling and FD_SETSIZE check 2026-02-16 10:33:43 +03:00
jeka 7e30aa6347 1 2026-02-16 08:44:05 +03:00
Evgeny bbed90cee5 Debug: Enable crypto packet dumps conditionally based on debug level 2026-02-16 08:15:51 +03:00
Evgeny 7a4d256228 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 915b6ff7d1 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 1cd31b00bf 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 4eaabf2e1c 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 f12466d06e Mesh test с файлами конфигов - все еще ошибки расшифровки 2026-02-15 21:36:18 +03:00
Evgeny ad4cc9a17a WIP: исправление портов и добавление отладки в mesh test 2026-02-15 21:32:32 +03:00
Evgeny 3717daae52 Рефакторинг 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 32610304d3 Добавлен тестовый режим для 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 a25030020e Remove test binaries from git tracking (now ignored) 2026-02-15 18:57:23 +03:00
Evgeny 03e3286eb9 Update .gitignore: add test binaries and all log files 2026-02-15 18:55:53 +03:00
Evgeny f8b8705464 Simplify: Extract common crypto logic into helper functions for both OpenSSL and TinyCrypt 2026-02-15 18:47:49 +03:00
Evgeny 1740c51db0 Simplify: Remove unreachable duplicate code block in init_connections 2026-02-15 18:40:43 +03:00
Evgeny 2451160632 Simplify: Deduplicate queue cleanup in etcp_connection_close using helper functions 2026-02-15 18:39:03 +03:00
Evgeny 705ebd94c0 Backup: before code simplification refactoring 2026-02-15 18:37:23 +03:00
jeka 721d5e39f4 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 b09f10712b 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 e259364850 Backup before fixing u_async socket registration bug 2026-02-15 17:25:34 +03:00
Evgeny 48b9a470d2 Add check.bat - Windows test runner script 2026-02-15 16:17:00 +03:00
Evgeny e3d55c4de3 Fix test_u_async_comprehensive: add Windows socketpair replacement using UDP sockets 2026-02-15 14:31:31 +03:00
Evgeny 5a94e4b9f6 Fix remaining test files: replace POSIX headers with platform_compat.h 2026-02-15 13:25:05 +03:00
Evgeny 1432f7c80f Fix test_u_async_comprehensive.c: replace POSIX headers with platform_compat.h 2026-02-15 13:18:34 +03:00
Evgeny f9153a3538 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 4314b7d8eb Fix Windows: use sys/time.h for gettimeofday, remove custom implementation 2026-02-15 12:57:53 +03:00
Evgeny f67a138714 Fix Windows build: skip gettimeofday on MSYS2, force recompile ecc_platform_specific 2026-02-15 12:26:32 +03:00
Evgeny df092af751 Touch ecc_platform_specific.c to force recompilation 2026-02-15 11:54:20 +03:00
Evgeny f8419372f0 Fix ecc_platform_specific.c: check Windows first, fix typo (| to ||), add stdint.h 2026-02-15 04:47:53 +03:00
Evgeny 2e0f01e36b Fix tests Makefile.am: WIN_LIBS must be defined before COMMON_LIBS 2026-02-15 04:41:25 +03:00
Evgeny 2e4a14d0b8 Add -ladvapi32 for Windows CryptGenRandom support 2026-02-15 04:36:47 +03:00
Evgeny e7f6aa7086 Fix Windows build: add default_CSPRNG and improve build.sh error handling
- Add Windows implementation of default_CSPRNG() using CryptGenRandom
- Add fallback stub for platforms without CSPRNG support
- Fix build.sh to properly detect build failures (use PIPESTATUS)
- Show proper error message instead of "Build completed successfully" on failure
2026-02-15 04:34:05 +03:00
Evgeny 108e55a3c5 Fix remaining Windows test build issues
- Remove sys/socket.h include from test_etcp_two_instances.c (Linux-only)
- Fix test_mkdtemp buffer overflow - use memcpy instead of strncpy
- Fix test_mkdtemp return value check (replace == NULL with != 0)
- Add Windows socket libraries (-lws2_32 -liphlpapi) to test builds
- All tests build successfully on Linux
2026-02-15 04:24:46 +03:00
Evgeny 4826751596 Fix test files for Windows cross-platform compatibility
- Create test_utils.h with cross-platform utility functions:
  * test_mkdtemp() - Windows uses GetTempPath + _mkdir, Linux uses mkdtemp
  * test_unlink() - Windows _unlink, Linux unlink
  * test_rmdir() - Windows _rmdir, Linux rmdir

- Update all test files to use test_utils.h
- Replace arpa/inet.h and netinet/in.h with platform_compat.h
- Replace unistd.h with conditional includes
- Replace mkdtemp(), unlink(), rmdir() with test_* versions

- Tests now build on both Linux and Windows
- Note: Some integration tests may fail on Linux due to test environment
2026-02-15 04:09:24 +03:00
Evgeny 57e771f64d Fix Windows build: use WSAPoll instead of poll for linking 2026-02-15 03:54:35 +03:00
Evgeny 05d298318e Fix Windows build: wintun function pointer declarations
- Add * to Wintun function pointer declarations (wintun.h defines types as functions)
- Use (void *) cast in GetProcAddress to avoid errors
- All 22 tests pass on Linux
2026-02-15 03:49:47 +03:00
Evgeny 4a952d6c7e Fix Windows build: tun_windows.c function pointers and MIB_IPINTERFACE_ROW
- Fix function pointer declarations in tun_windows.c (removed broken macro)
- Use explicit GetProcAddress calls for each Wintun function
- Remove invalid fields from MIB_IPINTERFACE_ROW (PromiscuousMode, DadState, etc.)
- Add #ifndef _WIN32 around IF_NAMESIZE/if_indextoname in etcp_connections.c
- All 22 tests pass on Linux
2026-02-15 03:46:05 +03:00