Commit Graph
72 Commits
Author SHA1 Message Date
Evgeny c05e1c9991 replace uIP with adapted lwIP TCP stack (lwip_tcp)
- Replace uIP (src/uip/) with adapted lwIP 2.1.x TCP module
- Remove original src/lwip/ (replaced by src/lwip_tcp/)
- New src/lwip_tcp/ module: lwip_pbuf, lwip_tcp core/in/out
- Full TCP state machine, sliding window, congestion control
- Fast retransmit/recovery, Van Jacobson RTT estimation
- Nagle algorithm (TF_NODELAY), delayed ACK
- OOSEQ reassembly, TIME-WAIT handling
- Memory: memory_pool for PCB, listen PCB, tcp_seg
- Timers: uasync periodic timer drives fast/slow timers
- Output: callback-based IP packet output (TUN/raw-fd)
- Error codes: LERR_ prefix to avoid conflicts
- pbuf: simplified PBUF_RAM with proper header space reservation
- Integrate into tcp_proxy.c/h with per-pcb callbacks
- Active connection API: struct proxy_conn* instead of int conn_idx
- Makefile: remove uip, add lwip_tcp files
- test_tcp_proxy updated for new API; test_tcp_proxy_remote disabled
- Known: test_tcp_proxy data transfer needs flow tuning (WIP)
2026-05-11 22:51:48 +03:00
Evgeny a6311a17d0 add UDP/ICMP proxy, refactor tcp_proxy via_node to instance-level
- UDP proxy: datagram relay client↔exit over ETCP
- ICMP proxy: echo ping relay client↔exit over ETCP
- Move via_node_id from per-forward-mapping to global tcp_proxy setting
- Support multiple concurrent tcp_proxy instances (no singleton g_tcp_proxy)
- Cap handshake padding to stay within 1472+overhead
- Handle non-TCP packets (UDP/ICMP) in tcp_proxy raw/tun input paths
- Add utun_instance_create_from_str() for test config creation
2026-05-11 18:37:36 +03:00
Evgeny a0e5446790 migrate NAT and DATA to etcp_router, fix warnings and destroy order 2026-05-10 14:00:49 +03:00
Evgeny c24a6367cc add IPv6 default route interface auto-detection for permanent/temporary IPv6 without netif
- get_default_route_netif_index(): UDP connect trick + getifaddrs to find default route iface
- etcp_socket_add(): auto-detect netif_index when not specified in config
- queue_new() API: explicit index_offset/index_size params instead of implicit from hash_size
- radix: cleanup types (uint8_t*), replace bzero/bcmp with memset/memcmp, remove kernel ifdefs
- route6_lib: new IPv6 routing library + get_node_v6_routes()
2026-05-10 00:05:23 +03:00
Evgeny 9869cf66f1 add etcp_router service routing layer + remote TCP proxy (uip+socket via router)
etcp_router: routable service packets with dst/src node_id
- etcp_router_bind/unbind: per-instance service handler registry
- etcp_route_send: send to node by id via BGP routing
- multi-hop forwarding through intermediate nodes
- loopback optimization (dst==self dispatches directly)

remote_proxy: exit node creating OS sockets on demand
- handles CONNECT/DATA/CLOSE via etcp_router
- non-blocking socket connect with uasync callbacks
- echo back response data to requesting node

tcp_proxy: etcp_transport for remote proxy
- via_node_id in mapping selects between sock/etcp transport
- unified handler for both tcp_proxy and remote_proxy roles
- config: forward = port -> ip:port via NODE_HEX [remote_proxy] section

tests: test_etcp_router (20 pkts bidirectional), test_remote_proxy (echo)
2026-04-28 20:01:12 +03:00
Evgeny 171e70a810 add inflight data return to normalizer on reinit + configurable inflight min/max limits + test 2026-04-27 23:50:52 +03:00
Evgeny dea3a39598 fix: reconnect test — cancel timers in conn_reset, add init_timer cancel on link_state=3, add reinit resilience to test
- etcp_conn_reset: cancel retrans_timer/ack_resp_timer via uasync_cancel_timeout
  before nulling (was leaking timer handles, confirmed by 'Timer leak: diff')
- etcp_connections: cancel link->init_timer explicitly when link_state becomes 3
  on both client and server INIT_RESPONSE paths (prevents spurious INIT after
  connection is established that could trigger cascading reinits)
- etcp_connections: remove duplicate conn->session_id assignment in new conn path
  (session_id is set later via conn_reinit flow)
- pkt_normalizer: resume output queue callback after pn_reset
- Add test_etcp_reconnect with reinit detection — monitors conn->reinit_count
  and restarts data transfer if reinit occurs during active phase
- Add etcp_dump.c/h — ETCP connection state dump utility for debugging
2026-04-27 19:46:45 +03:00
Evgeny 0f8df44b2b build: out-of-tree VPATH build, tests run once with colored timing
- Root Makefile: hand-written bootstrap delegating to build/
- Makefile.am: simplified to SUBDIRS + clean-local
- build.sh: delegates to make, autoreconf only
- tests: removed duplicate TESTS run, added colored [PASS]/[FAIL]/[SKIP] with timing
- .gitignore: added /build/ for out-of-tree artifacts

Result: 0 .o files in source dirs, 29/29 tests pass
2026-04-27 13:48:22 +03:00
Evgeny d0d4199273 etcp: unified send hook via etcp_udp_send, remove loss_rate, add dummynet_filter inline mode, rewrite BGP test
- Add etcp_udp_send_fn_t hook typedef, send_hook/send_hook_ctx fields to ETCP_LINK
- Implement etcp_udp_send() wrapper — all UDP sends go through one point
- Remove loss_rate from ETCP_SOCKET, CFG_SERVER, config parser, send path
- Add dummynet_filter: inline send-hook with loss/delay, no proxy socket needed
- Rewrite test_bgp_route_exchange: 3-node chain A(2 links)↔B↔C, 7 phases
  with dummynet_filter-based link failure/recovery simulation
- Clean up tests: remove skeleton test_routing_mesh, 6 debug/stale test files
- Refactor test_etcp_simple_traffic and test_pkt_normalizer_etcp (remove debug spam)
- Fix test_etcp_two_instances: remove private field access, fix false PASS on timeout
2026-04-27 12:43:52 +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 9c509d4c86 add connectivity probing + NAT type rename OPEN->EIM, RESTRICTED->STRICT
- Rename NAT types: OPEN->EIM, RESTRICTED->STRICT across all code
- Add flat addr list {type,ip,port,socket_id} to NODEINFO (NODEINFO_IPV4_ADDR)
- Add NODEINFO_IPV4_SOCKET_META for per-socket metadata
- Add NODE_CONNECTIVITY with per-type probe status and min_rtt
- New module: route_connectivity.c/h (probing engine with socket fallback)
- STRICT verified addresses excluded from NODEINFO broadcast
- Trigger probing on new/updated BGP node, cancel on remove/withdraw
- Update NAT type names in etcpmon GUI
2026-04-25 18:41:45 +03:00
Evgeny 907ef244c6 NAT: Full Cone (EIM) NAT with ETCP_ID_NAT protocol, per-node routing, and comprehensive test suite
- New ETCP protocol ETCP_ID_NAT (0x02) for NAT traffic between nodes
- eim_nat.c/h: Pure NAT engine (table, port allocation, checksum updates, egress/ingress)
- nat_transport.c/h: Transport layer (NAT TUN, ETCP binding, client/provider roles)
- route_bgp_find_conn_for_node(): shared utility for optimal connection lookup
- tun_init_nat(): dedicated TUN creation for NAT
- Config: [nat] section with tun_ip, port_start/end, nat_via, forward rules
- Fix: csum_update_ip/transport use htonl() halves (correct on LE systems)
- Fix: IP_FRAG_MF_MASK changed to 0x2000 (after ntohs, MF is bit 13)
- Tests: 26 engine unit + 4 transport integration + 7 stress (29 total)
2026-04-25 00:43:25 +03:00
Evgeny 57dba26e7c GUI: поле действия и кнопка Send для отправки команд в utun
- Добавлен ETCPMON_CMD_ACTION в протокол (32 байта текст)
- В GUI добавлено поле ввода и кнопка Send правее блока Sockets
- Добавлен etcpmon_client_send_action для отправки команд
- Обработка action 'nat' в control_server: запускает NAT check для всех линков
- Сделана route_bgp_start_link_nat_check не-static
- Добавлена route_bgp_request_nat_check_all
- Исправлен баг route_ping.c (request_id -> nonce)
- Исправлена линковка tests/Makefile.am
2026-04-22 20:52:30 +03:00
Evgeny 7cdb84c7a2 Add NAT detection with burst ping, test timing, fix port conflicts
- route_ping.c: burst mode - send next ping immediately on response
- route_ping.h: add target_ipv4/target_port/pubkey to BGP_PING_REQUEST
- test_nat_detection.c: add test for ping without embedded pubkey
- test_etcp_simple_traffic.c: use dynamic ports + fix timebase units
- Makefile.am: show test execution time in ms
2026-04-14 14:25:36 +03:00
Evgeny 31eb4a5d26 Add NAT detection with STUN-like ping and integration test 2026-04-14 12:02:43 +03:00
Evgeny 2903b82941 Add test_serialize to Makefile and include serialize in libuasync.a
- tests/Makefile.am: add test_serialize to check_PROGRAMS
- lib/Makefile.am: add serialize.c/h to libuasync_a_SOURCES
2026-04-13 23:50:32 +03:00
Evgeny ffbc0da86f add ping 2026-04-13 20:12:13 +03:00
Evgeny 05323ded60 WIP: backup before debugging test_bgp_route_exchange 2026-04-13 13:55:21 +03:00
Evgeny 9f13cf5459 route redesign + tests 2026-03-30 18:26:56 +03:00
Evgeny 27618217cc fix: update tests for new NODEINFO routing API
- Added route_node.o to test linking
- Simplified test_route_lib to avoid old API calls
- Minor fixes to build system

Branch: feature/nodeinfo-routing
2026-03-29 20:55:40 +03:00
Evgeny 9517454ee6 firewall + random init pkt size 2026-03-26 22:42:22 +03:00
Evgeny ef75d20d0f 1 2026-03-13 00:19:43 +03:00
jeka aa5171bcd1 route improvements 2026-03-12 02:57:38 +03:00
Evgeny f9bdb2733f 1 2026-03-08 20:43:53 +03:00
Evgeny 83a21fee1b 1 2026-03-08 20:36:27 +03:00
Evgeny e876437c69 1 2026-03-08 20:20:39 +03:00
jeka 066a9aa89e +memory check module
fix double free @routing
2026-03-06 15:55:16 +03:00
jeka b20bff32dd config 2026-03-04 01:53:17 +03:00
jeka 783f229711 obf 2026-03-01 17:19:47 +03:00
jeka c420b8f18e пердайт icmp в tun 2026-03-01 02:48:03 +03:00
Evgeny fc9fac2e3a Fix: Remove reference to missing test_control_server.c 2026-02-21 23:29:31 +03:00
jeka b8ea33160d восстановление морды (частичное) 2026-02-21 21:04:11 +03:00
Evgeny 6ffec2f1e7 Fix: INVALID_SOCKET usage in POSIX code and remove missing test
- control_server.c: Use -1 instead of INVALID_SOCKET on lines 241 and 511
- Makefile.am: Remove test_control_server reference (source file missing)
2026-02-21 18:09:47 +03:00
jeka d10bddd1f7 Build: incremental build support, Windows uasync fixes, TUN cross-platform refactoring
- 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
2026-02-20 21:20:50 +03:00
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 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
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 560e121d4c Fix tests Makefile.am: WIN_LIBS must be defined before COMMON_LIBS 2026-02-15 04:41:25 +03:00
Evgeny ada25ec4cc Add -ladvapi32 for Windows CryptGenRandom support 2026-02-15 04:36:47 +03:00
Evgeny 27f2edca40 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 15b670e563 Add cross-platform TUN support with Wintun for Windows
- Split TUN implementation into platform-specific files:
  - tun_if.c: Common code (queues, callbacks, statistics)
  - tun_linux.c: Linux TUN/TAP implementation (/dev/net/tun + ioctl)
  - tun_windows.c: Windows Wintun implementation (wintun.dll + IP Helper)

- Update tun_if.h with platform abstraction layer:
  - tun_platform_init/cleanup/read/write/get_poll_fd
  - Platform handles: fd (Linux), WINTUN handles (Windows)

- Windows implementation features:
  - Dynamic loading of wintun.dll with graceful error handling
  - IP Helper API for IP address and MTU configuration
  - HANDLE-based uasync integration
  - Clear error message if wintun.dll is not found

- Update build system:
  - configure.ac: Detect Windows (mingw/msys/cygwin)
  - src/Makefile.am: Conditional compilation of tun_linux/tun_windows
  - tests/Makefile.am: Link platform-specific TUN objects

- Add wintun.dll and wintun.h to lib/ directory
- All 22 tests pass on Linux
- Ready for MSYS2 UCRT64 Windows build
2026-02-15 01:40:17 +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 8334b97521 Backup before adding NAT IP:port tracking to ETCP handshake 2026-02-14 11:02:20 +03:00
Evgeny 6e93c087ca Add test_etcp_api.c - test for ETCP API (etcp_send, etcp_bind)
Based on test_pkt_normalizer_etcp.c but uses high-level API:
- etcp_send() for sending packets via ETCP normalizer
- etcp_bind() for registering receive callbacks
- etcp_api_init()/etcp_api_deinit() for API lifecycle

NOTE: Test has current limitation - pkt_normalizer packer aggregates
packets into ~1536 byte chunks, exceeding ETCP max payload of 1480 bytes.
This causes encrypt_send to fail. The test demonstrates correct API usage
pattern but requires packer fix for full functionality.
2026-02-13 23:37:13 +03:00
Evgeny 15001487af Build: Out-of-tree build system with separate build directory
- Build in build/ directory instead of source tree
- Main binary (utun) copied to project root
- Tests run from build/tests/ with config files copied there
- Test output redirected to build/tests/logs/*.log files
- Console shows only [PASS]/[FAIL]/[SKIP] status
- Incremental build works correctly
- make check runs all tests with summary

Changes:
- New root Makefile as wrapper for out-of-tree build
- Updated Makefile.am files for lib, src, tests
- Added tinycrypt-objects target for test dependencies
- Tests no longer clutter project root
2026-02-13 22:58:41 +03:00
Evgeny ffaf7a25b8 Add etcp_api.c/h - ETCP packet send/receive API
Implemented:
- etcp_send(conn, entry) - отправляет пакет в очередь normalizer
- etcp_bind(id, callback) - подписка на пакеты с определенным ID
- etcp_unbind(id) - отписка от пакетов
- etcp_recv(queue, arg) - коллбэк для маршрутизации пакетов по ID
- etcp_api_init/deinit - инициализация API

Integration:
- pn_init() теперь устанавливает etcp_recv как callback для pn->output
- Добавлены etcp_api.c/h в src/Makefile.am
- Добавлен etcp_api.o в тестовые зависимости

API использует первый байт кодограммы (cmd) как ID для маршрутизации.
ID=0 используется как default handler если нет специфичного binding.
2026-02-13 19:15:16 +03:00
Evgeny 5dfb67a4e3 Fix: Update tests/Makefile.am for correct object dependencies
- Changed object file references from 'name.o' to 'utun-name.o' to match automake naming
- Added explicit rules for building TinyCrypt objects
- Added tinycrypt-objects target for building crypto dependencies
- Fixed test_etcp_simple_traffic.c: replaced etcp_send with etcp_int_send
- Fixed test_etcp_100_packets.c: replaced etcp_send with etcp_int_send

Test Results: All 19 tests PASS
2026-02-13 18:30:59 +03:00
Evgeny ce15d6b883 Backup before route_lib.c refactoring 2026-02-13 18:12:26 +03:00
Evgeny 277ab872bf Fix: routing initialization timing and test callbacks
- Fixed race condition: routing_add_conn called before etcp->normalizer was assigned

- Moved routing_add_conn from pn_init to etcp_connection_create after normalizer init

- Added routing.h include to etcp.c

- Fixed tests: disable routing callback on output_queue to keep packets for test verification

All 19 tests now pass.
2026-02-07 23:41:07 +03:00