wip(blaze-proto): retained Blaze frame/codec refinement WIP

RETAINED PRE-EXISTING WIP (brought forward after verification, not authored
here, not production-ready). Blaze wire frame/packet layout work (Fire2
header still flagged as an unvalidated FIFA23 guess). No secrets/captures
staged (captures/ + certs/ gitignored). Preserved off detached base f4f33969f2.
This commit is contained in:
funman300
2026-08-20 16:08:36 +00:00
parent f4f33969f2
commit b7126b255f
9 changed files with 227 additions and 144 deletions
+51 -25
View File
@@ -3,45 +3,57 @@
//! Every packet (in and out) is appended to a JSONL file so the session can
//! be replayed with `jq` and the component/command IDs can be catalogued.
use blaze_proto::Packet;
use chrono::Utc;
use serde_json::json;
use std::{
fs::{File, OpenOptions},
io::Write,
sync::{Arc, Mutex},
};
use blaze_proto::Packet;
use chrono::Utc;
use serde_json::json;
use tracing::{info, warn};
#[derive(Clone, Copy)]
pub enum Dir { In, Out }
pub enum Dir {
In,
Out,
}
impl Dir {
fn as_str(self) -> &'static str { match self { Dir::In => "IN", Dir::Out => "OUT" } }
fn as_str(self) -> &'static str {
match self {
Dir::In => "IN",
Dir::Out => "OUT",
}
}
}
pub struct CaptureWriter {
file : Arc<Mutex<File>>,
pretty : bool,
counter : Arc<Mutex<u64>>,
file: Arc<Mutex<File>>,
pretty: bool,
counter: Arc<Mutex<u64>>,
}
impl CaptureWriter {
pub fn open(dir: &str, pretty: bool) -> anyhow::Result<Self> {
std::fs::create_dir_all(dir)?;
let ts = Utc::now().format("%Y%m%d-%H%M%S");
let ts = Utc::now().format("%Y%m%d-%H%M%S");
let path = format!("{dir}/capture-{ts}.jsonl");
let file = OpenOptions::new().create(true).append(true).open(&path)?;
info!(path, "capture file opened");
Ok(CaptureWriter {
file: Arc::new(Mutex::new(file)),
file: Arc::new(Mutex::new(file)),
pretty,
counter: Arc::new(Mutex::new(0)),
})
}
pub fn record(&self, pkt: &Packet, peer: &str, dir: Dir) {
let n = { let mut c = self.counter.lock().unwrap(); *c += 1; *c };
let n = {
let mut c = self.counter.lock().unwrap();
*c += 1;
*c
};
let ts = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
let rec = pkt.to_capture();
@@ -67,21 +79,35 @@ impl CaptureWriter {
}
if self.pretty {
println!("\n╔══ #{n:04} {ts} {peer} {d} ══",
d = dir.as_str());
println!("║ component=0x{:04X} command=0x{:04X} {ty} seq={seq}",
rec.component, rec.command, ty = rec.ty, seq = rec.seq);
println!("\n╔══ #{n:04} {ts} {peer} {d} ══", d = dir.as_str());
println!(
"║ component=0x{:04X} command=0x{:04X} {ty} seq={seq}",
rec.component,
rec.command,
ty = rec.ty,
seq = rec.seq
);
if rec.body_len > 0 {
println!("║ body ({} bytes):\n{}",
rec.body_len,
pkt.body.chunks(16)
.enumerate()
.map(|(i, chunk)| {
let h: String = chunk.iter().map(|b| format!("{b:02X}")).collect::<Vec<_>>().join(" ");
let a: String = chunk.iter().map(|&b| if b.is_ascii_graphic() { b as char } else { '.' }).collect();
format!("\n{:04X}: {h:<47} {a}", i * 16)
})
.collect::<String>());
println!(
"║ body ({} bytes):\n{}",
rec.body_len,
pkt.body
.chunks(16)
.enumerate()
.map(|(i, chunk)| {
let h: String = chunk
.iter()
.map(|b| format!("{b:02X}"))
.collect::<Vec<_>>()
.join(" ");
let a: String = chunk
.iter()
.map(|&b| if b.is_ascii_graphic() { b as char } else { '.' })
.collect();
format!("\n{:04X}: {h:<47} {a}", i * 16)
})
.collect::<String>()
);
println!("║ TDF: {}", rec.tdf);
}
println!("╚══════════════════════════════════════════════════");
+13 -14
View File
@@ -2,50 +2,49 @@ use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Config {
pub redirector : RedirectorConfig,
pub blaze : BlazeConfig,
pub tls : TlsConfig,
pub capture : CaptureConfig,
pub redirector: RedirectorConfig,
pub blaze: BlazeConfig,
pub tls: TlsConfig,
pub capture: CaptureConfig,
}
#[derive(Debug, Deserialize)]
pub struct RedirectorConfig {
/// Address to listen on. EA clients connect to gosredirector.ea.com which
/// you redirect to 127.0.0.1 via /etc/hosts.
pub listen : String,
pub listen: String,
}
#[derive(Debug, Deserialize)]
pub struct BlazeConfig {
/// Address the Blaze server listens on.
pub listen : String,
pub listen: String,
/// Address / hostname we tell the client to connect to (in the redirect response).
pub advertise_host : String,
pub advertise_host: String,
/// Port we tell the client to connect to (in the redirect response).
pub advertise_port : u16,
pub advertise_port: u16,
}
#[derive(Debug, Deserialize)]
pub struct TlsConfig {
/// PEM certificate file (RSA-2048 recommended — DirtySDK rejects ECDSA).
pub cert : String,
pub cert: String,
/// PEM private key file.
pub key : String,
pub key: String,
}
#[derive(Debug, Deserialize)]
pub struct CaptureConfig {
/// Directory where JSONL capture files are written.
pub dir : String,
pub dir: String,
/// Also print decoded packet trees to stdout.
pub pretty_print : bool,
pub pretty_print: bool,
}
impl Config {
pub fn load(path: &str) -> anyhow::Result<Self> {
let text = std::fs::read_to_string(path)
.map_err(|e| anyhow::anyhow!("cannot read {path}: {e}"))?;
toml::from_str(&text)
.map_err(|e| anyhow::anyhow!("config parse error in {path}: {e}"))
toml::from_str(&text).map_err(|e| anyhow::anyhow!("config parse error in {path}: {e}"))
}
}
+14 -8
View File
@@ -3,8 +3,8 @@
//! All FIFA 23 component/command IDs are UNKNOWN until capture reveals them.
//! The default handler returns an empty response — never panics, never hangs.
use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc};
use blaze_proto::Packet;
use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc};
use tracing::warn;
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
@@ -15,15 +15,19 @@ pub struct Dispatcher {
}
impl Dispatcher {
pub fn new() -> Self { Dispatcher { table: HashMap::new() } }
pub fn new() -> Self {
Dispatcher {
table: HashMap::new(),
}
}
pub fn register<F, Fut>(&mut self, component: u16, command: u16, f: F)
where
F: Fn(Packet) -> Fut + Send + Sync + 'static,
F: Fn(Packet) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Option<Packet>> + Send + 'static,
{
self.table.insert((component, command),
Arc::new(move |p| Box::pin(f(p))));
self.table
.insert((component, command), Arc::new(move |p| Box::pin(f(p))));
}
pub async fn dispatch(&self, pkt: Packet) -> Option<Packet> {
@@ -31,9 +35,11 @@ impl Dispatcher {
if let Some(h) = self.table.get(&key) {
h(pkt).await
} else {
warn!(component = format!("0x{:04X}", key.0),
command = format!("0x{:04X}", key.1),
"unhandled — returning empty response");
warn!(
component = format!("0x{:04X}", key.0),
command = format!("0x{:04X}", key.1),
"unhandled — returning empty response"
);
Some(Packet::response_empty(&pkt))
}
}
+39 -25
View File
@@ -33,14 +33,19 @@ async fn main() -> anyhow::Result<()> {
)
.init();
let cfg_path = std::env::args().nth(1).unwrap_or_else(|| "config.toml".into());
let cfg_path = std::env::args()
.nth(1)
.unwrap_or_else(|| "config.toml".into());
let cfg = config::Config::load(&cfg_path)?;
info!(config = cfg_path, "loaded");
let tls_cfg = tls::load_tls_config(&cfg.tls.cert, &cfg.tls.key)?;
let acceptor = TlsAcceptor::from(Arc::clone(&tls_cfg));
let capture = Arc::new(CaptureWriter::open(&cfg.capture.dir, cfg.capture.pretty_print)?);
let capture = Arc::new(CaptureWriter::open(
&cfg.capture.dir,
cfg.capture.pretty_print,
)?);
let dispatcher = Arc::new(Dispatcher::new());
let redir_addr: SocketAddr = cfg.redirector.listen.parse()?;
@@ -55,18 +60,22 @@ async fn main() -> anyhow::Result<()> {
// ── Redirector loop ───────────────────────────────────────────────────────
let redir_acceptor = acceptor.clone();
let redir_cap = Arc::clone(&capture);
let adv_host = Arc::clone(&advertise_host);
let redir_cap = Arc::clone(&capture);
let adv_host = Arc::clone(&advertise_host);
tokio::spawn(async move {
loop {
match redir_listener.accept().await {
Err(e) => { error!(error=%e, "redirector accept error"); }
Err(e) => {
error!(error=%e, "redirector accept error");
}
Ok((tcp, peer)) => {
let acc = redir_acceptor.clone();
let cap = Arc::clone(&redir_cap);
let acc = redir_acceptor.clone();
let cap = Arc::clone(&redir_cap);
let host = Arc::clone(&adv_host);
tokio::spawn(async move {
if let Err(e) = handle_redirector(tcp, peer, acc, cap, &host, advertise_port).await {
if let Err(e) =
handle_redirector(tcp, peer, acc, cap, &host, advertise_port).await
{
warn!(%peer, error=%e, "redirector session error");
}
});
@@ -78,10 +87,12 @@ async fn main() -> anyhow::Result<()> {
// ── Blaze loop ────────────────────────────────────────────────────────────
loop {
match blaze_listener.accept().await {
Err(e) => { error!(error=%e, "blaze accept error"); }
Err(e) => {
error!(error=%e, "blaze accept error");
}
Ok((tcp, peer)) => {
let acc = acceptor.clone();
let cap = Arc::clone(&capture);
let acc = acceptor.clone();
let cap = Arc::clone(&capture);
let disp = Arc::clone(&dispatcher);
tokio::spawn(async move {
if let Err(e) = handle_blaze(tcp, peer, acc, cap, disp).await {
@@ -96,15 +107,15 @@ async fn main() -> anyhow::Result<()> {
// ── Redirector handler ────────────────────────────────────────────────────────
async fn handle_redirector(
tcp : TcpStream,
peer : SocketAddr,
tcp: TcpStream,
peer: SocketAddr,
acceptor: TlsAcceptor,
capture : Arc<CaptureWriter>,
host : &str,
port : u16,
capture: Arc<CaptureWriter>,
host: &str,
port: u16,
) -> anyhow::Result<()> {
let tls = acceptor.accept(tcp).await?;
let codec = PacketCodec::new(FramingVariant::Fire2);
let tls = acceptor.accept(tcp).await?;
let codec = PacketCodec::new(FramingVariant::Fire2);
let mut io = Framed::new(tls, codec);
let peer_str = peer.to_string();
@@ -120,7 +131,10 @@ async fn handle_redirector(
// capture will reveal it. For now we return our advertise address as a
// simple string blob so the client gets something to parse.
let body = build_redirector_body(host, port);
let resp = Packet { frame: req.frame.response(), body };
let resp = Packet {
frame: req.frame.response(),
body,
};
capture.record(&resp, &peer_str, Dir::Out);
io.send(resp).await?;
}
@@ -146,14 +160,14 @@ fn build_redirector_body(host: &str, port: u16) -> Bytes {
// ── Blaze session handler ─────────────────────────────────────────────────────
async fn handle_blaze(
tcp : TcpStream,
peer : SocketAddr,
acceptor : TlsAcceptor,
capture : Arc<CaptureWriter>,
tcp: TcpStream,
peer: SocketAddr,
acceptor: TlsAcceptor,
capture: Arc<CaptureWriter>,
dispatcher: Arc<Dispatcher>,
) -> anyhow::Result<()> {
let tls = acceptor.accept(tcp).await?;
let codec = PacketCodec::new(FramingVariant::Fire2);
let tls = acceptor.accept(tcp).await?;
let codec = PacketCodec::new(FramingVariant::Fire2);
let mut io = Framed::new(tls, codec);
let peer_str = peer.to_string();
+8 -7
View File
@@ -1,7 +1,10 @@
use std::{fs::File, io::BufReader, sync::Arc};
use rustls::{ServerConfig, pki_types::{CertificateDer, PrivateKeyDer}};
use rustls_pemfile::{certs, private_key};
use anyhow::Context;
use rustls::{
pki_types::{CertificateDer, PrivateKeyDer},
ServerConfig,
};
use rustls_pemfile::{certs, private_key};
use std::{fs::File, io::BufReader, sync::Arc};
/// Load a TLS `ServerConfig` from PEM cert and key files.
///
@@ -13,10 +16,8 @@ pub fn load_tls_config(cert_path: &str, key_path: &str) -> anyhow::Result<Arc<Se
// Install the ring crypto provider once. Harmless if called multiple times.
let _ = rustls::crypto::ring::default_provider().install_default();
let cert_file = File::open(cert_path)
.with_context(|| format!("open cert: {cert_path}"))?;
let key_file = File::open(key_path)
.with_context(|| format!("open key: {key_path}"))?;
let cert_file = File::open(cert_path).with_context(|| format!("open cert: {cert_path}"))?;
let key_file = File::open(key_path).with_context(|| format!("open key: {key_path}"))?;
let certs: Vec<CertificateDer> = certs(&mut BufReader::new(cert_file))
.collect::<Result<_, _>>()