Commit Graph
53 Commits
Author SHA1 Message Date
Evgeny 0b5a710fe6 etcp_connect + BGP_READY callbacks + router reconnect test
- etcp_connect.c: async connect API with EARLY/LATE/BGP_READY callbacks
- etcp_connect.h: declaration (via etcp_api.h)
- connect_deliver: fix to preserve unfired callback nodes
- etcp_set_routing_exchange_state: fires bgp_ready_cbk on TABLE_COMPLETE
- route_bgp: TABLE_COMPLETE handler + route_bgp_send_table_complete
- etcp.c: connections_count tracking, cleanup on close
- test_etcp_router_reconnect: a-b-c topology with b restart (etcp_connect)
- test_etcp_connect: unit tests for async connect API
- etcp_router: inflight/retrans/close improvements
- Various proxy/NAT/router cleanups
2026-07-04 18:51:01 +03:00
Evgeny a7b20f268f feat: conn_mgr, dummynet block-addr, indirect routing, alien nodes, nodeinfo refactor 2026-06-29 20:01:40 +03:00
Evgeny 150e9977df stcp: unified transport — etcp_send/bind over TCP via stcp_link
- stcp_link.h/c: manage TCP connections through STCP protocol
  stcp_server_listen, stcp_link_connect/send/close
  rx dispatch goes directly through inst->api_bindings (single table)
- etcp_api.c: etcp_send checks conn->transport_link for TCP path
  etcp_bind stores only in api_bindings (no duplication)
- etcp_connections.c: init_sockets creates stcp_server for TCP
  init_connections creates stcp_link_connect for TCP clients
  tcp_server_on_link creates minimal ETCP_CONN + fires callbacks
- etcp.h: ETCP_CONN.transport_link field (NULL for UDP, set for TCP)
- config_parser: CFG_SERVER.transport field, parsing transport=tcp|udp
- utun_instance.h: struct stcp_server*
- Tests: test_stcp_link (handshake, wrong key)
         test_etcp_stcp (etcp_send/bind over TCP)
- Renamed: transport.h/c → stcp_link.h/c (cleaner, no bindings table)
- 46/46 tests pass
2026-06-16 01:19:58 +03:00
Evgeny 474bb8bd6b bbdr: rename BBR log fields, add mode transition logs, configurable max inflight 2026-06-11 11:06:31 +03:00
Evgeny 5982b011b4 etcp: restore etcp_link_update_inflight_lim + state machine fixes + diagnostics
- etcp_link_update_inflight_lim: self-contained method with clamping,
  send_blocked_inflight check, loadbalancer_link_ready on cwnd increase
- etcp_conn_on_inflight_lim_changed: recalc optimal_inflight + resume input
- etcp_ack_recv: use etcp_link_update_inflight_lim instead of manual set
- etcp_request_pkt: fix line 928 check old link (inf_pkt->last_link) not new
- etcp_link_close: recalc optimal_inflight on link removal (both branches)
- etcp_socket_remove: fix dangling pointer loop (nullify after close)
- uasync_print_resources: show timer names, remain time, deleted entries
- diagnostics in utun_instance_destroy and test_etcp_reconnect
2026-06-09 16:40:37 +03:00
Evgeny 6c79939db3 congestion: заменить AIMD на BBR v3 (per-link), добавить юнит-тесты BBR
- Новые файлы: src/etcp_bbr.h/c — полный порт BBR v3 из BBR/bbr_v3.c (референс сохранён)
- struct ETCP_LINK: удалены AIMD-поля (rtt_history, rtt_swm, stat_win, stats_timer, inflight_phase...), добавлены bbr*, delivered_bytes, bbr_pacing_rate
- struct INFLIGHT_PACKET: +3 поля для rate_sample (delivered_at_send, inflight_at_send, is_app_limited)
- etcp_ack_recv: вызов bbr_main() с rate_sample, обновление inflight_lim_bytes и pacing
- etcp_request_pkt: заполнение BBR rate_sample полей при отправке
- Шейпер: bandwidth обновляется из bbr_pacing_rate
- Конфиг: inflight_min/max заменены на bbr_max_cwnd
- Дамп: BBR поля (mode, cycle, pacing, min_rtt_us, bw_hi/lo, inflight_hi/lo)
- Time injection: bbr->now_tb для детерминированных тестов
- tests/test_etcp_bbr.c: 8 юнит-тестов (init, startup, full_bw/drain, loss, cwnd cap, loss cut, fast_path, probe_rtt)
- Отключены test_etcp_congestion и test_etcp_reinit_inflight (старый congestion control)
- 40/40 тестов пройдено
2026-06-01 12:58:31 +03:00
Evgeny b829ff7001 fix use-after-free in tests: swap queue_entry_free/queue_dgram_free order, fix dangling timer handles and stack args; add ETCP MTU bounds, assembly overflow check, etcp_update_mtu 2026-05-13 12:38:20 +03:00
Evgeny 61fee27478 congestion: burst-based BW measurement + adaptive inflight (slow start/cong avoidance/loss response)
New features:
- get_time_us() in lib/u_async.c/h for µs-precision timing
- Burst measurement (ETCP_SECTION_MEAS_TS 0x07, MEAS_RESP 0x08, FILLER 0x09)
  - 12 MTU packets sent at line rate, receiver measures inter-packet gaps
  - Burst triggered when link saturated + min 500ms interval
  - Result: measured BW -> bandwidth for shaper, burst_target_bdp for window cap
- 3-phase adaptive inflight in link_stats_timer_cb:
  - Slow start: windows doubles each RTT, exits on loss/RTT spike/threshold
  - Congestion avoidance: additive increase, proportional RTT shrink, multiplicative loss shrink
  - Burst target cap: inflight_lim <= burst_target_bdp * 1.1
- Dynamic optimal_inflight = sum(link->inflight_lim_bytes), recalculated on change
- Adaptive win_timebase = rtt/2 (was hardcoded 10ms)

Fixes:
- dummynet.c: shaper formula fixed (80000 -> 80)
- dummynet.c: queue_data_put call fixed (3 args -> 2)
- etcp.c: SIZE ERROR format string (missing log_name argument)
- etcp_request_pkt: FILLER leaves room for PAYLOAD overhead

Tests:
- test_etcp_congestion.c: single-threaded, 5-phase BW/delay/loss test
  - sender + receiver + dummynet in one uasync
  - CSV metrics output every 100ms
- All 29 existing tests pass
2026-04-26 00:17:32 +03:00
Evgeny 33fd5bc123 ETCP: add session_id to prevent false reinit on new link addition
- Added 32-bit session_id to ETCP_CONN struct (random per client)
- Session_id transmitted in INIT_REQUEST/RESPONSE after node_id
- Server: skip reinit if session_id matches existing connection
- Server: send INIT_RESPONSE (0x03) only when reinit actually done
- Server: send INIT_RESPONSE_NOINIT (0x05) for same session
- Client: ignore INIT_RESPONSE with wrong session_id
- Fixed tx_state initialization in etcp_conn_ready for noinit case
- All 26 tests passing
2026-04-22 23:53:25 +03:00
Evgeny 385aa066b2 Add duplicate packet counter to ACK frames
- Add rx_dup_count (local) and tx_dup_count (remote via ACK) to ETCP_CONN
- Extend ACK section format: add 16-bit rx_dup_count after last_delivered_id
- Reconstruct 32-bit tx_dup_count from received 16-bit diff
- Update etcpmon protocol and control_server to expose counters
- Update packet dumper for new ACK format
2026-04-22 16:04:11 +03:00
Evgeny 6a971389b6 channel select: round-robin and inflight 2026-04-22 00:04:20 +03:00
Evgeny 097e1acc6d queue: add variable size hash
bgp: add to headers new node info
2026-03-28 21:52:46 +03:00
jeka 26cfa3209a add per-link inflight 2026-03-22 20:08:16 +03:00
jeka 3153c5eaaf 1 2026-03-21 21:04:46 +03:00
jeka 1ee288fdeb 1 2026-03-18 14:16:31 +03:00
jeka 4c3681c045 control socket disconnect fix 2026-03-17 15:37:51 +03:00
Evgeny 06323dbad1 1 2026-03-13 16:24:55 +03:00
jeka 771cbc1c3f ack fix 2026-03-13 12:29:20 +03:00
jeka aa5171bcd1 route improvements 2026-03-12 02:57:38 +03:00
jeka 33629a17c6 etcp - добавлено etcp_on_conn_ready callback_fn
+ trace + по мелочи
2026-03-11 19:10:10 +03:00
jeka 5816fbea70 1 2026-03-08 17:19:38 +03:00
jeka 8880db0ca2 1 2026-03-08 16:52:24 +03:00
jeka 220d23daf7 1 2026-03-07 22:44:19 +03:00
jeka b1c8ba7e90 add metrics to monitor 2026-03-07 19:01:14 +03:00
jeka d06bfffc68 1 2026-03-07 17:11:40 +03:00
Evgeny 4352041416 1 2026-03-07 15:28:12 +03:00
jeka 46c95b3fd8 +bping +gui rtt 2026-03-04 23:14:32 +03:00
jeka 0ffcfb2f52 reset fix 2026-03-03 18:41:39 +03:00
jeka 9d0223d3fa refactor 2026-02-28 15:15:34 +03:00
Evgeny 68668821e4 BGP: Implement route exchange module between uTun instances
- Add route_bgp.c/h with BGP-like route exchange functionality
- Implement route_bgp_init/destroy for module lifecycle
- Add route_bgp_new_conn to send routing table on connection
- Implement route_bgp_receive_cbk for processing incoming routes
- Add route_table_delete_entry for individual route removal
- Extend ROUTE_ENTRY with endpoint_ip, endpoint_port, destination_node_id
- Add DEBUG_CATEGORY_BGP to debug_config.h
- Integrate BGP initialization into utun_instance_create
- Call route_bgp_new_conn from etcp_connections on link init
- Create integration test test_bgp_route_exchange.c
- Add route_bgp_delete_entry tests to test_route_lib.c
- Update Makefiles to include new module

Route exchange tested and working in both directions (client-server)
2026-02-14 20:37:14 +03:00
Evgeny ce15d6b883 Backup before route_lib.c refactoring 2026-02-13 18:12:26 +03:00
Evgeny c1890ad7a6 Debug: Add ETCP log_name identifier and improve log format
- Add log_name[16] field to ETCP_CONN structure for connection identification
- Add etcp_update_log_name() function to update identifier when peer_node_id is known
- Update all DEBUG_* calls in etcp.c and etcp_loadbalancer.c to include log_name prefix
- Add DEBUG_CATEGORY_NORMALIZER for packet normalizer debug output
- Change log timestamp format to [hh:mm:ss-mmm.uuu] with microseconds precision
- Reorder debug output: (file:line) function() [log_name] message
- Remove duplicate function names from log messages
- Clean up backup files from pkt_normalizer development
2026-02-04 18:56:43 +03:00
Evgeny 98c43e6fb6 Backup before fixing dgram_pool initialization 2026-02-03 17:56:31 +03:00
Evgeny dd4644776d Refactor: Add dgram fields to ll_queue, remove ref_count, integrate pkt_normalizer
- ll_queue: Add dgram, dgram_free_fn, dgram_pool, len fields to ll_entry
- ll_queue: Remove ref_count, simplify memory management
- etcp: Add normalizer pointer to ETCP_CONN struct
- pkt_normalizer: Major refactoring for queue integration
- tests: Update for new ll_entry structure
- cleanup: Remove backup files
2026-01-31 23:02:35 +03:00
Evgeny 191de191d5 Fix ETCP memory allocation to use queue_data_new_from_pool 2026-01-28 23:28:07 +03:00
Evgeny 41626a02c3 Fix ll_queue callback signature and add debug utilities
Changes:
- ll_queue callback now receives only queue pointer and arg (no data)
- Added log_dump and addr_to_string utility functions
- Removed temporary backup files
- Updated AGENTS.md with additional guidelines
- Fixed compiler warnings in etcp.c and pkt_normalizer.c
2026-01-27 22:43:18 +03:00
Evgeny c1f73584e0 Implement etcp_ack_recv function for ETCP packet acknowledgment
- Add etcp_ack_recv function declaration to etcp.h
- Implement complete ACK processing with RTT calculation and statistics
- Handle packet removal from inflight queues with proper memory management
- Update connection state and trigger new packet transmission
- Integrates with existing etcp_conn_input ACK section processing
2026-01-26 23:24:41 +03:00
Evgeny 1bafe6a681 Backup before fixing etcp_connections list addition 2026-01-26 17:40:51 +03:00
Evgeny d74f76a5a0 Fix: Resolved double free in timeout_heap_pop() and test_etcp_simple_traffic bind conflict
- Fixed incorrect init_connections() call in test_etcp_simple_traffic.c (was calling server_instance instead of client_instance)
- Fixed double free in timeout_heap_pop() when handling deleted elements
- Enhanced NULL pointer safety in uasync_print_resources() by removing complex heap manipulation
- Added debug logging to timeout_heap_pop() for better error tracking

Test results: test_etcp_simple_traffic now passes without double free errors
2026-01-25 10:47:02 +03:00
Evgeny e048b10899 Fix: ETCP module compilation errors and build system issues
- Added missing structure members to ETCP_CONN (ack_packets_count, last_rx_ack_id, rtt_history, rtt_history_idx, total_packets_sent)
- Added missing bandwidth member to ETCP_LINK structure
- Fixed include path for ll_queue.h header
- Added math library linking (-lm) to build system
- Added etcp_loadbalancer.c to build sources
- Fixed forward declarations and function calls in ETCP modules
- Updated test dependencies to include loadbalancer object files

All simple compilation errors resolved, project builds successfully and tests pass (except TUN permission test which is expected in container).
2026-01-23 00:43:48 +03:00
Evgeny 195d0b303c Fix: ETCP connection timing and packet handling improvements
- Made get_current_time_units() function globally accessible in etcp.h
- Improved packet dump formatting for better debugging clarity
- Added link timing tracking with last_recv_local_time and last_recv_timestamp
- Fixed packet parsing to properly skip timestamp bytes
- Enhanced connection state monitoring and error handling
- Removed obsolete etcp_connections.c4 debug file
- Updated test output formatting for better readability
2026-01-21 22:59:32 +03:00
Evgeny 56dfd2f0df Ревизия: добавлены DEBUG сообщения для ошибок и предупреждений
Добавлены комплексные DEBUG сообщения в критические точки проекта:

- **ETCP протокол** (etcp.c): ошибки инициализации криптоконтекста, выделения памяти для очередей, коротких пакетов, сбоев шифрования
- **ETCP соединения** (etcp_connections.c): ошибки установки публичных ключей, расшифровки пакетов, шифрования при отправке
- **TUN интерфейс** (tun_if.c): ошибки создания устройства, настройки IP/MTU, чтения/записи
- **Конфигурация** (config_parser.c): ошибки выделения памяти для структур конфигурации, парсинга IP-адресов
- **Маршрутизация** (routing.c): ошибки выделения памяти для таблиц, отсутствие маршрутов

Все DEBUG сообщения используют существующую систему категорий (CRYPTO, MEMORY, CONFIG, ROUTING, TUN, CONNECTION, ETCP) и предоставляют детальную информацию для диагностики проблем.
2026-01-21 18:18:32 +03:00
Evgeny 4a2044973c Fix includes and complete test_etcp_connection_init build
- Fixed header includes (ll_queue.h, u_async.h, tinycrypt paths)
- Updated Makefile.am with proper CFLAGS and all dependencies
- Test compiles and runs successfully
2026-01-20 18:48:56 +03:00
Evgeny fe9eba14cd Update: Build script, ETCP protocol docs, and TUN interface
- Modified build.sh for better compilation flow
- Updated etcp.h with connection structures
- Refined etcp_protocol.txt documentation
- Enhanced tun_if.c implementation
2026-01-20 18:28:25 +03:00
Evgeny aab0e445f7 Рефакторинг: упрощен etcp_connection_create через вызов etcp_conn_reset
- Удалено ~50 строк дублирующего кода инициализации
- Все поля теперь сбрасываются через etcp_conn_reset
- Сохранена специфичная инициализация: mtu, crypto, очереди, callback
2026-01-20 16:48:55 +03:00
Evgeny 3f7fd9f8ad Сохранить текущее состояние перед исправлением компиляционных ошибок 2026-01-19 23:10:44 +03:00
Evgeny 20e5401ec9 ETCP_CONNECTIONS: add encryption support with secure channel (AES-CCM), nonce, counters. Simplified architecture by removing socket wrappers and integrating uasync_add_socket. pubkey exchange moved to INIT packet only. Added statistics counters. 2026-01-18 20:29:11 +03:00
Evgeny 3f0a23aa93 Fix build: rename u_async to lib, add missing constants, out-of-tree build support 2026-01-18 16:18:28 +03:00
Evgeny 8d9340c949 Refactor: Move mainloop from utun_instance to main
Major architectural changes:
- utun_instance_run() now does single iteration instead of mainloop
- Added tun_read_callback() to handle TUN device packets
- Added utun_instance_register_sockets() for uasync integration
- Mainloop moved to main() with proper signal handling
- Removed parse config file functions from debug_config
- all fprintf replaced with DEBUG_* macros

Files changed:
- src/utun.c: Added mainloop, signal handlers, proper init order
- src/utun_instance.c: Added callback, socket registration, single-run
- src/utun_instance.h: Added declarations, tun_socket_id field
- u_async/debug_config.c: Removed file parsing and auto-reload
- u_async/debug_config.h: Removed file functions, added categories
- changelog.txt: Added all changes

Breaking changes:
- debug_parse_config_file() removed (use debug_parse_config() only)
- etcp crypto integration needs fixing (separate issue)

AGENTS.md principles followed:
- No backward compatibility preserved
- Removed 103+ lines of legacy code
- Added statistics tracking
- Clean architecture: create -> init -> register -> run -> destroy
2026-01-18 14:28:57 +03:00
Evgeny c869ccf174 Major refactoring: Tasks 1-4 complete
Task 1: Migrate to GNU Autotools
- Add configure.ac, Makefile.am files (root, src, u_async, tests)
- Add autogen.sh bootstrap script
- Create INSTALL.autotools guide
- Update .gitignore for autotools
- Old Makefile backed up as Makefile.old

Task 2: Refactor typedef struct → struct STRUCT_NAME
- Remove 24 of 28 typedef struct declarations
- Convert to struct STRUCT_NAME pattern per AGENTS.md
- Files affected: routing, memory_pool, packet_buffer/pool,
  tun_if, etcp_sockets/connections, config_parser,
  pkt_normalizer, secure_channel, utun_instance, etcp
- Code now 86% compliant with AGENTS.md style guide

Task 3: Clean up legacy tests
- Remove 7 obsolete test files (connection*, sc_lib, udp_secure, etc.)
- Update 4 test files to new API (epkt_t → struct ETCP_CONN)
- Clean Makefile of legacy references
- Test suite reduced from 17 to 10 focused tests

Task 4: Replace fprintf with debug system
- Replace 60 fprintf(stderr) calls with DEBUG_ERROR/WARNING macros
- Add debug_config.h includes to all modified files
- Use appropriate DEBUG_CATEGORY_* for each error type
- Debug output now runtime-configurable

Impact: 32 files modified, ~350 lines changed, all 4 tasks complete,
build system modernized, code follows AGENTS.md, debugging improved.
2026-01-18 12:42:42 +03:00