Commit Graph
1387 Commits
Author SHA1 Message Date
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 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 1b1bf91e79 Убран неиспользуемый #include <netdb.h> ломающий сборку на MSYS2/MinGW 2026-08-04 16:42:03 +03:00
Evgeny d816493af6 Инвайт-ссылка chatserver печатается в лог всегда, не только в foreground 2026-08-04 16:32:17 +03:00
Evgeny ae1add5437 parse_chatserver: молчаливый провал, ошибка только после chat_setting_set 2026-08-04 16:28:18 +03:00
Evgeny 876155688f Устранено дублирование: storage_total_size/unit_size вместо storage_maxsize_gb/autoload_maxsize_mb 2026-08-04 16:17:06 +03:00
Evgeny c22991f7d9 Добавлена секция [chatserver] в конфиг — объединяет активацию чата и настройки в одной секции 2026-08-04 16:05:06 +03:00
evgeny 712d1b53df 1 2026-08-04 15:29:25 +03:00
Evgeny 26f4da1b7c socket_monitor: cross-platform support (Linux netlink, FreeBSD AF_ROUTE, Windows IP Helper)
- platform_compat: get_interface_ipv6_addr_nl stub uses get_interface_ipv6_by_index fallback
  - socket_monitor: extract common update_if_addr/fire_one, platform dispatch
  - FreeBSD: PF_ROUTE socket with RTM_IFINFO/NEWADDR/ADD event monitoring
  - Windows: NotifyUnicastIpAddressChange + NotifyRouteChange2 via uasync_post
2026-08-04 15:20:20 +03:00
evgeny de9e467b39 media_delivery: BLOCK_PROCESSING + relay streaming + per-file download limit
- block_availability: status column (0=processing, 1=completed)
- md_ba_complete_block(): DELETE old + check exists + INSERT new id
- BLOCK_PROCESSING subcmd (0x10) — INSERT with new id, no REPLACE/IGNORE
- BLOCK_RELAY_FULL subcmd (0x11) — redirect when source/relay at capacity
- relay_block_ctx: downstream forwarding from chunk file
- md_file_load: per-file source download limit (max_downloads_per_file)
- RELAY_FULL from source node when at capacity
- relay_full handler: retry existing peers, not just new ones
- sync.md: full documentation
2026-08-04 11:42:59 +03:00
evgeny 7263bdcf56 media_download tests: backpressure, block relay, OOB block_id, assembly
5 new tests in test_media_delivery_download:
- conn_cb starts only first block (backpressure)
- conn_cb with multiple peers
- BLOCK_DONE triggers next block relay from same peer
- assembly after all blocks validated
- peer with more blocks than dl (OOB fix verification)

md_dl_conn_cb made non-static for test visibility
md_dl_send added NULL guard for test instances without routing
media_download.h: added conn_cb extern declaration
2026-08-04 00:22:18 +03:00
evgeny 41e9c9b0e6 media_download: fix block_id OOB, add backpressure, close conn_mgr
- md_dl_send_block_req now takes explicit block_id (not peer-local index
  into dl->block_ids) — fixes OOB 'aaaaaaaa...' garbage block_id
- conn_cb sends only first unstarted block per peer (backpressure)
- BLOCK_DONE success triggers next block from same peer
- conn_mgr handles stored in peer->cm_handle, closed on assembly/cancel
2026-08-04 00:02:20 +03:00
evgeny 3665a9bc23 chat_msg: fix strstr on non-null-terminated blob/text data
chat_core_attachment_download: use sqlite3_column_text for null-term
on_msg_inserted: copy data to local null-term buf before strstr
Both caused b64_decode to misread body from garbage memory
2026-08-03 23:31:56 +03:00
evgeny a0049a4187 b64 prefix: * marker to distinguish base64-encoded display data from old plain text
* prefix prepended in on_media_registered before b64 data
on_msg_inserted, chat_core_attachment_download, get_messages_json
only attempt b64_decode when prefix starts with '*' marker
2026-08-03 23:10:15 +03:00
evgeny ea6eeae210 msg b64: base64-encode display prefix in d-field to avoid pipe/quote breaking parse
b64_encode/decode (URL-safe A-Za-z0-9-_) in chat_core_priv.h
on_media_registered encodes msg_data before full_data
on_msg_inserted/chat_core_attachment_download decode base_filename
android_jni_bridge decodes prefix for UI display
2026-08-03 23:02:49 +03:00
evgeny e3df5008da etcp: fire link_status_cbk in etcp_link_new for new links 2026-08-03 21:46:22 +03:00
evgeny 13c6ef2210 member_sync: fix p-6 for ip pointer, add stcp link addr+status to JNI bridge 2026-08-03 21:13:08 +03:00
evgeny 5d23f461a7 member_sync/topo_sqlite: add proto byte to address serialization
- _compute_bucket_hash: SELECT protocol, write proto byte
- _member_get_items: SELECT protocol, write proto byte
- _member_apply_items: consume proto byte in skip calculation
- topo_node_sqlite_channel_peers_all: SELECT protocol, write proto byte
All 5 writers and 5 readers now consistently include protocol byte.
2026-08-03 20:59:26 +03:00
evgeny 8023f6ee70 stcp: separate v4/v6 sockets, protocol byte in chat addr format, error on bind fail
- stcp_server_create: support AF_INET and AF_INET6 V6ONLY=1 (no dual-stack)
- Add listen_family to stcp_link_config
- init_sockets: return error (not partial) on any bind failure
- add chat_core_sync_my_addresses() call at chatgui startup
- collect_my_addrs: add proto byte (1=UDP, 2=TCP) to binary format
- chat_sync.c JOIN/WELCOME/PEER_UPSERT: read proto byte, write protocol column
- member_sync.c: read proto byte, dynamic protocol bind
- topo_node.c: debug logs for nodeinfo changed detection
- node_config.cpp: type=public for all servers
2026-08-03 20:35:46 +03:00
evgeny 3deaa0eabe stcp: multiple servers support via linked list in UTUN_INSTANCE
- Replace instance->stcp_server (single pointer) with stcp_servers linked list
- Add stcp_server_list_add/destroy_all/count API in stcp_link.h/c
- Fix port extraction for both AF_INET and AF_INET6 in init_sockets
- Filter out 0.0.0.0 and [::] addresses in chat_profile.c TCP address sync
- Add type=public to servers in node_config.cpp saveFull()
2026-08-03 19:39:50 +03:00
evgeny e1e54df4f4 fix: invite не затирает имя узла, имя читается из member_sync peers.userinfo
- conn_mgr_core.c: убрана запись node_name из cm_handle_invite_info_resp
- topo_node_sqlite.c: name в nodes не перезаписывается пустой строкой
- android_jni_bridge.c: bridge_get_node_name читает peers_<ch>.userinfo если nodes.name пуст
2026-08-03 18:50:11 +03:00
evgeny 253129cb27 topo_node_sqlite: убрал запись node_addresses из BGP-пути (только nodes). Адреса — через member_sync. 2026-08-03 15:17:51 +03:00
evgeny ddf696bcf6 refactor: TCP socket addresses — sync to chat DB, topo_node, config file single source
- chat: collect_my_addrs extends to TCP + IPv6, chat_core_sync_my_addresses writes TCP addrs
- topo_node: replace CFG_SERVER with TCP_SOCKET for TCP addresses, simplify NAT logic
- etcp_connections: add IPv6 interface addr resolution for TCP sockets
- Android: INI config file as single source of truth for servers, remove JSON/Gson
- Android: filter temporary IPv6 addresses, fix restart with socket cleanup
- instance_lite: sync addresses after socket creation, proper restart cleanup
2026-08-03 13:57:42 +03:00
evgeny 740ed2a93a fix: NCD UAF, conn_mgr invite protocol, node_id derivation, link reuse
node_conn_direct:
- ncd_init_cb: skip UP when links_up==0, ncd_up_cb delivers when link comes up
- close/force_close: handle_count safety checks, callback clearing
- open/open_node case 2: create links on reused dead conn
- ncd_create_links: skip duplicate link on same conn (stale->etcp==conn)
- set_callback: optional callback change on live handle

conn_mgr:
- cm_ncd_callback: DOWN only delivers event (handle stays alive)
- cm_ncd_callback: TIMEOUT force_close BEFORE cm_deliver_event
- cm_deliver_event: read handle fields to locals before callback (reentrany-safe)
- INVITE_INFO_REQ/RESP: add duplicate cmd byte for direct-send protocol
- cm_handle_invite_info_resp: search invite by group_id in channel conn_mgr

Android:
- node_id computed by sc_derive_node_id_from_pubkey in C, not Kotlin
- utun_bridge_join_channel: recompute node_id, log mismatch
- invite_link_c: compute nodeId from pubkey via sc_derive_node_id_from_pubkey
- NativeLib.deriveNodeId, InviteLink.kt uses C function
2026-08-03 09:51:06 +03:00
evgeny 4b07d59043 chat: skip own addresses from remote in member_sync_recv
Remote peers should not overwrite local node_addresses.
When member_sync_recv processes data about our own node_id,
we trust locally-synced addresses (from sync_my_addresses)
and ignore address data from the remote peer.
2026-08-02 20:42:40 +03:00
evgeny 63272abe53 chat: fix duplicate v6 address from v4 socket's interface_addr
sync_my_addresses used interface_addr even when its family
differed from the socket's local_addr family. A v4 socket
bound to 0.0.0.0 could pick up a v6 interface_addr on
dual-stack Android, inserting a duplicate v6 entry.
Now interface_addr is only used when families match.
2026-08-02 20:38:42 +03:00
evgeny c2191aad3b chat: user-friendly INFO logs for invite/connect flow
- chat_sync.c: invite entry, JOINED/TIMEOUT messages
- conn_mgr_core.c: invite start (addrs+udp+tcp), NCD UP/DOWN/TIMEOUT,
  TCP connect/ready/close, membership check send/receive/confirm/deny,
  overall timeout
- node_conn_direct.c: NCD event names instead of numbers
2026-08-02 20:32:01 +03:00
evgeny c35135cb52 topo_group: migrate CONN_MGR entries to ll_queue, simplify TOPO_GROUP_NODE
- CONN_MGR entries: replace dynamic array with ll_queue (hash=256, key_size=8)
  cm_find_entry now O(1) via queue_find_data_by_index
  cm_ensure_entry uses queue_entry_new + queue_data_put_with_index
  cm_entry_cleanup removes from queue and frees entry

- TOPO_GROUP_NODE: replace handles** array with single CONN_MGR_HANDLE*
  remove topo_node_handle_register/unregister/count — dead indirection
  nq->handle = h / nq->handle = NULL in all call sites

- TOPO_GROUP_NODE: remove dead fields dirty, best_socket, tranzit_data/count
  dirty replaced with local variable in nat_detection.c
  tranzit_data removed from wire format (TOPOMSG_NODE), serialize, deserialize
  update struct layout: one field per line with comments
2026-08-02 16:45:52 +03:00
evgeny f5efaa495b socket_monitor: extract socket monitoring from etcp_connections, add per-instance context
- New files: transport_layer/socket_monitor.c/h — socket state monitoring with per-instance ctx
- etcp_api: expose get_latency/1s_pkt_count measuring, add etcp_hashrnd for tests
- utun_instance: store socket_monitor per instance, add is_socket_ok check
- topo_node: detect IPv4 addresses with port from listening sockets
- topo_group: use node_name for display in routes
- Makefile.am: add socket_monitor.c to build
2026-08-02 12:16:42 +03:00