aria2-protocol 0.3.10

Multi-protocol networking stack for aria2-rust: HTTP/HTTPS client, FTP/SFTP, full BitTorrent (DHT/PEX/MSE), and Metalink V3/V4 parser
Documentation
//! Encoding and decoding helpers for Content-Disposition filename values.
//!
//! Handles UTF-8 validation, ISO-8859-1 to UTF-8 conversion, directory-traversal
//! detection, and the final decoding of raw filename bytes into `String`s.

use tracing::trace;

// ---------------------------------------------------------------------------
// Charset enum for filename* values
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Charset {
    Unknown,
    Utf8,
    Iso8859p1,
}

// ---------------------------------------------------------------------------
// UTF-8 validation helper
// ---------------------------------------------------------------------------

/// Validate a byte sequence as UTF-8, returning the decoded String or None.
/// This replaces the C++ DFA-based `utf8dfa` validation.
#[inline]
pub(super) fn validate_utf8(bytes: &[u8]) -> Option<String> {
    std::str::from_utf8(bytes).ok().map(|s| s.to_owned())
}

// ---------------------------------------------------------------------------
// ISO-8859-1 to UTF-8 conversion
// ---------------------------------------------------------------------------

/// Convert ISO-8859-1 bytes to a UTF-8 String.
/// Returns `None` if the input contains bytes in the 0x80..0x9F range
/// (C1 control characters not valid in ISO-8859-1 per the C++ implementation).
pub(super) fn iso8859p1_to_utf8(src: &[u8]) -> Option<String> {
    let mut out = String::with_capacity(src.len() * 2);
    for &c in src {
        if c >= 0xa0 {
            // ISO-8859-1 bytes 0xA0..0xFF map 1:1 to Unicode codepoints U+00A0..U+00FF.
            // Rust String::push handles the UTF-8 encoding automatically.
            out.push(c as char);
        } else if (0x80..=0x9f).contains(&c) {
            // C1 control characters — invalid in ISO-8859-1 per C++ impl
            return None;
        } else {
            out.push(c as char);
        }
    }
    Some(out)
}

// ---------------------------------------------------------------------------
// Directory-traversal detection (matching C++ `detectDirTraversal`)
// ---------------------------------------------------------------------------

/// Check whether a filename contains directory-traversal components or
/// path separators, making it unsafe for use as a download filename.
pub(super) fn is_dir_traversal(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    // Reject control characters
    for c in s.bytes() {
        if c <= 0x1f || c == 0x7f {
            return true;
        }
    }
    // Reject path separators and traversal patterns
    s == "."
        || s == ".."
        || s.starts_with('/')
        || s.starts_with("./")
        || s.starts_with("../")
        || s.contains("/../")
        || s.contains("/./")
        || s.ends_with('/')
        || s.ends_with("/.")
        || s.ends_with("/..")
        // Also reject backslash (Windows path separator)
        || s.contains('\\')
}

// ---------------------------------------------------------------------------
// Decoding helpers
// ---------------------------------------------------------------------------

/// Decode the `filename=` parameter value (plain or quoted).
///
/// A plain filename has no charset marker. Callers can opt into UTF-8 for
/// modern servers, or retain the historical ISO-8859-1 interpretation used
/// by aria2 by passing `false`.
pub(super) fn decode_filename_ascii(bytes: &[u8], default_utf8: bool) -> Option<String> {
    if bytes.is_empty() {
        return None;
    }

    let decoded = if default_utf8 {
        validate_utf8(bytes)
    } else {
        iso8859p1_to_utf8(bytes)
    }?;

    if is_dir_traversal(&decoded) {
        trace!(filename = %decoded, "decode_filename_ascii: rejected due to directory traversal");
        None
    } else {
        Some(decoded)
    }
}

/// Decode the `filename*=` parameter value with charset awareness.
/// The bytes have already been percent-decoded by the state machine.
/// Rejects directory-traversal filenames.
pub(super) fn decode_filename_ext(bytes: &[u8], charset: Charset) -> Option<String> {
    if bytes.is_empty() {
        return None;
    }

    let decoded = match charset {
        Charset::Utf8 => validate_utf8(bytes)?,
        Charset::Iso8859p1 => iso8859p1_to_utf8(bytes)?,
        Charset::Unknown => {
            // For unknown charsets, try UTF-8 first, then ISO-8859-1
            validate_utf8(bytes).or_else(|| iso8859p1_to_utf8(bytes))?
        }
    };

    if is_dir_traversal(&decoded) {
        trace!(filename = %decoded, "decode_filename_ext: rejected due to directory traversal");
        return None;
    }

    Some(decoded)
}