Commit Graph
885 Commits
Author SHA1 Message Date
Evgeny f1f533a552 move CLOSE/RST flags from hdr->seq to hdr->flags
- ROUTER_SEQ_CLOSE_FLAG (0x80000000) → ROUTER_FLAG_CLOSE (0x02 in flags)
- ROUTER_SEQ_RST_FLAG (0x40000000) → ROUTER_FLAG_RST (0x40 in flags, already existed)
- router_send_one_flags: uint32_t seq_flags → uint8_t flag_bits
- router_send_to: uint32_t seq_flags → uint8_t flag_bits, hdr->seq=0, hdr->flags=flag_bits
- etcp_router_recv_cb: check hdr->flags instead of hdr->seq for CLOSE/RST
2026-07-03 20:38:11 +03:00
Evgeny 03490cfc00 refactor: extract etcp_router_recv_cb into 5 functions + fix send_q threshold
- router_verify_signature — Ed25519 signature verification
- router_handle_ack — ACK processing + drain on send_blocked
- router_forward_transit — packet forwarding
- router_check_peer_restart — session restart + RST detection
- router_handle_data_packet — reorder/assembly/dedup
- free_entry helper
- etcp_router_recv_cb: 198 → 42 lines
- ROUTER_MAX_SEND_Q_PACKETS threshold: MAX/2 → MAX-1 (min wait)
2026-07-03 19:27:36 +03:00
Evgeny ba14e31e09 fix: remove retry_timer, use waiter-based round-robin on send_q for fairness
- tcp_proxy_server: drain_cb uses etcp_router_on_send_ready instead of retry_timer
- socks_proxy: on_read_cb + tx_waiter_cb use etcp_router_on_send_ready instead of waiter_register
- Result: FIFO round-robin via ll_queue waiters on send_q, all streams get fair share
- No timers — wakeup is event-driven via queue_data_get → check_waiters
- TCP backpressure: read_queue callback_suspended prevents over-reading
2026-07-03 16:23:56 +03:00
Evgeny 5b850ea5da test: add profiling (MB/s per file per worker) to socks_http_proxy 2026-07-03 15:54:09 +03:00
Evgeny 2fba5c31c4 fix: backpressure data loss in socks/http proxy + comprehensive test
socks_proxy (client side):
- tx_buf buffering on send_data failure in RELAY path, retry in tx_waiter_cb
- process_http_request: version_str null-term fix (memcpy(vlen)+explicit \0)
- process_http_request: assemble hdr+body+extra into heap pkt, atomic send
- socks_proxy_handle_etcp: alloc failure logs write_queue state + byte counters

tcp_proxy_server (exit node):
- read_queue_drain_cb: tx_buf buffering on backpressure, retry_timer (500ms, force=1)
- on_fin_cb: defer FIN when read_queue+tx_buf has pending data (dst_fin_deferred)
- handle_data + drain_cb: per-stream byte counters (sent/recv/relayed/drain_count)
- on_fin_cb/on_error_cb: detailed state logging (counters, queues, buffers)

test_socks_http_proxy:
- 4 workers: socks_ipv4, socks_domain (DNS resolution via SOCKS), http_proxy, https_connect
- 4 file sizes: 1KB, 100KB, 1MB, 10MB — deterministic content, byte-by-byte cmp -s
- HTTPS server with self-signed cert, POST/echo, HEAD, OPTIONS
- 51/51 tests PASS
2026-07-03 14:29:17 +03:00
jeka 4f168c93f6 1 2026-07-03 12:48:25 +03:00
Evgeny 6c938ed2ba test_etcp_router: dummynet congestion test + timer leak fixes
- test_etcp_router: full rewrite with dummynet proxy, congestion cycles
  (fill inflight to backpressure, push 20 packets through, release shaper)
  bitmap tracking (0 loss, 0 dup, 0 corrupt checks), timing diagnostics
- Makefile.am: add utun-dummynet.o to test_etcp_router LDADD
- conn_mgr: fix cm_exch_probe timer leak (NULL callback → retry_cb),
  clean exchange_pending in cm_entry_destroy + conn_mgr_destroy
- utun_instance: add stcp_server_destroy() call in utun_instance_destroy
2026-07-03 12:48:51 +03:00
Evgeny 2cb85cbc3d socks_proxy: поддержка HTTP-прокси (GET/POST/HEAD/OPTIONS/...) — не только CONNECT
process_http_request() теперь обрабатывает любые HTTP-методы:
- CONNECT — туннель как раньше, без изменений
- GET/POST/PUT/HEAD/OPTIONS/... — парсинг абсолютного URL, DNS,
  send_connect + пересборка строки с относительным путём + тело DATA

test_socks_http_proxy: +3-й worker (http_proxy через -x без --proxytunnel),
+проверки POST (echo), HEAD (200 OK), OPTIONS (Allow). Все 78 проверок — PASS.
2026-07-02 22:04:37 +03:00
Evgeny 754c08e9c2 etcpmon: widen sockets list by ~100px (15 chars), shift action section 2026-07-02 21:26:21 +03:00
Evgeny 71ccccc2d5 etcpmon: widen sockets list +15px, shift action section right 2026-07-02 21:20:37 +03:00
Evgeny c6d1ebeeaf debug: log etcpmon socket_list NAT values in send_socket_list 2026-07-02 20:40:08 +03:00
Evgeny eea0ed0a48 debug: add NAT category logging to self-detect, init_resp nat update, and NAT_INFO receive paths 2026-07-02 20:31:32 +03:00
Evgeny 0738dcfd5a fix: self-detection uses interface_addr instead of local_addr (works with 0.0.0.0 bind); don't overwrite nat_addr in handle_init_response_client if NAT already verified 2026-07-02 20:24:32 +03:00
Evgeny 4862c30261 add CFG_SERVER_TYPE_LOCAL (type=local) and UNKNOWN semantics: PRIVATE/LOCAL hidden from nodeinfo, PRIVATE blocks incoming INIT, LOCAL accepts; UNKNOWN treated as PUBLIC; self-detection of PUBLIC IP on incoming INIT; filter LOCAL from NAT checks and connectivity 2026-07-02 19:30:08 +03:00
Evgeny 3c5d82a6ee add cross-build-win.sh for Windows cross-compilation; gitignore build-win/ build artifacts only 2026-07-02 18:59:20 +03:00
Evgeny 389ef00da6 refactor: split socket meta 'type' into config_type and nat_type — separate config (PUBLIC/NAT/PRIVATE) from detected NAT (EIM/STRICT/DIRECT) across NODEINFO, conn_mgr, route_bgp, route_node, etcpmon; win32 compat fixes (memmem, SHUT_WR, tun test_mode, tcp_proxy guards) 2026-07-02 18:58:34 +03:00
Evgeny 487cb8718e fix: preserve newlines in config_updater insert/update — no extra newlines on key replacement, add leading nl when inserting at end without trailing nl v0.1.0-rc1 2026-07-02 17:37:17 +03:00
Evgeny 42d96f118d fix: swap queue_entry_free/queue_dgram_free order in 27 places — prevents UAF when dgram_free accesses freed entry
uasync: replace raw socket_node* handle with packed index — fixes UAF after socket_array realloc
tcp_io: defer u_free in tcp_conn_destroy via uasync_call_soon — prevents callback-chain UAF
tcp_io: guard read_cb/write_cb with NULL queue checks after deferred destroy
tcp_io: save read_queue to local before queue_data_put + NULL guard after
route_connectivity: linked-list probe_ctx — cancel all parallel probes before nq free
2026-07-02 17:14:38 +03:00
Evgeny 8962f58ea4 uasync: replace raw socket_node pointer with index-based handle — fix UAF after realloc 2026-07-02 17:08:24 +03:00
Evgeny 1f541d6432 tcp_io: save read_queue to local var before queue_data_put, add NULL guard after 2026-07-02 16:38:31 +03:00
Evgeny e66156eb49 tcp_io: deferred free in tcp_conn_destroy to prevent UAF in callback chain 2026-07-02 16:26:43 +03:00
Evgeny 2cd38988e6 AGENTS: add ASAN build instructions 2026-07-02 15:49:10 +03:00
Evgeny d58b532741 gitignore: add utun.pid 2026-07-02 15:48:05 +03:00
Evgeny 4716e54069 build: add --asan flag to build.sh, tcp_io: null sock/queues in destroy + guard read_cb/write_cb 2026-07-02 15:47:54 +03:00
Evgeny aa73e9d8cb route_connectivity: fix UAF in conn_probe_finish — break ctx->nq on cancel_node, always free ctx in finish 2026-07-02 15:02:11 +03:00
Evgeny 993c265125 control_server: add idle timeout (30s) on client socket + large output queue warning 2026-07-02 14:17:42 +03:00
Evgeny 5ca0bbf9e7 tcp_io: place write_monitor=0 before queue_resume_callback to prevent busy-loop when waiter_defer=1 2026-07-02 13:50:43 +03:00
Evgeny 0ef7ee597c tcp_io: fix write_cb busy-loop with deferred callback — turn off write_monitor after flush when waiter_defer=1 2026-07-02 13:43:19 +03:00
Evgeny 7d460ca156 fix: ASAN-detected UAFs and buffer overflows across 6 modules
- etcp_connections: fix link leak & UAF in etcp_socket_remove — remove_link inside etcp_link_close shifts array, skip NULL set and i++
- stcp_server: fix UAF in stcp_conn_process_recv — defer free via uasync_call_soon after stcp_conn_do_close
- etcp: save pkt_len before queue_data_put to output_queue (callback may free entry synchronously)
- socks_proxy: add pool bounds check before memcpy, UINT16_MAX truncation guard, freed flag
- tcp_proxy_server: reorder cleanup (cancel waiters before tcp_conn_destroy), UINT16_MAX guard
- test_route6_lib: increase nodes[] array to STRESS_NODES + STRESS_OPS
2026-07-02 13:35:22 +03:00
Evgeny b738b2ff1b etcp_router: add u_check guards at send_q/recv_q entry points to detect memory corruption 2026-07-02 12:57:21 +03:00
Evgeny cc5289e37c etcp_router: don't reset start_sent in reactive restart — prevents START-flag cascade on multi-hop restart detection 2026-07-02 12:28:31 +03:00
Evgeny 0c5f25c96d etcp_router: fix restart cascade — sync peer_sess_id on auto-create, remove sess_id increment on reactive restart 2026-07-02 12:23:12 +03:00
Evgeny b53758bdbe etcp_router: cancel timers in conn_restart, reset last_ack_sent_tb — fix use-after-free SIGSEGV 2026-07-02 11:34:57 +03:00
Evgeny f5b1c3e789 etcp_router: fix OOB drops after restart — add peer_sync_done to sync rx_seq with first incoming seq 2026-07-02 11:12:14 +03:00
Evgeny 0edd21e335 etcpmon: lift Router to y=1181 (tight to Queues), shrink window to 1400 2026-07-02 10:33:41 +03:00
Evgeny e0c38676e7 etcpmon: compress Queues h 300->280, lift Router y 1260->1240 2026-07-02 10:31:44 +03:00
Evgeny fefd2bcc52 etcpmon: fix layout — restore Debug Levels y=485, lift Links to y=710, compress Queues h=300 y=900 2026-07-02 10:29:58 +03:00
Evgeny 8427e18c98 control_server: fix infinite loop in router_conns aggregation — use read-only head->next traversal instead of get/put 2026-07-02 10:23:06 +03:00
Evgeny 7329fa65f1 etcp_router: add congestion counters, fix tx_seq rollback on etcp_send failure, add router metrics to etcpmon GUI
- etcp_router.h: add 9 per-conn counters (pkts_sent/err/rcvd, ack_sent/recv/stale, dup/oob/sign_fail)
- etcp_router.c: increment counters at 13 event points; fix tx_seq rollback on etcp_send failure (was causing phantom inflight=256 deadlock); add DEBUG_ERROR on all 5 ignored etcp_send returns; fix router_ack_do_send to update timestamps only on success
- etcpmon_protocol.h: add etcpmon_router_metrics (14 aggregated fields)
- control_server.c: iterate router_conns to fill aggregated router metrics
- etcpmon_gui: new 'Router Congestion' block with queue depths and all counters, Debug Levels shifted down, window 1300->1440
- test_etcp_router_unit: fix test_ack_timer for correct no-BGP-route behavior
2026-07-02 09:49:10 +03:00
Evgeny de8cce521a all 51 tests pass: fd=0 protection + clean socks_http_proxy test
- socket_compat: never close fd=0
- socks_http_proxy: rewritten cleanly, 2 workers, 25 reqs each, up to 100KB
- uasync_socket_race: dup2-based fd=0 reservation
- u_async: removed DIAG spam
- tcp_io: removed debug fprintf

Result: 51/51 tests pass.
2026-07-02 00:58:47 +03:00
Evgeny f06ebd2ab4 fix: protect fd 0 from close in socket_close_wrapper + dup2 reserve in tests
- socket_close_wrapper: never close sock==0 (prevents fd 0 reuse cycle)
- test_uasync_socket_race: dup2-based fd 0 reservation, pass 800/800
- tcp_io: SOCKET_INVALID before on_error (previous commit)
- Plus earlier fixes: uasync gen counter, ll_queue call_soon_id, pkt_normalizer

Result: test_uasync_socket_race PASSES, 50/51 tests pass
2026-07-02 00:50:36 +03:00
Evgeny a97a38d867 fix: set tc->sock=SOCKET_INVALID before on_error in handle_error
В одном epoll_wait batch три события для fd: EPOLLERR (освобождает tc),
EPOLLIN (read_cb), EPOLLOUT (write_cb). read_cb/write_cb guard проверяет
tc->sock==SOCKET_INVALID, но sock обнулялся ПОСЛЕ on_error.
Перенос sock=SOCKET_INVALID до on_error защищает от use-after-free.

Доказано: без фикса segfault на tcp_io.c:374 (write_cb → tc->connected).
С фиксом тест работает без крашей.
2026-07-02 00:43:37 +03:00
Evgeny aff3b2d00f fix: always remove socket from epoll in tcp_conn_handle_error
tcp_conn_handle_error гвардил uasync_remove_socket_t по tc->socket_id,
пропуская повторный вызов. В одном epoll_wait batch два события
(EPOLLERR + EPOLLOUT) на один fd: первое делает remove (socket_id=NULL),
второе проходит guard и dispatch'ит write_cb на освобождённом tc.

Фикс: всегда вызывать uasync_remove_socket_t + epoll_ctl(DEL),
независимо от socket_id.
2026-07-02 00:16:05 +03:00
Evgeny ccdbab95a8 fix: use-after-free in pkt_normalizer + ll_queue waiter cancel + uasync gen counter for epoll fd-reuse
- pkt_normalizer: save recvpart->len before queue_data_put (may free synchronously)
- ll_queue: save uasync_call_soon handle in queue_waiter_handle, cancel on free
- uasync: generation counter in epoll data.u64 to skip stale events after fd reuse
- uasync: keep fd_to_index mapping after socket_array_remove for inactive nodes
- test: test_uasync_socket_race — 4 children × 200 iterations, currently flaky
2026-07-01 23:51:31 +03:00
Evgeny a01e2f0899 tun_enabled config + socks/http stress test (50 reqs, 2 workers)
- config_parser: tun_enabled в [global] (по умолчанию yes), не дефолтить
  tun_ifname если TUN не нужен
- utun_instance: уважать tun_enabled, чистые дефолты tcp_proxy TUN
- socks_proxy: фикс дэдлока — reply сразу после CONNECT, без ожидания DATA
- utun.conf.sample: документирован tun_enabled, tun_ifname
- test_socks_http_proxy: 50 запросов (SOCKS+HTTP), 2 воркера параллельно,
  файлы 1k..100k, сверка через cmp, python http.server + curl
2026-07-01 22:14:37 +03:00
Evgeny dfdec06a17 build.sh: add missing ./configure step after autoreconf 2026-07-01 21:19:21 +03:00
Evgeny 393a641e18 socks/http proxy client: SOCKS5 + HTTP CONNECT через ETCP
Добавлен модуль socks_proxy.c/h — SOCKS5 и HTTP CONNECT proxy на клиенте.
Использует tcp_io для локальных TCP соединений, туннелит трафик через
существующий ETCP-протокол (ETCP_ID_TCP_PROXY/ETCP_ID_TCP_PROXY_CLIENT).

Конфиг [tcp_proxy_client]:
- socks_enabled/socks_addr — включить SOCKS5 сервер на указанном IP:PORT
- http_proxy_enabled/http_proxy_addr — включить HTTP CONNECT сервер
- Можно включать TUN, SOCKS и HTTP прокси одновременно или раздельно

Весь трефик идёт через exit node (tcp_proxy_server), менять exit не пришлось.
2026-07-01 20:33:11 +03:00
Evgeny 53d41d5c62 fix: use-after-free in route table — add route_delete before u_free in route_bgp_update_my_nodeinfo and route_bgp_process_nodeinfo, relax routes_overlap to allow hierarchical routes
Root cause: when bgp->local_node was reallocated (changed=1), old route
entries remained with stale v_node_info pointing to freed memory. The freed
memory got reused by a BGP peer's NODEINFO_Q, causing route_lookup to return
wrong node_id (b3b2b1b0afaeadac instead of local), which then failed at
etcp_route_send with 'no BGP route' and dropped packets to 10.23.2.1.

Changes:
- route_node.c: route_delete(old) before u_free + route_insert(new) after alloc
- utun_instance.c: remove duplicate route_insert (now atomic inside function)
- route_bgp.c: route_delete before freeing old peer NODEINFO_Q
- route_lib.c: routes_overlap now rejects only exact prefix+network duplicates
- tests/Makefile.am: add route_lib.o to test_route6_lib
2026-07-01 18:53:23 +03:00
Evgeny c60ba6eaec tun: tun_init_nat always uses TUN_MTU_DEFAULT (1500), ignore ETCP mtu from config 2026-07-01 17:57:36 +03:00
Evgeny c5123e4baf bgp: prevent sending NODEINFO to self + own NODEINFO early return
- route_bgp_process_nodeinfo: skip own node_id early, don't add to bgp->nodes
- broadcast loop: skip sending NODEINFO to connection where peer == node_id
- route_bgp_should_send_to: don't send node's NODEINFO to itself
- tests: lower debug level to ERROR, fix keepalive adaptive config
2026-07-01 17:49:27 +03:00