| 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 | fn chrome_major(platform: Platform, executable: &Path) -> u32 { |
| 92 | let detected = match platform { |
| 93 | Platform::Linux | Platform::Macos => Command::new(executable) |
| 94 | .arg("--version") |
| 95 | .output() |
| 96 | .ok() |
| 97 | .and_then(|output| major_from_version_output(&String::from_utf8_lossy(&output.stdout))), |
| 98 | Platform::Windows | Platform::Wsl => executable |
| 99 | .parent() |
| 100 | .and_then(|parent| std::fs::read_dir(parent).ok()) |
| 101 | .and_then(|entries| { |
| 102 | let names: Vec<String> = entries |
| 103 | .flatten() |
| 104 | .map(|entry| entry.file_name().to_string_lossy().into_owned()) |
| 105 | .collect(); |
| 106 | major_from_directory_names(names.iter().map(String::as_str)) |
| 107 | }), |
| 108 | }; |
| 109 | detected.unwrap_or(FALLBACK_MAJOR) |
| 110 | } |
| 111 | |
| 112 | pub struct SystemLauncher { |
| 113 | config: Config, |
| 114 | } |
| 115 | |
| 116 | impl SystemLauncher { |
| 117 | pub fn new(config: Config) -> SystemLauncher { |
| 118 | SystemLauncher { config } |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | impl Launcher for SystemLauncher { |
| 123 | fn spawn(&self, request: &LaunchRequest) -> Result<(), BrowserError> { |
| 124 | let executable = self.config.chrome_executable()?; |
| 125 | let agent = user_agent( |
| 126 | self.config.platform, |
| 127 | chrome_major(self.config.platform, &executable), |
| 128 | ); |
| 129 | let arguments = chrome_arguments(&ArgumentSpec { |
| 130 | port: self.config.port, |
| 131 | profile: &self.config.profile, |
| 132 | headless: request.headless, |
| 133 | user_agent: &agent, |
| 134 | start_urls: &request.start_urls, |
| 135 | }); |
| 136 | let mut command = Command::new(&executable); |
| 137 | command |
| 138 | .args(arguments) |
| 139 | .stdin(Stdio::null()) |
| 140 | .stdout(Stdio::null()) |
| 141 | .stderr(Stdio::null()); |
| 142 | if self.config.platform == Platform::Wsl { |
| 143 | command.current_dir("/mnt/c"); |
| 144 | } |
| 145 | detach(&mut command); |
| 146 | let mut child = command.spawn()?; |
| 147 | std::thread::spawn(move || { |
| 148 | let _ = child.wait(); |
| 149 | }); |
| 150 | Ok(()) |
| 151 | } |
| 152 | |
| 153 | fn kill_listener(&self, port: u16) -> Result<(), BrowserError> { |
| 154 | crate::process::kill_listener(self.config.platform, port) |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | #[cfg(unix)] |
| 159 | fn detach(command: &mut Command) { |
| 160 | use std::os::unix::process::CommandExt; |
| 161 | command.process_group(0); |
| 162 | } |
| 163 | |
| 164 | #[cfg(windows)] |
| 165 | fn detach(command: &mut Command) { |
| 166 | use std::os::windows::process::CommandExt; |
| 167 | const DETACHED_PROCESS: u32 = 0x0000_0008; |
| 168 | const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; |
| 169 | command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP); |
| 170 | } |
| 171 | |
| 172 | #[cfg(test)] |
| 173 | mod tests { |
| 174 | use super::*; |
| 175 | |
| 176 | fn spec<'a>(headless: bool, urls: &'a [String]) -> ArgumentSpec<'a> { |
| 177 | ArgumentSpec { |
| 178 | port: 9222, |
| 179 | profile: r"C:\p\rusty-teams-chrome", |
| 180 | headless, |
| 181 | user_agent: "UA", |
| 182 | start_urls: urls, |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | #[test] |
| 187 | fn headless_arguments() { |
| 188 | let urls = vec!["https://teams.cloud.microsoft/".to_owned()]; |
| 189 | let arguments = chrome_arguments(&spec(true, &urls)); |
| 190 | assert_eq!( |
| 191 | &arguments[..7], |
| 192 | [ |
| 193 | "--remote-debugging-port=9222", |
| 194 | r"--user-data-dir=C:\p\rusty-teams-chrome", |
| 195 | "--no-first-run", |
| 196 | "--no-default-browser-check", |
| 197 | "--headless=new", |
| 198 | "--user-agent=UA", |
| 199 | "--window-size=1400,1000", |
| 200 | ] |
| 201 | ); |
| 202 | assert_eq!(&arguments[7..17], HEADLESS_MEMORY_FLAGS); |
| 203 | assert_eq!(arguments[17], "https://teams.cloud.microsoft/"); |
| 204 | assert!( |
| 205 | !arguments |
| 206 | .iter() |
| 207 | .any(|argument| argument == "--process-per-site") |
| 208 | ); |
| 209 | } |
| 210 | |
| 211 | #[test] |
| 212 | fn visible_arguments_have_no_headless_flags_and_all_urls() { |
| 213 | let urls = vec!["https://a/".to_owned(), "https://b/".to_owned()]; |
| 214 | let arguments = chrome_arguments(&spec(false, &urls)); |
| 215 | assert!( |
| 216 | !arguments |
| 217 | .iter() |
| 218 | .any(|argument| argument.contains("headless") || argument.contains("user-agent")) |
| 219 | ); |
| 220 | assert_eq!(&arguments[4..], ["https://a/", "https://b/"]); |
| 221 | } |
| 222 | |
| 223 | #[test] |
| 224 | fn user_agents_per_platform() { |
| 225 | assert!(user_agent(Platform::Wsl, 154).contains("Windows NT 10.0; Win64; x64")); |
| 226 | assert!(user_agent(Platform::Windows, 154).contains("Chrome/154.0.0.0")); |
| 227 | assert!(user_agent(Platform::Linux, 140).contains("X11; Linux x86_64")); |
| 228 | assert!(user_agent(Platform::Macos, 154).contains("Macintosh; Intel Mac OS X 10_15_7")); |
| 229 | assert!(user_agent(Platform::Macos, 154).contains("Chrome/154.0.0.0")); |
| 230 | assert!(!user_agent(Platform::Macos, 154).contains("Windows NT")); |
| 231 | } |
| 232 | |
| 233 | #[test] |
| 234 | fn major_from_version_directories() { |
| 235 | let names = [ |
| 236 | "154.0.8037.98", |
| 237 | "153.0.1.2", |
| 238 | "Dictionaries", |
| 239 | "chrome.exe", |
| 240 | "1.2.3", |
| 241 | ]; |
| 242 | assert_eq!(major_from_directory_names(names.into_iter()), Some(154)); |
| 243 | assert_eq!(major_from_directory_names(["x"].into_iter()), None); |
| 244 | } |
| 245 | |
| 246 | #[test] |
| 247 | fn major_from_version_text() { |
| 248 | assert_eq!( |
| 249 | major_from_version_output("Google Chrome 154.0.8037.98 \n"), |
| 250 | Some(154) |
| 251 | ); |
| 252 | assert_eq!( |
| 253 | major_from_version_output("Chromium 131.0.6778.85 snap"), |
| 254 | Some(131) |
| 255 | ); |
| 256 | assert_eq!(major_from_version_output("nothing"), None); |
| 257 | } |
| 258 | } |