1extern crate alloc;
9pub mod duckduckgo;
10pub mod google;
11pub mod osm;
12pub mod pure;
13pub mod sabr;
14mod sabr_diag;
15mod ytpatch;
16pub mod youtube;
17use crate::os_lib::web_engine::site_hooks::{self, SiteHooks};
18use alloc::string::String;
19use alloc::vec::Vec;
20
21pub struct LegacySites;
23
24static LEGACY_SITES: LegacySites = LegacySites;
25
26pub fn register() {
28 site_hooks::register(&LEGACY_SITES);
29}
30
31impl SiteHooks for LegacySites {
32 fn fetch_is_special(&self, method: &str, full_url: &str) -> bool {
36 method == "POST" && full_url.contains("googlevideo.com/videoplayback")
37 }
38
39 fn fetch_rewrite_request(&self, url: &str, body: &[u8]) -> (String, Option<Vec<u8>>) {
41 let effective_url = sabr::normalize_sabr_url(url);
43 let mid_body: alloc::borrow::Cow<'_, [u8]> = if let Some(target_cpn) = sabr::extract_cpn_from_url(&effective_url) {
44 if let Some(aligned) = sabr::align_sabr_request_cpn(body, target_cpn) {
45 alloc::borrow::Cow::Owned(aligned)
47 } else {
48 alloc::borrow::Cow::Borrowed(body)
49 }
50 } else {
51 alloc::borrow::Cow::Borrowed(body)
52 };
53
54 let final_body = if let Some(sanitized) = sabr::sanitize_sabr_request(&mid_body) {
55 alloc::borrow::Cow::Owned(sanitized)
57 } else {
58 mid_body
59 };
60 sabr::record_sabr_request(&effective_url, &final_body);
61 let replaced = match final_body {
62 alloc::borrow::Cow::Owned(v) => Some(v),
63 alloc::borrow::Cow::Borrowed(_) => None,
64 };
65 (effective_url, replaced)
66 }
67
68 fn fetch_on_response(&self, raw: &mut Vec<u8>) {
70 if sabr::has_sps_reject(raw) {
71 crate::warn!("[SABR] レスポンス Part 58 に SPS Reject (status 3) を検知");
72 }
73 sabr::record_sabr_response(raw);
74 }
78
79 fn is_streaming_url(&self, host: &str, path: &str) -> bool {
81 pure::is_streaming_url(host, path)
82 }
83
84 fn user_agent(&self, host: &str) -> Option<&'static str> {
88 pure::user_agent(host)
89 }
90
91 fn offline_page(
95 &self,
96 current_host: &str,
97 current_path: &str,
98 current_is_https: bool,
99 is_post: bool,
100 post_body: &str,
101 ) -> Option<String> {
102 if duckduckgo::is_duckduckgo_host(current_host) {
103 crate::info!("[NET] DuckDuckGo offline simulation: host={}, path={}", current_host, current_path);
104 let variant = duckduckgo::detect_variant_from_host(current_host);
105 let (query_opt, category) = if is_post {
106 let q = duckduckgo::extract_query_param(post_body, "q");
107 let cat = duckduckgo::extract_query_param(post_body, "ia")
108 .map(|s| duckduckgo::DuckDuckGoCategory::from_ia_str(&s))
109 .unwrap_or(duckduckgo::DuckDuckGoCategory::Web);
110 (q, cat)
111 } else {
112 let full_url = alloc::format!("{}{}{}", if current_is_https { "https://" } else { "http://" }, current_host, current_path);
113 match duckduckgo::parse_duckduckgo_url(&full_url) {
114 Some(duckduckgo::DuckDuckGoUrlType::Search { query, category, .. }) => (Some(query), category),
115 _ => (None, duckduckgo::DuckDuckGoCategory::Web),
116 }
117 };
118
119 let html = if let Some(q) = query_opt {
120 let results = duckduckgo::get_mock_results_for_category(&q, category);
121 let page = duckduckgo::DuckDuckGoPage {
122 query: q.clone(),
123 variant,
124 offset: 0,
125 category,
126 instant_answer: duckduckgo::get_instant_answer_for_query(&q),
127 results,
128 related_searches: duckduckgo::get_related_searches_for_query(&q),
129 };
130 duckduckgo::generate_duckduckgo_page_html(&page)
131 } else {
132 duckduckgo::generate_duckduckgo_home_html(variant)
133 };
134 return Some(html);
135 } else if google::is_google_host(current_host) {
136 crate::info!("[NET] Google offline simulation: host={}, path={}", current_host, current_path);
137 let query_opt = if is_post {
138 google::extract_query_param(post_body, "q")
139 } else {
140 let full_url = alloc::format!("{}{}{}", if current_is_https { "https://" } else { "http://" }, current_host, current_path);
141 match google::parse_google_url(&full_url) {
142 Some(google::GoogleUrlType::Search { query, .. }) => Some(query),
143 _ => None,
144 }
145 };
146
147 let html = if let Some(q) = query_opt {
148 let results = google::get_mock_google_results(&q);
149 let knowledge = google::parse_google_knowledge_card("", &q);
150 let related_searches = alloc::vec![
151 alloc::format!("{} 使い方", q),
152 alloc::format!("{} 入門", q),
153 alloc::format!("{} 最新情報", q),
154 alloc::format!("{} AtmOS", q),
155 ];
156 let page = google::GoogleSearchPage {
157 query: q.clone(),
158 start_offset: 0,
159 total_results_text: String::from("約 1,480,000 件"),
160 search_time_sec: String::from("0.24"),
161 results,
162 knowledge,
163 related_searches,
164 };
165 google::generate_google_page_html(&page)
166 } else {
167 google::generate_google_home_html()
168 };
169 return Some(html);
170 } else if youtube::is_youtube_host(current_host) {
171 crate::info!("[NET] YouTube offline player: host={}, path={}", current_host, current_path);
172 let full_url = alloc::format!("{}{}{}", if current_is_https { "https://" } else { "http://" }, current_host, current_path);
173 let html = match youtube::parse_youtube_url(&full_url) {
174 Some(youtube::YouTubeUrlType::Watch(id)) => {
175 let info = youtube::get_video_info_by_id(&id);
176 youtube::generate_youtube_watch_html(&id, &info.title, &info.description)
177 }
178 Some(youtube::YouTubeUrlType::Embed(id)) => {
179 let info = youtube::get_video_info_by_id(&id);
180 youtube::generate_youtube_embed_html(&id, &info.title)
181 }
182 Some(youtube::YouTubeUrlType::Shorts(id)) => {
183 let info = youtube::get_video_info_by_id(&id);
184 youtube::generate_youtube_shorts_html(&id, &info.title, &info.channel_name)
185 }
186 Some(youtube::YouTubeUrlType::Search(q)) => {
187 youtube::generate_youtube_search_results_html(&q)
188 }
189 _ => {
190 youtube::generate_youtube_home_html()
191 }
192 };
193 return Some(html);
194 }
195 None
196 }
197
198 fn rewrite_response(&self, current_host: &str, current_path: &str, current_is_https: bool, body: String) -> String {
200 if duckduckgo::is_duckduckgo_host(current_host) {
201 let variant = duckduckgo::detect_variant_from_host(current_host);
202 let full_url = alloc::format!(
203 "{}{}{}",
204 if current_is_https { "https://" } else { "http://" },
205 current_host,
206 current_path
207 );
208 let url_type = duckduckgo::parse_duckduckgo_url(&full_url);
209 match url_type {
210 Some(duckduckgo::DuckDuckGoUrlType::Search { query, offset, category, .. }) => {
211 let page = duckduckgo::parse_duckduckgo_page(&body, &query, variant, offset, category);
212 crate::info!(
213 "[NET] DuckDuckGo search page parsed: {} items found for query '{}' [{}]",
214 page.results.len(),
215 query,
216 category.as_str()
217 );
218 duckduckgo::generate_duckduckgo_page_html(&page)
219 }
220 Some(duckduckgo::DuckDuckGoUrlType::Home(_)) => {
221 if body.trim().is_empty() || body.len() < 300 {
222 duckduckgo::generate_duckduckgo_home_html(variant)
223 } else {
224 body
225 }
226 }
227 _ => {
228 let items = duckduckgo::parse_duckduckgo_results(&body);
229 if !items.is_empty() {
230 duckduckgo::generate_duckduckgo_results_html("DuckDuckGo Search", &items, 0, variant)
231 } else {
232 body
233 }
234 }
235 }
236 } else if google::is_google_host(current_host) {
237 let full_url = alloc::format!(
238 "{}{}{}",
239 if current_is_https { "https://" } else { "http://" },
240 current_host,
241 current_path
242 );
243 let url_type = google::parse_google_url(&full_url);
244 match url_type {
245 Some(google::GoogleUrlType::Search { query, start }) => {
246 let page = google::parse_google_page(&body, &query, start);
247 crate::info!(
248 "[NET] Google search page parsed: {} items found for query '{}'",
249 page.results.len(),
250 query
251 );
252 google::generate_google_page_html(&page)
253 }
254 Some(google::GoogleUrlType::Home) => {
255 if body.trim().is_empty() || body.len() < 300 {
256 google::generate_google_home_html()
257 } else {
258 body
259 }
260 }
261 Some(google::GoogleUrlType::Redirect { target_url }) => {
262 alloc::format!(
263 r#"<html><head><meta http-equiv="refresh" content="0; url={}"></head><body><p>Redirecting to <a href="{}">{}</a>...</p></body></html>"#,
264 target_url, target_url, target_url
265 )
266 }
267 _ => {
268 let items = google::parse_google_results(&body);
269 if !items.is_empty() {
270 let page = google::GoogleSearchPage {
271 query: String::from("Google Search"),
272 start_offset: 0,
273 total_results_text: alloc::format!("約 {} 件", items.len()),
274 search_time_sec: String::from("0.18"),
275 results: items,
276 knowledge: None,
277 related_searches: alloc::vec![],
278 };
279 google::generate_google_page_html(&page)
280 } else {
281 body
282 }
283 }
284 }
285 } else if youtube::is_youtube_host(current_host) {
286 if body.len() >= 300 && !body.trim().is_empty() {
287 body.replace("html5_bandaid_attach_content_po_token\\u003dtrue", "html5_bandaid_attach_content_po_token\\u003dfalse")
295 .replace("html5_bandaid_attach_content_po_token=true", "html5_bandaid_attach_content_po_token=false")
296 .replace("\"html5_bandaid_attach_content_po_token\":true", "\"html5_bandaid_attach_content_po_token\":false")
297 .replace("html5_generate_content_po_token\\u003dtrue", "html5_generate_content_po_token\\u003dfalse")
298 .replace("html5_generate_content_po_token=true", "html5_generate_content_po_token=false")
299 .replace("\"html5_generate_content_po_token\":true", "\"html5_generate_content_po_token\":false")
300 .replace("html5_use_shared_owl_instance\\u003dtrue", "html5_use_shared_owl_instance\\u003dfalse")
301 .replace("html5_use_shared_owl_instance=true", "html5_use_shared_owl_instance=false")
302 .replace("\"html5_use_shared_owl_instance\":true", "\"html5_use_shared_owl_instance\":false")
303 .replace("html5_webpo_idle_priority_job\\u003dtrue", "html5_webpo_idle_priority_job\\u003dfalse")
304 .replace("html5_webpo_idle_priority_job=true", "html5_webpo_idle_priority_job=false")
305 .replace("\"html5_webpo_idle_priority_job\":true", "\"html5_webpo_idle_priority_job\":false")
306 } else {
307 let full_url = alloc::format!(
310 "{}{}{}",
311 if current_is_https { "https://" } else { "http://" },
312 current_host,
313 current_path
314 );
315 let parsed_yt = youtube::parse_youtube_url(&full_url);
316 match parsed_yt {
317 Some(youtube::YouTubeUrlType::Watch(id)) => {
318 let info = youtube::get_video_info_by_id(&id);
319 youtube::generate_youtube_watch_html(&id, &info.title, &info.description)
320 }
321 Some(youtube::YouTubeUrlType::Embed(id)) => {
322 let info = youtube::get_video_info_by_id(&id);
323 youtube::generate_youtube_embed_html(&id, &info.title)
324 }
325 Some(youtube::YouTubeUrlType::Shorts(id)) => {
326 let info = youtube::get_video_info_by_id(&id);
327 youtube::generate_youtube_shorts_html(&id, &info.title, &info.channel_name)
328 }
329 Some(youtube::YouTubeUrlType::Search(q)) => {
330 youtube::generate_youtube_search_results_html(&q)
331 }
332 _ => {
333 youtube::generate_youtube_home_html()
334 }
335 }
336 }
337 } else {
338 body
339 }
340 }
341
342 fn load_failed_page(&self, current_host: &str, current_path: &str, current_is_https: bool, e: &str) -> Option<String> {
344 if google::is_google_host(current_host) {
345 crate::warn!("[NET] BROWSER_LOADER: Google load failed ({}), falling back to internal engine", e);
346 let full_url = alloc::format!(
347 "{}{}{}",
348 if current_is_https { "https://" } else { "http://" },
349 current_host,
350 current_path
351 );
352 let fallback_html = match google::parse_google_url(&full_url) {
353 Some(google::GoogleUrlType::Search { query, start }) => {
354 let results = google::get_mock_google_results(&query);
355 let knowledge = google::parse_google_knowledge_card("", &query);
356 let page = google::GoogleSearchPage {
357 query: query.clone(),
358 start_offset: start,
359 total_results_text: String::from("約 1,230,000 件"),
360 search_time_sec: String::from("0.28"),
361 results,
362 knowledge,
363 related_searches: alloc::vec![
364 alloc::format!("{} 使い方", query),
365 alloc::format!("{} 入門", query),
366 alloc::format!("{} 最新情報", query),
367 alloc::format!("{} AtmOS", query),
368 ],
369 };
370 google::generate_google_page_html(&page)
371 }
372 Some(google::GoogleUrlType::Redirect { target_url }) => {
373 alloc::format!(
374 r#"<html><body><p>Redirecting to <a href="{}">{}</a></p></body></html>"#,
375 target_url, target_url
376 )
377 }
378 _ => {
379 google::generate_google_home_html()
380 }
381 };
382 Some(fallback_html)
383 } else if youtube::is_youtube_host(current_host) {
384 crate::warn!("[NET] BROWSER_LOADER: YouTube load failed ({}), falling back to internal player", e);
385 let full_url = alloc::format!(
386 "{}{}{}",
387 if current_is_https { "https://" } else { "http://" },
388 current_host,
389 current_path
390 );
391 let fallback_html = match youtube::parse_youtube_url(&full_url) {
392 Some(youtube::YouTubeUrlType::Watch(id)) => {
393 let info = youtube::get_video_info_by_id(&id);
394 youtube::generate_youtube_watch_html(&id, &info.title, &info.description)
395 }
396 Some(youtube::YouTubeUrlType::Embed(id)) => {
397 let info = youtube::get_video_info_by_id(&id);
398 youtube::generate_youtube_embed_html(&id, &info.title)
399 }
400 Some(youtube::YouTubeUrlType::Shorts(id)) => {
401 let info = youtube::get_video_info_by_id(&id);
402 youtube::generate_youtube_shorts_html(&id, &info.title, &info.channel_name)
403 }
404 Some(youtube::YouTubeUrlType::Search(q)) => {
405 youtube::generate_youtube_search_results_html(&q)
406 }
407 _ => {
408 youtube::generate_youtube_home_html()
409 }
410 };
411 Some(fallback_html)
412 } else {
413 None
414 }
415 }
416
417 fn patch_script(&self, url: &str, s: &mut String) {
419 ytpatch::patch_script(url, s);
420 }
421
422 fn load_settle_ms(&self, host: &str) -> Option<u64> {
429 if youtube::is_youtube_host(host) { Some(3000) } else { None }
430 }
431
432 fn is_dark_host(&self, host: &str) -> bool {
433 youtube::is_youtube_host(host)
435 }
436
437 fn page_tick(&self, url_with_hash: &str, frame_depth: u32, js: &mut dyn core::any::Any) {
442 let Some(js) = js.downcast_mut::<crate::os_lib::ecma::JsRuntime>() else { return };
443 static LAST_MS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
444 if frame_depth != 0 || !url_with_hash.contains("youtube.com/watch") {
445 return;
446 }
447 let now = crate::kernel::timer::get_system_time_ms();
448 if now.saturating_sub(LAST_MS.load(core::sync::atomic::Ordering::Relaxed)) < 15_000 {
449 return;
450 }
451 LAST_MS.store(now, core::sync::atomic::Ordering::Relaxed);
452 const PROBE: &str = "(function(){try{var w=window,s='';\
454 for(var k in w){if(k.indexOf('havuokmhhs')===0||k==='bevasrsg'){var g=w[k];\
455 s+=' '+k+'{bevasrs='+(g?typeof g.bevasrs:'-')+' nqfbel='+(g&&g.nqfbel?g.nqfbel.length:'-')+'}';\
456 var b=g&&g.bevasrs;if(b&&!w.__atmosAtt){w.__atmosAtt={bg:'wait',mint:'wait'};var o=w.__atmosAtt;\
457 var es=function(e){return e&&(e.code!==undefined?'code='+e.code+' ':'')+(e&&e.message||String(e))};\
458 if(b.p&&b.p.then)b.p.then(function(){o.bg='ready'},function(e){o.bg='err '+es(e)});else o.bg='no-p';\
459 if(b.wpc)b.wpc().then(function(m){m.f().then(function(){o.mint='ready'},function(e){o.mint='err '+es(e)})},\
460 function(e){o.mint='wpc-err '+es(e)});else o.mint='no-wpc'}}}\
461 if(w.__atmosAtt)s+=' bg='+w.__atmosAtt.bg+' mint='+w.__atmosAtt.mint;\
462 var d=w['havuokmhhs-'+Math.floor(performance.timeOrigin)];\
463 s+=' direct{'+(d?('bevasrs='+typeof d.bevasrs+' nqfbel='+(d.nqfbel?d.nqfbel.length:'-')):'undefined')+'}';\
464 return 'timeOrigin='+Math.floor(performance.timeOrigin)+' ytAtRC='+typeof w.ytAtRC\
465 +' trayride='+typeof w.trayride+' bgevmc='+typeof w.bgevmc+' slots:'+(s||' none')\
466 +' idle='+(typeof w.__atmosIdleCount==='function'?w.__atmosIdleCount():'-')\
467 +' whenDefined:'+Object.keys((w.customElements&&w.customElements._when_defined)||{}).join(',').slice(0,400)\
468 +' pend20s: '+(typeof w.__atmosPromiseDiag==='function'?w.__atmosPromiseDiag(20000).slice(0,1500):'-')}catch(e){return 'err '+e}})()";
469 match crate::os_lib::ecma::eval(PROBE, js) {
470 Ok(v) => crate::warn!("[ATT][PROBE] t={}s {}", now / 1000, v.to_js_string()),
471 Err(e) => crate::warn!("[ATT][PROBE] 評価に失敗: {}", e),
472 }
473 let timers: alloc::vec::Vec<(u64, Option<u64>, alloc::string::String)> = {
475 let q = js.macrotasks.borrow();
476 let mut v: alloc::vec::Vec<_> = q
477 .iter()
478 .map(|t| {
479 let src = match &t.cb {
480 crate::os_lib::ecma::value::Value::Object(o) => match &o.borrow().kind {
481 crate::os_lib::ecma::value::ObjKind::Function(f) => f
482 .body()
483 .source_head(70)
484 .unwrap_or_else(|| alloc::string::String::from("?")),
485 _ => alloc::string::String::from("native"),
486 },
487 _ => alloc::string::String::from("-"),
488 };
489 (t.due_ms, t.period_ms, src)
490 })
491 .collect();
492 v.sort_by_key(|x| x.0);
493 v
494 };
495 let now_ms = crate::kernel::timer::get_system_time_ms();
496 let mut line = alloc::format!("n={}", timers.len());
497 for (due, per, src) in timers.iter().take(8) {
498 line.push_str(&alloc::format!(" | in={}ms per={:?} {}", due.saturating_sub(now_ms) as i64, per, src));
499 }
500 crate::warn!("[ATT][TIMERS] {}", line);
501 }
502
503 fn initial_page(&self) -> (&'static str, &'static str) {
505 ("duckduckgo.com", "DuckDuckGo")
506 }
507
508 fn resolve_redirect_link(&self, href: &str) -> Option<String> {
510 duckduckgo::extract_direct_url_from_uddg(href)
512 }
513
514 fn default_bookmarks(&self) -> Vec<(&'static str, &'static str)> {
518 pure::default_bookmarks()
519 }
520
521 fn omnibox_prefix_suggestion(&self, q: &str) -> Option<(String, String)> {
523 pure::omnibox_prefix_suggestion(q)
524 }
525
526 fn search_suggestion_url(&self, s: &str) -> String {
528 pure::search_suggestion_url(s)
529 }
530
531 fn navigate_shortcut(&self, input: &str) -> Option<(String, String)> {
533 pure::navigate_shortcut(input)
534 }
535
536 fn default_search(&self, input: &str) -> Option<(String, String)> {
538 pure::default_search(input)
539 }
540
541 fn search_suggestions(&self, text: &str) -> Vec<String> {
543 pure::search_suggestions(text)
544 }
545
546 fn media_stream_begin(&self) {
550 sabr::set_sabr_transport(Some(default_sabr_transport));
551 }
552
553 fn media_stream_end(&self) {
555 sabr::set_sabr_transport(None);
556 }
557
558 fn media_stream_playback_head(&self, ms: u64) {
560 if let Some(ref mut session) = *sabr::GLOBAL_SABR_SESSION.lock() {
561 session.update_playback_head(ms);
562 }
563 }
564
565 fn media_stream_refill(&self, ms_id: usize) -> bool {
567 sabr::trigger_sabr_auto_refill(ms_id)
568 }
569
570 fn map_embed(&self, url: &str) -> Option<crate::os_lib::web_engine::embed_map::Embed> {
574 osm::parse_embed_url(url)
575 }
576
577 fn map_tile_url(&self, z: u32, x: i64, y: i64) -> String {
579 osm::osm_tile_url(z, x, y)
580 }
581}
582
583fn default_sabr_transport(url: &str, body: &[u8]) -> Result<alloc::vec::Vec<u8>, &'static str> {
587 let effective_url = sabr::normalize_sabr_url(url);
588 let (is_https, host, path) = match sabr::parse_url_host_path(&effective_url) {
589 Some(t) => t,
590 None => return Err("invalid SABR URL"),
591 };
592
593 let _exempt = crate::kernel::sync_fetch::begin_exempt(&host, &path);
596 let stack = crate::kernel::net_stack::TcpIpStack::new();
597 let mut hdrs = alloc::vec![
598 ("Content-Type", "application/x-protobuf"),
599 ("Origin", "https://www.youtube.com"),
600 ("Referer", "https://www.youtube.com/"),
601 ("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"),
602 ];
603
604 let cookie_str = crate::os_lib::web_apis::builtins::cookie_string();
605 if !cookie_str.is_empty() {
606 hdrs.push(("Cookie", &cookie_str));
607 }
608
609 let resp = match stack.web_request(is_https, &host, &path, "POST", "application/x-protobuf", body, &hdrs) {
610 Ok(r) => r,
611 Err(_) => return Err("tcp web_request failed"),
612 };
613 if resp.status_code >= 200 && resp.status_code < 300 {
614 Ok(resp.body_bytes)
615 } else {
616 Err("SABR HTTP status not 2xx")
617 }
618}
619
620