- build.sh: added --full flag for full rebuild (autoreconf + configure + make)
- build_direct.sh: incremental compilation (skips unchanged files)
- build_full.bat: new Windows batch for full rebuild
- configure.ac: fixed Windows detection using AC_COMPILE_IFELSE
- lib/u_async.c/h: Windows wakeup socket support, uasync_post for thread-safe callbacks
- src/tun_if.c/h: cross-platform TUN refactoring, Windows read thread support
- src/tun_windows.c: Windows TUN implementation improvements
- src/control_server.c: removed premature return statement
- src/routing.c: include ordering fix
- src/utun.c: windows compat includes
- Deleted obsolete net_emulator/Makefile and tinycrypt/Makefile
- 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
- Добавлена функция 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 теста проходят
- 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.
- 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.
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().
- etcp_loadbalancer_select_link() теперь пропускает линки со статусом != 1
- При установке initialized=1 сразу выставляется link_status=1 (up)
- Добавлено логирование при изменении статуса линка на UP
- Добавлен параметр 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()
- Добавлены поля keepalive_timer и pkt_sent_since_keepalive в struct ETCP_LINK
- Реализована отправка пустых keepalive пакетов (только timestamp) по таймеру
- Keepalive пропускается если был отправлен другой пакет с момента последнего тика
- Таймер запускается после инициализации линка (keepalive_interval из конфига)
- Исправлен тест test_bgp_route_exchange: убран лишний htonl() при проверке маршрутов
uasync генерирует слишком много служебных логов.
Теперь по умолчанию включены все категории кроме uasync.
Для включения uasync логов используйте:
debug_categories=all
или
debug_categories=uasync,connection,etcp
Проблема: recv() на netlink сокете блокировал бесконечно,
если ядро не отвечало на сообщение.
Решение:
- Добавлен флаг SOCK_NONBLOCK при создании сокета
- Добавлен poll() с таймаутом 1 секунда перед recv()
- Добавлен заголовок poll.h
Теперь utun не зависает при старте и продолжает инициализацию сокетов.
Использован ntohl() для преобразования сетевого адреса из network byte order
в host byte order перед добавлением в таблицу маршрутизации.
Теперь маршруты отображаются корректно (10.23.1.0 вместо 0.1.23.10).
- Переименовано поле 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 для сборки новых файлов
- Добавлен platform_compat.c с кроссплатформенной генерацией случайных чисел
- Исправлена генерация ключей и node_id на Windows (вместо /dev/urandom)
- PID файл отключен по умолчанию на Windows
- Добавлено двойное логирование: файл utun.log + консоль
- Добавлен манифест Windows для запроса прав администратора
- Исправлено завершение программы при ошибках отправки (Network unreachable)
- TUN инициализация включена по умолчанию
- Исправлен main loop (instance->running = 1)
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.
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
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.
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)
- Создана общая функция instance_init_common() для инициализации instance
- Упрощены utun_instance_create() и utun_instance_create_from_config()
- Удалено ~90 строк дублирующегося кода
- Обе функции теперь используют общую логику инициализации
- Добавлена опция tun_test_mode в конфиг для работы без реального TUN устройства
- Добавлены функции для работы с очередями TUN в тестовом режиме
- Добавлен API для программного создания instance из структуры конфига
- Создан тест test_routing_mesh.c с 3-instance mesh топологией
- Ключи генерируются автоматически и распределяются между instance
- 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