Skip to main content

quickgui_system/
protocol.rs

1use std::path::PathBuf;
2
3#[cfg(not(any(target_os = "windows", target_os = "linux")))]
4use crate::SystemIntegrationError;
5use crate::{Result, invalid, platform, validate_text};
6
7pub const MAX_PROTOCOL_ARGUMENTS: usize = 64;
8pub const MAX_PROTOCOL_ARGUMENT_BYTES: usize = 8 * 1024;
9
10#[derive(Clone, Debug, Eq, PartialEq)]
11pub struct ProtocolRegistrationOptions {
12    pub app_name: String,
13    /// Stable reverse-DNS-style identifier used for the Linux desktop entry filename.
14    pub app_id: String,
15    pub executable: PathBuf,
16    pub arguments: Vec<String>,
17}
18
19impl ProtocolRegistrationOptions {
20    pub fn new(app_name: impl Into<String>, app_id: impl Into<String>) -> Result<Self> {
21        Ok(Self {
22            app_name: app_name.into(),
23            app_id: app_id.into(),
24            executable: std::env::current_exe().map_err(platform)?,
25            arguments: Vec::new(),
26        })
27    }
28}
29
30/// A dynamic URL-scheme registration for Windows or Linux.
31///
32/// macOS schemes must be declared in the signed application bundle's `CFBundleURLTypes`; runtime
33/// registration is deliberately reported as unsupported.
34#[derive(Clone, Debug, Eq, PartialEq)]
35pub struct ProtocolRegistration {
36    scheme: String,
37    options: ProtocolRegistrationOptions,
38}
39
40impl ProtocolRegistration {
41    pub fn new(scheme: impl Into<String>, options: ProtocolRegistrationOptions) -> Result<Self> {
42        let scheme = scheme.into().to_ascii_lowercase();
43        validate_scheme(&scheme)?;
44        validate_options(&options)?;
45        Ok(Self { scheme, options })
46    }
47
48    pub const fn supports_dynamic_registration() -> bool {
49        cfg!(any(target_os = "windows", target_os = "linux"))
50    }
51
52    pub fn scheme(&self) -> &str {
53        &self.scheme
54    }
55
56    pub fn register(&self) -> Result<()> {
57        #[cfg(target_os = "windows")]
58        return windows::register(self);
59        #[cfg(target_os = "linux")]
60        return linux::register(self);
61        #[cfg(not(any(target_os = "windows", target_os = "linux")))]
62        Err(SystemIntegrationError::Unsupported)
63    }
64
65    pub fn unregister(&self) -> Result<bool> {
66        #[cfg(target_os = "windows")]
67        return windows::unregister(self);
68        #[cfg(target_os = "linux")]
69        return linux::unregister(self);
70        #[cfg(not(any(target_os = "windows", target_os = "linux")))]
71        Err(SystemIntegrationError::Unsupported)
72    }
73
74    pub fn is_registered(&self) -> Result<bool> {
75        #[cfg(target_os = "windows")]
76        return windows::is_registered(self);
77        #[cfg(target_os = "linux")]
78        return linux::is_registered(self);
79        #[cfg(not(any(target_os = "windows", target_os = "linux")))]
80        Err(SystemIntegrationError::Unsupported)
81    }
82}
83
84fn validate_scheme(scheme: &str) -> Result<()> {
85    if scheme.len() > 64
86        || !scheme
87            .bytes()
88            .next()
89            .is_some_and(|byte| byte.is_ascii_alphabetic())
90        || !scheme
91            .bytes()
92            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.'))
93    {
94        return Err(invalid(
95            "a URL scheme must follow RFC 3986 and be at most 64 ASCII bytes",
96        ));
97    }
98    Ok(())
99}
100
101fn validate_options(options: &ProtocolRegistrationOptions) -> Result<()> {
102    validate_text(&options.app_name, "the protocol application name", 256)?;
103    if options.app_name.contains(['\r', '\n']) {
104        return Err(invalid("the protocol application name must be single-line"));
105    }
106    validate_text(&options.app_id, "the protocol application id", 1_024)?;
107    if options
108        .app_id
109        .bytes()
110        .any(|byte| !(byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')))
111    {
112        return Err(invalid(
113            "the protocol application id may contain only ASCII letters, digits, dots, underscores, and hyphens",
114        ));
115    }
116    if !options.executable.is_absolute() {
117        return Err(invalid("the protocol handler executable must be absolute"));
118    }
119    if options
120        .executable
121        .to_str()
122        .is_none_or(|path| path.contains(['\0', '\r', '\n']))
123    {
124        return Err(invalid(
125            "the protocol handler executable path must be valid UTF-8, NUL-free, and single-line",
126        ));
127    }
128    if options.arguments.len() > MAX_PROTOCOL_ARGUMENTS {
129        return Err(invalid("protocol handlers accept at most 64 arguments"));
130    }
131    let mut total = 0_usize;
132    for argument in &options.arguments {
133        if argument.contains('\0') || argument.contains(['\r', '\n']) {
134            return Err(invalid(
135                "protocol handler arguments must be NUL-free and single-line",
136            ));
137        }
138        total = total.saturating_add(argument.len());
139    }
140    if total > MAX_PROTOCOL_ARGUMENT_BYTES {
141        return Err(invalid(
142            "protocol handler arguments cannot exceed 8192 aggregate UTF-8 bytes",
143        ));
144    }
145    Ok(())
146}
147
148#[cfg(target_os = "windows")]
149mod windows {
150    use winreg::{RegKey, enums::HKEY_CURRENT_USER};
151
152    use super::*;
153
154    fn key_path(registration: &ProtocolRegistration) -> String {
155        format!("Software\\Classes\\{}", registration.scheme)
156    }
157
158    fn command(registration: &ProtocolRegistration) -> Result<String> {
159        let executable = dunce::simplified(&registration.options.executable)
160            .to_str()
161            .ok_or_else(|| invalid("the protocol handler executable must be valid UTF-8"))?;
162        let mut parts = Vec::with_capacity(registration.options.arguments.len() + 2);
163        parts.push(windows_quote(executable));
164        parts.extend(
165            registration
166                .options
167                .arguments
168                .iter()
169                .map(|argument| windows_quote(argument)),
170        );
171        parts.push("\"%1\"".to_owned());
172        Ok(parts.join(" "))
173    }
174
175    pub(super) fn register(registration: &ProtocolRegistration) -> Result<()> {
176        let current_user = RegKey::predef(HKEY_CURRENT_USER);
177        let path = key_path(registration);
178        let (root, _) = current_user.create_subkey(&path).map_err(platform)?;
179        root.set_value(
180            "",
181            &format!("URL:{} protocol", registration.options.app_name),
182        )
183        .map_err(platform)?;
184        root.set_value("URL Protocol", &"").map_err(platform)?;
185        let (icon, _) = current_user
186            .create_subkey(format!("{path}\\DefaultIcon"))
187            .map_err(platform)?;
188        icon.set_value(
189            "",
190            &format!("{},0", registration.options.executable.display()),
191        )
192        .map_err(platform)?;
193        let (open, _) = current_user
194            .create_subkey(format!("{path}\\shell\\open\\command"))
195            .map_err(platform)?;
196        open.set_value("", &command(registration)?)
197            .map_err(platform)
198    }
199
200    pub(super) fn is_registered(registration: &ProtocolRegistration) -> Result<bool> {
201        let current_user = RegKey::predef(HKEY_CURRENT_USER);
202        let Ok(open) =
203            current_user.open_subkey(format!("{}\\shell\\open\\command", key_path(registration)))
204        else {
205            return Ok(false);
206        };
207        let value: String = open.get_value("").map_err(platform)?;
208        Ok(value == command(registration)?)
209    }
210
211    pub(super) fn unregister(registration: &ProtocolRegistration) -> Result<bool> {
212        if !is_registered(registration)? {
213            return Ok(false);
214        }
215        let current_user = RegKey::predef(HKEY_CURRENT_USER);
216        current_user
217            .delete_subkey_all(key_path(registration))
218            .map_err(platform)?;
219        Ok(true)
220    }
221
222    fn windows_quote(value: &str) -> String {
223        if !value.is_empty()
224            && !value
225                .bytes()
226                .any(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\x0b' | b'"'))
227        {
228            return value.to_owned();
229        }
230        let mut quoted = String::from("\"");
231        let mut backslashes = 0;
232        for character in value.chars() {
233            if character == '\\' {
234                backslashes += 1;
235            } else {
236                if character == '"' {
237                    quoted.extend(std::iter::repeat_n('\\', backslashes * 2 + 1));
238                } else {
239                    quoted.extend(std::iter::repeat_n('\\', backslashes));
240                }
241                backslashes = 0;
242                quoted.push(character);
243            }
244        }
245        quoted.extend(std::iter::repeat_n('\\', backslashes * 2));
246        quoted.push('"');
247        quoted
248    }
249}
250
251#[cfg(target_os = "linux")]
252mod linux {
253    use std::{fs, process::Command};
254
255    use ini::Ini;
256
257    use super::*;
258
259    fn applications_dir() -> Result<PathBuf> {
260        dirs::data_dir()
261            .map(|path| path.join("applications"))
262            .ok_or_else(|| platform("the XDG data directory is unavailable"))
263    }
264
265    fn file_name(registration: &ProtocolRegistration) -> String {
266        format!("{}-url-handler.desktop", registration.options.app_id)
267    }
268
269    fn desktop_path(registration: &ProtocolRegistration) -> Result<PathBuf> {
270        Ok(applications_dir()?.join(file_name(registration)))
271    }
272
273    fn mime(registration: &ProtocolRegistration) -> String {
274        format!("x-scheme-handler/{}", registration.scheme)
275    }
276
277    pub(super) fn register(registration: &ProtocolRegistration) -> Result<()> {
278        let directory = applications_dir()?;
279        fs::create_dir_all(&directory).map_err(platform)?;
280        let path = desktop_path(registration)?;
281        let mut desktop = Ini::load_from_file(&path).unwrap_or_default();
282        let mut section = desktop.with_section(Some("Desktop Entry"));
283        section.set("Type", "Application");
284        section.set("Name", registration.options.app_name.clone());
285        section.set("Exec", desktop_command(registration)?);
286        section.set("Terminal", "false");
287        section.set("NoDisplay", "true");
288        let mime = mime(registration);
289        let mut mimes = section
290            .get("MimeType")
291            .unwrap_or_default()
292            .split(';')
293            .filter(|value| !value.is_empty())
294            .map(str::to_owned)
295            .collect::<Vec<_>>();
296        if !mimes.contains(&mime) {
297            mimes.push(mime.clone());
298        }
299        section.set("MimeType", format!("{};", mimes.join(";")));
300        desktop.write_to_file(&path).map_err(platform)?;
301        run_command("update-desktop-database", &[directory.as_os_str()])?;
302        run_command(
303            "xdg-mime",
304            &[
305                std::ffi::OsStr::new("default"),
306                std::ffi::OsStr::new(&file_name(registration)),
307                std::ffi::OsStr::new(&mime),
308            ],
309        )?;
310        Ok(())
311    }
312
313    pub(super) fn is_registered(registration: &ProtocolRegistration) -> Result<bool> {
314        let output = Command::new("xdg-mime")
315            .args(["query", "default", &mime(registration)])
316            .output()
317            .map_err(platform)?;
318        if !output.status.success() {
319            return Err(platform(format!(
320                "xdg-mime exited with status {}",
321                output.status
322            )));
323        }
324        Ok(String::from_utf8_lossy(&output.stdout).trim() == file_name(registration))
325    }
326
327    pub(super) fn unregister(registration: &ProtocolRegistration) -> Result<bool> {
328        if !is_registered(registration)? {
329            return Ok(false);
330        }
331        let path = desktop_path(registration)?;
332        if let Ok(mut desktop) = Ini::load_from_file(&path) {
333            let mut remove_file = true;
334            if let Some(section) = desktop.section_mut(Some("Desktop Entry")) {
335                let mime = mime(registration);
336                let mimes = section
337                    .get("MimeType")
338                    .unwrap_or_default()
339                    .split(';')
340                    .filter(|value| !value.is_empty() && *value != mime)
341                    .collect::<Vec<_>>();
342                if !mimes.is_empty() {
343                    section.insert("MimeType".to_owned(), format!("{};", mimes.join(";")));
344                    remove_file = false;
345                }
346            }
347            if remove_file {
348                fs::remove_file(&path).map_err(platform)?;
349            } else {
350                desktop.write_to_file(&path).map_err(platform)?;
351            }
352        }
353        remove_mimeapps_default(registration)?;
354        run_command(
355            "update-desktop-database",
356            &[applications_dir()?.as_os_str()],
357        )?;
358        Ok(true)
359    }
360
361    fn remove_mimeapps_default(registration: &ProtocolRegistration) -> Result<()> {
362        let Some(config) = dirs::config_dir() else {
363            return Ok(());
364        };
365        let path = config.join("mimeapps.list");
366        let Ok(mut mimeapps) = Ini::load_from_file(&path) else {
367            return Ok(());
368        };
369        let mime = mime(registration);
370        let file = file_name(registration);
371        let mut changed = false;
372        for name in ["Default Applications", "Added Associations"] {
373            if let Some(section) = mimeapps.section_mut(Some(name)) {
374                let values = section
375                    .get(&mime)
376                    .unwrap_or_default()
377                    .split(';')
378                    .filter(|value| !value.is_empty() && *value != file)
379                    .collect::<Vec<_>>();
380                if values.is_empty() {
381                    changed |= section.remove(&mime).is_some();
382                } else {
383                    section.insert(mime.clone(), format!("{};", values.join(";")));
384                    changed = true;
385                }
386            }
387        }
388        if changed {
389            mimeapps.write_to_file(path).map_err(platform)?;
390        }
391        Ok(())
392    }
393
394    fn desktop_command(registration: &ProtocolRegistration) -> Result<String> {
395        let executable = registration
396            .options
397            .executable
398            .to_str()
399            .ok_or_else(|| invalid("the protocol handler executable must be valid UTF-8"))?;
400        let mut command = desktop_quote(executable);
401        for argument in &registration.options.arguments {
402            command.push(' ');
403            command.push_str(&desktop_quote(argument));
404        }
405        command.push_str(" %u");
406        Ok(command)
407    }
408
409    fn desktop_quote(value: &str) -> String {
410        let escaped = value
411            .replace('\\', "\\\\")
412            .replace('"', "\\\"")
413            .replace('`', "\\`")
414            .replace('$', "\\$")
415            .replace('%', "%%");
416        format!("\"{escaped}\"")
417    }
418
419    fn run_command(program: &str, arguments: &[&std::ffi::OsStr]) -> Result<()> {
420        let status = Command::new(program)
421            .args(arguments)
422            .status()
423            .map_err(platform)?;
424        if !status.success() {
425            return Err(platform(format!("{program} exited with status {status}")));
426        }
427        Ok(())
428    }
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434
435    #[test]
436    fn validates_rfc_scheme_shape() {
437        assert!(validate_scheme("quickgui+preview").is_ok());
438        assert!(validate_scheme("1quickgui").is_err());
439        assert!(validate_scheme("quick_gui").is_err());
440    }
441}