content_scan/extraction_context.rs
1use varmap::VarMap;
2
3use crate::{ContentType, Context, FindingMetadata};
4
5/// Region of a parent [`Content`](crate::Content) that a
6/// [`ContentExtractor`](crate::ContentExtractor) should look at, plus
7/// optional analyzer-supplied parameters.
8///
9/// Passed to
10/// [`ContentExtractor::create_session`](crate::ContentExtractor::create_session).
11/// Copy the fields you need into the [`ExtractionSession`](crate::ExtractionSession);
12/// the context is only valid for that call.
13///
14/// When the scanner invokes an extractor because the parent was
15/// identified as that extractor's type, the context covers the whole
16/// object: `offset = 0`, `length = Some(content.size())`,
17/// `params = None`. When an analyzer queued the pass with
18/// [`Context::request_extract`], the fields come from that request.
19pub struct ExtractionContext<'a> {
20 /// First byte of the region within the parent content.
21 pub offset: u64,
22 /// Size of the region in bytes, when known.
23 ///
24 /// `Some(n)` asserts the region is `n` bytes. `None` means the
25 /// extractor determines the extent itself (parse until the format
26 /// ends, scan to EOF, …).
27 pub length: Option<u64>,
28 /// Analyzer-supplied extras (password, codec, flags, …).
29 ///
30 /// `None` when the request had no
31 /// [`.param()`](ExtractRequestBuilder::param) calls (including
32 /// type-specific extraction of the parent itself). `Some` borrows
33 /// the pooled map for the duration of `create_session` only —
34 /// copy values out if the session needs them later.
35 pub params: Option<&'a VarMap>,
36}
37
38pub(crate) struct ExtractionRequestMetadata {
39 pub(crate) start: u64,
40 pub(crate) len: Option<u64>,
41 pub(crate) params_handle: Option<varmap::PoolHandle>,
42}
43
44#[derive(Copy, Clone)]
45pub(crate) struct ExtractionRequest<T: ContentType> {
46 pub(crate) content_type: T,
47 pub(crate) start: u64,
48 pub(crate) len: Option<u64>,
49 pub(crate) params_handle: Option<varmap::PoolHandle>,
50}
51
52/// Fluent builder for an extraction request, returned by
53/// [`Context::request_extract`].
54///
55/// Borrows the [`Context`] for the duration of the chain. [`.param()`](Self::param)
56/// lazily reserves a pooled [`VarMap`] on first use, so a param-less
57/// request touches no map at all. Commit with [`emit`](Self::emit);
58/// dropping the builder without emitting files nothing and returns any
59/// reserved map to the pool.
60///
61/// ```ignore
62/// context.request_extract(MyTypes::Zip)
63/// .at(0x1000)
64/// .len(4096)
65/// .param(var!("password"), "secret")
66/// .emit();
67/// ```
68#[must_use = "an extraction request does nothing until `.emit()` is called"]
69pub struct ExtractRequestBuilder<'c, T: ContentType, M: FindingMetadata> {
70 ctx: &'c mut Context<T, M>,
71 request: ExtractionRequest<T>,
72}
73
74impl<'c, T: ContentType, M: FindingMetadata> ExtractRequestBuilder<'c, T, M> {
75 pub(crate) fn new(ctx: &'c mut Context<T, M>, content_type: T) -> Self {
76 Self {
77 ctx,
78 request: ExtractionRequest {
79 content_type,
80 start: 0,
81 len: None,
82 params_handle: None,
83 },
84 }
85 }
86 /// Sets the byte offset within the parent where extraction begins.
87 ///
88 /// Defaults to `0` (start of the parent) when not called.
89 #[inline]
90 pub fn at(mut self, start: u64) -> Self {
91 self.request.start = start;
92 self
93 }
94
95 /// Sets the length of the region in bytes.
96 ///
97 /// Omit this call to leave [`ExtractionContext::length`] as `None`,
98 /// meaning the extractor determines the extent itself. Calling
99 /// `.len(n)` asserts the analyzer knows the region is `n` bytes.
100 #[inline]
101 pub fn len(mut self, len: u64) -> Self {
102 self.request.len = Some(len);
103 self
104 }
105
106 /// Adds one extractor-specific parameter. Repeatable.
107 ///
108 /// The first call reserves a pooled [`VarMap`]; subsequent calls
109 /// write into the same map. A request with no `.param()` call
110 /// carries no map, and `create_session` sees
111 /// [`ExtractionContext::params`] as `None`.
112 ///
113 /// `V` must implement [`varmap::VarMapValue`]. Keys are typically
114 /// created with the `var!` macro re-exported from this crate.
115 #[inline]
116 pub fn param<V>(mut self, key: varmap::Key, value: V) -> Self
117 where
118 V: varmap::VarMapValue,
119 {
120 let handle = match self.request.params_handle {
121 Some(handle) => handle,
122 None => {
123 let handle = self.ctx.varmap_pool.allocate();
124 self.request.params_handle = Some(handle);
125 handle
126 }
127 };
128 if let Some(vm) = self.ctx.varmap_pool.get_mut(handle) {
129 vm.set(key, value);
130 }
131 self
132 }
133
134 /// Commits the request into the [`Context`]'s queue for the current
135 /// object. After this the builder is consumed and files nothing
136 /// further.
137 #[inline]
138 pub fn emit(mut self) {
139 self.ctx.extraction_requests_stack.push(self.request);
140 self.request.params_handle = None;
141 }
142}
143
144impl<'c, T: ContentType, M: FindingMetadata> Drop for ExtractRequestBuilder<'c, T, M> {
145 fn drop(&mut self) {
146 // If we reserved a param map but never emitted, give it back.
147 if let Some(handle) = self.request.params_handle {
148 self.ctx.varmap_pool.release(handle);
149 self.request.params_handle = None;
150 }
151 }
152}