misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
Linux: the .deb and .rpm install the browsers' host files for everyone, and uninstalling leaves none behind (Fixes #266) (#279)
Ahmed Nefzaoui126c34f6670e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eb53ae16..c540f831 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -610,6 +610,15 @@ choose. And Linux, checked on a real desktop with every change.### Fixed+- **Linux: uninstalling the .deb or .rpm leaves no browser files behind**+ ([#266](https://github.com/anefzaoui/misterdownloadmanager/issues/266)): MDM wrote the files+ that tell each browser where its helper is in every user's home folder, and `apt remove` or+ `dnf remove` left them there, naming a program that was gone. The packages now install them for+ everyone, in each browser's own folder (Chrome and Brave, Chromium and Vivaldi, Edge, Firefox,+ the Snap Firefox included), and remove them with the package; MDM writes none in the home+ folder for those browsers, and takes away the ones an earlier version wrote. The AppImage and+ the tar.gz, and Opera, Helium, Thorium and Firefox's forks (which read them only in the home+ folder), still get them there.#### Windows, menus and dialogs- **Sharper text on Windows** ([#262](https://github.com/anefzaoui/misterdownloadmanager/issues/262)):diff --git a/ROADMAP.md b/ROADMAP.mdindex 2da84c35..d94529d8 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -18,9 +18,10 @@ Everything below ships together, in the next release.[#262](https://github.com/anefzaoui/misterdownloadmanager/issues/262))- ✅ Linux: Update now asks the package manager which package MDM is; a copy installed byanother package manager (pacman) is left to the system's updates, with a plain message-- ✅ Linux: the guide says what uninstalling leaves in each user's home folder (the browsers' host- files, the list and settings) and how to remove it; a package can't- ([#266](https://github.com/anefzaoui/misterdownloadmanager/issues/266))+- ✅ Linux: the .deb and .rpm install the browsers' host files for everyone and remove them on+ uninstall, so nothing is left in the home folders for Chrome, Chromium, Edge, Brave, Vivaldi and+ Firefox (the Snap too); the guide says what the AppImage and the tar.gz leave, and how to remove+ it ([#266](https://github.com/anefzaoui/misterdownloadmanager/issues/266))- ✅ Linux: menus and drop-down lists open under what was clicked on tiling compositors (sway)too, through XWayland, as on GNOME and KDE([#267](https://github.com/anefzaoui/misterdownloadmanager/issues/267))diff --git a/crates/app/src/unix.rs b/crates/app/src/unix.rsindex 7f2f72d9..9aeb981c 100644--- a/crates/app/src/unix.rs+++ b/crates/app/src/unix.rs@@ -316,7 +316,8 @@ fn run_register(host: &Path, limit: std::time::Duration) -> Result<String, Strin/// Where browser integration stands (Options → General → Test browser integration): the/// manifests in the folders the browsers here read (mdm_ipc::browsers), for this user, or for-/// everyone when no browser is there for this user, and the helper each names.+/// everyone when no browser is there for this user, and the helper each names. A browser that+/// reads the package's manifest for everyone naming this helper (#266) needs none of its own.pub fn host_registration() -> crate::extension::Registration {let home = PathBuf::from(std::env::var_os("HOME").unwrap_or_default());let config = std::env::var_os("XDG_CONFIG_HOME")@@ -324,10 +325,11 @@ pub fn host_registration() -> crate::extension::Registration {.filter(|p| p.is_absolute()).unwrap_or_else(|| home.join(".config"));let mac = cfg!(target_os = "macos");- let user = mdm_ipc::browsers::host_dirs(&home, &config, mac, false);+ let host = registered_host();+ let user = mdm_ipc::browsers::host_dirs(&home, &config, mac, false, host.as_deref());if user.is_empty() {registration_in(- mdm_ipc::browsers::host_dirs(&home, &config, mac, true),+ mdm_ipc::browsers::host_dirs(&home, &config, mac, true, None),true,)} else {@@ -335,6 +337,15 @@ pub fn host_registration() -> crate::extension::Registration {}}+/// The helper `register_browsers` registers, without copying anything: beside this program, or+/// from an AppImage its copy in the data folder.+fn registered_host() -> Option<PathBuf> {+ if std::env::var_os("APPIMAGE").is_some_and(|i| !i.is_empty()) {+ return mdm_ipc::data_dir().map(|d| d.join("browser-host").join(HOST));+ }+ std::env::current_exe().ok().map(|e| e.with_file_name(HOST))+}+/// `host_registration` for the host folders `dirs`, everyone's (`all_users`) or one user's.fn registration_in(dirs: Vec<(PathBuf, mdm_ipc::browsers::Family)>,diff --git a/crates/ipc/src/browsers.rs b/crates/ipc/src/browsers.rsindex 1e88e255..144c7696 100644--- a/crates/ipc/src/browsers.rs+++ b/crates/ipc/src/browsers.rs@@ -8,6 +8,18 @@//! `brave_main_delegate.cc`, `chrome_paths_linux.cc` and `chromium_install_modes.h`); folders//! marked "unverified" in issue #41 come from other projects' installers and cost nothing when//! absent.+//!+//! Everyone's folders on Linux (`LINUX_SYSTEM_HOST_DIRS`), which the .deb and .rpm ship a manifest+//! in (#266), each browser's documented one: Chrome's and Chromium's from Chrome's "Native+//! messaging" guide (developer.chrome.com/docs/extensions/develop/concepts/native-messaging,+//! "Native messaging host location") and `chrome_paths.cc` (`DIR_NATIVE_MESSAGING`: Chrome's+//! branding reads `/etc/opt/chrome`, every other build `/etc/chromium`); Edge's from Microsoft's+//! (learn.microsoft.com/microsoft-edge/extensions/developer-guide/native-messaging, Linux);+//! Brave's from `brave_main_delegate.cc` (Linux: Chrome's, `/etc/opt/chrome`); Vivaldi, built+//! without Chrome's branding, reads Chromium's (as Vivaldi's forum confirms); Firefox's from+//! MDN's "Native manifests" (Linux, global: `/usr/lib/mozilla` or `/usr/lib64/mozilla`). Opera,+//! Helium, Thorium and Firefox's forks document none: they keep their manifest in the home+//! folder.use std::path::{Path, PathBuf};@@ -36,6 +48,9 @@ pub struct Browser {pub linux_config: &'static [&'static str],/// Linux: Gecko data folders under $HOME (`.zen`).pub linux_home: &'static [&'static str],+ /// Linux: the folders for everyone it reads host manifests from as well, after its user+ /// folder (`LINUX_SYSTEM_HOST_DIRS`); none known for some.+ pub linux_system: &'static [&'static str],/// macOS: the folder under ~/Library/Application Support whose `NativeMessagingHosts` a/// Chromium browser reads when it isn't its own data folder (Brave reads Chrome's).pub mac_hosts: Option<&'static str>,@@ -56,6 +71,7 @@ const fn chromium(mac_data,linux_config,linux_home: &[],+ linux_system: &[],mac_hosts: None,}}@@ -66,8 +82,37 @@ impl Browser {self.mac_hosts = Some(folder);self}++ /// On Linux it reads the manifests for everyone in `folders` too.+ const fn linux_system_in(mut self, folders: &'static [&'static str]) -> Browser {+ self.linux_system = folders;+ self+ }}+/// Linux: Chrome's folder for everyone (Google's builds of Chrome, every channel; Brave).+const ETC_CHROME: &str = "/etc/opt/chrome/native-messaging-hosts";+/// Linux: Chromium's (every build without Chrome's branding that keeps Chromium's: Vivaldi).+const ETC_CHROMIUM: &str = "/etc/chromium/native-messaging-hosts";+/// Linux: Edge's.+const ETC_EDGE: &str = "/etc/opt/edge/native-messaging-hosts";+/// Linux: Firefox's, `lib64`'s on 64-bit Fedora and openSUSE (MDN, "Native manifests").+const MOZILLA: [&str; 2] = [+ "/usr/lib/mozilla/native-messaging-hosts",+ "/usr/lib64/mozilla/native-messaging-hosts",+];++/// Linux: every folder for everyone a browser reads host manifests from, with the family whose+/// manifest goes there: where the .deb and .rpm put theirs (`misterdownloadmanager-nmhost+/// --package-manifests`), and `--register --all-users` too.+pub const LINUX_SYSTEM_HOST_DIRS: &[(&str, Family)] = &[+ (ETC_CHROME, Family::Chromium),+ (ETC_CHROMIUM, Family::Chromium),+ (ETC_EDGE, Family::Chromium),+ (MOZILLA[0], Family::Gecko),+ (MOZILLA[1], Family::Gecko),+];+const fn gecko(name: &'static str,mac_apps: &'static [&'static str],@@ -84,6 +129,7 @@ const fn gecko(mac_data,linux_config,linux_home,+ linux_system: &[],mac_hosts: None,}}@@ -118,14 +164,16 @@ pub const BROWSERS: &[Browser] = &["google-chrome-unstable","google-chrome-canary",],- ),+ )+ .linux_system_in(&[ETC_CHROME]),chromium("Chromium",&["Chromium.app"],&["chromium", "chromium-browser"],&["Chromium"],&["chromium"],- ),+ )+ .linux_system_in(&[ETC_CHROMIUM]),chromium("Microsoft Edge",&[@@ -151,7 +199,8 @@ pub const BROWSERS: &[Browser] = &["microsoft-edge-beta","microsoft-edge-dev",],- ),+ )+ .linux_system_in(&[ETC_EDGE]),// Brave and Brave Origin (#253), each channel in its own folder (`-Beta`, `-Dev`, `-Nightly`),// all named "Brave" to the extension. On Linux each reads its own folder; on macOS all read// Chrome's (brave_main_delegate.cc); on Windows, Chromium's and Chrome's keys.@@ -193,14 +242,16 @@ pub const BROWSERS: &[Browser] = &["BraveSoftware/Brave-Origin-Nightly",],)- .mac_hosts_in("Google/Chrome"),+ .mac_hosts_in("Google/Chrome")+ .linux_system_in(&[ETC_CHROME]),chromium("Vivaldi",&["Vivaldi.app"],&["vivaldi", "vivaldi-stable", "vivaldi-snapshot"],&["Vivaldi"],&["vivaldi", "vivaldi-snapshot"],- ),+ )+ .linux_system_in(&[ETC_CHROMIUM]),// Opera's folders: unverified.chromium("Opera",@@ -234,9 +285,11 @@ pub const BROWSERS: &[Browser] = &[&["Mozilla", "Firefox"],&["mozilla"],// The Snap (Ubuntu's own Firefox) keeps its profile in its snap folder and never makes- // ~/.mozilla; it reaches the host through the desktop portal, which reads ~/.mozilla's.+ // ~/.mozilla; it reaches the host through the desktop portal, which reads ~/.mozilla's,+ // then Mozilla's folders for everyone (xdg-desktop-portal's WebExtensions portal).&[".mozilla", "snap/firefox/common/.mozilla"],- ),+ )+ .linux_system_in(&MOZILLA),gecko("Zen Browser",&["Zen.app", "Zen Browser.app"],@@ -325,6 +378,9 @@ pub fn windows_can_run_extension(program: &str) -> bool {!program.to_lowercase().ends_with("iexplore.exe")}+/// The host manifest's file name, in every folder.+pub const HOST_MANIFEST: &str = "com.misterdownloadmanager.host.json";+/// Linux and macOS (`mac`): the folders to write the host manifest into, each with the family/// whose manifest goes there, for this user (`home`, `config` = $XDG_CONFIG_HOME) or for/// everyone. A user's folder is given only for a browser that is there.@@ -334,42 +390,62 @@ pub fn windows_can_run_extension(program: &str) -> bool {/// NativeMessagingHosts`, even when they keep their data elsewhere (Firefox's newer/// `~/.config/mozilla`, Zen's `~/.zen`, the Snap's `~/snap/firefox`): it is given, to be created,/// when any of them is there.-pub fn host_dirs(home: &Path, config: &Path, mac: bool, all_users: bool) -> Vec<(PathBuf, Family)> {+///+/// `host` (Linux, for one user): the helper being registered. A browser that already reads a+/// manifest for everyone naming it (the .deb's or .rpm's, #266) gets no user folder: the package+/// manager removes that one with the package, and nothing is left in the home folder. Mozilla's+/// user folder is given while one Gecko browser there doesn't read such a manifest.+pub fn host_dirs(+ home: &Path,+ config: &Path,+ mac: bool,+ all_users: bool,+ host: Option<&Path>,+) -> Vec<(PathBuf, Family)> {+ host_dirs_in(Path::new("/"), home, config, mac, all_users, host)+}++/// `host_dirs`, with everyone's folders under `root` (`/`; a test's own folder).+fn host_dirs_in(+ root: &Path,+ home: &Path,+ config: &Path,+ mac: bool,+ all_users: bool,+ host: Option<&Path>,+) -> Vec<(PathBuf, Family)> {+ let system = |d: &str| root.join(d.trim_start_matches('/'));let mut dirs: Vec<(PathBuf, Family)> = Vec::new();if all_users {- let (chromium, gecko): (&[&str], &[&str]) = if mac {- (- &[+ if mac {+ dirs.extend(+ ["/Library/Google/Chrome/NativeMessagingHosts","/Library/Application Support/Chromium/NativeMessagingHosts","/Library/Microsoft/Edge/NativeMessagingHosts",- ],- &["/Library/Application Support/Mozilla/NativeMessagingHosts"],- )- } else {- (- &[- "/etc/opt/chrome/native-messaging-hosts",- "/etc/chromium/native-messaging-hosts",- "/etc/opt/edge/native-messaging-hosts",- ],- // Firefox reads lib64's on 64-bit Fedora and openSUSE (MDN, "Native manifests").- &[- "/usr/lib/mozilla/native-messaging-hosts",- "/usr/lib64/mozilla/native-messaging-hosts",- ],- )- };- dirs.extend(- chromium+ ].iter()- .map(|d| (PathBuf::from(d), Family::Chromium)),- );- dirs.extend(gecko.iter().map(|d| (PathBuf::from(d), Family::Gecko)));+ .map(|d| (system(d), Family::Chromium)),+ );+ dirs.push((+ system("/Library/Application Support/Mozilla/NativeMessagingHosts"),+ Family::Gecko,+ ));+ } else {+ dirs.extend(LINUX_SYSTEM_HOST_DIRS.iter().map(|(d, f)| (system(d), *f)));+ }// Everyone's: only where the browser's folder is.dirs.retain(|(d, _)| d.parent().is_some_and(Path::is_dir));return dirs;}+ // A browser that reads a manifest for everyone naming this helper.+ let covered = |b: &Browser| {+ !mac && host.is_some_and(|host| {+ b.linux_system+ .iter()+ .any(|d| names_program(&system(d).join(HOST_MANIFEST), host))+ })+ };let support = home.join("Library/Application Support");let data = |b: &Browser| -> Vec<PathBuf> {if mac {@@ -390,20 +466,23 @@ pub fn host_dirs(home: &Path, config: &Path, mac: bool, all_users: bool) -> Vec<let mut gecko_there = false;for b in BROWSERS {let there: Vec<PathBuf> = data(b).into_iter().filter(|d| d.is_dir()).collect();+ if there.is_empty() || covered(b) {+ continue;+ }match (b.family, b.mac_hosts.filter(|_| mac)) {// Brave on macOS: Chrome's folder, made if need be, whichever channel is there.- (Family::Chromium, Some(hosts)) if !there.is_empty() => {+ (Family::Chromium, Some(hosts)) => {push(support.join(hosts).join("NativeMessagingHosts"),Family::Chromium,);}- (Family::Chromium, _) => {+ (Family::Chromium, None) => {for d in there {push(d.join("NativeMessagingHosts"), Family::Chromium);}}- (Family::Gecko, _) => gecko_there |= !there.is_empty(),+ (Family::Gecko, _) => gecko_there = true,}}if gecko_there {@@ -429,6 +508,36 @@ pub fn host_dirs(home: &Path, config: &Path, mac: bool, all_users: bool) -> Vec<dirs}+/// Whether the host manifest at `manifest` starts `program` (the same file), and it runs.+pub fn names_program(manifest: &Path, program: &Path) -> bool {+ let Some(named) = manifest_program(manifest) else {+ return false;+ };+ let same = match (+ std::fs::canonicalize(&named),+ std::fs::canonicalize(program),+ ) {+ (Ok(a), Ok(b)) => a == b,+ _ => false,+ };+ same && runs(&named)+}++/// A program file that can be run.+fn runs(path: &Path) -> bool {+ let Ok(meta) = std::fs::metadata(path) else {+ return false;+ };+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ meta.is_file() && meta.permissions().mode() & 0o111 != 0+ }+ // Windows reads its manifests through the registry, not these folders.+ #[cfg(not(unix))]+ meta.is_file()+}+/// The program the host manifest at `manifest` starts (its `path`; a relative one, which/// Windows allows, is beside the manifest), when the manifest can be read.pub fn manifest_program(manifest: &Path) -> Option<PathBuf> {@@ -449,7 +558,7 @@ mod tests {use super::*;fn user(home: &Path, mac: bool) -> Vec<(PathBuf, Family)> {- host_dirs(home, &home.join(".config"), mac, false)+ host_dirs(home, &home.join(".config"), mac, false, None)}#[test]@@ -703,6 +812,85 @@ mod tests {}}+ /// #266: a browser that reads the package's manifest for everyone, naming this helper, gets+ /// no user folder; a manifest naming another program, or one that doesn't run, doesn't count.+ /// Mozilla's user folder stays while a fork that reads only it is there.+ #[cfg(unix)]+ #[test]+ fn a_manifest_for_everyone_covers_its_browsers() {+ use std::os::unix::fs::PermissionsExt;+ let t = tempfile::tempdir().unwrap();+ let (root, home) = (t.path().join("root"), t.path().join("home"));+ for d in [+ ".config/google-chrome",+ ".config/BraveSoftware/Brave-Browser",+ ".config/opera",+ ".mozilla",+ ] {+ std::fs::create_dir_all(home.join(d)).unwrap();+ }+ let helper = root.join("usr/bin/misterdownloadmanager-nmhost");+ std::fs::create_dir_all(helper.parent().unwrap()).unwrap();+ std::fs::write(&helper, "#!/bin/sh\n").unwrap();+ std::fs::set_permissions(&helper, std::fs::Permissions::from_mode(0o755)).unwrap();+ let system = |d: &str, program: &Path| {+ let dir = root.join(d.trim_start_matches('/'));+ std::fs::create_dir_all(&dir).unwrap();+ let json = serde_json::json!({ "name": "x", "path": program, "type": "stdio" });+ std::fs::write(dir.join(HOST_MANIFEST), json.to_string()).unwrap();+ };+ let dirs = |host: Option<&Path>| -> Vec<PathBuf> {+ host_dirs_in(&root, &home, &home.join(".config"), false, false, host)+ .into_iter()+ .map(|(d, _)| d.strip_prefix(&home).unwrap().to_owned())+ .collect()+ };+ let all = |names: &[&str]| -> Vec<PathBuf> { names.iter().map(PathBuf::from).collect() };+ let chrome = ".config/google-chrome/NativeMessagingHosts";+ let brave = ".config/BraveSoftware/Brave-Browser/NativeMessagingHosts";+ let opera = ".config/opera/NativeMessagingHosts";+ let mozilla = ".mozilla/native-messaging-hosts";+ assert_eq!(dirs(Some(&helper)), all(&[chrome, brave, opera, mozilla]));++ // Chrome's for everyone: Chrome and Brave read it, Opera doesn't.+ system(ETC_CHROME, &helper);+ assert_eq!(dirs(Some(&helper)), all(&[opera, mozilla]));+ // Unregistering (no helper given) still sees every user folder.+ assert_eq!(dirs(None), all(&[chrome, brave, opera, mozilla]));+ // Firefox's, in lib64 (Fedora's).+ system(MOZILLA[1], &helper);+ assert_eq!(dirs(Some(&helper)), all(&[opera]));+ // Zen reads only Mozilla's user folder: it stays.+ std::fs::create_dir_all(home.join(".zen")).unwrap();+ assert_eq!(dirs(Some(&helper)), all(&[opera, mozilla]));+ std::fs::remove_dir(home.join(".zen")).unwrap();++ // Another helper (an AppImage's copy) isn't covered by the package's.+ let other = t.path().join("copy/misterdownloadmanager-nmhost");+ std::fs::create_dir_all(other.parent().unwrap()).unwrap();+ std::fs::copy(&helper, &other).unwrap();+ assert_eq!(dirs(Some(&other)), all(&[chrome, brave, opera, mozilla]));+ // A manifest naming a helper that can't run covers nothing.+ std::fs::set_permissions(&helper, std::fs::Permissions::from_mode(0o644)).unwrap();+ assert_eq!(dirs(Some(&helper)), all(&[chrome, brave, opera, mozilla]));+ }++ /// The folders for everyone each browser reads are in the list the packages ship.+ #[test]+ fn every_browsers_system_folder_is_shipped() {+ for b in BROWSERS {+ for d in b.linux_system {+ assert!(+ LINUX_SYSTEM_HOST_DIRS+ .iter()+ .any(|(x, f)| x == d && *f == b.family),+ "{} reads {d}",+ b.name+ );+ }+ }+ }+#[test]fn a_manifests_program() {let d = tempfile::tempdir().unwrap();diff --git a/crates/nmhost/src/main.rs b/crates/nmhost/src/main.rsindex ed61617a..660af2c1 100644--- a/crates/nmhost/src/main.rs+++ b/crates/nmhost/src/main.rs@@ -17,7 +17,12 @@//! this exe, with the per-user (HKCU) registry entries the browsers look up; with `--all-users`//! (the installer, installing for everyone, elevated) under HKLM instead. Linux and macOS: in//! each installed browser's own host folder (the app does it at every start, as there is no-//! installer step), or the system-wide ones with `--all-users`. Nothing else.+//! installer step), or the system-wide ones with `--all-users`. A browser that reads a+//! system-wide manifest naming this same program (the .deb's or .rpm's) gets none in the home+//! folder: the package manager removes the package's with it (#266).+//! - `misterdownloadmanager-nmhost --package-manifests <root>` (Linux, the .deb and .rpm build):+//! writes the system-wide manifests under `<root>`, naming the packaged helper+//! (`/usr/bin/misterdownloadmanager-nmhost`). Nothing else.use std::io::{self, Read, Write};use std::path::PathBuf;@@ -680,26 +685,32 @@ fn serve() -> io::Result<()> {Ok(())}-/// The manifest Chromium browsers read: the host may serve our extension's origin only.-fn chromium_manifest() -> Result<serde_json::Value, String> {- Ok(serde_json::json!({+/// This program, which the manifests name.+fn this_program() -> Result<PathBuf, String> {+ std::env::current_exe().map_err(|e| e.to_string())+}++/// The manifest Chromium browsers read: the host (`program`) may serve our extension's origin+/// only.+fn chromium_manifest(program: &std::path::Path) -> serde_json::Value {+ serde_json::json!({"name": HOST_NAME,"description": "Mister Download Manager",- "path": std::env::current_exe().map_err(|e| e.to_string())?,+ "path": program,"type": "stdio","allowed_origins": chromium_ids().into_iter().map(origin).collect::<Vec<_>>(),- }))+ })}/// Firefox's manifest: the same host, allowed for our add-on ID instead of an origin.-fn firefox_manifest() -> Result<serde_json::Value, String> {- Ok(serde_json::json!({+fn firefox_manifest(program: &std::path::Path) -> serde_json::Value {+ serde_json::json!({"name": HOST_NAME,"description": "Mister Download Manager",- "path": std::env::current_exe().map_err(|e| e.to_string())?,+ "path": program,"type": "stdio","allowed_extensions": [FIREFOX_ID],- }))+ })}fn write_json(path: &std::path::Path, value: &serde_json::Value) -> Result<(), String> {@@ -741,7 +752,7 @@ fn register(all_users: bool) -> Result<(), String> {portable_refused()?;let root = if all_users { "HKLM" } else { "HKCU" };let path = exe_dir()?.join(format!("{HOST_NAME}.json"));- write_json(&path, &chromium_manifest()?)?;+ write_json(&path, &chromium_manifest(&this_program()?))?;for key in REGISTRY_KEYS {reg(&["add",@@ -755,7 +766,7 @@ fn register(all_users: bool) -> Result<(), String> {])?;}let ff_path = exe_dir()?.join(format!("{HOST_NAME}.firefox.json"));- write_json(&ff_path, &firefox_manifest()?)?;+ write_json(&ff_path, &firefox_manifest(&this_program()?))?;reg(&["add",&format!(r"{root}\{FIREFOX_KEY}\{HOST_NAME}"),@@ -823,14 +834,16 @@ fn reg(args: &[&str]) -> Result<(), String> {/// Linux and macOS: the folders the browsers there read host manifests from, for one user (in/// the home folder) or for everyone, each with whether it is Firefox's (`mdm_ipc::browsers`).+/// With `host`, a user's folder is left out for a browser that reads a manifest for everyone+/// naming it (the package's, #266).#[cfg(not(windows))]-fn host_dirs(all_users: bool) -> Vec<(PathBuf, bool)> {+fn host_dirs(all_users: bool, host: Option<&std::path::Path>) -> Vec<(PathBuf, bool)> {let home = PathBuf::from(std::env::var_os("HOME").unwrap_or_default());let config = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from).filter(|p| p.is_absolute()).unwrap_or_else(|| home.join(".config"));- mdm_ipc::browsers::host_dirs(&home, &config, cfg!(target_os = "macos"), all_users)+ mdm_ipc::browsers::host_dirs(&home, &config, cfg!(target_os = "macos"), all_users, host).into_iter().map(|(d, f)| (d, f == mdm_ipc::browsers::Family::Gecko)).collect()@@ -884,8 +897,36 @@ fn mount_refused() -> Result<(), String> {fn register(all_users: bool) -> Result<(), String> {portable_refused()?;mount_refused()?;- let (chromium, firefox) = (chromium_manifest()?, firefox_manifest()?);- let dirs = host_dirs(all_users);+ let program = this_program()?;+ let (chromium, firefox) = (chromium_manifest(&program), firefox_manifest(&program));+ let dirs = host_dirs(all_users, Some(&program));+ // A browser that reads the package's manifest for everyone, naming this program, needs none+ // in the home folder: one written there before is taken away, so uninstalling the package+ // leaves nothing behind (#266). The browser reads a user's manifest first, so one naming+ // another program (an earlier MDM, an AppImage's copy) would win over the package's: the MDM+ // registered last is the one the browsers start, as when each wrote its own.+ let mut covered = 0;+ if !all_users {+ for (dir, _) in host_dirs(false, None) {+ if dirs.iter().any(|(d, _)| *d == dir) {+ continue;+ }+ covered += 1;+ let manifest = dir.join(format!("{HOST_NAME}.json"));+ if std::fs::remove_file(&manifest).is_ok() {+ println!(+ "removed {} (the browser reads the one for everyone)",+ manifest.display()+ );+ }+ }+ }+ if covered > 0 {+ println!(+ "registered {HOST_NAME} for everyone by the package: {covered} of this user's \+ browser folders need nothing"+ );+ }// One browser's folder that can't be written doesn't keep the others from theirs.let mut failed = Vec::new();for (dir, is_firefox) in &dirs {@@ -898,7 +939,7 @@ fn register(all_users: bool) -> Result<(), String> {Err(e) => failed.push(e),}}- if dirs.is_empty() {+ if dirs.is_empty() && covered == 0 {println!("registered {HOST_NAME} for no browser: none found");}if !failed.is_empty() {@@ -917,7 +958,7 @@ fn register(all_users: bool) -> Result<(), String> {#[cfg(not(windows))]fn unregister(all_users: bool) -> Result<(), String> {- for (dir, _) in host_dirs(all_users) {+ for (dir, _) in host_dirs(all_users, None) {let _ = std::fs::remove_file(dir.join(format!("{HOST_NAME}.json")));}if let Some(dir) = chrome_external_dir(all_users) {@@ -927,12 +968,46 @@ fn unregister(all_users: bool) -> Result<(), String> {Ok(())}+/// Linux: where the .deb and .rpm install this program, which their manifests name.+#[cfg(target_os = "linux")]+const PACKAGED_HOST: &str = "/usr/bin/misterdownloadmanager-nmhost";++/// Linux (the .deb and .rpm build, tools/installer/build-linux.sh): the manifests for everyone,+/// in each folder the browsers read them from (`mdm_ipc::browsers::LINUX_SYSTEM_HOST_DIRS`),+/// under `root`, naming the packaged helper. The package owns them, so the package manager+/// removes them with it (#266).+#[cfg(target_os = "linux")]+fn package_manifests(root: Option<&str>) -> Result<(), String> {+ let root = std::path::Path::new(root.ok_or("--package-manifests needs a folder")?);+ let program = std::path::Path::new(PACKAGED_HOST);+ for (dir, family) in mdm_ipc::browsers::LINUX_SYSTEM_HOST_DIRS {+ let dir = root.join(dir.trim_start_matches('/'));+ std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ let manifest = match family {+ mdm_ipc::browsers::Family::Chromium => chromium_manifest(program),+ mdm_ipc::browsers::Family::Gecko => firefox_manifest(program),+ };+ let path = dir.join(format!("{HOST_NAME}.json"));+ write_json(&path, &manifest)?;+ println!("{}", path.display());+ }+ Ok(())+}++/// The system-wide manifests are packaged for Linux only (macOS's and Windows' installers+/// register with `--register --all-users`).+#[cfg(not(target_os = "linux"))]+fn package_manifests(_: Option<&str>) -> Result<(), String> {+ Err("--package-manifests: the .deb and .rpm are Linux's".into())+}+fn main() {let args: Vec<String> = std::env::args().skip(1).collect();let all_users = args.iter().any(|a| a == "--all-users");let result = match args.first().map(String::as_str).unwrap_or_default() {"--register" => register(all_users),"--unregister" => unregister(all_users),+ "--package-manifests" => package_manifests(args.get(1).map(String::as_str)),// Browsers start the host naming the caller: serve only our own extension (the// manifests' allowed_origins / allowed_extensions say the same; this is a second check)._ if our_caller(&args) => serve().map_err(|e| e.to_string()),@@ -963,7 +1038,7 @@ mod tests {/// served: the manifest's allowed_origins and the host's own caller check agree.#[test]fn store_and_unpacked_extensions_both_allowed() {- let manifest = chromium_manifest().unwrap();+ let manifest = chromium_manifest(&this_program().unwrap());for id in ["ejoleppdfgjdndddcjoehopknmlglojp","oogbclbbninliongijffeeggalppliok",diff --git a/docs/browser-help.md b/docs/browser-help.mdindex 8208f2c0..e39fc0a1 100644--- a/docs/browser-help.md+++ b/docs/browser-help.md@@ -35,7 +35,7 @@ The browser started MDM's helper, but it stopped before answering. Security soft- Allow `misterdownloadmanager-nmhost.exe` (in MDM's folder) in your antivirus or anti-malware program.- Reinstall MDM to restore its files.- On Linux, with Firefox or Chromium installed as a Snap, see [Flatpak and Snap browsers](#linux-sandbox).-- Uninstalled MDM on Linux? Its browser files stay in your home folder: [remove them](getting-started.md#uninstall-linux), and the extension too.+- Uninstalled MDM on Linux? The .deb and .rpm take their browser files with them; the AppImage's and the tar.gz's stay in your home folder: [remove them](getting-started.md#uninstall-linux), and the extension too.## MDM doesn't accept this copy of the extension {#forbidden}@@ -85,7 +85,7 @@ An add-on loaded with **Load Temporary Add-on** (from `about:debugging`) is remoBrowsers installed as a Flatpak or a Snap run in a sandbox, which decides whether they can reach MDM.-- **Firefox as a Snap** (Ubuntu's own Firefox) reaches MDM through the desktop. The first time the extension calls MDM, the desktop asks **Allow Firefox to start WebExtension backend?** for Mister Download Manager: choose **Allow**. After **Don't allow**, the extension says the connection failed and the desktop doesn't ask again; to be asked again, run this in a terminal, then use the extension again:+- **Firefox as a Snap** (Ubuntu's own Firefox) reaches MDM through the desktop, which reads the browser files in your home folder and those the .deb or .rpm installs for everyone. The first time the extension calls MDM, the desktop asks **Allow Firefox to start WebExtension backend?** for Mister Download Manager: choose **Allow**. After **Don't allow**, the extension says the connection failed and the desktop doesn't ask again; to be asked again, run this in a terminal, then use the extension again:`gdbus call --session --dest org.freedesktop.impl.portal.PermissionStore --object-path /org/freedesktop/impl/portal/PermissionStore --method org.freedesktop.impl.portal.PermissionStore.Delete webextensions com.misterdownloadmanager.host`- **Chromium as a Snap** (Ubuntu's Chromium) starts MDM's helper inside its sandbox, where it can't reach MDM, so MDM doesn't list it in **Add Mister Download Manager to your browser**. Use Firefox, or Google Chrome from its own `.deb`.diff --git a/docs/getting-started.md b/docs/getting-started.mdindex 4822fcc2..5be0587d 100644--- a/docs/getting-started.md+++ b/docs/getting-started.md@@ -73,12 +73,17 @@ And on the other desktops it was checked on:#### Uninstall on Linux {#uninstall-linux}`sudo apt remove misterdownloadmanager` (or `sudo dnf remove misterdownloadmanager`) removes the-programs; for the AppImage or the tar.gz, delete the file or the folder. What MDM keeps in your-home folder stays, as with any package: your list and settings-(`~/.local/share/misterdownloadmanager`) and the small files that tell your browsers where MDM's-helper is. A package can't remove those: it never touches home folders. Without MDM they lead-nowhere, so the extension says it can't reach MDM. To remove them as well, run this as each user-who used MDM, **before** uninstalling:+programs, and the small files that tell your browsers where MDM's helper is: the .deb and .rpm+install those for everyone (in `/etc` and `/usr/lib`), for Chrome, Chromium, Edge, Brave, Vivaldi+and Firefox (the Snap too), so MDM doesn't write them in your home folder. For the AppImage or the+tar.gz, delete the file or the folder.++What MDM keeps in your home folder stays, as with any package: your list and settings+(`~/.local/share/misterdownloadmanager`), the AppImage's and the tar.gz's browser files, and+those of the browsers that read them only there (Opera, Helium, Thorium, and Firefox's forks:+Zen, LibreWolf, Floorp, Waterfox). A package can't remove those: it never touches+home folders. Without MDM they lead nowhere, so the extension says it can't reach MDM. To remove+them as well, run this as each user who used MDM, **before** uninstalling:```shmisterdownloadmanager-nmhost --unregisterdiff --git a/tools/installer/build-linux.sh b/tools/installer/build-linux.shindex eee0eb9b..fa03c93a 100755--- a/tools/installer/build-linux.sh+++ b/tools/installer/build-linux.sh@@ -84,8 +84,18 @@ tar -C "$stage" -czf "$dist/$name.tar.gz" "$name"# libxkbcommon-x11 (winit's keyboard under X11, and XWayland, MDM's default in a Wayland session)# the window panics at start; EGL draws Wayland windows; without the CA certificates no download# starts, HTTP ones too ("No CA certificates were loaded from the system"). GTK pulls in the rest.+# The browsers' host manifests for everyone (#266), in the .deb and .rpm only: each folder the+# browsers read them from (/etc/opt/chrome, /etc/chromium, /etc/opt/edge, /usr/lib/mozilla and+# /usr/lib64/mozilla), naming /usr/bin/misterdownloadmanager-nmhost. The package owns them, so+# uninstalling it removes them (not conffiles: `apt remove` takes them too), and MDM writes none+# in the home folder for a browser that reads them. The AppImage and the tar.gz register per user.+system="$stage/system"+"$tree/usr/bin/misterdownloadmanager-nmhost" --package-manifests "$system"deb="$stage/deb"cp -r "$tree" "$deb"+# Debian and Ubuntu's Firefox reads /usr/lib/mozilla; lib64's is Fedora's and openSUSE's.+cp -r "$system/." "$deb/"+rm -rf "$deb/usr/lib64"mkdir -p "$deb/DEBIAN"cat > "$deb/DEBIAN/control" <<EOFPackage: misterdownloadmanager@@ -121,6 +131,7 @@ browser, and downloads videos and torrents.%installcp -a "$tree/." %{buildroot}/+cp -a "$system/." %{buildroot}/%files/usr/bin/misterdownloadmanager@@ -131,6 +142,8 @@ cp -a "$tree/." %{buildroot}//usr/share/icons/hicolor/256x256/apps/misterdownloadmanager.png/usr/share/misterdownloadmanager/usr/share/doc/misterdownloadmanager+$(cd "$system" && find . -mindepth 1 -type d | sed 's|^\.||' | grep -Ev '^/(etc|etc/opt|usr|usr/lib|usr/lib64)$' | sort | sed 's|^|%dir |')+$(cd "$system" && find . -type f | sed 's|^\.||' | sort)EOFrpmbuild --define "_topdir $rpm" --define "_build_id_links none" -bb "$rpm/SPECS/mdm.spec"cp "$rpm"/RPMS/x86_64/*.rpm "$dist/$name.rpm"diff --git a/tools/lab/linux-vm/store-check.mjs b/tools/lab/linux-vm/store-check.mjsindex 41f44428..f1f97067 100644--- a/tools/lab/linux-vm/store-check.mjs+++ b/tools/lab/linux-vm/store-check.mjs@@ -179,10 +179,14 @@ if (browser === "firefox") {fs.rmSync(profile, { recursive: true, force: true });const downloads = path.join(profile, "downloads");fs.mkdirSync(downloads, { recursive: true });- // With --user-data-dir, Chrome reads host manifests from <user-data-dir>/NativeMessagingHosts.+ // With --user-data-dir, Chrome reads host manifests from <user-data-dir>/NativeMessagingHosts,+ // then from everyone's (/etc/opt/chrome/native-messaging-hosts): the user's is copied there when+ // there is one (with the .deb or .rpm installed there is none, #266, and everyone's is read).const hosts = path.join(profile, "NativeMessagingHosts");fs.mkdirSync(hosts, { recursive: true });- fs.copyFileSync(path.join(process.env.HOME, ".config/google-chrome/NativeMessagingHosts/com.misterdownloadmanager.host.json"), path.join(hosts, "com.misterdownloadmanager.host.json"));+ const mine = path.join(process.env.HOME, ".config/google-chrome/NativeMessagingHosts/com.misterdownloadmanager.host.json");+ if (fs.existsSync(mine)) fs.copyFileSync(mine, path.join(hosts, "com.misterdownloadmanager.host.json"));+ say(`host manifest: ${fs.existsSync(mine) ? mine : "/etc/opt/chrome/native-messaging-hosts (none in the home folder)"}`);const proc = spawn("/usr/bin/google-chrome",["--headless", "--remote-debugging-pipe", "--enable-unsafe-extension-debugging", "--password-store=basic", `--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check", "about:blank"],