Debian Codegraph @

src/data_format/v0.rs

raw symbols SCIP
1 //! Contains representations of data from the adblocking engine in a
2 //! forwards-and-backwards-compatible format, as well as utilities for converting these to and from
3 //! the actual `Engine` components.
4 //!
5 //! Any new fields should be added to the _end_ of both `SerializeFormat` and `DeserializeFormat`.
6
7 use std::collections::{HashMap, HashSet};
8
9 use rmp_serde as rmps;
10 use serde::{Deserialize, Serialize};
11
12 use crate::blocker::{Blocker, NetworkFilterList};
13 use crate::cosmetic_filter_cache::{CosmeticFilterCache, HostnameRuleDb};
14 use crate::filters::network::NetworkFilter;
15 use crate::utils::Hash;
16
17 use super::utils::{stabilize_hashmap_serialization, stabilize_hashset_serialization};
18 use super::{DeserializationError, SerializationError};
19
20 /// Each variant describes a single rule that is specific to a particular hostname.
21 #[derive(Clone, Debug, Deserialize, Serialize)]
22 enum LegacySpecificFilterType {
23 Hide(String),
24 Unhide(String),
25 Style(String, String),
26 UnhideStyle(String, String),
27 ScriptInject(String),
28 UnhideScriptInject(String),
29 }
30
31 #[derive(Deserialize, Serialize, Default)]
32 pub(crate) struct LegacyHostnameRuleDb {
33 #[serde(serialize_with = "crate::data_format::utils::stabilize_hashmap_serialization")]
34 db: HashMap<Hash, Vec<LegacySpecificFilterType>>,
35 }
36
37 impl From<&HostnameRuleDb> for LegacyHostnameRuleDb {
38 fn from(v: &HostnameRuleDb) -> Self {
39 let mut db = HashMap::<Hash, Vec<LegacySpecificFilterType>>::new();
40 for (hash, bin) in v.hide.0.iter() {
41 for f in bin {
42 db.entry(*hash)
43 .and_modify(|v| v.push(LegacySpecificFilterType::Hide(f.to_owned())))
44 .or_insert_with(|| vec![LegacySpecificFilterType::Hide(f.to_owned())]);
45 }
46 }
47 for (hash, bin) in v.unhide.0.iter() {
48 for f in bin {
49 db.entry(*hash)
50 .and_modify(|v| v.push(LegacySpecificFilterType::Unhide(f.to_owned())))
51 .or_insert_with(|| vec![LegacySpecificFilterType::Unhide(f.to_owned())]);
52 }
53 }
54 for (hash, bin) in v.inject_script.0.iter() {
55 for (f, _mask) in bin {
56 db.entry(*hash)
57 .and_modify(|v| v.push(LegacySpecificFilterType::ScriptInject(f.to_owned())))
58 .or_insert_with(|| vec![LegacySpecificFilterType::ScriptInject(f.to_owned())]);
59 }
60 }
61 for (hash, bin) in v.uninject_script.0.iter() {
62 for f in bin {
63 db.entry(*hash)
64 .and_modify(|v| v.push(LegacySpecificFilterType::UnhideScriptInject(f.to_owned())))
65 .or_insert_with(|| vec![LegacySpecificFilterType::UnhideScriptInject(f.to_owned())]);
66 }
67 }
68 for (hash, bin) in v.style.0.iter() {
69 for f in bin {
70 db.entry(*hash)
71 .and_modify(|v| v.push(LegacySpecificFilterType::Style(f.0.to_owned(), f.1.to_owned())))
72 .or_insert_with(|| vec![LegacySpecificFilterType::Style(f.0.to_owned(), f.1.to_owned())]);
73 }
74 }
75 for (hash, bin) in v.unstyle.0.iter() {
76 for f in bin {
77 db.entry(*hash)
78 .and_modify(|v| v.push(LegacySpecificFilterType::UnhideStyle(f.0.to_owned(), f.1.to_owned())))
79 .or_insert_with(|| vec![LegacySpecificFilterType::UnhideStyle(f.0.to_owned(), f.1.to_owned())]);
80 }
81 }
82 LegacyHostnameRuleDb {
83 db,
84 }
85 }
86 }
87
88 impl Into<HostnameRuleDb> for LegacyHostnameRuleDb {
89 fn into(self) -> HostnameRuleDb {
90 use crate::cosmetic_filter_cache::HostnameFilterBin;
91
92 let mut hide = HostnameFilterBin::default();
93 let mut unhide = HostnameFilterBin::default();
94 let mut style = HostnameFilterBin::default();
95 let mut unstyle = HostnameFilterBin::default();
96 let mut inject_script = HostnameFilterBin::default();
97 let mut uninject_script = HostnameFilterBin::default();
98
99 for (hash, bin) in self.db.into_iter() {
100 for rule in bin.into_iter() {
101 match rule {
102 LegacySpecificFilterType::Hide(s) => hide.insert(&hash, s),
103 LegacySpecificFilterType::Unhide(s) => unhide.insert(&hash, s),
104 LegacySpecificFilterType::Style(s, st) => style.insert(&hash, (s, st)),
105 LegacySpecificFilterType::UnhideStyle(s, st) => unstyle.insert(&hash, (s, st)),
106 LegacySpecificFilterType::ScriptInject(s) => inject_script.insert(&hash, (s, Default::default())),
107 LegacySpecificFilterType::UnhideScriptInject(s) => uninject_script.insert(&hash, s),
108 }
109 }
110 }
111 HostnameRuleDb {
112 hide,
113 unhide,
114 inject_script,
115 uninject_script,
116 remove: HostnameFilterBin::default(),
117 unremove: HostnameFilterBin::default(),
118 style,
119 unstyle,
120 remove_attr: HostnameFilterBin::default(),
121 unremove_attr: HostnameFilterBin::default(),
122 remove_class: HostnameFilterBin::default(),
123 unremove_class: HostnameFilterBin::default(),
124 }
125 }
126 }
127
128 #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
129 pub(crate) struct LegacyRedirectResource {
130 pub content_type: String,
131 pub data: String,
132 }
133
134 #[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
135 pub(crate) struct LegacyRedirectResourceStorage {
136 #[serde(serialize_with = "crate::data_format::utils::stabilize_hashmap_serialization")]
137 pub resources: HashMap<String, LegacyRedirectResource>,
138 }
139
140 #[derive(Clone, Deserialize, Serialize)]
141 pub(crate) struct LegacyScriptletResource {
142 scriptlet: String,
143 }
144
145 #[derive(Default, Deserialize, Serialize)]
146 pub(crate) struct LegacyScriptletResourceStorage {
147 #[serde(serialize_with = "crate::data_format::utils::stabilize_hashmap_serialization")]
148 resources: HashMap<String, LegacyScriptletResource>,
149 }
150
151 /// `_bug` is no longer used, and is removed from future format versions.
152 #[derive(Debug, Clone, Serialize)]
153 struct NetworkFilterV0SerializeFmt<'a> {
154 mask: &'a crate::filters::network::NetworkFilterMask,
155 filter: &'a crate::filters::network::FilterPart,
156 opt_domains: &'a Option<Vec<crate::utils::Hash>>,
157 opt_not_domains: &'a Option<Vec<crate::utils::Hash>>,
158 redirect: &'a Option<String>,
159 hostname: &'a Option<String>,
160 csp: &'a Option<String>,
161 _bug: Option<u32>,
162 tag: &'a Option<String>,
163 raw_line: Option<String>,
164 id: &'a crate::utils::Hash,
165 opt_domains_union: &'a Option<crate::utils::Hash>,
166 opt_not_domains_union: &'a Option<crate::utils::Hash>,
167 }
168
169 /// Generic over `Borrow<NetworkFilter>` because `tagged_filters_all` requires `&'a NetworkFilter`
170 /// while `NetworkFilterList` requires `&'a Arc<NetworkFilter>`.
171 impl<'a, T> From<&'a T> for NetworkFilterV0SerializeFmt<'a>
172 where
173 T: std::borrow::Borrow<NetworkFilter>,
174 {
175 fn from(v: &'a T) -> NetworkFilterV0SerializeFmt<'a> {
176 let v = v.borrow();
177 NetworkFilterV0SerializeFmt {
178 mask: &v.mask,
179 filter: &v.filter,
180 opt_domains: &v.opt_domains,
181 opt_not_domains: &v.opt_not_domains,
182 redirect: if v.is_redirect() {
183 &v.modifier_option
184 } else {
185 &None
186 },
187 hostname: &v.hostname,
188 csp: if v.is_csp() {
189 &v.modifier_option
190 } else {
191 &None
192 },
193 _bug: None,
194 tag: &v.tag,
195 raw_line: v.raw_line.as_ref().map(|raw| *raw.clone()),
196 id: &v.id,
197 opt_domains_union: &v.opt_domains_union,
198 opt_not_domains_union: &v.opt_not_domains_union,
199 }
200 }
201 }
202
203 /// Forces a `NetworkFilterList` to be serialized with the v0 filter format by converting to an
204 /// intermediate representation that is constructed with `NetworkFilterV0Fmt` instead.
205 fn serialize_v0_network_filter_list<S>(list: &NetworkFilterList, s: S) -> Result<S::Ok, S::Error>
206 where
207 S: serde::Serializer,
208 {
209 #[derive(Serialize, Default)]
210 struct NetworkFilterListV0SerializeFmt<'a> {
211 #[serde(serialize_with = "crate::data_format::utils::stabilize_hashmap_serialization")]
212 filter_map: HashMap<crate::utils::Hash, Vec<NetworkFilterV0SerializeFmt<'a>>>,
213 }
214
215 let v0_list = NetworkFilterListV0SerializeFmt {
216 filter_map: list
217 .filter_map
218 .iter()
219 .map(|(k, v)| (*k, v.iter().map(|f| f.into()).collect()))
220 .collect(),
221 };
222
223 v0_list.serialize(s)
224 }
225
226 /// Forces a `NetworkFilter` slice to be serialized with the v0 filter format by converting to
227 /// an intermediate representation that is constructed with `NetworkFilterV0Fmt` instead.
228 fn serialize_v0_network_filter_vec<S>(vec: &[NetworkFilter], s: S) -> Result<S::Ok, S::Error>
229 where
230 S: serde::Serializer,
231 {
232 let v0_vec: Vec<_> = vec.iter().map(NetworkFilterV0SerializeFmt::from).collect();
233
234 v0_vec.serialize(s)
235 }
236
237 /// Provides structural aggregration of referenced adblock engine data to allow for allocation-free
238 /// serialization.
239 #[derive(Serialize)]
240 pub(crate) struct SerializeFormat<'a> {
241 #[serde(serialize_with = "serialize_v0_network_filter_list")]
242 csp: &'a NetworkFilterList,
243 #[serde(serialize_with = "serialize_v0_network_filter_list")]
244 exceptions: &'a NetworkFilterList,
245 #[serde(serialize_with = "serialize_v0_network_filter_list")]
246 importants: &'a NetworkFilterList,
247 #[serde(serialize_with = "serialize_v0_network_filter_list")]
248 redirects: &'a NetworkFilterList,
249 #[serde(serialize_with = "serialize_v0_network_filter_list")]
250 filters_tagged: &'a NetworkFilterList,
251 #[serde(serialize_with = "serialize_v0_network_filter_list")]
252 filters: &'a NetworkFilterList,
253 #[serde(serialize_with = "serialize_v0_network_filter_list")]
254 generic_hide: &'a NetworkFilterList,
255
256 #[serde(serialize_with = "serialize_v0_network_filter_vec")]
257 tagged_filters_all: &'a Vec<NetworkFilter>,
258
259 enable_optimizations: bool,
260
261 resources: LegacyRedirectResourceStorage,
262
263 #[serde(serialize_with = "stabilize_hashset_serialization")]
264 simple_class_rules: &'a HashSet<String>,
265 #[serde(serialize_with = "stabilize_hashset_serialization")]
266 simple_id_rules: &'a HashSet<String>,
267 #[serde(serialize_with = "stabilize_hashmap_serialization")]
268 complex_class_rules: &'a HashMap<String, Vec<String>>,
269 #[serde(serialize_with = "stabilize_hashmap_serialization")]
270 complex_id_rules: &'a HashMap<String, Vec<String>>,
271
272 specific_rules: LegacyHostnameRuleDb,
273
274 #[serde(serialize_with = "stabilize_hashset_serialization")]
275 misc_generic_selectors: &'a HashSet<String>,
276
277 scriptlets: LegacyScriptletResourceStorage,
278 }
279
280 impl<'a> SerializeFormat<'a> {
281 pub fn serialize(&self) -> Result<Vec<u8>, SerializationError> {
282 let mut output = super::ADBLOCK_RUST_DAT_MAGIC.to_vec();
283 output.push(0);
284 rmps::encode::write(&mut output, &self)?;
285 Ok(output)
286 }
287 }
288
289 /// `_bug` is no longer used, and is cleaned up from future format versions.
290 #[derive(Debug, Clone, Deserialize)]
291 pub(crate) struct NetworkFilterV0DeserializeFmt {
292 pub mask: crate::filters::network::NetworkFilterMask,
293 pub filter: crate::filters::network::FilterPart,
294 pub opt_domains: Option<Vec<crate::utils::Hash>>,
295 pub opt_not_domains: Option<Vec<crate::utils::Hash>>,
296 pub redirect: Option<String>,
297 pub hostname: Option<String>,
298 pub csp: Option<String>,
299 _bug: Option<u32>,
300 pub tag: Option<String>,
301 pub raw_line: Option<String>,
302 pub id: crate::utils::Hash,
303 pub opt_domains_union: Option<crate::utils::Hash>,
304 pub opt_not_domains_union: Option<crate::utils::Hash>,
305 }
306
307 impl From<NetworkFilterV0DeserializeFmt> for NetworkFilter {
308 fn from(v: NetworkFilterV0DeserializeFmt) -> Self {
309 Self {
310 mask: v.mask,
311 filter: v.filter,
312 opt_domains: v.opt_domains,
313 opt_not_domains: v.opt_not_domains,
314 modifier_option: v.redirect.or(v.csp),
315 hostname: v.hostname,
316 tag: v.tag,
317 raw_line: v.raw_line.map(Box::new),
318 id: v.id,
319 opt_domains_union: v.opt_domains_union,
320 opt_not_domains_union: v.opt_not_domains_union,
321 }
322 }
323 }
324
325 #[derive(Debug, Deserialize, Default)]
326 pub(crate) struct NetworkFilterListV0DeserializeFmt {
327 pub filter_map: HashMap<crate::utils::Hash, Vec<NetworkFilterV0DeserializeFmt>>,
328 }
329
330 impl From<NetworkFilterListV0DeserializeFmt> for NetworkFilterList {
331 fn from(v: NetworkFilterListV0DeserializeFmt) -> Self {
332 Self {
333 filter_map: v
334 .filter_map
335 .into_iter()
336 .map(|(k, v)| {
337 (
338 k,
339 v.into_iter()
340 .map(|f| std::sync::Arc::new(f.into()))
341 .collect(),
342 )
343 })
344 .collect(),
345 }
346 }
347 }
348
349 /// Structural representation of adblock engine data that can be built up from deserialization and
350 /// used directly to construct new `Engine` components without unnecessary allocation.
351 #[derive(Deserialize)]
352 pub(crate) struct DeserializeFormat {
353 csp: NetworkFilterListV0DeserializeFmt,
354 exceptions: NetworkFilterListV0DeserializeFmt,
355 importants: NetworkFilterListV0DeserializeFmt,
356 redirects: NetworkFilterListV0DeserializeFmt,
357 filters_tagged: NetworkFilterListV0DeserializeFmt,
358 filters: NetworkFilterListV0DeserializeFmt,
359 generic_hide: NetworkFilterListV0DeserializeFmt,
360
361 tagged_filters_all: Vec<NetworkFilterV0DeserializeFmt>,
362
363 enable_optimizations: bool,
364
365 _resources: LegacyRedirectResourceStorage,
366
367 simple_class_rules: HashSet<String>,
368 simple_id_rules: HashSet<String>,
369 complex_class_rules: HashMap<String, Vec<String>>,
370 complex_id_rules: HashMap<String, Vec<String>>,
371
372 specific_rules: LegacyHostnameRuleDb,
373
374 misc_generic_selectors: HashSet<String>,
375
376 _scriptlets: LegacyScriptletResourceStorage,
377 }
378
379 impl DeserializeFormat {
380 pub fn deserialize(serialized: &[u8]) -> Result<Self, DeserializationError> {
381 assert!(serialized.starts_with(&super::ADBLOCK_RUST_DAT_MAGIC));
382 assert!(serialized[super::ADBLOCK_RUST_DAT_MAGIC.len()] == 0);
383 let format: Self =
384 rmps::decode::from_read(&serialized[super::ADBLOCK_RUST_DAT_MAGIC.len() + 1..])?;
385 Ok(format)
386 }
387 }
388
389 impl<'a> From<(&'a Blocker, &'a CosmeticFilterCache)> for SerializeFormat<'a> {
390 fn from(v: (&'a Blocker, &'a CosmeticFilterCache)) -> Self {
391 let (blocker, cfc) = v;
392 Self {
393 csp: &blocker.csp,
394 exceptions: &blocker.exceptions,
395 importants: &blocker.importants,
396 redirects: &blocker.redirects,
397 filters_tagged: &blocker.filters_tagged,
398 filters: &blocker.filters,
399 generic_hide: &blocker.generic_hide,
400
401 tagged_filters_all: &blocker.tagged_filters_all,
402
403 enable_optimizations: blocker.enable_optimizations,
404
405 resources: LegacyRedirectResourceStorage::default(),
406
407 simple_class_rules: &cfc.simple_class_rules,
408 simple_id_rules: &cfc.simple_id_rules,
409 complex_class_rules: &cfc.complex_class_rules,
410 complex_id_rules: &cfc.complex_id_rules,
411
412 specific_rules: (&cfc.specific_rules).into(),
413
414 misc_generic_selectors: &cfc.misc_generic_selectors,
415
416 scriptlets: LegacyScriptletResourceStorage::default(),
417 }
418 }
419 }
420
421 impl From<DeserializeFormat> for (Blocker, CosmeticFilterCache) {
422 fn from(v: DeserializeFormat) -> Self {
423 (
424 Blocker {
425 csp: v.csp.into(),
426 exceptions: v.exceptions.into(),
427 importants: v.importants.into(),
428 redirects: v.redirects.into(),
429 removeparam: NetworkFilterList::default(),
430 filters_tagged: v.filters_tagged.into(),
431 filters: v.filters.into(),
432 generic_hide: v.generic_hide.into(),
433
434 tags_enabled: Default::default(),
435 tagged_filters_all: v.tagged_filters_all.into_iter().map(|f| f.into()).collect(),
436
437 enable_optimizations: v.enable_optimizations,
438
439 #[cfg(feature = "object-pooling")]
440 pool: Default::default(),
441 regex_manager: Default::default(),
442 },
443 CosmeticFilterCache {
444 simple_class_rules: v.simple_class_rules,
445 simple_id_rules: v.simple_id_rules,
446 complex_class_rules: v.complex_class_rules,
447 complex_id_rules: v.complex_id_rules,
448
449 specific_rules: v.specific_rules.into(),
450
451 misc_generic_selectors: v.misc_generic_selectors,
452 },
453 )
454 }
455 }