1use std::collections::BTreeMap;
14use std::sync::{Arc, Mutex, MutexGuard};
15
16use day_spec::Support;
17
18pub trait RequestFilter: Send + Sync + 'static {
27 fn decide(&self, request: &RequestInfo<'_>) -> RequestDecision;
29}
30
31impl<F> RequestFilter for F
32where
33 F: Fn(&RequestInfo<'_>) -> RequestDecision + Send + Sync + 'static,
34{
35 fn decide(&self, request: &RequestInfo<'_>) -> RequestDecision {
36 self(request)
37 }
38}
39
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub struct RequestInfo<'a> {
43 pub url: &'a str,
45 pub top_url: Option<&'a str>,
49 pub frame_url: Option<&'a str>,
51 pub kind: ResourceKind,
53 pub main_frame: bool,
55 pub method: &'a str,
57}
58
59#[derive(
61 Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
62)]
63#[serde(rename_all = "kebab-case")]
64pub enum ResourceKind {
65 Document,
67 Subdocument,
69 Script,
71 Stylesheet,
73 Image,
75 Font,
77 Media,
79 Xhr,
81 Fetch,
83 WebSocket,
85 Ping,
87 Object,
89 Other,
91 #[default]
93 Unknown,
94}
95
96impl ResourceKind {
97 pub fn infer(url: &str, accept: Option<&str>, main_frame: bool) -> ResourceKind {
102 if main_frame {
103 return ResourceKind::Document;
104 }
105 let accept = accept.unwrap_or_default().to_ascii_lowercase();
106 let first = accept.split(',').next().unwrap_or_default().trim();
107 if first.starts_with("text/html") || first.starts_with("application/xhtml") {
108 return ResourceKind::Subdocument;
109 }
110 if first.starts_with("text/css") {
111 return ResourceKind::Stylesheet;
112 }
113 if first.starts_with("image/") {
114 return ResourceKind::Image;
115 }
116 if first.starts_with("video/") || first.starts_with("audio/") {
117 return ResourceKind::Media;
118 }
119 if first.starts_with("font/") || first.starts_with("application/font") {
120 return ResourceKind::Font;
121 }
122 if first == "text/event-stream" {
123 return ResourceKind::Xhr;
124 }
125 match ResourceKind::from_extension(url) {
126 ResourceKind::Unknown if first.starts_with("application/json") => ResourceKind::Xhr,
127 kind => kind,
128 }
129 }
130
131 fn from_extension(url: &str) -> ResourceKind {
133 let path = url.split(['?', '#']).next().unwrap_or_default();
134 let path = path.split_once("://").map_or(path, |(_, rest)| {
135 rest.split_once('/').map_or("", |(_, p)| p)
136 });
137 let last = path.rsplit('/').next().unwrap_or_default();
138 let Some((_, ext)) = last.rsplit_once('.') else {
139 return ResourceKind::Unknown;
140 };
141 match ext.to_ascii_lowercase().as_str() {
142 "js" | "mjs" | "cjs" => ResourceKind::Script,
143 "css" => ResourceKind::Stylesheet,
144 "png" | "jpg" | "jpeg" | "gif" | "webp" | "avif" | "svg" | "ico" | "bmp" => {
145 ResourceKind::Image
146 }
147 "woff" | "woff2" | "ttf" | "otf" | "eot" => ResourceKind::Font,
148 "mp4" | "webm" | "mp3" | "m4a" | "m4v" | "ogg" | "oga" | "wav" | "m3u8" | "mpd" => {
149 ResourceKind::Media
150 }
151 "html" | "htm" => ResourceKind::Subdocument,
152 "json" | "xml" => ResourceKind::Xhr,
153 _ => ResourceKind::Unknown,
154 }
155 }
156
157 #[allow(
161 dead_code,
162 reason = "only the Qt and ArkUI arms see Chromium resource types"
163 )]
164 pub(crate) fn from_chromium(code: i32) -> ResourceKind {
165 match code {
166 0 | 19 => ResourceKind::Document,
167 1 | 20 => ResourceKind::Subdocument,
168 2 => ResourceKind::Stylesheet,
169 3 => ResourceKind::Script,
170 4 | 12 => ResourceKind::Image,
171 5 => ResourceKind::Font,
172 7 | 17 => ResourceKind::Object,
173 8 => ResourceKind::Media,
174 13 | 22 => ResourceKind::Xhr,
175 14 | 16 => ResourceKind::Ping,
176 21 => ResourceKind::WebSocket,
177 6 | 9 | 10 | 11 | 15 | 18 => ResourceKind::Other,
178 _ => ResourceKind::Unknown,
179 }
180 }
181
182 #[allow(
184 dead_code,
185 reason = "only the WinUI arm sees WebView2 resource contexts"
186 )]
187 #[expect(
188 clippy::match_same_arms,
189 reason = "one arm per WebView2 context value, in numeric order"
190 )]
191 pub(crate) fn from_webview2(context: i32) -> ResourceKind {
192 match context {
193 1 => ResourceKind::Document,
194 2 => ResourceKind::Stylesheet,
195 3 => ResourceKind::Image,
196 4 => ResourceKind::Media,
197 5 => ResourceKind::Font,
198 6 => ResourceKind::Script,
199 7 => ResourceKind::Xhr,
200 8 => ResourceKind::Fetch,
201 10 => ResourceKind::Xhr, 11 => ResourceKind::WebSocket,
203 14 | 15 => ResourceKind::Ping, 9 | 12 | 13 | 16 => ResourceKind::Other,
205 _ => ResourceKind::Unknown,
206 }
207 }
208}
209
210#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
212pub enum RequestDecision {
213 #[default]
215 Allow,
216 Block,
219}
220
221#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
223pub struct BlockedLoad {
224 pub url: String,
226 pub page_url: String,
229 pub kind: ResourceKind,
231}
232
233#[derive(Clone, Debug, PartialEq, Eq)]
237pub struct ContentRuleList {
238 pub id: String,
240 pub version: String,
243 pub json: Arc<str>,
245}
246
247impl ContentRuleList {
248 pub fn new(
250 id: impl Into<String>,
251 version: impl Into<String>,
252 json: impl Into<Arc<str>>,
253 ) -> Self {
254 ContentRuleList {
255 id: id.into(),
256 version: version.into(),
257 json: json.into(),
258 }
259 }
260
261 #[allow(
264 dead_code,
265 reason = "only the Apple arms keep compiled rule lists in a store"
266 )]
267 pub(crate) fn store_identifier(&self) -> String {
268 format!("{}@{}", self.id, self.version)
269 }
270}
271
272#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
274pub struct ContentRulesError {
275 pub id: String,
277 pub message: String,
279}
280
281#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
283pub enum InjectAt {
284 #[default]
286 DocumentStart,
287 DocumentEnd,
289}
290
291#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
293pub enum Frames {
294 #[default]
296 All,
297 Main,
299}
300
301#[derive(Clone, Debug, PartialEq, Eq)]
304#[must_use]
305pub struct UserScript {
306 pub source: Arc<str>,
308 pub at: InjectAt,
310 pub frames: Frames,
312}
313
314impl UserScript {
315 pub fn new(source: impl Into<Arc<str>>) -> Self {
317 UserScript {
318 source: source.into(),
319 at: InjectAt::DocumentStart,
320 frames: Frames::All,
321 }
322 }
323
324 pub fn at(mut self, at: InjectAt) -> Self {
326 self.at = at;
327 self
328 }
329
330 pub fn frames(mut self, frames: Frames) -> Self {
332 self.frames = frames;
333 self
334 }
335}
336
337#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
343pub struct ScriptMessage {
344 pub name: String,
346 pub payload: String,
348 #[serde(default)]
351 pub origin: String,
352 #[serde(default)]
354 pub main_frame: bool,
355}
356
357#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
360pub struct MediaRequest {
361 pub origin: String,
363 pub camera: bool,
365 pub microphone: bool,
367}
368
369#[derive(Clone)]
374pub struct RequestHooks(Arc<Hooks>);
375
376struct Hooks {
377 filter: Arc<dyn RequestFilter>,
378 top: Mutex<String>,
381 blocked: Option<Arc<BlockedSink>>,
382 exempt_internal: bool,
385}
386
387impl RequestHooks {
388 pub(crate) fn new(
389 filter: Arc<dyn RequestFilter>,
390 blocked: Option<Arc<BlockedSink>>,
391 exempt_internal: bool,
392 ) -> Self {
393 RequestHooks(Arc::new(Hooks {
394 filter,
395 top: Mutex::new(String::new()),
396 blocked,
397 exempt_internal,
398 }))
399 }
400
401 pub fn filters_internal(&self) -> bool {
405 !self.0.exempt_internal
406 }
407
408 pub fn decide(&self, request: &RequestInfo<'_>) -> RequestDecision {
414 if self.0.exempt_internal && is_internal(request.url) {
415 return RequestDecision::Allow;
416 }
417 let tracked = match request.top_url {
418 Some(_) => None,
419 None => Some(lock(&self.0.top).clone()).filter(|top| !top.is_empty()),
420 };
421 let info = RequestInfo {
422 top_url: request.top_url.or(tracked.as_deref()),
423 ..*request
424 };
425 let filter = &self.0.filter;
426 let decision =
427 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| filter.decide(&info)))
428 .unwrap_or_else(|_| {
429 log::warn!(
430 "day-piece-webview: a request filter panicked; allowing {}",
431 info.url
432 );
433 RequestDecision::Allow
434 });
435 match decision {
436 RequestDecision::Allow if info.main_frame && info.kind == ResourceKind::Document => {
437 self.set_top_url(info.url);
438 }
439 RequestDecision::Block => {
440 if let Some(sink) = &self.0.blocked {
441 sink.push(BlockedLoad {
442 url: info.url.to_owned(),
443 page_url: info
444 .frame_url
445 .or(info.top_url)
446 .unwrap_or(info.url)
447 .to_owned(),
448 kind: info.kind,
449 });
450 }
451 }
452 RequestDecision::Allow => {}
453 }
454 decision
455 }
456
457 pub fn set_top_url(&self, url: &str) {
460 let mut top = lock(&self.0.top);
461 if *top != url {
462 url.clone_into(&mut top);
463 }
464 }
465
466 pub fn top_url(&self) -> String {
468 lock(&self.0.top).clone()
469 }
470}
471
472impl PartialEq for RequestHooks {
473 fn eq(&self, other: &Self) -> bool {
474 Arc::ptr_eq(&self.0, &other.0)
475 }
476}
477
478impl std::fmt::Debug for RequestHooks {
479 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
480 f.write_str("RequestHooks")
481 }
482}
483
484fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
486 mutex
487 .lock()
488 .unwrap_or_else(std::sync::PoisonError::into_inner)
489}
490
491fn is_internal(url: &str) -> bool {
496 url.starts_with("day-resource:")
497 || url.starts_with("https://day-resource.invalid/")
498 || url
499 .strip_prefix("http://day-resource.p")
500 .and_then(|rest| rest.split_once('/'))
501 .is_some_and(|(id, _)| !id.is_empty() && id.bytes().all(|b| b.is_ascii_digit()))
502}
503
504const BLOCKED_BACKLOG: usize = 2000;
507
508pub(crate) const BLOCKED_PERIOD_MS: u32 = 100;
511
512#[derive(Default)]
515pub(crate) struct BlockedSink {
516 state: Mutex<SinkState>,
517}
518
519#[derive(Default)]
520struct SinkState {
521 loads: Vec<BlockedLoad>,
522 wake: Option<day_async::Deliver<()>>,
523 dropped: usize,
524}
525
526impl BlockedSink {
527 pub(crate) fn push(&self, load: BlockedLoad) {
528 self.extend(std::iter::once(load));
529 }
530
531 pub(crate) fn extend(&self, loads: impl IntoIterator<Item = BlockedLoad>) {
532 let wake = {
533 let mut state = lock(&self.state);
534 for load in loads {
535 if state.loads.len() < BLOCKED_BACKLOG {
536 state.loads.push(load);
537 } else {
538 state.dropped += 1;
539 }
540 }
541 if state.loads.is_empty() {
542 None
543 } else {
544 state.wake.take()
545 }
546 };
547 if let Some(wake) = wake {
548 wake.send(());
549 }
550 }
551
552 fn take_or_wait(&self) -> Result<Vec<BlockedLoad>, day_async::Oneshot<()>> {
554 let mut state = lock(&self.state);
555 if !state.loads.is_empty() {
556 if state.dropped > 0 {
557 log::debug!(
558 "day-piece-webview: {} blocked loads not reported (backlog full)",
559 state.dropped
560 );
561 state.dropped = 0;
562 }
563 return Ok(std::mem::take(&mut state.loads));
564 }
565 let (tx, rx) = day_async::oneshot();
566 state.wake = Some(tx);
567 Err(rx)
568 }
569}
570
571pub(crate) type BlockedCallback = std::rc::Rc<dyn Fn(&[BlockedLoad])>;
573
574pub(crate) fn deliver_blocked(
577 sink: Arc<BlockedSink>,
578 callback: BlockedCallback,
579) -> day_core::TaskHandle {
580 day_core::task(async move {
581 loop {
582 match sink.take_or_wait() {
583 Ok(loads) => {
584 callback(&loads);
585 day_core::sleep(BLOCKED_PERIOD_MS).await;
586 }
587 Err(arrival) => {
588 if arrival.await.is_err() {
589 return;
590 }
591 day_core::sleep(BLOCKED_PERIOD_MS).await;
593 }
594 }
595 }
596 })
597}
598
599static TOKENS: Mutex<BTreeMap<u64, std::sync::Weak<Hooks>>> = Mutex::new(BTreeMap::new());
604
605#[allow(
607 dead_code,
608 reason = "only the Android, Qt, WinUI and ArkUI arms reach their hooks by token"
609)]
610pub(crate) fn register(hooks: &RequestHooks) -> u64 {
611 let token = day_async::next_token();
612 let mut tokens = lock(&TOKENS);
613 tokens.retain(|_, hooks| hooks.strong_count() > 0);
614 tokens.insert(token, Arc::downgrade(&hooks.0));
615 token
616}
617
618#[cfg(test)]
620pub(crate) fn unregister(token: u64) {
621 lock(&TOKENS).remove(&token);
622}
623
624#[allow(
626 dead_code,
627 reason = "only the Android, Qt, WinUI and ArkUI arms reach their hooks by token"
628)]
629pub(crate) fn hooks(token: u64) -> Option<RequestHooks> {
630 if token == 0 {
631 return None;
632 }
633 lock(&TOKENS)
634 .get(&token)
635 .and_then(std::sync::Weak::upgrade)
636 .map(RequestHooks)
637}
638
639#[derive(Clone, Debug, Default, PartialEq)]
643pub struct PageContent {
644 pub requests: Option<RequestHooks>,
646 pub rules: Vec<ContentRuleList>,
648 pub scripts: Vec<UserScript>,
650 pub styles: Vec<Arc<str>>,
652 pub messages: Vec<String>,
655 pub media_handler: bool,
658}
659
660impl PageContent {
661 #[allow(
663 dead_code,
664 reason = "only the Android, Qt, WinUI and ArkUI arms ask before injecting the bridge"
665 )]
666 pub(crate) fn has_scripts(&self) -> bool {
667 !self.scripts.is_empty() || !self.styles.is_empty() || !self.messages.is_empty()
668 }
669
670 #[allow(
674 dead_code,
675 reason = "every native arm injects scripts; the web arm and a build with none do not"
676 )]
677 pub(crate) fn page_scripts(
678 &self,
679 transport: Transport,
680 native_styles: bool,
681 ) -> Vec<UserScript> {
682 let mut scripts = Vec::new();
683 if !self.messages.is_empty() {
684 scripts.push(UserScript::new(message_shim(transport, &self.messages)));
685 }
686 if !native_styles {
687 scripts.extend(
688 self.styles
689 .iter()
690 .map(|css| UserScript::new(style_script(css))),
691 );
692 }
693 scripts.extend(self.scripts.iter().cloned());
694 scripts
695 }
696}
697
698#[allow(
700 dead_code,
701 reason = "each arm builds its own transport, so the others' variants are never built"
702)]
703#[derive(Clone, Copy, Debug, PartialEq, Eq)]
704pub(crate) enum Transport {
705 WebKit,
708 Android,
711 WebView2,
713 Envelope(&'static str),
716}
717
718pub(crate) fn message_shim(transport: Transport, names: &[String]) -> String {
723 let names = serde_json::to_string(names).unwrap_or_else(|_| "[]".into());
724 let send = match transport {
725 Transport::WebKit => {
726 "const h=window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers[name];\
727 if(!h)return Promise.reject(new Error('no handler '+name));\
728 return Promise.resolve(h.postMessage(text)).then(v=>v===undefined?null:v);"
729 .to_owned()
730 }
731 Transport::Android => {
732 "const o=window[name];if(!o||typeof o.postMessage!=='function')return Promise.reject(new Error('no handler '+name));\
734 if(!hooked.has(name)){hooked.add(name);o.addEventListener('message',e=>{const d=String(e.data);if(d.charCodeAt(0)!==2)return;\
735 const i=d.indexOf('\\u0002',1);settle(+d.slice(1,i),d.charAt(i+1)==='1'?d.slice(i+2):null);});}\
736 const id=next++;return new Promise(r=>{waiting.set(id,r);o.postMessage('\\u0002'+id+'\\u0002'+text);});"
737 .to_owned()
738 }
739 Transport::WebView2 => {
740 "const w=window.chrome&&window.chrome.webview;if(!w)return Promise.reject(new Error('no host'));\
741 if(!hooked.has('')){hooked.add('');w.addEventListener('message',e=>{const d=e.data;if(d&&typeof d==='object'&&'dayMessageReply' in d)settle(d.dayMessageReply,d.value);});}\
742 const id=next++;return new Promise(r=>{waiting.set(id,r);w.postMessage(JSON.stringify({dayMessage:name,id:id,payload:text}));});"
743 .to_owned()
744 }
745 Transport::Envelope(post) => format!(
747 "const id=next++;const e=JSON.stringify({{dayMessage:name,id:id,payload:text}});\
748 if(window!==window.top){{{post}(e);return Promise.resolve(null);}}\
749 return new Promise(r=>{{waiting.set(id,r);{post}(e);}});"
750 ),
751 };
752 let aliases = match transport {
753 Transport::WebKit | Transport::Android => "",
755 Transport::WebView2 | Transport::Envelope(_) => {
756 "for(const n of NAMES){if(!(n in window))Object.defineProperty(window,n,{value:Object.freeze({postMessage:t=>{send(n,String(t)).catch(()=>{});}})});}"
757 }
758 };
759 format!(
760 "(()=>{{if(window.dayMessage)return;const NAMES={names};let next=1+Math.floor(Math.random()*1e9);const waiting=new Map();const hooked=new Set();\
761 const settle=(id,v)=>{{const r=waiting.get(id);if(r){{waiting.delete(id);r(v===undefined?null:v);}}}};\
762 Object.defineProperty(window,'__dayMessageReply',{{value:settle}});\
763 const send=(name,text)=>{{{send}}};\
764 Object.defineProperty(window,'dayMessage',{{value:(name,payload)=>{{try{{return send(String(name),payload==null?'':String(payload));}}catch(e){{return Promise.reject(e);}}}}}});\
765 {aliases}}})();"
766 )
767}
768
769pub(crate) fn style_script(css: &str) -> String {
773 let css = crate::js_string_literal(css);
774 format!(
775 "(()=>{{const css={css};const add=()=>{{const r=document.head||document.documentElement;if(!r)return false;\
776 const s=document.createElement('style');s.setAttribute('data-day-user-style','');s.textContent=css;r.appendChild(s);return true;}};\
777 if(!add())document.addEventListener('readystatechange',add,{{once:true}});}})();"
778 )
779}
780
781#[allow(
786 dead_code,
787 reason = "only the Android, WinUI and ArkUI arms lack a native document-start injection"
788)]
789pub(crate) fn document_start_everywhere(script: &UserScript) -> String {
790 let mut source = script.source.to_string();
791 if script.at == InjectAt::DocumentEnd {
792 source = format!(
793 "(()=>{{const run=()=>{{{source}\n}};if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',run,{{once:true}});else run();}})();"
794 );
795 }
796 if script.frames == Frames::Main {
797 source = format!("if(window===window.top){{{source}\n}}");
798 }
799 source
800}
801
802#[allow(
805 dead_code,
806 reason = "only the Qt and ArkUI arms answer the page through a script"
807)]
808pub(crate) fn reply_script(id: u64, reply: Option<&str>) -> String {
809 let value = reply.map_or_else(|| "null".to_owned(), crate::js_string_literal);
810 format!("window.__dayMessageReply&&window.__dayMessageReply({id},{value})")
811}
812
813#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
816pub(crate) struct MessageReport {
817 pub id: u64,
818 #[serde(flatten)]
819 pub message: ScriptMessage,
820}
821
822#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
824pub(crate) struct MediaReport {
825 pub id: u64,
826 #[serde(flatten)]
827 pub request: MediaRequest,
828}
829
830#[allow(
832 dead_code,
833 reason = "only the Qt and WinUI arms receive messages in an envelope"
834)]
835pub(crate) fn parse_envelope(text: &str) -> Option<(String, u64, String)> {
836 #[derive(serde::Deserialize)]
837 struct Envelope {
838 #[serde(rename = "dayMessage")]
839 name: String,
840 id: u64,
841 #[serde(default)]
842 payload: String,
843 }
844 let envelope: Envelope = serde_json::from_str(text).ok()?;
845 Some((envelope.name, envelope.id, envelope.payload))
846}
847
848pub fn request_filter_support() -> Support {
852 if cfg!(any(
853 all(feature = "material", target_os = "android"),
854 all(feature = "xaml", windows),
855 feature = "qt",
856 all(feature = "arkui", target_env = "ohos"),
857 )) {
858 Support::Native
859 } else {
860 Support::Unsupported
861 }
862}
863
864pub fn blocked_report_support() -> Support {
866 request_filter_support()
867}
868
869pub fn content_rules_support() -> Support {
872 if cfg!(any(
873 all(
874 any(feature = "appkit", feature = "gtk"),
875 target_os = "macos"
876 ),
877 all(feature = "uikit", target_os = "ios"),
878 all(feature = "gtk", not(target_os = "macos"), not(windows)),
879 )) {
880 Support::Native
881 } else {
882 Support::Unsupported
883 }
884}
885
886pub fn user_script_support() -> Support {
890 #[cfg(all(feature = "material", target_os = "android"))]
891 if !crate::android_impl::document_start_scripts() {
892 return Support::Emulated;
893 }
894 if cfg!(any(
895 all(
896 any(feature = "appkit", feature = "gtk"),
897 target_os = "macos"
898 ),
899 all(feature = "uikit", target_os = "ios"),
900 all(feature = "gtk", not(target_os = "macos"), not(windows)),
901 all(feature = "material", target_os = "android"),
902 all(feature = "xaml", windows),
903 feature = "qt",
904 all(feature = "arkui", target_env = "ohos"),
905 )) {
906 Support::Native
907 } else {
908 Support::Unsupported
909 }
910}
911
912pub fn script_message_support() -> Support {
914 user_script_support()
915}
916
917#[derive(Default)]
923#[allow(
925 dead_code,
926 reason = "only the Apple and Linux GTK arms hold loads while rules compile"
927)]
928pub(crate) struct RuleGate {
929 generation: std::cell::Cell<u64>,
930 pending_load: std::cell::RefCell<Option<Box<dyn FnOnce()>>>,
931}
932
933#[allow(
934 dead_code,
935 reason = "only the Apple and Linux GTK arms hold loads while rules compile"
936)]
937impl RuleGate {
938 pub(crate) fn begin(&self, load: Option<Box<dyn FnOnce()>>) -> u64 {
941 let generation = self.generation.get() + 1;
942 self.generation.set(generation);
943 if let Some(load) = load {
944 *self.pending_load.borrow_mut() = Some(load);
945 }
946 generation
947 }
948
949 pub(crate) fn is_current(&self, generation: u64) -> bool {
951 self.generation.get() == generation
952 }
953
954 pub(crate) fn is_holding(&self) -> bool {
956 self.pending_load.borrow().is_some()
957 }
958
959 pub(crate) fn redirect(&self, load: Box<dyn FnOnce()>) -> Option<Box<dyn FnOnce()>> {
963 let mut pending = self.pending_load.borrow_mut();
964 if pending.is_some() {
965 *pending = Some(load);
966 None
967 } else {
968 Some(load)
969 }
970 }
971
972 pub(crate) fn finish(&self, generation: u64) {
975 if !self.is_current(generation) {
976 return;
977 }
978 let load = self.pending_load.borrow_mut().take();
980 if let Some(load) = load {
981 load();
982 }
983 }
984}
985
986#[cfg(test)]
987mod tests {
988 use super::*;
989
990 #[test]
991 fn every_namespace_form_is_internal() {
992 for url in [
993 "day-resource://p3/ads.css",
994 "https://day-resource.invalid/3/ads.css",
995 "http://day-resource.p3/ads.css",
996 ] {
997 assert!(is_internal(url), "{url}");
998 }
999 for url in [
1000 "http://day-resource.pages.example/ads.css",
1001 "http://day-resource.p/ads.css",
1002 "https://day-resource.p3/ads.css",
1003 "https://news.example/day-resource:",
1004 ] {
1005 assert!(!is_internal(url), "{url}");
1006 }
1007 }
1008
1009 #[test]
1010 fn only_the_newest_rules_release_the_first_load() {
1011 use std::cell::Cell;
1012 use std::rc::Rc;
1013 let gate = RuleGate::default();
1014 let loaded = Rc::new(Cell::new(false));
1015 let first = gate.begin(Some(Box::new({
1016 let loaded = loaded.clone();
1017 move || loaded.set(true)
1018 })));
1019 let second = gate.begin(None);
1021 assert!(!gate.is_current(first));
1023 gate.finish(first);
1024 assert!(!loaded.get());
1025 assert!(gate.is_current(second));
1027 gate.finish(second);
1028 assert!(loaded.get());
1029 loaded.set(false);
1030 gate.finish(second);
1031 assert!(!loaded.get());
1032 }
1033
1034 #[test]
1035 fn a_navigation_while_held_replaces_the_first_load() {
1036 use std::cell::RefCell;
1037 use std::rc::Rc;
1038 let gate = RuleGate::default();
1039 let page = Rc::new(RefCell::new(Vec::new()));
1040 let load = |name: &'static str| -> Box<dyn FnOnce()> {
1041 let page = page.clone();
1042 Box::new(move || page.borrow_mut().push(name))
1043 };
1044 let generation = gate.begin(Some(load("initial")));
1045 assert!(gate.is_holding());
1046 assert!(gate.redirect(load("first")).is_none());
1048 assert!(gate.redirect(load("requested")).is_none());
1049 assert!(page.borrow().is_empty());
1050 gate.finish(generation);
1051 assert_eq!(*page.borrow(), ["requested"]);
1052 assert!(!gate.is_holding());
1054 match gate.redirect(load("later")) {
1055 Some(now) => now(),
1056 None => panic!("a navigation after the first load was held"),
1057 }
1058 assert_eq!(*page.borrow(), ["requested", "later"]);
1059 }
1060
1061 #[test]
1062 fn kinds_follow_the_accept_header_then_the_extension() {
1063 let infer = |url, accept| ResourceKind::infer(url, accept, false);
1064 assert_eq!(
1065 ResourceKind::infer("https://a.test/", Some("text/html"), true),
1066 ResourceKind::Document
1067 );
1068 assert_eq!(
1069 infer(
1070 "https://a.test/frame",
1071 Some("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
1072 ),
1073 ResourceKind::Subdocument
1074 );
1075 assert_eq!(
1076 infer("https://a.test/x?y", Some("text/css,*/*;q=0.1")),
1077 ResourceKind::Stylesheet
1078 );
1079 assert_eq!(
1080 infer("https://a.test/pixel", Some("image/avif,image/webp,*/*")),
1081 ResourceKind::Image
1082 );
1083 assert_eq!(
1085 infer("https://ads.test/tag.JS?v=2#x", Some("*/*")),
1086 ResourceKind::Script
1087 );
1088 assert_eq!(infer("https://a.test/font.woff2", None), ResourceKind::Font);
1089 assert_eq!(
1090 infer("https://a.test/clip.m3u8", Some("*/*")),
1091 ResourceKind::Media
1092 );
1093 assert_eq!(
1094 infer("https://a.test/api/feed.json", Some("*/*")),
1095 ResourceKind::Xhr
1096 );
1097 assert_eq!(
1098 infer("https://a.test/api/feed", Some("application/json")),
1099 ResourceKind::Xhr
1100 );
1101 assert_eq!(
1102 infer("https://a.test/collect", Some("*/*")),
1103 ResourceKind::Unknown
1104 );
1105 assert_eq!(infer("https://a.test", None), ResourceKind::Unknown);
1106 assert_eq!(infer("https://a.test/dir.v2/", None), ResourceKind::Unknown);
1107 }
1108
1109 #[test]
1110 fn engine_type_codes_map_to_kinds() {
1111 assert_eq!(ResourceKind::from_chromium(0), ResourceKind::Document);
1112 assert_eq!(ResourceKind::from_chromium(1), ResourceKind::Subdocument);
1113 assert_eq!(ResourceKind::from_chromium(3), ResourceKind::Script);
1114 assert_eq!(ResourceKind::from_chromium(13), ResourceKind::Xhr);
1115 assert_eq!(ResourceKind::from_chromium(21), ResourceKind::WebSocket);
1116 assert_eq!(ResourceKind::from_chromium(255), ResourceKind::Unknown);
1117 assert_eq!(ResourceKind::from_webview2(8), ResourceKind::Fetch);
1118 assert_eq!(ResourceKind::from_webview2(11), ResourceKind::WebSocket);
1119 assert_eq!(ResourceKind::from_webview2(0), ResourceKind::Unknown);
1120 }
1121
1122 #[test]
1123 fn hooks_track_the_top_page_and_never_filter_the_resource_namespace() {
1124 let filter = |request: &RequestInfo<'_>| {
1125 if request.url.contains("ads") || request.url.starts_with("day-resource:") {
1126 RequestDecision::Block
1127 } else {
1128 RequestDecision::Allow
1129 }
1130 };
1131 let sink = Arc::new(BlockedSink::default());
1132 let hooks = RequestHooks::new(Arc::new(filter), Some(sink.clone()), true);
1133 #[expect(
1134 clippy::items_after_statements,
1135 reason = "the helper sits beside the test steps that use it"
1136 )]
1137 fn request(url: &str, kind: ResourceKind, main_frame: bool) -> RequestInfo<'_> {
1138 RequestInfo {
1139 url,
1140 top_url: None,
1141 frame_url: None,
1142 kind,
1143 main_frame,
1144 method: "GET",
1145 }
1146 }
1147 assert_eq!(
1148 hooks.decide(&request("https://news.test/", ResourceKind::Document, true)),
1149 RequestDecision::Allow
1150 );
1151 assert_eq!(hooks.top_url(), "https://news.test/");
1152 assert_eq!(
1153 hooks.decide(&request(
1154 "https://ads.test/a.js",
1155 ResourceKind::Script,
1156 false
1157 )),
1158 RequestDecision::Block
1159 );
1160 assert_eq!(
1161 hooks.decide(&request(
1162 "day-resource://p1/ads.html",
1163 ResourceKind::Subdocument,
1164 false
1165 )),
1166 RequestDecision::Allow
1167 );
1168 assert_eq!(
1170 hooks.decide(&request("https://ads.test/", ResourceKind::Document, true)),
1171 RequestDecision::Block
1172 );
1173 assert_eq!(hooks.top_url(), "https://news.test/");
1174 let loads = sink.take_or_wait().ok().unwrap();
1175 assert_eq!(
1176 loads[0],
1177 BlockedLoad {
1178 url: "https://ads.test/a.js".into(),
1179 page_url: "https://news.test/".into(),
1180 kind: ResourceKind::Script,
1181 }
1182 );
1183 assert_eq!(loads.len(), 2);
1184 assert!(sink.take_or_wait().is_err());
1185 let sees_all = RequestHooks::new(
1187 Arc::new(|r: &RequestInfo<'_>| {
1188 if r.url.contains("ads") {
1189 RequestDecision::Block
1190 } else {
1191 RequestDecision::Allow
1192 }
1193 }),
1194 None,
1195 false,
1196 );
1197 assert!(sees_all.filters_internal());
1198 assert_eq!(
1199 sees_all.decide(&request(
1200 "https://day-resource.invalid/p1/https/ads.example/a.js",
1201 ResourceKind::Script,
1202 false
1203 )),
1204 RequestDecision::Block
1205 );
1206 let panicky = RequestHooks::new(
1208 Arc::new(|_: &RequestInfo<'_>| -> RequestDecision { panic!("filter bug") }),
1209 None,
1210 true,
1211 );
1212 assert_eq!(
1213 panicky.decide(&request("https://x.test/", ResourceKind::Image, false)),
1214 RequestDecision::Allow
1215 );
1216 let workers: Vec<_> = (0..3)
1218 .map(|worker| {
1219 let hooks = hooks.clone();
1220 std::thread::spawn(move || {
1221 for i in 0..100 {
1222 let url = format!("https://ads.test/{worker}/{i}.js");
1223 assert_eq!(
1224 hooks.decide(&request(&url, ResourceKind::Script, false)),
1225 RequestDecision::Block
1226 );
1227 }
1228 })
1229 })
1230 .collect();
1231 for worker in workers {
1232 worker.join().unwrap();
1233 }
1234 assert_eq!(sink.take_or_wait().ok().map(|loads| loads.len()), Some(300));
1235 let token = register(&hooks);
1236 assert!(hooks_eq(super::hooks(token), &hooks));
1237 unregister(token);
1238 assert!(super::hooks(token).is_none());
1239 }
1240
1241 fn hooks_eq(found: Option<RequestHooks>, hooks: &RequestHooks) -> bool {
1242 found.is_some_and(|found| found == *hooks)
1243 }
1244
1245 #[test]
1246 fn envelopes_round_trip_and_shims_name_their_handlers() {
1247 assert_eq!(
1248 parse_envelope(r#"{"dayMessage":"dayAdblock","id":7,"payload":"{\"a\":1}"}"#),
1249 Some(("dayAdblock".into(), 7, "{\"a\":1}".into()))
1250 );
1251 assert_eq!(parse_envelope("plain text"), None);
1252 let names = vec!["dayAdblock".to_owned()];
1253 for transport in [
1254 Transport::WebKit,
1255 Transport::Android,
1256 Transport::WebView2,
1257 Transport::Envelope("console.debug"),
1258 ] {
1259 let shim = message_shim(transport, &names);
1260 assert!(shim.contains("\"dayAdblock\""), "{shim}");
1261 assert!(
1262 shim.starts_with("(()=>{") && shim.ends_with("})();"),
1263 "{shim}"
1264 );
1265 }
1266 assert_eq!(
1267 reply_script(3, None),
1268 "window.__dayMessageReply&&window.__dayMessageReply(3,null)"
1269 );
1270 assert!(reply_script(3, Some("a\"b")).ends_with("(3,\"a\\\"b\")"));
1271 assert!(style_script("a{b:'c'}\n").contains("\"a{b:'c'}\\n\""));
1272 }
1273}