| 1 | use std::path::Path; |
| 2 | use std::process::{Command, Stdio}; |
| 3 | |
| 4 | use crate::config::{Config, Engine, Platform}; |
| 5 | use crate::error::BrowserError; |
| 6 | |
| 7 | #[derive(Debug, Clone)] |
| 8 | pub struct LaunchRequest { |
| 9 | pub headless: bool, |
| 10 | pub start_urls: Vec<String>, |
| 11 | } |
| 12 | |
| 13 | pub trait Launcher: Send + Sync { |
| 14 | fn spawn(&self, request: &LaunchRequest) -> Result<(), BrowserError>; |
| 15 | fn kill_listener(&self, port: u16) -> Result<(), BrowserError>; |
| 16 | |
| 17 | /// Lets the browser on `port` quit cleanly and returns once it is gone. |
| 18 | fn terminate_listener(&self, port: u16) -> Result<(), BrowserError> { |
| 19 | self.kill_listener(port) |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | pub struct ArgumentSpec<'a> { |
| 24 | pub port: u16, |
| 25 | pub profile: &'a str, |
| 26 | pub headless: bool, |
| 27 | pub user_agent: &'a str, |
| 28 | pub start_urls: &'a [String], |
| 29 | } |
| 30 | |
| 31 | const HEADLESS_MEMORY_FLAGS: [&str; 10] = [ |
| 32 | "--disable-features=Translate,MediaRouter,OptimizationHints,WebUIOmniboxPopup,WebUIOmniboxAimPopup", |
| 33 | "--disable-background-networking", |
| 34 | "--disable-component-update", |
| 35 | "--disable-component-extensions-with-background-pages", |
| 36 | "--disable-default-apps", |
| 37 | "--disable-sync", |
| 38 | "--disable-breakpad", |
| 39 | "--disable-client-side-phishing-detection", |
| 40 | "--disable-extensions", |
| 41 | "--disable-gpu", |
| 42 | ]; |
| 43 | |
| 44 | pub fn chrome_arguments(spec: &ArgumentSpec) -> Vec<String> { |
| 45 | let mut arguments = vec![ |
| 46 | format!("--remote-debugging-port={}", spec.port), |
| 47 | format!("--user-data-dir={}", spec.profile), |
| 48 | "--no-first-run".into(), |
| 49 | "--no-default-browser-check".into(), |
| 50 | ]; |
| 51 | if spec.headless { |
| 52 | arguments.extend([ |
| 53 | "--headless=new".into(), |
| 54 | format!("--user-agent={}", spec.user_agent), |
| 55 | "--window-size=1400,1000".into(), |
| 56 | ]); |
| 57 | arguments.extend(HEADLESS_MEMORY_FLAGS.iter().map(|flag| (*flag).to_owned())); |
| 58 | } |
| 59 | arguments.extend(spec.start_urls.iter().cloned()); |
| 60 | arguments |
| 61 | } |
| 62 | |
| 63 | /// Firefox keeps its own user agent: headless Firefox does not mark itself, so Microsoft accepts it. |
| 64 | pub fn firefox_arguments(spec: &ArgumentSpec) -> Vec<String> { |
| 65 | let mut arguments = vec![ |
| 66 | format!("--remote-debugging-port={}", spec.port), |
| 67 | "--profile".into(), |
| 68 | spec.profile.into(), |
| 69 | "--no-remote".into(), |
| 70 | ]; |
| 71 | if spec.headless { |
| 72 | arguments.extend(["--headless".into(), "--window-size=1400,1000".into()]); |
| 73 | } |
| 74 | arguments.extend(spec.start_urls.iter().cloned()); |
| 75 | arguments |
| 76 | } |
| 77 | |
| 78 | /// Prefs for the app's own Firefox profile: no first-run pages, no restored tabs, no quit prompts, |
| 79 | /// no Safe Mode. |
| 80 | const FIREFOX_PREFS: &str = r#"user_pref("browser.shell.checkDefaultBrowser", false); |
| 81 | user_pref("browser.startup.homepage_override.mstone", "ignore"); |
| 82 | user_pref("browser.startup.page", 0); |
| 83 | user_pref("browser.aboutwelcome.enabled", false); |
| 84 | user_pref("browser.sessionstore.resume_from_crash", false); |
| 85 | user_pref("browser.tabs.warnOnClose", false); |
| 86 | user_pref("browser.warnOnQuit", false); |
| 87 | user_pref("datareporting.policy.dataSubmissionPolicyBypassNotification", true); |
| 88 | user_pref("toolkit.telemetry.reportingpolicy.firstRun", false); |
| 89 | // A browser the app stopped hard counts as a startup crash; Safe Mode would hang a headless start. |
| 90 | user_pref("toolkit.startup.max_resumed_crashes", -1); |
| 91 | user_pref("zen.welcome-screen.seen", true); |
| 92 | "#; |
| 93 | |
| 94 | fn write_firefox_prefs(profile: &str) -> std::io::Result<()> { |
| 95 | std::fs::create_dir_all(profile)?; |
| 96 | std::fs::write(Path::new(profile).join("user.js"), FIREFOX_PREFS) |
| 97 | } |
| 98 | |
| 99 | pub fn user_agent(platform: Platform, major: u32) -> String { |
| 100 | let system = match platform { |
| 101 | Platform::Linux => "X11; Linux x86_64", |
| 102 | Platform::Macos => "Macintosh; Intel Mac OS X 10_15_7", |
| 103 | Platform::Windows | Platform::Wsl => "Windows NT 10.0; Win64; x64", |
| 104 | }; |
| 105 | format!( |
| 106 | "Mozilla/5.0 ({system}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36" |
| 107 | ) |
| 108 | } |
| 109 | |
| 110 | pub(crate) fn major_from_directory_names<'a>(names: impl Iterator<Item = &'a str>) -> Option<u32> { |
| 111 | names |
| 112 | .filter_map(|name| { |
| 113 | let parts: Vec<&str> = name.split('.').collect(); |
| 114 | let numeric = parts.len() == 4 && parts.iter().all(|part| part.parse::<u32>().is_ok()); |
| 115 | numeric.then(|| parts[0].parse::<u32>().ok())? |
| 116 | }) |
| 117 | .max() |
| 118 | } |
| 119 | |
| 120 | /// The Chromium major from `--version`. Forks print their own version first, as in |
| 121 | /// "Helium 0.21.3.1 (Chromium 157.0.8103.78)", so the highest major wins. |
| 122 | pub(crate) fn major_from_version_output(output: &str) -> Option<u32> { |
| 123 | output |
| 124 | .split(|character: char| character.is_whitespace() || character == '(' || character == ')') |
| 125 | .filter(|word| word.contains('.')) |
| 126 | .filter_map(|word| word.split('.').next()?.parse::<u32>().ok()) |
| 127 | .max() |
| 128 | } |
| 129 | |
| 130 | const FALLBACK_MAJOR: u32 = 150; |
| 131 | |
| 132 | /// Marker directory used by `app_base::linux_fonts::hide_system_color_emoji`. |
| 133 | /// Only that app-generated conf must be cleared for Chrome; a user-provided |
| 134 | /// `FONTCONFIG_FILE` / `FONTCONFIG_PATH` stays inherited. |
| 135 | const APP_EMOJI_FONTCONFIG_MARKER: &str = "fontconfig-emoji"; |
| 136 | |
| 137 | fn is_app_emoji_fontconfig(value: &std::ffi::OsStr) -> bool { |
| 138 | std::path::Path::new(value) |
| 139 | .components() |
| 140 | .any(|component| component.as_os_str() == APP_EMOJI_FONTCONFIG_MARKER) |
| 141 | } |
| 142 | |
| 143 | fn strip_app_fontconfig(command: &mut Command) { |
| 144 | for key in app_fontconfig_keys(|key| std::env::var_os(key)) { |
| 145 | command.env_remove(key); |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | fn app_fontconfig_keys(lookup: impl Fn(&str) -> Option<std::ffi::OsString>) -> Vec<&'static str> { |
| 150 | ["FONTCONFIG_FILE", "FONTCONFIG_PATH"] |
| 151 | .into_iter() |
| 152 | .filter(|key| lookup(key).is_some_and(|value| is_app_emoji_fontconfig(&value))) |
| 153 | .collect() |
| 154 | } |
| 155 | |
| 156 | fn chrome_major(platform: Platform, executable: &Path) -> u32 { |
| 157 | let detected = match platform { |
| 158 | Platform::Linux | Platform::Macos => { |
| 159 | let mut command = crate::host::command(executable); |
| 160 | strip_app_fontconfig(&mut command); |
| 161 | command.arg("--version").output().ok().and_then(|output| { |
| 162 | major_from_version_output(&String::from_utf8_lossy(&output.stdout)) |
| 163 | }) |
| 164 | } |
| 165 | Platform::Windows | Platform::Wsl => executable |
| 166 | .parent() |
| 167 | .and_then(|parent| std::fs::read_dir(parent).ok()) |
| 168 | .and_then(|entries| { |
| 169 | let names: Vec<String> = entries |
| 170 | .flatten() |
| 171 | .map(|entry| entry.file_name().to_string_lossy().into_owned()) |
| 172 | .collect(); |
| 173 | major_from_directory_names(names.iter().map(String::as_str)) |
| 174 | }), |
| 175 | }; |
| 176 | detected.unwrap_or(FALLBACK_MAJOR) |
| 177 | } |
| 178 | |
| 179 | pub struct SystemLauncher { |
| 180 | config: Config, |
| 181 | } |
| 182 | |
| 183 | impl SystemLauncher { |
| 184 | pub fn new(config: Config) -> SystemLauncher { |
| 185 | SystemLauncher { config } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | impl Launcher for SystemLauncher { |
| 190 | fn spawn(&self, request: &LaunchRequest) -> Result<(), BrowserError> { |
| 191 | let executable = self.config.executable()?; |
| 192 | let arguments = match self.config.engine { |
| 193 | Engine::Chromium => { |
| 194 | let agent = user_agent( |
| 195 | self.config.platform, |
| 196 | chrome_major(self.config.platform, &executable), |
| 197 | ); |
| 198 | chrome_arguments(&ArgumentSpec { |
| 199 | port: self.config.port, |
| 200 | profile: &self.config.profile, |
| 201 | headless: request.headless, |
| 202 | user_agent: &agent, |
| 203 | start_urls: &request.start_urls, |
| 204 | }) |
| 205 | } |
| 206 | Engine::Firefox => { |
| 207 | write_firefox_prefs(&self.config.profile)?; |
| 208 | firefox_arguments(&ArgumentSpec { |
| 209 | port: self.config.port, |
| 210 | profile: &self.config.profile, |
| 211 | headless: request.headless, |
| 212 | user_agent: "", |
| 213 | start_urls: &request.start_urls, |
| 214 | }) |
| 215 | } |
| 216 | }; |
| 217 | let mut command = crate::host::command(&executable); |
| 218 | strip_app_fontconfig(&mut command); |
| 219 | command |
| 220 | .args(arguments) |
| 221 | .stdin(Stdio::null()) |
| 222 | .stdout(Stdio::null()) |
| 223 | .stderr(Stdio::null()); |
| 224 | if self.config.platform == Platform::Wsl { |
| 225 | command.current_dir("/mnt/c"); |
| 226 | } |
| 227 | detach(&mut command); |
| 228 | let mut child = command.spawn()?; |
| 229 | std::thread::spawn(move || { |
| 230 | let _ = child.wait(); |
| 231 | }); |
| 232 | Ok(()) |
| 233 | } |
| 234 | |
| 235 | fn kill_listener(&self, port: u16) -> Result<(), BrowserError> { |
| 236 | crate::process::kill_listener(self.config.platform, port) |
| 237 | } |
| 238 | |
| 239 | fn terminate_listener(&self, port: u16) -> Result<(), BrowserError> { |
| 240 | crate::process::terminate_listener(self.config.platform, port) |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | #[cfg(unix)] |
| 245 | fn detach(command: &mut Command) { |
| 246 | use std::os::unix::process::CommandExt; |
| 247 | command.process_group(0); |
| 248 | } |
| 249 | |
| 250 | #[cfg(windows)] |
| 251 | fn detach(command: &mut Command) { |
| 252 | use std::os::windows::process::CommandExt; |
| 253 | const DETACHED_PROCESS: u32 = 0x0000_0008; |
| 254 | const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; |
| 255 | command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP); |
| 256 | } |
| 257 | |
| 258 | #[cfg(test)] |
| 259 | mod tests { |
| 260 | use super::*; |
| 261 | |
| 262 | fn spec<'a>(headless: bool, urls: &'a [String]) -> ArgumentSpec<'a> { |
| 263 | ArgumentSpec { |
| 264 | port: 9222, |
| 265 | profile: r"C:\p\rusty-teams-chrome", |
| 266 | headless, |
| 267 | user_agent: "UA", |
| 268 | start_urls: urls, |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | #[test] |
| 273 | fn headless_arguments() { |
| 274 | let urls = vec!["https://teams.cloud.microsoft/".to_owned()]; |
| 275 | let arguments = chrome_arguments(&spec(true, &urls)); |
| 276 | assert_eq!( |
| 277 | &arguments[..7], |
| 278 | [ |
| 279 | "--remote-debugging-port=9222", |
| 280 | r"--user-data-dir=C:\p\rusty-teams-chrome", |
| 281 | "--no-first-run", |
| 282 | "--no-default-browser-check", |
| 283 | "--headless=new", |
| 284 | "--user-agent=UA", |
| 285 | "--window-size=1400,1000", |
| 286 | ] |
| 287 | ); |
| 288 | assert_eq!(&arguments[7..17], HEADLESS_MEMORY_FLAGS); |
| 289 | assert_eq!(arguments[17], "https://teams.cloud.microsoft/"); |
| 290 | assert!( |
| 291 | !arguments |
| 292 | .iter() |
| 293 | .any(|argument| argument == "--process-per-site") |
| 294 | ); |
| 295 | } |
| 296 | |
| 297 | #[test] |
| 298 | fn visible_arguments_have_no_headless_flags_and_all_urls() { |
| 299 | let urls = vec!["https://a/".to_owned(), "https://b/".to_owned()]; |
| 300 | let arguments = chrome_arguments(&spec(false, &urls)); |
| 301 | assert!( |
| 302 | !arguments |
| 303 | .iter() |
| 304 | .any(|argument| argument.contains("headless") || argument.contains("user-agent")) |
| 305 | ); |
| 306 | assert_eq!(&arguments[4..], ["https://a/", "https://b/"]); |
| 307 | } |
| 308 | |
| 309 | #[test] |
| 310 | fn firefox_arguments_use_bidi_port_own_profile_and_no_user_agent() { |
| 311 | let urls = vec!["https://teams.cloud.microsoft/".to_owned()]; |
| 312 | let headless = firefox_arguments(&spec(true, &urls)); |
| 313 | assert_eq!( |
| 314 | headless, |
| 315 | [ |
| 316 | "--remote-debugging-port=9222", |
| 317 | "--profile", |
| 318 | r"C:\p\rusty-teams-chrome", |
| 319 | "--no-remote", |
| 320 | "--headless", |
| 321 | "--window-size=1400,1000", |
| 322 | "https://teams.cloud.microsoft/", |
| 323 | ] |
| 324 | ); |
| 325 | let visible = firefox_arguments(&spec(false, &urls)); |
| 326 | assert!(!visible.iter().any(|argument| argument.contains("headless"))); |
| 327 | } |
| 328 | |
| 329 | #[test] |
| 330 | fn user_agents_per_platform() { |
| 331 | assert!(user_agent(Platform::Wsl, 154).contains("Windows NT 10.0; Win64; x64")); |
| 332 | assert!(user_agent(Platform::Windows, 154).contains("Chrome/154.0.0.0")); |
| 333 | assert!(user_agent(Platform::Linux, 140).contains("X11; Linux x86_64")); |
| 334 | assert!(user_agent(Platform::Macos, 154).contains("Macintosh; Intel Mac OS X 10_15_7")); |
| 335 | assert!(user_agent(Platform::Macos, 154).contains("Chrome/154.0.0.0")); |
| 336 | assert!(!user_agent(Platform::Macos, 154).contains("Windows NT")); |
| 337 | } |
| 338 | |
| 339 | #[test] |
| 340 | fn major_from_version_directories() { |
| 341 | let names = [ |
| 342 | "154.0.8037.98", |
| 343 | "153.0.1.2", |
| 344 | "Dictionaries", |
| 345 | "chrome.exe", |
| 346 | "1.2.3", |
| 347 | ]; |
| 348 | assert_eq!(major_from_directory_names(names.into_iter()), Some(154)); |
| 349 | assert_eq!(major_from_directory_names(["x"].into_iter()), None); |
| 350 | } |
| 351 | |
| 352 | #[test] |
| 353 | fn major_from_version_text() { |
| 354 | assert_eq!( |
| 355 | major_from_version_output("Google Chrome 154.0.8037.98 \n"), |
| 356 | Some(154) |
| 357 | ); |
| 358 | assert_eq!( |
| 359 | major_from_version_output("Chromium 131.0.6778.85 snap"), |
| 360 | Some(131) |
| 361 | ); |
| 362 | assert_eq!( |
| 363 | major_from_version_output("Helium 0.21.3.1 (Chromium 157.0.8103.78)\n"), |
| 364 | Some(157) |
| 365 | ); |
| 366 | assert_eq!(major_from_version_output("nothing"), None); |
| 367 | } |
| 368 | |
| 369 | #[test] |
| 370 | fn chrome_drops_only_app_emoji_fontconfig() { |
| 371 | let keys = app_fontconfig_keys(|key| match key { |
| 372 | "FONTCONFIG_FILE" => Some("/tmp/cache/fontconfig-emoji/fonts.conf".into()), |
| 373 | "FONTCONFIG_PATH" => Some("/etc/fonts".into()), |
| 374 | _ => None, |
| 375 | }); |
| 376 | assert_eq!(keys, vec!["FONTCONFIG_FILE"]); |
| 377 | assert!(app_fontconfig_keys(|_| None).is_empty()); |
| 378 | } |
| 379 | } |