use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use lopdf::{Dictionary, Document, Object, ObjectId};
use serde_derive::Serialize;
use crate::{PdfConformance, PdfDocument, PdfParseErrorSeverity, PdfSaveOptions};
mod colour;
mod content;
mod file;
mod structure;
mod util;
pub(crate) mod xmp;
#[cfg(test)]
mod tests;
pub(crate) const MAX_PAGES: usize = 100_000;
pub(crate) const MAX_TREE_DEPTH: usize = 64;
pub(crate) const MAX_NESTING: usize = 12;
pub(crate) const MAX_OBJECTS: usize = 2_000_000;
pub(crate) const MAX_FINDINGS: usize = 1_000;
pub(crate) const MAX_CONTENT_BYTES: usize = 128 * 1024 * 1024;
pub(crate) const MAX_VALIDATION_BYTES: usize = 128 * 1024 * 1024;
pub(crate) const MAX_STREAM_BYTES: usize = 64 * 1024 * 1024;
pub(crate) const MAX_OPERATORS: usize = 20_000_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Info,
Warning,
Error,
}
impl Severity {
pub fn as_str(self) -> &'static str {
match self {
Severity::Info => "info",
Severity::Warning => "warning",
Severity::Error => "error",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[allow(non_camel_case_types)]
pub enum PreflightProfile {
#[serde(rename = "general")]
General,
#[serde(rename = "pdfa-1b")]
PdfA1b,
#[serde(rename = "pdfa-2b")]
PdfA2b,
#[serde(rename = "pdfx-1a")]
PdfX1a_2001,
#[serde(rename = "pdfx-3")]
PdfX3_2002,
}
impl PreflightProfile {
pub const ALL: [PreflightProfile; 5] = [
PreflightProfile::General,
PreflightProfile::PdfA1b,
PreflightProfile::PdfA2b,
PreflightProfile::PdfX1a_2001,
PreflightProfile::PdfX3_2002,
];
pub fn name(self) -> &'static str {
match self {
PreflightProfile::General => "general",
PreflightProfile::PdfA1b => "pdfa-1b",
PreflightProfile::PdfA2b => "pdfa-2b",
PreflightProfile::PdfX1a_2001 => "pdfx-1a",
PreflightProfile::PdfX3_2002 => "pdfx-3",
}
}
pub fn label(self) -> &'static str {
match self {
PreflightProfile::General => "General",
PreflightProfile::PdfA1b => "PDF/A-1b",
PreflightProfile::PdfA2b => "PDF/A-2b",
PreflightProfile::PdfX1a_2001 => "PDF/X-1a:2001",
PreflightProfile::PdfX3_2002 => "PDF/X-3:2002",
}
}
pub fn from_name(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|p| p.name() == name)
}
pub fn for_conformance(c: &PdfConformance) -> Option<Self> {
match c {
PdfConformance::A1B_2005_PDF_1_4 | PdfConformance::A1A_2005_PDF_1_4 => {
Some(PreflightProfile::PdfA1b)
}
PdfConformance::A2_2011_PDF_1_7
| PdfConformance::A2A_2011_PDF_1_7
| PdfConformance::A2B_2011_PDF_1_7
| PdfConformance::A2U_2011_PDF_1_7 => Some(PreflightProfile::PdfA2b),
PdfConformance::X1A_2001_PDF_1_3 => Some(PreflightProfile::PdfX1a_2001),
PdfConformance::X3_2002_PDF_1_3 => Some(PreflightProfile::PdfX3_2002),
_ => None,
}
}
fn conformance(self) -> PdfConformance {
match self {
PreflightProfile::General => PdfConformance::default(),
PreflightProfile::PdfA1b => PdfConformance::A1B_2005_PDF_1_4,
PreflightProfile::PdfA2b => PdfConformance::A2B_2011_PDF_1_7,
PreflightProfile::PdfX1a_2001 => PdfConformance::X1A_2001_PDF_1_3,
PreflightProfile::PdfX3_2002 => PdfConformance::X3_2002_PDF_1_3,
}
}
pub(crate) fn is_pdfa(self) -> bool {
matches!(self, PreflightProfile::PdfA1b | PreflightProfile::PdfA2b)
}
pub(crate) fn is_pdfx(self) -> bool {
matches!(
self,
PreflightProfile::PdfX1a_2001 | PreflightProfile::PdfX3_2002
)
}
pub(crate) fn is_standard(self) -> bool {
self != PreflightProfile::General
}
pub(crate) fn forbids_transparency(self) -> bool {
matches!(
self,
PreflightProfile::PdfA1b | PreflightProfile::PdfX1a_2001 | PreflightProfile::PdfX3_2002
)
}
pub(crate) fn forbids_layers(self) -> bool {
self.forbids_transparency()
}
pub(crate) fn forbids_compressed_structure(self) -> bool {
self.forbids_transparency()
}
pub(crate) fn base_version(self) -> Option<(u32, u32)> {
match self {
PreflightProfile::General => None,
PreflightProfile::PdfA1b => Some((1, 4)),
PreflightProfile::PdfA2b => Some((1, 7)),
PreflightProfile::PdfX1a_2001 | PreflightProfile::PdfX3_2002 => Some((1, 3)),
}
}
pub(crate) fn allows_3d(self) -> bool {
self.conformance().is_3d_content_allowed()
}
pub(crate) fn allows_video(self) -> bool {
self.conformance().is_video_content_allowed()
}
pub(crate) fn allows_audio(self) -> bool {
self.conformance().is_audio_content_allowed()
}
pub(crate) fn allows_javascript(self) -> bool {
self.conformance().is_javascript_content_allowed()
}
pub(crate) fn pdfx_identifier(self) -> Option<&'static str> {
match self {
PreflightProfile::PdfX1a_2001 => Some("PDF/X-1a:2001"),
PreflightProfile::PdfX3_2002 => Some("PDF/X-3:2002"),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Finding {
pub severity: Severity,
pub rule: &'static str,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub page: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub object: Option<(u32, u16)>,
#[serde(skip_serializing_if = "Option::is_none")]
pub standard_reference: Option<&'static str>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PreflightSummary {
pub errors: usize,
pub warnings: usize,
pub infos: usize,
pub suppressed: usize,
pub pages_checked: usize,
pub objects_visited: usize,
pub limits_reached: Vec<&'static str>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PreflightReport {
pub profile: PreflightProfile,
pub findings: Vec<Finding>,
pub summary: PreflightSummary,
pub not_checked: Vec<&'static str>,
}
impl PreflightReport {
pub fn has_errors(&self) -> bool {
self.summary.errors > 0
}
pub fn findings_for_rule<'a>(&'a self, rule: &'a str) -> impl Iterator<Item = &'a Finding> {
self.findings.iter().filter(move |f| f.rule == rule)
}
fn add_finding(&mut self, f: Finding) {
if self.findings.len() >= MAX_FINDINGS {
self.summary.suppressed = self.summary.suppressed.saturating_add(1);
return;
}
match f.severity {
Severity::Error => self.summary.errors = self.summary.errors.saturating_add(1),
Severity::Warning => self.summary.warnings = self.summary.warnings.saturating_add(1),
Severity::Info => self.summary.infos = self.summary.infos.saturating_add(1),
}
self.findings.push(f);
}
}
pub const NOT_CHECKED: &[&str] = &[
"glyph coverage, widths and the validity of font programs beyond their first bytes",
"the content of ICC profiles beyond the header, and whether a profile fits the output condition",
"image data, image resolution and the consistency of image dictionaries beyond the colour space",
"consistency between the Info dictionary and the XMP metadata",
"XMP metadata schemas beyond the PDF/A identification, and extension schemas",
"logical structure and tagged PDF (PDF/A level A, PDF/UA)",
"annotation flags, annotation appearance streams and form fields",
"the content streams of Type 3 character procedures",
"implementation limits of the standards (nesting depth, string and array sizes)",
"overprint, halftone, transfer function and rendering intent rules",
"trapping, OPI and printer marks",
"digital signatures and the contents of embedded files",
"anything that depends on rendering the page",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RuleInfo {
pub id: &'static str,
pub description: &'static str,
}
macro_rules! rules {
($($id:literal => $description:literal,)*) => {
&[$(RuleInfo { id: $id, description: $description }),*]
};
}
pub const RULES: &[RuleInfo] = rules! {
"file-unreadable" => "the file could not be loaded",
"header-missing" => "no %PDF- header in the first 1024 bytes",
"header-not-at-start" => "bytes before the %PDF- header",
"header-version-invalid" => "the header version is not 1.0 to 1.7 or 2.0",
"header-binary-comment-missing" => "no comment of four bytes above 127 after the header",
"pdf-version-too-new" => "the header version is newer than the standard allows",
"eof-marker-missing" => "no %%EOF marker at the end",
"data-after-eof" => "data after the last %%EOF marker",
"startxref-missing" => "no startxref keyword at the end",
"xref-reconstructed" => "the cross-reference table was unreadable and was rebuilt by scanning",
"xref-offset-corrected" => "a startxref or /Prev offset did not point at a cross-reference section",
"xref-entry-bad-offset" => "a cross-reference entry does not point at its object",
"trailer-root-missing" => "the trailer has no usable /Root",
"catalog-type-wrong" => "the catalog has no /Type /Catalog",
"trailer-size-wrong" => "the trailer /Size is smaller than the highest object number",
"trailer-id-missing" => "the trailer has no /ID",
"encrypted" => "the file is encrypted",
"object-stream-forbidden" => "object streams in a standard based on PDF 1.4 or older",
"xref-stream-forbidden" => "a cross-reference stream in a standard based on PDF 1.4 or older",
"dangling-reference" => "a reference to an object that does not exist",
"stream-length-missing" => "a stream without /Length",
"stream-length-mismatch" => "/Length differs from the bytes between stream and endstream",
"stream-filter-unknown" => "a /Filter name that PDF does not define",
"stream-decode-failed" => "a stream whose filters fail to decode",
"stream-external-file" => "a stream whose data is in an external file",
"lzw-filter" => "LZWDecode, which PDF/A does not allow",
"filter-not-in-base-version" => "JPXDecode, JBIG2Decode or BrotliDecode where the base version of the standard has none",
"pages-tree-missing" => "the catalog has no usable /Pages",
"page-tree-cycle" => "the page tree contains itself",
"page-tree-node-invalid" => "a page tree node is not a dictionary or does not exist",
"page-count-mismatch" => "/Count of the root differs from the number of pages",
"no-pages" => "the document has no pages",
"mediabox-missing" => "a page has no /MediaBox, own or inherited",
"mediabox-invalid" => "a /MediaBox that is not four numbers or has no area",
"page-box-invalid" => "a CropBox, BleedBox, TrimBox or ArtBox that is not four numbers",
"page-size-huge" => "a page larger than 14400 units, the limit of Acrobat",
"page-size-tiny" => "a page smaller than 3 units, the limit of Acrobat",
"page-box-outside-mediabox" => "a page box that is not inside the MediaBox",
"page-rotate-invalid" => "/Rotate that is not a multiple of 90",
"trimbox-missing" => "PDF/X page with neither TrimBox nor ArtBox",
"trimbox-and-artbox" => "PDF/X page with both TrimBox and ArtBox",
"contents-invalid" => "/Contents is not a stream or an array of streams",
"content-stream-unreadable" => "a content stream that cannot be decoded or parsed",
"resource-not-found" => "a content stream uses a resource name that the resources do not have",
"resource-dangling" => "a resource entry refers to an object that does not exist",
"resources-malformed" => "a resource category that is not a dictionary",
"graphics-state-unbalanced" => "q and Q do not match in a content stream",
"text-object-unbalanced" => "BT and ET do not match in a content stream",
"text-outside-text-object" => "a text-showing operator outside BT ... ET",
"form-bbox-missing" => "a form XObject without /BBox",
"xobject-subtype-invalid" => "an XObject that is not an image, form or PostScript object",
"postscript-xobject" => "a PostScript XObject",
"image-dict-incomplete" => "an image without /Width, /Height or /BitsPerComponent",
"image-no-colour-space" => "an image that is not a mask and has no /ColorSpace",
"colour-space-malformed" => "a colour space array or dictionary of the wrong shape",
"colour-space-unknown" => "a colour space name or family that PDF does not define",
"icc-profile-invalid" => "an ICC profile stream with a bad /N or without the ICC signature",
"device-colour-without-output-intent" => "device colour without a matching output intent or default colour space (PDF/A)",
"rgb-colour-in-pdfx1a" => "DeviceRGB in PDF/X-1a",
"colour-space-not-allowed" => "calibrated, Lab or ICC-based colour in PDF/X-1a",
"font-not-embedded" => "a used font whose program is not in the file",
"font-descriptor-missing" => "a font that is not one of the 14 standard fonts and has no /FontDescriptor",
"font-program-invalid" => "a font file that is missing, empty or has a wrong signature",
"font-subtype-invalid" => "a font dictionary without a known /Subtype",
"font-no-tounicode" => "a font whose text cannot be mapped to Unicode",
"transparency-smask" => "a soft mask",
"transparency-alpha" => "a constant opacity below 1",
"transparency-blend-mode" => "a blend mode other than Normal",
"transparency-group" => "a transparency group",
"optional-content" => "optional content (layers)",
"info-title-missing" => "PDF/X without /Title in the Info dictionary",
"info-date-missing" => "PDF/X without /CreationDate or /ModDate",
"trapped-missing" => "PDF/X without /Trapped True or False",
"pdfx-version-missing" => "PDF/X without /GTS_PDFXVersion",
"pdfx-version-mismatch" => "/GTS_PDFXVersion names another standard",
"output-intent-missing" => "PDF/X without an output intent",
"output-intent-invalid" => "an output intent that is not a dictionary or lacks required keys",
"output-intent-subtype" => "a PDF/A output intent whose /S is not GTS_PDFA1",
"output-intent-profile-missing" => "an output intent without /DestOutputProfile",
"xmp-missing" => "PDF/A without XMP metadata in the catalog",
"xmp-stream-invalid" => "/Metadata is not a stream of /Subtype /XML",
"xmp-not-well-formed" => "the XMP metadata is not well-formed XML",
"pdfa-id-missing" => "no pdfaid:part in the XMP metadata",
"pdfa-id-mismatch" => "pdfaid:part or pdfaid:conformance does not fit the profile",
"javascript" => "a JavaScript action",
"launch-action" => "a Launch action",
"named-action-not-allowed" => "a named action other than NextPage, PrevPage, FirstPage and LastPage",
"remote-goto-action" => "a go-to action that opens another file",
"uri-javascript" => "a URI action with the javascript: scheme",
"embedded-file" => "an embedded file",
"3d-content" => "a 3D annotation",
"video-content" => "a movie annotation or action",
"audio-content" => "a sound annotation or action",
"multimedia-content" => "a screen, rich media or rendition object",
"check-limit-reached" => "a bound on the work was reached; the report is incomplete",
"content-not-checked" => "a part of the file was not checked",
"writer-warning" => "a warning that printpdf raised while saving the document",
};
pub fn preflight_bytes(bytes: &[u8], profile: PreflightProfile) -> PreflightReport {
let mut sink = Sink::new(profile);
file::check_header_and_tail(&mut sink, bytes);
match Document::load_mem(bytes) {
Err(e) => {
if matches!(e, lopdf::Error::InvalidPassword) {
let sev = sink
.forbidden(Some(Severity::Info))
.unwrap_or(Severity::Info);
sink.push(
sev,
"encrypted",
Loc::default(),
"the file is encrypted and needs a password".to_string(),
);
}
sink.error(
"file-unreadable",
Loc::default(),
format!("the file could not be loaded: {e}"),
);
}
Ok(doc) => {
let mut run = Run::new(&doc, sink);
structure::check_document(&mut run, bytes);
sink = run.sink;
}
}
sink.into_report()
}
impl PdfDocument {
pub fn preflight(&self, profile: PreflightProfile) -> PreflightReport {
self.preflight_with_options(profile, &PdfSaveOptions::default())
}
pub fn preflight_with_options(
&self,
profile: PreflightProfile,
opts: &PdfSaveOptions,
) -> PreflightReport {
let mut warnings = Vec::new();
let bytes = self.save(opts, &mut warnings);
let mut report = preflight_bytes(&bytes, profile);
for w in warnings {
let severity = match w.severity {
PdfParseErrorSeverity::Error => Severity::Error,
PdfParseErrorSeverity::Warning => Severity::Warning,
PdfParseErrorSeverity::Info => continue,
};
report.add_finding(Finding {
severity,
rule: "writer-warning",
message: w.msg,
page: None,
object: None,
standard_reference: None,
});
}
report
}
}
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct Loc {
pub page: Option<usize>,
pub obj: Option<ObjectId>,
}
impl Loc {
pub fn obj(id: ObjectId) -> Loc {
Loc {
page: None,
obj: Some(id),
}
}
pub fn at(page: Option<usize>, obj: Option<ObjectId>) -> Loc {
Loc { page, obj }
}
}
struct Aggregate {
finding: Finding,
more: usize,
}
pub(crate) struct Sink {
pub profile: PreflightProfile,
findings: Vec<Finding>,
suppressed: usize,
aggregates: BTreeMap<(&'static str, String), Aggregate>,
limits: BTreeSet<&'static str>,
pages: usize,
objects: usize,
}
impl Sink {
fn new(profile: PreflightProfile) -> Sink {
Sink {
profile,
findings: Vec::new(),
suppressed: 0,
aggregates: BTreeMap::new(),
limits: BTreeSet::new(),
pages: 0,
objects: 0,
}
}
pub fn forbidden(&self, general: Option<Severity>) -> Option<Severity> {
if self.profile.is_standard() {
Some(Severity::Error)
} else {
general
}
}
pub fn push(&mut self, severity: Severity, rule: &'static str, loc: Loc, message: String) {
if self.findings.len() >= MAX_FINDINGS {
self.suppressed = self.suppressed.saturating_add(1);
return;
}
self.findings.push(Finding {
severity,
rule,
message,
page: loc.page,
object: loc.obj,
standard_reference: standard_reference(self.profile, rule),
});
}
pub fn error(&mut self, rule: &'static str, loc: Loc, message: String) {
self.push(Severity::Error, rule, loc, message);
}
pub fn warn(&mut self, rule: &'static str, loc: Loc, message: String) {
self.push(Severity::Warning, rule, loc, message);
}
pub fn info(&mut self, rule: &'static str, loc: Loc, message: String) {
self.push(Severity::Info, rule, loc, message);
}
pub fn once(
&mut self,
severity: Severity,
rule: &'static str,
key: String,
loc: Loc,
message: String,
) {
let profile = self.profile;
self.aggregates
.entry((rule, key))
.and_modify(|a| a.more = a.more.saturating_add(1))
.or_insert_with(|| Aggregate {
finding: Finding {
severity,
rule,
message,
page: loc.page,
object: loc.obj,
standard_reference: standard_reference(profile, rule),
},
more: 0,
});
}
pub fn limit(&mut self, what: &'static str) {
self.limits.insert(what);
}
fn into_report(mut self) -> PreflightReport {
for (_, mut a) in std::mem::take(&mut self.aggregates) {
if a.more > 0 {
a.finding.message = format!(
"{} ({} more of the same kind elsewhere)",
a.finding.message, a.more
);
}
if self.findings.len() >= MAX_FINDINGS {
self.suppressed = self.suppressed.saturating_add(1);
} else {
self.findings.push(a.finding);
}
}
for what in &self.limits {
self.findings.push(Finding {
severity: Severity::Info,
rule: "check-limit-reached",
message: format!("{what}; the report may be incomplete"),
page: None,
object: None,
standard_reference: None,
});
}
let mut summary = PreflightSummary {
suppressed: self.suppressed,
pages_checked: self.pages,
objects_visited: self.objects,
limits_reached: self.limits.iter().copied().collect(),
..PreflightSummary::default()
};
for f in &self.findings {
match f.severity {
Severity::Error => summary.errors = summary.errors.saturating_add(1),
Severity::Warning => summary.warnings = summary.warnings.saturating_add(1),
Severity::Info => summary.infos = summary.infos.saturating_add(1),
}
}
PreflightReport {
profile: self.profile,
findings: self.findings,
summary,
not_checked: NOT_CHECKED.to_vec(),
}
}
}
fn standard_reference(profile: PreflightProfile, rule: &str) -> Option<&'static str> {
if profile != PreflightProfile::PdfA1b {
return None;
}
let clause = match rule {
"header-not-at-start" | "header-binary-comment-missing" => "ISO 19005-1 6.1.2",
"encrypted" | "trailer-id-missing" | "eof-marker-missing" | "data-after-eof" => {
"ISO 19005-1 6.1.3"
}
"stream-length-missing" | "stream-length-mismatch" | "stream-external-file" => {
"ISO 19005-1 6.1.7"
}
"lzw-filter" => "ISO 19005-1 6.1.10",
"embedded-file" => "ISO 19005-1 6.1.11",
"optional-content" => "ISO 19005-1 6.1.13",
"output-intent-subtype" | "output-intent-profile-missing" => "ISO 19005-1 6.2.2",
"device-colour-without-output-intent" => "ISO 19005-1 6.2.3",
"font-not-embedded" => "ISO 19005-1 6.3.4",
"transparency-smask"
| "transparency-alpha"
| "transparency-blend-mode"
| "transparency-group" => "ISO 19005-1 6.4",
"javascript"
| "launch-action"
| "named-action-not-allowed"
| "video-content"
| "audio-content" => "ISO 19005-1 6.6.1",
"xmp-missing" => "ISO 19005-1 6.7.2",
"pdfa-id-missing" | "pdfa-id-mismatch" => "ISO 19005-1 6.7.11",
_ => return None,
};
Some(clause)
}
pub(crate) struct Run<'a> {
pub doc: &'a Document,
pub sink: Sink,
pub content_left: usize,
pub validation_left: usize,
pub operators_left: usize,
pub objects_left: usize,
pub has_output_intent: bool,
pub intent_components: Vec<i64>,
pub default_spaces: [bool; 3],
pub seen: HashSet<(Seen, ObjectId)>,
pub seen_dicts: HashSet<usize>,
pub decode_failed: HashSet<ObjectId>,
pub cs_cache: HashMap<ObjectId, colour::Space>,
pub device_use: [Option<Option<usize>>; 3],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum Seen {
Font,
Form,
Image,
Resources,
Profile,
}
impl<'a> Run<'a> {
fn new(doc: &'a Document, sink: Sink) -> Run<'a> {
Run {
doc,
sink,
content_left: MAX_CONTENT_BYTES,
validation_left: MAX_VALIDATION_BYTES,
operators_left: MAX_OPERATORS,
objects_left: MAX_OBJECTS,
has_output_intent: false,
intent_components: Vec::new(),
default_spaces: [false; 3],
seen: HashSet::new(),
seen_dicts: HashSet::new(),
decode_failed: HashSet::new(),
cs_cache: HashMap::new(),
device_use: [None; 3],
}
}
pub fn profile(&self) -> PreflightProfile {
self.sink.profile
}
pub fn visit(&mut self) -> bool {
if self.objects_left == 0 {
self.sink
.limit("the limit of 2,000,000 visited objects was reached");
return false;
}
self.objects_left -= 1;
self.sink.objects = self.sink.objects.saturating_add(1);
true
}
pub fn first_visit(&mut self, what: Seen, id: ObjectId) -> bool {
self.seen.insert((what, id))
}
}
pub(crate) fn dict_of(o: &Object) -> Option<&Dictionary> {
match o {
Object::Dictionary(d) => Some(d),
Object::Stream(s) => Some(&s.dict),
_ => None,
}
}