Commit Graph
789 Commits
Author SHA1 Message Date
Evgeny 974c6770e0 fix: prevent ack_q unbounded growth on duplicate packets
Check queue_find_data_by_index(ack_q) before creating a new ACK_PACKET
in ETCP_SECTION_PAYLOAD handler. Previously every duplicate packet
created a new entry in ack_q, and with links blocked (inf_block) the
queue grew without bounds.
2026-06-09 22:49:27 +03:00
Evgeny 075c4f4583 memory_pool: name field — идентификация пула в диагностике коррапшна 2026-06-09 22:20:25 +03:00
Evgeny 9e133699bf log_dump: level+category, memory_pool: дамп user_data через log_dump при коррапшне 2026-06-09 22:20:06 +03:00
Evgeny 81cad40e3b memory_pool: усиленная канарейка 4B + хранение alloc_loc для диагностики 2026-06-09 22:19:47 +03:00
Evgeny baca018387 proxy/udp: buf 65536→1600 на стеке, UDP не нужен гигантский буфер 2026-06-09 22:19:30 +03:00
Evgeny 48a4f182aa ll_queue: inline→static inline queue_waiter_call — fix link error with -Og 2026-06-09 22:18:29 +03:00
Evgeny 7c456a1652 proxy: bounds check data_len перед memcpy в handle_data — fix buffer overflow 2026-06-09 22:18:12 +03:00
Evgeny a0ea19acb8 fix: diag_timer_cb UAF — обнуляем rc->diag_timer до раннего возврата 2026-06-09 21:50:04 +03:00
Evgeny 1f34629753 Merge commit 'HEAD@{1}' into bbr
# Conflicts:
#	src/etcp.c
#	src/etcp_connections.c
2026-06-09 19:48:52 +03:00
Evgeny 9a3eb1ce80 fix: reconnect test — clear_queue callback deadlock + conn_ok timing
- etcp_conn_reset: queue_resume_callback after clear_queue (input_queue,
  input_send_q, input_wait_ack) to prevent suspended callback deadlock
- is_connection_established: check conn->initialized (reliable across
  reinit) instead of link->initialized (never cleared on reinit)
- test: force etcp_conn_reinit after server recreation so conn_ok
  waits for fresh INIT handshake
- test: guard send_packets() with is_connection_established in reconnect
  phases to avoid sending data while conn is down
2026-06-09 19:35:06 +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 e55c4ec7ce bugfixes 2026-06-09 13:18:42 +03:00
Evgeny dd1b9f2680 etcp: dedup ack_q — не добавлять дубликаты ACK для одного seq 2026-06-07 21:01:44 +03:00
Evgeny 52f32da3f1 etcp: BBR callback для обновления inflight_lim_bytes + пересчёт optimal_inflight
- BBR: добавлен callback on_cwnd_update(ctx, new_cwnd) в struct bbr, вызывается при изменении cwnd
- etcp_link_update_inflight_lim() — атомарно обновляет inflight_lim_bytes линка и пересчитывает optimal_inflight (сумма по всем линкам)
- BBR теперь сам обновляет лимиты через callback, ручное присваивание в etcp_ack_recv() удалено
- is_server в config_parser.c: печать адресов через sockaddr_storage_to_str (поддержка IPv4/IPv6)
- utun_instance.c: local_sockaddr_equal() — добавлено сравнение AF_INET6
- Убраны отладочные memory_pool_is_freed
2026-06-07 12:17:18 +03:00
Evgeny defb70f63a 1 2026-06-06 00:22:21 +03:00
Evgeny 40c7a5b487 1 2026-06-05 22:34:49 +03:00
Evgeny e81299a727 1 2026-06-05 21:43:26 +03:00
Evgeny 3217f744f9 memory_pool_is_freed + стратегические проверки на висячие указатели
memory_pool: memory_pool_is_freed(pool,obj) — поиск obj в free-списке

tw_pcbs (3 места): !ctx→halt и is_freed→halt в начале итерации
  — ловит висячий PCB до re-alloc и после re-alloc

etcp: is_freed→halt перед etcp_conn_input (caller + callee)
  — ловит pkt освобождённый до входа

tcp_alloc: убран старый скан tw_pcbs (заменён на is_freed)
все dangling проверки — halt (while(1)) вместо break/return
2026-06-05 20:45:42 +03:00
Evgeny 24a5de9398 memory_pool: канарейка (0xAA) + счётчик double-free; lwip_tcp: убраны TCP_TW_MAX/tw_iter, добавлен хук в tcp_alloc
memory_pool: +2 байта за объектом — canary 0xAA для детекции buffer overflow,
counter для детекции double-free. При free проверяется canary и counter==0,
при alloc выставляется новый counter.

lwip_tcp: убраны TCP_TW_MAX и счётчики tw_iter (толку нет, краш на 2й итерации).
Оставлены: !pcb->ctx (dangling pointer), self-loop checks, next_owner диагностика.
Добавлена проверка в tcp_alloc: если новый PCB найден в tw_pcbs → halt.
2026-06-05 20:01:28 +03:00
Evgeny a09c647dfd lwip_tcp: детект и защита от self-loop (pcb->next==pcb) в tw_pcbs
tcp_slowtmr: после tcp_free проверка pcb==pcb2 → ctx->tw_pcbs=NULL, break
tcp_kill_timewait: проверка inactive->next==inactive → ctx->tw_pcbs=NULL, tcp_free
lwip_tcp_input: проверка pcb->next==pcb перед tcp_timewait_input → tcp_abort
все 3 лога выводят next_owner для диагностики источника self-ссылки
2026-06-05 18:15:43 +03:00
Evgeny 11002bcb57 lwip_tcp: защита от зацикливания tw_pcbs + next_owner диагностика + таймауты + фикс RTO
- TCP_TW_MAX=256: циклозащита в for/while циклах tw_pcbs (input, slowtmr, kill_timewait)
  + TCP_RMV макрос тоже защищён от бесконечного поиска
- next_owner в struct tcp_pcb/tcp_pcb_listen: отслеживает кто правил pcb->next
  (REG=1, RMV=2, SLOWTMR=3, INPUT=4). memset при alloc обнуляет
- таймауты: FIN_WAIT 20s→6s, SYN_RCVD 20s→6s, MSL 60s→25s (TIME_WAIT=50s)
- tcp_alloc: RTO из ctx->rto_min_ms вместо хардкода 3000
- handle_fin: pcb_state в лог
2026-06-05 17:19:50 +03:00
Evgeny 7a35f4c386 proxy client: привести lwIP TCP close к лучшим практикам
handle_close: tcp_abort→tcp_close + полное обнуление коллбэков (graceful FIN вместо RST)
handle_error: отделён от handle_close, свой cleanup с tcp_abort (RST — нештатная ситуация)
poll_cb/destroy: полное обнуление коллбэков перед tcp_abort (tcp_arg/recv/sent/err/poll)
handle_fin: исправлен лог (shutdown write, не read)
tx_waiter_cb: проверка pc->pcb перед tcp_recved
2026-06-05 15:33:17 +03:00
Evgeny 483bf440fb tcp_proxy_client: skip tcp_shutdown on TIME_WAIT/CLOSED pcb
handle_fin вызывает tcp_shutdown(pcb,0,1) на любом PCB, включая TIME_WAIT.
При active close (FIN_WAIT_1→FIN_WAIT_2→TIME_WAIT) PCB уже в tw_pcbs,
tcp_shutdown на нём портит состояние → tw_pcbs зацикливается → lwip_tcp_input зависает.

Проверка state != TIME_WAIT && != CLOSED перед вызовом.
2026-06-05 12:45:51 +03:00
Evgeny 6f1916b6b2 tcp_proxy_client: tcp_close→tcp_abort, fix tw_pcbs loop
При CLOSE и FIN от сервера в обратном порядке (FIN relay + CLOSE от двух FIN),
клиент сначала обрабатывает CLOSE (tcp_close → TIME_WAIT), потом FIN
(tcp_shutdown на TIME_WAIT pcb), что портит tw_pcbs список — pcb->next
замыкается на себя, lwip_tcp_input зависает в бесконечном цикле.

tcp_abort шлёт RST и удаляет pcb сразу, без TIME_WAIT.
2026-06-05 12:25:46 +03:00
Evgeny 01dbd76834 1 2026-06-05 00:17:17 +03:00
Evgeny 6ee030ca7c 1 2026-06-04 23:07:34 +03:00
Evgeny 3ae4988353 1 2026-06-04 22:39:02 +03:00
Evgeny 57281a975e 1 2026-06-04 21:59:40 +03:00
Evgeny b953a6daf0 tcp_io: FIN/close через write_queue, отладка всех этапов закрытия
- tcp_io.h/c: push_fin/push_close через очередь отправки
  Кодирование: dgram=NULL→close, len=0+dgram!=NULL→FIN (sentinel)
  FIN: shutdown(SHUT_WR), стоп чтения, on_fin_sent
  CLOSE: close сокета, on_closed
  read_cb: отбрасывание входящих после fin_sent
  guard wq_fetch: error||closed (не fin)
- tcp_proxy_server: адаптация handle_fin→push_fin, handle_close→push_close
  read_queue_drain_cb: discard при fin_sent
  DEBUG_INFO на всех точках закрытия
- tcp_proxy_client: send_fin, handle_fin — DEBUG_INFO
- test_tcp_io: +6 тестов (push_fin, push_close, ordering, double-push, fin+close)
2026-06-04 19:20:20 +03:00
Evgeny 612b6bf1bf tcp_io: add DEBUG_TRACE for POLLOUT/busy-loop diagnostics 2026-06-04 16:37:07 +03:00
Evgeny 58e45e9232 proxy: implement CLOSE and FIN relay protocol
- CLOSE: admin connection teardown (drain queues, shutdown, free)
  Server: handle_close — pause read, drain rq (discard), drain wq to socket, shutdown, free
  Client: handle_close — drain to_lwip/tx_buf (discard), tcp_close pcb, free
  ERROR calls handle_close on both sides
- FIN: transparent relay event through ETCP (TCP_PROXY_SUBCMD_FIN=0x06)
  Server: on_fin_cb relays FIN_MSG to client, on_flushed_cb relays FIN_MSG
  Server: handle_fin relays FIN to remote socket via shutdown(SHUT_WR)
  Client: recv_cb relays FIN_MSG to exit, tx_waiter_cb relays FIN_MSG
  Client: handle_fin relays FIN to local TCP via tcp_shutdown(pcb,0,1)
- new tcp_conn_pause_read() in tcp_io (EPOLLIN off + cancel waiter)
- poll_cb simplified: remove tun_closed&&rem_closed wait block
- conn_free drains close_pending before free on both sides
- handle_data WARN→INFO for drops after close
- tcp_shutdown declared in lwip_tcp.h
2026-06-04 16:02:32 +03:00
Evgeny f8111f7f03 tcp_proxy_client: move PROXY FEED per-packet log from DEBUG to TRACE 2026-06-04 12:26:27 +03:00
Evgeny 859290c202 etcp_router: move per-packet ETCP_SEND/ETCP_RECV/ACK_SEND/queued logs from DEBUG to TRACE 2026-06-04 12:24:15 +03:00
Evgeny cfd885de7c tcp_proxy_server: move per-packet SOCK:RECV log from INFO to TRACE 2026-06-04 12:20:10 +03:00
Evgeny 8d0c40195b tcp proxy/lwip: move per-packet traffic logs from INFO/ERROR to TRACE 2026-06-04 12:13:50 +03:00
Evgeny e765d62e43 etcp_route_send: add force parameter to bypass send_q limit for control messages
CLOSE/ERROR/CONNECT and routing messages use force=1 to never be
dropped by backpressure. Regular DATA uses force=0 (default).
2026-06-04 12:01:55 +03:00
Evgeny c56ec0b0ed uasync: добавить отладку poll→fd/rev, timer→имя при разрешении событий 2026-06-04 01:57:10 +03:00
Evgeny 4dfc0ce947 fix: correct INIT padding — include SC_NONCE_SIZE + SC_CRC32_SIZE in formula
REQUEST: s_max = mtu - SC_NONCE_SIZE - 3 - SC_CRC32_SIZE - SC_TAG_SIZE
                 - SC_PUBKEY_ENC_SIZE + UDP_SC_HDR_SIZE (= mtu-78, was mtu-61)
RESPONSE: s_max = mtu (noencrypt=0, simple cap)

Removed debug logs.
2026-06-04 01:31:39 +03:00
Evgeny b8da0db1ab debug: add final offset/to_add/data_len log before encrypt_send
INIT_REQ/INIT_RESP now log offset, s, to_add, data_len, noencrypt_len
right before etcp_encrypt_send to trace why enc_buf exceeds mtu.
2026-06-04 01:17:32 +03:00
Evgeny 30acde7b18 debug: add ERROR-level logs for INIT padding calc (req+resp)
Shows mtu, s_rand, s_max, offset/xoffset, and whether capped.
RESP: removed old hardcoded 1472+26 cap, replaced by formula.
Both paths use consistent formula based on #defines.
2026-06-04 01:13:15 +03:00
Evgeny c0b6e5769e fix: correct INIT padding cap using defines instead of hardcoded 19
Formula: s_max = mtu - 3 - SC_TAG_SIZE + UDP_SC_HDR_SIZE - SC_PUBKEY_ENC_SIZE
For mtu=1460: 1460 - 3 - 16 + 30 - 72 = 1399 (was 1390, off by 9)
2026-06-04 00:57:19 +03:00
Evgeny 3c036ecc4c fix: restore conn_free cleanup — tcp_conn_destroy, timers, waiters were lost
Previous edit accidentally removed tcp_conn_destroy, timer cancellations,
and etcp_router_cancel_send_ready from conn_free. Without tcp_conn_destroy
the socket was never removed from uasync, causing repeated EPOLLERR →
repeated conn_free on freed memory → double-free crash.

Added debug logs for freed guard entry and u_free.
2026-06-04 00:44:51 +03:00
Evgeny cb764a1143 fix: INIT padding cap computed from actual link MTU, not hardcoded 1472
Hardcoded 1472-46 cap exceeded link MTU=1460, causing 'packet too long'
error on INIT handshake. Use link->mtu - UDP_HDR_SIZE - offset - 19
instead of fixed 1472.
2026-06-04 00:33:29 +03:00
Evgeny 0c8de3db84 fix: double-free in tcp_proxy_server_conn_free via freed flag
error_cb can fire twice for the same fd in one epoll batch,
or conn_free called from multiple callbacks during restart/shutdown.
freed flag makes conn_free idempotent.
2026-06-04 00:13:28 +03:00
Evgeny 4ba790b921 fix: SIGSEGV in tcp_proxy_client_destroy — abort pcbs before lwip destroy
Move lwip_tcp_destroy after pcb cleanup to avoid aborting pcbs
with already-freed context. Add state != CLOSED guard to tcp_abort.
2026-06-04 00:02:47 +03:00
Evgeny e0378ebf1d refactor: remove consumer_ack, isolate proxy from router internals
etcp_router:
  - removed consumer_ack field, consumer_ack function, consumer_ack logic
  - ACK always auto-sent via router_schedule_ack (10ms throttle)
  - conn_restart: local-only reset, no remote CLOSE, unified close notification (len=9)
  - START detection: only when rx_seq>0 (first conn doesn't trigger)
  - new API: etcp_router_on_send_ready / cancel_send_ready for send_q backpressure

tcp_proxy_server:
  - removed write_on_get_cb, queue_set_on_get, rconn->consumer_ack
  - removed etcp_router_conn_get, direct send_q access
  - uses etcp_router_on_send_ready for backpressure

tcp_proxy_client:
  - removed consumer_ack call
  - unified conn=NULL handler (len=9 = close/restart with node_id)

protocol: close/restart notification now len=9 (svc_id + node_id), no RESTART subcmd
2026-06-03 23:46:11 +03:00
Evgeny d784b2bfbe fix: use-after-free in tcp_conn_destroy + throttle consumer_ack
tcp_conn_destroy: set read/write queue callbacks to NULL before
queue_free to stop deferred autofetch (drain_cb on freed rc).

write_on_get_cb: throttle consumer_ack to every 8th write_queue
dequeue instead of every single one (was 30+ ACK/sec).

ack_batch field in tcp_proxy_server_conn.
2026-06-03 22:47:23 +03:00
Evgeny 0449a5fd9d test: 5 new router unit tests — RST, restart, sess_id
test_rst_flag: inject ROUTER_FLAG_RST → rconn destroyed, service notified
test_client_restart: pump random data → inject START → restart detected
test_sess_id_change: pump sess_id=0 → inject sess_id=1+START → detected
test_sess_id_wrap: pump sess_id=3, peer_sess_id=3 → inject sess_id=0+START → wrap detected
test_server_reinit: reinit router → new rconn start_sent=0, sess_id=0

inject() extended with uint8_t flags parameter.
pump_data helper for random data injection.
test_handler tracks g_notify_count for close/restart notifications.

fix: etcp_router_recv_cb — return after RST flag to avoid NULL rconn deref
2026-06-03 21:56:11 +03:00
Evgeny d0029178e7 feat: 1-byte flags in SVC_ROUTE_HDR — START, RST, 2-bit sess_id
SVC_ROUTE_HDR: +uint8_t flags (23 bytes total).
  bit7=START (0x80) — first data packet of new session
  bit6=RST (0x40) — sequence violation detected
  bit5-4=sess_id (0-3) — cyclically incremented on restart

router_send_one_flags: sets START+sess_id on first data packet.
router_send_ack: sets sess_id only (no START for ACK).
etcp_router_recv_cb: detects restart via sess_id change or START flag.
  Old seq=0 heuristic replaced with explicit flags.
etcp_router_conn_get: init sess_id=0, peer_sess_id=0, start_sent=0.
etcp_router_conn_restart: increment sess_id before closing rconn.
2026-06-03 21:20:05 +03:00
Evgeny ca7f6c0d01 feat: peer restart detection + etcp_router_conn_restart with service notification
etcp_router: new etcp_router_conn_restart(inst, node_id, svc_id) — closes
all rconns for the peer, notifies service via cb(NULL, entry) with
node_id, resets seq state.

seq=0 detection in etcp_router_recv_cb: when rx_seq >= 256 (MAX_INFLIGHT)
and a data packet arrives with seq=0, detect peer restart and reset rconn.

tcp_proxy_client: handle TCP_PROXY_SUBCMD_RESTART — clear all client conns
and server conns for the restarted peer.

Threshold prevents false positives on in-window seq=0 duplicates.
2026-06-03 20:45:42 +03:00