BlueGit

ict rusty-teams

Files

rusty-teams / crates / browser / src / launch.rs

launch.rs

launch.rs 10.4 KiB Download Raw
1use std::path::Path;
2use std::process::{Command, Stdio};
3
4use crate::config::{Config, Platform};
5use crate::error::BrowserError;
6
7#[derive(Debug, Clone)]
8pub struct LaunchRequest {
9 pub headless: bool,
10 pub start_urls: Vec<String>,
11}
12
13pub trait Launcher: Send + Sync {
14 fn spawn(&self, request: &LaunchRequest) -> Result<(), BrowserError>;
15 fn kill_listener(&self, port: u16) -> Result<(), BrowserError>;
16}
17
18pub 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
26const 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
39pub 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
58pub 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
69pub(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
79pub(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
89const 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.
94const APP_EMOJI_FONTCONFIG_MARKER: &str = "fontconfig-emoji";
95
96fn 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
102fn strip_app_fontconfig(command: &mut Command) {
103 for key in ["FONTCONFIG_FILE", "FONTCONFIG_PATH"] {
104 let Some(value) = std::env::var_os(key) else {
105 continue;
106 };
107 if is_app_emoji_fontconfig(&value) {
108 command.env_remove(key);
109 }
110 }
111}
112
113fn chrome_major(platform: Platform, executable: &Path) -> u32 {
114 let detected = match platform {
115 Platform::Linux | Platform::Macos => {
116 let mut command = Command::new(executable);
117 strip_app_fontconfig(&mut command);
118 command
119 .arg("--version")
120 .output()
121 .ok()
122 .and_then(|output| {
123 major_from_version_output(&String::from_utf8_lossy(&output.stdout))
124 })
125 }
126 Platform::Windows | Platform::Wsl => executable
127 .parent()
128 .and_then(|parent| std::fs::read_dir(parent).ok())
129 .and_then(|entries| {
130 let names: Vec<String> = entries
131 .flatten()
132 .map(|entry| entry.file_name().to_string_lossy().into_owned())
133 .collect();
134 major_from_directory_names(names.iter().map(String::as_str))
135 }),
136 };
137 detected.unwrap_or(FALLBACK_MAJOR)
138}
139
140pub struct SystemLauncher {
141 config: Config,
142}
143
144impl SystemLauncher {
145 pub fn new(config: Config) -> SystemLauncher {
146 SystemLauncher { config }
147 }
148}
149
150impl Launcher for SystemLauncher {
151 fn spawn(&self, request: &LaunchRequest) -> Result<(), BrowserError> {
152 let executable = self.config.chrome_executable()?;
153 let agent = user_agent(
154 self.config.platform,
155 chrome_major(self.config.platform, &executable),
156 );
157 let arguments = chrome_arguments(&ArgumentSpec {
158 port: self.config.port,
159 profile: &self.config.profile,
160 headless: request.headless,
161 user_agent: &agent,
162 start_urls: &request.start_urls,
163 });
164 let mut command = Command::new(&executable);
165 strip_app_fontconfig(&mut command);
166 command
167 .args(arguments)
168 .stdin(Stdio::null())
169 .stdout(Stdio::null())
170 .stderr(Stdio::null());
171 if self.config.platform == Platform::Wsl {
172 command.current_dir("/mnt/c");
173 }
174 detach(&mut command);
175 let mut child = command.spawn()?;
176 std::thread::spawn(move || {
177 let _ = child.wait();
178 });
179 Ok(())
180 }
181
182 fn kill_listener(&self, port: u16) -> Result<(), BrowserError> {
183 crate::process::kill_listener(self.config.platform, port)
184 }
185}
186
187#[cfg(unix)]
188fn detach(command: &mut Command) {
189 use std::os::unix::process::CommandExt;
190 command.process_group(0);
191}
192
193#[cfg(windows)]
194fn detach(command: &mut Command) {
195 use std::os::windows::process::CommandExt;
196 const DETACHED_PROCESS: u32 = 0x0000_0008;
197 const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
198 command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204
205 fn spec<'a>(headless: bool, urls: &'a [String]) -> ArgumentSpec<'a> {
206 ArgumentSpec {
207 port: 9222,
208 profile: r"C:\p\rusty-teams-chrome",
209 headless,
210 user_agent: "UA",
211 start_urls: urls,
212 }
213 }
214
215 #[test]
216 fn headless_arguments() {
217 let urls = vec!["https://teams.cloud.microsoft/".to_owned()];
218 let arguments = chrome_arguments(&spec(true, &urls));
219 assert_eq!(
220 &arguments[..7],
221 [
222 "--remote-debugging-port=9222",
223 r"--user-data-dir=C:\p\rusty-teams-chrome",
224 "--no-first-run",
225 "--no-default-browser-check",
226 "--headless=new",
227 "--user-agent=UA",
228 "--window-size=1400,1000",
229 ]
230 );
231 assert_eq!(&arguments[7..17], HEADLESS_MEMORY_FLAGS);
232 assert_eq!(arguments[17], "https://teams.cloud.microsoft/");
233 assert!(
234 !arguments
235 .iter()
236 .any(|argument| argument == "--process-per-site")
237 );
238 }
239
240 #[test]
241 fn visible_arguments_have_no_headless_flags_and_all_urls() {
242 let urls = vec!["https://a/".to_owned(), "https://b/".to_owned()];
243 let arguments = chrome_arguments(&spec(false, &urls));
244 assert!(
245 !arguments
246 .iter()
247 .any(|argument| argument.contains("headless") || argument.contains("user-agent"))
248 );
249 assert_eq!(&arguments[4..], ["https://a/", "https://b/"]);
250 }
251
252 #[test]
253 fn user_agents_per_platform() {
254 assert!(user_agent(Platform::Wsl, 154).contains("Windows NT 10.0; Win64; x64"));
255 assert!(user_agent(Platform::Windows, 154).contains("Chrome/154.0.0.0"));
256 assert!(user_agent(Platform::Linux, 140).contains("X11; Linux x86_64"));
257 assert!(user_agent(Platform::Macos, 154).contains("Macintosh; Intel Mac OS X 10_15_7"));
258 assert!(user_agent(Platform::Macos, 154).contains("Chrome/154.0.0.0"));
259 assert!(!user_agent(Platform::Macos, 154).contains("Windows NT"));
260 }
261
262 #[test]
263 fn major_from_version_directories() {
264 let names = [
265 "154.0.8037.98",
266 "153.0.1.2",
267 "Dictionaries",
268 "chrome.exe",
269 "1.2.3",
270 ];
271 assert_eq!(major_from_directory_names(names.into_iter()), Some(154));
272 assert_eq!(major_from_directory_names(["x"].into_iter()), None);
273 }
274
275 #[test]
276 fn major_from_version_text() {
277 assert_eq!(
278 major_from_version_output("Google Chrome 154.0.8037.98 \n"),
279 Some(154)
280 );
281 assert_eq!(
282 major_from_version_output("Chromium 131.0.6778.85 snap"),
283 Some(131)
284 );
285 assert_eq!(major_from_version_output("nothing"), None);
286 }
287
288 #[test]
289 fn chrome_drops_only_app_emoji_fontconfig() {
290 assert!(is_app_emoji_fontconfig(std::ffi::OsStr::new(
291 "/tmp/cache/fontconfig-emoji/fonts.conf"
292 )));
293 assert!(!is_app_emoji_fontconfig(std::ffi::OsStr::new(
294 "/etc/fonts/fonts.conf"
295 )));
296
297 let previous_file = std::env::var_os("FONTCONFIG_FILE");
298 let previous_path = std::env::var_os("FONTCONFIG_PATH");
299 // SAFETY: test-only env mutation around a synchronous strip call.
300 unsafe {
301 std::env::set_var(
302 "FONTCONFIG_FILE",
303 "/tmp/cache/fontconfig-emoji/fonts.conf",
304 );
305 std::env::set_var("FONTCONFIG_PATH", "/etc/fonts");
306 }
307 let mut command = Command::new("true");
308 strip_app_fontconfig(&mut command);
309 // App marker path is removed; user FONTCONFIG_PATH is left alone.
310 let _ = command;
311 unsafe {
312 match previous_file {
313 Some(value) => std::env::set_var("FONTCONFIG_FILE", value),
314 None => std::env::remove_var("FONTCONFIG_FILE"),
315 }
316 match previous_path {
317 Some(value) => std::env::set_var("FONTCONFIG_PATH", value),
318 None => std::env::remove_var("FONTCONFIG_PATH"),
319 }
320 }
321 }
322}