| 1 | use std::path::Path; |
| 2 | use std::process::{Command, Stdio}; |
| 3 | |
| 4 | use crate::config::{Config, 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 | |
| 18 | pub struct ArgumentSpec<'a> { |
| 19 | pub port: u16, |
| 20 | pub profile: &'a str, |
| 21 | pub headless: bool, |
| 22 | pub user_agent: &'a str, |
| 23 | pub start_urls: &'a [String], |
| 24 | } |
| 25 | |
| 26 | const HEADLESS_MEMORY_FLAGS: [&str; 10] = [ |
| 27 | "--disable-features=Translate,MediaRouter,OptimizationHints,WebUIOmniboxPopup,WebUIOmniboxAimPopup", |
| 28 | "--disable-background-networking", |
| 29 | "--disable-component-update", |
| 30 | "--disable-component-extensions-with-background-pages", |
| 31 | "--disable-default-apps", |
| 32 | "--disable-sync", |
| 33 | "--disable-breakpad", |
| 34 | "--disable-client-side-phishing-detection", |
| 35 | "--disable-extensions", |
| 36 | "--disable-gpu", |
| 37 | ]; |
| 38 | |
| 39 | pub fn chrome_arguments(spec: &ArgumentSpec) -> Vec<String> { |
| 40 | let mut arguments = vec![ |
| 41 | format!("--remote-debugging-port={}", spec.port), |
| 42 | format!("--user-data-dir={}", spec.profile), |
| 43 | "--no-first-run".into(), |
| 44 | "--no-default-browser-check".into(), |
| 45 | ]; |
| 46 | if spec.headless { |
| 47 | arguments.extend([ |
| 48 | "--headless=new".into(), |
| 49 | format!("--user-agent={}", spec.user_agent), |
| 50 | "--window-size=1400,1000".into(), |
| 51 | ]); |
| 52 | arguments.extend(HEADLESS_MEMORY_FLAGS.iter().map(|flag| (*flag).to_owned())); |
| 53 | } |
| 54 | arguments.extend(spec.start_urls.iter().cloned()); |
| 55 | arguments |
| 56 | } |
| 57 | |
| 58 | pub fn user_agent(platform: Platform, major: u32) -> String { |
| 59 | let system = match platform { |
| 60 | Platform::Linux => "X11; Linux x86_64", |
| 61 | Platform::Macos => "Macintosh; Intel Mac OS X 10_15_7", |
| 62 | Platform::Windows | Platform::Wsl => "Windows NT 10.0; Win64; x64", |
| 63 | }; |
| 64 | format!( |
| 65 | "Mozilla/5.0 ({system}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36" |
| 66 | ) |
| 67 | } |
| 68 | |
| 69 | pub(crate) fn major_from_directory_names<'a>(names: impl Iterator<Item = &'a str>) -> Option<u32> { |
| 70 | names |
| 71 | .filter_map(|name| { |
| 72 | let parts: Vec<&str> = name.split('.').collect(); |
| 73 | let numeric = parts.len() == 4 && parts.iter().all(|part| part.parse::<u32>().is_ok()); |
| 74 | numeric.then(|| parts[0].parse::<u32>().ok())? |
| 75 | }) |
| 76 | .max() |
| 77 | } |
| 78 | |
| 79 | pub(crate) fn major_from_version_output(output: &str) -> Option<u32> { |
| 80 | output.split_whitespace().find_map(|word| { |
| 81 | word.split('.') |
| 82 | .next()? |
| 83 | .parse::<u32>() |
| 84 | .ok() |
| 85 | .filter(|_| word.contains('.')) |
| 86 | }) |
| 87 | } |
| 88 | |
| 89 | const FALLBACK_MAJOR: u32 = 150; |
| 90 | |
| 91 | /// Marker directory used by `app_base::linux_fonts::hide_system_color_emoji`. |
| 92 | /// Only that app-generated conf must be cleared for Chrome; a user-provided |
| 93 | /// `FONTCONFIG_FILE` / `FONTCONFIG_PATH` stays inherited. |
| 94 | const APP_EMOJI_FONTCONFIG_MARKER: &str = "fontconfig-emoji"; |
| 95 | |
| 96 | fn is_app_emoji_fontconfig(value: &std::ffi::OsStr) -> bool { |
| 97 | std::path::Path::new(value) |
| 98 | .components() |
| 99 | .any(|component| component.as_os_str() == APP_EMOJI_FONTCONFIG_MARKER) |
| 100 | } |
| 101 | |
| 102 | fn strip_app_fontconfig(command: &mut Command) { |
| 103 | for key in app_fontconfig_keys(|key| std::env::var_os(key)) { |
| 104 | command.env_remove(key); |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | fn app_fontconfig_keys(lookup: impl Fn(&str) -> Option<std::ffi::OsString>) -> Vec<&'static str> { |
| 109 | ["FONTCONFIG_FILE", "FONTCONFIG_PATH"] |
| 110 | .into_iter() |
| 111 | .filter(|key| lookup(key).is_some_and(|value| is_app_emoji_fontconfig(&value))) |
| 112 | .collect() |
| 113 | } |
| 114 | |
| 115 | fn chrome_major(platform: Platform, executable: &Path) -> u32 { |
| 116 | let detected = match platform { |
| 117 | Platform::Linux | Platform::Macos => { |
| 118 | let mut command = Command::new(executable); |
| 119 | strip_app_fontconfig(&mut command); |
| 120 | command.arg("--version").output().ok().and_then(|output| { |
| 121 | major_from_version_output(&String::from_utf8_lossy(&output.stdout)) |
| 122 | }) |
| 123 | } |
| 124 | Platform::Windows | Platform::Wsl => executable |
| 125 | .parent() |
| 126 | .and_then(|parent| std::fs::read_dir(parent).ok()) |
| 127 | .and_then(|entries| { |
| 128 | let names: Vec<String> = entries |
| 129 | .flatten() |
| 130 | .map(|entry| entry.file_name().to_string_lossy().into_owned()) |
| 131 | .collect(); |
| 132 | major_from_directory_names(names.iter().map(String::as_str)) |
| 133 | }), |
| 134 | }; |
| 135 | detected.unwrap_or(FALLBACK_MAJOR) |
| 136 | } |
| 137 | |
| 138 | pub struct SystemLauncher { |
| 139 | config: Config, |
| 140 | } |
| 141 | |
| 142 | impl SystemLauncher { |
| 143 | pub fn new(config: Config) -> SystemLauncher { |
| 144 | SystemLauncher { config } |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | impl Launcher for SystemLauncher { |
| 149 | fn spawn(&self, request: &LaunchRequest) -> Result<(), BrowserError> { |
| 150 | let executable = self.config.chrome_executable()?; |
| 151 | let agent = user_agent( |
| 152 | self.config.platform, |
| 153 | chrome_major(self.config.platform, &executable), |
| 154 | ); |
| 155 | let arguments = chrome_arguments(&ArgumentSpec { |
| 156 | port: self.config.port, |
| 157 | profile: &self.config.profile, |
| 158 | headless: request.headless, |
| 159 | user_agent: &agent, |
| 160 | start_urls: &request.start_urls, |
| 161 | }); |
| 162 | let mut command = Command::new(&executable); |
| 163 | strip_app_fontconfig(&mut command); |
| 164 | command |
| 165 | .args(arguments) |
| 166 | .stdin(Stdio::null()) |
| 167 | .stdout(Stdio::null()) |
| 168 | .stderr(Stdio::null()); |
| 169 | if self.config.platform == Platform::Wsl { |
| 170 | command.current_dir("/mnt/c"); |
| 171 | } |
| 172 | detach(&mut command); |
| 173 | let mut child = command.spawn()?; |
| 174 | std::thread::spawn(move || { |
| 175 | let _ = child.wait(); |
| 176 | }); |
| 177 | Ok(()) |
| 178 | } |
| 179 | |
| 180 | fn kill_listener(&self, port: u16) -> Result<(), BrowserError> { |
| 181 | crate::process::kill_listener(self.config.platform, port) |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | #[cfg(unix)] |
| 186 | fn detach(command: &mut Command) { |
| 187 | use std::os::unix::process::CommandExt; |
| 188 | command.process_group(0); |
| 189 | } |
| 190 | |
| 191 | #[cfg(windows)] |
| 192 | fn detach(command: &mut Command) { |
| 193 | use std::os::windows::process::CommandExt; |
| 194 | const DETACHED_PROCESS: u32 = 0x0000_0008; |
| 195 | const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; |
| 196 | command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP); |
| 197 | } |
| 198 | |
| 199 | #[cfg(test)] |
| 200 | mod tests { |
| 201 | use super::*; |
| 202 | |
| 203 | fn spec<'a>(headless: bool, urls: &'a [String]) -> ArgumentSpec<'a> { |
| 204 | ArgumentSpec { |
| 205 | port: 9222, |
| 206 | profile: r"C:\p\rusty-teams-chrome", |
| 207 | headless, |
| 208 | user_agent: "UA", |
| 209 | start_urls: urls, |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | #[test] |
| 214 | fn headless_arguments() { |
| 215 | let urls = vec!["https://teams.cloud.microsoft/".to_owned()]; |
| 216 | let arguments = chrome_arguments(&spec(true, &urls)); |
| 217 | assert_eq!( |
| 218 | &arguments[..7], |
| 219 | [ |
| 220 | "--remote-debugging-port=9222", |
| 221 | r"--user-data-dir=C:\p\rusty-teams-chrome", |
| 222 | "--no-first-run", |
| 223 | "--no-default-browser-check", |
| 224 | "--headless=new", |
| 225 | "--user-agent=UA", |
| 226 | "--window-size=1400,1000", |
| 227 | ] |
| 228 | ); |
| 229 | assert_eq!(&arguments[7..17], HEADLESS_MEMORY_FLAGS); |
| 230 | assert_eq!(arguments[17], "https://teams.cloud.microsoft/"); |
| 231 | assert!( |
| 232 | !arguments |
| 233 | .iter() |
| 234 | .any(|argument| argument == "--process-per-site") |
| 235 | ); |
| 236 | } |
| 237 | |
| 238 | #[test] |
| 239 | fn visible_arguments_have_no_headless_flags_and_all_urls() { |
| 240 | let urls = vec!["https://a/".to_owned(), "https://b/".to_owned()]; |
| 241 | let arguments = chrome_arguments(&spec(false, &urls)); |
| 242 | assert!( |
| 243 | !arguments |
| 244 | .iter() |
| 245 | .any(|argument| argument.contains("headless") || argument.contains("user-agent")) |
| 246 | ); |
| 247 | assert_eq!(&arguments[4..], ["https://a/", "https://b/"]); |
| 248 | } |
| 249 | |
| 250 | #[test] |
| 251 | fn user_agents_per_platform() { |
| 252 | assert!(user_agent(Platform::Wsl, 154).contains("Windows NT 10.0; Win64; x64")); |
| 253 | assert!(user_agent(Platform::Windows, 154).contains("Chrome/154.0.0.0")); |
| 254 | assert!(user_agent(Platform::Linux, 140).contains("X11; Linux x86_64")); |
| 255 | assert!(user_agent(Platform::Macos, 154).contains("Macintosh; Intel Mac OS X 10_15_7")); |
| 256 | assert!(user_agent(Platform::Macos, 154).contains("Chrome/154.0.0.0")); |
| 257 | assert!(!user_agent(Platform::Macos, 154).contains("Windows NT")); |
| 258 | } |
| 259 | |
| 260 | #[test] |
| 261 | fn major_from_version_directories() { |
| 262 | let names = [ |
| 263 | "154.0.8037.98", |
| 264 | "153.0.1.2", |
| 265 | "Dictionaries", |
| 266 | "chrome.exe", |
| 267 | "1.2.3", |
| 268 | ]; |
| 269 | assert_eq!(major_from_directory_names(names.into_iter()), Some(154)); |
| 270 | assert_eq!(major_from_directory_names(["x"].into_iter()), None); |
| 271 | } |
| 272 | |
| 273 | #[test] |
| 274 | fn major_from_version_text() { |
| 275 | assert_eq!( |
| 276 | major_from_version_output("Google Chrome 154.0.8037.98 \n"), |
| 277 | Some(154) |
| 278 | ); |
| 279 | assert_eq!( |
| 280 | major_from_version_output("Chromium 131.0.6778.85 snap"), |
| 281 | Some(131) |
| 282 | ); |
| 283 | assert_eq!(major_from_version_output("nothing"), None); |
| 284 | } |
| 285 | |
| 286 | #[test] |
| 287 | fn chrome_drops_only_app_emoji_fontconfig() { |
| 288 | let keys = app_fontconfig_keys(|key| match key { |
| 289 | "FONTCONFIG_FILE" => Some("/tmp/cache/fontconfig-emoji/fonts.conf".into()), |
| 290 | "FONTCONFIG_PATH" => Some("/etc/fonts".into()), |
| 291 | _ => None, |
| 292 | }); |
| 293 | assert_eq!(keys, vec!["FONTCONFIG_FILE"]); |
| 294 | assert!(app_fontconfig_keys(|_| None).is_empty()); |
| 295 | } |
| 296 | } |