Skip to main content

rightkit_browser/
session.rs

1use crate::config::{
2    reject_real_browser_profile, resolve_executable, validate_extra_args, validate_profile_dir,
3    validate_profile_name, LaunchOptions, ProfileSpec,
4};
5use crate::error::{cdp, BrowserError, Result};
6use crate::page::BrowserPage;
7use crate::policy::{Guard, LifecycleKind};
8use crate::proc::ChromeProc;
9use crate::proxy::{PinProxy, PinnedConnection};
10use chromiumoxide::browser::Browser;
11use chromiumoxide::cdp::browser_protocol::browser::{
12    PermissionDescriptor, PermissionSetting, ResetPermissionsParams, SetDownloadBehaviorBehavior,
13    SetDownloadBehaviorParams, SetPermissionParams,
14};
15use chromiumoxide::handler::HandlerConfig;
16use futures::StreamExt;
17use std::collections::HashSet;
18use std::ffi::OsString;
19use std::path::{Path, PathBuf};
20use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
21use std::sync::{Arc, Mutex as StdMutex};
22use std::time::{Duration, Instant};
23use tokio::sync::Mutex;
24use tokio::task::JoinHandle;
25
26static SESSION_SEQ: AtomicU64 = AtomicU64::new(0);
27
28/// Per-step wait before escalating a close (CDP -> SIGTERM -> SIGKILL).
29const GRACE: Duration = Duration::from_secs(5);
30
31enum ProfileGuard {
32    Temp(#[allow(dead_code)] tempfile::TempDir),
33    Named {
34        _lock: std::fs::File,
35    },
36    /// Caller-owned directory: dropping this guard has no filesystem effects.
37    Existing,
38}
39
40/// Remove the session's profile. A temporary profile is deleted with bounded retries:
41/// on Windows a just-terminated helper can hold a handle for a moment after its job ends.
42fn release_profile(guard: Option<ProfileGuard>) {
43    if let Some(ProfileGuard::Temp(dir)) = guard {
44        let path = dir.path().to_path_buf();
45        drop(dir);
46        let deadline = std::time::Instant::now() + Duration::from_secs(3);
47        while path.exists()
48            && std::fs::remove_dir_all(&path).is_err()
49            && std::time::Instant::now() < deadline
50        {
51            std::thread::sleep(Duration::from_millis(100));
52        }
53    }
54}
55
56fn prepare_profile(profile: &ProfileSpec) -> Result<(ProfileGuard, PathBuf, PathBuf)> {
57    match profile {
58        ProfileSpec::Temporary => {
59            let t = tempfile::tempdir()?;
60            let p = t.path().to_path_buf();
61            let dl = p.join("downloads");
62            Ok((ProfileGuard::Temp(t), p, dl))
63        }
64        ProfileSpec::Named { root, name } => {
65            validate_profile_name(name)?;
66            reject_real_browser_profile(root)?;
67            let dir = root.join(name);
68            std::fs::create_dir_all(&dir)?;
69            let lock = std::fs::OpenOptions::new()
70                .create(true)
71                .write(true)
72                .truncate(false)
73                .open(dir.join(".rightkit-browser.lock"))?;
74            match lock.try_lock() {
75                Ok(()) => {}
76                Err(std::fs::TryLockError::WouldBlock) => {
77                    return Err(BrowserError::ProfileInUse(name.clone()))
78                }
79                Err(std::fs::TryLockError::Error(e)) => return Err(e.into()),
80            }
81            let dl = dir.join("rightkit-downloads");
82            Ok((ProfileGuard::Named { _lock: lock }, dir, dl))
83        }
84        ProfileSpec::Directory(path) => {
85            validate_profile_dir(path)?;
86            Ok((
87                ProfileGuard::Existing,
88                path.clone(),
89                path.join("rightkit-downloads"),
90            ))
91        }
92    }
93}
94
95/// One Chrome process with any number of pages.
96pub struct BrowserSession {
97    id: String,
98    browser: Mutex<Browser>,
99    pages: StdMutex<Vec<Arc<BrowserPage>>>,
100    current: StdMutex<Option<String>>,
101    page_seq: AtomicU64,
102    handler: StdMutex<Option<JoinHandle<()>>>,
103    watcher: StdMutex<Option<JoinHandle<()>>>,
104    /// Released (temporary profile deleted) once Chrome has exited, on shutdown or drop.
105    profile_guard: StdMutex<Option<ProfileGuard>>,
106    profile_dir: PathBuf,
107    download_dir: PathBuf,
108    upload_root: Option<PathBuf>,
109    headless: bool,
110    guard: Arc<Guard>,
111    pid: Option<u32>,
112    proc: Arc<StdMutex<Option<ChromeProc>>>,
113    proxy: Option<PinProxy>,
114    /// Set before an intentional stop so the CDP pump does not report a crash.
115    stopping: Arc<AtomicBool>,
116    stopped: AtomicBool,
117}
118
119impl BrowserSession {
120    pub async fn launch(
121        #[cfg_attr(not(windows), allow(unused_mut))] mut opts: LaunchOptions,
122    ) -> Result<Self> {
123        validate_extra_args(&opts.extra_args)?;
124        let exe = resolve_executable(&opts)?;
125        let (profile_guard, profile_dir, default_dl) = prepare_profile(&opts.profile)?;
126        let download_dir = opts.download_dir.clone().unwrap_or(default_dl);
127        std::fs::create_dir_all(&download_dir)?;
128
129        let id = format!("bs-{}", SESSION_SEQ.fetch_add(1, Ordering::Relaxed));
130        let guard = Arc::new(Guard {
131            session_id: id.clone(),
132            admission: opts.admission.clone(),
133            network: opts.network.clone(),
134            events: opts.on_event.clone(),
135        });
136        let proxy = if opts.network.unrestricted {
137            None
138        } else {
139            Some(PinProxy::start(guard.clone()).await?)
140        };
141
142        let mut args: Vec<OsString> = [
143            "--remote-debugging-port=0",
144            "--no-first-run",
145            "--no-default-browser-check",
146            "--disable-background-networking",
147            "--disable-background-timer-throttling",
148            "--disable-backgrounding-occluded-windows",
149            "--disable-breakpad",
150            "--disable-client-side-phishing-detection",
151            "--disable-component-extensions-with-background-pages",
152            "--disable-default-apps",
153            "--disable-dev-shm-usage",
154            "--disable-extensions",
155            "--disable-hang-monitor",
156            "--disable-ipc-flooding-protection",
157            "--disable-prompt-on-repost",
158            "--disable-renderer-backgrounding",
159            "--disable-sync",
160            "--force-color-profile=srgb",
161            "--metrics-recording-only",
162            "--password-store=basic",
163            "--use-mock-keychain",
164            // No unmanaged windows: a pop-up would be a page the policy never saw.
165            "--block-new-web-contents",
166        ]
167        .iter()
168        .map(|s| OsString::from(*s))
169        .collect();
170        args.push(crate::proc::profile_arg(&profile_dir));
171        args.push(format!("--window-size={},{}", opts.viewport.0, opts.viewport.1).into());
172        args.push(if opts.headless {
173            "--headless=new".into()
174        } else {
175            "--hide-crash-restore-bubble".into()
176        });
177        if opts.mute_audio {
178            args.push("--mute-audio".into());
179        }
180        if let Some(p) = &proxy {
181            // Every connection, loopback included, goes through the pinning proxy;
182            // Chrome itself resolves nothing but the proxy address.
183            args.push(format!("--proxy-server=http://{}", p.addr).into());
184            args.push("--proxy-bypass-list=<-loopback>".into());
185            args.push("--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1".into());
186            // Keep cross-site frames in the page process so interception covers them.
187            args.push("--disable-site-isolation-trials".into());
188            // No UDP path around the proxy: WebRTC only over proxied routes, no QUIC.
189            args.push("--force-webrtc-ip-handling-policy=disable_non_proxied_udp".into());
190            args.push("--disable-quic".into());
191        }
192        for a in &opts.extra_args {
193            args.push(format!("--{}", a.trim_start_matches('-')).into());
194        }
195        args.push("about:blank".into());
196        let launch_timeout = opts.launch_timeout;
197        let request_timeout = opts.request_timeout;
198        #[cfg(windows)]
199        let job = opts.windows_job.take();
200        #[cfg(not(windows))]
201        let job = None;
202        let proc = tokio::task::spawn_blocking(move || {
203            crate::proc::spawn_chrome(&exe, &args, launch_timeout, job)
204        })
205        .await
206        .map_err(|e| BrowserError::Launch(e.to_string()))??;
207        let pid = Some(proc.child.id());
208        let config = HandlerConfig {
209            request_timeout,
210            ..HandlerConfig::default()
211        };
212        let (browser, mut handler) = Browser::connect_with_config(proc.ws_url.clone(), config)
213            .await
214            .map_err(|e| BrowserError::Launch(e.to_string()))?;
215        let proc = Arc::new(StdMutex::new(Some(proc)));
216        let stopping = Arc::new(AtomicBool::new(false));
217        let crashed = Arc::new(AtomicBool::new(false));
218        let (pump_proc, pump_stopping, pump_guard, pump_crashed) = (
219            proc.clone(),
220            stopping.clone(),
221            guard.clone(),
222            crashed.clone(),
223        );
224        let pump = tokio::spawn(async move {
225            // Transient handler errors are tolerated while Chrome is alive; the
226            // stream ending (or Chrome exiting) ends the session.
227            let mut errors = 0u32;
228            while let Some(ev) = handler.next().await {
229                if ev.is_err() {
230                    errors += 1;
231                    if errors > 50 || chrome_exit(&pump_proc).is_some() {
232                        break;
233                    }
234                } else {
235                    errors = 0;
236                }
237            }
238            // Give the OS a moment to reap so the reason carries the exit status.
239            let mut status = None;
240            for _ in 0..25 {
241                status = chrome_exit(&pump_proc);
242                if status.is_some() || pump_stopping.load(Ordering::SeqCst) {
243                    break;
244                }
245                tokio::time::sleep(Duration::from_millis(20)).await;
246            }
247            report_crash(&pump_guard, &pump_stopping, &pump_crashed, status, pid);
248        });
249        // The CDP stream does not always end when Chrome dies, so also watch the process.
250        let (w_proc, w_stopping, w_crashed, w_guard) = (
251            proc.clone(),
252            stopping.clone(),
253            crashed.clone(),
254            guard.clone(),
255        );
256        let watcher = tokio::spawn(async move {
257            loop {
258                tokio::time::sleep(Duration::from_millis(200)).await;
259                if w_stopping.load(Ordering::SeqCst) || w_crashed.load(Ordering::SeqCst) {
260                    return;
261                }
262                if let Some(status) = chrome_exit(&w_proc) {
263                    report_crash(&w_guard, &w_stopping, &w_crashed, Some(status), pid);
264                    return;
265                }
266            }
267        });
268        browser
269            .execute(
270                SetDownloadBehaviorParams::builder()
271                    .behavior(SetDownloadBehaviorBehavior::Allow)
272                    .download_path(download_dir.to_string_lossy().to_string())
273                    .build()
274                    .map_err(BrowserError::Launch)?,
275            )
276            .await
277            .map_err(cdp)?;
278
279        let mode = if opts.headless { "headless" } else { "headed" };
280        guard.emit_kind(LifecycleKind::Start, format!("launched ({mode})"), |e| {
281            e.pid = pid
282        });
283        Ok(Self {
284            id,
285            browser: Mutex::new(browser),
286            pages: StdMutex::new(Vec::new()),
287            current: StdMutex::new(None),
288            page_seq: AtomicU64::new(0),
289            handler: StdMutex::new(Some(pump)),
290            watcher: StdMutex::new(Some(watcher)),
291            profile_guard: StdMutex::new(Some(profile_guard)),
292            profile_dir,
293            download_dir,
294            upload_root: opts.upload_root,
295            headless: opts.headless,
296            guard,
297            pid,
298            proc,
299            proxy,
300            stopping,
301            stopped: AtomicBool::new(false),
302        })
303    }
304
305    pub fn id(&self) -> &str {
306        &self.id
307    }
308    /// OS process id of the Chrome child this session owns.
309    pub fn process_id(&self) -> Option<u32> {
310        self.pid
311    }
312    /// Connections the pinning proxy made, with the address it pinned for each.
313    pub fn pinned_connections(&self) -> Vec<PinnedConnection> {
314        self.proxy
315            .as_ref()
316            .map(|p| p.log.lock().unwrap().clone())
317            .unwrap_or_default()
318    }
319    pub fn is_headless(&self) -> bool {
320        self.headless
321    }
322    pub fn profile_dir(&self) -> &Path {
323        &self.profile_dir
324    }
325    pub fn download_dir(&self) -> &Path {
326        &self.download_dir
327    }
328
329    /// Open a new page (tab), make it current, and navigate to `url`.
330    pub async fn new_page(&self, url: &str) -> Result<Arc<BrowserPage>> {
331        let inner = self
332            .browser
333            .lock()
334            .await
335            .new_page("about:blank")
336            .await
337            .map_err(cdp)?;
338        let id = format!("p{}", self.page_seq.fetch_add(1, Ordering::Relaxed) + 1);
339        let page = Arc::new(
340            BrowserPage::attach(
341                id.clone(),
342                inner,
343                self.upload_root.clone(),
344                self.guard.clone(),
345            )
346            .await?,
347        );
348        self.pages.lock().unwrap().push(page.clone());
349        *self.current.lock().unwrap() = Some(id);
350        if url != "about:blank" {
351            page.goto(url).await?;
352        }
353        Ok(page)
354    }
355
356    pub fn pages(&self) -> Vec<Arc<BrowserPage>> {
357        self.pages.lock().unwrap().clone()
358    }
359
360    pub fn page(&self, id: &str) -> Result<Arc<BrowserPage>> {
361        self.pages
362            .lock()
363            .unwrap()
364            .iter()
365            .find(|p| p.id() == id)
366            .cloned()
367            .ok_or_else(|| BrowserError::UnknownPage(id.into()))
368    }
369
370    /// The page actions default to.
371    pub fn current(&self) -> Result<Arc<BrowserPage>> {
372        let id = self
373            .current
374            .lock()
375            .unwrap()
376            .clone()
377            .ok_or_else(|| BrowserError::UnknownPage("<none>".into()))?;
378        self.page(&id)
379    }
380
381    /// Make `id` current and bring it to the front.
382    pub async fn select_page(&self, id: &str) -> Result<Arc<BrowserPage>> {
383        let p = self.page(id)?;
384        p.bring_to_front().await?;
385        *self.current.lock().unwrap() = Some(id.into());
386        Ok(p)
387    }
388
389    pub async fn close_page(&self, id: &str) -> Result<()> {
390        let p = self.page(id)?;
391        self.pages.lock().unwrap().retain(|x| x.id() != id);
392        {
393            let mut cur = self.current.lock().unwrap();
394            if cur.as_deref() == Some(id) {
395                *cur = self
396                    .pages
397                    .lock()
398                    .unwrap()
399                    .last()
400                    .map(|p| p.id().to_string());
401            }
402        }
403        p.close_inner().await
404    }
405
406    /// Completed files currently in the download directory.
407    pub fn downloads(&self) -> HashSet<PathBuf> {
408        completed_files(&self.download_dir)
409    }
410
411    /// Wait for a download not in `before` to finish (no `.crdownload`, stable size).
412    pub async fn wait_download(
413        &self,
414        before: &HashSet<PathBuf>,
415        timeout: Duration,
416    ) -> Result<PathBuf> {
417        let deadline = Instant::now() + timeout;
418        loop {
419            let now = completed_files(&self.download_dir);
420            if let Some(p) = now.difference(before).next() {
421                let size = std::fs::metadata(p).map(|m| m.len()).unwrap_or(0);
422                tokio::time::sleep(Duration::from_millis(100)).await;
423                if std::fs::metadata(p).map(|m| m.len()).unwrap_or(1) == size {
424                    return Ok(p.clone());
425                }
426            }
427            if Instant::now() >= deadline {
428                return Err(BrowserError::Timeout("download did not complete".into()));
429            }
430            tokio::time::sleep(Duration::from_millis(100)).await;
431        }
432    }
433
434    /// Set a W3C permission (`geolocation`, `notifications`, `clipboard-read`,
435    /// `midi`, ...) to granted or denied for `origin`, or every origin when `None`.
436    pub async fn set_permission(
437        &self,
438        origin: Option<&str>,
439        name: &str,
440        granted: bool,
441    ) -> Result<()> {
442        let mut params = SetPermissionParams::new(
443            PermissionDescriptor::new(name),
444            if granted {
445                PermissionSetting::Granted
446            } else {
447                PermissionSetting::Denied
448            },
449        );
450        params.origin = origin.map(str::to_string);
451        self.browser
452            .lock()
453            .await
454            .execute(params)
455            .await
456            .map_err(cdp)?;
457        Ok(())
458    }
459
460    pub async fn reset_permissions(&self) -> Result<()> {
461        self.browser
462            .lock()
463            .await
464            .execute(ResetPermissionsParams::default())
465            .await
466            .map_err(cdp)?;
467        Ok(())
468    }
469
470    /// Close Chrome gracefully: CDP `Browser.close` and up to 5 s for exit, then SIGTERM to
471    /// the process group and up to 5 s more, then SIGKILL (job termination on Windows).
472    /// Safe to call twice. A temporary profile is deleted once Chrome has exited.
473    pub async fn shutdown(&self) {
474        self.stop(false).await;
475    }
476
477    /// Cancel: kill the owned Chrome now and wait for it to exit. Helper
478    /// processes exit with their parent; none are detached.
479    pub async fn cancel(&self) {
480        self.stop(true).await;
481    }
482
483    async fn stop(&self, hard: bool) {
484        self.stopping.store(true, Ordering::SeqCst);
485        if !hard {
486            let graceful = async {
487                let _ = self.browser.lock().await.close().await;
488                let end = Instant::now() + GRACE;
489                loop {
490                    let done = match self.proc.lock().unwrap().as_mut() {
491                        Some(p) => matches!(p.child.try_wait(), Ok(Some(_)) | Err(_)),
492                        None => true,
493                    };
494                    if done || Instant::now() >= end {
495                        break;
496                    }
497                    tokio::time::sleep(Duration::from_millis(20)).await;
498                }
499            };
500            let _ = tokio::time::timeout(Duration::from_secs(6), graceful).await;
501        }
502        // Whatever is left: SIGTERM the process group with a bounded wait, SIGKILL last
503        // (cancel kills at once). Windows: the job object takes the whole tree.
504        let taken = self.proc.lock().unwrap().take();
505        if let Some(mut p) = taken {
506            let grace = if hard { Duration::ZERO } else { GRACE };
507            let _ = tokio::task::spawn_blocking(move || p.terminate_gracefully(grace)).await;
508        }
509        release_profile(self.profile_guard.lock().unwrap().take());
510        for p in self.pages.lock().unwrap().drain(..) {
511            p.abort_pumps();
512        }
513        if let Some(h) = self.handler.lock().unwrap().take() {
514            h.abort();
515        }
516        if let Some(w) = self.watcher.lock().unwrap().take() {
517            w.abort();
518        }
519        let reason = if hard { "cancelled" } else { "shutdown" };
520        self.emit_stopped(reason);
521    }
522
523    fn emit_stopped(&self, reason: &str) {
524        if !self.stopped.swap(true, Ordering::SeqCst) {
525            let pid = self.pid;
526            self.guard
527                .emit_kind(LifecycleKind::Stop, reason, |e| e.pid = pid);
528        }
529    }
530}
531
532/// Emit at most one `Crash` per session, never during an intentional stop.
533fn report_crash(
534    guard: &Guard,
535    stopping: &AtomicBool,
536    crashed: &AtomicBool,
537    status: Option<std::process::ExitStatus>,
538    pid: Option<u32>,
539) {
540    if stopping.load(Ordering::SeqCst) || crashed.swap(true, Ordering::SeqCst) {
541        return;
542    }
543    let reason = match status {
544        Some(s) => format!("chrome exited unexpectedly ({s})"),
545        None => "devtools connection lost".to_string(),
546    };
547    guard.emit_kind(LifecycleKind::Crash, reason, |e| e.pid = pid);
548}
549
550/// Exit status of the owned Chrome, if it has exited.
551fn chrome_exit(proc: &StdMutex<Option<ChromeProc>>) -> Option<std::process::ExitStatus> {
552    proc.lock()
553        .ok()?
554        .as_mut()
555        .and_then(|p| p.child.try_wait().ok().flatten())
556}
557
558impl Drop for BrowserSession {
559    fn drop(&mut self) {
560        self.stopping.store(true, Ordering::SeqCst);
561        for p in self.pages.lock().unwrap().iter() {
562            p.abort_pumps();
563        }
564        if let Some(h) = self.handler.lock().unwrap().take() {
565            h.abort();
566        }
567        if let Some(w) = self.watcher.lock().unwrap().take() {
568            w.abort();
569        }
570        // An abandoned session (cancelled caller, panic, early return) still closes
571        // gracefully: SIGTERM to Chrome's process group, a bounded wait, SIGKILL last.
572        if let Some(mut p) = self.proc.lock().unwrap().take() {
573            p.terminate_gracefully(GRACE);
574        }
575        // Chrome has exited: now the temporary profile can go.
576        release_profile(self.profile_guard.lock().unwrap().take());
577        self.emit_stopped("dropped");
578    }
579}
580
581fn completed_files(dir: &Path) -> HashSet<PathBuf> {
582    std::fs::read_dir(dir)
583        .map(|rd| {
584            rd.filter_map(|e| e.ok())
585                .map(|e| e.path())
586                .filter(|p| {
587                    p.is_file()
588                        && !p
589                            .extension()
590                            .is_some_and(|e| e == "crdownload" || e == "tmp")
591                })
592                .collect()
593        })
594        .unwrap_or_default()
595}
596
597#[cfg(test)]
598mod tests {
599    use super::*;
600
601    #[test]
602    fn profile_dir_accepts_spaces_and_preserves_caller_directory_on_cleanup() {
603        let temp = tempfile::tempdir().unwrap();
604        let name = format!(".ScrapeRight profile's ΓΌ & (data) {}", "x".repeat(65));
605        assert!(validate_profile_name(&name).is_err());
606        let path = temp.path().join(name);
607        std::fs::create_dir(&path).unwrap();
608        let sentinel = path.join("Preferences");
609        std::fs::write(&sentinel, "caller data").unwrap();
610        let opts = LaunchOptions::default().profile_dir(&path);
611        assert_eq!(opts.profile, ProfileSpec::Directory(path.clone()));
612        let (guard, resolved, downloads) = prepare_profile(&opts.profile).unwrap();
613        assert!(matches!(&guard, ProfileGuard::Existing));
614        assert_eq!(resolved, path);
615        assert_eq!(downloads, path.join("rightkit-downloads"));
616        assert_eq!(std::fs::read_dir(&path).unwrap().count(), 1);
617        // shutdown/cancel/Drop all release this same guard through Option::take.
618        let guard = StdMutex::new(Some(guard));
619        drop(guard.lock().unwrap().take());
620        drop(guard.lock().unwrap().take());
621        assert!(path.is_dir());
622        assert_eq!(std::fs::read_to_string(sentinel).unwrap(), "caller data");
623        assert_eq!(std::fs::read_dir(&path).unwrap().count(), 1);
624    }
625
626    #[test]
627    fn profile_dir_rejects_relative_missing_and_file_paths_without_creation() {
628        let temp = tempfile::tempdir().unwrap();
629        let missing = temp.path().join("missing profile");
630        let file = temp.path().join("not a directory");
631        std::fs::write(&file, "keep").unwrap();
632        for (path, message) in [
633            (PathBuf::from("relative profile"), "must be absolute"),
634            (missing.clone(), "must exist"),
635            (file.clone(), "not a directory"),
636        ] {
637            let opts = LaunchOptions::default().profile_dir(path);
638            let err = match prepare_profile(&opts.profile) {
639                Ok(_) => panic!("invalid profile was accepted"),
640                Err(err) => err,
641            };
642            assert!(matches!(&err, BrowserError::Profile(_)));
643            assert!(err.to_string().contains(message), "{err}");
644        }
645        assert!(!missing.exists());
646        assert_eq!(std::fs::read_to_string(file).unwrap(), "keep");
647    }
648
649    #[test]
650    fn temporary_profile_still_uses_cleanup_guard() {
651        let opts = LaunchOptions::default();
652        assert_eq!(opts.profile, ProfileSpec::Temporary);
653        let (guard, path, downloads) = prepare_profile(&opts.profile).unwrap();
654        assert!(matches!(&guard, ProfileGuard::Temp(_)));
655        assert_eq!(downloads, path.join("downloads"));
656        assert!(path.is_dir());
657        drop(guard);
658        assert!(!path.exists());
659    }
660
661    // APFS (macOS) rejects non-UTF-8 file names with EILSEQ; Linux filesystems accept them.
662    #[cfg(target_os = "linux")]
663    #[test]
664    fn profile_dir_accepts_non_utf8_names() {
665        use std::os::unix::ffi::OsStringExt;
666        let temp = tempfile::tempdir().unwrap();
667        let path = temp
668            .path()
669            .join(OsString::from_vec(b"profile \xff".to_vec()));
670        std::fs::create_dir(&path).unwrap();
671        let opts = LaunchOptions::default().profile_dir(&path);
672        let (guard, resolved, _) = prepare_profile(&opts.profile).unwrap();
673        assert_eq!(resolved, path);
674        drop(guard);
675        assert!(path.is_dir());
676    }
677}