#[cfg(feature = "parse")]
use crate::parse::{FieldValue, Fields, Hint};
#[cfg(feature = "parse")]
use crate::record::Spot;
#[cfg(feature = "parse")]
use crate::record::{FirstRead, LayerCache, LayerPlan};
use crate::record::{Json, Kind, Miss, Walk, Walked};
#[cfg(feature = "xml")]
use crate::record::{Xml, XmlAt};
use super::closed::{self, Unread};
use super::field;
use super::walk::{Event, Malformed, RecordValues, recycle, shape};
use super::{Report, Scrub, ScrubScratch, Scrubber};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct JsonBytes(pub Vec<u8>);
#[cfg(feature = "xml")]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct XmlBytes(pub Vec<u8>);
#[cfg(feature = "parse")]
#[derive(Debug, Clone)]
pub struct LayeredBytes<'p> {
pub plan: &'p LayerPlan,
pub bytes: Vec<u8>,
}
impl Scrubber {
pub fn scrub_record<'a, R: Walk<'a>>(
&self,
record: R,
scratch: &mut ScrubScratch,
report: &mut Report,
masked: impl FnMut(R::At, Vec<u8>),
) -> Result<(), Miss> {
let mut events = Vec::new();
record.walk(|n| events.push(Event::new(n.depth, n.key, shape(n.kind), n.at)))?;
if !record.read_whole() {
return Err(Miss::Malformed);
}
self.scrub_events(&mut events, &RecordValues(record), scratch, report, masked)
.map_err(|Malformed| Miss::Malformed)
}
pub fn scrub_json_bytes(
&self,
json: &[u8],
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<Option<Vec<u8>>, Miss> {
let mut out = Vec::new();
let changed = self.splice_json(json, scratch, report, &mut out);
Ok(changed.then_some(out))
}
fn splice_json(
&self,
json: &[u8],
scratch: &mut ScrubScratch,
report: &mut Report,
out: &mut Vec<u8>,
) -> bool {
let done = self.splice_parsed_json(json, scratch, report, out);
done.unwrap_or_else(|_| self.fail_closed(Unread::Json, json, report, out))
}
#[cold]
#[inline(never)]
fn fail_closed(
&self,
unread: Unread,
bytes: &[u8],
report: &mut Report,
out: &mut Vec<u8>,
) -> bool {
self.own(report);
let mut masked = Vec::new();
let n = closed::mask(unread, bytes, self.pair_token.as_bytes(), &mut masked);
report.add_n(self.compiled().rules.len(), super::Kind::Malformed, n);
if self.redactor.observes() {
return false;
}
report.set_changed();
*out = masked;
true
}
fn splice_parsed_json(
&self,
json: &[u8],
scratch: &mut ScrubScratch,
report: &mut Report,
out: &mut Vec<u8>,
) -> Result<bool, Miss> {
let record = Json::new(json);
let mut edits: Vec<(&str, Vec<u8>)> = Vec::new();
let mut events: Vec<Event<'_, &str>> = recycle(std::mem::take(&mut scratch.events));
let mut opened = std::mem::take(&mut scratch.stack);
opened.clear();
let walked = record.walk_once_in(&mut scratch.json, |step| match step {
Walked::Value(n) => {
if let Kind::List | Kind::Map = n.kind {
opened.push(events.len());
}
events.push(Event::new(n.depth, n.key, shape(n.kind), n.at));
}
Walked::Closed(at) => {
if let Some(i) = opened.pop() {
events[i].set_pos(at);
}
}
});
scratch.stack = opened;
scratch
.spellings
.set_plain(self.tokens_plain && field::is_plain(json));
let scrubbed = walked.and_then(|()| {
self.scrub_events(
&mut events,
&RecordValues(record),
scratch,
report,
|at, out| {
edits.push((at, out));
},
)
.map_err(|Malformed| Miss::Malformed)
});
scratch.spellings.set_plain(false);
scratch.events = recycle(events);
scrubbed?;
if edits.is_empty() {
return Ok(false);
}
out.clear();
out.reserve(json.len() + 32 * edits.len());
record.splice_strings(&edits, out)?;
Ok(true)
}
#[cfg(feature = "xml")]
pub fn scrub_xml_bytes(
&self,
xml: &[u8],
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<Option<Vec<u8>>, Miss> {
let mut out = Vec::new();
let changed = self.splice_xml(xml, scratch, report, &mut out);
Ok(changed.then_some(out))
}
#[cfg(feature = "xml")]
fn splice_xml(
&self,
xml: &[u8],
scratch: &mut ScrubScratch,
report: &mut Report,
out: &mut Vec<u8>,
) -> bool {
let done = self.splice_read_xml(xml, scratch, report, out);
done.unwrap_or_else(|_| self.fail_closed(Unread::Xml, xml, report, out))
}
#[cfg(feature = "xml")]
fn splice_read_xml(
&self,
xml: &[u8],
scratch: &mut ScrubScratch,
report: &mut Report,
out: &mut Vec<u8>,
) -> Result<bool, Miss> {
let record = Xml::new(xml);
let mut edits: Vec<(XmlAt, Vec<u8>)> = Vec::new();
self.scrub_record(record, scratch, report, |at, out| edits.push((at, out)))?;
if edits.is_empty() {
return Ok(false);
}
out.clear();
out.reserve(xml.len() + 32 * edits.len());
record.splice_text(&edits, out)?;
Ok(true)
}
#[cfg(feature = "parse")]
pub fn scrub_layered_bytes(
&self,
plan: &LayerPlan,
record: &[u8],
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<Option<Vec<u8>>, Miss> {
let mut out = Vec::new();
let changed = self.splice_layered(plan, record, scratch, report, &mut out);
Ok(changed.then_some(out))
}
#[cfg(feature = "parse")]
fn splice_layered(
&self,
plan: &LayerPlan,
record: &[u8],
scratch: &mut ScrubScratch,
report: &mut Report,
out: &mut Vec<u8>,
) -> bool {
let cache = LayerCache::new();
let done = self.splice_read_layered(plan, record, &cache, scratch, report, out);
done.unwrap_or_else(|_| {
let unread = match cache.first_read() {
Some(FirstRead::Json) => Unread::Json,
#[cfg(feature = "xml")]
Some(FirstRead::Xml) => Unread::Xml,
Some(FirstRead::Fields) | None => Unread::Whole,
};
self.fail_closed(unread, record, report, out)
})
}
#[cfg(feature = "parse")]
fn splice_read_layered<'c>(
&self,
plan: &'c LayerPlan,
record: &'c [u8],
cache: &'c LayerCache<'c>,
scratch: &mut ScrubScratch,
report: &mut Report,
out: &mut Vec<u8>,
) -> Result<bool, Miss> {
let layered = plan.open(record, cache)?;
let mut edits: Vec<(_, Vec<u8>)> = Vec::new();
self.scrub_record(layered, scratch, report, |at, out| edits.push((at, out)))?;
if edits.is_empty() {
return Ok(false);
}
out.clear();
out.reserve(record.len() + 32 * edits.len());
if layered.splice(&edits, out).is_ok() {
return Ok(true);
}
let mut alone = Vec::new();
for i in 0..edits.len() {
alone.clear();
if layered.splice(&edits[i..=i], &mut alone).is_err() {
edits[i].1.retain(|b| !matches!(b, b'[' | b']'));
}
}
out.clear();
layered.splice(&edits, out)?;
Ok(true)
}
#[cfg(feature = "parse")]
pub fn scrub_fields(
&self,
fields: &mut Fields<'_>,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<bool, Miss> {
let written = self.field_spots(fields, scratch, report).and_then(|spots| {
if spots.is_empty() {
return Ok(false);
}
crate::record::write_strings(fields, spots)?;
Ok(true)
});
Ok(written.unwrap_or_else(|_| self.fields_closed(fields, report)))
}
#[cfg(feature = "parse")]
fn fields_closed(&self, fields: &mut Fields<'_>, report: &mut Report) -> bool {
self.own(report);
let n = fields.len().max(1);
report.add_n(self.compiled().rules.len(), super::Kind::Malformed, n);
if self.redactor.observes() {
return false;
}
for (_, value) in fields.as_mut_slice() {
*value = FieldValue::owned(self.pair_token.as_bytes().to_vec(), Hint::Text);
}
report.set_changed();
true
}
#[cfg(feature = "parse")]
fn field_spots(
&self,
fields: &Fields<'_>,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<Vec<(Spot, Vec<u8>)>, Miss> {
let mut edits = Vec::new();
self.scrub_record(fields, scratch, report, |at, out| edits.push((at, out)))?;
edits
.into_iter()
.map(|(at, out)| crate::record::spot(fields, at).map(|s| (s, out)))
.collect()
}
}
fn rewrite(
bytes: &mut Vec<u8>,
scratch: &mut ScrubScratch,
splice: impl FnOnce(&[u8], &mut ScrubScratch, &mut Vec<u8>) -> bool,
) -> bool {
let mut out = std::mem::take(&mut scratch.spliced);
let changed = splice(bytes, scratch, &mut out);
if changed {
bytes.clear();
bytes.extend_from_slice(&out);
}
scratch.spliced = out;
changed
}
impl Scrub for JsonBytes {
type Error = Miss;
fn scrub_in_place(
&mut self,
scrubber: &Scrubber,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<bool, Miss> {
Ok(rewrite(&mut self.0, scratch, |json, scratch, out| {
scrubber.splice_json(json, scratch, report, out)
}))
}
fn scrubbed(
&self,
scrubber: &Scrubber,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<Option<Self>, Miss> {
Ok(scrubber
.scrub_json_bytes(&self.0, scratch, report)?
.map(Self))
}
}
#[cfg(feature = "xml")]
impl Scrub for XmlBytes {
type Error = Miss;
fn scrub_in_place(
&mut self,
scrubber: &Scrubber,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<bool, Miss> {
Ok(rewrite(&mut self.0, scratch, |xml, scratch, out| {
scrubber.splice_xml(xml, scratch, report, out)
}))
}
fn scrubbed(
&self,
scrubber: &Scrubber,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<Option<Self>, Miss> {
Ok(scrubber
.scrub_xml_bytes(&self.0, scratch, report)?
.map(Self))
}
}
#[cfg(feature = "parse")]
impl Scrub for LayeredBytes<'_> {
type Error = Miss;
fn scrub_in_place(
&mut self,
scrubber: &Scrubber,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<bool, Miss> {
let plan = self.plan;
Ok(rewrite(&mut self.bytes, scratch, |record, scratch, out| {
scrubber.splice_layered(plan, record, scratch, report, out)
}))
}
fn scrubbed(
&self,
scrubber: &Scrubber,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<Option<Self>, Miss> {
let out = scrubber.scrub_layered_bytes(self.plan, &self.bytes, scratch, report)?;
Ok(out.map(|bytes| Self {
plan: self.plan,
bytes,
}))
}
}
#[cfg(feature = "parse")]
impl Scrub for Fields<'_> {
type Error = Miss;
fn scrub_in_place(
&mut self,
scrubber: &Scrubber,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<bool, Miss> {
scrubber.scrub_fields(self, scratch, report)
}
fn scrubbed(
&self,
scrubber: &Scrubber,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<Option<Self>, Miss> {
if let Ok(spots) = scrubber.field_spots(self, scratch, report) {
if spots.is_empty() {
return Ok(None);
}
let mut copy = self.clone();
if crate::record::write_strings(&mut copy, spots).is_ok() {
return Ok(Some(copy));
}
}
let mut copy = self.clone();
Ok(scrubber.fields_closed(&mut copy, report).then_some(copy))
}
}