VNOX-Client/src/net/session/handlers/core.rs
loki5512344 9a20ace6e6
feat(client): TLS 1.3 control connection with SPKI pinning and LNEx v3
Replace the custom X25519/HKDF/ChaCha20 TCP layer with rustls (TLS 1.3 only,
ALPN vnox-lnex/3, no plaintext or fallback). Add a trust store (pin, trust on
first use, public CA), block changed fingerprints and identities, bind the
Ed25519 auth signature to the TLS exporter, add RU/EN trust dialog and
update the interop test and e2e voice tool.

Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4
2026-10-24 22:05:19 +02:00

214 lines
9.5 KiB
Rust

use std::time::Duration;
use anyhow::{Context, Result};
use tokio::sync::mpsc;
use tokio::time::{MissedTickBehavior, interval};
use tracing::warn;
use crate::identity::Identity;
use crate::net::wire;
use crate::net::{
framing, handshake, internal,
payloads::*,
trust::TrustStore,
types::{NetCommand, NetEvent},
};
use super::super::switch::ReconnectRequested;
use super::{VoiceState, handle_cmd};
pub async fn session_loop(
identity: &Identity,
address: &str,
trust: &TrustStore,
channels: &mut Vec<String>,
restored: bool,
cmd_rx: &mut mpsc::Receiver<NetCommand>,
event_tx: &mpsc::Sender<NetEvent>,
) -> Result<()> {
let connection = tokio::time::timeout(
Duration::from_secs(10),
crate::net::transport::connect_with_peer(address, trust),
)
.await
.context("gateway connection timed out")??;
let peer = connection.peer;
let mut stream = connection.stream;
let mut seq = 0u32;
let outcome = tokio::time::timeout(
Duration::from_secs(10),
handshake::run(
&mut stream,
identity,
&mut seq,
&connection.binding,
&connection.trust_key,
connection
.record
.as_ref()
.and_then(|record| record.identity.as_deref()),
),
)
.await
.context("gateway handshake timed out")??;
// The identity is learned inside an already trusted channel and then pinned.
if let Err(error) = trust.set_identity(&connection.trust_key, &outcome.server_identity) {
tracing::warn!(%error, "could not store the server identity");
}
let session_id = outcome.session_id;
let node_name = outcome.node_name;
let private_mode = outcome.private_mode;
let _ = event_tx
.send(NetEvent::Connected {
session_id: session_id.clone(),
node_name,
restored,
private_mode,
})
.await;
for channel_id in channels.clone() {
framing::write(
&mut stream,
PID_JOIN_CHANNEL,
&mut seq,
&wire::encode(&JoinChannelPayload { channel_id })?,
)
.await?;
}
let (reader, mut stream) = tokio::io::split(stream);
let mut incoming = framing::io::Reader::new(reader);
let mut voice_state: Option<VoiceState> = None;
let mut used_voice_routes = std::collections::HashSet::new();
let mut voice_endpoint: Option<std::net::SocketAddr> = None;
let mut voice_tick = interval(Duration::from_secs(5));
voice_tick.set_missed_tick_behavior(MissedTickBehavior::Delay);
let mut ping_tick = interval(Duration::from_secs(2));
ping_tick.set_missed_tick_behavior(MissedTickBehavior::Delay);
loop {
tokio::select! {
_ = voice_tick.tick() => { if let Some(voice)=voice_state.as_mut() {voice.keep_alive().await?;} }
_ = ping_tick.tick() => {
let ts = now_ms();
let payload = wire::encode(&PingPayload { timestamp: ts })?;
framing::write(&mut stream, PID_PING, &mut seq, &payload).await?;
}
result = incoming.next() => {
let pkt = result?;
if pkt.packet_id == PID_VOICE_SESSION {
let session:wire::VoiceSession=wire::decode(&pkt.payload)?;
anyhow::ensure!(session.route_id.len()==16 && session.c2s_key.len()==32 && session.s2c_key.len()==32,"invalid voice credentials");
anyhow::ensure!(used_voice_routes.len()<1024 && used_voice_routes.insert(session.route_id.clone()),"voice credentials must be fresh; reconnect required");
let mut voice=VoiceState::new(event_tx,peer.is_ipv6()).await?;
if let Some(endpoint)=voice_endpoint {voice.set_endpoint(endpoint).await?;}
voice.configure(session).await?;
voice_state=Some(voice);continue;
}
if pkt.packet_id == PID_VOICE_STATE {
let state:wire::VoiceState=wire::decode(&pkt.payload)?;
if state.state=="disconnected" && state.user_id==identity.pubkey_hex {
if voice_state.as_ref().and_then(|value|value.channel_id())==Some(state.channel_id.as_str()) {voice_state=None;voice_endpoint=None;}
channels.retain(|id|id!=&state.channel_id);
let _=event_tx.send(NetEvent::VoiceRevoked {channel_id:state.channel_id}).await;
}
continue;
}
if pkt.packet_id == PID_CHANNEL_STATE
&& let Ok(p) = wire::decode::<ChannelStatePayload>(&pkt.payload)
&& p.kind == "voice" && !p.voice_endpoint.is_empty()
{
let mut endpoint:std::net::SocketAddr=p.voice_endpoint.parse()?;
if endpoint.ip().is_unspecified() {endpoint.set_ip(peer.ip());}
voice_endpoint=Some(endpoint);
if let Some(voice)=voice_state.as_mut(){voice.set_endpoint(endpoint).await?;}
}
internal::dispatch::incoming(pkt.packet_id, &pkt.payload, event_tx).await?;
}
cmd = cmd_rx.recv() => {
match cmd {
None | Some(NetCommand::Disconnect) => {
let _ = framing::write(&mut stream, PID_DISCONNECT, &mut seq,
&wire::encode(&Disconnect {reason: "bye".into()})?).await;
return Ok(());
}
Some(NetCommand::Connect { address, auto_reconnect }) => {
warn!("connect while connected to {address}, reconnecting");
if channels.is_empty() {
*channels = vec!["general".into()];
}
return Err(anyhow::Error::new(ReconnectRequested {
address,
auto_reconnect,
}));
}
Some(NetCommand::JoinChannel { channel_id }) => {
track_channel(channels, &channel_id);
framing::write(&mut stream, PID_JOIN_CHANNEL, &mut seq,
&wire::encode(&JoinChannelPayload { channel_id })?).await?;
}
Some(NetCommand::LeaveChannel { channel_id }) => {
channels.retain(|c| c != &channel_id);
if voice_state.as_ref().and_then(|value|value.channel_id())==Some(channel_id.as_str()) {voice_state=None;voice_endpoint=None;}
framing::write(&mut stream, PID_LEAVE_CHANNEL, &mut seq,
&wire::encode(&LeaveChannelPayload { channel_id })?).await?;
}
Some(NetCommand::ChannelCreate { channel_id, channel_name, kind, guild_id }) => {
let payload = wire::encode(&ChannelCreatePayload {
channel_id,
channel_name,
kind,
guild_id,
})?;
framing::write(&mut stream, PID_CHANNEL_CREATE, &mut seq, &payload).await?;
}
Some(NetCommand::ChannelDelete { channel_id }) => {
let payload = wire::encode(&ChannelDeletePayload { channel_id })?;
framing::write(&mut stream, PID_CHANNEL_DELETE, &mut seq, &payload).await?;
}
Some(NetCommand::ChannelList) => {
framing::write(&mut stream, PID_CHANNEL_LIST, &mut seq, b"").await?;
}
Some(NetCommand::SendChat { channel_id, content, reply_to }) => {
let msg = ChatMessagePayload {
message_id: uuid_v4(), channel_id,
sender_id: identity.pubkey_hex.clone(),
content, timestamp: now_ms(),
edited: false,
reply_to,
};
framing::write(&mut stream, PID_CHAT_MESSAGE, &mut seq, &wire::encode(&msg)?).await?;
}
Some(NetCommand::SendVoice { channel_id, voice_seq: voice_pkt_seq, timestamp, opus_data }) => {
if let Some(voice)=voice_state.as_mut(){voice.send(Some(channel_id), voice_pkt_seq, timestamp, &opus_data).await?;}
}
Some(NetCommand::ReadReceipt { channel_id, last_read_message_id }) => {
let payload = wire::encode(&ReadReceipt {channel_id,last_read_message_id,user_id: identity.pubkey_hex.clone()})?;
framing::write(&mut stream, PID_READ_RECEIPT, &mut seq, &payload).await?;
}
Some(other) => handle_cmd(other, &mut stream, &mut seq, identity).await?,
}
}
}
}
}
pub(super) fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as i64
}
pub(super) fn uuid_v4() -> String {
uuid::Uuid::new_v4().to_string()
}
fn track_channel(channels: &mut Vec<String>, channel_id: &str) {
if !channels.iter().any(|c| c == channel_id) {
channels.push(channel_id.to_string());
}
}