BlueGit

ict rusty-teams

Files

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

launch.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
launch.rs 7.2 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 = if platform == Platform::Linux { "X11; Linux x86_64" } else { "Windows NT 10.0; Win64; x64" };
60 format!("Mozilla/5.0 ({system}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36")
61}
62
63pub(crate) fn major_from_directory_names<'a>(names: impl Iterator<Item = &'a str>) -> Option<u32> {
64 names
65 .filter_map(|name| {
66 let parts: Vec<&str> = name.split('.').collect();
67 let numeric = parts.len() == 4 && parts.iter().all(|part| part.parse::<u32>().is_ok());
68 numeric.then(|| parts[0].parse::<u32>().ok())?
69 })
70 .max()
71}
72
73pub(crate) fn major_from_version_output(output: &str) -> Option<u32> {
74 output
75 .split_whitespace()
76 .find_map(|word| word.split('.').next()?.parse::<u32>().ok().filter(|_| word.contains('.')))
77}
78
79const FALLBACK_MAJOR: u32 = 150;
80
81fn chrome_major(platform: Platform, executable: &Path) -> u32 {
82 let detected = match platform {
83 Platform::Linux => Command::new(executable)
84 .arg("--version")
85 .output()
86 .ok()
87 .and_then(|output| major_from_version_output(&String::from_utf8_lossy(&output.stdout))),
88 _ => executable.parent().and_then(|parent| std::fs::read_dir(parent).ok()).and_then(|entries| {
89 let names: Vec<String> =
90 entries.flatten().map(|entry| entry.file_name().to_string_lossy().into_owned()).collect();
91 major_from_directory_names(names.iter().map(String::as_str))
92 }),
93 };
94 detected.unwrap_or(FALLBACK_MAJOR)
95}
96
97pub struct SystemLauncher {
98 config: Config,
99}
100
101impl SystemLauncher {
102 pub fn new(config: Config) -> SystemLauncher {
103 SystemLauncher { config }
104 }
105}
106
107impl Launcher for SystemLauncher {
108 fn spawn(&self, request: &LaunchRequest) -> Result<(), BrowserError> {
109 let executable = self.config.chrome_executable()?;
110 let agent = user_agent(self.config.platform, chrome_major(self.config.platform, &executable));
111 let arguments = chrome_arguments(&ArgumentSpec {
112 port: self.config.port,
113 profile: &self.config.profile,
114 headless: request.headless,
115 user_agent: &agent,
116 start_urls: &request.start_urls,
117 });
118 let mut command = Command::new(&executable);
119 command.args(arguments).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
120 if self.config.platform == Platform::Wsl {
121 command.current_dir("/mnt/c");
122 }
123 detach(&mut command);
124 let mut child = command.spawn()?;
125 std::thread::spawn(move || {
126 let _ = child.wait();
127 });
128 Ok(())
129 }
130
131 fn kill_listener(&self, port: u16) -> Result<(), BrowserError> {
132 crate::process::kill_listener(self.config.platform, port)
133 }
134}
135
136#[cfg(unix)]
137fn detach(command: &mut Command) {
138 use std::os::unix::process::CommandExt;
139 command.process_group(0);
140}
141
142#[cfg(windows)]
143fn detach(command: &mut Command) {
144 use std::os::windows::process::CommandExt;
145 const DETACHED_PROCESS: u32 = 0x0000_0008;
146 const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
147 command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
148}
149
150#[cfg(test)]
151mod tests {
152 use super::*;
153
154 fn spec<'a>(headless: bool, urls: &'a [String]) -> ArgumentSpec<'a> {
155 ArgumentSpec { port: 9222, profile: r"C:\p\rusty-teams-chrome", headless, user_agent: "UA", start_urls: urls }
156 }
157
158 #[test]
159 fn headless_arguments() {
160 let urls = vec!["https://teams.cloud.microsoft/".to_owned()];
161 let arguments = chrome_arguments(&spec(true, &urls));
162 assert_eq!(
163 &arguments[..7],
164 [
165 "--remote-debugging-port=9222",
166 r"--user-data-dir=C:\p\rusty-teams-chrome",
167 "--no-first-run",
168 "--no-default-browser-check",
169 "--headless=new",
170 "--user-agent=UA",
171 "--window-size=1400,1000",
172 ]
173 );
174 assert_eq!(&arguments[7..17], HEADLESS_MEMORY_FLAGS);
175 assert_eq!(arguments[17], "https://teams.cloud.microsoft/");
176 assert!(!arguments.iter().any(|argument| argument == "--process-per-site"));
177 }
178
179 #[test]
180 fn visible_arguments_have_no_headless_flags_and_all_urls() {
181 let urls = vec!["https://a/".to_owned(), "https://b/".to_owned()];
182 let arguments = chrome_arguments(&spec(false, &urls));
183 assert!(!arguments.iter().any(|argument| argument.contains("headless") || argument.contains("user-agent")));
184 assert_eq!(&arguments[4..], ["https://a/", "https://b/"]);
185 }
186
187 #[test]
188 fn user_agents_per_platform() {
189 assert!(user_agent(Platform::Wsl, 154).contains("Windows NT 10.0; Win64; x64"));
190 assert!(user_agent(Platform::Windows, 154).contains("Chrome/154.0.0.0"));
191 assert!(user_agent(Platform::Linux, 140).contains("X11; Linux x86_64"));
192 }
193
194 #[test]
195 fn major_from_version_directories() {
196 let names = ["154.0.8037.98", "153.0.1.2", "Dictionaries", "chrome.exe", "1.2.3"];
197 assert_eq!(major_from_directory_names(names.into_iter()), Some(154));
198 assert_eq!(major_from_directory_names(["x"].into_iter()), None);
199 }
200
201 #[test]
202 fn major_from_version_text() {
203 assert_eq!(major_from_version_output("Google Chrome 154.0.8037.98 \n"), Some(154));
204 assert_eq!(major_from_version_output("Chromium 131.0.6778.85 snap"), Some(131));
205 assert_eq!(major_from_version_output("nothing"), None);
206 }
207}