opener 0.9.0

Open a file or link using the system default program.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
use crate::browser_command::{substitute_target, supports_direct_launch};
use crate::OpenError;
use std::ffi::{OsStr, OsString};
use std::os::unix::ffi::OsStrExt;
use std::path::PathBuf;
use std::process::{Command, Output, Stdio};
use std::{env, io};
use url::Url;

const DISCOVER_BROWSER: &str = include_str!("wsl_browser.ps1");

// The target is read from the environment, so it is never parsed as command-line text.
// Exit code 2 means the Windows shell tried to open the target and failed.
const SHELL_EXECUTE: &str = r"$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
$info = New-Object System.Diagnostics.ProcessStartInfo($env:OPENER_TARGET)
$info.UseShellExecute = $true
$info.Verb = 'open'
try { [void][System.Diagnostics.Process]::Start($info) }
catch { [Console]::Error.Write($_.Exception.GetBaseException().Message); exit 2 }";

pub(super) fn open(path: &OsStr) -> Result<(), OpenError> {
    // Until the Windows shell has tried to open the target, nothing has been launched, so falling
    // back cannot open it twice.
    let target = match windows_target(path, |path| wslpath("-aw", path)) {
        Ok(target) => target,
        // The target cannot be expressed for Windows, so another launcher would fail too.
        Err(error) if error.kind() == io::ErrorKind::InvalidInput => {
            return Err(OpenError::Io(error));
        }
        Err(_) => return super::open_with_xdg_open(path),
    };
    let result = run_powershell(SHELL_EXECUTE, Some(&target), |mut command| {
        command
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .output()
    });
    match result {
        Ok(output) if output.status.success() => Ok(()),
        Ok(output) if output.status.code() == Some(2) => Err(OpenError::ExitStatus {
            cmd: "powershell.exe",
            status: output.status,
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
        }),
        _ => super::open_with_xdg_open(path),
    }
}

pub(super) fn open_browser(path: &OsStr) -> Result<(), OpenError> {
    let Some(target) = path.to_str().filter(|s| {
        s.get(..5)
            .is_some_and(|prefix| prefix.eq_ignore_ascii_case("file:"))
    }) else {
        return open(path);
    };

    // Match native Windows: unsupported associations, unavailable discovery, and failed spawns
    // fall back to open. None of these launched anything, so the target cannot open twice.
    let Ok((executable, args)) = resolve_browser_command(target) else {
        return open(path);
    };

    // For example, WSL cannot execute browsers installed from the Microsoft Store.
    let spawned = crate::spawn_detached(
        Command::new(&executable)
            .args(args)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null()),
    );
    if spawned.is_err() {
        return open(path);
    }
    Ok(())
}

/// Resolves the default browser's command for a file URL, with the URL converted for Windows and
/// the executable converted to a WSL path.
fn resolve_browser_command(target: &str) -> io::Result<(OsString, Vec<String>)> {
    let target = windows_file_url(target, |path| wslpath("-aw", path))?;
    let output = discover_browser()?;
    let (executable, args) = association_command(&output, &target)?;
    let executable = wslpath("-u", OsStr::new(&executable))?;
    Ok((executable, args))
}

/// Converts an argument for a Windows `BROWSER` executable, or returns `None` to pass it unchanged.
pub(crate) fn windows_browser_argument(path: &OsStr) -> Option<OsString> {
    if let Some(target) = path.to_str() {
        if let Ok(url) = Url::parse(target) {
            if url.scheme() == "file" {
                return windows_file_url(target, |path| wslpath("-aw", path))
                    .ok()
                    .map(OsString::from);
            }
            // Single-letter schemes are Windows drive paths such as `C:\file`, not URLs.
            if url.scheme().len() > 1 {
                return None;
            }
        }
    }
    wslpath("-w", path).ok()
}

fn checked_output(mut command: Command) -> io::Result<Vec<u8>> {
    let Output { status, stdout, .. } = command
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .output()?;
    if !status.success() {
        return Err(io::Error::other(format!("command failed: {status}")));
    }
    Ok(stdout)
}

pub(super) fn wslpath(mode: &str, path: &OsStr) -> io::Result<OsString> {
    use std::os::unix::ffi::OsStringExt;
    let mut command = Command::new("wslpath");
    command.args([OsStr::new(mode), path]);
    let mut output = checked_output(command)?;
    // Remove only wslpath's terminator; whitespace can be part of a filename.
    if output.last() == Some(&b'\n') {
        output.pop();
    }
    if output.is_empty() || output.contains(&0) {
        return Err(io::Error::other("invalid wslpath output"));
    }
    Ok(OsString::from_vec(output))
}

/// Runs a PowerShell script, passing `target` to it as `$env:OPENER_TARGET`.
fn run_powershell<T>(
    script: &str,
    target: Option<&OsStr>,
    run: impl Fn(Command) -> io::Result<T>,
) -> io::Result<T> {
    let command = |executable: &OsStr| {
        let mut command = Command::new(executable);
        command.args([
            "-NoLogo",
            "-NoProfile",
            "-NonInteractive",
            "-Command",
            script,
        ]);
        if let Some(target) = target {
            // WSLENV lists the variables that are shared with Windows processes.
            let mut wslenv = env::var_os("WSLENV").unwrap_or_default();
            if !wslenv.is_empty() {
                wslenv.push(":");
            }
            wslenv.push("OPENER_TARGET");
            command.env("OPENER_TARGET", target).env("WSLENV", wslenv);
        }
        command
    };
    match run(command(OsStr::new("powershell.exe"))) {
        Err(error) if error.kind() == io::ErrorKind::NotFound => {
            // wslpath respects custom Windows drive mount locations.
            let executable = wslpath(
                "-u",
                OsStr::new(r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"),
            )?;
            run(command(&executable))
        }
        result => result,
    }
}

fn discover_browser() -> io::Result<Vec<u8>> {
    run_powershell(DISCOVER_BROWSER, None, checked_output)
}

fn invalid_data(message: &str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, message)
}

fn invalid_input(message: &str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidInput, message)
}

fn is_windows_drive_path(path: &[u8]) -> bool {
    path.len() >= 4 && path[1].is_ascii_alphabetic() && path[2..4] == *b":/"
}

/// Percent-decodes a file URL's path, ignoring any host. Drive letters like `C|` become `C:`.
///
/// Like Python's `urllib` and Windows, escaped separators such as `%2F` are decoded too.
fn file_url_path(url: &Url) -> io::Result<PathBuf> {
    // to_file_path rejects hosts here, so decode the path from a local copy.
    let mut local = Url::parse("file:///").unwrap();
    local.set_path(url.path());
    local
        .to_file_path()
        .map_err(|()| invalid_input("invalid file URL path"))
}

/// Converts `path` to a target for the Windows shell. URLs other than file URLs are unchanged.
fn windows_target(
    path: &OsStr,
    convert: impl FnOnce(&OsStr) -> io::Result<OsString>,
) -> io::Result<OsString> {
    let Some(target) = path.to_str() else {
        return convert(path);
    };
    let url = match Url::parse(target) {
        Ok(url) if url.scheme() == "file" => url,
        // Includes Windows drive paths such as `C:\file`, which parse as single-letter schemes.
        Ok(_) => return Ok(path.to_owned()),
        Err(_) => return convert(path),
    };
    // Like on Windows, the shell opens a file path, so the query and fragment are discarded.
    let host = url.host_str();
    let path = file_url_path(&url)?;
    if host.is_none() && !is_windows_drive_path(path.as_os_str().as_bytes()) {
        return convert(path.as_os_str());
    }
    let path = path
        .to_str()
        .ok_or_else(|| invalid_input("non-Unicode Windows path"))?
        .replace('/', "\\");
    Ok(match host {
        Some(host) => format!(r"\\{host}{path}"),
        None => path[1..].to_owned(),
    }
    .into())
}

fn windows_file_url(
    target: &str,
    convert: impl FnOnce(&OsStr) -> io::Result<OsString>,
) -> io::Result<String> {
    let parsed = Url::parse(target).map_err(|error| invalid_data(&error.to_string()))?;
    if parsed.scheme() != "file" {
        return Err(invalid_data("not a file URL"));
    }
    let path = file_url_path(&parsed)?;
    if parsed.host_str().is_some() || is_windows_drive_path(path.as_os_str().as_bytes()) {
        // Already a Windows drive or UNC URL. Preserve the original encoding exactly.
        return Ok(target.to_owned());
    }
    let converted = convert(path.as_os_str())?;
    let converted = converted
        .to_str()
        .ok_or_else(|| invalid_data("non-Unicode Windows path"))?;
    let normalized = converted.replace('\\', "/");
    let mut result = Url::parse("file:///").unwrap();
    let path = if let Some(unc) = normalized.strip_prefix("//") {
        let (host, path) = unc
            .split_once('/')
            .ok_or_else(|| invalid_data("invalid UNC path"))?;
        if host.is_empty() {
            return Err(invalid_data("empty UNC host"));
        }
        result
            .set_host(Some(host))
            .map_err(|error| invalid_data(&error.to_string()))?;
        path
    } else {
        let bytes = normalized.as_bytes();
        if bytes.len() < 3 || !bytes[0].is_ascii_alphabetic() || bytes[1..3] != *b":/" {
            return Err(invalid_data("Windows path is not absolute"));
        }
        &normalized
    };
    // Segment setters encode literal %, # and ? in filenames instead of treating them as URL syntax.
    result
        .path_segments_mut()
        .unwrap()
        .clear()
        .extend(path.split('/'));
    result.set_query(parsed.query());
    result.set_fragment(parsed.fragment());
    Ok(result.into())
}

fn association_command(output: &[u8], target: &str) -> io::Result<(String, Vec<String>)> {
    let output =
        std::str::from_utf8(output).map_err(|_| invalid_data("non-UTF-8 browser command"))?;
    let mut parts = output.split('\0');
    let executable = parts.next().unwrap_or_default();
    if !supports_direct_launch(executable) {
        return Err(invalid_data("unsupported browser executable"));
    }
    let args = substitute_target(parts, target)
        .ok_or_else(|| invalid_data("unsupported browser command arguments"))?;
    Ok((executable.to_owned(), args))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::unix::fs::PermissionsExt;
    use std::path::PathBuf;

    #[test]
    fn converts_linux_file_url_and_preserves_url_components() {
        let result = windows_file_url(
            "file:///mnt/c/Me%C5%82/name%23%25%20two.html?x=%23&y=two%20words#section%201",
            |path| {
                assert_eq!(path, "/mnt/c/Meł/name#% two.html");
                Ok(OsString::from(r"C:\Meł\name#% two.html"))
            },
        )
        .unwrap();
        assert_eq!(
            result,
            "file:///C:/Me%C5%82/name%23%25%20two.html?x=%23&y=two%20words#section%201"
        );
    }

    #[test]
    fn converts_linux_filesystem_to_unc_url() {
        let result = windows_file_url("file://localhost/home/me/report.html?#", |path| {
            assert_eq!(path, "/home/me/report.html");
            Ok(OsString::from(
                r"\\wsl.localhost\archlinux\home\me\report.html",
            ))
        })
        .unwrap();
        assert_eq!(
            result,
            "file://wsl.localhost/archlinux/home/me/report.html?#"
        );
    }

    #[test]
    fn preserves_existing_windows_urls_exactly() {
        for target in [
            "file:///C:/Me%C5%82/a%23.html?q=%25#section",
            "FILE:///c:/a%2fb.html#fragment",
            "file://server/share/a%20b.html#section",
            "file:///C:",
            "file:///C|/Me%C5%82/a.html#section",
        ] {
            assert_eq!(
                windows_file_url(target, |_| panic!("already a Windows URL")).unwrap(),
                target
            );
        }
    }

    #[test]
    fn conversion_failures_do_not_produce_a_wrong_url() {
        assert!(
            windows_file_url("file:///tmp/a", |_| Err(io::Error::other("no wslpath"))).is_err()
        );
        assert!(windows_file_url("file:///tmp/a", |_| Ok(OsString::from("relative"))).is_err());
    }

    #[test]
    fn converts_targets_for_the_windows_shell() {
        let convert = |path: &OsStr| -> io::Result<OsString> {
            Ok(format!("converted:{}", path.to_str().unwrap()).into())
        };
        for (input, expected) in [
            (
                "https://example.com/a%20b?q=1#section",
                "https://example.com/a%20b?q=1#section",
            ),
            (r"C:\Users\Me\a b.txt", r"C:\Users\Me\a b.txt"),
            ("file:///C:/Me%C5%82/a%23.html?q#section", r"C:\Meł\a#.html"),
            ("file:///C:", r"C:\"),
            (
                "file://server/share/a%20b.html#section",
                r"\\server\share\a b.html",
            ),
            (
                "file:///mnt/c/Me%C5%82/a%23.html#section",
                "converted:/mnt/c/Meł/a#.html",
            ),
            (
                "file://localhost/home/me/report.html",
                "converted:/home/me/report.html",
            ),
            ("report.html", "converted:report.html"),
            ("/home/me/a b.html", "converted:/home/me/a b.html"),
            ("file:///C|/Me%C5%82/a.html#section", r"C:\Meł\a.html"),
            // Like Python's urllib, escaped separators are decoded.
            ("file:///C:/docs/a%2Fb.html", r"C:\docs\a\b.html"),
            ("file:///C:/docs/a%5Cb.html", r"C:\docs\a\b.html"),
            ("file://server/share/a%5cb.html", r"\\server\share\a\b.html"),
            ("file:///mnt/c/a%2Fb.html", "converted:/mnt/c/a/b.html"),
            // wslpath maps `\` in Linux file names to a character Windows allows.
            ("file:///mnt/c/a%5Cb.html", r"converted:/mnt/c/a\b.html"),
        ] {
            assert_eq!(
                windows_target(OsStr::new(input), convert).unwrap(),
                expected,
                "{input}"
            );
        }
    }

    #[test]
    fn browser_override_receives_non_file_urls_unchanged() {
        for url in [
            "https://example.com/a%20b?q=1#section",
            "mailto:me@example.com",
        ] {
            assert_eq!(windows_browser_argument(OsStr::new(url)), None);
        }
    }

    #[test]
    #[ignore = "requires WSL with a configured Windows HTTPS association"]
    fn discovers_the_system_browser_command_without_changing_the_url() {
        let target = "file:///C:/Users/Me%C5%82/index.html#section";
        let output = discover_browser().unwrap();
        let (executable, args) =
            association_command(&output, target).expect("the browser command should be supported");
        assert!(args.iter().any(|arg| arg.contains(target)), "{args:?}");
        let executable = wslpath("-u", OsStr::new(&executable)).unwrap();
        assert!(PathBuf::from(&executable).exists(), "{executable:?}");
    }

    #[test]
    fn substitutes_url_once_without_interpreting_its_contents() {
        let target = "file:///C:/Me%C5%82/a%20b.html?x=\"two words\"&p=%1%L|^#section";
        let (exe, args) = association_command(
            b"C:\\Program Files\\Browser\\browser.exe\0--url=%L\0--after\0%*",
            target,
        )
        .unwrap();
        assert_eq!(exe, r"C:\Program Files\Browser\browser.exe");
        assert_eq!(args, [format!("--url={target}"), "--after".to_owned()]);
    }

    #[test]
    fn rejects_unsupported_or_malformed_commands() {
        // browser_command tests the checks themselves; this covers parsing PowerShell's output.
        for output in [
            &b"C:\\Windows\\System32\\cmd.exe\0/C\0%1"[..],
            b"C:\\browser.exe\0%2",
            b"C:\\browser.exe",
            b"\xff\0%1",
        ] {
            assert!(association_command(output, "url").is_err());
        }
    }

    struct Fixture(PathBuf);

    impl Fixture {
        fn new() -> Self {
            let path = env::temp_dir().join(format!(
                "opener-wsl-{}-{}",
                std::process::id(),
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_nanos()
            ));
            std::fs::create_dir(&path).unwrap();
            Self(path)
        }

        fn script(&self, name: &str, body: &str) {
            let path = self.0.join(name);
            std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
    }

    impl Drop for Fixture {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    #[test]
    fn launches_converted_url_and_handles_fallbacks_in_subprocesses() {
        // Environment changes are confined to subprocesses, so parallel tests stay independent.
        for scenario in [
            "browser",
            "shell",
            "http",
            "shell-error",
            "no-powershell",
            "spawn-failure",
            "nul-byte",
            "override",
        ] {
            let fixture = Fixture::new();
            if scenario != "no-powershell" {
                // Without OPENER_TARGET, this is browser discovery; with it, a shell launch.
                fixture.script(
                    "powershell.exe",
                    r#"if [ -z "$OPENER_TARGET" ]; then
    [ "$OPENER_WSL_SCENARIO" = shell ] && exit 1
    printf 'C:\\browser.exe\000--single-argument\000%%1'
else
    case ":$WSLENV:" in *:OPENER_TARGET:*) ;; *) exit 1;; esac
    [ "$OPENER_WSL_SCENARIO" = shell-error ] && printf 'No application' >&2 && exit 2
    printf '%s\000' "$0" "$OPENER_TARGET" > "$OPENER_WSL_FIXTURE/received"
fi"#,
                );
            }
            fixture.script(
                "wslpath",
                r#"case "$1" in
-aw) printf 'C:\\Meł\\name#%% two.html\n';;
-u) case "$2" in
    *powershell.exe) printf '%s/missing.exe\n' "$OPENER_WSL_FIXTURE";;
    *) printf '%s/browser.exe\n' "$OPENER_WSL_FIXTURE";;
    esac;;
esac"#,
            );
            let recorder = "printf '%s\\000' \"$0\" \"$@\" > \"$OPENER_WSL_FIXTURE/received\"";
            if scenario != "spawn-failure" {
                fixture.script("browser.exe", recorder);
            }
            fixture.script("xdg-open", recorder);
            fixture.script("override", recorder);
            let status = Command::new(env::current_exe().unwrap())
                .args([
                    "--ignored",
                    "--exact",
                    "linux_and_more::wsl::tests::launch_helper",
                ])
                .env("PATH", &fixture.0)
                .env("OPENER_WSL_FIXTURE", &fixture.0)
                .env("OPENER_WSL_SCENARIO", scenario)
                .env_remove("BROWSER")
                .status()
                .unwrap();
            assert!(status.success(), "scenario {scenario}");
        }
    }

    #[test]
    #[ignore = "subprocess helper"]
    fn launch_helper() {
        let Some(root) = env::var_os("OPENER_WSL_FIXTURE").map(PathBuf::from) else {
            return;
        };
        let scenario = env::var("OPENER_WSL_SCENARIO").unwrap();
        let target = match scenario.as_str() {
            "http" | "shell-error" => "https://example.com/a%20b#section",
            "nul-byte" => "file:///mnt/c/a%00b.html",
            _ => "file:///mnt/c/Me%C5%82/name%23%25%20two.html?x=%23#section",
        };
        let result = if scenario == "override" {
            env::set_var("BROWSER", root.join("override"));
            crate::open_browser(target)
        } else {
            open_browser(OsStr::new(target))
        };
        let received = root.join("received");
        match scenario.as_str() {
            // The shell tried to open the target, so its failure is reported without falling back.
            "shell-error" => assert!(matches!(
                result,
                Err(OpenError::ExitStatus { cmd: "powershell.exe", ref stderr, .. })
                    if stderr == "No application"
            )),
            // No launcher can accept the decoded NUL, so this fails without trying xdg-open.
            "nul-byte" => assert!(matches!(
                result,
                Err(OpenError::Io(ref error)) if error.kind() == io::ErrorKind::InvalidInput
            )),
            _ => result.unwrap(),
        }
        if matches!(scenario.as_str(), "shell-error" | "nul-byte") {
            assert!(!received.exists());
            return;
        }
        // Opening is asynchronous; wait for the recorder to finish writing the final NUL.
        let mut bytes = Vec::new();
        for _ in 0..250 {
            bytes = std::fs::read(&received).unwrap_or_default();
            if bytes.last() == Some(&0) {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        let received = String::from_utf8(bytes).unwrap();
        let (executable, args) = match scenario.as_str() {
            "browser" => (
                "browser.exe",
                "--single-argument\0file:///C:/Me%C5%82/name%23%25%20two.html?x=%23#section",
            ),
            "shell" | "spawn-failure" => ("powershell.exe", r"C:\Meł\name#% two.html"),
            "http" => ("powershell.exe", target),
            "no-powershell" => ("xdg-open", target),
            "override" => ("override", target),
            _ => unreachable!(),
        };
        assert_eq!(
            received,
            format!("{}\0{args}\0", root.join(executable).display())
        );
    }
}