Skip to content

Email Header Analyzer — Rust source

Paste raw email headers to trace the message path, detect spoofing, and check SPF/DKIM/DMARC authentication results. Runs entirely in your browser.

This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! email-header-analyzer — RFC 5322 header parser + spoofing / authentication analysis.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `email-header-analyzer` tool, ported
//! from src/lib/email-header-analyzer.ts (the canonical TypeScript implementation).
//!
//! The TS lib leans on `Date.parse` for RFC 2822 dates; std Rust has no date
//! parser, so this file carries a small positional RFC 2822 parser (civil date
//! to Unix seconds via `days_from_civil`) plus hand-rolled stand-ins for the
//! lib's hop/auth regexes. Same inputs, same outputs.
//!
//! display source — part of CosmoDev's polyglot tool pages.

/// One unfolded header line, e.g. `From: a@b.com`.
pub struct Header { pub name: String, pub value: String }

/// One relay leg, chronological. `timestamp` is Unix seconds (None when the
/// Received header carried no parseable date); `delay` is seconds elapsed
/// since the previous (earlier) hop.
pub struct Hop {
    pub from: String,
    pub by: String,
    pub timestamp: Option<i64>,
    pub delay: Option<f64>,
    pub protocol: String,
}

/// One SPF/DKIM/DMARC verdict a relay recorded in Authentication-Results.
pub struct AuthResult {
    /// pass / fail / softfail / neutral / none / temperror / permerror / unknown
    pub result: String,
    pub domain: Option<String>,
    pub selector: Option<String>,
    /// DMARC `p=` token (dmarc only).
    pub policy: Option<String>,
    /// The full authentication clause, when present.
    pub detail: Option<String>,
}

pub struct AuthResults { pub spf: AuthResult, pub dkim: AuthResult, pub dmarc: AuthResult }

/// One suspicious pattern worth surfacing (`severity`: "critical" | "warning" | "info").
pub struct Anomaly { pub anomaly_type: String, pub severity: &'static str, pub message: String }

pub struct ParsedHeaders {
    pub headers: Vec<Header>,
    /// Chronological order: hops[0] is the OLDEST hop (parsed bottom-up).
    pub hops: Vec<Hop>,
    pub auth: AuthResults,
    pub anomalies: Vec<Anomaly>,
}

const SUSPICIOUS_MAILERS: [&str; 13] = ["bulk", "mass mail", "massmail", "storm", "flood", "bomber", "grabber", "harvest", "spambot", "stealth", "anonymous", "dark", "crack"];
const MONTHS: [&str; 12] = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
const WEEKDAYS: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];

/// Split raw header text into unfolded name/value pairs. Stops at the first
/// empty line (body separator).
pub fn parse_header_lines(raw: &str) -> Vec<Header> {
    let mut headers: Vec<Header> = Vec::new();
    let mut current: Option<usize> = None;
    for line in raw.replace("\r\n", "\n").split('\n') {
        if line.trim().is_empty() { break; } // end of headers / blank separator
        // Continuation line (RFC 5322 folding) — append to the previous value.
        if let Some(i) = current {
            if line.starts_with(' ') || line.starts_with('\t') {
                headers[i].value.push(' ');
                headers[i].value.push_str(line.trim());
                continue;
            }
        }
        // Not a header line (no colon, or colon first) — skip garbage.
        let Some(colon) = line.find(':').filter(|&c| c > 0) else { continue };
        headers.push(Header { name: line[..colon].trim().to_string(), value: line[colon + 1..].trim().to_string() });
        current = Some(headers.len() - 1);
    }
    headers
}

/// All values for a header name, case-insensitive, in file order.
pub fn get_headers(headers: &[Header], name: &str) -> Vec<String> {
    let lower = name.to_ascii_lowercase();
    headers.iter().filter(|h| h.name.to_ascii_lowercase() == lower).map(|h| h.value.clone()).collect()
}

/// Extract an email address from a header value: prefers `<addr>`, falls back
/// to the first bare address. (Hand-rolled stand-ins for the lib's two
/// address regexes.)
pub fn extract_address(value: &str) -> Option<String> {
    let chars: Vec<char> = value.chars().collect();
    for open in 0..chars.len() {
        if chars[open] != '<' { continue; }
        let mut inner = String::new();
        for &c in &chars[open + 1..] {
            match c {
                '<' => break, // regex cannot match here; retry from the next '<'
                '>' => { if !inner.is_empty() { return Some(inner); } break; }
                _ if c.is_whitespace() => break,
                _ => inner.push(c),
            }
        }
    }
    let ok = |c: char| !c.is_whitespace() && !"<>,;\"'".contains(c);
    for at in 0..chars.len() {
        if chars[at] != '@' || at == 0 || at + 1 >= chars.len() { continue; }
        if !ok(chars[at - 1]) || !ok(chars[at + 1]) { continue; }
        let mut start = at - 1;
        while start > 0 && ok(chars[start - 1]) { start -= 1; }
        let mut end = at + 1;
        while end + 1 < chars.len() && ok(chars[end + 1]) { end += 1; }
        return Some(chars[start..=end].iter().collect());
    }
    None
}

/// Howard Hinnant's `days_from_civil`: days since 1970-01-01 for a civil date.
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let (yoe, mp) = (y - era * 400, (m + 9) % 12);
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + (153 * mp + 2) / 5 + d - 1;
    era * 146097 + doe - 719468
}

/// RFC 5322 zone token to offset seconds (`+HHMM` / `-HHMM` or the named US
/// zones; unknown letters count as +0000, per the RFC's obs-zone rule).
fn zone_offset(token: &str) -> i64 {
    let b = token.as_bytes();
    if b.len() == 5 && (b[0] == b'+' || b[0] == b'-') {
        let sign: i64 = if b[0] == b'-' { -1 } else { 1 };
        let hh: i64 = token[1..3].parse().unwrap_or(0);
        let mm: i64 = token[3..5].parse().unwrap_or(0);
        return sign * (hh * 3600 + mm * 60);
    }
    match token.to_ascii_uppercase().as_str() {
        "EDT" => -4 * 3600,
        "EST" | "CDT" => -5 * 3600,
        "CST" | "MDT" => -6 * 3600,
        "MST" | "PDT" => -7 * 3600,
        "PST" => -8 * 3600,
        _ => 0, // GMT / UT / UTC / unknown
    }
}

/// Drop "(comment)" spans, mirroring the lib's `/\([^)]*\)/g` strip.
fn strip_comments(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    let mut depth = 0usize;
    for c in value.chars() {
        match c {
            '(' => depth += 1,
            ')' => depth = depth.saturating_sub(1),
            _ if depth == 0 => out.push(c),
            _ => {}
        }
    }
    out
}

/// Parse an RFC 2822 date into Unix seconds, ignoring "(ZONE)" comments —
/// the std-only stand-in for the TS `Date.parse`. Positional layout after any
/// weekday name: day month year HH:MM[:SS] zone. None when unparseable.
pub fn parse_rfc2822_date(value: &str) -> Option<i64> {
    let cleaned = strip_comments(value);
    let mut tokens: Vec<&str> = cleaned
        .split(|c: char| c == ',' || c.is_whitespace())
        .filter(|t| !t.is_empty())
        .collect();
    if let Some(first) = tokens.first() {
        let lower = first.to_ascii_lowercase();
        if WEEKDAYS.iter().any(|d| lower.starts_with(d)) {
            tokens.remove(0);
        }
    }
    if tokens.len() < 4 { return None; } // need day month year time
    let day: i64 = tokens[0].parse().ok()?;
    let month = MONTHS.iter().position(|m| *m == tokens[1].to_ascii_lowercase())? as i64 + 1;
    let mut year: i64 = tokens[2].parse().ok()?;
    if year < 100 { year += if year < 50 { 2000 } else { 1900 }; } // obsolete 2-digit years
    let mut time_parts = tokens[3].split(':');
    let hour: i64 = time_parts.next()?.parse().ok()?;
    let minute: i64 = time_parts.next().unwrap_or("0").parse().unwrap_or(0);
    let second: i64 = time_parts.next().unwrap_or("0").parse().unwrap_or(0);
    let zone = tokens.get(4).map(|z| zone_offset(z)).unwrap_or(0);
    Some(days_from_civil(year, month, day) * 86400 + hour * 3600 + minute * 60 + second - zone)
}

/// Stand-in for the lib's `/\b(?:Mon|Tue|…|Sun),\s+[^\n]+/` — the date-looking
/// fallback for Received values that omit the ';' before their timestamp.
fn date_guess(text: &str) -> Option<String> {
    let lower = text.to_ascii_lowercase();
    let bytes = lower.as_bytes();
    let mut start: Option<usize> = None;
    for day in WEEKDAYS {
        let mut from = 0usize;
        while let Some(pos) = lower[from..].find(day) {
            let abs = pos + from;
            let word_before = abs > 0 && (bytes[abs - 1] as char).is_ascii_alphanumeric();
            if !word_before && lower[abs + day.len()..].starts_with(',') {
                start = Some(match start { Some(s) => s.min(abs), None => abs });
                break;
            }
            from = abs + 1;
        }
    }
    let s = start?;
    let end = text[s..].find('\n').map(|e| s + e).unwrap_or(text.len());
    Some(text[s..end].trim_end().to_string())
}

/// First case-insensitive `keyword <whitespace> token` — hand-rolled stand-in
/// for the lib's `/\bfrom\s+([^\s(;]+)/i`-style hop regexes.
fn keyword_token(text: &str, keyword: &str) -> Option<String> {
    let lower = text.to_ascii_lowercase();
    let bytes = lower.as_bytes();
    let mut from = 0usize;
    while let Some(pos) = lower[from..].find(keyword) {
        let abs = pos + from;
        let word_before = abs > 0 && (bytes[abs - 1] as char).is_ascii_alphanumeric();
        let after = abs + keyword.len();
        if !word_before && after < bytes.len() && (bytes[after] as char).is_ascii_whitespace() {
            let rest = &text[after..];
            let end = rest.find(|c: char| c.is_whitespace() || c == '(' || c == ';').unwrap_or(rest.len());
            return Some(rest[..end].to_string());
        }
        from = abs + 1;
    }
    None
}

/// Strip one trailing '.' or ',', mirroring the lib's `/[.,]$/` trims.
fn trim_punct(s: &str) -> String {
    match s.strip_suffix('.').or_else(|| s.strip_suffix(',')) {
        Some(t) => t.to_string(),
        None => s.to_string(),
    }
}

/// Parse one Received header value into a hop (delay is filled in by parse_headers).
pub fn parse_received(value: &str) -> Hop {
    // The timestamp follows the last ';'. Some clients omit the ';' — fall
    // back to the first date-looking token.
    let timestamp = value
        .rfind(';')
        .and_then(|i| parse_rfc2822_date(&value[i + 1..]))
        .or_else(|| date_guess(value).and_then(|g| parse_rfc2822_date(&g)));
    Hop {
        from: keyword_token(value, "from").map(|t| trim_punct(&t)).unwrap_or_default(),
        by: keyword_token(value, "by").map(|t| trim_punct(&t)).unwrap_or_default(),
        timestamp,
        delay: None,
        protocol: keyword_token(value, "with").unwrap_or_default(),
    }
}

fn no_auth() -> AuthResult {
    AuthResult { result: "none".into(), domain: None, selector: None, policy: None, detail: None }
}

/// The verdict word after the first '=' — the lib's `/=\s*([a-z]+)\b/i`.
fn result_word(clause: &str) -> String {
    let bytes = clause.as_bytes();
    for i in 0..bytes.len() {
        if bytes[i] != b'=' { continue; }
        let mut j = i + 1;
        while j < bytes.len() && (bytes[j] as char).is_whitespace() { j += 1; }
        let start = j;
        while j < bytes.len() && bytes[j].is_ascii_alphabetic() { j += 1; }
        if j > start { return clause[start..j].to_ascii_lowercase(); }
    }
    "unknown".to_string()
}

/// `key=token` lookup — stand-in for the lib's `/\bkey=([^\s;)]+)/i`.
fn clause_token(clause: &str, key: &str) -> Option<String> {
    let lower = clause.to_ascii_lowercase();
    let bytes = lower.as_bytes();
    let mut from = 0usize;
    while let Some(pos) = lower[from..].find(key) {
        let abs = pos + from;
        let word_before = abs > 0 && (bytes[abs - 1] as char).is_ascii_alphanumeric();
        let after = abs + key.len();
        if !word_before && after < bytes.len() && bytes[after] == b'=' {
            let rest = &clause[after + 1..];
            let end = rest.find(|c: char| c.is_whitespace() || c == ';' || c == ')').unwrap_or(rest.len());
            return Some(trim_punct(&rest[..end]));
        }
        from = abs + 1;
    }
    None
}

/// The DMARC `p=` token — the lib's `/\bp=([a-z]+)/i`.
fn policy_word(clause: &str) -> Option<String> {
    let lower = clause.to_ascii_lowercase();
    let bytes = lower.as_bytes();
    for i in 0..bytes.len() {
        let word_before = i > 0 && (bytes[i - 1] as char).is_ascii_alphanumeric();
        if bytes[i] == b'p' && !word_before && i + 1 < bytes.len() && bytes[i + 1] == b'=' {
            let rest = &clause[i + 2..];
            let end = rest.find(|c: char| !c.is_ascii_alphabetic()).unwrap_or(rest.len());
            if end > 0 { return Some(rest[..end].to_ascii_lowercase()); }
        }
    }
    None
}

/// Parse Authentication-Results clauses. Example:
///   mx.google.com; spf=pass smtp.mailfrom=a@b.com; dkim=pass header.s=sel
///   header.d=b.com; dmarc=pass (p=REJECT) header.from=b.com
pub fn parse_auth_results(values: &[String]) -> AuthResults {
    let mut auth = AuthResults { spf: no_auth(), dkim: no_auth(), dmarc: no_auth() };
    for value in values {
        for raw in value.split(';') {
            let clause = raw.trim();
            let lower = clause.to_ascii_lowercase();
            let kind = if lower.starts_with("spf=") { 0 }
                else if lower.starts_with("dkim=") { 1 }
                else if lower.starts_with("dmarc=") { 2 }
                else { continue };
            let target = match kind { 0 => &mut auth.spf, 1 => &mut auth.dkim, _ => &mut auth.dmarc };
            if target.result != "none" { continue; } // first result wins
            target.result = result_word(clause);
            target.detail = Some(clause.to_string());
            match kind {
                0 => target.domain = clause_token(clause, "smtp.mailfrom").or_else(|| clause_token(clause, "mailfrom")),
                1 => {
                    target.domain = clause_token(clause, "header.d").or_else(|| clause_token(clause, "header.i"));
                    target.selector = clause_token(clause, "header.s");
                }
                _ => {
                    target.domain = clause_token(clause, "header.from");
                    target.policy = policy_word(clause);
                }
            }
        }
    }
    auth
}

/// Classic spoofing checks: sender mismatch, Reply-To misdirection, bulk
/// mailers, Received-chain gaps.
pub fn detect_anomalies(headers: &[Header], hops: &[Hop]) -> Vec<Anomaly> {
    let mut anomalies: Vec<Anomaly> = Vec::new();
    let mut add = |anomaly_type: &str, severity: &'static str, message: String| {
        anomalies.push(Anomaly { anomaly_type: anomaly_type.to_string(), severity, message });
    };
    let first = |name: &str| get_headers(headers, name).into_iter().next().unwrap_or_default();
    let from = extract_address(&first("From"));
    let return_path = extract_address(&first("Return-Path"));
    if let (Some(f), Some(r)) = (&from, &return_path) {
        if f.to_lowercase() != r.to_lowercase() {
            add("from-return-path-mismatch", "critical", format!("Return-Path ({r}) does not match From ({f}) — the envelope sender differs from the displayed sender. Common in spoofing and mailing-list relay."));
        }
    }
    let reply_to = extract_address(&first("Reply-To"));
    if let (Some(f), Some(rt)) = (&from, &reply_to) {
        if f.to_lowercase() != rt.to_lowercase() {
            add("reply-to-mismatch", "warning", format!("Reply-To ({rt}) differs from From ({f}) — replies would go to a different address than the visible sender."));
        }
    }
    let x_mailer = get_headers(headers, "X-Mailer").into_iter().next();
    let mailer = x_mailer.or_else(|| get_headers(headers, "User-Agent").into_iter().next()).unwrap_or_default();
    let hit = if mailer.is_empty() {
        None
    } else {
        let lower = mailer.to_lowercase();
        SUSPICIOUS_MAILERS.iter().find(|s| lower.contains(*s)).copied()
    };
    if let Some(token) = hit {
        add("suspicious-mailer", "warning", format!("Mailer string \"{mailer}\" contains a suspicious token (\"{token}\") often seen in bulk sending tools."));
    }
    for (i, hop) in hops.iter().enumerate() {
        match hop.timestamp {
            None => {
                let label = if !hop.from.is_empty() { &hop.from } else if !hop.by.is_empty() { &hop.by } else { "unknown" };
                add("hop-missing-timestamp", "info", format!("Hop {} ({}) has no parseable timestamp — delay for this leg cannot be computed.", i + 1, label));
            }
            Some(ts) => {
                if let Some(prev) = if i > 0 { hops[i - 1].timestamp } else { None } {
                    let delta = ts - prev;
                    if delta < 0 {
                        add("negative-delay", "warning", format!("Hop {} is timestamped {:.1}s BEFORE hop {} — clock skew between servers or a forged Received header.", i + 1, (delta as f64).abs(), i));
                    }
                }
            }
        }
    }
    if get_headers(headers, "Authentication-Results").is_empty() {
        add("no-auth-results", "info", "No Authentication-Results header found — SPF/DKIM/DMARC status cannot be verified from this message.".to_string());
    }
    anomalies
}

/// Parse raw email headers (RFC 5322): unfolded headers, chronological hops
/// with delays, auth verdicts, and spoofing anomalies.
pub fn parse_headers(raw: &str) -> ParsedHeaders {
    let headers = parse_header_lines(raw);
    // Received headers are listed newest-first; parse bottom-up so hops[0] is the oldest.
    let mut hops: Vec<Hop> = get_headers(&headers, "Received").iter().rev().map(|v| parse_received(v)).collect();
    for i in 1..hops.len() {
        if let (Some(prev), Some(cur)) = (hops[i - 1].timestamp, hops[i].timestamp) {
            hops[i].delay = Some((cur - prev) as f64);
        }
    }
    let auth = parse_auth_results(&get_headers(&headers, "Authentication-Results"));
    let anomalies = detect_anomalies(&headers, &hops);
    ParsedHeaders { headers, hops, auth, anomalies }
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →