Commit Graph
2373 Commits
Author SHA1 Message Date
evgeny 9846599086 stcp: fix memory leaks and cleanup architecture
- stcp_conn_do_close: always deferred free for allocated conns (was else-if)
- stcp_link_on_stcp_close: don't null link->conn (close_impl needs it for rx_queue)
- stcp_link_close_impl: free rx_queue/tx_queue before close, null conn after cleanup
- stcp_client_connect: return NULL on derive_session failure (was returning dead cli)
- stcp_frame_decrypt/stcp_recv_try: dedup CRC check into stcp_check_crc helper
- test_stcp: add test8_srv_recv_close (error-recv close chain)
2026-08-08 11:42:16 +03:00
evgeny 5c8355ee63 stcp: unified recv FSM, handshake timeout, RX backpressure, opaque pointer fix
- stcp_recv_try / stcp_recv_set: unified chunk reader with raw+stream modes
  replacing duplicated stcp_conn_process_recv in server+client (~250 LOC removed)
- stcp_conn_read / stcp_conn_do_close / stcp_tx_queue_cb: unified shared functions
- continuous stream XOR: stcp_frame_encrypt now XORs len+data+CRC
- handshake timeout via uasync_set_timeout (5s server, 10s client)
- RX backpressure: stcp_rx_push / stcp_rx_resume_if_needed with hysteresis
- stcp_server_list_remove: new API fixes opaque pointer violation in auto_socket
  and 4 double-free bugs on shutdown
- removed hs_expected_len/hs_key_processed fields (replaced by callback chain)
- removed recv_buf<4096 debug workaround
- stcp_try_send const fix (takes ownership of malloc'd data)
2026-08-08 10:48:12 +03:00
evgeny d453e73ddb etcp: TCP links skip remote keepalive gating; chatgui: show interface names in member detail, fix destructor callbacks 2026-08-08 07:31:38 +03:00
evgeny 80e77f12c2 fix: auto_socket TCP duplicate sockets + NAT v4 address resolution
auto_socket.c: create_iface_tcp_socket returns stcp_server* instead of int,
ifa->v4_tcp/ifa->v6_tcp now properly track the created server, preventing
duplicate bind/listen on every reconcile_iface call.

etcp_connections.c: tcp_socket_add now resolves interface_addr via
get_interface_ip_by_index/get_interface_ipv6_addr_nl for any type (not just
PUBLIC), preventing NAT TCP v4 sockets from being destroyed due to INADDR_ANY.
2026-08-07 20:06:30 +03:00
evgeny de61a2dacc fix: auto_socket TCP hang + missing debug config apply in utun_instance_create_from_config
auto_socket.c: remove tsrv from inst->stcp_servers before stcp_link_server_destroy
when TCP socket has null addr — freed pointer stayed in linked list corrupting it
on next stcp_server_listen->stcp_server_list_add, causing hang

utun_instance.c: apply debug_level + per-category debug from config in
utun_instance_create_from_config (was only in utun_instance_create)

chat_core.c: verbose error log on invalid args
2026-08-07 18:31:30 +03:00
evgeny ec9edb6a7c Add test_etcp_link_stress: dynamic socket/link add/remove during traffic
- 2 instances, 1 initial UDP connection, 2000ms stress test
- Sends 1 packet every 1ms during stress
- Every 100ms: adds new UDP/TCP socket+link, removes oldest with stats
- Liveness check per cycle detects hangs
- Per-link report: type, state, decrypted/encrypted/acked bytes, retrans, RTT
- Removal stats: lifetime, encrypted, decrypted, acked, retrans, RTT, inflight
2026-08-07 17:32:28 +03:00
evgeny d6c78d96c4 stcp: dedup encrypt/decrypt/send to stcp.c, add pending queue for buffering, add server pubkey verification, add 4MB bulk test 2026-08-07 13:31:24 +03:00
evgeny 087ac9b0e4 stcp: close old TCP links on reconnect, check stcp_link_is_ready before send, notify ETCP on STCP close
1a: tcp_server_on_link — close existing TCP links before creating new ETCP_LINK
1b: etcp_tcp_send — skip send if stcp_link not ready
3a+3b+3c: stcp_conn_set_on_close → stcp_link_on_stcp_close → marks link DOWN → triggers reconnect
2026-08-07 12:46:46 +03:00
evgeny fd00e5dd15 cp 2026-08-07 12:21:41 +03:00
evgeny 38c9f229bc stcp: ed25519 pubkey exchange in handshake, fix instance destroy segfault, fix chat_tcp_test
- u_async.c: process immediate_queue BEFORE epoll_wait in uasync_poll
- stcp_link.c: defensive NULL etcp_conn/etcp_link in stcp_link_close
- utun_instance.c: move stcp_server_list_destroy_all to Phase J (before ETCP),
  add deferred drain in both Phase J and L
- stcp.h/c: STCP_HS_ENC_CLIENT 6→38, STCP_HS_ENC_SERVER 7→39,
  exchange ed25519_pubkey in both handshake directions
- etcp_connections.c: copy peer_ed25519 from STCP to ETCP_CONN in
  etcp_link_enter_ready_tcp; guard link->etcp in tcp_link_close_cb
- chat_sync.c: fix lk->conn NULL dereference for TCP links
- test_stcp.c: update stcp_server_create/stcp_client_connect callsites
- tools/chat_tcp_test: change transport udp→tcp
2026-08-07 00:48:27 +03:00
evgeny a3783b5f55 fix: re-index conn_queue_entry after setting peer_node_id
tcp_server_on_link sets conn->peer_node_id after etcp_connection_create
which adds the entry with peer_node_id=0. instance_find_conn couldnt
find TCP connections until the queue entry was re-indexed.
2026-08-06 23:14:57 +03:00
evgeny adac854c94 fix: TCP data flow — tx_state, keepalive, last_recv_local_time
- etcp_link_enter_ready_tcp: set tx_state=DATA_WAIT (was 0, blocking sends)
- etcp_conn_input: update last_recv_local_time on every packet (keepalive liveness)
- link_rx_cb: handle ETCP_KEEPALIVE before etcp_conn_input (conflicts with MEAS_RESP=0x08)
- KEEPALIVE handler: set recv_keepalive, remote_keepalive, link_status, keepalive_recv_count
- test_stcp_traffic: etcp_send instead of raw stcp_link_send
- test_etcp_stcp: rewrite for utun_instance + etcp_connect
2026-08-06 23:09:01 +03:00
evgeny 928fa7731c refactor: STCP connections as ETCP links (is_tcp) 2026-08-06 22:14:44 +03:00
evgeny d773f1724a refactor: STCP connections as ETCP links (is_tcp)
- Add is_tcp, tcp_link, tcp_reconnect_* fields to ETCP_LINK
- Remove transport_link from ETCP_CONN, add tcp_link_count
- stcp_link: replace embedded etcp_conn with pointer; add etcp_link backpointer
- stcp_link: link_rx_cb routes ETCP data to etcp_conn_input
- stcp_link: call on_close_cb in close
- New TCP functions: etcp_link_enter_ready_tcp, etcp_tcp_link_start_connect,
  etcp_tcp_link_start_reconnect, tcp_link_close_cb, etcp_tcp_send
- etcp_link_new: handle NULL conn for TCP links; skip enter_init for TCP
- etcp_link_close: close stcp_link for TCP
- etcp_encrypt_send: redirect TCP to etcp_tcp_send (skips AES-CCM)
- tcp_server_on_link: create ETCP_LINK(is_tcp=1) + enter_ready_tcp
- etcp_connect: TCP addrs -> etcp_tcp_link_start_connect
- Remove ctx->tcp_link/tcp_ready
- test_stcp_traffic: find stcp_link via links->is_tcp instead of transport_link
- 66/68 tests pass; 2 STCP tests expected to fail (integration not complete)
2026-08-06 22:14:32 +03:00
evgeny 937af4c26a fix: STCP handshake ordering + invite peer_node_id match + test script
- stcp_server: send handshake response BEFORE on_ready to prevent ETCP INIT data mixing into client recv buffer (crc mismatch)
- conn_mgr: relax peer_node_id match for INVITE_INFO_RESP when peer_node_id==0 (STCP connections)
- chat_tcp_test: remove invalid 'local' outside function
2026-08-06 19:28:52 +03:00
evgeny 62504dc3b7 diag: full buffer dumps for CRC debug 2026-08-06 19:05:23 +03:00
evgeny c66b63ea39 diagnostics: stcp session_key + xor data dumps 2026-08-06 18:57:42 +03:00
evgeny dfe9d36783 wip: STCP TCP chat integration — diagnostics, invite TCP fallback, test infra 2026-08-06 18:41:41 +03:00
evgeny e2d8f68c9a fix: peer discovery queries include IPv6 (family IN (4,6))
get_public_peers, get_local_peers, get_supernode_peers
were filtering na.family=4 only — never found v6 peers.
Changed to na.family IN (4,6).
2026-08-06 14:20:33 +03:00
evgeny 25ebad9f52 fix: UDP packet size and addr_type classification
- etcp_connections.h: add WIRE_OVERHEAD, IP_UDP_OVERHEAD_V4/V6, SC_ENCRYPT_OVERHEAD
  (properly accounts for v6 IP(40)+UDP(8)+SC(3)+CCM tag(16) = 67 vs old UDP_HDR_SIZE=28)
- etcp_connections.c etcp_encrypt_send: use WIRE_OVERHEAD instead of UDP_HDR_SIZE
- etcp_connections.c send_init_response: clamp padding to max_data = mtu - WIRE_OVERHEAD
- chat_core_priv.h: add addr_type_from_ip() classifier
- chat_profile.c, chat_sync.c, member_sync.c: use classified addr_type instead of hardcoded 0
- chat_sync.c: skip zero nat_addr in JOIN, fall back to interface_addr
- topo_node_sqlite.c, member_sync.c: remove addr_type=0 filter from SELECT/DELETE
- chat_profile.c, member_sync.c: DELETE all addresses (not just addr_type=0)
2026-08-06 14:08:20 +03:00
evgeny 5066cff333 fix: IPv6 bind to permanent SLAAC address instead of ::
- etcp_connections.c: detect interface_addr before bind(),
  use specific IPv6 addr instead of in6addr_any
  (netlink path for Linux, connect trick for Android)
- chat_profile.c: filter PRIVATE/LOCAL sockets from
  node_addresses sync
- conn_mgr_core.c: diagnostic logs in cm_invite_tcp_connect,
  continue to next addr on TCP connect failure
- node_conn_direct.c: diagnostic logs in ncd_create_links
- auto_socket.c: suppress spurious ADDR_CHANGED events
- etcp_api.c: extended socket event log
2026-08-06 13:17:39 +03:00
evgeny dc8c9f7875 fix: cm_invite_pending — deferred free + cancelled guard
Корень краша: cm_handle_invite_info_resp вызывал cm_invite_cleanup(inv)
без unlink из invite_list — висячий указатель при conn_mgr_destroy → SIGSEGV.

Механизм защиты:
- cancelled:1 в cm_invite_pending — блокирует все коллбэки после cancel
- cm_invite_cancel: cancelled=1 первой строкой, deferred free через uasync_post
- Все коллбэки (NCD, TCP ready/close, overall timer): guard + DEBUG_WARN
- Success path: temp_nq=NULL (передача владения), вызов cm_invite_cancel
- INV_CANCEL логи: skip (NULL) / done — видно что реально сделано
2026-08-06 10:54:56 +03:00
evgeny f476188566 fix(chat): node online status race, WELCOME peer_needed off-by-one, JOIN missing proto byte
- node_put/node_update_verified: set online=1 on INSERT (nodes created when conn is UP)
- channel_peers_all: fix peer_needed calculation (atl byte was missing)
- cs_send_channel_join: add proto byte to address serialization matching all parsers
2026-08-06 01:18:27 +03:00
evgeny 38eb51c679 fix: Android event handler lost after restart — g_event_handler now preserved
Root cause: instance_lite_restart was creating new thread without
re-setting g_event_handler, causing all chat events (CHANNEL_UPDATED,
CONNECT_RESULT, etc.) to be silently dropped after app restart.

Fixes:
- instance_lite_restart: save/restore g_event_handler across hard restart
- instance_thread restart loop: re-call chat_event_set_handler after uasync_create
- utun_bridge_restart: call instance_lite_set_event_handler before restart
- AppEventHandler SharedFlow replay: 1 → 16 to not lose early init events
- ViewModel: added diagnostic logging for channel/connect events
- Keep diagnostic logs in instance_lite (set_handler, chat_event_forward NULL check)
- instance_event_handler: removed static for cross-block forward declaration
2026-08-06 00:06:28 +03:00
evgeny ef637d33a6 auto_socket: модуль авто-управления сокетами при изменении сетевых интерфейсов + fix pre-existing ASAN-багов
- auto_socket.c/h: создание/удаление UDP сокетов автоматически при изменении интерфейсов через netlink/route socket
  При auto_sockets=yes пропускает ручные [server] сокеты
  Тип сокета: PUBLIC если публичный IP, иначе NAT
  Для новых сокетов добавляются линки ко всем активным NCD-соединениям
  При удалении интерфейса линки убираются, сокет закрывается
  Platform-agnostic API для использования из Android/chatgui

- node_conn_direct.h/c: ncd_add_socket_links / ncd_remove_socket_links — управление линками на конкретном сокете

- socket_monitor.h/c: экспорт socket_monitor_update_if_addr для auto_socket

- config_parser.h/c: опция auto_sockets в [global]

- init_sockets(): пропуск ручных сокетов при auto_sockets=yes

- utun_instance: интеграция auto_socket_init/destroy

- media_delivery: fix stack-buffer-overflow ack[3] → ack[9]

- topo_node: fix heap-use-after-free в topo_group_update_my_nodeinfo — сохранение node_id/ver перед registry_store, использование return value
2026-08-05 23:09:59 +03:00
evgeny a0ba6dee21 fix: tgc_phase1_timeout closing all handles including connected ones 2026-08-05 18:57:35 +03:00
evgeny 513ec75c28 fix elementary format string bugs in log messages
- etcp.c:466: %d→%s for log_name (was printing garbage like -2012603448)
- etcp_connections.c:2235: Server type %d→%s with server_type_str()
- etcp_connections.c:845,1578,1587: type=%d/nat_type=%d→%s with helpers
2026-08-05 18:35:55 +03:00
evgeny 4c1ea11022 conn_mgr: split handler into router (routed) and direct paths
conn_mgr_router_recv_handler (etcp_router_bind): DIRECT_REQ, INTERM_EXCHANGE, DISCONNECT
conn_mgr_direct_recv_handler (etcp_bind): INVITE_INFO_REQ, INVITE_INFO_RESP
Each transport path now has its own handler — no more mixed concerns.
2026-08-05 18:16:18 +03:00
evgeny 85f23e0a94 conn_mgr: move etcp_router bind/unbind from per-group to instance level
svc_id=17 (ETCP_RT_ID_CONN_MGR) is a singleton resource — bind once
at utun_instance_init, unbind once at utun_instance_destroy.
Previously each conn_mgr (one per group) called bind/unbind separately,
causing 'overwriting' and 'not bound' WARNs on every group init/shutdown.
Handler dispatches by group_id from message — no need for per-group binding.
2026-08-05 18:04:43 +03:00
evgeny d296074330 etcp: show which specific link went DOWN + always use registry node_name
1. etcp_on_down: add down_link param — log the specific lost link + remaining
   Connection DOWN — link 192.168.40.247:2122 lost, remaining: [::1]:6669, [::2]:9970
   Connection DOWN — closing, links: ... (for reinit/close)

2. etcp_on_link_down: pass the triggering link through to etcp_on_down

3. etcp_update_log_name: always check registry for node_name
   (n_5a1b... → SM-A525F when name is available in registry)
2026-08-05 17:41:44 +03:00
evgeny 1b6fd1c29b etcp: use human-readable names for socket type and NAT type in logs
Add helper functions server_type_str() and nat_type_str() to convert
CFG_SERVER_TYPE_* and NAT_TYPE_* codes to readable names.
Now: Add Socket type=PUBLIC instead of type=1
     self-detect check: type=PUBLIC nat=UNKNOWN instead of type=1 nat_type=0
2026-08-05 17:32:53 +03:00
evgeny 5f24aad6a6 etcp: use node_name from registry in log_name for human-readable connection names
etcp_update_log_name: if name is empty, look up peer_node_id in topo_node_registry
and use node_name (e.g. 'SM-A525F') instead of empty or generic name.
Result: [45C2->03D3 [SM-A525F]] instead of [45C2->03D3 []]
2026-08-05 17:30:04 +03:00
evgeny 83aba82887 etcp: add link addresses to all UP/DOWN/close log messages
- etcp_on_up: list up-link addresses after connection summary
- etcp_on_down: show all link addresses that were lost
- Link UP (server/client): add addr=X
- Connection established: add addr=X
- Link closed: add addr=X before traffic stats
- Link down (keepalive timeout): add addr=X
Now: [conn] Link 1 UP (server, mtu=1600, addr=192.168.40.247:2122)
2026-08-05 17:24:41 +03:00
evgeny cf8236266b chat_sync: find_conn NOT FOUND INFO→DEBUG — fires for unrelated stub nodes during reinit storms 2026-08-05 14:26:00 +03:00
evgeny e51d8ddda2 chatgui: fix ERROR→WARN/DEBUG for normal situations
- member_sync apply_items: empty payload is normal sync completion, not error
- topo_node_sqlite node_load: no addresses is normal for stub/seed nodes
- conn_mgr_core: node skipped when not in routing (normal for nodes w/o addrs)
- topo_group send_nodeinfo: downgrade ERROR→WARN in DEBUG category
- db_sync INIT_RESP: protocol details belong in DEBUG, not INFO
2026-08-05 14:15:43 +03:00
evgeny 5feeb2c169 chatgui: clean up log — remove spam, move messages to proper categories
A-B: Remove gui_bridge_post_uasync_fn log, MainWindow::onMessageReceived, InputBar send text
B1: Move lifecycle messages to GENERAL (utun_node, main, mainwindow, animtimer, sound_manager, messagelist, db_manager)
B2: Move chat events to CHAT_SYNC (MSG_RECEIVED, CHANNEL_UPDATED, CHANNEL_PEERS_ONLINE, DB_READY)
B3: Move peer/connect events to MEMBER_SYNC (CONNECT_RESULT, NEW_PEER, AUTO_CONNECT, NODE_CHANGED)
C: Lower level of C-side spam (recalc, send OK, PUSH ACK, connect_channel) INFO->DEBUG
D: Fix duplicate PUSH log line in db_sync.c
E: Add debounce to CHANNEL_PEERS_ONLINE — log only on change
Misc: Remove sort=0 from ChannelList::loadChannels, improve DB_READY message
2026-08-05 12:50:27 +03:00
evgeny be0e76c9a6 debug: реорганизация категорий — SYS(1), ETCP(4) расширен, CONNECTION(3) очищен; fix stcp_client.c sock_err до connect()
Категории:
- DEBUG_CATEGORY_SYS=1: u_async + ll_queue + memory + timing (было 4)
- DEBUG_CATEGORY_ETCP=4: ETCP + normalizer + BBR (было 3)
- DEBUG_CATEGORY_CONNECTION=3: только события статуса линка/подключения (INFO)
- DEBUG_CATEGORY_KEEPALIVE=21: только периодический мониторинг (DEBUG)
- Удалены: NORMALIZER, BBR, CONNECTIVITY
- Устаревшие DB_SYNC → CHAT_SYNC + MEMBER_SYNC (предыдущий коммит)

CONNECTION+INFO — только: Connection UP/DOWN, Link UP/down, Link initialized/added,
  NAT address init/changed, init server/client.
CONNECTION+DEBUG — retry, collision, reinit, socket register.
KEEPALIVE — init_timer SUPPRESSED, timer started, keepalive skipped.
REINIT — ETCP+INFO.
Connection status changed — GENERAL (пользовательский callback).
Dedup link_status: if(old_link_status) перед Link down.
Убран дублирующий Conn:%s из Link down, добавлен link_id в client added link.
Молчаливые ошибки: +DEBUG_ERROR в 15 местах (merkle_sync, member_sync, db_sync).

Fix: stcp_client.c — socket_get_error() вызывался ДО connect(), проверяя
застарелое errno вместо ошибки connect(). Неблокирующий connect() возвращает
-1+EINPROGRESS (норма), но сравнивался с мусором → ложный FAIL.
Все 4 STCP-теста исправлены (68/68 pass).
2026-08-05 10:43:32 +03:00
evgeny 1895f23034 add chat_sync_invite_to_channel_with_addrs — connect with addresses, send CHANNEL_INVITE, 3s timeout, post result to GUI 2026-08-04 23:14:03 +03:00
evgeny 44c99f603d move INV button from footer into channel delegate rows (second button left of plus) 2026-08-04 22:57:36 +03:00
evgeny 24316e8cf8 split InviteDialog into ShareInviteDialog + InviteByLinkDialog, add INV button to channel list 2026-08-04 22:42:22 +03:00
evgeny 5632bc9c8b invitedialog: fix IPv4 byte order, show v6 prefix, add channel_id to diagnostic 2026-08-04 22:30:56 +03:00
evgeny 262dc9bb51 invitedialog: show decoded link info on text change (paste), not just on Send click 2026-08-04 22:23:54 +03:00
evgeny f8d98cab47 add error logging to all silent returns in chat_sync invite/join chain + GUI self-invite check 2026-08-04 22:20:01 +03:00
evgeny 21a0ee6caf conn_mgr: fix use-after-free in invite NCD callback cleanup
cm_invite_fail and cm_handle_invite_info_resp: always close invite's NCD
handle before freeing the invite struct. Previously the NCD close was
skipped when nq->handle != NULL (success path never closed it at all),
leaving cm_invite_ncd_callback registered with a dangling pointer.
On subsequent NCD DOWN event the stale callback caused SIGSEGV.
2026-08-04 20:53:38 +03:00
Evgeny fa5878ef4b media_download: fix md_mkdir_parent for Windows (drive letter, backslash), add errno to fopen errors, sanitize base_filename with WARNING 2026-08-04 19:09:46 +03:00
Evgeny cf1843e586 fix: etcp_connect_timeout_tb=0 in utun_instance_create (missing init)
utun_instance_create() allocated with u_calloc (zeroed) but never
set etcp_connect_timeout_tb. utun_instance_create_from_config() had it
at line 371, but utun_instance_create (used by chatgui) was missing.
Timer with tb=0 fires instantly → CLOSE sent before handshake completes.
Diagnostics confirmed: value_tb=0, tb=0, delta_tb=0 on Windows chatgui.
2026-08-04 18:25:24 +03:00
Evgeny 2b10f53466 diagnostics: ncd connect timer SET/FIRE logs + WSAEWOULDBLOCK fix + cm_invite_fail details
- u_async.c: log ncd_connect timer expiration calculation (tb, now_tb, exp_tb, exp_ms, delta_tb)
- node_conn_direct.c: SET logs at 4 timer creation points with value_tb/now_tb/path; TIMEOUT log with now_tb
- conn_mgr_core.c: cm_invite_fail entry log + CLOSE/SKIP branch detail
- stcp_client.c: fix WSAEWOULDBLOCK (10035) treated as error on Windows (add ERR_WOULDBLOCK check)
2026-08-04 18:16:53 +03:00
Evgeny 9d797c91eb chatgui: postChatSetting в хедер, chat_core_get_inst include, chat→chatserver 2026-08-04 17:28:05 +03:00
Evgeny 3b20c84c4d mkdtemp: #ifdef _WIN32 в локальных обёртках, без test_utils.h 2026-08-04 17:16:55 +03:00
Evgeny ebd975a03b mkdtemp → test_mkdtemp из test_utils.h для кроссплатформенной сборки (MSYS2/MinGW) 2026-08-04 17:13:45 +03:00