rusty_pdf_core 0.1.0

Pure-Rust PDF reader core: objects, classic and stream cross-reference tables, object streams, incremental updates, broken-xref repair, RC4 and AES-128/256 decryption, stream filters, page tree, content streams, editing and save. Hostile input errors or stays bounded. No C, no unsafe.
Documentation
//! Content streams: the operators that draw a page.

use crate::error::{Error, Result};
use crate::object::{Dictionary, Object, Stream};
use crate::parser::{find, is_whitespace, Parser};
use crate::Limits;

/// One operator with its operands, as written: `10 20 m` is operator `m`
/// with operands `[10, 20]`.
///
/// An inline image (`BI … ID … EI`) is one operation with operator `BI` and
/// a single [`Object::Stream`] operand: the image dictionary, with its keys
/// as abbreviated in the file, and the image data.
#[derive(Debug, Clone, PartialEq)]
pub struct Operation {
    /// The operator. Operators are ASCII; bytes that are not are replaced.
    pub operator: String,
    /// The operands, in order.
    pub operands: Vec<Object>,
}

impl Operation {
    /// An operation from an operator and operands.
    pub fn new(operator: &str, operands: Vec<Object>) -> Self {
        Self { operator: operator.to_owned(), operands }
    }
}

/// A parsed content stream.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Content {
    /// The operations, in drawing order.
    pub operations: Vec<Operation>,
}

/// Most operands kept for one operator. No operator takes more than a few
/// (the largest, `SCN` in a DeviceN space, takes 33); a longer run is junk
/// and its oldest operands are dropped.
const MAX_OPERANDS: usize = 256;

impl Content {
    /// Parse decoded content-stream bytes with default limits.
    pub fn parse(data: &[u8]) -> Result<Self> {
        Self::parse_with(data, &Limits::default())
    }

    /// Parse decoded content-stream bytes.
    ///
    /// Junk between operators is skipped, as viewers skip it. An inline
    /// image whose end cannot be found is an error: everything after it
    /// would be guesswork.
    pub fn parse_with(data: &[u8], limits: &Limits) -> Result<Self> {
        let mut p = Parser::for_content(data, limits.max_nesting);
        let mut operations = Vec::new();
        let mut operands: Vec<Object> = Vec::new();
        loop {
            p.skip_ws();
            if p.at_end() {
                break;
            }
            let before = p.pos;
            match p.object() {
                Ok(o) => {
                    if operands.len() >= MAX_OPERANDS {
                        operands.remove(0);
                    }
                    operands.push(o);
                }
                Err(e @ Error::Limit { .. }) => return Err(e),
                Err(_) => {
                    p.pos = before;
                    let token = p.token();
                    if token.is_empty() {
                        // A stray delimiter.
                        p.pos += 1;
                        continue;
                    }
                    if token == b"BI" {
                        let image = inline_image(&mut p)?;
                        operands.clear();
                        operations.push(Operation { operator: "BI".into(), operands: vec![Object::Stream(image)] });
                    } else {
                        operations.push(Operation {
                            operator: String::from_utf8_lossy(token).into_owned(),
                            operands: std::mem::take(&mut operands),
                        });
                    }
                }
            }
        }
        Ok(Self { operations })
    }

    /// Serialise back to content-stream bytes.
    #[must_use]
    pub fn encode(&self) -> Vec<u8> {
        let mut out = Vec::new();
        for op in &self.operations {
            if op.operator == "BI" {
                if let Some(Object::Stream(image)) = op.operands.first() {
                    out.extend_from_slice(b"BI");
                    for (key, value) in image.dict.iter() {
                        // `/Length` is ours (`Stream::new` sets it), not
                        // part of an inline image.
                        if key == b"Length" {
                            continue;
                        }
                        out.push(b' ');
                        crate::writer::write_name(&mut out, key);
                        out.push(b' ');
                        crate::writer::write_object(&mut out, value, &|_| 0);
                    }
                    out.extend_from_slice(b"\nID\n");
                    out.extend_from_slice(image.raw());
                    out.extend_from_slice(b"\nEI\n");
                    continue;
                }
            }
            for operand in &op.operands {
                crate::writer::write_object(&mut out, operand, &|_| 0);
                out.push(b' ');
            }
            out.extend_from_slice(op.operator.as_bytes());
            out.push(b'\n');
        }
        out
    }
}

/// An inline image; `BI` is already consumed.
fn inline_image(p: &mut Parser<'_>) -> Result<Stream> {
    let mut dict = Dictionary::new();
    loop {
        p.skip_ws();
        if p.at_end() {
            return Err(Error::Syntax { offset: p.pos, message: "inline image has no ID" });
        }
        if p.eat_keyword(b"ID") {
            break;
        }
        match p.object() {
            Ok(Object::Name(key)) => {
                p.skip_ws();
                let before = p.pos;
                match p.object() {
                    Ok(value) => dict.set(key, value),
                    Err(e @ Error::Limit { .. }) => return Err(e),
                    Err(_) => p.pos = before,
                }
            }
            Ok(_) => {}
            Err(e @ Error::Limit { .. }) => return Err(e),
            Err(_) => {
                if p.token().is_empty() {
                    p.pos += 1;
                }
            }
        }
    }
    // One white-space character separates `ID` from the data.
    if p.peek().is_some_and(is_whitespace) {
        p.pos += 1;
    }
    let start = p.pos.min(p.data.len());
    let end = inline_image_end(p.data, start, &dict)
        .ok_or(Error::Syntax { offset: start, message: "inline image has no EI" })?;
    p.pos = end.1;
    Ok(Stream::new(dict, p.data[start..end.0].to_vec()))
}

/// Where an inline image's data ends, and where parsing resumes after `EI`.
fn inline_image_end(data: &[u8], start: usize, dict: &Dictionary) -> Option<(usize, usize)> {
    // Unfiltered data has a length the dictionary determines; trust it when
    // `EI` is where it says.
    if let Some(len) = unfiltered_length(dict) {
        if let Some(end) = start.checked_add(len).filter(|e| *e <= data.len()) {
            let mut probe = Parser::for_content(data, 0);
            probe.pos = end;
            probe.skip_ws();
            if probe.eat_keyword(b"EI") {
                return Some((end, probe.pos));
            }
        }
    }
    // Otherwise the first `EI` that stands alone and is followed by what
    // looks like content-stream text, not more binary.
    let mut from = start;
    while let Some(at) = find(data, b"EI", from) {
        from = at + 1;
        let alone = (at == start || is_whitespace(data[at - 1]))
            && data.get(at + 2).copied().is_none_or(is_whitespace);
        if !alone {
            continue;
        }
        let tail = &data[at + 2..data.len().min(at + 2 + 16)];
        let texty = tail.iter().all(|b| is_whitespace(*b) || (0x20..0x7F).contains(b));
        if texty {
            let end = if at > start { at - 1 } else { at };
            return Some((end.max(start), at + 2));
        }
    }
    None
}

/// The data length of an inline image with no filter, if the dictionary
/// determines it.
fn unfiltered_length(dict: &Dictionary) -> Option<usize> {
    if dict.has(b"F") || dict.has(b"Filter") {
        return None;
    }
    let get = |short: &[u8], long: &[u8]| dict.get(short).or_else(|| dict.get(long));
    let int = |o: &Object| o.as_i64().ok().and_then(|v| usize::try_from(v).ok());
    let width = get(b"W", b"Width").and_then(int)?;
    let height = get(b"H", b"Height").and_then(int)?;
    let mask = get(b"IM", b"ImageMask").and_then(|o| o.as_bool().ok()).unwrap_or(false);
    let (components, bits) = if mask {
        (1, 1)
    } else {
        let bits = get(b"BPC", b"BitsPerComponent").and_then(int)?;
        let components = match get(b"CS", b"ColorSpace")?.as_name().ok()? {
            b"G" | b"DeviceGray" | b"CalGray" | b"I" | b"Indexed" => 1,
            b"RGB" | b"DeviceRGB" | b"CalRGB" => 3,
            b"CMYK" | b"DeviceCMYK" => 4,
            _ => return None,
        };
        (components, bits)
    };
    let row = width.checked_mul(components)?.checked_mul(bits)?.div_ceil(8);
    row.checked_mul(height)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ops(data: &[u8]) -> Vec<(String, usize)> {
        Content::parse(data)
            .unwrap()
            .operations
            .into_iter()
            .map(|o| (o.operator, o.operands.len()))
            .collect()
    }

    #[test]
    fn operators_and_operands() {
        let c = Content::parse(b"q 1 0 0 1 10 20 cm /Im1 Do Q BT /F1 12 Tf (Hi) Tj [(a) -20 (b)] TJ ET").unwrap();
        let names: Vec<&str> = c.operations.iter().map(|o| o.operator.as_str()).collect();
        assert_eq!(names, ["q", "cm", "Do", "Q", "BT", "Tf", "Tj", "TJ", "ET"]);
        assert_eq!(c.operations[1].operands.len(), 6);
        assert_eq!(c.operations[2].operands[0], Object::name("Im1"));
        assert_eq!(c.operations[6].operands[0], Object::string("Hi"));
        // `f*`, `'`, `"` and `T*` are single tokens.
        assert_eq!(ops(b"f* T* (a) ' 1 2 (b) \""), [("f*".into(), 0), ("T*".into(), 0), ("'".into(), 1), ("\"".into(), 3)]);
    }

    #[test]
    fn junk_is_skipped_not_fatal() {
        assert_eq!(ops(b"} ) 1 0 0 rg >"), [("rg".into(), 3)]);
        assert_eq!(ops(b""), []);
        assert_eq!(ops(b"   % only a comment"), []);
    }

    #[test]
    fn inline_images() {
        // Unfiltered: the length comes from the dictionary, so data that
        // contains ` EI ` is not cut short.
        let c = Content::parse(b"q BI /W 2 /H 2 /BPC 8 /CS /G ID \x00 EI\nEI Q").unwrap();
        assert_eq!(c.operations.len(), 3);
        let image = c.operations[1].operands[0].as_stream().unwrap();
        assert_eq!(image.raw(), b"\x00 EI");
        assert_eq!(image.dict.get_i64(b"W"), Some(2));
        // Filtered: ends at the first free-standing EI followed by text.
        let c = Content::parse(b"BI /W 9 /H 9 /F /Fl ID \x01\xFFEI\x02 EI\x80 EI Q").unwrap();
        let image = c.operations[0].operands[0].as_stream().unwrap();
        assert_eq!(image.raw(), b"\x01\xFFEI\x02 EI\x80");
        assert_eq!(c.operations[1].operator, "Q");
        assert!(Content::parse(b"BI /W 1 /H 1 /F /Fl ID \x00\x01\x02").is_err());
    }

    #[test]
    fn round_trip() {
        let src = b"q 1 0 0 1 10.5 -20 cm /Im1 Do Q BT /F1 12 Tf (a\\(b) Tj ET BI /W 1 /H 1 /BPC 8 /CS /G ID \x7f\nEI f";
        let first = Content::parse(src).unwrap();
        let second = Content::parse(&first.encode()).unwrap();
        assert_eq!(first, second);
    }
}