Skip to content

A hardened Linux desktop, rebuilt from scratch, with your Windows apps built in. Free and open source.

Sync with build 503: Beta 1

Dan547bcdd8f63f
diff --git a/packages/wildos-archive/CMakeLists.txt b/packages/wildos-archive/CMakeLists.txt
index 7c40f5f..20c34d5 100644
--- a/packages/wildos-archive/CMakeLists.txt
+++ b/packages/wildos-archive/CMakeLists.txt
@@ -33,6 +33,7 @@ qt_add_qml_module(wildos-archive
src/progress.h
src/reader.cpp src/reader.h
src/thumbnails.cpp src/thumbnails.h
+ src/tools.cpp src/tools.h
src/entrymodel.cpp src/entrymodel.h
src/session.cpp src/session.h
src/maker.cpp src/maker.h
diff --git a/packages/wildos-archive/debian/changelog b/packages/wildos-archive/debian/changelog
index e31e604..c7930f5 100644
--- a/packages/wildos-archive/debian/changelog
+++ b/packages/wildos-archive/debian/changelog
@@ -1,3 +1,19 @@
+wildos-archive (0.1.2) trixie; urgency=medium
+
+ * Opens password-protected 7z and RAR archives, hidden file names
+ included: Archive asks for the password, then lists, extracts, tests
+ and shows pictures from them. 7-Zip reads protected 7z, The
+ Unarchiver protected RAR 5; libarchive still reads everything else.
+ * The password never goes on a command line or to disk.
+ * Files from 7-Zip and The Unarchiver are unpacked into a private
+ folder first and only then moved into place, with the same checks as
+ every other archive: nothing lands outside the folder you chose.
+ * RAR files protected with the older RAR 4 encryption say so plainly.
+ No free tool can unlock them yet.
+ * The icon ink in light mode is the warm grey of the rest of Wild OS.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 11:00:00 +0000
+
wildos-archive (0.1.1) trixie; urgency=medium
* Extract here asks before extracting into a folder that is already
diff --git a/packages/wildos-archive/debian/control b/packages/wildos-archive/debian/control
index 40721fc..83fab95 100644
--- a/packages/wildos-archive/debian/control
+++ b/packages/wildos-archive/debian/control
@@ -32,6 +32,8 @@ Depends:
qml6-module-qtquick-dialogs,
qml6-module-qtqml-workerscript,
qt6-svg-plugins,
+ 7zip,
+ unar,
Description: Wild OS Archive
Archive opens ZIP, 7z, RAR and TAR archives and GZ, XZ, BZ2 and ZST
files, on libarchive. Browse an archive's folders with picture
diff --git a/packages/wildos-archive/qml/ArchiveStyle.qml b/packages/wildos-archive/qml/ArchiveStyle.qml
index 729a6a8..1701792 100644
--- a/packages/wildos-archive/qml/ArchiveStyle.qml
+++ b/packages/wildos-archive/qml/ArchiveStyle.qml
@@ -30,7 +30,7 @@ QtObject {
readonly property color checkEdge: contrast ? "#ffffff" : dark ? Qt.rgba(1, 1, 1, 0.55) : Qt.rgba(0, 0, 0, 0.429)
readonly property color folderInk: contrast ? "#ffffff" : dark ? "#f2b84d" : "#96722f"
- readonly property color iconInk: contrast ? "#ffffff" : dark ? Qt.rgba(1, 1, 1, 0.86) : "#2a3147"
+ readonly property color iconInk: contrast ? "#ffffff" : dark ? Qt.rgba(1, 1, 1, 0.86) : "#34363a"
readonly property color fileInk: UI.Style.inkMuted
readonly property color thumbBlank: UI.Style.surfaceTile
diff --git a/packages/wildos-archive/qml/Banner.qml b/packages/wildos-archive/qml/Banner.qml
index 8134a03..bd42caf 100644
--- a/packages/wildos-archive/qml/Banner.qml
+++ b/packages/wildos-archive/qml/Banner.qml
@@ -10,6 +10,10 @@ Rectangle {
property string text
property string iconName: "info"
property bool warning: false
+ // Words that act, at the end of the note.
+ property string action
+
+ signal activated()
implicitHeight: Math.max(36, label.implicitHeight + 16)
radius: 8
@@ -30,11 +34,21 @@ Rectangle {
id: label
anchors.left: icon.right
anchors.leftMargin: 10
- anchors.right: parent.right
- anchors.rightMargin: 12
+ anchors.right: link.visible ? link.left : parent.right
+ anchors.rightMargin: link.visible ? 8 : 12
anchors.verticalCenter: parent.verticalCenter
text: banner.text
size: 12.5
wrapMode: Text.Wrap
}
+ UI.LinkButton {
+ id: link
+ anchors.right: parent.right
+ anchors.rightMargin: 8
+ anchors.verticalCenter: parent.verticalCenter
+ visible: banner.action.length > 0
+ text: banner.action
+ size: 13
+ onClicked: banner.activated()
+ }
}
diff --git a/packages/wildos-archive/qml/ExtractHereWindow.qml b/packages/wildos-archive/qml/ExtractHereWindow.qml
index b2c0524..3a1fff6 100644
--- a/packages/wildos-archive/qml/ExtractHereWindow.qml
+++ b/packages/wildos-archive/qml/ExtractHereWindow.qml
@@ -58,8 +58,8 @@ UI.AppWindow {
window.problem(qsTr("Archive couldn't open %1").arg(fileName), errorText, []);
} else if (state === "ready") {
if (lockedFormat) {
- window.problem(qsTr("This archive is protected"),
- qsTr("%1 is a %2 archive with a password. Archive can't open protected 7z and RAR files yet.").arg(fileName).arg(formatName), []);
+ window.problem(qsTr("Archive can't unlock this RAR"),
+ qsTr("%1 is protected with the older RAR 4 encryption, which Archive can't unlock. Ask whoever sent it for a 7z or ZIP copy.").arg(fileName), []);
} else {
// Asks for the password first when there is one, then
// carries on.
@@ -217,6 +217,7 @@ UI.AppWindow {
onAccepted: {
if (text.length > 0) {
archive.setPassword(text);
+ text = "";
}
}
}
@@ -283,7 +284,10 @@ UI.AppWindow {
kind: "primary"
text: qsTr("Unlock")
enabled: passwordField.text.length > 0
- onClicked: archive.setPassword(passwordField.text)
+ onClicked: {
+ archive.setPassword(passwordField.text);
+ passwordField.text = "";
+ }
}
UI.Button {
kind: window.problemTitle.length > 0 && window.clash.length === 0 ? "primary" : "secondary"
diff --git a/packages/wildos-archive/qml/Main.qml b/packages/wildos-archive/qml/Main.qml
index 01d58e0..2595f6d 100644
--- a/packages/wildos-archive/qml/Main.qml
+++ b/packages/wildos-archive/qml/Main.qml
@@ -419,7 +419,18 @@ UI.AppWindow {
visible: window.ready && archive.lockedFormat
warning: true
iconName: "lock"
- text: qsTr("This %1 archive is protected with a password. Archive can't open protected 7z and RAR files yet.").arg(archive.formatName)
+ text: qsTr("This RAR is protected with the older RAR 4 encryption, which Archive can't unlock. You can see what's in it, but not extract it.")
+ }
+ Banner {
+ Layout.fillWidth: true
+ Layout.leftMargin: 16
+ Layout.rightMargin: 16
+ Layout.bottomMargin: 8
+ visible: window.ready && archive.namesHidden
+ iconName: "lock"
+ text: qsTr("This archive is protected with a password, and even the names of its files are hidden until you enter it.")
+ action: qsTr("Enter password")
+ onActivated: archive.askPassword()
}
Banner {
Layout.fillWidth: true
@@ -800,6 +811,7 @@ UI.AppWindow {
onAccepted: {
if (text.length > 0) {
archive.setPassword(text);
+ text = "";
passwordDialog.close();
}
}
@@ -810,6 +822,7 @@ UI.AppWindow {
text: qsTr("Cancel")
onClicked: {
archive.forgetPending();
+ passwordField.text = "";
passwordDialog.close();
}
},
@@ -819,6 +832,7 @@ UI.AppWindow {
enabled: passwordField.text.length > 0
onClicked: {
archive.setPassword(passwordField.text);
+ passwordField.text = "";
passwordDialog.close();
}
}
diff --git a/packages/wildos-archive/src/reader.cpp b/packages/wildos-archive/src/reader.cpp
index a5402c2..3734553 100644
--- a/packages/wildos-archive/src/reader.cpp
+++ b/packages/wildos-archive/src/reader.cpp
@@ -1,6 +1,7 @@
#include "reader.h"
#include "format.h"
+#include "tools.h"
#include <archive.h>
#include <archive_entry.h>
@@ -11,12 +12,18 @@
#include <QFile>
#include <QFileInfo>
#include <QImageReader>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
#include <QSaveFile>
+#include <QSet>
+#include <QStandardPaths>
#include <QTemporaryFile>
#include <QtEndian>
#include <cerrno>
#include <cstring>
+#include <memory>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
@@ -346,18 +353,117 @@ bool safePath(const QString &stored, QString *clean)
return safe;
}
-Listing list(const QString &path, Progress *progress)
+namespace
{
- Listing listing;
- const QFileInfo info(path);
- if (!info.isFile()) {
- listing.error = QStringLiteral("This file isn't there any more.");
- return listing;
+// The tree of entries, built as they come in archive order.
+struct Builder {
+ Listing &listing;
+ QHash<QString, int> dirs;
+
+ int add(Entry entry)
+ {
+ const int index = int(listing.entries.size());
+ if (entry.parent >= 0) {
+ listing.entries[entry.parent].children.append(index);
+ } else {
+ listing.roots.append(index);
+ }
+ listing.entries.append(std::move(entry));
+ return index;
}
- if (!info.isReadable()) {
- listing.error = QStringLiteral("You don't have permission to open this file.");
- return listing;
+
+ int ensureDir(const QString &dirPath)
+ {
+ if (dirPath.isEmpty()) {
+ return -1;
+ }
+ const auto it = dirs.constFind(dirPath);
+ if (it != dirs.constEnd()) {
+ return it.value();
+ }
+ const int slash = int(dirPath.lastIndexOf(QLatin1Char('/')));
+ Entry dir;
+ dir.parent = ensureDir(slash < 0 ? QString() : dirPath.left(slash));
+ dir.path = dirPath;
+ dir.name = dirPath.mid(slash + 1);
+ dir.dir = true;
+ const int index = add(dir);
+ dirs.insert(dirPath, index);
+ return index;
+ }
+
+ // `entry` comes with its order, type, sizes, time and link.
+ void place(Entry entry, const QString &stored)
+ {
+ QString clean;
+ const bool safe = safePath(stored, &clean);
+ if (safe && clean.isEmpty()) {
+ listing.byOrder.append(-1);
+ return;
+ }
+ if (!safe) {
+ entry.unsafe = true;
+ entry.path = stored;
+ entry.name = stored;
+ listing.byOrder.append(add(entry));
+ return;
+ }
+ const int slash = int(clean.lastIndexOf(QLatin1Char('/')));
+ entry.path = clean;
+ entry.name = clean.mid(slash + 1);
+ if (entry.dir) {
+ const auto it = dirs.constFind(clean);
+ if (it != dirs.constEnd()) {
+ Entry &known = listing.entries[it.value()];
+ known.order = entry.order;
+ known.modified = entry.modified;
+ known.toolPath = entry.toolPath;
+ listing.byOrder.append(it.value());
+ return;
+ }
+ }
+ entry.parent = ensureDir(slash < 0 ? QString() : clean.left(slash));
+ entry.image = !entry.dir && !entry.symlink && Format::isImage(entry.name);
+ const bool isDir = entry.dir;
+ const int index = add(entry);
+ if (isDir) {
+ dirs.insert(clean, index);
+ }
+ listing.byOrder.append(index);
+ }
+};
+
+// Children always come after their folder, so one pass from the end adds
+// every file into each folder above it.
+void addUp(Listing &listing)
+{
+ for (qsizetype i = listing.entries.size() - 1; i >= 0; --i) {
+ Entry &entry = listing.entries[i];
+ if (!entry.dir) {
+ entry.fileCount = 1;
+ listing.totalSize += entry.size;
+ ++listing.fileCount;
+ }
+ if (entry.parent >= 0) {
+ Entry &parent = listing.entries[entry.parent];
+ parent.size += entry.size;
+ parent.fileCount += entry.fileCount;
+ if (entry.packed >= 0 && listing.packedPerFile) {
+ parent.packed = qMax<qint64>(parent.packed, 0) + entry.packed;
+ }
+ }
+ }
+ for (Entry &entry : listing.entries) {
+ if (entry.dir) {
+ entry.packed = -1;
+ }
}
+}
+
+Listing listLibarchive(const QString &path, Progress *progress)
+{
+ Listing listing;
+ const QFileInfo info(path);
listing.packedSize = info.size();
progress->total = info.size();
@@ -376,39 +482,10 @@ Listing list(const QString &path, Progress *progress)
listing.error = errorOf(h.a);
return listing;
}
- QHash<QString, int> dirs;
+ Builder builder{listing, {}};
int order = 0;
bool retry = false;
- const auto add = [&listing](Entry entry) {
- const int index = int(listing.entries.size());
- if (entry.parent >= 0) {
- listing.entries[entry.parent].children.append(index);
- } else {
- listing.roots.append(index);
- }
- listing.entries.append(std::move(entry));
- return index;
- };
- std::function<int(const QString &)> ensureDir = [&](const QString &dirPath) -> int {
- if (dirPath.isEmpty()) {
- return -1;
- }
- const auto it = dirs.constFind(dirPath);
- if (it != dirs.constEnd()) {
- return it.value();
- }
- const int slash = int(dirPath.lastIndexOf(QLatin1Char('/')));
- Entry dir;
- dir.parent = ensureDir(slash < 0 ? QString() : dirPath.left(slash));
- dir.path = dirPath;
- dir.name = dirPath.mid(slash + 1);
- dir.dir = true;
- const int index = add(dir);
- dirs.insert(dirPath, index);
- return index;
- };
-
archive_entry *e = nullptr;
for (;;) {
if (progress->cancel) {
@@ -446,19 +523,10 @@ Listing list(const QString &path, Progress *progress)
const QString stored = raw ? Format::archiveBaseName(info.fileName()) : storedPath(e);
const mode_t type = archive_entry_filetype(e);
- const bool isDir = type == AE_IFDIR || stored.endsWith(QLatin1Char('/'));
- QString clean;
- const bool safe = safePath(stored, &clean);
- const int thisOrder = order++;
- if (safe && clean.isEmpty()) {
- listing.byOrder.append(-1);
- continue;
- }
-
Entry entry;
- entry.order = thisOrder;
- entry.dir = isDir;
- entry.size = !isDir && archive_entry_size_is_set(e) ? archive_entry_size(e) : 0;
+ entry.order = order++;
+ entry.dir = type == AE_IFDIR || stored.endsWith(QLatin1Char('/'));
+ entry.size = !entry.dir && archive_entry_size_is_set(e) ? archive_entry_size(e) : 0;
if (archive_entry_mtime_is_set(e)) {
entry.modified = QDateTime::fromSecsSinceEpoch(archive_entry_mtime(e));
}
@@ -481,34 +549,7 @@ Listing list(const QString &path, Progress *progress)
progress->done = before;
entry.modified = info.lastModified();
}
-
- if (!safe) {
- entry.unsafe = true;
- entry.path = stored;
- entry.name = stored;
- listing.byOrder.append(add(entry));
- continue;
- }
- const int slash = int(clean.lastIndexOf(QLatin1Char('/')));
- entry.path = clean;
- entry.name = clean.mid(slash + 1);
- if (isDir) {
- const auto it = dirs.constFind(clean);
- if (it != dirs.constEnd()) {
- Entry &known = listing.entries[it.value()];
- known.order = thisOrder;
- known.modified = entry.modified;
- listing.byOrder.append(it.value());
- continue;
- }
- }
- entry.parent = ensureDir(slash < 0 ? QString() : clean.left(slash));
- entry.image = !isDir && !entry.symlink && Format::isImage(entry.name);
- const int index = add(entry);
- if (isDir) {
- dirs.insert(clean, index);
- }
- listing.byOrder.append(index);
+ builder.place(entry, stored);
}
if (retry) {
continue;
@@ -529,33 +570,7 @@ Listing list(const QString &path, Progress *progress)
listing.entries.first().packed = listing.packedSize;
listing.packedPerFile = true;
}
- if (listing.encrypted && (base == ARCHIVE_FORMAT_7ZIP || base == ARCHIVE_FORMAT_RAR || base == ARCHIVE_FORMAT_RAR_V5)) {
- listing.lockedHeaders = true;
- }
-
- // Children always come after their folder, so one pass from the
- // end adds every file into each folder above it.
- for (qsizetype i = listing.entries.size() - 1; i >= 0; --i) {
- Entry &entry = listing.entries[i];
- if (!entry.dir) {
- entry.fileCount = 1;
- listing.totalSize += entry.size;
- ++listing.fileCount;
- }
- if (entry.parent >= 0) {
- Entry &parent = listing.entries[entry.parent];
- parent.size += entry.size;
- parent.fileCount += entry.fileCount;
- if (entry.packed >= 0 && listing.packedPerFile) {
- parent.packed = qMax<qint64>(parent.packed, 0) + entry.packed;
- }
- }
- }
- for (Entry &entry : listing.entries) {
- if (entry.dir) {
- entry.packed = -1;
- }
- }
+ addUp(listing);
progress->done = progress->total.load();
return listing;
}
@@ -563,11 +578,315 @@ Listing list(const QString &path, Progress *progress)
return listing;
}
-PasswordState checkPassword(const QString &path, const Listing &listing, const QByteArray &password)
+enum class Magic { Other, SevenZip, Rar4, Rar5 };
+
+Magic magic(const QString &path)
+{
+ QFile file(path);
+ if (!file.open(QIODevice::ReadOnly)) {
+ return Magic::Other;
+ }
+ const QByteArray head = file.read(8);
+ static const QByteArray sevenZip("7z\xbc\xaf\x27\x1c", 6);
+ static const QByteArray rar5("Rar!\x1a\x07\x01\x00", 8);
+ static const QByteArray rar4("Rar!\x1a\x07\x00", 7);
+ if (head.startsWith(sevenZip)) {
+ return Magic::SevenZip;
+ }
+ if (head.startsWith(rar5)) {
+ return Magic::Rar5;
+ }
+ return head.startsWith(rar4) ? Magic::Rar4 : Magic::Other;
+}
+
+// Whether libarchive can decompress the first file it would need to. It
+// lists every RAR but cannot unpack some of them (old methods, some RAR 5
+// features), and that is better found now than when every file fails.
+bool decompresses(const QString &path)
+{
+ Handle h(newReader({}, false));
+ if (!openFile(h.a, path)) {
+ return false;
+ }
+ archive_entry *e = nullptr;
+ while (archive_read_next_header(h.a, &e) >= ARCHIVE_WARN) {
+ if (archive_entry_is_data_encrypted(e) || archive_entry_filetype(e) != AE_IFREG || archive_entry_size(e) == 0) {
+ continue;
+ }
+ char buffer[16384];
+ return archive_read_data(h.a, buffer, sizeof buffer) >= 0;
+ }
+ return true;
+}
+
+Listing lockedListing(const QString &tool, const QString &format, qint64 size)
+{
+ Listing listing;
+ listing.tool = tool;
+ listing.format = format;
+ listing.packedSize = size;
+ listing.encrypted = true;
+ listing.lockedHeaders = true;
+ return listing;
+}
+
+Listing fromTool(const Tools::Contents &contents, const QString &tool, const QString &format, qint64 size)
+{
+ Listing listing;
+ listing.tool = tool;
+ listing.format = format;
+ listing.packedSize = size;
+ Builder builder{listing, {}};
+ bool packedPerFile = true;
+ for (int i = 0; i < contents.items.size(); ++i) {
+ const Tools::Item &item = contents.items[i];
+ if (item.path.isEmpty()) {
+ listing.byOrder.append(-1);
+ continue;
+ }
+ Entry entry;
+ entry.order = i;
+ entry.dir = item.dir;
+ entry.size = item.dir ? 0 : item.size;
+ entry.packed = item.dir ? -1 : item.packed;
+ entry.modified = item.modified;
+ entry.symlink = item.symlink && !item.dir;
+ entry.linkTarget = item.linkTarget;
+ entry.encrypted = item.encrypted;
+ entry.toolPath = item.path;
+ entry.executable = item.executable;
+ listing.encrypted = listing.encrypted || item.encrypted;
+ packedPerFile = packedPerFile && (item.dir || item.packed >= 0);
+ builder.place(entry, item.path);
+ }
+
+ // A path under a file or a link is never extracted: a tool could
+ // write it through a link it made a moment before.
+ QSet<QString> notFolders;
+ for (const Entry &e : std::as_const(listing.entries)) {
+ if (!e.dir && !e.unsafe) {
+ notFolders.insert(e.path);
+ }
+ }
+ for (Entry &e : listing.entries) {
+ for (qsizetype at = e.path.indexOf(QLatin1Char('/')); !e.unsafe && at >= 0; at = e.path.indexOf(QLatin1Char('/'), at + 1)) {
+ e.unsafe = notFolders.contains(e.path.left(at));
+ }
+ }
+
+ listing.packedPerFile = packedPerFile;
+ if (!packedPerFile) {
+ for (Entry &e : listing.entries) {
+ e.packed = -1;
+ }
+ }
+ addUp(listing);
+ return listing;
+}
+
+QString missingTool(const QString &program)
+{
+ return program == QLatin1String("7z") ? QStringLiteral("Archive needs 7-Zip (the 7zip package) for this archive, and it isn't installed.")
+ : QStringLiteral("Archive needs The Unarchiver (the unar package) for this archive, and it isn't installed.");
+}
+
+const QString rar4Locked = QStringLiteral(
+ "It's protected with the older RAR 4 encryption, which Archive can't unlock. Ask whoever sent it for a 7z or ZIP copy.");
+
+Listing with7z(const QString &path, const QByteArray &password, Listing fallback, const QString &format, Progress *progress)
+{
+ if (!Tools::available(QStringLiteral("7z"))) {
+ fallback.error = missingTool(QStringLiteral("7z"));
+ fallback.cantDecrypt = fallback.encrypted;
+ return fallback;
+ }
+ const Tools::Contents contents = Tools::list7z(path, password, progress);
+ if (contents.cancelled) {
+ Listing cancelled;
+ cancelled.error = QStringLiteral("cancelled");
+ return cancelled;
+ }
+ if (contents.needsPassword) {
+ return lockedListing(QStringLiteral("7z"), format, fallback.packedSize);
+ }
+ if (!contents.ok) {
+ if (fallback.error.isEmpty()) {
+ fallback.error = contents.error;
+ }
+ return fallback;
+ }
+ return fromTool(contents, QStringLiteral("7z"), format, fallback.packedSize);
+}
+
+Listing withUnar(const QString &path, const QByteArray &password, Listing fallback, Magic kind, Progress *progress)
+{
+ if (!Tools::available(QStringLiteral("unar")) || !Tools::available(QStringLiteral("lsar"))) {
+ fallback.error = missingTool(QStringLiteral("unar"));
+ fallback.cantDecrypt = fallback.encrypted;
+ return fallback;
+ }
+ const QString format = QStringLiteral("RAR");
+ Tools::Contents contents = Tools::listLsar(path, progress);
+ if (contents.needsPassword) {
+ if (kind == Magic::Rar4) {
+ Listing locked;
+ locked.format = format;
+ locked.error = rar4Locked;
+ return locked;
+ }
+ if (password.isEmpty()) {
+ return lockedListing(QStringLiteral("unar"), format, fallback.packedSize);
+ }
+ // lsar takes a password only on its command line, so the hidden
+ // names come from 7-Zip, which reads RAR headers (but cannot
+ // decompress RAR without the non-free plugin) and lists them in
+ // the same order. unar still does the unpacking.
+ if (!Tools::available(QStringLiteral("7z"))) {
+ fallback.error = missingTool(QStringLiteral("7z"));
+ return fallback;
+ }
+ contents = Tools::list7z(path, password, progress);
+ if (contents.needsPassword) {
+ return lockedListing(QStringLiteral("unar"), format, fallback.packedSize);
+ }
+ }
+ if (contents.cancelled) {
+ Listing cancelled;
+ cancelled.error = QStringLiteral("cancelled");
+ return cancelled;
+ }
+ if (!contents.ok) {
+ if (fallback.error.isEmpty()) {
+ fallback.error = contents.error;
+ }
+ fallback.cantDecrypt = fallback.encrypted;
+ return fallback;
+ }
+ Listing listing = fromTool(contents, QStringLiteral("unar"), format, fallback.packedSize);
+ // lsar says "RAR" or "RAR 5", 7-Zip "Rar" or "Rar5".
+ const bool rar4 = kind == Magic::Rar4 || contents.type.compare(QLatin1String("RAR"), Qt::CaseInsensitive) == 0;
+ listing.cantDecrypt = rar4 && listing.encrypted;
+ return listing;
+}
+
+QString privateStaging()
+{
+ const QString base = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
+ QDir().mkpath(base);
+ return Tools::makeStaging(base);
+}
+
+// Removed however the function returns, cancel included.
+struct Staging {
+ QString path;
+ explicit Staging(const QString &p)
+ : path(p)
+ {
+ }
+ ~Staging()
+ {
+ Tools::removeTree(path);
+ }
+ Staging(const Staging &) = delete;
+ Staging &operator=(const Staging &) = delete;
+ QString into() const
+ {
+ return path + QStringLiteral("/x");
+ }
+};
+
+// Unpacks the files at `orders` into staging.into(), counting progress
+// towards `total`.
+Tools::Outcome unpack(const QString &archive, const Listing &listing, const QByteArray &password, const QList<int> &orders, const Staging &staging,
+ qint64 total, Progress *progress)
+{
+ ::mkdir(QFile::encodeName(staging.into()).constData(), 0700);
+ Tools::Job job;
+ job.password = password;
+ if (listing.tool == QLatin1String("7z")) {
+ QFile names(staging.path + QStringLiteral("/names"));
+ if (names.open(QIODevice::WriteOnly)) {
+ for (int order : orders) {
+ names.write(listing.entries[listing.byOrder[order]].toolPath.toUtf8() + '\n');
+ }
+ names.close();
+ }
+ job.program = QStringLiteral("7z");
+ job.arguments = {QStringLiteral("x"), QStringLiteral("-y"), QStringLiteral("-bso0"),
+ QStringLiteral("-bse2"), QStringLiteral("-bsp1"), QStringLiteral("-spd"),
+ QStringLiteral("-sccUTF-8"), QStringLiteral("-scsUTF-8"), QStringLiteral("-o") + staging.into(),
+ archive, QStringLiteral("-i@") + names.fileName()};
+ job.line = [progress, total](const QByteArray &line) {
+ // " 45% 3 - name"
+ const QByteArray t = line.trimmed();
+ const qsizetype percent = t.indexOf('%');
+ bool ok = false;
+ const int value = percent > 0 ? t.left(percent).toInt(&ok) : 0;
+ if (ok) {
+ progress->done = total * qBound(0, value, 100) / 100;
+ }
+ };
+ } else {
+ job.program = QStringLiteral("unar");
+ job.terminal = true;
+ // -D: no folder of its own; -nr: not into archives inside it;
+ // -k skip: no Mac resource forks; -s: skip, never ask, if a name
+ // is there twice.
+ job.arguments = {QStringLiteral("-o"), staging.into(), QStringLiteral("-D"), QStringLiteral("-nr"), QStringLiteral("-k"),
+ QStringLiteral("skip"), QStringLiteral("-s"), QStringLiteral("-i"), archive};
+ auto sizes = std::make_shared<QList<qint64>>();
+ for (int order : orders) {
+ job.arguments.append(QString::number(order));
+ sizes->append(listing.entries[listing.byOrder[order]].size);
+ }
+ auto finished = std::make_shared<int>(0);
+ job.line = [progress, sizes, finished](const QByteArray &line) {
+ // unar reports each entry as " name (size)... OK." or
+ // "... Failed! (why)", in the order asked.
+ if ((line.endsWith("OK.") || line.contains("Failed!")) && *finished < sizes->size()) {
+ progress->done += sizes->at((*finished)++);
+ }
+ };
+ }
+ return Tools::run(job, progress);
+}
+
+// The unpacked file for `entry` in staging, when it is a whole plain file.
+QString unpacked(const Staging &staging, const Entry &entry)
+{
+ const QString file = staging.into() + QLatin1Char('/') + entry.path;
+ struct stat st;
+ if (::lstat(QFile::encodeName(file).constData(), &st) != 0 || !S_ISREG(st.st_mode) || st.st_size != entry.size) {
+ return QString();
+ }
+ return file;
+}
+
+// The text of a 7z symlink entry: 7-Zip lists links in 7z archives as
+// small files that hold where they point.
+QString linkTargetOf(const QString &archive, const Entry &entry, const QByteArray &password, Progress *progress)
+{
+ QByteArray target;
+ Tools::Job job;
+ job.program = QStringLiteral("7z");
+ job.arguments = {QStringLiteral("x"), QStringLiteral("-so"), QStringLiteral("-bsp0"), QStringLiteral("-spd"), archive, QStringLiteral("-i!") + entry.toolPath};
+ job.password = password;
+ job.data = [&target](const char *data, qsizetype size) {
+ target.append(data, size);
+ return target.size() <= 4096;
+ };
+ const Tools::Outcome outcome = Tools::run(job, progress);
+ if (outcome.exitCode != 0 || target.size() > 4096) {
+ return QString();
+ }
+ return QString::fromUtf8(target);
+}
+
+Reader::PasswordState checkLibarchive(const QString &path, const Listing &listing, const QByteArray &password)
{
Handle h(newReader(password, listing.raw));
if (!openFile(h.a, path)) {
- return PasswordState::Fine;
+ return Reader::PasswordState::Fine;
}
archive_entry *e = nullptr;
while (archive_read_next_header(h.a, &e) >= ARCHIVE_WARN) {
@@ -576,11 +895,552 @@ PasswordState checkPassword(const QString &path, const Listing &listing, const Q
}
char buffer[16384];
if (archive_read_data(h.a, buffer, sizeof buffer) < 0) {
- return passwordError(h.a) ? passwordState(password) : PasswordState::Fine;
+ return passwordError(h.a) ? passwordState(password) : Reader::PasswordState::Fine;
+ }
+ return Reader::PasswordState::Fine;
+ }
+ return Reader::PasswordState::Fine;
+}
+}
+
+Listing list(const QString &path, const QByteArray &password, Progress *progress)
+{
+ const QFileInfo info(path);
+ if (!info.isFile()) {
+ Listing listing;
+ listing.error = QStringLiteral("This file isn't there any more.");
+ return listing;
+ }
+ if (!info.isReadable()) {
+ Listing listing;
+ listing.error = QStringLiteral("You don't have permission to open this file.");
+ return listing;
+ }
+ Listing listing = listLibarchive(path, progress);
+ if (listing.error == QLatin1String("cancelled")) {
+ return listing;
+ }
+ // libarchive stays first: the tools only take over what it cannot
+ // decrypt or read.
+ const Magic kind = magic(path);
+ const bool failed = !listing.error.isEmpty();
+ if (kind == Magic::SevenZip || listing.format == QLatin1String("7z")) {
+ return failed || listing.encrypted ? with7z(path, password, listing, QStringLiteral("7z"), progress) : listing;
+ }
+ if (kind == Magic::Rar4 || kind == Magic::Rar5 || listing.format == QLatin1String("RAR")) {
+ return failed || listing.encrypted || !decompresses(path) ? withUnar(path, password, listing, kind, progress) : listing;
+ }
+ if (listing.format == QLatin1String("ZIP") && failed && listing.entries.isEmpty() && Tools::available(QStringLiteral("7z"))) {
+ Listing other = with7z(path, password, listing, QStringLiteral("ZIP"), progress);
+ return other.error.isEmpty() || other.lockedHeaders ? other : listing;
+ }
+ return listing;
+}
+
+Unlock unlock(const QString &path, const Listing &listing, const QByteArray &password, Progress *progress)
+{
+ Unlock result;
+ if (listing.tool.isEmpty()) {
+ result.state = checkLibarchive(path, listing, password);
+ return result;
+ }
+ if (listing.lockedHeaders) {
+ Listing named = list(path, password, progress);
+ if (named.error == QLatin1String("cancelled")) {
+ result.state = PasswordState::Needed;
+ return result;
+ }
+ if (named.lockedHeaders) {
+ result.state = PasswordState::Wrong;
+ return result;
+ }
+ // 7z and RAR use the one password for the names and the files.
+ result.relisted = true;
+ result.listing = std::move(named);
+ return result;
+ }
+
+ // A small protected file, tried with the password.
+ const Entry *pick = nullptr;
+ for (const Entry &e : listing.entries) {
+ if (e.encrypted && !e.dir && !e.symlink && !e.unsafe && e.order >= 0 && e.size > 0 && (!pick || e.size < pick->size)) {
+ pick = &e;
+ }
+ }
+ if (!pick) {
+ return result;
+ }
+ if (listing.tool == QLatin1String("7z")) {
+ Tools::Job job;
+ job.program = QStringLiteral("7z");
+ job.arguments = {QStringLiteral("t"), QStringLiteral("-bso0"), QStringLiteral("-bsp0"), QStringLiteral("-spd"), path, QStringLiteral("-i!") + pick->toolPath};
+ job.password = password;
+ result.state = Tools::passwordOutcome(Tools::run(job, progress), password);
+ return result;
+ }
+ const Staging staging(privateStaging());
+ if (staging.path.isEmpty()) {
+ return result;
+ }
+ const Tools::Outcome outcome = unpack(path, listing, password, {pick->order}, staging, pick->size, progress);
+ result.state = Tools::passwordOutcome(outcome, password);
+ return result;
+}
+
+namespace
+{
+QList<int> sortedKeys(const QHash<int, QString> &targets)
+{
+ QList<int> orders = targets.keys();
+ std::sort(orders.begin(), orders.end());
+ return orders;
+}
+
+QImage scaledImage(QByteArray &data, QSize box)
+{
+ QBuffer buffer(&data);
+ buffer.open(QIODevice::ReadOnly);
+ QImageReader reader(&buffer);
+ reader.setAutoTransform(true);
+ const QSize size = reader.size();
+ if (size.isValid()) {
+ const QSize scaled = size.scaled(box, Qt::KeepAspectRatioByExpanding);
+ if (scaled.width() < size.width()) {
+ reader.setScaledSize(scaled);
+ }
+ }
+ return reader.read();
+}
+
+// The tool only ever unpacks plain files, into a private folder inside
+// the destination. Archive then checks each one and moves it into place
+// with the same rules as for what libarchive reads, and makes the folders
+// and links itself, so the tool never writes where it shouldn't, and a
+// cancel or a failure leaves no half file.
+Result extractWithTool(const ExtractOptions &options, const Listing &listing, const QHash<int, QString> &targets, const QString &root, qint64 total,
+ Progress *progress, Result result)
+{
+ const QList<int> orders = sortedKeys(targets);
+ QList<int> files;
+ for (int order : orders) {
+ const Entry &entry = listing.entries[listing.byOrder[order]];
+ if (!entry.dir && !entry.symlink) {
+ files.append(order);
+ }
+ }
+ const Staging staging(Tools::makeStaging(root));
+ if (staging.path.isEmpty()) {
+ result.ok = false;
+ result.error = QStringLiteral("Couldn't write in %1: %2").arg(Format::folder(root), QString::fromLocal8Bit(std::strerror(errno)));
+ return result;
+ }
+ if (!files.isEmpty()) {
+ const Tools::Outcome outcome = unpack(options.archive, listing, options.password, files, staging, total, progress);
+ if (outcome.cancelled) {
+ result.cancelled = true;
+ return result;
+ }
+ if (!outcome.started) {
+ result.ok = false;
+ result.error = QString::fromUtf8(outcome.errors);
+ return result;
+ }
+ const PasswordState state = Tools::passwordOutcome(outcome, options.password);
+ if (state != PasswordState::Fine) {
+ result.ok = false;
+ result.password = state;
+ return result;
+ }
+ }
+ progress->done = progress->total.load();
+
+ for (int order : orders) {
+ if (progress->cancel) {
+ result.cancelled = true;
+ return result;
+ }
+ const Entry &entry = listing.entries[listing.byOrder[order]];
+ const QString rel = targets.value(order);
+ QStringList steps = rel.split(QLatin1Char('/'), Qt::SkipEmptyParts);
+ const QString target = root + QLatin1Char('/') + rel;
+ const QString leaf = steps.isEmpty() ? QString() : steps.takeLast();
+ if (leaf.isEmpty()) {
+ continue;
+ }
+ const Made made = makeDirs(root, entry.dir ? steps + QStringList{leaf} : steps);
+ if (made == Made::Link) {
+ result.unsafe.append(entry.path);
+ continue;
+ }
+ if (made == Made::Blocked) {
+ result.failed.append(QStringLiteral("%1: a file is in the way of its folder").arg(entry.path));
+ continue;
+ }
+ if (entry.dir) {
+ continue;
+ }
+ progress->setCurrent(entry.name);
+
+ const QByteArray targetName = QFile::encodeName(target);
+ struct stat st;
+ const bool exists = ::lstat(targetName.constData(), &st) == 0;
+ if (exists && S_ISDIR(st.st_mode)) {
+ result.failed.append(QStringLiteral("%1: a folder has the same name").arg(entry.path));
+ continue;
+ }
+ if (exists && !options.replace) {
+ ++result.kept;
+ continue;
+ }
+ if (exists && S_ISLNK(st.st_mode)) {
+ ::unlink(targetName.constData());
+ }
+
+ if (entry.symlink) {
+ QString linkTarget = entry.linkTarget;
+ if (linkTarget.isEmpty() && listing.tool == QLatin1String("7z")) {
+ linkTarget = linkTargetOf(options.archive, entry, options.password, progress);
+ }
+ const QString dirRel = steps.join(QLatin1Char('/'));
+ const QString resolved = QDir::cleanPath(dirRel.isEmpty() ? linkTarget : dirRel + QLatin1Char('/') + linkTarget);
+ if (linkTarget.isEmpty() || linkTarget.startsWith(QLatin1Char('/')) || resolved == QLatin1String("..")
+ || resolved.startsWith(QLatin1String("../"))) {
+ result.unsafe.append(entry.path);
+ continue;
+ }
+ if (exists) {
+ ::unlink(targetName.constData());
+ }
+ if (::symlink(QFile::encodeName(linkTarget).constData(), targetName.constData()) != 0) {
+ result.failed.append(QStringLiteral("%1: %2").arg(entry.path, QString::fromLocal8Bit(std::strerror(errno))));
+ }
+ continue;
+ }
+
+ const QString source = unpacked(staging, entry);
+ struct stat from;
+ if (source.isEmpty() || ::lstat(QFile::encodeName(source).constData(), &from) != 0) {
+ result.failed.append(QStringLiteral("%1: it couldn't be unpacked").arg(entry.path));
+ continue;
+ }
+ bool placed = false;
+ QString error;
+ if (from.st_nlink > 1) {
+ // A hard link the tool made: copied, so the new file shares
+ // nothing with any other.
+ QFile in(source);
+ QSaveFile out(target);
+ out.setDirectWriteFallback(false);
+ if (in.open(QIODevice::ReadOnly) && out.open(QIODevice::WriteOnly)) {
+ placed = out.write(in.readAll()) == from.st_size && out.commit();
+ }
+ error = out.errorString();
+ } else {
+ // On the same file system, so a rename: the file appears whole
+ // under its name, or not at all.
+ placed = ::rename(QFile::encodeName(source).constData(), targetName.constData()) == 0;
+ error = QString::fromLocal8Bit(std::strerror(errno));
+ }
+ if (!placed) {
+ result.ok = false;
+ result.error = QStringLiteral("Couldn't write %1: %2").arg(entry.name, error);
+ return result;
+ }
+ ::chmod(targetName.constData(), (from.st_mode & 0111) || entry.executable ? 0755 : 0644);
+ setTimes(target, entry.modified);
+ ++result.written;
+ if (result.firstWritten.isEmpty()) {
+ result.firstWritten = root + QLatin1Char('/') + rel.section(QLatin1Char('/'), 0, 0);
+ }
+ }
+ result.ok = result.failed.isEmpty();
+ return result;
+}
+
+QList<int> plainFiles(const Listing &listing)
+{
+ QList<int> files;
+ for (int order = 0; order < listing.byOrder.size(); ++order) {
+ const int index = listing.byOrder[order];
+ if (index < 0) {
+ continue;
+ }
+ const Entry &e = listing.entries[index];
+ if (!e.dir && !e.symlink && !e.unsafe) {
+ files.append(order);
+ }
+ }
+ return files;
+}
+
+Result testWithTool(const QString &path, const QByteArray &password, const Listing &listing, Progress *progress)
+{
+ Result result;
+ const QList<int> files = plainFiles(listing);
+ const qint64 total = qMax<qint64>(listing.totalSize, 1);
+ progress->total = total;
+ progress->done = 0;
+
+ if (listing.tool == QLatin1String("7z")) {
+ Tools::Job job;
+ job.program = QStringLiteral("7z");
+ job.arguments = {QStringLiteral("t"), QStringLiteral("-bso0"), QStringLiteral("-bse2"), QStringLiteral("-bsp1"), QStringLiteral("-spd"),
+ QStringLiteral("-sccUTF-8"), path};
+ job.password = password;
+ job.line = [progress, total](const QByteArray &line) {
+ const QByteArray t = line.trimmed();
+ const qsizetype percent = t.indexOf('%');
+ bool ok = false;
+ const int value = percent > 0 ? t.left(percent).toInt(&ok) : 0;
+ if (ok) {
+ progress->done = total * qBound(0, value, 100) / 100;
+ }
+ };
+ const Tools::Outcome outcome = Tools::run(job, progress);
+ if (outcome.cancelled) {
+ result.cancelled = true;
+ return result;
+ }
+ if (!outcome.started) {
+ result.ok = false;
+ result.error = QString::fromUtf8(outcome.errors);
+ return result;
+ }
+ // "ERROR: Data Error in encrypted file. Wrong password? : name"
+ int wrong = 0;
+ for (const QByteArray &raw : outcome.errors.split('\n')) {
+ const QString line = QString::fromUtf8(raw).trimmed();
+ const qsizetype colon = line.lastIndexOf(QLatin1String(" : "));
+ if (!line.startsWith(QLatin1String("ERROR: ")) || colon < 0) {
+ continue;
+ }
+ const QString name = line.mid(colon + 3);
+ const QString why = line.mid(7, colon - 7);
+ if (line.mid(7).startsWith(path + QLatin1String(" : "))) {
+ continue;
+ }
+ wrong += why.contains(QLatin1String("Wrong password")) ? 1 : 0;
+ result.failed.append(QStringLiteral("%1: %2").arg(name, why));
+ }
+ // Every file failing on the password is the password; one or two
+ // among good ones is damage.
+ const PasswordState state = Tools::passwordOutcome(outcome, password);
+ if (state != PasswordState::Fine && (result.failed.isEmpty() || (wrong == result.failed.size() && wrong >= files.size()))) {
+ result.ok = false;
+ result.failed.clear();
+ result.password = state;
+ return result;
+ }
+ result.written = int(qMax<qsizetype>(0, files.size() - result.failed.size()));
+ if (outcome.exitCode != 0 && result.failed.isEmpty()) {
+ result.ok = false;
+ result.error = QString::fromUtf8(outcome.errors).trimmed();
+ return result;
+ }
+ result.ok = result.failed.isEmpty();
+ return result;
+ }
+
+ if (!listing.encrypted) {
+ // Nothing protected: lsar checks every file against its checksum
+ // and says how each went.
+ Tools::Job job;
+ job.program = QStringLiteral("lsar");
+ job.arguments = {QStringLiteral("-t"), QStringLiteral("-ja"), QStringLiteral("-nr"), path};
+ auto seen = std::make_shared<int>(0);
+ job.line = [progress, seen, &listing](const QByteArray &line) {
+ if (line.contains("\"lsarTestResult\"")) {
+ const int index = listing.byOrder.value((*seen)++, -1);
+ if (index >= 0) {
+ progress->done += listing.entries[index].dir ? 0 : listing.entries[index].size;
+ }
+ }
+ };
+ const Tools::Outcome outcome = Tools::run(job, progress);
+ if (outcome.cancelled) {
+ result.cancelled = true;
+ return result;
+ }
+ const QJsonDocument document = QJsonDocument::fromJson(outcome.output);
+ const QJsonArray contents = document.object().value(QLatin1String("lsarContents")).toArray();
+ if (contents.isEmpty()) {
+ result.ok = false;
+ result.error = QString::fromUtf8(outcome.errors).trimmed();
+ return result;
+ }
+ for (qsizetype i = 0; i < contents.size(); ++i) {
+ const int index = listing.byOrder.value(int(i), -1);
+ if (index < 0 || listing.entries[index].dir || listing.entries[index].symlink || listing.entries[index].unsafe) {
+ continue;
+ }
+ const QString test = contents.at(i).toObject().value(QLatin1String("lsarTestResult")).toString();
+ if (test == QLatin1String("wrong_checksum")) {
+ result.failed.append(QStringLiteral("%1: its checksum is wrong").arg(listing.entries[index].path));
+ } else if (test == QLatin1String("unpacking_failed")) {
+ result.failed.append(QStringLiteral("%1: it couldn't be unpacked").arg(listing.entries[index].path));
+ } else {
+ ++result.written;
+ }
+ }
+ result.ok = result.failed.isEmpty();
+ return result;
+ }
+
+ // lsar can't take a password safely, so a protected RAR is tested by
+ // unpacking it into a private folder that goes straight after.
+ const Staging staging(privateStaging());
+ if (staging.path.isEmpty()) {
+ result.ok = false;
+ result.error = QStringLiteral("Couldn't make a private folder to test in.");
+ return result;
+ }
+ const Tools::Outcome outcome = unpack(path, listing, password, files, staging, total, progress);
+ if (outcome.cancelled) {
+ result.cancelled = true;
+ return result;
+ }
+ for (int order : files) {
+ const Entry &entry = listing.entries[listing.byOrder[order]];
+ if (unpacked(staging, entry).isEmpty()) {
+ result.failed.append(QStringLiteral("%1: it couldn't be unpacked").arg(entry.path));
+ } else {
+ ++result.written;
+ }
+ }
+ const PasswordState state = Tools::passwordOutcome(outcome, password);
+ if (state != PasswordState::Fine && result.written == 0) {
+ result.ok = false;
+ result.failed.clear();
+ result.password = state;
+ return result;
+ }
+ result.ok = result.failed.isEmpty();
+ return result;
+}
+
+Result readOneWithTool(const QString &path, const QByteArray &password, const Listing &listing, int order, const QString &target, Progress *progress)
+{
+ Result result;
+ const int index = listing.byOrder.value(order, -1);
+ if (index < 0) {
+ result.ok = false;
+ result.error = QStringLiteral("The file isn't in the archive any more.");
+ return result;
+ }
+ const Entry &entry = listing.entries[index];
+ progress->total = qMax<qint64>(entry.size, 1);
+ progress->done = 0;
+
+ if (listing.tool == QLatin1String("7z")) {
+ QSaveFile out(target);
+ if (!out.open(QIODevice::WriteOnly)) {
+ result.ok = false;
+ result.error = out.errorString();
+ return result;
+ }
+ Tools::Job job;
+ job.program = QStringLiteral("7z");
+ job.arguments = {QStringLiteral("x"), QStringLiteral("-so"), QStringLiteral("-bsp0"), QStringLiteral("-spd"), path, QStringLiteral("-i!") + entry.toolPath};
+ job.password = password;
+ bool writeFailed = false;
+ job.data = [&](const char *data, qsizetype size) {
+ if (out.write(data, size) != size) {
+ writeFailed = true;
+ return false;
+ }
+ progress->done += size;
+ return true;
+ };
+ const Tools::Outcome outcome = Tools::run(job, progress);
+ const PasswordState state = Tools::passwordOutcome(outcome, password);
+ if (outcome.cancelled || writeFailed || state != PasswordState::Fine || outcome.exitCode != 0) {
+ out.cancelWriting();
+ out.commit();
+ result.ok = false;
+ result.cancelled = outcome.cancelled;
+ result.password = state;
+ result.error = writeFailed ? out.errorString() : QString::fromUtf8(outcome.errors).trimmed();
+ return result;
+ }
+ if (!out.commit()) {
+ result.ok = false;
+ result.error = out.errorString();
+ return result;
+ }
+ ::chmod(QFile::encodeName(target).constData(), 0600);
+ return result;
+ }
+
+ const Staging staging(Tools::makeStaging(QFileInfo(target).absolutePath()));
+ if (staging.path.isEmpty()) {
+ result.ok = false;
+ result.error = QString::fromLocal8Bit(std::strerror(errno));
+ return result;
+ }
+ const Tools::Outcome outcome = unpack(path, listing, password, {order}, staging, entry.size, progress);
+ result.password = Tools::passwordOutcome(outcome, password);
+ const QString source = unpacked(staging, entry);
+ if (outcome.cancelled || result.password != PasswordState::Fine || source.isEmpty()) {
+ result.ok = false;
+ result.cancelled = outcome.cancelled;
+ result.error = QStringLiteral("It couldn't be unpacked.");
+ return result;
+ }
+ if (::rename(QFile::encodeName(source).constData(), QFile::encodeName(target).constData()) != 0) {
+ result.ok = false;
+ result.error = QString::fromLocal8Bit(std::strerror(errno));
+ return result;
+ }
+ ::chmod(QFile::encodeName(target).constData(), 0600);
+ return result;
+}
+
+// A batch of pictures at a time, unpacked into a private folder and each
+// deleted the moment it is read.
+void thumbnailsWithTool(const QString &path, const QByteArray &password, const Listing &listing, const QSet<int> &orders, QSize box,
+ Progress *progress, const std::function<void(int, const QImage &)> &found)
+{
+ QList<int> wanted;
+ for (int order : orders) {
+ const int index = listing.byOrder.value(order, -1);
+ if (index >= 0 && (!listing.entries[index].encrypted || !password.isEmpty())) {
+ wanted.append(order);
+ }
+ }
+ std::sort(wanted.begin(), wanted.end());
+ constexpr int batchSize = 40;
+ for (qsizetype start = 0; start < wanted.size() && !progress->cancel; start += batchSize) {
+ const QList<int> batch = wanted.mid(start, batchSize);
+ const Staging staging(privateStaging());
+ if (staging.path.isEmpty()) {
+ return;
+ }
+ const Tools::Outcome outcome = unpack(path, listing, password, batch, staging, 0, progress);
+ if (outcome.cancelled || Tools::passwordOutcome(outcome, password) != PasswordState::Fine) {
+ return;
+ }
+ for (int order : batch) {
+ if (progress->cancel) {
+ return;
+ }
+ const QString file = unpacked(staging, listing.entries[listing.byOrder[order]]);
+ if (file.isEmpty()) {
+ continue;
+ }
+ QFile in(file);
+ QByteArray data;
+ if (in.open(QIODevice::ReadOnly)) {
+ data = in.readAll();
+ in.close();
+ }
+ ::unlink(QFile::encodeName(file).constData());
+ const QImage image = scaledImage(data, box);
+ if (!image.isNull()) {
+ found(order, image);
+ }
}
- return PasswordState::Fine;
}
- return PasswordState::Fine;
+}
}
Result extract(const ExtractOptions &options, const Listing &listing, Progress *progress)
@@ -633,6 +1493,9 @@ Result extract(const ExtractOptions &options, const Listing &listing, Progress *
}
progress->total = qMax<qint64>(total, 1);
progress->done = 0;
+ if (!listing.tool.isEmpty()) {
+ return extractWithTool(options, listing, targets, root, total, progress, result);
+ }
Handle h(newReader(options.password, listing.raw));
if (!openFile(h.a, options.archive)) {
@@ -791,6 +1654,9 @@ Result extract(const ExtractOptions &options, const Listing &listing, Progress *
Result test(const QString &path, const QByteArray &password, const Listing &listing, Progress *progress)
{
+ if (!listing.tool.isEmpty()) {
+ return testWithTool(path, password, listing, progress);
+ }
Result result;
progress->total = qMax<qint64>(listing.totalSize, 1);
progress->done = 0;
@@ -840,6 +1706,9 @@ Result test(const QString &path, const QByteArray &password, const Listing &list
Result readOne(const QString &path, const QByteArray &password, const Listing &listing, int order, const QString &target, Progress *progress)
{
+ if (!listing.tool.isEmpty()) {
+ return readOneWithTool(path, password, listing, order, target, progress);
+ }
Result result;
Handle h(newReader(password, listing.raw));
if (!openFile(h.a, path)) {
@@ -890,6 +1759,10 @@ Result readOne(const QString &path, const QByteArray &password, const Listing &l
void thumbnails(const QString &path, const QByteArray &password, const Listing &listing, const QSet<int> &orders, QSize box,
Progress *progress, const std::function<void(int, const QImage &)> &found)
{
+ if (!listing.tool.isEmpty()) {
+ thumbnailsWithTool(path, password, listing, orders, box, progress, found);
+ return;
+ }
Handle h(newReader(password, listing.raw));
if (!openFile(h.a, path)) {
return;
@@ -920,17 +1793,7 @@ void thumbnails(const QString &path, const QByteArray &password, const Listing &
continue;
}
buffer.close();
- buffer.open(QIODevice::ReadOnly);
- QImageReader reader(&buffer);
- reader.setAutoTransform(true);
- const QSize size = reader.size();
- if (size.isValid()) {
- const QSize scaled = size.scaled(box, Qt::KeepAspectRatioByExpanding);
- if (scaled.width() < size.width()) {
- reader.setScaledSize(scaled);
- }
- }
- const QImage image = reader.read();
+ const QImage image = scaledImage(data, box);
if (!image.isNull()) {
found(order, image);
}
@@ -980,15 +1843,58 @@ Result create(const CreateOptions &options, Progress *progress)
}
Listing source;
+ // An archive only a tool can read is unpacked first, into a private
+ // folder beside the new one, and its files go in from there.
+ std::unique_ptr<Staging> unpackedSource;
if (!options.source.isEmpty()) {
Progress quiet;
- source = list(options.source, &quiet);
- if (!source.error.isEmpty()) {
+ source = list(options.source, options.sourcePassword, &quiet);
+ if (!source.error.isEmpty() || source.lockedHeaders || source.cantDecrypt) {
result.ok = false;
- result.error = QStringLiteral("Couldn't read %1: %2").arg(QFileInfo(options.source).fileName(), source.error);
+ result.error = QStringLiteral("Couldn't read %1: %2")
+ .arg(QFileInfo(options.source).fileName(),
+ source.error.isEmpty() ? QStringLiteral("Archive can't unlock it.") : source.error);
return result;
}
- total += source.totalSize;
+ if (!source.tool.isEmpty()) {
+ unpackedSource = std::make_unique<Staging>(Tools::makeStaging(targetInfo.absolutePath()));
+ ExtractOptions unpackOptions;
+ unpackOptions.archive = options.source;
+ unpackOptions.password = options.sourcePassword;
+ unpackOptions.destination = unpackedSource->into();
+ Result unpackedResult;
+ if (!unpackedSource->path.isEmpty()) {
+ unpackedResult = extract(unpackOptions, source, progress);
+ }
+ if (unpackedSource->path.isEmpty() || unpackedResult.cancelled || unpackedResult.password != PasswordState::Fine
+ || !unpackedResult.error.isEmpty()) {
+ result.ok = false;
+ result.cancelled = unpackedResult.cancelled;
+ result.password = unpackedResult.password;
+ result.error = QStringLiteral("Couldn't read %1: %2")
+ .arg(QFileInfo(options.source).fileName(),
+ unpackedResult.error.isEmpty() ? QStringLiteral("it couldn't be unpacked.") : unpackedResult.error);
+ return result;
+ }
+ result.failed += unpackedResult.failed;
+ const QDir dir(unpackedSource->into());
+ QList<Item> fromSource;
+ QDirIterator it(dir.path(), QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System, QDirIterator::Subdirectories);
+ while (it.hasNext()) {
+ const QString file = it.next();
+ const QString name = dir.relativeFilePath(file);
+ if (names.contains(name)) {
+ continue;
+ }
+ fromSource.append({file, name});
+ if (it.fileInfo().isFile() && !it.fileInfo().isSymLink()) {
+ total += it.fileInfo().size();
+ }
+ }
+ items = fromSource + items;
+ } else {
+ total += source.totalSize;
+ }
}
progress->total = qMax<qint64>(total, 1);
progress->done = 0;
@@ -1018,7 +1924,7 @@ Result create(const CreateOptions &options, Progress *progress)
}
static thread_local QByteArray buffer(blockSize, Qt::Uninitialized);
- if (!options.source.isEmpty()) {
+ if (!options.source.isEmpty() && source.tool.isEmpty()) {
Handle h(newReader(options.sourcePassword, source.raw));
if (!openFile(h.a, options.source)) {
return fail(errorOf(h.a));
diff --git a/packages/wildos-archive/src/reader.h b/packages/wildos-archive/src/reader.h
index 642e7ea..bf8bb81 100644
--- a/packages/wildos-archive/src/reader.h
+++ b/packages/wildos-archive/src/reader.h
@@ -39,6 +39,10 @@ struct Entry {
// appears in other entries' paths.
int order = -1;
int fileCount = 0;
+ // Marked executable in an archive a tool reads; unar does not keep it.
+ bool executable = false;
+ // The name 7-Zip knows the entry by, to ask it for just this one.
+ QString toolPath;
};
struct Listing {
@@ -54,9 +58,14 @@ struct Listing {
bool encrypted = false;
bool packedPerFile = false;
QString error;
- // 7z and RAR can hide even the names behind a password, which
- // libarchive cannot open.
+ // 7z and RAR can hide even the names behind a password: nothing is
+ // listed until it is given.
bool lockedHeaders = false;
+ // Who reads the archive: empty for libarchive, "7z" for 7-Zip, "unar"
+ // for The Unarchiver. Entries' orders are then the tool's indexes.
+ QString tool;
+ // Protected in a way no free tool can decrypt: RAR 4's encryption.
+ bool cantDecrypt = false;
};
namespace Reader
@@ -67,10 +76,22 @@ enum class PasswordState { Fine, Needed, Wrong };
// letter or a .. step. `clean` gets the path without ./ and empty steps.
bool safePath(const QString &stored, QString *clean);
-Listing list(const QString &path, Progress *progress);
+// libarchive first; 7-Zip or The Unarchiver only for what libarchive
+// cannot decrypt or read. The password is for names behind one.
+Listing list(const QString &path, const QByteArray &password, Progress *progress);
+inline Listing list(const QString &path, Progress *progress)
+{
+ return list(path, QByteArray(), progress);
+}
-// Reads a little of the first protected file with the password.
-PasswordState checkPassword(const QString &path, const Listing &listing, const QByteArray &password);
+// Tries the password on a little of the archive. When the names were
+// behind it, `relisted` gets the archive listed with it.
+struct Unlock {
+ PasswordState state = PasswordState::Fine;
+ bool relisted = false;
+ Listing listing;
+};
+Unlock unlock(const QString &path, const Listing &listing, const QByteArray &password, Progress *progress);
struct ExtractOptions {
QString archive;
diff --git a/packages/wildos-archive/src/session.cpp b/packages/wildos-archive/src/session.cpp
index 91ae9e1..6625c8e 100644
--- a/packages/wildos-archive/src/session.cpp
+++ b/packages/wildos-archive/src/session.cpp
@@ -3,6 +3,7 @@
#include "archiveapp.h"
#include "format.h"
#include "thumbnails.h"
+#include "tools.h"
#include <QDesktopServices>
#include <QDir>
@@ -32,6 +33,7 @@ Archive::~Archive()
{
stopAll();
Thumbnails::drop(m_key);
+ Tools::wipe(m_password);
}
void Archive::stopAll()
@@ -139,6 +141,11 @@ bool Archive::encrypted() const
}
bool Archive::lockedFormat() const
+{
+ return m_listing && m_listing->cantDecrypt;
+}
+
+bool Archive::namesHidden() const
{
return m_listing && m_listing->lockedHeaders;
}
@@ -167,7 +174,8 @@ void Archive::open(const QString &path)
m_path = QFileInfo(path).absoluteFilePath();
m_state = QStringLiteral("loading");
m_error.clear();
- m_password.clear();
+ // Every worker has stopped, so no copy of the password is in use.
+ Tools::wipe(m_password);
m_pending = nullptr;
m_listing.reset();
m_dirs.clear();
@@ -194,22 +202,12 @@ void Archive::open(const QString &path)
Q_EMIT loaded();
return;
}
- m_listing = listing;
- m_state = QStringLiteral("ready");
- m_error = listing->lockedHeaders ? QString() : listing->error;
- for (int i = 0; i < listing->entries.size(); ++i) {
- if (listing->entries[i].dir) {
- m_dirs.insert(listing->entries[i].path, i);
- }
- }
- m_model->setListing(m_listing.get(), m_key);
- // An archive that holds only one folder opens inside it.
- const QList<int> &roots = listing->roots;
- const bool single = roots.size() == 1 && listing->entries[roots.first()].dir;
- show(single ? listing->entries[roots.first()].path : QString(), false);
+ adopt(listing);
ArchiveApp::instance()->addRecent(m_path);
Q_EMIT loaded();
- if (listing->encrypted && !listing->lockedHeaders) {
+ // Asked straight away, as Windows does: the names, or the
+ // files, are no use without it.
+ if ((listing->encrypted || listing->lockedHeaders) && !listing->cantDecrypt) {
Q_EMIT passwordNeeded(false);
}
startThumbnails();
@@ -217,22 +215,53 @@ void Archive::open(const QString &path)
});
}
+void Archive::adopt(const std::shared_ptr<const Listing> &listing)
+{
+ m_listing = listing;
+ m_state = QStringLiteral("ready");
+ m_error = listing->lockedHeaders ? QString() : listing->error;
+ m_dirs.clear();
+ for (int i = 0; i < listing->entries.size(); ++i) {
+ if (listing->entries[i].dir) {
+ m_dirs.insert(listing->entries[i].path, i);
+ }
+ }
+ m_model->setListing(m_listing.get(), m_key);
+ m_history.clear();
+ // An archive that holds only one folder opens inside it.
+ const QList<int> &roots = listing->roots;
+ const bool single = roots.size() == 1 && listing->entries[roots.first()].dir;
+ show(single ? listing->entries[roots.first()].path : QString(), false);
+}
+
void Archive::setPassword(const QString &password)
{
if (!m_listing || password.isEmpty()) {
return;
}
- const QByteArray bytes = password.toUtf8();
+ QByteArray bytes = password.toUtf8();
const auto listing = m_listing;
const QString file = m_path;
- start(QStringLiteral("password"), [this, bytes, listing, file](Progress *) -> Done {
- const Reader::PasswordState state = Reader::checkPassword(file, *listing, bytes);
- return [this, bytes, state] {
- if (state != Reader::PasswordState::Fine) {
- Q_EMIT passwordNeeded(true);
+ start(QStringLiteral("password"), [this, bytes, listing, file](Progress *progress) -> Done {
+ auto unlocked = std::make_shared<Reader::Unlock>(Reader::unlock(file, *listing, bytes, progress));
+ return [this, bytes, unlocked]() mutable {
+ if (unlocked->state != Reader::PasswordState::Fine) {
+ Tools::wipe(bytes);
+ Q_EMIT passwordNeeded(unlocked->state == Reader::PasswordState::Wrong);
return;
}
m_password = bytes;
+ if (unlocked->relisted) {
+ const auto named = std::make_shared<const Listing>(std::move(unlocked->listing));
+ if (!named->error.isEmpty() && named->entries.isEmpty()) {
+ m_state = QStringLiteral("failed");
+ m_error = named->error;
+ Q_EMIT loaded();
+ return;
+ }
+ adopt(named);
+ Q_EMIT loaded();
+ }
Q_EMIT passwordChanged();
startThumbnails();
if (m_pending) {
@@ -249,9 +278,16 @@ void Archive::forgetPending()
m_pending = nullptr;
}
+void Archive::askPassword()
+{
+ if (m_listing && !m_listing->cantDecrypt && m_password.isEmpty() && (m_listing->encrypted || m_listing->lockedHeaders) && m_job.isEmpty()) {
+ Q_EMIT passwordNeeded(false);
+ }
+}
+
bool Archive::needPassword(const Done &retry)
{
- if (!m_listing || !m_listing->encrypted || !m_password.isEmpty() || m_listing->lockedHeaders) {
+ if (!m_listing || m_listing->cantDecrypt || !m_password.isEmpty() || (!m_listing->encrypted && !m_listing->lockedHeaders)) {
return false;
}
m_pending = retry;
@@ -761,10 +797,6 @@ void Archive::runExtract(Reader::ExtractOptions options, const QString &what, bo
result.unsafe);
return;
}
- if (!result.failed.isEmpty() && result.written == 0 && unreadableRar()) {
- Q_EMIT finished(QStringLiteral("extract"), false, QStringLiteral("Archive couldn't read the files in this RAR"), rarNote(), {});
- return;
- }
if (!result.failed.isEmpty()) {
Q_EMIT finished(QStringLiteral("extract"), false, QStringLiteral("Some files couldn't be extracted"),
QStringLiteral("The rest are in %1.").arg(where), result.failed);
@@ -815,10 +847,6 @@ void Archive::test()
QStringLiteral("%1 files checked out before the damage. %2").arg(result.written).arg(result.error), result.failed);
return;
}
- if (!result.failed.isEmpty() && result.written == 0 && unreadableRar()) {
- Q_EMIT finished(QStringLiteral("test"), false, QStringLiteral("Archive couldn't read the files in this RAR"), rarNote(), {});
- return;
- }
if (!result.failed.isEmpty()) {
Q_EMIT finished(QStringLiteral("test"), false,
result.failed.size() == 1 ? QStringLiteral("1 file is damaged") : QStringLiteral("%1 files are damaged").arg(result.failed.size()),
@@ -877,19 +905,6 @@ void Archive::openEntry(int entry)
});
}
-// libarchive does not say when a RAR's files are behind a password; they
-// just fail to decompress, every one of them.
-bool Archive::unreadableRar() const
-{
- return formatName() == QLatin1String("RAR");
-}
-
-QString Archive::rarNote() const
-{
- return QStringLiteral("Every file failed to decompress. That usually means the RAR is protected with a password, and Archive can't open "
- "protected RAR files yet. If it has no password, the archive is damaged.");
-}
-
void Archive::cancel()
{
if (m_progress) {
diff --git a/packages/wildos-archive/src/session.h b/packages/wildos-archive/src/session.h
index dd1f209..93ce3cd 100644
--- a/packages/wildos-archive/src/session.h
+++ b/packages/wildos-archive/src/session.h
@@ -32,8 +32,10 @@ class Archive : public QObject
Q_PROPERTY(QString formatName READ formatName NOTIFY loaded)
Q_PROPERTY(QString summary READ summary NOTIFY loaded)
Q_PROPERTY(bool encrypted READ encrypted NOTIFY loaded)
- // A 7z or RAR with a password: libarchive cannot decrypt those.
+ // Protected in a way Archive cannot decrypt: RAR 4 encryption.
Q_PROPERTY(bool lockedFormat READ lockedFormat NOTIFY loaded)
+ // The names are behind the password too, and it hasn't been given.
+ Q_PROPERTY(bool namesHidden READ namesHidden NOTIFY loaded)
Q_PROPERTY(bool hasPassword READ hasPassword NOTIFY passwordChanged)
Q_PROPERTY(int unsafeCount READ unsafeCount NOTIFY loaded)
Q_PROPERTY(EntryModel *model READ model CONSTANT)
@@ -86,6 +88,7 @@ public:
QString summary() const;
bool encrypted() const;
bool lockedFormat() const;
+ bool namesHidden() const;
bool hasPassword() const
{
return !m_password.isEmpty();
@@ -187,6 +190,7 @@ public:
Q_INVOKABLE void openUrl(const QUrl &url);
Q_INVOKABLE void setPassword(const QString &password);
Q_INVOKABLE void forgetPending();
+ Q_INVOKABLE void askPassword();
Q_INVOKABLE void goTo(const QString &folder);
Q_INVOKABLE void up();
@@ -241,9 +245,8 @@ private:
void runExtract(Reader::ExtractOptions options, const QString &what, bool openAfter);
void openEntry(int entry);
bool needPassword(const Done &retry);
+ void adopt(const std::shared_ptr<const Listing> &listing);
double rate() const;
- bool unreadableRar() const;
- QString rarNote() const;
EntryModel *m_model;
QString m_path;
diff --git a/packages/wildos-archive/src/tools.cpp b/packages/wildos-archive/src/tools.cpp
new file mode 100644
index 0000000..b1c2f61
--- /dev/null
+++ b/packages/wildos-archive/src/tools.cpp
@@ -0,0 +1,596 @@
+#include "tools.h"
+
+#include <QDir>
+#include <QFile>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QProcessEnvironment>
+#include <QStandardPaths>
+#include <QTimeZone>
+
+#include <cerrno>
+#include <csignal>
+#include <cstring>
+#include <fcntl.h>
+#include <ftw.h>
+#include <mutex>
+#include <poll.h>
+#include <pty.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <termios.h>
+#include <unistd.h>
+#include <vector>
+
+namespace
+{
+// What unar's getpass() shows. The tools print plain English that is
+// never translated, so these are stable.
+constexpr char unarPrompt[] = "(will not be shown): ";
+constexpr char sevenZipPrompt[] = "Enter password";
+
+// So a tool that quits before reading its password cannot kill Archive
+// with SIGPIPE while the password is written to it.
+void ignoreSigpipe()
+{
+ static std::once_flag once;
+ std::call_once(once, [] {
+ ::signal(SIGPIPE, SIG_IGN);
+ });
+}
+
+bool writeAll(int fd, const char *data, size_t size)
+{
+ while (size > 0) {
+ const ssize_t n = ::write(fd, data, size);
+ if (n < 0) {
+ if (errno == EINTR) {
+ continue;
+ }
+ return false;
+ }
+ data += n;
+ size -= size_t(n);
+ }
+ return true;
+}
+
+void closeFd(int &fd)
+{
+ if (fd >= 0) {
+ ::close(fd);
+ fd = -1;
+ }
+}
+
+// The tools print paths and their own messages in UTF-8 under this
+// locale, and 7z decodes a typed password as UTF-8 under it.
+std::vector<QByteArray> environment()
+{
+ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
+ env.insert(QStringLiteral("LC_ALL"), QStringLiteral("C.UTF-8"));
+ env.insert(QStringLiteral("LANG"), QStringLiteral("C.UTF-8"));
+ env.remove(QStringLiteral("LANGUAGE"));
+ std::vector<QByteArray> out;
+ for (const QString &pair : env.toStringList()) {
+ out.push_back(pair.toLocal8Bit());
+ }
+ return out;
+}
+
+QDateTime localTime(const QString &text)
+{
+ // 7z prints local time, to a tenth of a microsecond or less.
+ const QDateTime t = QDateTime::fromString(text.left(19), QStringLiteral("yyyy-MM-dd HH:mm:ss"));
+ return t.isValid() ? t : QDateTime();
+}
+
+QDateTime lsarTime(const QString &text)
+{
+ // "2026-11-07 17:31:05 +0000"
+ const QDateTime t = QDateTime::fromString(text.left(19), QStringLiteral("yyyy-MM-dd HH:mm:ss"));
+ if (!t.isValid()) {
+ return QDateTime();
+ }
+ int offset = 0;
+ const QString zone = text.mid(20).trimmed();
+ if (zone.size() == 5 && (zone.at(0) == QLatin1Char('+') || zone.at(0) == QLatin1Char('-'))) {
+ offset = (zone.mid(1, 2).toInt() * 60 + zone.mid(3, 2).toInt()) * 60;
+ if (zone.at(0) == QLatin1Char('-')) {
+ offset = -offset;
+ }
+ }
+ return QDateTime(t.date(), t.time(), QTimeZone::fromSecondsAheadOfUtc(offset)).toLocalTime();
+}
+}
+
+namespace Tools
+{
+
+bool available(const QString &program)
+{
+ return !QStandardPaths::findExecutable(program).isEmpty();
+}
+
+void wipe(QByteArray &bytes)
+{
+ if (!bytes.isEmpty()) {
+ // Through constData so the shared buffer is cleared rather than a
+ // detached copy.
+ volatile char *p = const_cast<char *>(bytes.constData());
+ for (qsizetype i = 0; i < bytes.size(); ++i) {
+ p[i] = 0;
+ }
+ }
+ bytes.clear();
+}
+
+void removeTree(const QString &path)
+{
+ if (path.isEmpty()) {
+ return;
+ }
+ ::nftw(
+ QFile::encodeName(path).constData(),
+ [](const char *name, const struct stat *, int type, struct FTW *) -> int {
+ if (type == FTW_DP) {
+ ::rmdir(name);
+ } else {
+ ::unlink(name);
+ }
+ return 0;
+ },
+ 32, FTW_DEPTH | FTW_PHYS);
+}
+
+QString makeStaging(const QString &parent)
+{
+ QByteArray name = QFile::encodeName(parent + QStringLiteral("/.wildos-archive-XXXXXX"));
+ if (!::mkdtemp(name.data())) {
+ return QString();
+ }
+ return QFile::decodeName(name);
+}
+
+Outcome run(const Job &job, Progress *progress)
+{
+ Outcome outcome;
+ const QString exe = QStandardPaths::findExecutable(job.program);
+ if (exe.isEmpty()) {
+ outcome.errors = job.program.toUtf8() + " isn't installed";
+ return outcome;
+ }
+ ignoreSigpipe();
+
+ // Everything the child needs is made before fork: in a process with
+ // threads, only async-signal-safe calls are allowed between fork and
+ // exec.
+ std::vector<QByteArray> args;
+ args.push_back(QFile::encodeName(exe));
+ for (const QString &a : job.arguments) {
+ args.push_back(QFile::encodeName(a));
+ }
+ std::vector<char *> argv;
+ for (QByteArray &a : args) {
+ argv.push_back(a.data());
+ }
+ argv.push_back(nullptr);
+ std::vector<QByteArray> env = environment();
+ std::vector<char *> envp;
+ for (QByteArray &e : env) {
+ envp.push_back(e.data());
+ }
+ envp.push_back(nullptr);
+
+ int in[2] = {-1, -1};
+ int out[2] = {-1, -1};
+ int err[2] = {-1, -1};
+ int master = -1;
+ int slave = -1;
+ if (job.terminal) {
+ struct winsize size = {};
+ size.ws_row = 24;
+ size.ws_col = 4000;
+ if (::openpty(&master, &slave, nullptr, nullptr, &size) != 0) {
+ outcome.errors = "Couldn't make a terminal for " + job.program.toUtf8();
+ return outcome;
+ }
+ ::fcntl(master, F_SETFD, FD_CLOEXEC);
+ ::fcntl(slave, F_SETFD, FD_CLOEXEC);
+ // No echo at all, so nothing typed is ever shown back, even
+ // before the tool turns echo off for its prompt.
+ struct termios t;
+ if (::tcgetattr(slave, &t) == 0) {
+ t.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
+ ::tcsetattr(slave, TCSANOW, &t);
+ }
+ } else if (::pipe2(in, O_CLOEXEC) != 0 || ::pipe2(out, O_CLOEXEC) != 0 || ::pipe2(err, O_CLOEXEC) != 0) {
+ for (int *fd : {&in[0], &in[1], &out[0], &out[1], &err[0], &err[1]}) {
+ closeFd(*fd);
+ }
+ outcome.errors = "Couldn't start " + job.program.toUtf8();
+ return outcome;
+ }
+
+ const pid_t pid = ::fork();
+ if (pid == 0) {
+ ::signal(SIGPIPE, SIG_DFL);
+ if (job.terminal) {
+ // Its own session with the pseudo terminal as its controlling
+ // terminal: getpass() reads the password from /dev/tty.
+ ::setsid();
+ ::ioctl(slave, TIOCSCTTY, 0);
+ ::dup2(slave, 0);
+ ::dup2(slave, 1);
+ ::dup2(slave, 2);
+ } else {
+ ::setpgid(0, 0);
+ ::dup2(in[0], 0);
+ ::dup2(out[1], 1);
+ ::dup2(err[1], 2);
+ }
+ ::close_range(3, ~0U, 0);
+ ::execve(argv[0], argv.data(), envp.data());
+ ::_exit(127);
+ }
+ if (pid < 0) {
+ for (int *fd : {&in[0], &in[1], &out[0], &out[1], &err[0], &err[1], &master, &slave}) {
+ closeFd(*fd);
+ }
+ outcome.errors = "Couldn't start " + job.program.toUtf8();
+ return outcome;
+ }
+ outcome.started = true;
+ closeFd(slave);
+ closeFd(in[0]);
+ closeFd(out[1]);
+ closeFd(err[1]);
+
+ if (!job.terminal) {
+ // 7z reads one line when it needs the password and nothing when
+ // it doesn't. With no password, stdin just ends, and 7z says so.
+ if (!job.password.isEmpty()) {
+ QByteArray line = job.password + '\n';
+ writeAll(in[1], line.constData(), size_t(line.size()));
+ wipe(line);
+ }
+ closeFd(in[1]);
+ }
+
+ int killed = 0;
+ qint64 killedAt = 0;
+ struct timespec started;
+ ::clock_gettime(CLOCK_MONOTONIC, &started);
+ const auto now = [&] {
+ struct timespec t;
+ ::clock_gettime(CLOCK_MONOTONIC, &t);
+ return qint64(t.tv_sec - started.tv_sec) * 1000 + (t.tv_nsec - started.tv_nsec) / 1000000;
+ };
+ const auto stop = [&] {
+ if (killed == 0) {
+ ::kill(-pid, SIGTERM);
+ ::kill(pid, SIGTERM);
+ killed = 1;
+ killedAt = now();
+ }
+ };
+
+ QByteArray pending;
+ const auto lines = [&](const char *data, ssize_t n) {
+ if (!job.line) {
+ return;
+ }
+ pending.append(data, n);
+ qsizetype start = 0;
+ for (qsizetype i = 0; i < pending.size(); ++i) {
+ // 7z redraws its progress with backspaces, unar ends lines
+ // with \r\n on the terminal.
+ const char c = pending.at(i);
+ if (c == '\n' || c == '\r' || c == '\b') {
+ if (i > start) {
+ job.line(pending.mid(start, i - start));
+ }
+ start = i + 1;
+ }
+ }
+ pending.remove(0, start);
+ };
+
+ bool answered = false;
+ qsizetype scanned = 0;
+ int status = 0;
+ bool reaped = false;
+ char buffer[65536];
+ for (;;) {
+ if (progress && progress->cancel && !outcome.cancelled) {
+ outcome.cancelled = true;
+ stop();
+ }
+ if (killed == 1 && now() - killedAt > 1500) {
+ ::kill(-pid, SIGKILL);
+ ::kill(pid, SIGKILL);
+ killed = 2;
+ }
+ struct pollfd fds[2];
+ int count = 0;
+ if (job.terminal) {
+ if (master >= 0) {
+ fds[count++] = {master, POLLIN, 0};
+ }
+ } else {
+ if (out[0] >= 0) {
+ fds[count++] = {out[0], POLLIN, 0};
+ }
+ if (err[0] >= 0) {
+ fds[count++] = {err[0], POLLIN, 0};
+ }
+ }
+ if (count == 0) {
+ if (!reaped) {
+ // Every stream is closed; the tool is finishing or has
+ // handed its terminal to nobody. Wait for it, still
+ // honouring a cancel.
+ const pid_t r = ::waitpid(pid, &status, WNOHANG);
+ if (r == pid) {
+ reaped = true;
+ } else {
+ ::usleep(20000);
+ continue;
+ }
+ }
+ break;
+ }
+ const int ready = ::poll(fds, nfds_t(count), 100);
+ if (ready < 0 && errno != EINTR) {
+ break;
+ }
+ for (int i = 0; i < count && ready > 0; ++i) {
+ if (!(fds[i].revents & (POLLIN | POLLHUP | POLLERR))) {
+ continue;
+ }
+ const ssize_t n = ::read(fds[i].fd, buffer, sizeof buffer);
+ if (n <= 0) {
+ if (n < 0 && errno == EINTR) {
+ continue;
+ }
+ // A pseudo terminal reads EIO once the tool has gone.
+ if (fds[i].fd == master) {
+ closeFd(master);
+ } else if (fds[i].fd == out[0]) {
+ closeFd(out[0]);
+ } else {
+ closeFd(err[0]);
+ }
+ continue;
+ }
+ if (fds[i].fd == err[0]) {
+ if (outcome.errors.size() < 1024 * 1024) {
+ outcome.errors.append(buffer, n);
+ }
+ lines(buffer, n);
+ continue;
+ }
+ if (job.data && fds[i].fd == out[0]) {
+ if (!outcome.stopped && !job.data(buffer, n)) {
+ outcome.stopped = true;
+ stop();
+ }
+ continue;
+ }
+ if (outcome.output.size() < 256 * 1024 * 1024) {
+ outcome.output.append(buffer, n);
+ }
+ lines(buffer, n);
+ if (job.terminal) {
+ const qsizetype at = outcome.output.indexOf(unarPrompt, qMax<qsizetype>(0, scanned - qsizetype(sizeof unarPrompt)));
+ scanned = outcome.output.size();
+ if (at >= 0) {
+ outcome.output.replace(at, qsizetype(std::strlen(unarPrompt)), "(asked)\n");
+ scanned = outcome.output.size();
+ outcome.askedForPassword = true;
+ if (answered || job.password.isEmpty()) {
+ // Asked again: unar took the first answer as
+ // wrong. Nothing more to try.
+ outcome.askedAgain = answered;
+ stop();
+ } else {
+ QByteArray line = job.password + '\n';
+ writeAll(master, line.constData(), size_t(line.size()));
+ wipe(line);
+ answered = true;
+ }
+ }
+ }
+ }
+ }
+ closeFd(master);
+ closeFd(out[0]);
+ closeFd(err[0]);
+ closeFd(in[1]);
+ if (!reaped) {
+ while (::waitpid(pid, &status, 0) < 0 && errno == EINTR) {
+ }
+ }
+ outcome.exitCode = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
+ const QByteArray all = outcome.output + outcome.errors;
+ if (all.contains(sevenZipPrompt)) {
+ outcome.askedForPassword = true;
+ }
+ return outcome;
+}
+
+Reader::PasswordState passwordOutcome(const Outcome &outcome, const QByteArray &password)
+{
+ const Reader::PasswordState missing = password.isEmpty() ? Reader::PasswordState::Needed : Reader::PasswordState::Wrong;
+ if (outcome.askedAgain) {
+ return Reader::PasswordState::Wrong;
+ }
+ const QByteArray all = (outcome.output + outcome.errors).toLower();
+ // 7z: "Wrong password?" and "Cannot open encrypted archive"; unar:
+ // "Missing or wrong password".
+ if (all.contains("wrong password") || all.contains("cannot open encrypted archive")) {
+ return missing;
+ }
+ if (outcome.askedForPassword && password.isEmpty()) {
+ return Reader::PasswordState::Needed;
+ }
+ return Reader::PasswordState::Fine;
+}
+
+Contents list7z(const QString &archive, const QByteArray &password, Progress *progress)
+{
+ Contents contents;
+ Job job;
+ job.program = QStringLiteral("7z");
+ // -spd: names are names, never wildcards.
+ job.arguments = {QStringLiteral("l"), QStringLiteral("-slt"), QStringLiteral("-bsp0"), QStringLiteral("-sccUTF-8"), QStringLiteral("-spd"), archive};
+ job.password = password;
+ const Outcome outcome = run(job, progress);
+ if (outcome.cancelled) {
+ contents.cancelled = true;
+ return contents;
+ }
+ if (!outcome.started) {
+ contents.error = QString::fromUtf8(outcome.errors);
+ return contents;
+ }
+ contents.password = passwordOutcome(outcome, password);
+ if (contents.password != Reader::PasswordState::Fine) {
+ contents.needsPassword = true;
+ return contents;
+ }
+ if (outcome.exitCode != 0) {
+ const QString errors = QString::fromUtf8(outcome.errors).trimmed();
+ contents.error = errors.isEmpty() ? QStringLiteral("7-Zip couldn't read this archive.") : errors;
+ return contents;
+ }
+
+ const QList<QByteArray> lines = outcome.output.split('\n');
+ bool inItems = false;
+ Item item;
+ bool haveItem = false;
+ const auto finish = [&] {
+ if (haveItem) {
+ contents.items.append(item);
+ }
+ item = Item();
+ haveItem = false;
+ };
+ for (const QByteArray &raw : lines) {
+ const QString line = QString::fromUtf8(raw).remove(QLatin1Char('\r'));
+ if (!inItems) {
+ if (line.startsWith(QLatin1String("Type = ")) && contents.type.isEmpty()) {
+ contents.type = line.mid(7);
+ }
+ if (line == QLatin1String("----------")) {
+ inItems = true;
+ }
+ continue;
+ }
+ if (line.isEmpty()) {
+ finish();
+ continue;
+ }
+ const qsizetype eq = line.indexOf(QLatin1String(" = "));
+ const QString key = eq < 0 ? line.chopped(line.endsWith(QLatin1String(" =")) ? 2 : 0) : line.left(eq);
+ const QString value = eq < 0 ? QString() : line.mid(eq + 3);
+ if (key == QLatin1String("Path")) {
+ finish();
+ item.path = value;
+ haveItem = true;
+ } else if (key == QLatin1String("Folder")) {
+ item.dir = item.dir || value == QLatin1String("+");
+ } else if (key == QLatin1String("Size")) {
+ item.size = value.toLongLong();
+ } else if (key == QLatin1String("Packed Size")) {
+ item.packed = value.isEmpty() ? -1 : value.toLongLong();
+ } else if (key == QLatin1String("Modified")) {
+ item.modified = localTime(value);
+ } else if (key == QLatin1String("Attributes")) {
+ // "D drwxr-xr-x", "A -rw-r--r--", " lrwxrwxrwx": Windows
+ // attributes, then the Unix mode when the archive has one.
+ const QStringList parts = value.split(QLatin1Char(' '));
+ item.dir = item.dir || parts.value(0).contains(QLatin1Char('D'));
+ const QString mode = parts.value(1);
+ if (mode.size() == 10) {
+ item.dir = item.dir || mode.at(0) == QLatin1Char('d');
+ item.symlink = mode.at(0) == QLatin1Char('l');
+ item.executable = mode.at(3) == QLatin1Char('x');
+ }
+ } else if (key == QLatin1String("Encrypted")) {
+ item.encrypted = value == QLatin1String("+");
+ } else if (key == QLatin1String("Symbolic Link")) {
+ if (!value.isEmpty()) {
+ item.symlink = true;
+ item.linkTarget = value;
+ }
+ }
+ }
+ finish();
+ contents.ok = true;
+ return contents;
+}
+
+Contents listLsar(const QString &archive, Progress *progress)
+{
+ Contents contents;
+ Job job;
+ job.program = QStringLiteral("lsar");
+ // -ja: plain ASCII JSON, every other character escaped. -nr: what is
+ // in the archive, not inside archives in it.
+ job.arguments = {QStringLiteral("-ja"), QStringLiteral("-nr"), archive};
+ const Outcome outcome = run(job, progress);
+ if (outcome.cancelled) {
+ contents.cancelled = true;
+ return contents;
+ }
+ if (!outcome.started) {
+ contents.error = QString::fromUtf8(outcome.errors);
+ return contents;
+ }
+ if (outcome.errors.contains("requires a password")) {
+ contents.needsPassword = true;
+ contents.password = Reader::PasswordState::Needed;
+ return contents;
+ }
+ QJsonParseError parseError;
+ const QJsonDocument document = QJsonDocument::fromJson(outcome.output, &parseError);
+ if (parseError.error != QJsonParseError::NoError || !document.isObject()) {
+ const QString errors = QString::fromUtf8(outcome.errors).trimmed();
+ contents.error = errors.isEmpty() ? QStringLiteral("The Unarchiver couldn't read this archive.") : errors;
+ return contents;
+ }
+ const QJsonObject root = document.object();
+ contents.type = root.value(QLatin1String("lsarFormatName")).toString();
+ const QJsonArray list = root.value(QLatin1String("lsarContents")).toArray();
+ for (qsizetype i = 0; i < list.size(); ++i) {
+ const QJsonObject o = list.at(i).toObject();
+ // Archive picks entries for unar by this index, so the listing
+ // must have them in that order.
+ if (o.value(QLatin1String("XADIndex")).toInt(-1) != int(i)) {
+ contents.error = QStringLiteral("The Unarchiver listed this archive out of order.");
+ return contents;
+ }
+ Item item;
+ // Mac resource forks sit beside their files; unar is told to
+ // skip them, so they are left out here too.
+ if (!o.value(QLatin1String("XADIsResourceFork")).toInt()) {
+ item.path = o.value(QLatin1String("XADFileName")).toString();
+ }
+ item.dir = o.value(QLatin1String("XADIsDirectory")).toInt() != 0;
+ item.symlink = o.value(QLatin1String("XADIsLink")).toInt() != 0;
+ item.linkTarget = o.value(QLatin1String("XADLinkDestination")).toString();
+ item.size = qint64(o.value(QLatin1String("XADFileSize")).toDouble());
+ item.packed = o.contains(QLatin1String("XADCompressedSize")) ? qint64(o.value(QLatin1String("XADCompressedSize")).toDouble()) : -1;
+ item.modified = lsarTime(o.value(QLatin1String("XADLastModificationDate")).toString());
+ item.encrypted = o.value(QLatin1String("XADIsEncrypted")).toInt() != 0;
+ item.executable = (o.value(QLatin1String("XADPosixPermissions")).toInt() & 0111) != 0;
+ contents.items.append(item);
+ }
+ contents.ok = true;
+ return contents;
+}
+
+}
diff --git a/packages/wildos-archive/src/tools.h b/packages/wildos-archive/src/tools.h
new file mode 100644
index 0000000..04afee4
--- /dev/null
+++ b/packages/wildos-archive/src/tools.h
@@ -0,0 +1,96 @@
+#pragma once
+
+#include "progress.h"
+#include "reader.h"
+
+#include <QByteArray>
+#include <QDateTime>
+#include <QList>
+#include <QString>
+#include <QStringList>
+
+#include <functional>
+
+// The free archivers Archive hands over to where libarchive cannot
+// decrypt: 7-Zip (7z, from the 7zip package) for protected 7z, and The
+// Unarchiver (unar and lsar, from the unar package) for protected RAR.
+//
+// A password never goes on a command line, where every user on the PC can
+// read it in /proc. 7z reads it from its stdin when it is not a terminal.
+// unar only takes it with -p or at its own prompt, which it shows on a
+// terminal, so it runs on a pseudo terminal of its own and is answered
+// there.
+namespace Tools
+{
+struct Job {
+ QString program;
+ QStringList arguments;
+ QByteArray password;
+ // On a pseudo terminal, answering the tool's password prompt, rather
+ // than on pipes with the password on stdin.
+ bool terminal = false;
+ // Takes stdout as it comes instead of keeping it. Returning false
+ // stops the tool.
+ std::function<bool(const char *data, qsizetype size)> data;
+ // Each line of text the tool prints, for progress.
+ std::function<void(const QByteArray &line)> line;
+};
+
+struct Outcome {
+ bool started = false;
+ bool cancelled = false;
+ // Stopped because `data` asked.
+ bool stopped = false;
+ int exitCode = -1;
+ // stdout, or everything the terminal showed.
+ QByteArray output;
+ QByteArray errors;
+ bool askedForPassword = false;
+ // Asked a second time: the first answer was not taken.
+ bool askedAgain = false;
+};
+
+bool available(const QString &program);
+Outcome run(const Job &job, Progress *progress);
+
+// Overwrites the bytes in place, for passwords: every copy of an
+// implicitly shared QByteArray sees the zeros.
+void wipe(QByteArray &bytes);
+// Removes a folder and everything in it without following any link.
+void removeTree(const QString &path);
+// A new private folder (0700) inside `parent`, or empty.
+QString makeStaging(const QString &parent);
+
+struct Item {
+ QString path;
+ qint64 size = 0;
+ qint64 packed = -1;
+ QDateTime modified;
+ bool dir = false;
+ bool symlink = false;
+ bool encrypted = false;
+ bool executable = false;
+ QString linkTarget;
+};
+
+struct Contents {
+ QList<Item> items;
+ // 7z's "Type" or lsar's format name.
+ QString type;
+ bool ok = false;
+ bool cancelled = false;
+ // Even the names are behind a password.
+ bool needsPassword = false;
+ Reader::PasswordState password = Reader::PasswordState::Fine;
+ QString error;
+};
+
+// `7z l -slt`, with the password on stdin when there is one.
+Contents list7z(const QString &archive, const QByteArray &password, Progress *progress);
+// `lsar -j`; lsar cannot take a password safely, so an archive with hidden
+// names comes back with needsPassword and is listed with 7z instead.
+Contents listLsar(const QString &archive, Progress *progress);
+
+// What a tool said about the password, from its output.
+Reader::PasswordState passwordOutcome(const Outcome &outcome, const QByteArray &password);
+}
diff --git a/packages/wildos-backup/CMakeLists.txt b/packages/wildos-backup/CMakeLists.txt
index 8e8f66b..53e66c0 100644
--- a/packages/wildos-backup/CMakeLists.txt
+++ b/packages/wildos-backup/CMakeLists.txt
@@ -33,6 +33,7 @@ qt_add_qml_module(wildos-backup
src/keyring.cpp src/keyring.h
src/restic.cpp src/restic.h
src/plan.cpp src/plan.h
+ src/driveclass.cpp src/driveclass.h
src/drives.cpp src/drives.h
src/history.cpp src/history.h
src/windowsmode.cpp src/windowsmode.h
@@ -69,3 +70,13 @@ install(FILES
install(FILES data/systemd/manual.d/50-now.conf DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/user/[email protected])
install(PROGRAMS data/windows-disk data/make-folder DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/wildos-backup)
install(FILES data/org.wildos.backup.policy DESTINATION ${CMAKE_INSTALL_DATADIR}/polkit-1/actions)
+
+option(BUILD_TESTING "Build the tests" ON)
+if(BUILD_TESTING)
+ enable_testing()
+ find_package(Qt6 6.8 REQUIRED COMPONENTS Test)
+ qt_add_executable(driveclass-test tests/driveclass-test.cpp src/driveclass.cpp)
+ target_include_directories(driveclass-test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
+ target_link_libraries(driveclass-test PRIVATE Qt6::Test Qt6::DBus)
+ add_test(NAME driveclass COMMAND driveclass-test)
+endif()
diff --git a/packages/wildos-backup/debian/changelog b/packages/wildos-backup/debian/changelog
index b402e6f..3a11072 100644
--- a/packages/wildos-backup/debian/changelog
+++ b/packages/wildos-backup/debian/changelog
@@ -1,3 +1,14 @@
+wildos-backup (0.1.1) trixie; urgency=medium
+
+ * Drives plugged in lists every drive you plug in. One Backup can't use
+ is greyed and says why: a Wild OS installer stick, a disc image,
+ read-only, too small, a filesystem Backup can't write to, or locked.
+ Format this drive is offered where formatting would fix it.
+ * Backup no longer waits for a drive when the one plugged in can't be
+ used: it says no drive here can hold backups yet.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 12:49:40 +0000
+
wildos-backup (0.1.0) trixie; urgency=medium
* Initial release.
diff --git a/packages/wildos-backup/qml/DriveChoice.qml b/packages/wildos-backup/qml/DriveChoice.qml
index 8472af3..e8d5b92 100644
--- a/packages/wildos-backup/qml/DriveChoice.qml
+++ b/packages/wildos-backup/qml/DriveChoice.qml
@@ -3,8 +3,9 @@ import QtQuick.Layouts
import WildOS.Backup
import WildOS.UI as UI
-// A drive that's plugged in and could take backups: its name, kind and
-// room, and Use this drive.
+// A drive that's plugged in: its name, kind and room, and Use this drive.
+// One Backup can't use is greyed, says why, and offers Format this drive
+// when formatting would fix it.
Item {
id: row
@@ -12,9 +13,11 @@ Item {
property bool busy: false
property string actionText: qsTr("Use this drive")
+ readonly property bool usable: drive.usable !== false
+
signal chosen()
- implicitHeight: 56
+ implicitHeight: Math.max(56, details.implicitHeight + 20)
Rectangle {
width: parent.width
@@ -27,11 +30,14 @@ Item {
spacing: 14
BackupIcon {
+ Layout.alignment: row.usable ? Qt.AlignVCenter : Qt.AlignTop
+ Layout.topMargin: row.usable ? 0 : 11
name: "drive"
size: 18
- color: UI.Style.inkMuted
+ color: row.usable ? UI.Style.inkMuted : UI.Style.inkSubtle
}
ColumnLayout {
+ id: details
Layout.fillWidth: true
spacing: 2
@@ -39,6 +45,7 @@ Item {
Layout.fillWidth: true
text: row.drive.name || ""
size: 13.5
+ color: row.usable ? UI.Style.ink : UI.Style.inkMuted
elide: Text.ElideRight
}
UI.Label {
@@ -53,16 +60,32 @@ Item {
return parts.join(" · ");
}
size: 12.5
- color: UI.Style.inkMuted
+ color: row.usable ? UI.Style.inkMuted : UI.Style.inkSubtle
elide: Text.ElideRight
}
+ UI.Label {
+ Layout.fillWidth: true
+ visible: !row.usable
+ text: row.drive.reasonText || ""
+ size: 12.5
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ }
}
UI.Button {
implicitHeight: 32
+ visible: row.usable
text: row.actionText
busy: row.busy
enabled: Setup.state !== "working"
onClicked: row.chosen()
}
+ UI.Button {
+ implicitHeight: 32
+ visible: !row.usable && row.drive.canFormat === true
+ text: qsTr("Format this drive")
+ enabled: Setup.state !== "working"
+ onClicked: Drives.formatDrive(row.drive.device)
+ }
}
}
diff --git a/packages/wildos-backup/qml/DrivesPage.qml b/packages/wildos-backup/qml/DrivesPage.qml
index 9d52c0a..20b5c85 100644
--- a/packages/wildos-backup/qml/DrivesPage.qml
+++ b/packages/wildos-backup/qml/DrivesPage.qml
@@ -14,7 +14,8 @@ Item {
property string choosing
property string removing
- readonly property var others: Drives.available.filter(d => !d.known)
+ readonly property var others: Drives.all.filter(d => !d.known)
+ readonly property bool anyUsable: others.some(d => d.usable)
Flickable {
id: flick
@@ -167,15 +168,25 @@ Item {
wrapMode: Text.Wrap
}
+ UI.Label {
+ Layout.fillWidth: true
+ Layout.bottomMargin: 6
+ visible: page.others.length > 0 && !page.anyUsable
+ text: qsTr("No drive here can hold backups yet.")
+ size: 13
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ }
+
Repeater {
model: page.others
delegate: DriveChoice {
required property var modelData
Layout.fillWidth: true
drive: modelData
- busy: Setup.state === "working" && page.choosing === modelData.uuid
+ busy: Setup.state === "working" && page.choosing === modelData.id
onChosen: {
- page.choosing = modelData.uuid;
+ page.choosing = modelData.id;
Setup.useDrive(modelData.uuid);
}
}
diff --git a/packages/wildos-backup/qml/SetupCard.qml b/packages/wildos-backup/qml/SetupCard.qml
index faffceb..f07d54b 100644
--- a/packages/wildos-backup/qml/SetupCard.qml
+++ b/packages/wildos-backup/qml/SetupCard.qml
@@ -10,9 +10,11 @@ Panel {
property string choosing
- readonly property var drives: Drives.available.filter(d => !d.known)
+ // Usable ones first; the rest greyed with their reason.
+ readonly property var drives: Drives.all.filter(d => !d.known)
+ readonly property bool anyUsable: drives.some(d => d.usable)
readonly property bool working: Setup.state === "working"
- readonly property int step: working ? 3 : drives.length > 0 ? 2 : 1
+ readonly property int step: working ? 3 : anyUsable ? 2 : 1
implicitHeight: column.implicitHeight + padding * 2
padding: 22
@@ -138,15 +140,25 @@ Panel {
Accessible.role: Accessible.Heading
}
+ UI.Label {
+ Layout.fillWidth: true
+ Layout.bottomMargin: 6
+ visible: card.drives.length > 0 && !card.anyUsable
+ text: qsTr("No drive here can hold backups yet.")
+ size: 13
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ }
+
Repeater {
model: card.drives
delegate: DriveChoice {
required property var modelData
Layout.fillWidth: true
drive: modelData
- busy: card.working && card.choosing === modelData.uuid
+ busy: card.working && card.choosing === modelData.id
onChosen: {
- card.choosing = modelData.uuid;
+ card.choosing = modelData.id;
Setup.useDrive(modelData.uuid);
}
}
diff --git a/packages/wildos-backup/src/driveclass.cpp b/packages/wildos-backup/src/driveclass.cpp
new file mode 100644
index 0000000..d1ce615
--- /dev/null
+++ b/packages/wildos-backup/src/driveclass.cpp
@@ -0,0 +1,337 @@
+#include "driveclass.h"
+
+#include <QCoreApplication>
+#include <QDBusArgument>
+#include <QDBusObjectPath>
+#include <QFile>
+#include <QLocale>
+#include <QStorageInfo>
+
+#include <cmath>
+
+namespace
+{
+const QString blockIface = QStringLiteral("org.freedesktop.UDisks2.Block");
+const QString fsIface = QStringLiteral("org.freedesktop.UDisks2.Filesystem");
+const QString driveIface = QStringLiteral("org.freedesktop.UDisks2.Drive");
+const QString partIface = QStringLiteral("org.freedesktop.UDisks2.Partition");
+const QString tableIface = QStringLiteral("org.freedesktop.UDisks2.PartitionTable");
+const QString cryptIface = QStringLiteral("org.freedesktop.UDisks2.Encrypted");
+
+// The installer's ISO 9660 volume ID (build/build.sh VOLID).
+const QString installerLabel = QStringLiteral("WILDOS");
+
+// UDisks2 sends paths as NUL-terminated byte arrays.
+QString bytes(const QVariant &v)
+{
+ if (v.metaType().id() == QMetaType::QString) {
+ return v.toString();
+ }
+ return QString::fromUtf8(v.toByteArray().constData());
+}
+
+QStringList byteArrays(const QVariant &v)
+{
+ QStringList out;
+ if (v.metaType() == QMetaType::fromType<QDBusArgument>()) {
+ const QDBusArgument arg = v.value<QDBusArgument>();
+ arg.beginArray();
+ while (!arg.atEnd()) {
+ QByteArray b;
+ arg >> b;
+ out << QString::fromUtf8(b.constData());
+ }
+ arg.endArray();
+ } else {
+ for (const QVariant &item : v.toList()) {
+ out << bytes(item);
+ }
+ }
+ return out;
+}
+
+QString objectPath(const QVariant &v)
+{
+ if (v.metaType() == QMetaType::fromType<QDBusObjectPath>()) {
+ return v.value<QDBusObjectPath>().path();
+ }
+ return v.toString();
+}
+
+bool realPath(const QString &path)
+{
+ return !path.isEmpty() && path != QLatin1String("/");
+}
+
+bool systemMount(const QString &mountPoint)
+{
+ // The last three are the live system's own medium, when Wild OS runs
+ // from the stick: that stick is not one the person plugged in.
+ static const QStringList system{
+ QStringLiteral("/"), QStringLiteral("/home"), QStringLiteral("/boot"), QStringLiteral("/boot/efi"),
+ QStringLiteral("/efi"), QStringLiteral("/usr"), QStringLiteral("/var"),
+ QStringLiteral("/run/initramfs/live"), QStringLiteral("/run/live/medium"), QStringLiteral("/cdrom"),
+ };
+ return system.contains(mountPoint);
+}
+
+bool discType(const QString &type)
+{
+ return type == QLatin1String("iso9660") || type == QLatin1String("udf");
+}
+
+// make-iso.sh writes this. It can only be read when something else
+// mounted the stick already; Backup never mounts one to look.
+bool liveMarker(const QStringList &mounts)
+{
+ for (const QString &m : mounts) {
+ QFile info(m + QStringLiteral("/.disk/info"));
+ if (info.open(QIODevice::ReadOnly) && info.read(256).startsWith("Wild OS")) {
+ return true;
+ }
+ }
+ return false;
+}
+
+// As BackupStyle.size: decimal units, one place under 10.
+QString sizeText(qint64 count)
+{
+ double v = double(count) / 1e9;
+ QString unit = QCoreApplication::translate("Drives", "GB");
+ if (v < 1) {
+ v = double(count) / 1e6;
+ unit = QCoreApplication::translate("Drives", "MB");
+ }
+ const bool decimal = v < 10 && std::abs(v - std::round(v)) >= 0.05;
+ return QStringLiteral("%1 %2").arg(QLocale().toString(v, 'f', decimal ? 1 : 0), unit);
+}
+}
+
+bool DriveClass::writableType(const QString &type)
+{
+ // Not hfsplus: Linux mounts journaled HFS+, which Macs make, read-only.
+ static const QStringList ok{
+ QStringLiteral("vfat"), QStringLiteral("exfat"), QStringLiteral("ntfs"), QStringLiteral("ntfs3"),
+ QStringLiteral("ext2"), QStringLiteral("ext3"), QStringLiteral("ext4"), QStringLiteral("btrfs"),
+ QStringLiteral("xfs"), QStringLiteral("f2fs"),
+ };
+ return ok.contains(type);
+}
+
+QList<DriveInfo> DriveClass::classify(const Objects &objects)
+{
+ // Blocks by the drive they sit on. What an unlocked encrypted drive
+ // holds follows the drive it was unlocked from.
+ QMap<QString, QStringList> groups;
+ QStringList order;
+ auto groupOf = [&objects](const QString &path) {
+ QString at = path;
+ for (int hops = 0; hops < 4; ++hops) {
+ const QVariantMap block = objects.value(at).value(blockIface);
+ const QString backing = objectPath(block.value(QStringLiteral("CryptoBackingDevice")));
+ if (!realPath(backing) || !objects.contains(backing)) {
+ const QString drive = objectPath(block.value(QStringLiteral("Drive")));
+ return realPath(drive) ? drive : at;
+ }
+ at = backing;
+ }
+ return at;
+ };
+ for (auto it = objects.cbegin(); it != objects.cend(); ++it) {
+ if (!it.value().contains(blockIface)) {
+ continue;
+ }
+ const QString key = groupOf(it.key());
+ if (!groups.contains(key)) {
+ order << key;
+ }
+ groups[key] << it.key();
+ }
+
+ QList<DriveInfo> out;
+ for (const QString &key : order) {
+ const QStringList blocks = groups.value(key);
+ const QVariantMap drive = objects.value(key).value(driveIface);
+ const QString bus = drive.value(QStringLiteral("ConnectionBus")).toString();
+ const bool removable = drive.value(QStringLiteral("Removable")).toBool() || drive.value(QStringLiteral("MediaRemovable")).toBool()
+ || drive.value(QStringLiteral("Ejectable")).toBool() || bus == QLatin1String("usb") || bus == QLatin1String("ieee1394")
+ || bus == QLatin1String("sdio");
+ const bool optical = drive.value(QStringLiteral("Optical")).toBool();
+
+ QString whole;
+ bool onSystem = false;
+ bool hotPlugged = false;
+ bool installer = false;
+ bool disc = false;
+ QString discLabel;
+ for (const QString &path : blocks) {
+ const auto ifaces = objects.value(path);
+ const QVariantMap block = ifaces.value(blockIface);
+ if (!ifaces.contains(partIface) && !realPath(objectPath(block.value(QStringLiteral("CryptoBackingDevice"))))) {
+ whole = path;
+ }
+ }
+ for (const QString &path : blocks) {
+ const auto ifaces = objects.value(path);
+ const QVariantMap block = ifaces.value(blockIface);
+ const QStringList mounts = byteArrays(ifaces.value(fsIface).value(QStringLiteral("MountPoints")));
+ for (const QString &m : mounts) {
+ onSystem = onSystem || systemMount(m);
+ }
+ // UDisks2 clears HintSystem for anything removable or plugged in
+ // while running, such as an eSATA disk.
+ hotPlugged = hotPlugged || !block.value(QStringLiteral("HintSystem"), true).toBool();
+ const QString label = block.value(QStringLiteral("IdLabel")).toString().trimmed();
+ if (block.value(QStringLiteral("IdUsage")).toString() == QLatin1String("filesystem")
+ && discType(block.value(QStringLiteral("IdType")).toString())) {
+ disc = true;
+ if (discLabel.isEmpty() || path == whole) {
+ discLabel = label;
+ }
+ installer = installer || label.compare(installerLabel, Qt::CaseInsensitive) == 0 || liveMarker(mounts);
+ }
+ }
+ const bool shown = (removable || hotPlugged) && !onSystem;
+
+ QString kind;
+ const QString firstDevice = bytes(objects.value(whole.isEmpty() ? blocks.value(0) : whole).value(blockIface).value(QStringLiteral("Device")));
+ if (firstDevice.startsWith(QLatin1String("/dev/loop"))) {
+ kind = QCoreApplication::translate("Drives", "Disk image");
+ } else if (bus == QLatin1String("sdio") || drive.value(QStringLiteral("Media")).toString().startsWith(QLatin1String("flash_sd"))) {
+ kind = QCoreApplication::translate("Drives", "SD card");
+ } else if (bus == QLatin1String("usb")) {
+ kind = QCoreApplication::translate("Drives", "USB drive");
+ } else {
+ kind = QCoreApplication::translate("Drives", "External drive");
+ }
+ const QString model = (drive.value(QStringLiteral("Vendor")).toString().trimmed() + QLatin1Char(' ')
+ + drive.value(QStringLiteral("Model")).toString().trimmed())
+ .trimmed();
+ const bool wholeReadOnly = objects.value(whole).value(blockIface).value(QStringLiteral("ReadOnly")).toBool();
+
+ auto row = [&](const QString &path) {
+ const auto ifaces = objects.value(path);
+ const QVariantMap block = ifaces.value(blockIface);
+ const QVariantMap fs = ifaces.value(fsIface);
+ DriveInfo d;
+ d.object = path;
+ d.uuid = block.value(QStringLiteral("IdUUID")).toString();
+ d.id = d.uuid.isEmpty() ? path : d.uuid;
+ d.device = bytes(block.value(QStringLiteral("Device")));
+ d.fsType = block.value(QStringLiteral("IdType")).toString();
+ d.size = block.value(QStringLiteral("Size")).toLongLong();
+ d.mountPoint = byteArrays(fs.value(QStringLiteral("MountPoints"))).value(0);
+ d.kind = kind;
+ d.shown = shown;
+ d.optical = optical;
+ const QString label = block.value(QStringLiteral("IdLabel")).toString().trimmed();
+ d.name = !label.isEmpty() ? label : !model.isEmpty() ? model : kind;
+ // A write-protect switch makes the kernel, and so UDisks2, call
+ // the whole device read-only.
+ bool readOnly = wholeReadOnly || block.value(QStringLiteral("ReadOnly")).toBool() || fs.value(QStringLiteral("ReadOnly")).toBool();
+ if (!d.mountPoint.isEmpty()) {
+ const QStorageInfo storage(d.mountPoint);
+ readOnly = readOnly || (storage.isValid() && storage.isReadOnly());
+ }
+ if (readOnly) {
+ d.problems << QStringLiteral("readOnly");
+ }
+ return d;
+ };
+
+ if (disc) {
+ // One row for the whole stick: an installer's EFI partition and
+ // the copy of the image in its first partition are all one thing.
+ DriveInfo d = row(whole.isEmpty() ? blocks.value(0) : whole);
+ d.id = key;
+ d.problems << (installer ? QStringLiteral("installer") : QStringLiteral("image"));
+ d.name = !discLabel.isEmpty() ? discLabel : !model.isEmpty() ? model : kind;
+ out << d;
+ continue;
+ }
+
+ QList<DriveInfo> main;
+ QList<DriveInfo> spare;
+ for (const QString &path : blocks) {
+ const auto ifaces = objects.value(path);
+ const QVariantMap block = ifaces.value(blockIface);
+ const QString usage = block.value(QStringLiteral("IdUsage")).toString();
+ if (block.value(QStringLiteral("HintIgnore")).toBool()) {
+ continue;
+ }
+ if (usage == QLatin1String("filesystem")) {
+ DriveInfo d = row(path);
+ if (!writableType(d.fsType) || d.uuid.isEmpty()) {
+ d.problems << QStringLiteral("filesystem");
+ }
+ main << d;
+ } else if (usage == QLatin1String("crypto")) {
+ const QString clear = objectPath(ifaces.value(cryptIface).value(QStringLiteral("CleartextDevice")));
+ if (realPath(clear) && objects.contains(clear)) {
+ continue;
+ }
+ DriveInfo d = row(path);
+ d.problems << QStringLiteral("locked");
+ main << d;
+ } else if (ifaces.contains(tableIface) || ifaces.value(partIface).value(QStringLiteral("IsContainer")).toBool()) {
+ continue;
+ } else if (block.value(QStringLiteral("Size")).toLongLong() > 0) {
+ // Blank, swap, or part of a RAID set.
+ DriveInfo d = row(path);
+ d.problems << QStringLiteral("filesystem");
+ (path == whole ? main : spare) << d;
+ }
+ }
+ // An empty partition beside a usable one is most likely a reserved
+ // one Windows or a Mac made, not worth a row of its own.
+ if (main.isEmpty()) {
+ main = spare;
+ }
+ if (main.isEmpty() && !whole.isEmpty() && objects.value(whole).value(blockIface).value(QStringLiteral("Size")).toLongLong() > 0) {
+ // A partition table with nothing Backup can see in it.
+ DriveInfo d = row(whole);
+ d.problems << QStringLiteral("filesystem");
+ main << d;
+ }
+ out << main;
+ }
+ return out;
+}
+
+void DriveClass::judge(DriveInfo &d, qint64 needed)
+{
+ const bool small = d.size > 0 && (d.size < smallestDrive || (needed > 0 && d.size < needed));
+ static const QStringList order{
+ QStringLiteral("installer"), QStringLiteral("image"), QStringLiteral("readOnly"),
+ QStringLiteral("small"), QStringLiteral("filesystem"), QStringLiteral("locked"),
+ };
+ d.reason.clear();
+ for (const QString &r : order) {
+ if (r == QLatin1String("small") ? small : d.problems.contains(r)) {
+ d.reason = r;
+ break;
+ }
+ }
+ if (d.reason == QLatin1String("installer")) {
+ d.reasonText = QCoreApplication::translate("Drives", "This is a Wild OS installer stick, so it can't hold backups.");
+ } else if (d.reason == QLatin1String("image")) {
+ d.reasonText = QCoreApplication::translate("Drives", "This drive holds a disc image, so it can't hold backups.");
+ } else if (d.reason == QLatin1String("readOnly")) {
+ d.reasonText = QCoreApplication::translate("Drives", "This drive is read-only.");
+ } else if (d.reason == QLatin1String("small")) {
+ d.reasonText = needed > d.size
+ ? QCoreApplication::translate("Drives", "This drive is too small for your backups (%1, your files need about %2).")
+ .arg(sizeText(d.size), sizeText(needed))
+ : QCoreApplication::translate("Drives", "This drive is too small for your backups (%1, Backup needs one of 4 GB or more).")
+ .arg(sizeText(d.size));
+ } else if (d.reason == QLatin1String("filesystem")) {
+ d.reasonText = QCoreApplication::translate("Drives", "Backup can't use this drive as it is.");
+ } else if (d.reason == QLatin1String("locked")) {
+ d.reasonText = QCoreApplication::translate("Drives", "Unlock this drive in Files first.");
+ } else {
+ d.reasonText.clear();
+ }
+ d.usable = d.shown && d.reason.isEmpty() && !d.uuid.isEmpty();
+ d.canFormat = d.shown && !d.optical
+ && (d.reason == QLatin1String("installer") || d.reason == QLatin1String("image") || d.reason == QLatin1String("filesystem"));
+}
diff --git a/packages/wildos-backup/src/driveclass.h b/packages/wildos-backup/src/driveclass.h
new file mode 100644
index 0000000..4f3d598
--- /dev/null
+++ b/packages/wildos-backup/src/driveclass.h
@@ -0,0 +1,61 @@
+#pragma once
+
+#include <QMap>
+#include <QString>
+#include <QStringList>
+#include <QVariantMap>
+
+// One drive or filesystem UDisks2 knows about, and whether Backup may use
+// it. Internal disks are kept too (shown false) so the scheduled run can
+// still find a drive the person picked by its UUID.
+struct DriveInfo {
+ // Unique in a scan: the filesystem UUID, or the UDisks2 object path for
+ // something without one (a blank stick, a locked drive).
+ QString id;
+ QString uuid;
+ QString object; // the block device's UDisks2 object path
+ QString device;
+ QString name;
+ QString kind;
+ QString fsType;
+ qint64 size = 0;
+ QString mountPoint;
+ // Plugged in by the person: removable or hot-plugged, and holding
+ // nothing of the running system.
+ bool shown = false;
+ // Every reason Backup can't use it, unordered; DriveClass::judge picks
+ // the one to tell.
+ QStringList problems;
+ // Set by judge: the reason shown, or empty when Backup may use it.
+ QString reason;
+ QString reasonText;
+ bool usable = false;
+ bool canFormat = false;
+ bool optical = false;
+
+ QVariantMap toMap() const;
+};
+
+// Sorting what UDisks2 reports into drives Backup can use and drives it
+// can't, from properties alone: a drive is never mounted to find out.
+namespace DriveClass
+{
+// GetManagedObjects as plain values: object path, then interface, then
+// properties. Object paths and byte strings may be plain strings, so tests
+// and the test rig can write them by hand.
+using Objects = QMap<QString, QMap<QString, QVariantMap>>;
+
+// Under this a drive holds too little to be worth backing up to. A stick
+// sold as 4 GB holds a little under 4 billion bytes, so it still passes.
+constexpr qint64 smallestDrive = 3500000000LL;
+
+// Filesystems Backup writes to. restic's packs are 16 MiB, well inside
+// FAT32's 4 GB file limit, so FAT32 is fine.
+bool writableType(const QString &type);
+
+QList<DriveInfo> classify(const Objects &objects);
+
+// Settles reason, usable and canFormat, checking size against `needed`,
+// the bytes the backup would hold (0 or less when not known yet).
+void judge(DriveInfo &drive, qint64 needed);
+}
diff --git a/packages/wildos-backup/src/drives.cpp b/packages/wildos-backup/src/drives.cpp
index 09e425d..5017e59 100644
--- a/packages/wildos-backup/src/drives.cpp
+++ b/packages/wildos-backup/src/drives.cpp
@@ -1,5 +1,7 @@
#include "drives.h"
+#include "backupstatus.h"
#include "settings.h"
+#include "sizes.h"
#include <QCoreApplication>
#include <QDBusArgument>
@@ -8,11 +10,17 @@
#include <QDBusMetaType>
#include <QDBusObjectPath>
#include <QDBusReply>
+#include <QDesktopServices>
+#include <QFile>
#include <QFileInfo>
#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
#include <QPointer>
+#include <QProcess>
#include <QStorageInfo>
#include <QThread>
+#include <QUrl>
using InterfaceProps = QMap<QString, QVariantMap>;
using ManagedObjects = QMap<QDBusObjectPath, InterfaceProps>;
@@ -24,9 +32,7 @@ namespace
Drives *s_instance = nullptr;
const QString service = QStringLiteral("org.freedesktop.UDisks2");
-const QString blockIface = QStringLiteral("org.freedesktop.UDisks2.Block");
const QString fsIface = QStringLiteral("org.freedesktop.UDisks2.Filesystem");
-const QString driveIface = QStringLiteral("org.freedesktop.UDisks2.Drive");
void registerTypes()
{
@@ -38,47 +44,24 @@ void registerTypes()
}
}
-// UDisks2 sends paths as NUL-terminated byte arrays.
-QString bytes(const QVariant &v)
+// A stand-in for UDisks2 on test rigs without it: GetManagedObjects as
+// JSON, object paths and byte strings written as plain strings.
+DriveClass::Objects testObjects(const QString &file)
{
- return QString::fromUtf8(v.toByteArray().constData());
-}
-
-QStringList byteArrays(const QVariant &v)
-{
- QStringList out;
- if (v.canConvert<QDBusArgument>()) {
- const QDBusArgument arg = v.value<QDBusArgument>();
- arg.beginArray();
- while (!arg.atEnd()) {
- QByteArray b;
- arg >> b;
- out << QString::fromUtf8(b.constData());
+ DriveClass::Objects out;
+ QFile f(file);
+ if (!f.open(QIODevice::ReadOnly)) {
+ return out;
+ }
+ const QJsonObject all = QJsonDocument::fromJson(f.readAll()).object();
+ for (auto it = all.begin(); it != all.end(); ++it) {
+ const QJsonObject ifaces = it.value().toObject();
+ for (auto i = ifaces.begin(); i != ifaces.end(); ++i) {
+ out[it.key()][i.key()] = i.value().toObject().toVariantMap();
}
- arg.endArray();
}
return out;
}
-
-bool systemMount(const QString &mountPoint)
-{
- static const QStringList system{
- QStringLiteral("/"), QStringLiteral("/home"), QStringLiteral("/boot"), QStringLiteral("/boot/efi"),
- QStringLiteral("/efi"), QStringLiteral("/usr"), QStringLiteral("/var"),
- };
- return system.contains(mountPoint);
-}
-
-// Filesystems a backup can be written to.
-bool writableType(const QString &type)
-{
- static const QStringList ok{
- QStringLiteral("vfat"), QStringLiteral("exfat"), QStringLiteral("ntfs"), QStringLiteral("ntfs3"),
- QStringLiteral("ext2"), QStringLiteral("ext3"), QStringLiteral("ext4"), QStringLiteral("btrfs"),
- QStringLiteral("xfs"), QStringLiteral("f2fs"), QStringLiteral("hfsplus"),
- };
- return ok.contains(type);
-}
}
QVariantMap DriveInfo::toMap() const
@@ -86,6 +69,11 @@ QVariantMap DriveInfo::toMap() const
const qint64 free = mountPoint.isEmpty() ? -1 : Drives::freeBytes(mountPoint);
const qint64 total = mountPoint.isEmpty() ? size : Drives::totalBytes(mountPoint);
return {
+ {QStringLiteral("id"), id},
+ {QStringLiteral("usable"), usable},
+ {QStringLiteral("reason"), reason},
+ {QStringLiteral("reasonText"), reasonText},
+ {QStringLiteral("canFormat"), canFormat},
{QStringLiteral("uuid"), uuid},
{QStringLiteral("name"), name},
{QStringLiteral("kind"), kind},
@@ -94,7 +82,7 @@ QVariantMap DriveInfo::toMap() const
{QStringLiteral("free"), double(free)},
{QStringLiteral("mountPoint"), mountPoint},
{QStringLiteral("connected"), true},
- {QStringLiteral("known"), !Settings::instance()->drive(uuid).isEmpty()},
+ {QStringLiteral("known"), !uuid.isEmpty() && !Settings::instance()->drive(uuid).isEmpty()},
};
}
@@ -121,6 +109,14 @@ Drives *Drives::create(QQmlEngine *, QJSEngine *)
{
Drives *drives = instance();
QQmlEngine::setObjectOwnership(drives, QQmlEngine::CppOwnership);
+ // Only the app judges "too small" against what's included; the
+ // scheduled run and the watcher have no use for walking the home folder.
+ if (!drives->m_sizes) {
+ drives->m_sizes = BackupStatus::instance()->sizes();
+ connect(drives->m_sizes, &Sizes::changed, drives, &Drives::changed);
+ connect(Settings::instance(), &Settings::includeChanged, drives, &Drives::changed);
+ drives->m_sizes->refresh(false);
+ }
drives->watch();
return drives;
}
@@ -131,7 +127,6 @@ QList<DriveInfo> Drives::scan()
QDBusInterface manager(service, QStringLiteral("/org/freedesktop/UDisks2"), QStringLiteral("org.freedesktop.DBus.ObjectManager"),
QDBusConnection::systemBus());
manager.setTimeout(10000);
- const QDBusReply<ManagedObjects> reply = manager.call(QStringLiteral("GetManagedObjects"));
QList<DriveInfo> out;
// Test rigs without UDisks2 (a container, a CI job) stand a folder in
// for a plugged-in drive.
@@ -139,71 +134,37 @@ QList<DriveInfo> Drives::scan()
if (!testMount.isEmpty()) {
DriveInfo d;
d.uuid = QStringLiteral("test-drive");
+ d.id = d.uuid;
d.object = QStringLiteral("/test");
d.name = QStringLiteral("Test drive");
d.kind = QCoreApplication::translate("Drives", "USB drive");
d.mountPoint = testMount;
d.size = totalBytes(testMount);
- d.usable = QFileInfo(testMount).isDir();
- if (d.usable) {
+ d.shown = true;
+ if (QFileInfo(testMount).isDir()) {
+ DriveClass::judge(d, 0);
out.append(d);
}
}
- if (!reply.isValid()) {
- return out;
- }
- const ManagedObjects objects = reply.value();
- for (auto it = objects.cbegin(); it != objects.cend(); ++it) {
- const InterfaceProps &ifaces = it.value();
- if (!ifaces.contains(fsIface) || !ifaces.contains(blockIface)) {
- continue;
- }
- const QVariantMap block = ifaces.value(blockIface);
- const QVariantMap fs = ifaces.value(fsIface);
- if (block.value(QStringLiteral("HintIgnore")).toBool() || block.value(QStringLiteral("IdUsage")).toString() != QLatin1String("filesystem")) {
- continue;
- }
- DriveInfo d;
- d.object = it.key().path();
- d.uuid = block.value(QStringLiteral("IdUUID")).toString();
- d.device = bytes(block.value(QStringLiteral("Device")));
- d.fsType = block.value(QStringLiteral("IdType")).toString();
- d.size = block.value(QStringLiteral("Size")).toLongLong();
- const QStringList mounts = byteArrays(fs.value(QStringLiteral("MountPoints")));
- d.mountPoint = mounts.value(0);
- if (d.uuid.isEmpty()) {
- continue;
- }
- const QString drivePath = block.value(QStringLiteral("Drive")).value<QDBusObjectPath>().path();
- const QVariantMap drive = objects.value(QDBusObjectPath(drivePath)).value(driveIface);
- const QString bus = drive.value(QStringLiteral("ConnectionBus")).toString();
- const bool removable = drive.value(QStringLiteral("Removable")).toBool() || drive.value(QStringLiteral("MediaRemovable")).toBool()
- || bus == QLatin1String("usb") || bus == QLatin1String("ieee1394") || bus == QLatin1String("sdio");
- const bool hintSystem = block.value(QStringLiteral("HintSystem")).toBool();
- const bool loop = d.device.startsWith(QLatin1String("/dev/loop"));
-
- bool onSystem = false;
- for (const QString &m : mounts) {
- onSystem = onSystem || systemMount(m);
+ // Everything UDisks2 knows, plugged in before Backup started or since,
+ // mounted or not.
+ DriveClass::Objects objects;
+ const QString fake = qEnvironmentVariable("WILDOS_BACKUP_TEST_UDISKS");
+ if (!fake.isEmpty()) {
+ objects = testObjects(fake);
+ } else {
+ const QDBusReply<ManagedObjects> reply = manager.call(QStringLiteral("GetManagedObjects"));
+ if (!reply.isValid()) {
+ return out;
}
- d.usable = !onSystem && !block.value(QStringLiteral("ReadOnly")).toBool() && writableType(d.fsType)
- && (removable || !hintSystem);
-
- if (loop) {
- d.kind = QCoreApplication::translate("Drives", "Disk image");
- } else if (bus == QLatin1String("sdio") || drive.value(QStringLiteral("Media")).toString().startsWith(QLatin1String("flash_sd"))) {
- d.kind = QCoreApplication::translate("Drives", "SD card");
- } else if (bus == QLatin1String("usb")) {
- d.kind = QCoreApplication::translate("Drives", "USB drive");
- } else {
- d.kind = QCoreApplication::translate("Drives", "External drive");
+ const ManagedObjects managed = reply.value();
+ for (auto it = managed.cbegin(); it != managed.cend(); ++it) {
+ objects.insert(it.key().path(), it.value());
}
- const QString label = block.value(QStringLiteral("IdLabel")).toString().trimmed();
- const QString model = (drive.value(QStringLiteral("Vendor")).toString().trimmed() + QLatin1Char(' ')
- + drive.value(QStringLiteral("Model")).toString().trimmed())
- .trimmed();
- d.name = !label.isEmpty() ? label : !model.isEmpty() ? model : d.kind;
+ }
+ for (DriveInfo &d : DriveClass::classify(objects)) {
+ DriveClass::judge(d, 0);
out.append(d);
}
return out;
@@ -291,7 +252,9 @@ qint64 Drives::totalBytes(const QString &mountPoint)
QVariantList Drives::available() const
{
QVariantList out;
- for (const DriveInfo &d : m_drives) {
+ const qint64 need = needed();
+ for (DriveInfo d : m_drives) {
+ DriveClass::judge(d, need);
if (d.usable) {
out.append(d.toMap());
}
@@ -299,6 +262,66 @@ QVariantList Drives::available() const
return out;
}
+QVariantList Drives::all() const
+{
+ // Usable ones first, so the choice is at the top of the list.
+ QVariantList usable;
+ QVariantList others;
+ const qint64 need = needed();
+ for (DriveInfo d : m_drives) {
+ DriveClass::judge(d, need);
+ if (d.shown) {
+ (d.usable ? usable : others).append(d.toMap());
+ }
+ }
+ return usable + others;
+}
+
+qint64 Drives::needed() const
+{
+ if (!m_sizes) {
+ return 0;
+ }
+ Settings *settings = Settings::instance();
+ double total = 0;
+ const QList<QPair<bool, double>> parts{
+ {settings->includeHome(), m_sizes->home()},
+ {settings->includeMail(), m_sizes->mail()},
+ {settings->includeSettings(), m_sizes->settings()},
+ };
+ for (const auto &[on, bytes] : parts) {
+ if (on && bytes > 0) {
+ total += bytes;
+ }
+ }
+ return qint64(total);
+}
+
+void Drives::formatDrive(const QString &device)
+{
+ // Files gains Format on its own branch; until its --format lands, ask
+ // it whether it has one rather than guessing, since an option it
+ // doesn't know makes it stop without opening.
+ static int hasFormat = -1;
+ if (hasFormat < 0) {
+ QProcess help;
+ help.start(QStringLiteral("wildos-files"), {QStringLiteral("--help")});
+ hasFormat = help.waitForFinished(5000) && help.readAllStandardOutput().contains("--format") ? 1 : 0;
+ }
+ if (hasFormat == 1) {
+ QProcess::startDetached(QStringLiteral("wildos-files"), {QStringLiteral("--format"), device});
+ return;
+ }
+ for (const DriveInfo &d : m_drives) {
+ if (d.device == device && !d.mountPoint.isEmpty()) {
+ QDesktopServices::openUrl(QUrl::fromLocalFile(d.mountPoint));
+ return;
+ }
+ }
+ // Files lists plugged-in drives, mounted or not, beside Home.
+ QProcess::startDetached(QStringLiteral("wildos-files"), {});
+}
+
QVariantMap Drives::mine() const
{
QVariantMap out;
@@ -340,7 +363,7 @@ void Drives::refresh()
}();
m_drives = scan();
for (const DriveInfo &d : m_drives) {
- if (!before.contains(d.uuid)) {
+ if (!d.uuid.isEmpty() && !before.contains(d.uuid)) {
Q_EMIT appeared(d.uuid);
}
}
diff --git a/packages/wildos-backup/src/drives.h b/packages/wildos-backup/src/drives.h
index 99829ec..d5de0bd 100644
--- a/packages/wildos-backup/src/drives.h
+++ b/packages/wildos-backup/src/drives.h
@@ -8,21 +8,9 @@
#include <functional>
-// One filesystem UDisks2 knows about.
-struct DriveInfo {
- QString uuid;
- QString object; // the block device's UDisks2 object path
- QString device;
- QString name;
- QString kind;
- QString fsType;
- qint64 size = 0;
- QString mountPoint;
- // An external drive Backup may use; internal and system disks never.
- bool usable = false;
+#include "driveclass.h"
- QVariantMap toMap() const;
-};
+class Sizes;
// The drives plugged in now, over UDisks2 on the system bus, and mounting
// one. The app watches for drives coming and going; the scheduled run asks
@@ -35,6 +23,9 @@ class Drives : public QObject
// Usable drives plugged in now: [{ uuid, name, kind, size, free, mountPoint, known }]
Q_PROPERTY(QVariantList available READ available NOTIFY changed)
+ // Every drive the person plugged in, usable or not, each with its
+ // reason and whether formatting would fix it.
+ Q_PROPERTY(QVariantList all READ all NOTIFY changed)
// The person's own drives by filesystem UUID, plugged in or not, as
// info() gives them; and which of them a backup would use now. Real
// properties, so bindings follow drives coming, going and mounting.
@@ -63,6 +54,13 @@ public:
static qint64 totalBytes(const QString &mountPoint);
QVariantList available() const;
+ QVariantList all() const;
+ // About how much the parts picked in What's included hold; 0 until
+ // that is worked out.
+ qint64 needed() const;
+
+ // The one place Backup hands a drive to Files to format.
+ Q_INVOKABLE void formatDrive(const QString &device);
// For the pages: is it plugged in, how full, what is it called now.
Q_INVOKABLE QVariantMap info(const QString &uuid) const;
@@ -80,6 +78,7 @@ private Q_SLOTS:
private:
QList<DriveInfo> m_drives;
+ Sizes *m_sizes = nullptr;
QTimer m_debounce;
bool m_watching = false;
};
diff --git a/packages/wildos-backup/tests/driveclass-test.cpp b/packages/wildos-backup/tests/driveclass-test.cpp
new file mode 100644
index 0000000..73375ea
--- /dev/null
+++ b/packages/wildos-backup/tests/driveclass-test.cpp
@@ -0,0 +1,342 @@
+#include "driveclass.h"
+
+#include <QTest>
+
+namespace
+{
+const QString blockIface = QStringLiteral("org.freedesktop.UDisks2.Block");
+const QString fsIface = QStringLiteral("org.freedesktop.UDisks2.Filesystem");
+const QString driveIface = QStringLiteral("org.freedesktop.UDisks2.Drive");
+const QString partIface = QStringLiteral("org.freedesktop.UDisks2.Partition");
+const QString tableIface = QStringLiteral("org.freedesktop.UDisks2.PartitionTable");
+const QString cryptIface = QStringLiteral("org.freedesktop.UDisks2.Encrypted");
+
+constexpr qint64 GB = 1000000000LL;
+
+// What UDisks2 reports for a stick, built up a block at a time.
+struct Rig {
+ DriveClass::Objects objects;
+
+ QString drive(const QString &name, const QString &bus = QStringLiteral("usb"), bool removable = true)
+ {
+ const QString path = QStringLiteral("/org/freedesktop/UDisks2/drives/") + name;
+ objects[path][driveIface] = QVariantMap{
+ {QStringLiteral("Vendor"), QStringLiteral("SanDisk")},
+ {QStringLiteral("Model"), QStringLiteral("Ultra")},
+ {QStringLiteral("ConnectionBus"), bus},
+ {QStringLiteral("Removable"), removable},
+ };
+ return path;
+ }
+
+ // `usage` and `type` as blkid gives them; an empty usage is a blank one.
+ QString block(const QString &dev, const QString &drive, qint64 size, const QString &usage = {}, const QString &type = {},
+ const QVariantMap &extra = {}, bool partition = false)
+ {
+ const QString path = QStringLiteral("/org/freedesktop/UDisks2/block_devices/") + dev;
+ QVariantMap b{
+ {QStringLiteral("Device"), QStringLiteral("/dev/") + dev},
+ {QStringLiteral("Drive"), drive.isEmpty() ? QStringLiteral("/") : drive},
+ {QStringLiteral("Size"), size},
+ {QStringLiteral("IdUsage"), usage},
+ {QStringLiteral("IdType"), type},
+ {QStringLiteral("HintSystem"), drive.isEmpty() || !objects.value(drive).value(driveIface).value(QStringLiteral("Removable")).toBool()},
+ {QStringLiteral("ReadOnly"), false},
+ };
+ for (auto it = extra.cbegin(); it != extra.cend(); ++it) {
+ b.insert(it.key(), it.value());
+ }
+ objects[path][blockIface] = b;
+ if (usage == QLatin1String("filesystem")) {
+ objects[path][fsIface] = QVariantMap{{QStringLiteral("MountPoints"), QVariantList{}}};
+ }
+ if (partition) {
+ objects[path][partIface] = QVariantMap{{QStringLiteral("IsContainer"), false}};
+ }
+ return path;
+ }
+
+ void table(const QString &block)
+ {
+ objects[block][tableIface] = QVariantMap{{QStringLiteral("Type"), QStringLiteral("gpt")}};
+ }
+
+ void mount(const QString &block, const QString &at)
+ {
+ objects[block][fsIface] = QVariantMap{{QStringLiteral("MountPoints"), QVariantList{at}}};
+ }
+
+ QList<DriveInfo> shown(qint64 needed = 0) const
+ {
+ QList<DriveInfo> out;
+ for (DriveInfo d : DriveClass::classify(objects)) {
+ DriveClass::judge(d, needed);
+ if (d.shown) {
+ out << d;
+ }
+ }
+ return out;
+ }
+};
+
+QVariantMap label(const QString &label, const QString &uuid)
+{
+ return {{QStringLiteral("IdLabel"), label}, {QStringLiteral("IdUUID"), uuid}};
+}
+}
+
+class DriveClassTest : public QObject
+{
+ Q_OBJECT
+
+private Q_SLOTS:
+ // The stick from the report: the installer image dd'd onto a SanDisk,
+ // nothing mounted.
+ void installerStick()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("SanDisk"));
+ const QString whole = rig.block(QStringLiteral("sdb"), drive, 115 * GB, QStringLiteral("filesystem"), QStringLiteral("iso9660"),
+ label(QStringLiteral("WILDOS"), QStringLiteral("2026-11-10-12-00-00-00")));
+ rig.table(whole);
+ rig.block(QStringLiteral("sdb1"), drive, 3 * GB, QStringLiteral("filesystem"), QStringLiteral("iso9660"),
+ label(QStringLiteral("WILDOS"), QStringLiteral("2026-11-10-12-00-00-00")), true);
+ rig.block(QStringLiteral("sdb2"), drive, 10000000, QStringLiteral("filesystem"), QStringLiteral("vfat"),
+ label(QString(), QStringLiteral("ABCD-1234")), true);
+
+ const QList<DriveInfo> rows = rig.shown();
+ QCOMPARE(rows.size(), 1);
+ QCOMPARE(rows[0].reason, QStringLiteral("installer"));
+ QCOMPARE(rows[0].reasonText, QStringLiteral("This is a Wild OS installer stick, so it can't hold backups."));
+ QCOMPARE(rows[0].device, QStringLiteral("/dev/sdb"));
+ QCOMPARE(rows[0].name, QStringLiteral("WILDOS"));
+ QVERIFY(!rows[0].usable);
+ QVERIFY(rows[0].canFormat);
+ }
+
+ void otherDiscImage()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("Stick"));
+ rig.block(QStringLiteral("sdb"), drive, 16 * GB, QStringLiteral("filesystem"), QStringLiteral("udf"),
+ label(QStringLiteral("CCCOMA_X64FRE"), QStringLiteral("1234")));
+ const QList<DriveInfo> rows = rig.shown();
+ QCOMPARE(rows.size(), 1);
+ QCOMPARE(rows[0].reason, QStringLiteral("image"));
+ QCOMPARE(rows[0].reasonText, QStringLiteral("This drive holds a disc image, so it can't hold backups."));
+ QVERIFY(rows[0].canFormat);
+ }
+
+ void exfatStick()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("Stick"));
+ rig.table(rig.block(QStringLiteral("sdc"), drive, 64 * GB));
+ rig.block(QStringLiteral("sdc1"), drive, 64 * GB, QStringLiteral("filesystem"), QStringLiteral("exfat"),
+ label(QStringLiteral("STICK"), QStringLiteral("1A2B-3C4D")), true);
+ const QList<DriveInfo> rows = rig.shown();
+ QCOMPARE(rows.size(), 1);
+ QVERIFY(rows[0].usable);
+ QVERIFY(rows[0].reason.isEmpty());
+ QVERIFY(!rows[0].canFormat);
+ QCOMPARE(rows[0].name, QStringLiteral("STICK"));
+ QCOMPARE(rows[0].id, QStringLiteral("1A2B-3C4D"));
+ }
+
+ void readOnlyStick()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("Locked"));
+ rig.table(rig.block(QStringLiteral("sdd"), drive, 32 * GB, {}, {}, {{QStringLiteral("ReadOnly"), true}}));
+ rig.block(QStringLiteral("sdd1"), drive, 32 * GB, QStringLiteral("filesystem"), QStringLiteral("exfat"),
+ label(QStringLiteral("PHOTOS"), QStringLiteral("AAAA-BBBB")), true);
+ const QList<DriveInfo> rows = rig.shown();
+ QCOMPARE(rows.size(), 1);
+ QCOMPARE(rows[0].reason, QStringLiteral("readOnly"));
+ QCOMPARE(rows[0].reasonText, QStringLiteral("This drive is read-only."));
+ QVERIFY(!rows[0].usable);
+ QVERIFY(!rows[0].canFormat);
+ }
+
+ void smallStick()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("Small"));
+ rig.block(QStringLiteral("sde"), drive, 2 * GB, QStringLiteral("filesystem"), QStringLiteral("vfat"),
+ label(QStringLiteral("OLD"), QStringLiteral("1111-2222")));
+ QList<DriveInfo> rows = rig.shown();
+ QCOMPARE(rows.size(), 1);
+ QCOMPARE(rows[0].reason, QStringLiteral("small"));
+ QCOMPARE(rows[0].reasonText, QStringLiteral("This drive is too small for your backups (2 GB, Backup needs one of 4 GB or more)."));
+ QVERIFY(!rows[0].canFormat);
+
+ rows = rig.shown(12400000000LL);
+ QCOMPARE(rows[0].reasonText, QStringLiteral("This drive is too small for your backups (2 GB, your files need about 12 GB)."));
+ }
+
+ // A drive sold as 4 GB holds a little under 4 billion bytes.
+ void fourGigabyteStickIsFine()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("Four"));
+ rig.block(QStringLiteral("sde"), drive, 3880000000LL, QStringLiteral("filesystem"), QStringLiteral("vfat"),
+ label(QString(), QStringLiteral("1111-2222")));
+ QVERIFY(rig.shown()[0].usable);
+ }
+
+ void smallerThanTheFiles()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("Mid"));
+ rig.block(QStringLiteral("sde"), drive, 32 * GB, QStringLiteral("filesystem"), QStringLiteral("exfat"),
+ label(QString(), QStringLiteral("1111-2222")));
+ const QList<DriveInfo> rows = rig.shown(120 * GB);
+ QCOMPARE(rows[0].reason, QStringLiteral("small"));
+ QCOMPARE(rows[0].reasonText, QStringLiteral("This drive is too small for your backups (32 GB, your files need about 120 GB)."));
+ }
+
+ void unformattedStick()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("Blank"));
+ rig.block(QStringLiteral("sdf"), drive, 16 * GB);
+ const QList<DriveInfo> rows = rig.shown();
+ QCOMPARE(rows.size(), 1);
+ QCOMPARE(rows[0].reason, QStringLiteral("filesystem"));
+ QCOMPARE(rows[0].reasonText, QStringLiteral("Backup can't use this drive as it is."));
+ QCOMPARE(rows[0].device, QStringLiteral("/dev/sdf"));
+ QCOMPARE(rows[0].name, QStringLiteral("SanDisk Ultra"));
+ QVERIFY(rows[0].canFormat);
+ }
+
+ void emptyPartitionTable()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("Wiped"));
+ rig.table(rig.block(QStringLiteral("sdf"), drive, 16 * GB));
+ const QList<DriveInfo> rows = rig.shown();
+ QCOMPARE(rows.size(), 1);
+ QCOMPARE(rows[0].reason, QStringLiteral("filesystem"));
+ QVERIFY(rows[0].canFormat);
+ }
+
+ void unknownFilesystem()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("Mac"));
+ rig.table(rig.block(QStringLiteral("sdg"), drive, 500 * GB));
+ rig.block(QStringLiteral("sdg1"), drive, 200000000, QStringLiteral("filesystem"), QStringLiteral("vfat"),
+ {{QStringLiteral("IdUUID"), QStringLiteral("EFI-1")}, {QStringLiteral("HintIgnore"), true}}, true);
+ rig.block(QStringLiteral("sdg2"), drive, 499 * GB, QStringLiteral("filesystem"), QStringLiteral("hfsplus"),
+ label(QStringLiteral("Time Machine"), QStringLiteral("9999")), true);
+ const QList<DriveInfo> rows = rig.shown();
+ QCOMPARE(rows.size(), 1);
+ QCOMPARE(rows[0].reason, QStringLiteral("filesystem"));
+ QVERIFY(rows[0].canFormat);
+ }
+
+ // Windows' reserved partition beside NTFS gets no row of its own.
+ void reservedPartitionHidden()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("Passport"));
+ rig.table(rig.block(QStringLiteral("sdh"), drive, 1000 * GB));
+ rig.block(QStringLiteral("sdh1"), drive, 16000000, {}, {}, {}, true);
+ rig.block(QStringLiteral("sdh2"), drive, 999 * GB, QStringLiteral("filesystem"), QStringLiteral("ntfs"),
+ label(QStringLiteral("My Passport"), QStringLiteral("0123ABCD")), true);
+ const QList<DriveInfo> rows = rig.shown();
+ QCOMPARE(rows.size(), 1);
+ QVERIFY(rows[0].usable);
+ }
+
+ void lockedStick()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("Secret"));
+ rig.table(rig.block(QStringLiteral("sdi"), drive, 64 * GB));
+ const QString luks = rig.block(QStringLiteral("sdi1"), drive, 64 * GB, QStringLiteral("crypto"), QStringLiteral("crypto_LUKS"),
+ {{QStringLiteral("IdUUID"), QStringLiteral("luks-1")}}, true);
+ rig.objects[luks][cryptIface] = QVariantMap{{QStringLiteral("CleartextDevice"), QStringLiteral("/")}};
+ const QList<DriveInfo> rows = rig.shown();
+ QCOMPARE(rows.size(), 1);
+ QCOMPARE(rows[0].reason, QStringLiteral("locked"));
+ QCOMPARE(rows[0].reasonText, QStringLiteral("Unlock this drive in Files first."));
+ QVERIFY(!rows[0].canFormat);
+ }
+
+ // Once unlocked, what is inside shows instead, on the same stick.
+ void unlockedStick()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("Secret"));
+ rig.table(rig.block(QStringLiteral("sdi"), drive, 64 * GB));
+ const QString luks = rig.block(QStringLiteral("sdi1"), drive, 64 * GB, QStringLiteral("crypto"), QStringLiteral("crypto_LUKS"),
+ {{QStringLiteral("IdUUID"), QStringLiteral("luks-1")}}, true);
+ const QString clear = rig.block(QStringLiteral("dm-0"), {}, 64 * GB - 16000000, QStringLiteral("filesystem"), QStringLiteral("ext4"),
+ {{QStringLiteral("IdUUID"), QStringLiteral("ext-1")}, {QStringLiteral("CryptoBackingDevice"), luks}});
+ rig.objects[luks][cryptIface] = QVariantMap{{QStringLiteral("CleartextDevice"), clear}};
+ const QList<DriveInfo> rows = rig.shown();
+ QCOMPARE(rows.size(), 1);
+ QCOMPARE(rows[0].uuid, QStringLiteral("ext-1"));
+ QCOMPARE(rows[0].kind, QStringLiteral("USB drive"));
+ QVERIFY(rows[0].usable);
+ }
+
+ void internalDiskIgnored()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("NVMe"), QString(), false);
+ rig.table(rig.block(QStringLiteral("nvme0n1"), drive, 512 * GB));
+ const QString root = rig.block(QStringLiteral("nvme0n1p2"), drive, 500 * GB, QStringLiteral("filesystem"), QStringLiteral("ext4"),
+ {{QStringLiteral("IdUUID"), QStringLiteral("root")}}, true);
+ rig.mount(root, QStringLiteral("/"));
+ rig.block(QStringLiteral("nvme0n1p3"), drive, 10 * GB, QStringLiteral("filesystem"), QStringLiteral("ext4"),
+ {{QStringLiteral("IdUUID"), QStringLiteral("spare")}}, true);
+ QVERIFY(rig.shown().isEmpty());
+ // Still found by UUID, as before, for a run asking after it.
+ QCOMPARE(DriveClass::classify(rig.objects).size(), 2);
+ }
+
+ // Running live from the installer, the stick is the system itself.
+ void liveMediumIgnored()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("SanDisk"));
+ const QString whole = rig.block(QStringLiteral("sdb"), drive, 115 * GB, QStringLiteral("filesystem"), QStringLiteral("iso9660"),
+ label(QStringLiteral("WILDOS"), QStringLiteral("2026")));
+ rig.mount(whole, QStringLiteral("/run/initramfs/live"));
+ QVERIFY(rig.shown().isEmpty());
+ }
+
+ // The order the reasons are told in: an installer stick is that first,
+ // even if it is small and read-only.
+ void reasonOrder()
+ {
+ Rig rig;
+ const QString drive = rig.drive(QStringLiteral("Old"));
+ rig.block(QStringLiteral("sdb"), drive, 2 * GB, QStringLiteral("filesystem"), QStringLiteral("iso9660"),
+ {{QStringLiteral("IdLabel"), QStringLiteral("WILDOS")}, {QStringLiteral("ReadOnly"), true}});
+ QCOMPARE(rig.shown()[0].reason, QStringLiteral("installer"));
+
+ Rig rig2;
+ const QString drive2 = rig2.drive(QStringLiteral("Old"));
+ const QString block2 = rig2.block(QStringLiteral("sdb"), drive2, 2 * GB, QStringLiteral("filesystem"), QStringLiteral("hfsplus"),
+ {{QStringLiteral("IdUUID"), QStringLiteral("x")}, {QStringLiteral("ReadOnly"), true}});
+ QCOMPARE(rig2.shown()[0].reason, QStringLiteral("readOnly"));
+ rig2.objects[block2][blockIface][QStringLiteral("ReadOnly")] = false;
+ QCOMPARE(rig2.shown()[0].reason, QStringLiteral("small"));
+ }
+
+ void acceptedFilesystems()
+ {
+ for (const char *t : {"ext4", "exfat", "ntfs", "ntfs3", "btrfs", "xfs", "vfat"}) {
+ QVERIFY2(DriveClass::writableType(QString::fromLatin1(t)), t);
+ }
+ for (const char *t : {"hfsplus", "apfs", "iso9660", "squashfs", "swap", ""}) {
+ QVERIFY2(!DriveClass::writableType(QString::fromLatin1(t)), t);
+ }
+ }
+};
+
+QTEST_GUILESS_MAIN(DriveClassTest)
+#include "driveclass-test.moc"
diff --git a/packages/wildos-branding/debian/changelog b/packages/wildos-branding/debian/changelog
index f35d796..1078295 100644
--- a/packages/wildos-branding/debian/changelog
+++ b/packages/wildos-branding/debian/changelog
@@ -1,3 +1,17 @@
+wildos-branding (0.1.34) trixie; urgency=medium
+
+ * Start search results show each app's own icon again, not a
+ generic one, when results arrive in several bursts.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 13:10:50 +0000
+
+wildos-branding (0.1.33) trixie; urgency=medium
+
+ * The security status reports whether 32-bit apps can run, and the
+ taskbar shield lists it while they can.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 14:00:00 +0000
+
wildos-branding (0.1.32) trixie; urgency=medium
* The licence notice for the Settings icon is installed where it is
diff --git a/packages/wildos-branding/files/libexec/security-status b/packages/wildos-branding/files/libexec/security-status
index c78f11b..2716188 100644
--- a/packages/wildos-branding/files/libexec/security-status
+++ b/packages/wildos-branding/files/libexec/security-status
@@ -41,6 +41,9 @@
# people; for diagnostics and Settings.
# kernel=on|off Kicksecure's kernel hardening is in force. Not
# shown to people; for diagnostics and Settings.
+# compat32=on|off 32-bit programs can run: "Steam and 32-bit apps"
+# is on in Settings and the computer has restarted
+# since. Off is how Wild OS ships.
# ignored=a,b Warnings this person chose to ignore (see below).
#
# Some warnings describe a choice a person can reasonably make and live with:
@@ -256,5 +259,16 @@ else
echo "kernel=off"
fi
+# Kicksecure starts the kernel with ia32_emulation=0, which leaves out its
+# 32-bit compatibility layer; the kernel takes the last value it is given.
+compat32=on
+for word in $(cat /proc/cmdline 2>/dev/null); do
+ case "$word" in
+ ia32_emulation=0 | ia32_emulation=n | ia32_emulation=N | ia32_emulation=no | ia32_emulation=off | ia32_emulation=false) compat32=off ;;
+ ia32_emulation=*) compat32=on ;;
+ esac
+done
+echo "compat32=$compat32"
+
# Only known keys, so a hand-edited file can't hide anything else.
echo "ignored=$(grep -xE 'encryption|apps|devices|secureboot' "$ignored_file" 2>/dev/null | sort -u | paste -sd, -)"
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/Flyout.qml b/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/Flyout.qml
index e26960d..d4aefc1 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/Flyout.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/Flyout.qml
@@ -174,7 +174,10 @@ FocusScope {
return "Check now to see whether any security updates are waiting.";
}
const count = s.warnings.length;
- const lead = count === 0 ? "Nothing needs your attention."
+ // 32-bit apps on is a choice, not a problem, but
+ // the summary should not read as if it weren't there.
+ const lead = count === 0 && s.status.compat32 === "on" ? "32-bit apps are on, by your choice."
+ : count === 0 ? "Nothing needs your attention."
: count === 1 ? "1 thing needs your attention."
: count + " things need your attention.";
// On its own line, so "just now" never wraps alone.
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/main.qml b/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/main.qml
index 42a58f6..e2bb1fa 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/main.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/main.qml
@@ -126,6 +126,11 @@ PlasmoidItem {
row("network", "globe", "Network protection", "Other computers can't connect to this one", "ok", "", "privacy");
}
+ // A choice made in Settings, so it is listed but never a warning.
+ if (s.compat32 === "on") {
+ row("compat32", "chip", "32-bit apps", "On, for Steam and older apps", "quiet", "", "privacy");
+ }
+
// Only worth a row when it could be on and is not; on a BIOS machine
// there is nothing anyone can do about it.
if (s.secureboot === "off") {
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/SearchView.qml b/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/SearchView.qml
index b7f5c9d..9ab4556 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/SearchView.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/SearchView.qml
@@ -135,7 +135,7 @@ FocusScope {
const items = [];
const calc = filter === "all" ? Helpers.calculate(launcher.query) : null;
if (calc) {
- items.push({ header: false, kind: "calc", src: -1, title: calc.value, subtitle: calc.expression, detail: calc.expression + " =", plain: calc.plain });
+ items.push({ header: false, kind: "calc", src: -1, title: calc.value, subtitle: calc.expression, detail: calc.expression + " =", icon: "accessories-calculator", plain: calc.plain });
}
for (let i = 0; i < matches.count; i++) {
const entry = matches.objectAt(i);
@@ -147,7 +147,12 @@ FocusScope {
continue;
}
const text = describe(entry.model, kind);
- items.push({ header: false, kind: kind, src: i, title: text.title, subtitle: text.subtitle, detail: text.detail, plain: "" });
+ // The icon is copied now, not read from the match later: the
+ // runner model resets as results arrive, which replaces every
+ // match object, and a row still holding the old one would fall
+ // back to the generic app icon.
+ const icon = entry.model.decoration || (kind === "folders" ? "folder" : "unknown");
+ items.push({ header: false, kind: kind, src: i, title: text.title, subtitle: text.subtitle, detail: text.detail, icon: icon, plain: "" });
}
const out = [];
@@ -460,7 +465,6 @@ FocusScope {
readonly property bool isHeader: modelData.header
readonly property bool isBest: modelData.best === true
readonly property bool isSelected: search.selected === index
- readonly property var match: search.modelOf(modelData)
width: ListView.view.width
height: isHeader ? (modelData.first ? 18 : 28) : (isBest ? 64 : 50)
@@ -499,9 +503,7 @@ FocusScope {
anchors.verticalCenter: parent.verticalCenter
width: entry.isBest ? 36 : 26
height: width
- source: entry.modelData.kind === "calc" ? "accessories-calculator"
- : entry.match ? (entry.match.model.decoration || (entry.modelData.kind === "folders" ? "folder" : "unknown"))
- : ""
+ source: entry.modelData.icon ?? ""
}
Column {
@@ -578,10 +580,7 @@ FocusScope {
anchors.horizontalCenter: parent.horizontalCenter
width: 72
height: 72
- source: !search.current ? ""
- : search.current.kind === "calc" ? "accessories-calculator"
- : search.modelOf(search.current) ? (search.modelOf(search.current).model.decoration || (search.current.kind === "folders" ? "folder" : "unknown"))
- : ""
+ source: search.current ? search.current.icon : ""
}
UI.Label {
diff --git a/packages/wildos-files/CMakeLists.txt b/packages/wildos-files/CMakeLists.txt
index 97fc3e3..ab6f99b 100644
--- a/packages/wildos-files/CMakeLists.txt
+++ b/packages/wildos-files/CMakeLists.txt
@@ -32,6 +32,8 @@ qt_add_qml_module(wildos-files
src/format.cpp src/format.h
src/settings.cpp src/settings.h
src/drives.cpp src/drives.h
+ src/driveformat.cpp src/driveformat.h
+ src/formatsafety.cpp src/formatsafety.h
src/foldermodel.cpp src/foldermodel.h
src/placesmodel.cpp src/placesmodel.h
src/fileops.cpp src/fileops.h
@@ -54,6 +56,15 @@ target_link_libraries(wildos-files PRIVATE
KF6::Archive KF6::FileMetaData
)
+if(WILDOS_FILES_TESTS)
+ find_package(Qt6 REQUIRED COMPONENTS Test)
+ enable_testing()
+ qt_add_executable(formatsafety-test tests/formatsafety_test.cpp src/formatsafety.cpp)
+ target_include_directories(formatsafety-test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
+ target_link_libraries(formatsafety-test PRIVATE Qt6::Core Qt6::Test)
+ add_test(NAME formatsafety COMMAND formatsafety-test)
+endif()
+
install(TARGETS wildos-files RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
install(FILES data/org.wildos.files.desktop DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)
install(FILES data/org.wildos.Files.service data/org.wildos.files.FileManager1.service DESTINATION ${CMAKE_INSTALL_DATADIR}/dbus-1/services)
diff --git a/packages/wildos-files/debian/changelog b/packages/wildos-files/debian/changelog
index 585d20d..903a83f 100644
--- a/packages/wildos-files/debian/changelog
+++ b/packages/wildos-files/debian/changelog
@@ -1,3 +1,22 @@
+wildos-files (0.1.10) trixie; urgency=medium
+
+ * A USB stick, SD card or external drive with nothing on it, new or
+ left blank by a format that did not finish, shows in Files as needing
+ formatting. Opening it offers to format it.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 13:27:58 +0000
+
+wildos-files (0.1.9) trixie; urgency=medium
+
+ * Format... is in the right-click menu of USB sticks, SD cards and
+ external drives, as in Windows: exFAT, NTFS, FAT32 or ext4, a label,
+ quick or full format, and a password to encrypt the drive if wanted.
+ The drive Wild OS runs from is never offered.
+ * Encrypted USB drives show in Files and ask for their password when
+ opened.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 12:48:01 +0000
+
wildos-files (0.1.8) trixie; urgency=medium
* Renaming in place works like Explorer: the arrow keys move within the
diff --git a/packages/wildos-files/debian/control b/packages/wildos-files/debian/control
index 390b1f9..7b54b13 100644
--- a/packages/wildos-files/debian/control
+++ b/packages/wildos-files/debian/control
@@ -27,8 +27,12 @@ Architecture: any
Depends:
${shlibs:Depends},
${misc:Depends},
+ dosfstools,
+ e2fsprogs,
+ exfatprogs,
fonts-jetbrains-mono,
kio6,
+ ntfs-3g,
qml6-module-qtcore,
qml6-module-qtmultimedia,
qml6-module-qtquick,
@@ -41,6 +45,7 @@ Depends:
qml6-module-qtquick-window,
qt6-image-formats-plugins,
qt6-svg-plugins,
+ udisks2,
wildos-ui,
Recommends:
kio-extras,
diff --git a/packages/wildos-files/debian/rules b/packages/wildos-files/debian/rules
index 393af14..1136b9b 100644
--- a/packages/wildos-files/debian/rules
+++ b/packages/wildos-files/debian/rules
@@ -4,4 +4,7 @@
dh $@
override_dh_auto_configure:
- dh_auto_configure -- -DCMAKE_BUILD_TYPE=Release
+ dh_auto_configure -- -DCMAKE_BUILD_TYPE=Release -DWILDOS_FILES_TESTS=ON
+
+override_dh_auto_test:
+ cd obj-* && ./formatsafety-test
diff --git a/packages/wildos-files/qml/FilesView.qml b/packages/wildos-files/qml/FilesView.qml
index 884b839..40afcd4 100644
--- a/packages/wildos-files/qml/FilesView.qml
+++ b/packages/wildos-files/qml/FilesView.qml
@@ -12,6 +12,8 @@ Item {
id: root
property var startUrls: []
+ // Set when another app asked Files to format a drive.
+ property string formatUdi: ""
// The window's WindowFrame, so maximising goes through it.
property var frame: null
property var tabs: []
@@ -98,6 +100,18 @@ Item {
newTab(url);
}
currentIndex = 0;
+ if (formatUdi.length > 0) {
+ Qt.callLater(() => root.formatDrive(root.formatUdi, ""));
+ }
+ }
+
+ function formatDrive(udi, name) {
+ if (!DriveFormat.canFormat(udi)) {
+ showError("Files only formats removable drives, such as USB sticks and SD cards, and never the drive Wild OS runs from.");
+ return;
+ }
+ // A blank drive is named for what it needs; the dialog says it.
+ formatDialog.show(udi, name.replace(" (needs formatting)", ""));
}
Connections {
@@ -115,6 +129,13 @@ Item {
root.showError(message);
}
}
+ function onNeedsFormat(udi, name) {
+ if (FileOps.activeWindow === root.Window.window) {
+ needsFormatDialog.udi = udi;
+ needsFormatDialog.kind = name.replace(" (needs formatting)", "");
+ needsFormatDialog.open();
+ }
+ }
function onChooseAppRequested(urls) {
if (FileOps.activeWindow === root.Window.window) {
root.chooseApp(urls);
@@ -402,6 +423,10 @@ Item {
entries.push({ text: "Open in new tab", icon: "new-tab", enabled: opened, run: () => root.newTab(driveUrl, false) });
if (udi.length > 0 && f.isRemovableAt(at)) {
entries.push({ text: "Eject", icon: "eject", enabled: opened, run: () => FileOps.ejectDrive(udi) });
+ if (DriveFormat.canFormat(udi)) {
+ const name = f.nameAt(at);
+ entries.push({ text: "Format…", icon: "drive", run: () => root.formatDrive(udi, name) });
+ }
}
entries.push({ separator: true });
entries.push({ text: "Properties", icon: "info", enabled: opened, run: () => root.properties([driveUrl]) });
@@ -545,10 +570,16 @@ Item {
entries.push({ text: "Open in new window", icon: "menu-window", run: () => App.openWindow([place.url]) });
}
entries.push({ text: "Open in new tab", icon: "plus", run: () => sidebar.open(place, true) });
- if (place.removable && hasUrl) {
+ const formattable = place.removable && place.udi.length > 0 && DriveFormat.canFormat(place.udi);
+ if ((place.removable && hasUrl) || formattable) {
entries.push({ separator: true });
+ }
+ if (place.removable && hasUrl) {
entries.push({ text: "Eject", icon: "eject", run: () => FileOps.ejectDrive(place.udi) });
}
+ if (formattable) {
+ entries.push({ text: "Format…", icon: "drive", run: () => root.formatDrive(place.udi, place.name) });
+ }
if (place.kind === "place" || (place.kind === "drive" && hasUrl)) {
entries.push({ separator: true });
entries.push({ text: "Properties", icon: "properties", run: () => root.properties([place.url]) });
@@ -1073,6 +1104,38 @@ Item {
}
}
+ // Opening a blank drive, as Windows asks "You need to format the disk
+ // before you can use it".
+ UI.Dialog {
+ id: needsFormatDialog
+ property string udi
+ property string kind
+ readonly property string lower: /^(USB|SD) /.test(kind) ? kind : kind.charAt(0).toLowerCase() + kind.slice(1)
+ title: "Format this " + lower + "?"
+ text: "This " + lower + " has nothing on it Wild OS can read, so it needs formatting before it can be used. Formatting erases anything on it."
+ onClosed: root.focusContent()
+ buttons: [
+ UI.Button {
+ text: "Cancel"
+ onClicked: needsFormatDialog.close()
+ },
+ UI.Button {
+ kind: "primary"
+ text: "Format…"
+ onClicked: {
+ needsFormatDialog.close();
+ root.formatDrive(needsFormatDialog.udi, needsFormatDialog.kind);
+ }
+ }
+ ]
+ }
+
+ FormatDialog {
+ id: formatDialog
+ onClosed: root.focusContent()
+ onOpenDrive: path => root.folder.openUrl("file://" + path)
+ }
+
ShortcutDialog {
id: shortcutDialog
onClosed: root.focusContent()
diff --git a/packages/wildos-files/qml/FilesWindow.qml b/packages/wildos-files/qml/FilesWindow.qml
index 6de6a18..bfb2b65 100644
--- a/packages/wildos-files/qml/FilesWindow.qml
+++ b/packages/wildos-files/qml/FilesWindow.qml
@@ -10,6 +10,7 @@ UI.AppWindow {
id: window
property var startUrls: []
+ property string formatUdi: ""
width: Settings.windowSize().width
height: Settings.windowSize().height
@@ -29,6 +30,7 @@ UI.AppWindow {
anchors.fill: parent
anchors.margins: window.maximised ? 0 : 1
startUrls: window.startUrls
+ formatUdi: window.formatUdi
frame: window.frame
onCloseWindow: window.close()
}
diff --git a/packages/wildos-files/qml/FormatDialog.qml b/packages/wildos-files/qml/FormatDialog.qml
new file mode 100644
index 0000000..087b04f
--- /dev/null
+++ b/packages/wildos-files/qml/FormatDialog.qml
@@ -0,0 +1,314 @@
+import QtQuick
+import QtQuick.Layouts
+import QtQuick.Templates as T
+import WildOS.Files
+import WildOS.UI as UI
+
+// Format... for a USB stick, SD card or external drive, after Windows 11's
+// Format dialog: a file system (exFAT first, as it works everywhere), the
+// label, Quick format and, beyond Windows, encryption. Then progress, then
+// done or what went wrong, in the same dialog.
+UI.Dialog {
+ id: dialog
+
+ property string udi
+ property string driveName
+ property var info: ({})
+ property string fs: "exfat"
+ // "form", "working", "done" or "failed"
+ property string stage: "form"
+ property string message
+ property string mountPath
+ property bool tried: false
+
+ signal openDrive(string path)
+
+ readonly property bool encrypt: encryptBox.checked
+ readonly property string passwordProblem: !encrypt ? ""
+ : passwordField.text.length < 8 ? "Use at least 8 characters."
+ : passwordField.text !== confirmField.text ? "The passwords don't match."
+ : ""
+ readonly property int labelLimit: fs === "vfat" ? 11 : fs === "exfat" ? 15 : fs === "ntfs" ? 32 : 16
+
+ function sizeText(bytes) {
+ // In the units the drive tiles use (1024-based, as Windows counts),
+ // so the dialog and the tile give the same size.
+ if (!(bytes > 0)) {
+ return "";
+ }
+ const gb = bytes / 1073741824;
+ if (gb >= 1024) {
+ return (gb / 1024).toLocaleString(Qt.locale(), "f", gb >= 10240 ? 0 : 1).replace(/\.0$/, "") + " TB";
+ }
+ if (gb < 1) {
+ return Math.round(bytes / 1048576) + " MB";
+ }
+ return gb.toLocaleString(Qt.locale(), "f", gb < 10 ? 1 : 0).replace(/\.0$/, "") + " GB";
+ }
+
+ function show(target, name) {
+ udi = target;
+ info = DriveFormat.describe(target);
+ driveName = name.length > 0 ? name : info.label && info.label.length > 0 ? info.label : (info.kind ?? "Drive");
+ fs = "exfat";
+ stage = "form";
+ tried = false;
+ message = "";
+ mountPath = "";
+ labelField.text = info.label ?? "";
+ quickBox.checked = true;
+ encryptBox.checked = false;
+ passwordField.text = "";
+ confirmField.text = "";
+ open();
+ startButton.forceActiveFocus();
+ }
+
+ function begin() {
+ tried = true;
+ if (passwordProblem.length > 0) {
+ passwordField.forceActiveFocus();
+ return;
+ }
+ stage = "working";
+ DriveFormat.start(udi, fs, labelField.text, quickBox.checked, encrypt ? passwordField.text : "");
+ }
+
+ Connections {
+ target: DriveFormat
+ enabled: dialog.stage === "working"
+ function onFinished(ok, text, path) {
+ if (ok) {
+ dialog.mountPath = path;
+ dialog.stage = "done";
+ } else if (text.length === 0) {
+ // Cancelled at the password prompt: back to the choices.
+ dialog.stage = "form";
+ } else {
+ dialog.message = text;
+ dialog.stage = "failed";
+ }
+ }
+ }
+
+ title: stage === "working" ? "Formatting " + driveName
+ : stage === "done" ? "Format complete"
+ : stage === "failed" ? "Format didn't finish"
+ : "Format " + driveName
+ text: stage === "working" ? (quickBox.checked ? "This takes a few seconds. Don't unplug the drive."
+ : "Writing over the whole drive. This can take a long time. Don't unplug the drive.")
+ : stage === "done" ? (labelField.text.trim().length > 0 ? labelField.text.trim() : driveName) + " is ready to use."
+ : stage === "failed" ? message
+ : [sizeText(info.size), info.kind].filter(s => s && s.length > 0).join(" ")
+ closePolicy: stage === "working" ? T.Popup.NoAutoClose : T.Popup.CloseOnEscape
+
+ component Hint: UI.Label {
+ Layout.fillWidth: true
+ font.pixelSize: UI.Style.px(12)
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ component Heading: UI.Label {
+ Layout.fillWidth: true
+ Layout.topMargin: 6
+ font.weight: UI.Style.weightMedium
+ }
+
+ component Choice: UI.RadioButton {
+ property string value
+ property bool available: true
+ T.ButtonGroup.group: fileSystems
+ enabled: available
+ checked: dialog.fs === value
+ onToggled: if (checked) dialog.fs = value
+ }
+
+ T.ButtonGroup {
+ id: fileSystems
+ }
+
+ // The choices.
+ ColumnLayout {
+ Layout.fillWidth: true
+ visible: dialog.stage === "form"
+ spacing: 8
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: dialog.info.readOnly === true
+ text: "This drive is write-protected, so it can't be formatted. If it has a lock switch, slide it off and plug it back in."
+ color: UI.Style.danger
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ Heading {
+ Layout.topMargin: 0
+ text: "File system"
+ }
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 22
+ Choice {
+ value: "exfat"
+ text: "exFAT"
+ available: dialog.info.tools?.exfat ?? true
+ }
+ Choice {
+ value: "ntfs"
+ text: "NTFS"
+ available: dialog.info.tools?.ntfs ?? true
+ }
+ Choice {
+ value: "vfat"
+ text: "FAT32"
+ available: (dialog.info.fatAllowed ?? true) && (dialog.info.tools?.vfat ?? true)
+ }
+ Choice {
+ value: "ext4"
+ text: "ext4"
+ available: dialog.info.tools?.ext4 ?? true
+ }
+ }
+ Hint {
+ text: dialog.fs === "exfat" ? "Works on Windows, Mac and Linux. Best for most drives."
+ : dialog.fs === "ntfs" ? "Best for Windows. Macs can open it but can't save to it."
+ : dialog.fs === "vfat" ? "For older cameras, TVs and car stereos. No file can be over 4 GB."
+ : "Linux only."
+ }
+ Hint {
+ visible: dialog.info.fatAllowed === false
+ text: "FAT32 is only for drives up to 32 GB, and this one is bigger."
+ }
+
+ Heading {
+ text: "Volume label"
+ }
+ UI.TextField {
+ id: labelField
+ Layout.fillWidth: true
+ Accessible.name: "Volume label"
+ placeholderText: "A name for the drive"
+ maximumLength: dialog.labelLimit
+ }
+
+ UI.CheckBox {
+ id: quickBox
+ Layout.topMargin: 6
+ text: "Quick format"
+ checked: true
+ }
+ Hint {
+ Layout.leftMargin: 30
+ visible: !quickBox.checked
+ text: "Writes over the whole drive so nothing on it can be recovered. This takes much longer."
+ }
+
+ UI.CheckBox {
+ id: encryptBox
+ visible: dialog.info.canEncrypt === true
+ text: "Encrypt this drive"
+ }
+ Hint {
+ Layout.leftMargin: 30
+ visible: encryptBox.checked
+ text: "You'll need this password to open the drive. Only Linux PCs, like this one, can open it. If you forget the password, nothing on it can be recovered."
+ }
+ UI.TextField {
+ id: passwordField
+ Layout.fillWidth: true
+ Layout.leftMargin: 30
+ visible: encryptBox.checked
+ Accessible.name: "Password"
+ placeholderText: "Password"
+ revealable: true
+ error: dialog.tried && dialog.passwordProblem.length > 0
+ }
+ UI.TextField {
+ id: confirmField
+ Layout.fillWidth: true
+ Layout.leftMargin: 30
+ visible: encryptBox.checked
+ Accessible.name: "Type the password again"
+ placeholderText: "Type the password again"
+ revealable: true
+ error: dialog.tried && dialog.passwordProblem.length > 0
+ }
+ UI.Label {
+ Layout.fillWidth: true
+ Layout.leftMargin: 30
+ visible: encryptBox.checked && dialog.tried && dialog.passwordProblem.length > 0
+ text: dialog.passwordProblem
+ font.pixelSize: UI.Style.px(12)
+ color: UI.Style.danger
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ Layout.topMargin: 8
+ spacing: 10
+ UI.Icon {
+ Layout.alignment: Qt.AlignTop
+ name: "warning"
+ size: 18
+ color: UI.Style.warning
+ }
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Everything on " + dialog.driveName + " will be erased."
+ font.weight: UI.Style.weightMedium
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+ }
+ }
+
+ UI.ProgressBar {
+ Layout.fillWidth: true
+ Layout.topMargin: 4
+ visible: dialog.stage === "working"
+ indeterminate: DriveFormat.progress < 0
+ value: Math.max(0, DriveFormat.progress)
+ }
+ UI.Label {
+ Layout.fillWidth: true
+ visible: dialog.stage === "working" && DriveFormat.progress >= 0
+ text: Math.floor(DriveFormat.progress * 100) + "%"
+ color: UI.Style.inkMuted
+ }
+
+ buttons: [
+ UI.Button {
+ visible: dialog.stage === "form"
+ text: "Cancel"
+ onClicked: dialog.close()
+ },
+ UI.Button {
+ id: startButton
+ visible: dialog.stage === "form"
+ kind: "primary"
+ text: "Start"
+ enabled: dialog.info.ok === true && dialog.info.readOnly !== true
+ onClicked: dialog.begin()
+ },
+ UI.Button {
+ visible: dialog.stage === "done" || dialog.stage === "failed"
+ kind: dialog.stage === "failed" || dialog.mountPath.length === 0 ? "primary" : "secondary"
+ text: "Close"
+ onClicked: dialog.close()
+ },
+ UI.Button {
+ visible: dialog.stage === "done" && dialog.mountPath.length > 0
+ kind: "primary"
+ text: "Open drive"
+ onClicked: {
+ dialog.close();
+ dialog.openDrive(dialog.mountPath);
+ }
+ }
+ ]
+}
diff --git a/packages/wildos-files/src/app.cpp b/packages/wildos-files/src/app.cpp
index c7ed553..67dca3d 100644
--- a/packages/wildos-files/src/app.cpp
+++ b/packages/wildos-files/src/app.cpp
@@ -1,4 +1,6 @@
#include "app.h"
+#include "driveformat.h"
+#include "foldermodel.h"
#include <algorithm>
@@ -118,7 +120,15 @@ void App::Open(const QStringList &urls)
openWindow(toUrls(urls));
}
-void App::openWindow(const QList<QUrl> &urls)
+void App::Format(const QString &device)
+{
+ const QString udi = DriveFormat::objectFor(device);
+ if (!udi.isEmpty()) {
+ openWindow({FolderModel::computerUrl()}, udi);
+ }
+}
+
+void App::openWindow(const QList<QUrl> &urls, const QString &formatUdi)
{
if (!m_engine) {
return;
@@ -130,7 +140,7 @@ void App::openWindow(const QList<QUrl> &urls)
for (const QUrl &url : urls) {
list.append(url);
}
- QObject *object = m_component->createWithInitialProperties({{QStringLiteral("startUrls"), list}});
+ QObject *object = m_component->createWithInitialProperties({{QStringLiteral("startUrls"), list}, {QStringLiteral("formatUdi"), formatUdi}});
if (!object) {
qWarning() << m_component->errors();
return;
diff --git a/packages/wildos-files/src/app.h b/packages/wildos-files/src/app.h
index 0687034..79ad7a9 100644
--- a/packages/wildos-files/src/app.h
+++ b/packages/wildos-files/src/app.h
@@ -25,7 +25,12 @@ public:
public Q_SLOTS:
Q_SCRIPTABLE void Open(const QStringList &urls);
- Q_INVOKABLE void openWindow(const QList<QUrl> &urls);
+ // Opens the Format dialog for a drive, for other apps (Backup offers it
+ // for a drive it can't write to): a device such as /dev/sdb1 or a
+ // UDisks2 block object path. A drive Files would not format gets a
+ // message instead.
+ Q_SCRIPTABLE void Format(const QString &device);
+ Q_INVOKABLE void openWindow(const QList<QUrl> &urls, const QString &formatUdi = QString());
Q_INVOKABLE void newWindow() { openWindow({}); }
private:
diff --git a/packages/wildos-files/src/driveformat.cpp b/packages/wildos-files/src/driveformat.cpp
new file mode 100644
index 0000000..362c5a8
--- /dev/null
+++ b/packages/wildos-files/src/driveformat.cpp
@@ -0,0 +1,564 @@
+#include "driveformat.h"
+#include "drives.h"
+#include "formatsafety.h"
+
+#include <QCoreApplication>
+#include <QDBusArgument>
+#include <QDBusConnection>
+#include <QDBusInterface>
+#include <QDBusMessage>
+#include <QDBusMetaType>
+#include <QDBusObjectPath>
+#include <QDBusReply>
+#include <QFileInfo>
+#include <QPointer>
+#include <QThread>
+
+using InterfaceProps = QMap<QString, QVariantMap>;
+using ManagedObjects = QMap<QDBusObjectPath, InterfaceProps>;
+Q_DECLARE_METATYPE(InterfaceProps)
+Q_DECLARE_METATYPE(ManagedObjects)
+
+namespace
+{
+const QString service = QStringLiteral("org.freedesktop.UDisks2");
+const QString root = QStringLiteral("/org/freedesktop/UDisks2");
+const QString blockPrefix = QStringLiteral("/org/freedesktop/UDisks2/block_devices/");
+const QString blockIface = QStringLiteral("org.freedesktop.UDisks2.Block");
+const QString fsIface = QStringLiteral("org.freedesktop.UDisks2.Filesystem");
+const QString partIface = QStringLiteral("org.freedesktop.UDisks2.Partition");
+const QString tableIface = QStringLiteral("org.freedesktop.UDisks2.PartitionTable");
+const QString cryptIface = QStringLiteral("org.freedesktop.UDisks2.Encrypted");
+const QString driveIface = QStringLiteral("org.freedesktop.UDisks2.Drive");
+const QString jobIface = QStringLiteral("org.freedesktop.UDisks2.Job");
+const QString managerIface = QStringLiteral("org.freedesktop.UDisks2.Manager");
+
+// Writing zeros over a large, slow drive takes hours.
+constexpr int longCall = 12 * 60 * 60 * 1000;
+// FAT32 as Windows offers it: up to 32 GB.
+constexpr qint64 fatLimit = 32LL * 1024 * 1024 * 1024;
+// MBR, which every camera, TV and car stereo reads, ends at 2 TiB.
+constexpr qint64 mbrLimit = 2LL * 1024 * 1024 * 1024 * 1024;
+
+void registerTypes()
+{
+ static bool done = false;
+ if (!done) {
+ qDBusRegisterMetaType<InterfaceProps>();
+ qDBusRegisterMetaType<ManagedObjects>();
+ done = true;
+ }
+}
+
+ManagedObjects managedObjects()
+{
+ registerTypes();
+ QDBusInterface manager(service, root, QStringLiteral("org.freedesktop.DBus.ObjectManager"), QDBusConnection::systemBus());
+ manager.setTimeout(10000);
+ const QDBusReply<ManagedObjects> reply = manager.call(QStringLiteral("GetManagedObjects"));
+ return reply.isValid() ? reply.value() : ManagedObjects();
+}
+
+QString bytes(const QVariant &v)
+{
+ return QString::fromUtf8(v.toByteArray().constData());
+}
+
+QString path(const QVariant &v)
+{
+ const QString p = v.value<QDBusObjectPath>().path();
+ return p == QLatin1String("/") ? QString() : p;
+}
+
+QStringList paths(const QVariant &v)
+{
+ QStringList out;
+ if (v.canConvert<QDBusArgument>()) {
+ const QDBusArgument arg = v.value<QDBusArgument>();
+ arg.beginArray();
+ while (!arg.atEnd()) {
+ QDBusObjectPath p;
+ arg >> p;
+ out << p.path();
+ }
+ arg.endArray();
+ } else {
+ for (const QDBusObjectPath &p : v.value<QList<QDBusObjectPath>>()) {
+ out << p.path();
+ }
+ }
+ return out;
+}
+
+bool mounted(const InterfaceProps &ifaces)
+{
+ const QVariant v = ifaces.value(fsIface).value(QStringLiteral("MountPoints"));
+ if (!v.canConvert<QDBusArgument>()) {
+ return false;
+ }
+ const QDBusArgument arg = v.value<QDBusArgument>();
+ arg.beginArray();
+ const bool any = !arg.atEnd();
+ while (!arg.atEnd()) {
+ QByteArray b;
+ arg >> b;
+ }
+ arg.endArray();
+ return any;
+}
+
+// The block to format: the LUKS container when given what it unlocks to.
+QString formatTarget(const ManagedObjects &objects, const QString &object)
+{
+ const InterfaceProps ifaces = objects.value(QDBusObjectPath(object));
+ const QString backing = path(ifaces.value(blockIface).value(QStringLiteral("CryptoBackingDevice")));
+ return backing.isEmpty() ? object : backing;
+}
+
+bool removableDrive(const QVariantMap &drive)
+{
+ const QString bus = drive.value(QStringLiteral("ConnectionBus")).toString();
+ return drive.value(QStringLiteral("Removable")).toBool() || drive.value(QStringLiteral("MediaRemovable")).toBool()
+ || bus == QLatin1String("usb") || bus == QLatin1String("sdio") || bus == QLatin1String("ieee1394");
+}
+
+bool allowed(const ManagedObjects &objects, const QString &object)
+{
+ const InterfaceProps ifaces = objects.value(QDBusObjectPath(object));
+ if (!ifaces.contains(blockIface)) {
+ return false;
+ }
+ const QVariantMap block = ifaces.value(blockIface);
+ const QVariantMap drive = objects.value(QDBusObjectPath(path(block.value(QStringLiteral("Drive"))))).value(driveIface);
+ if (drive.isEmpty()) {
+ return false;
+ }
+ FormatSafety::Facts facts;
+ facts.blockName = QFileInfo(bytes(block.value(QStringLiteral("Device")))).fileName();
+ facts.removable = removableDrive(drive);
+ facts.optical = drive.value(QStringLiteral("Optical")).toBool()
+ || drive.value(QStringLiteral("MediaCompatibility")).toStringList().join(QLatin1Char(',')).contains(QLatin1String("optical"));
+ return FormatSafety::canFormat(QString(), facts);
+}
+
+QString kindOf(const QVariantMap &drive)
+{
+ const QString bus = drive.value(QStringLiteral("ConnectionBus")).toString();
+ if (bus == QLatin1String("sdio") || drive.value(QStringLiteral("Media")).toString().startsWith(QLatin1String("flash_sd"))) {
+ return QStringLiteral("SD card");
+ }
+ if (drive.value(QStringLiteral("Size")).toLongLong() > 0 && drive.value(QStringLiteral("RotationRate")).toInt() > 0) {
+ return QStringLiteral("external drive");
+ }
+ return bus == QLatin1String("usb") ? QStringLiteral("USB drive") : QStringLiteral("external drive");
+}
+
+// Labels as each file system stores them: FAT keeps 11 upper-case
+// characters and refuses some punctuation, as Windows does.
+QString cleanLabel(const QString &fs, QString label)
+{
+ label = label.trimmed();
+ if (fs == QLatin1String("vfat")) {
+ static const QString banned = QStringLiteral("*?.,;:/\\|+=<>[]\"");
+ QString out;
+ for (const QChar c : std::as_const(label)) {
+ if (!banned.contains(c) && c.unicode() < 128) {
+ out += c.toUpper();
+ }
+ }
+ return out.left(11);
+ }
+ if (fs == QLatin1String("exfat")) {
+ return label.left(15);
+ }
+ if (fs == QLatin1String("ntfs")) {
+ return label.left(32);
+ }
+ // ext4 allows 16 bytes.
+ QByteArray utf8 = label.toUtf8();
+ while (utf8.size() > 16) {
+ label.chop(1);
+ utf8 = label.toUtf8();
+ }
+ return label;
+}
+
+QString plainError(const QDBusError &error)
+{
+ const QString name = error.name();
+ const QString text = error.message();
+ qWarning() << "Format:" << name << text;
+ if (name.endsWith(QLatin1String("NotAuthorizedDismissed")) || name.endsWith(QLatin1String("Cancelled"))) {
+ return QString();
+ }
+ if (name.contains(QLatin1String("NotAuthorized"))) {
+ return QStringLiteral("Formatting this drive needs an administrator's permission, and it wasn't given.");
+ }
+ if (name.endsWith(QLatin1String("DeviceBusy")) || text.contains(QLatin1String("busy"), Qt::CaseInsensitive)) {
+ return QStringLiteral("The drive is in use. Close any files or apps using it, then try again.");
+ }
+ if (name == QLatin1String("org.freedesktop.DBus.Error.ServiceUnknown")) {
+ return QStringLiteral("Files can't reach the disk service, so it can't format drives right now. Restart the PC and try again.");
+ }
+ if (name == QLatin1String("org.freedesktop.DBus.Error.UnknownObject") || text.contains(QLatin1String("No such"), Qt::CaseInsensitive)) {
+ return QStringLiteral("The drive was unplugged before formatting finished. Plug it back in and format it again.");
+ }
+ if (text.contains(QLatin1String("read-only"), Qt::CaseInsensitive) || text.contains(QLatin1String("write-protect"), Qt::CaseInsensitive)) {
+ return QStringLiteral("The drive is write-protected. If it has a lock switch, slide it off, plug it back in and try again.");
+ }
+ return QStringLiteral("The drive couldn't be formatted. It may be faulty or not plugged in firmly. Try another USB port, then format it again.");
+}
+
+struct Outcome {
+ bool ok = false;
+ QString message;
+ QString mountPath;
+};
+
+struct Request {
+ QString object;
+ QString fs;
+ QString label;
+ bool quick = true;
+ QString password;
+};
+
+QDBusMessage call(const QString &object, const QString &iface, const QString &method, const QVariantList &args, int timeout = 120000)
+{
+ QDBusMessage message = QDBusMessage::createMethodCall(service, object, iface, method);
+ message.setArguments(args);
+ message.setInteractiveAuthorizationAllowed(true);
+ return QDBusConnection::systemBus().call(message, QDBus::Block, timeout);
+}
+
+Outcome failure(const QDBusMessage &reply)
+{
+ return {false, plainError(QDBusError(reply)), {}};
+}
+
+Outcome run(const Request &request)
+{
+ ManagedObjects objects = managedObjects();
+ if (objects.isEmpty()) {
+ return {false, plainError(QDBusError(QDBusError::ServiceUnknown, QString())), {}};
+ }
+ const QString target = formatTarget(objects, request.object);
+ if (!objects.contains(QDBusObjectPath(target))) {
+ return {false, QStringLiteral("The drive isn't plugged in any more."), {}};
+ }
+ if (!allowed(objects, target)) {
+ return {false, QStringLiteral("Files only formats removable drives, never the one Wild OS runs from."), {}};
+ }
+ const InterfaceProps targetIfaces = objects.value(QDBusObjectPath(target));
+ const QVariantMap block = targetIfaces.value(blockIface);
+ const QString drive = path(block.value(QStringLiteral("Drive")));
+ const bool wholeDisk = !targetIfaces.contains(partIface);
+
+ // Everything that has to let go first: the volume, or for a whole disk
+ // every partition on it, and what any unlocked container holds.
+ QStringList blocks;
+ for (auto it = objects.cbegin(); it != objects.cend(); ++it) {
+ const QVariantMap b = it.value().value(blockIface);
+ if (it.key().path() == target || (wholeDisk && path(b.value(QStringLiteral("Drive"))) == drive)) {
+ blocks << it.key().path();
+ }
+ }
+ QStringList cleartexts;
+ for (auto it = objects.cbegin(); it != objects.cend(); ++it) {
+ if (blocks.contains(path(it.value().value(blockIface).value(QStringLiteral("CryptoBackingDevice"))))) {
+ cleartexts << it.key().path();
+ }
+ }
+ const QVariantMap none;
+ for (const QString &object : cleartexts + blocks) {
+ if (mounted(objects.value(QDBusObjectPath(object)))) {
+ const QDBusMessage reply = call(object, fsIface, QStringLiteral("Unmount"), {none});
+ if (reply.type() == QDBusMessage::ErrorMessage) {
+ return failure(reply);
+ }
+ }
+ }
+ for (const QString &object : std::as_const(blocks)) {
+ const InterfaceProps ifaces = objects.value(QDBusObjectPath(object));
+ if (ifaces.contains(cryptIface) && !path(ifaces.value(cryptIface).value(QStringLiteral("CleartextDevice"))).isEmpty()) {
+ const QDBusMessage reply = call(object, cryptIface, QStringLiteral("Lock"), {none});
+ if (reply.type() == QDBusMessage::ErrorMessage) {
+ return failure(reply);
+ }
+ }
+ }
+
+ QVariantMap options;
+ const QString label = cleanLabel(request.fs, request.label);
+ if (!label.isEmpty()) {
+ options.insert(QStringLiteral("label"), label);
+ }
+ if (!request.quick) {
+ options.insert(QStringLiteral("erase"), QStringLiteral("zero"));
+ }
+ if (!request.password.isEmpty()) {
+ options.insert(QStringLiteral("encrypt.passphrase"), request.password);
+ options.insert(QStringLiteral("encrypt.type"), QStringLiteral("luks2"));
+ }
+ if (request.fs == QLatin1String("ext4")) {
+ // A new ext4 belongs to root; this hands it to the person.
+ options.insert(QStringLiteral("take-ownership"), true);
+ }
+
+ QString formatted = target;
+ if (wholeDisk) {
+ const qint64 size = block.value(QStringLiteral("Size")).toLongLong();
+ const bool gpt = size > mbrLimit;
+ QDBusMessage reply = call(target, blockIface, QStringLiteral("Format"), {gpt ? QStringLiteral("gpt") : QStringLiteral("dos"), none}, longCall);
+ if (reply.type() == QDBusMessage::ErrorMessage) {
+ return failure(reply);
+ }
+ const bool linuxOnly = request.fs == QLatin1String("ext4") || !request.password.isEmpty();
+ QString type;
+ if (gpt) {
+ type = linuxOnly ? QStringLiteral("0fc63daf-8483-4772-8e79-3d69d8477de4") : QStringLiteral("ebd0a0a2-b9e5-4433-87c0-68b6b72699c7");
+ } else {
+ type = linuxOnly ? QStringLiteral("0x83") : request.fs == QLatin1String("vfat") ? QStringLiteral("0x0c") : QStringLiteral("0x07");
+ }
+ reply = call(target, tableIface, QStringLiteral("CreatePartitionAndFormat"),
+ {QVariant::fromValue<qulonglong>(0), QVariant::fromValue<qulonglong>(0), type, QString(), none, request.fs, options}, longCall);
+ if (reply.type() == QDBusMessage::ErrorMessage) {
+ return failure(reply);
+ }
+ formatted = reply.arguments().value(0).value<QDBusObjectPath>().path();
+ } else {
+ options.insert(QStringLiteral("update-partition-type"), true);
+ const QDBusMessage reply = call(target, blockIface, QStringLiteral("Format"), {request.fs, options}, longCall);
+ if (reply.type() == QDBusMessage::ErrorMessage) {
+ return failure(reply);
+ }
+ }
+
+ // Open it again, as Windows leaves a formatted drive ready to use. An
+ // encrypted drive is left unlocked by the format; its file system is
+ // inside. UDisks can take a moment to notice the new file system.
+ Outcome outcome{true, {}, {}};
+ for (int attempt = 0; attempt < 20; ++attempt) {
+ objects = managedObjects();
+ QString fs = formatted;
+ const InterfaceProps ifaces = objects.value(QDBusObjectPath(formatted));
+ if (ifaces.contains(cryptIface)) {
+ fs = path(ifaces.value(cryptIface).value(QStringLiteral("CleartextDevice")));
+ }
+ if (!fs.isEmpty() && objects.value(QDBusObjectPath(fs)).contains(fsIface)) {
+ const QDBusMessage reply = call(fs, fsIface, QStringLiteral("Mount"), {none});
+ if (reply.type() == QDBusMessage::ReplyMessage) {
+ outcome.mountPath = reply.arguments().value(0).toString();
+ } else {
+ qWarning() << "Format: mounting afterwards:" << reply.errorMessage();
+ }
+ break;
+ }
+ QThread::msleep(250);
+ }
+ return outcome;
+}
+}
+
+DriveFormat *DriveFormat::instance()
+{
+ static DriveFormat *format = new DriveFormat;
+ return format;
+}
+
+DriveFormat *DriveFormat::create(QQmlEngine *, QJSEngine *)
+{
+ auto format = instance();
+ QJSEngine::setObjectOwnership(format, QJSEngine::CppOwnership);
+ return format;
+}
+
+DriveFormat::DriveFormat(QObject *parent)
+ : QObject(parent)
+{
+ m_poll.setInterval(700);
+ connect(&m_poll, &QTimer::timeout, this, &DriveFormat::poll);
+}
+
+QList<DriveFormat::Blank> DriveFormat::blankDrives()
+{
+ QList<Blank> out;
+ const ManagedObjects objects = managedObjects();
+ const QString formatting = instance()->m_busy ? instance()->m_drive : QString();
+ for (auto it = objects.cbegin(); it != objects.cend(); ++it) {
+ const QVariantMap drive = it.value().value(driveIface);
+ const QString drivePath = it.key().path();
+ if (drive.isEmpty() || drivePath == formatting || !removableDrive(drive)) {
+ continue;
+ }
+ if (drive.value(QStringLiteral("MediaRemovable")).toBool() && !drive.value(QStringLiteral("MediaAvailable")).toBool()) {
+ continue;
+ }
+ QString whole;
+ qint64 size = 0;
+ bool empty = true;
+ for (auto b = objects.cbegin(); b != objects.cend() && empty; ++b) {
+ const QVariantMap block = b.value().value(blockIface);
+ if (block.isEmpty() || path(block.value(QStringLiteral("Drive"))) != drivePath) {
+ continue;
+ }
+ if (!block.value(QStringLiteral("IdUsage")).toString().isEmpty() || b.value().contains(fsIface) || b.value().contains(cryptIface)) {
+ empty = false;
+ }
+ if (!b.value().contains(partIface)) {
+ whole = b.key().path();
+ size = block.value(QStringLiteral("Size")).toLongLong();
+ }
+ }
+ if (!empty || whole.isEmpty() || size <= 0 || !allowed(objects, whole)) {
+ continue;
+ }
+ out.append({whole, kindOf(drive), size});
+ }
+ return out;
+}
+
+QString DriveFormat::objectFor(const QString &device)
+{
+ if (device.startsWith(blockPrefix)) {
+ return device;
+ }
+ const QString real = QFileInfo(device).canonicalFilePath();
+ const QString name = QFileInfo(real.isEmpty() ? device : real).fileName();
+ return name.isEmpty() ? QString() : blockPrefix + name;
+}
+
+bool DriveFormat::canFormat(const QString &udi) const
+{
+ if (!udi.startsWith(blockPrefix)) {
+ return false;
+ }
+ const ManagedObjects objects = managedObjects();
+ return allowed(objects, formatTarget(objects, udi));
+}
+
+QVariantMap DriveFormat::describe(const QString &udi) const
+{
+ const ManagedObjects objects = managedObjects();
+ const QString target = formatTarget(objects, udi);
+ const InterfaceProps ifaces = objects.value(QDBusObjectPath(target));
+ const QVariantMap block = ifaces.value(blockIface);
+ const QVariantMap drive = objects.value(QDBusObjectPath(path(block.value(QStringLiteral("Drive"))))).value(driveIface);
+ QVariantMap out;
+ if (block.isEmpty() || !allowed(objects, target)) {
+ out.insert(QStringLiteral("ok"), false);
+ return out;
+ }
+ // The label people know is the file system's, which for an unlocked
+ // encrypted drive is inside the container.
+ QString label = block.value(QStringLiteral("IdLabel")).toString();
+ if (ifaces.contains(cryptIface)) {
+ const QString inside = path(ifaces.value(cryptIface).value(QStringLiteral("CleartextDevice")));
+ if (!inside.isEmpty()) {
+ label = objects.value(QDBusObjectPath(inside)).value(blockIface).value(QStringLiteral("IdLabel")).toString();
+ }
+ }
+ // Asked for a whole disk (/dev/sdb), the label is its partition's.
+ if (label.trimmed().isEmpty() && !ifaces.contains(partIface)) {
+ for (auto it = objects.cbegin(); it != objects.cend() && label.trimmed().isEmpty(); ++it) {
+ if (path(it.value().value(partIface).value(QStringLiteral("Table"))) == target) {
+ label = it.value().value(blockIface).value(QStringLiteral("IdLabel")).toString();
+ }
+ }
+ }
+ const qint64 size = block.value(QStringLiteral("Size")).toLongLong();
+ out.insert(QStringLiteral("ok"), true);
+ out.insert(QStringLiteral("label"), label.trimmed());
+ out.insert(QStringLiteral("size"), double(size));
+ out.insert(QStringLiteral("kind"), kindOf(drive));
+ out.insert(QStringLiteral("readOnly"), block.value(QStringLiteral("ReadOnly")).toBool());
+ out.insert(QStringLiteral("fatAllowed"), size <= fatLimit);
+ out.insert(QStringLiteral("encrypted"), ifaces.contains(cryptIface));
+
+ QDBusInterface manager(service, root + QStringLiteral("/Manager"), managerIface, QDBusConnection::systemBus());
+ QVariantMap tools;
+ for (const QString &fs : {QStringLiteral("exfat"), QStringLiteral("ntfs"), QStringLiteral("vfat"), QStringLiteral("ext4")}) {
+ const QDBusMessage reply = manager.call(QStringLiteral("CanFormat"), fs);
+ bool available = true;
+ if (reply.type() == QDBusMessage::ReplyMessage) {
+ const QDBusArgument arg = reply.arguments().value(0).value<QDBusArgument>();
+ QString missing;
+ arg.beginStructure();
+ arg >> available >> missing;
+ arg.endStructure();
+ }
+ tools.insert(fs, available);
+ }
+ out.insert(QStringLiteral("tools"), tools);
+ const QStringList crypt = manager.property("SupportedEncryptionTypes").toStringList();
+ out.insert(QStringLiteral("canEncrypt"), crypt.contains(QStringLiteral("luks2")));
+ return out;
+}
+
+void DriveFormat::start(const QString &udi, const QString &fs, const QString &label, bool quick, const QString &password)
+{
+ static const QStringList known = {QStringLiteral("exfat"), QStringLiteral("ntfs"), QStringLiteral("vfat"), QStringLiteral("ext4")};
+ if (m_busy || !known.contains(fs)) {
+ return;
+ }
+ Request request{udi, fs, label, quick, password};
+ {
+ const ManagedObjects objects = managedObjects();
+ const QVariantMap block = objects.value(QDBusObjectPath(formatTarget(objects, udi))).value(blockIface);
+ m_drive = path(block.value(QStringLiteral("Drive")));
+ }
+ m_busy = true;
+ m_progress = -1;
+ Q_EMIT busyChanged();
+ Q_EMIT progressChanged();
+ m_poll.start();
+
+ QPointer<DriveFormat> guard(this);
+ QThread *thread = QThread::create([guard, request] {
+ const Outcome outcome = run(request);
+ QMetaObject::invokeMethod(QCoreApplication::instance(), [guard, outcome] {
+ if (!guard) {
+ return;
+ }
+ guard->m_poll.stop();
+ guard->m_busy = false;
+ Q_EMIT guard->busyChanged();
+ // A format that failed half way can leave the drive blank, which
+ // no device event announces.
+ Q_EMIT Drives::instance()->changed();
+ Q_EMIT guard->finished(outcome.ok, outcome.message, outcome.mountPath);
+ }, Qt::QueuedConnection);
+ });
+ connect(thread, &QThread::finished, thread, &QObject::deleteLater);
+ thread->start();
+}
+
+void DriveFormat::poll()
+{
+ // A full format's zeroing runs as a UDisks job on one of the drive's
+ // blocks, with its own progress.
+ const ManagedObjects objects = managedObjects();
+ QStringList blocks;
+ for (auto it = objects.cbegin(); it != objects.cend(); ++it) {
+ const QVariantMap b = it.value().value(blockIface);
+ if (!b.isEmpty() && path(b.value(QStringLiteral("Drive"))) == m_drive) {
+ blocks << it.key().path();
+ }
+ }
+ double progress = -1;
+ for (auto it = objects.cbegin(); it != objects.cend(); ++it) {
+ const QVariantMap job = it.value().value(jobIface);
+ if (job.isEmpty() || !job.value(QStringLiteral("ProgressValid")).toBool()) {
+ continue;
+ }
+ for (const QString &object : paths(job.value(QStringLiteral("Objects")))) {
+ if (blocks.contains(object)) {
+ progress = std::max(progress, job.value(QStringLiteral("Progress")).toDouble());
+ }
+ }
+ }
+ if (progress != m_progress) {
+ m_progress = progress;
+ Q_EMIT progressChanged();
+ }
+}
diff --git a/packages/wildos-files/src/driveformat.h b/packages/wildos-files/src/driveformat.h
new file mode 100644
index 0000000..d511230
--- /dev/null
+++ b/packages/wildos-files/src/driveformat.h
@@ -0,0 +1,71 @@
+#pragma once
+
+#include <QObject>
+#include <QQmlEngine>
+#include <QTimer>
+#include <QVariantMap>
+
+// Formatting a removable drive, as Format... in File Explorer: unmount it,
+// give it a file system through UDisks2 (polkit decides who may), then
+// mount it again. A drive whose file system sits straight on the whole
+// disk, or which has none, gets one partition first.
+class DriveFormat : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(bool busy READ busy NOTIFY busyChanged)
+ // 0 to 1 while a full format writes over the drive, -1 when there is no
+ // way to tell.
+ Q_PROPERTY(double progress READ progress NOTIFY progressChanged)
+
+public:
+ static DriveFormat *instance();
+ static DriveFormat *create(QQmlEngine *, QJSEngine *);
+
+ bool busy() const { return m_busy; }
+ double progress() const { return m_progress; }
+
+ // Whether Format... is offered: a removable or hot-plugged drive that
+ // holds nothing of the running system. `udi` is Solid's, which for
+ // UDisks2 drives is the block device's object path.
+ Q_INVOKABLE bool canFormat(const QString &udi) const;
+ // What the dialog shows: label, size, kind, readOnly, fatAllowed,
+ // encryption and the file systems this PC has the tools for.
+ Q_INVOKABLE QVariantMap describe(const QString &udi) const;
+ // fs is "exfat", "ntfs", "vfat" or "ext4". An empty password means no
+ // encryption.
+ Q_INVOKABLE void start(const QString &udi, const QString &fs, const QString &label, bool quick, const QString &password);
+
+ // /dev/sdb1, /dev/sdb or a UDisks2 object path to the object path, for
+ // apps that ask Files to format a drive.
+ static QString objectFor(const QString &device);
+
+ struct Blank {
+ QString udi; // the whole disk's UDisks2 object path
+ QString kind; // "USB drive", "SD card", "external drive"
+ qint64 size = 0;
+ };
+ // Removable drives with nothing on them Wild OS can read: no file
+ // system, no encryption, not even a partition with something in it.
+ // A new stick, or one a format left half done. Only drives Files may
+ // format; a drive being formatted right now is left out.
+ static QList<Blank> blankDrives();
+
+Q_SIGNALS:
+ void busyChanged();
+ void progressChanged();
+ // ok false with an empty message means the person cancelled at the
+ // password prompt.
+ void finished(bool ok, const QString &message, const QString &mountPath);
+
+private:
+ explicit DriveFormat(QObject *parent = nullptr);
+ void poll();
+
+ bool m_busy = false;
+ double m_progress = -1;
+ QString m_drive;
+ QTimer m_poll;
+};
diff --git a/packages/wildos-files/src/drives.cpp b/packages/wildos-files/src/drives.cpp
index 4e02b7c..372a0b4 100644
--- a/packages/wildos-files/src/drives.cpp
+++ b/packages/wildos-files/src/drives.cpp
@@ -1,4 +1,5 @@
#include "drives.h"
+#include "driveformat.h"
#include <QLocale>
#include <QDir>
@@ -58,6 +59,16 @@ bool rootEncrypted()
return onLuks(QFileInfo(QFileInfo(device).canonicalFilePath()).fileName());
}
+bool removableDevice(const Solid::Device &device)
+{
+ for (Solid::Device parent = device.parent(); device.isValid() && parent.isValid(); parent = parent.parent()) {
+ if (auto storage = parent.as<Solid::StorageDrive>()) {
+ return storage->isRemovable() || storage->isHotpluggable();
+ }
+ }
+ return false;
+}
+
bool isNtfs(const QString &fsType)
{
return fsType == QLatin1String("ntfs") || fsType == QLatin1String("ntfs3") || fsType == QLatin1String("ntfs-3g");
@@ -159,7 +170,15 @@ QList<Drive> Drives::scan() const
if (!access || (access->isAccessible() && access->isIgnored())) {
continue;
}
- if (volume && (volume->isIgnored() || volume->usage() != Solid::StorageVolume::FileSystem)) {
+ const bool removable = removableDevice(device);
+ // An encrypted USB stick shows as itself, locked or not: opening it
+ // asks for its password, and once open the file system inside is
+ // not listed a second time.
+ const bool encrypted = volume && volume->usage() == Solid::StorageVolume::Encrypted;
+ if (volume && (volume->isIgnored() || (volume->usage() != Solid::StorageVolume::FileSystem && !(encrypted && removable)))) {
+ continue;
+ }
+ if (volume && !encrypted && removableDevice(volume->encryptedContainer())) {
continue;
}
if (block && block->device().startsWith(QStringLiteral("/dev/loop"))) {
@@ -179,14 +198,7 @@ QList<Drive> Drives::scan() const
drive.mounted = access->isAccessible();
drive.mountPath = drive.mounted ? path : QString();
- bool removable = false;
const bool optical = device.is<Solid::OpticalDisc>();
- for (Solid::Device parent = device.parent(); parent.isValid(); parent = parent.parent()) {
- if (auto storage = parent.as<Solid::StorageDrive>()) {
- removable = storage->isRemovable() || storage->isHotpluggable();
- break;
- }
- }
drive.removable = removable || optical;
// Windows keeps its recovery tools on a small NTFS partition it
// never shows; neither does Files.
@@ -194,8 +206,17 @@ QList<Drive> Drives::scan() const
continue;
}
const bool windowsSystem = ntfs && drive.mounted && QFileInfo::exists(drive.mountPath + QStringLiteral("/Windows/System32"));
- drive.chip = drive.removable ? QStringLiteral("Removable") : ntfs ? QStringLiteral("Windows") : QString();
- const QString label = volume ? volume->label().trimmed() : QString();
+ drive.chip = encrypted ? QStringLiteral("Encrypted") : drive.removable ? QStringLiteral("Removable") : ntfs ? QStringLiteral("Windows") : QString();
+ QString label = volume ? volume->label().trimmed() : QString();
+ if (encrypted && label.isEmpty()) {
+ for (const Solid::Device &inner : devices) {
+ auto innerVolume = inner.as<Solid::StorageVolume>();
+ if (innerVolume && innerVolume->encryptedContainer().udi() == device.udi()) {
+ label = innerVolume->label().trimmed();
+ break;
+ }
+ }
+ }
drive.total = volume ? qint64(volume->size()) : 0;
if (drive.mounted) {
const QStorageInfo info(drive.mountPath);
@@ -222,6 +243,19 @@ QList<Drive> Drives::scan() const
drives.append(drive);
}
+ for (const DriveFormat::Blank &blank : DriveFormat::blankDrives()) {
+ Drive drive;
+ drive.udi = blank.udi;
+ drive.blank = true;
+ drive.removable = true;
+ drive.total = blank.size;
+ drive.name = blank.kind.left(1).toUpper() + blank.kind.mid(1) + QStringLiteral(" (needs formatting)");
+ drive.chip = QStringLiteral("Removable");
+ drive.themeIcon = QStringLiteral("drive-removable-media-usb");
+ drive.lineIcon = QStringLiteral("usb");
+ drives.append(drive);
+ }
+
// The design rig has no udisks to report a Windows partition or a USB
// stick: WILDOS_FILES_RIG_DRIVES="name|chip|removable|total|free|path;..."
// adds drives as the code above would have named them.
@@ -267,6 +301,12 @@ Drive Drives::driveFor(const QString &path) const
void Drives::mount(const QString &udi)
{
+ for (const Drive &drive : list()) {
+ if (drive.udi == udi && drive.blank) {
+ Q_EMIT needsFormat(udi, drive.name);
+ return;
+ }
+ }
Solid::Device device(udi);
auto access = device.as<Solid::StorageAccess>();
if (!access) {
diff --git a/packages/wildos-files/src/drives.h b/packages/wildos-files/src/drives.h
index c411c29..9cd9d23 100644
--- a/packages/wildos-files/src/drives.h
+++ b/packages/wildos-files/src/drives.h
@@ -11,11 +11,14 @@ struct Drive {
QString lineIcon;
QString mountPath;
// What kind of drive it is, as a chip on its card: "Encrypted" for a
- // Wild OS disk behind LUKS, "Windows" for NTFS, "Removable".
+ // Wild OS disk or a USB stick behind LUKS, "Windows" for NTFS,
+ // "Removable".
QString chip;
bool mounted = false;
bool removable = false;
bool system = false;
+ // Plugged in but with nothing readable on it: it can only be formatted.
+ bool blank = false;
qint64 total = 0;
qint64 free = -1;
};
@@ -43,6 +46,8 @@ Q_SIGNALS:
void changed();
void mounted(const QString &udi, const QString &path);
void failed(const QString &message);
+ // Opening a blank drive: Files offers to format it, as Windows does.
+ void needsFormat(const QString &udi, const QString &name);
private:
explicit Drives(QObject *parent = nullptr);
diff --git a/packages/wildos-files/src/fileops.cpp b/packages/wildos-files/src/fileops.cpp
index fc2d1eb..4aa3bf2 100644
--- a/packages/wildos-files/src/fileops.cpp
+++ b/packages/wildos-files/src/fileops.cpp
@@ -447,6 +447,7 @@ FileOps::FileOps(QObject *parent)
connect(m_sharer, &Sharer::finished, this, &FileOps::notice);
connect(m_sharer, &Sharer::failed, this, &FileOps::failed);
connect(Drives::instance(), &Drives::failed, this, &FileOps::failed);
+ connect(Drives::instance(), &Drives::needsFormat, this, &FileOps::needsFormat);
// A quiet listing of the Recycle Bin keeps its icon and Empty Bin current.
m_bin->setAutoErrorHandlingEnabled(false);
diff --git a/packages/wildos-files/src/fileops.h b/packages/wildos-files/src/fileops.h
index a3532ed..15febef 100644
--- a/packages/wildos-files/src/fileops.h
+++ b/packages/wildos-files/src/fileops.h
@@ -158,6 +158,7 @@ Q_SIGNALS:
void activeWindowChanged();
void failed(const QString &message);
void notice(const QString &message);
+ void needsFormat(const QString &udi, const QString &name);
// Items that just appeared in a folder because of the user, to select
// (and with rename, to start renaming) once they are listed.
void created(const QUrl &folder, const QList<QUrl> &urls, bool rename);
diff --git a/packages/wildos-files/src/foldermodel.cpp b/packages/wildos-files/src/foldermodel.cpp
index 8ee06a2..806dd4c 100644
--- a/packages/wildos-files/src/foldermodel.cpp
+++ b/packages/wildos-files/src/foldermodel.cpp
@@ -840,7 +840,9 @@ QList<FolderModel::Entry> FolderModel::driveEntries() const
e.col2Key = 0;
e.sizeKey = drive.total;
e.sizeText = drive.total > 0 ? Format::size(drive.total) : QString();
- if (drive.free >= 0 && drive.total > 0) {
+ if (drive.blank) {
+ e.subtitle = Format::size(drive.total) + QStringLiteral(", needs formatting before it can be used");
+ } else if (drive.free >= 0 && drive.total > 0) {
e.subtitle = Format::size(drive.free) + QStringLiteral(" free of ") + Format::size(drive.total);
if (drive.removable) {
e.subtitle += QStringLiteral(", remove safely before unplugging");
diff --git a/packages/wildos-files/src/formatsafety.cpp b/packages/wildos-files/src/formatsafety.cpp
new file mode 100644
index 0000000..25c6ec8
--- /dev/null
+++ b/packages/wildos-files/src/formatsafety.cpp
@@ -0,0 +1,164 @@
+#include "formatsafety.h"
+
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+
+namespace
+{
+QString blockDir(const QString &root, const QString &name)
+{
+ return root + QStringLiteral("/sys/class/block/") + name;
+}
+
+void collect(const QString &root, const QString &name, QStringList &out, int depth)
+{
+ if (depth > 8 || name.isEmpty()) {
+ return;
+ }
+ const QString dir = blockDir(root, name);
+ // A device mapper target (LUKS, LVM) names what it sits on in slaves/.
+ const QStringList slaves = QDir(dir + QStringLiteral("/slaves")).entryList(QDir::Dirs | QDir::NoDotAndDotDot);
+ if (!slaves.isEmpty()) {
+ for (const QString &slave : slaves) {
+ collect(root, slave, out, depth + 1);
+ }
+ return;
+ }
+ // A partition's sysfs directory sits inside its disk's.
+ if (QFileInfo::exists(dir + QStringLiteral("/partition"))) {
+ const QString disk = QFileInfo(QFileInfo(dir).canonicalFilePath()).dir().dirName();
+ if (!disk.isEmpty() && !out.contains(disk)) {
+ out.append(disk);
+ }
+ return;
+ }
+ if (!out.contains(name)) {
+ out.append(name);
+ }
+}
+
+// /dev/sda2, /dev/mapper/luks-... or /dev/disk/by-uuid/... to "sda2" or
+// "dm-0", the names /sys uses.
+QString sysName(const QString &root, const QString &device)
+{
+ if (!device.startsWith(QStringLiteral("/dev/"))) {
+ return QString();
+ }
+ const QString real = QFileInfo(root + device).canonicalFilePath();
+ return QFileInfo(real.isEmpty() ? device : real).fileName();
+}
+
+// Unescapes the octal escapes /proc/self/mounts uses for spaces and tabs.
+QString unescape(const QByteArray &field)
+{
+ QByteArray out;
+ for (int i = 0; i < field.size(); ++i) {
+ if (field[i] == '\\' && i + 3 < field.size()) {
+ bool ok = false;
+ const int c = field.mid(i + 1, 3).toInt(&ok, 8);
+ if (ok) {
+ out.append(char(c));
+ i += 3;
+ continue;
+ }
+ }
+ out.append(field[i]);
+ }
+ return QString::fromUtf8(out);
+}
+
+bool systemMountPoint(const QString &point)
+{
+ static const QStringList exact = {
+ QStringLiteral("/"), QStringLiteral("/boot"), QStringLiteral("/boot/efi"), QStringLiteral("/efi"),
+ QStringLiteral("/home"), QStringLiteral("/usr"), QStringLiteral("/var"), QStringLiteral("/opt"),
+ QStringLiteral("/srv"), QStringLiteral("/root"), QStringLiteral("/tmp"),
+ };
+ // Where live-boot and dracut keep the stick a live session runs from.
+ static const QStringList live = {
+ QStringLiteral("/run/live/"), QStringLiteral("/lib/live/mount/"), QStringLiteral("/run/initramfs/"),
+ };
+ if (exact.contains(point)) {
+ return true;
+ }
+ for (const QString &prefix : live) {
+ if ((point + QLatin1Char('/')).startsWith(prefix)) {
+ return true;
+ }
+ }
+ return false;
+}
+}
+
+QStringList FormatSafety::baseDisks(const QString &root, const QString &blockName)
+{
+ QStringList out;
+ collect(root, blockName, out, 0);
+ return out;
+}
+
+QStringList FormatSafety::systemDisks(const QString &root)
+{
+ QStringList devices;
+ QFile mounts(root + QStringLiteral("/proc/self/mounts"));
+ if (mounts.open(QIODevice::ReadOnly)) {
+ while (!mounts.atEnd()) {
+ const QList<QByteArray> fields = mounts.readLine().split(' ');
+ if (fields.size() >= 2 && systemMountPoint(unescape(fields[1]))) {
+ devices.append(unescape(fields[0]));
+ }
+ }
+ }
+ QFile swaps(root + QStringLiteral("/proc/swaps"));
+ if (swaps.open(QIODevice::ReadOnly)) {
+ swaps.readLine();
+ while (!swaps.atEnd()) {
+ const QByteArray line = swaps.readLine().simplified();
+ if (!line.isEmpty()) {
+ devices.append(unescape(line.split(' ').first()));
+ }
+ }
+ }
+ QStringList disks;
+ for (const QString &device : std::as_const(devices)) {
+ // A live system's / is an overlay of a squashfs on loop0, whose
+ // file is on the stick; the stick's own mount is caught above.
+ for (const QString &disk : baseDisks(root, sysName(root, device))) {
+ if (!disks.contains(disk)) {
+ disks.append(disk);
+ }
+ }
+ }
+ return disks;
+}
+
+bool FormatSafety::canFormat(const QString &root, const Facts &facts)
+{
+ const QString &name = facts.blockName;
+ if (name.isEmpty() || facts.optical || !facts.removable) {
+ return false;
+ }
+ static const QStringList never = {
+ QStringLiteral("loop"), QStringLiteral("ram"), QStringLiteral("zram"), QStringLiteral("sr"), QStringLiteral("md"),
+ };
+ for (const QString &prefix : never) {
+ if (name.startsWith(prefix)) {
+ return false;
+ }
+ }
+ if (!QFileInfo::exists(blockDir(root, name))) {
+ return false;
+ }
+ const QStringList system = systemDisks(root);
+ const QStringList disks = baseDisks(root, name);
+ if (disks.isEmpty()) {
+ return false;
+ }
+ for (const QString &disk : disks) {
+ if (system.contains(disk)) {
+ return false;
+ }
+ }
+ return true;
+}
diff --git a/packages/wildos-files/src/formatsafety.h b/packages/wildos-files/src/formatsafety.h
new file mode 100644
index 0000000..a94b93d
--- /dev/null
+++ b/packages/wildos-files/src/formatsafety.h
@@ -0,0 +1,28 @@
+#pragma once
+
+#include <QString>
+#include <QStringList>
+
+// Which drives Files may offer to format. Kept apart from UDisks so the
+// rules can be tested against a made-up /proc and /sys.
+//
+// `root` is prefixed to every /proc, /sys and /dev path; it is empty on a
+// real system.
+namespace FormatSafety
+{
+// The whole disks (sysfs names: "sda", "nvme0n1") a block device is built
+// on, through partitions, LUKS and LVM.
+QStringList baseDisks(const QString &root, const QString &blockName);
+
+// The whole disks holding the running system: /, /boot, /home and the
+// rest, swap, and the stick a live session started from.
+QStringList systemDisks(const QString &root = QString());
+
+struct Facts {
+ QString blockName; // sysfs name of the volume, "sdb1"
+ bool removable = false; // removable media or a hot-plugged drive
+ bool optical = false;
+};
+
+bool canFormat(const QString &root, const Facts &facts);
+}
diff --git a/packages/wildos-files/src/main.cpp b/packages/wildos-files/src/main.cpp
index 48dda14..e24a772 100644
--- a/packages/wildos-files/src/main.cpp
+++ b/packages/wildos-files/src/main.cpp
@@ -40,6 +40,8 @@ int main(int argc, char *argv[])
parser.addPositionalArgument(QStringLiteral("locations"), QStringLiteral("Folders to open, each in its own tab. A file opens its folder with it selected."), QStringLiteral("[locations...]"));
QCommandLineOption selectOption(QStringLiteral("select"), QStringLiteral("Show the locations selected in their folders, folders included."));
parser.addOption(selectOption);
+ QCommandLineOption formatOption(QStringLiteral("format"), QStringLiteral("Open the Format dialog for a removable drive, such as /dev/sdb1."), QStringLiteral("device"));
+ parser.addOption(formatOption);
// Started by D-Bus for a call such as "show this file in its folder";
// the call itself opens the window.
QCommandLineOption serviceOption(QStringLiteral("service"), QStringLiteral("Start without a window, waiting for D-Bus requests."));
@@ -61,9 +63,15 @@ int main(int argc, char *argv[])
if (service && bus.isConnected() && bus.interface()->isServiceRegistered(serviceName)) {
return 0;
}
+ const QString formatDevice = parser.value(formatOption);
if (!preview && bus.isConnected() && bus.interface()->isServiceRegistered(serviceName)) {
- auto message = QDBusMessage::createMethodCall(serviceName, objectPath, serviceName, QStringLiteral("Open"));
- message << locations;
+ auto message = formatDevice.isEmpty() ? QDBusMessage::createMethodCall(serviceName, objectPath, serviceName, QStringLiteral("Open"))
+ : QDBusMessage::createMethodCall(serviceName, objectPath, serviceName, QStringLiteral("Format"));
+ if (formatDevice.isEmpty()) {
+ message << locations;
+ } else {
+ message << formatDevice;
+ }
bus.call(message, QDBus::Block, 5000);
return 0;
}
@@ -96,7 +104,9 @@ int main(int argc, char *argv[])
bus.registerService(QStringLiteral("org.freedesktop.FileManager1"));
}
- if (!service) {
+ if (!formatDevice.isEmpty()) {
+ files->Format(formatDevice);
+ } else if (!service) {
files->Open(locations);
} else {
QTimer::singleShot(60000, &app, [] {
diff --git a/packages/wildos-files/tests/formatsafety_test.cpp b/packages/wildos-files/tests/formatsafety_test.cpp
new file mode 100644
index 0000000..141e90a
--- /dev/null
+++ b/packages/wildos-files/tests/formatsafety_test.cpp
@@ -0,0 +1,146 @@
+#include "formatsafety.h"
+
+#include <QDir>
+#include <QFile>
+#include <QTemporaryDir>
+#include <QTest>
+
+// A made-up machine: Wild OS on sda (EFI on sda1, LUKS root on sda3 as
+// dm-0), a live stick on sdc, swap on nvme0n1, and a USB stick on sdb
+// with an ordinary partition and an unlocked LUKS one (dm-1).
+class FormatSafetyTest : public QObject
+{
+ Q_OBJECT
+
+private:
+ QTemporaryDir m_dir;
+ QString root() const { return m_dir.path(); }
+
+ void touch(const QString &path)
+ {
+ QDir().mkpath(QFileInfo(root() + path).path());
+ QFile f(root() + path);
+ QVERIFY(f.open(QIODevice::WriteOnly));
+ }
+
+ void disk(const QString &name, const QStringList &partitions)
+ {
+ QDir().mkpath(root() + QStringLiteral("/sys/block/") + name);
+ QFile::link(QStringLiteral("../../block/") + name, root() + QStringLiteral("/sys/class/block/") + name);
+ touch(QStringLiteral("/dev/") + name);
+ for (const QString &part : partitions) {
+ touch(QStringLiteral("/sys/block/%1/%2/partition").arg(name, part));
+ QFile::link(QStringLiteral("../../block/%1/%2").arg(name, part), root() + QStringLiteral("/sys/class/block/") + part);
+ touch(QStringLiteral("/dev/") + part);
+ }
+ }
+
+ void mapper(const QString &dm, const QString &slave, const QString &mapperName)
+ {
+ QDir().mkpath(root() + QStringLiteral("/sys/block/%1/slaves/%2").arg(dm, slave));
+ QFile::link(QStringLiteral("../../block/") + dm, root() + QStringLiteral("/sys/class/block/") + dm);
+ touch(QStringLiteral("/dev/") + dm);
+ QDir().mkpath(root() + QStringLiteral("/dev/mapper"));
+ QFile::link(QStringLiteral("../") + dm, root() + QStringLiteral("/dev/mapper/") + mapperName);
+ }
+
+ bool can(const QString &name, bool removable = true, bool optical = false)
+ {
+ FormatSafety::Facts facts;
+ facts.blockName = name;
+ facts.removable = removable;
+ facts.optical = optical;
+ return FormatSafety::canFormat(root(), facts);
+ }
+
+private Q_SLOTS:
+ void initTestCase()
+ {
+ QVERIFY(m_dir.isValid());
+ QDir().mkpath(root() + QStringLiteral("/sys/class/block"));
+ disk(QStringLiteral("sda"), {QStringLiteral("sda1"), QStringLiteral("sda2"), QStringLiteral("sda3")});
+ disk(QStringLiteral("sdb"), {QStringLiteral("sdb1"), QStringLiteral("sdb2")});
+ disk(QStringLiteral("sdc"), {QStringLiteral("sdc1"), QStringLiteral("sdc2")});
+ disk(QStringLiteral("nvme0n1"), {QStringLiteral("nvme0n1p1")});
+ disk(QStringLiteral("loop0"), {});
+ disk(QStringLiteral("sr0"), {});
+ mapper(QStringLiteral("dm-0"), QStringLiteral("sda3"), QStringLiteral("luks-0a1b"));
+ mapper(QStringLiteral("dm-1"), QStringLiteral("sdb2"), QStringLiteral("luks-9f8e"));
+
+ QDir().mkpath(root() + QStringLiteral("/proc/self"));
+ QFile mounts(root() + QStringLiteral("/proc/self/mounts"));
+ QVERIFY(mounts.open(QIODevice::WriteOnly));
+ mounts.write("/dev/mapper/luks-0a1b / ext4 rw,relatime 0 0\n"
+ "proc /proc proc rw 0 0\n"
+ "/dev/sda1 /boot/efi vfat rw 0 0\n"
+ "/dev/sdc1 /run/live/medium iso9660 ro 0 0\n"
+ "/dev/loop0 /run/live/rootfs/filesystem.squashfs squashfs ro 0 0\n"
+ "/dev/sdb1 /media/alex/HOLIDAY\\040PHOTOS exfat rw 0 0\n"
+ "/dev/mapper/luks-9f8e /media/alex/Private ext4 rw 0 0\n");
+ mounts.close();
+ QFile swaps(root() + QStringLiteral("/proc/swaps"));
+ QVERIFY(swaps.open(QIODevice::WriteOnly));
+ swaps.write("Filename\tType\tSize\tUsed\tPriority\n/dev/nvme0n1p1 partition 8388604 0 -2\n");
+ }
+
+ void baseDisksFollowsPartitionsAndLuks()
+ {
+ QCOMPARE(FormatSafety::baseDisks(root(), QStringLiteral("sda2")), QStringList{QStringLiteral("sda")});
+ QCOMPARE(FormatSafety::baseDisks(root(), QStringLiteral("dm-0")), QStringList{QStringLiteral("sda")});
+ QCOMPARE(FormatSafety::baseDisks(root(), QStringLiteral("sdb")), QStringList{QStringLiteral("sdb")});
+ }
+
+ void systemDisksAreRootBootLiveAndSwap()
+ {
+ QStringList disks = FormatSafety::systemDisks(root());
+ disks.sort();
+ QCOMPARE(disks, (QStringList{QStringLiteral("loop0"), QStringLiteral("nvme0n1"), QStringLiteral("sda"), QStringLiteral("sdc")}));
+ }
+
+ void usbStickCanBeFormatted()
+ {
+ QVERIFY(can(QStringLiteral("sdb1")));
+ QVERIFY(can(QStringLiteral("sdb")));
+ QVERIFY(can(QStringLiteral("sdb2")));
+ // Its unlocked encrypted partition, which formats as its container.
+ QVERIFY(can(QStringLiteral("dm-1")));
+ }
+
+ void systemDiskNever()
+ {
+ // Even if the system disk claims to be removable, as some USB
+ // enclosures and SD card readers do.
+ QVERIFY(!can(QStringLiteral("sda")));
+ QVERIFY(!can(QStringLiteral("sda1")));
+ QVERIFY(!can(QStringLiteral("sda2")));
+ QVERIFY(!can(QStringLiteral("sda3")));
+ QVERIFY(!can(QStringLiteral("dm-0")));
+ }
+
+ void liveStickNever()
+ {
+ QVERIFY(!can(QStringLiteral("sdc")));
+ QVERIFY(!can(QStringLiteral("sdc1")));
+ // Its other partition is on the same stick.
+ QVERIFY(!can(QStringLiteral("sdc2")));
+ }
+
+ void swapDiskNever()
+ {
+ QVERIFY(!can(QStringLiteral("nvme0n1")));
+ QVERIFY(!can(QStringLiteral("nvme0n1p1")));
+ }
+
+ void internalDrivesAndOthersNever()
+ {
+ QVERIFY(!can(QStringLiteral("sdb1"), false));
+ QVERIFY(!can(QStringLiteral("sr0")));
+ QVERIFY(!can(QStringLiteral("sdb1"), true, true));
+ QVERIFY(!can(QStringLiteral("loop0")));
+ QVERIFY(!can(QStringLiteral("sdz1")));
+ QVERIFY(!can(QString()));
+ }
+};
+
+QTEST_GUILESS_MAIN(FormatSafetyTest)
+#include "formatsafety_test.moc"
diff --git a/packages/wildos-installer/debian/changelog b/packages/wildos-installer/debian/changelog
index 59fb21f..fd0319f 100644
--- a/packages/wildos-installer/debian/changelog
+++ b/packages/wildos-installer/debian/changelog
@@ -1,3 +1,9 @@
+wildos-installer (0.1.5) trixie; urgency=medium
+
+ * Remove everything no longer asks to remove a USB stick or mentions a trial.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 16:11:19 +0000
+
wildos-installer (0.1.4) trixie; urgency=medium
* The sign-in and lock screens say the disk is encrypted on new installs
diff --git a/packages/wildos-installer/files/calamares/branding/wildos/finishedq.qml b/packages/wildos-installer/files/calamares/branding/wildos/finishedq.qml
index 002e667..5009617 100644
--- a/packages/wildos-installer/files/calamares/branding/wildos/finishedq.qml
+++ b/packages/wildos-installer/files/calamares/branding/wildos/finishedq.qml
@@ -73,7 +73,11 @@ Item {
Layout.alignment: Qt.AlignHCenter
Layout.preferredWidth: 460
horizontalAlignment: Text.AlignHCenter
- text: page.keptOther
+ // Remove everything starts the installer from the PC's own disk,
+ // so there is no USB stick to take out.
+ text: Installer.startMode === "recovery"
+ ? qsTr("Restart now. Next you'll create your account and join Wi-Fi.")
+ : page.keptOther
? qsTr("Remove the USB stick, then restart. Next you'll create your account, join Wi-Fi and bring your files across.")
: qsTr("Remove the USB stick, then restart. Next you'll create your account and join Wi-Fi.")
color: Qt.rgba(232 / 255, 236 / 255, 248 / 255, 0.82)
diff --git a/packages/wildos-installer/files/calamares/branding/wildos/summaryq.qml b/packages/wildos-installer/files/calamares/branding/wildos/summaryq.qml
index f8034f2..c7775f3 100644
--- a/packages/wildos-installer/files/calamares/branding/wildos/summaryq.qml
+++ b/packages/wildos-installer/files/calamares/branding/wildos/summaryq.qml
@@ -234,8 +234,9 @@ WPage {
}
Text {
Layout.fillWidth: true
- // Started straight into the installer, there is no trial behind it.
- text: Installer.startMode === "install"
+ // Started straight into the installer, or by Remove everything,
+ // there is no trial behind it.
+ text: Installer.startMode === "install" || Installer.startMode === "recovery"
? qsTr("Takes about 10 minutes. Keep the computer plugged in.")
: qsTr("Takes about 10 minutes. Keep the computer plugged in; you can keep using this trial while it installs.")
color: Qt.rgba(232 / 255, 236 / 255, 248 / 255, 0.85)
diff --git a/packages/wildos-recovery/debian/changelog b/packages/wildos-recovery/debian/changelog
index 66a9db2..80db49b 100644
--- a/packages/wildos-recovery/debian/changelog
+++ b/packages/wildos-recovery/debian/changelog
@@ -1,3 +1,17 @@
+wildos-recovery (0.1.3) trixie; urgency=medium
+
+ * Going back to a restore point keeps Steam's controller support as it
+ is now, with the Steam and 32-bit apps choice.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 16:11:45 +0000
+
+wildos-recovery (0.1.2) trixie; urgency=medium
+
+ * Going back to a restore point keeps the Steam and 32-bit apps choice
+ as it is now, like the hyper-threading one.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 14:00:00 +0000
+
wildos-recovery (0.1.1) trixie; urgency=medium
* Reset Wild OS is on. Keep my files ends at the sign-in screen with your
diff --git a/packages/wildos-recovery/files/restore-points b/packages/wildos-recovery/files/restore-points
index 1177dd0..e5304ff 100644
--- a/packages/wildos-recovery/files/restore-points
+++ b/packages/wildos-recovery/files/restore-points
@@ -90,6 +90,8 @@ CARRY = [
"/etc/fstab", "/etc/crypttab", "/etc/wildos/encrypted",
"/etc/grub.d/30_windows", "/etc/wildos/protection-level",
"/etc/wildos/cpu-threads", "/etc/default/grub.d/41_wildos_cpu_threads.cfg",
+ "/etc/wildos/32bit", "/etc/default/grub.d/41_wildos_32bit.cfg", "/etc/sysctl.d/991-wildos-32bit.conf",
+ "/etc/udev/rules.d/60-steam-input.rules", "/etc/udev/rules.d/60-steam-vr.rules",
"/etc/apt/sources.list.d/wildos.sources", "/etc/apt/apt.conf.d/20auto-upgrades",
"/etc/apt/apt.conf.d/52wildos-restart", HOLD_FILE,
# First-start setup: once it is done it must never come back.
diff --git a/packages/wildos-report/CMakeLists.txt b/packages/wildos-report/CMakeLists.txt
index 56a309a..2f241af 100644
--- a/packages/wildos-report/CMakeLists.txt
+++ b/packages/wildos-report/CMakeLists.txt
@@ -63,6 +63,7 @@ install(FILES data/wildos-report.svg DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/
install(PROGRAMS data/report-logs data/report-crash-note DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/wildos)
install(FILES data/org.wildos.report.policy DESTINATION ${CMAKE_INSTALL_DATADIR}/polkit-1/actions)
install(FILES data/50-wildos-report.rules DESTINATION ${CMAKE_INSTALL_DATADIR}/polkit-1/rules.d)
+install(FILES data/995-wildos-crash-reports.conf DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/sysctl.d)
install(FILES data/coredump-wildos-report.conf DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/system/[email protected]
RENAME wildos-report.conf)
install(FILES data/wildos-report-crash.path data/wildos-report-crash.service DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/user)
diff --git a/packages/wildos-report/data/995-wildos-crash-reports.conf b/packages/wildos-report/data/995-wildos-crash-reports.conf
new file mode 100644
index 0000000..0caab1b
--- /dev/null
+++ b/packages/wildos-report/data/995-wildos-crash-reports.conf
@@ -0,0 +1,8 @@
+# Crashes go to systemd-coredump again, so Wild OS can tell you when an app
+# closed unexpectedly and offer Report a problem. security-misc points
+# crashes at /bin/false (990-security-misc.conf), and this file sorts after
+# it. Its other protections stay: no core file is ever written (Storage=none
+# in its coredump.conf.d) and the core size limit stays 0, so
+# systemd-coredump records only which program crashed, the signal and the
+# time, never the program's memory. fs.suid_dumpable stays 0.
+kernel.core_pattern=|/usr/lib/systemd/systemd-coredump %P %u %g %s %t %c %h %d %F
diff --git a/packages/wildos-report/debian/changelog b/packages/wildos-report/debian/changelog
index afb448f..b3aef2a 100644
--- a/packages/wildos-report/debian/changelog
+++ b/packages/wildos-report/debian/changelog
@@ -1,3 +1,10 @@
+wildos-report (0.1.1) trixie; urgency=medium
+
+ * Crash notices: crashes are recorded again, as which program, the signal
+ and the time only.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 16:09:32 +0000
+
wildos-report (0.1.0) trixie; urgency=medium
* Initial release.
diff --git a/packages/wildos-settings/CMakeLists.txt b/packages/wildos-settings/CMakeLists.txt
index 1faec6e..20e1f12 100644
--- a/packages/wildos-settings/CMakeLists.txt
+++ b/packages/wildos-settings/CMakeLists.txt
@@ -51,6 +51,7 @@ qt_add_qml_module(wildos-settings
src/windowsmode.cpp src/windowsmode.h
src/windowsusb.cpp src/windowsusb.h
src/processor.cpp src/processor.h
+ src/compat32.cpp src/compat32.h
src/graphics.cpp src/graphics.h
src/inputdevices.cpp src/inputdevices.h
src/defaultapps.cpp src/defaultapps.h
@@ -113,7 +114,7 @@ install(TARGETS wildos-settings RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
install(FILES data/org.wildos.settings.desktop DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)
# The helpers are looked up by these exact paths (polkit pins the update
# helper to it), so they do not follow the distribution's libexec layout.
-install(PROGRAMS data/settings-update-policy data/settings-users data/settings-locale data/settings-protection data/settings-network data/settings-cpu-threads data/settings-graphics-driver data/settings-brave-spelling data/settings-fingerprint DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/wildos)
+install(PROGRAMS data/settings-update-policy data/settings-users data/settings-locale data/settings-protection data/settings-network data/settings-cpu-threads data/settings-32bit data/settings-game-overlay data/settings-graphics-driver data/settings-brave-spelling data/settings-fingerprint DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/wildos)
install(FILES data/org.wildos.settings.policy DESTINATION ${CMAKE_INSTALL_DATADIR}/polkit-1/actions)
# Opened from About > Credits. Not under /usr/share/doc, which the ISO
# leaves out.
diff --git a/packages/wildos-settings/data/org.wildos.settings.policy b/packages/wildos-settings/data/org.wildos.settings.policy
index 6f83b04..178123d 100644
--- a/packages/wildos-settings/data/org.wildos.settings.policy
+++ b/packages/wildos-settings/data/org.wildos.settings.policy
@@ -8,7 +8,8 @@
settings-fingerprint (Accounts),
settings-locale (Time and language), settings-protection (Privacy
and security), settings-network (the VPN kill switch) and
- settings-brave-spelling (Typing). -->
+ settings-brave-spelling (Typing). settings-cpu-threads and
+ settings-32bit change start-up options. -->
<policyconfig>
<vendor>Wild OS</vendor>
<vendor_url>https://wildos.io</vendor_url>
@@ -49,6 +50,18 @@
<annotate key="org.freedesktop.policykit.exec.path">/usr/libexec/wildos/settings-cpu-threads</annotate>
</action>
+ <action id="org.wildos.settings.32bit">
+ <description>Turn 32-bit apps on or off</description>
+ <message>Change whether this computer runs 32-bit apps such as Steam?</message>
+ <icon_name>security-medium</icon_name>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>no</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.exec.path">/usr/libexec/wildos/settings-32bit</annotate>
+ </action>
+
<action id="org.wildos.settings.graphics-driver">
<description>Change the graphics driver</description>
<message>Change which driver your NVIDIA graphics card uses?</message>
diff --git a/packages/wildos-settings/data/settings-32bit b/packages/wildos-settings/data/settings-32bit
new file mode 100644
index 0000000..1c1edaf
--- /dev/null
+++ b/packages/wildos-settings/data/settings-32bit
@@ -0,0 +1,111 @@
+#!/bin/sh
+# Turns 32-bit programs on or off from the next start-up: "Steam and 32-bit
+# apps" in Settings > Privacy and security, also offered by the prompt that
+# appears when a 32-bit program is opened while they are off. Runs as root
+# through pkexec (org.wildos.settings.32bit), and from settings-protection,
+# which turns them off at Strict and Maximum.
+#
+# Wild OS ships with them off: Kicksecure's ia32_emulation=0 removes the
+# kernel's 32-bit compatibility layer, a part of the kernel that has had
+# more than its share of security bugs. Steam's client and many older games
+# are 32-bit and cannot start without it. Turning it on drops that option,
+# and gives 32-bit programs back their vDSO (vdso32=0 and the
+# abi.vsyscall32=0 sysctl, which Kicksecure sets as a pair): without it every
+# system call they make goes the slow int 0x80 way and every clock read
+# becomes a full system call, a cost games pay many times a frame. 64-bit
+# programs are not affected either way. The kernel decides ia32_emulation at
+# boot, so it takes a restart.
+#
+# Steam's controller rules (Debian's steam-devices) come with it. They let
+# the signed-in user open game controllers directly and create virtual input
+# devices through /dev/uinput, which Steam Input and Remote Play need, and
+# which any program run by that user could also use to type or click. The
+# package moves the rules aside (debian/preinst), and they are linked back
+# into udev only while 32-bit apps are on.
+#
+# on | off save the choice and rebuild the boot menu
+# devices link or unlink the controller rules to match the saved choice
+
+set -eu
+
+CHOICE=/etc/wildos/32bit
+DROPIN=/etc/default/grub.d/41_wildos_32bit.cfg
+# Sorts after Kicksecure's 990-security-misc.conf, so this value wins.
+SYSCTL=/etc/sysctl.d/991-wildos-32bit.conf
+LEVEL_FILE=/etc/wildos/protection-level
+RULES_SRC=/usr/share/wildos/steam-devices
+RULES_DST=/etc/udev/rules.d
+RULES="60-steam-input.rules 60-steam-vr.rules"
+
+# Controllers plugged in now pick up the change straight away. uinput is
+# loaded here because udev only sees it once the module is in; at start-up
+# its static node does that job. Turning off closes /dev/uinput at once (a
+# mode of 0600 also masks the user's ACL entry); a controller already
+# plugged in keeps its access until it is unplugged or the PC restarts.
+devices() {
+ for rule in $RULES; do
+ if [ -e "$CHOICE" ] && [ -e "$RULES_SRC/$rule" ]; then
+ ln -sfn "$RULES_SRC/$rule" "$RULES_DST/$rule"
+ elif [ -L "$RULES_DST/$rule" ]; then
+ rm -f "$RULES_DST/$rule"
+ fi
+ done
+ if [ -e "$CHOICE" ]; then
+ modprobe -q uinput 2>/dev/null || true
+ elif [ -c /dev/uinput ]; then
+ chmod 0600 /dev/uinput 2>/dev/null || true
+ fi
+ if [ -d /run/udev ] && command -v udevadm >/dev/null 2>&1; then
+ udevadm control --reload >/dev/null 2>&1 || true
+ udevadm trigger --action=change --subsystem-match=misc \
+ --subsystem-match=hidraw --subsystem-match=usb >/dev/null 2>&1 || true
+ fi
+}
+
+case "${1:-}" in
+on)
+ # Strict and Maximum keep the 32-bit layer out of the kernel; Settings
+ # greys the switch out there, and this refuses in case anything else asks.
+ case "$(cat "$LEVEL_FILE" 2>/dev/null || true)" in
+ strict | maximum)
+ echo "Strict and Maximum protection keep 32-bit apps off." >&2
+ exit 3
+ ;;
+ esac
+ mkdir -p /etc/wildos
+ echo on > "$CHOICE"
+ # Sorts after 40_kernel_hardening.cfg, so it edits what that file added,
+ # whatever an update of it changes around these two options.
+ cat > "$DROPIN" <<'EOF'
+# Written by Wild OS Settings: Steam and 32-bit apps are on. Every other
+# kernel hardening option stays.
+GRUB_CMDLINE_LINUX="$(printf '%s' "$GRUB_CMDLINE_LINUX" | sed -e 's/ ia32_emulation=0//g' -e 's/ vdso32=0//g')"
+EOF
+ cat > "$SYSCTL" <<'EOF'
+# Written by Wild OS Settings: Steam and 32-bit apps are on, so they get the
+# 32-bit vDSO back.
+abi.vsyscall32 = 1
+EOF
+ devices
+ ;;
+off)
+ [ -e "$CHOICE" ] || [ -e "$DROPIN" ] || [ -e "$SYSCTL" ] || exit 0
+ rm -f "$CHOICE" "$DROPIN" "$SYSCTL"
+ sysctl -q -w abi.vsyscall32=0 2>/dev/null || true
+ devices
+ ;;
+devices)
+ devices
+ exit 0
+ ;;
+*)
+ echo "usage: $0 on|off|devices" >&2
+ exit 2
+ ;;
+esac
+
+if command -v update-grub >/dev/null 2>&1; then
+ update-grub >/dev/null 2>&1
+else
+ grub-mkconfig -o /boot/grub/grub.cfg >/dev/null 2>&1
+fi
diff --git a/packages/wildos-settings/data/settings-game-overlay b/packages/wildos-settings/data/settings-game-overlay
new file mode 100644
index 0000000..763a2b5
--- /dev/null
+++ b/packages/wildos-settings/data/settings-game-overlay
@@ -0,0 +1,64 @@
+#!/bin/sh
+# "Show a performance overlay in games", under Steam and 32-bit apps in
+# Settings > Privacy and security. Runs as the signed-in user, not root:
+# Steam comes from Flathub and the Store puts it in the user's own Flatpak
+# installation, so the overlay goes there too.
+#
+# The overlay is MangoHud's Vulkan layer as a Flatpak extension, on the
+# branch of Steam's own runtime (a layer on another branch is never loaded).
+# It is installed only while the overlay is on, and MANGOHUD=1 in Steam's
+# Flatpak overrides puts it in every Vulkan game Steam starts, including
+# Windows games through Proton. Native OpenGL games don't show it.
+#
+# on | off install or remove the layer and set Steam's override
+# status prints on or off
+
+set -u
+
+APP=com.valvesoftware.Steam
+LAYER=org.freedesktop.Platform.VulkanLayer.MangoHud
+FONT=/run/host/fonts/truetype/albert-sans/AlbertSans[wght].ttf
+
+# A few numbers in a quiet panel: frame rate, frame time, and load and
+# temperature for the processor and graphics. Labels in grey, figures in
+# white, no graph, no colour changes. Left Shift+F12 hides it in a game.
+CONFIG="legacy_layout=0,hud_compact,position=top-left,offset_x=16,offset_y=16"
+CONFIG="$CONFIG,round_corners=10,background_alpha=0.55,background_color=101114"
+CONFIG="$CONFIG,font_size=18,text_color=F2F2F4,gpu_color=9A9CA6,cpu_color=9A9CA6,engine_color=9A9CA6"
+CONFIG="$CONFIG,fps_color_change=0,fps,frametime,cpu_stats,cpu_temp,gpu_stats,gpu_temp"
+CONFIG="$CONFIG,toggle_hud=Shift_L+F12,font_file=$FONT"
+
+# Steam's installation: the user's own, or the system one if it came from
+# elsewhere (flatpak then asks for the password itself).
+scope=--user
+flatpak info --user "$APP" >/dev/null 2>&1 || scope=--system
+branch=$(flatpak info "$scope" -m "$APP" 2>/dev/null | sed -n 's|^runtime=.*/||p' | head -n 1)
+
+case "${1:-}" in
+on)
+ if [ -z "$branch" ]; then
+ echo "Steam is not installed." >&2
+ exit 3
+ fi
+ origin=$(flatpak info "$scope" --show-origin "$APP" 2>/dev/null)
+ flatpak install "$scope" -y --noninteractive "${origin:-flathub}" "$LAYER//$branch" >/dev/null || exit 4
+ flatpak override --user --env=MANGOHUD=1 "--env=MANGOHUD_CONFIG=$CONFIG" "$APP"
+ ;;
+off)
+ flatpak override --user --unset-env=MANGOHUD --unset-env=MANGOHUD_CONFIG "$APP" 2>/dev/null || true
+ for ref in $(flatpak list "$scope" --runtime --columns=ref 2>/dev/null | grep "^$LAYER/"); do
+ flatpak uninstall "$scope" -y --noninteractive "$ref" >/dev/null 2>&1 || true
+ done
+ ;;
+status)
+ if flatpak override --user --show "$APP" 2>/dev/null | grep -q '^MANGOHUD=1$'; then
+ echo on
+ else
+ echo off
+ fi
+ ;;
+*)
+ echo "usage: $0 on|off|status" >&2
+ exit 2
+ ;;
+esac
diff --git a/packages/wildos-settings/data/settings-protection b/packages/wildos-settings/data/settings-protection
index 79234c6..028cc95 100644
--- a/packages/wildos-settings/data/settings-protection
+++ b/packages/wildos-settings/data/settings-protection
@@ -120,11 +120,15 @@ case "${1:-}" in
usb "$1"
bluetooth "$1" "$previous"
camera "$1"
- # Strict and Maximum keep every CPU flaw protection on, so hyper-threading
- # goes off from the next start-up. Standard leaves the person's choice.
+ # Strict and Maximum keep every CPU flaw protection on and the kernel's
+ # 32-bit layer out, so hyper-threading and 32-bit apps go off from the
+ # next start-up. Standard leaves the person's choices.
if [ "$1" != standard ] && [ -x /usr/libexec/wildos/settings-cpu-threads ]; then
/usr/libexec/wildos/settings-cpu-threads off || true
fi
+ if [ "$1" != standard ] && [ -x /usr/libexec/wildos/settings-32bit ]; then
+ /usr/libexec/wildos/settings-32bit off || true
+ fi
if [ "$1" = standard ]; then
rm -f "$LEVEL_FILE"
else
diff --git a/packages/wildos-settings/debian/changelog b/packages/wildos-settings/debian/changelog
index 80349b4..0afaaca 100644
--- a/packages/wildos-settings/debian/changelog
+++ b/packages/wildos-settings/debian/changelog
@@ -1,3 +1,23 @@
+wildos-settings (0.1.28) trixie; urgency=medium
+
+ * Steam and 32-bit apps also turns on Steam's controller support: game
+ controllers, Steam Input and Remote Play work, and turning it off takes
+ it away again.
+ * Show a performance overlay in games, under Steam and 32-bit apps: frame
+ rate, frame time, and processor and graphics load and temperature in
+ Steam's Vulkan and Proton games. Off to start with.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 16:11:45 +0000
+
+wildos-settings (0.1.27) trixie; urgency=medium
+
+ * Steam and 32-bit apps, in Privacy and security: off to start with.
+ Turning it on asks for the password and offers a restart, and the
+ Security card says 32-bit apps are on. Strict and Maximum keep it off
+ and turn it off again.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 14:00:00 +0000
+
wildos-settings (0.1.26) trixie; urgency=medium
* Reset Wild OS is on: keep your files, or remove everything.
diff --git a/packages/wildos-settings/debian/control b/packages/wildos-settings/debian/control
index 5f7c5dd..ccaf6e7 100644
--- a/packages/wildos-settings/debian/control
+++ b/packages/wildos-settings/debian/control
@@ -58,6 +58,7 @@ Depends:
plasma-desktop,
libkscreen-bin,
wildos-branding,
+ steam-devices,
wildos-ui (>= 0.1.3),
kio6,
packagekit,
diff --git a/packages/wildos-settings/debian/postinst b/packages/wildos-settings/debian/postinst
index 5c0ec5b..136b527 100644
--- a/packages/wildos-settings/debian/postinst
+++ b/packages/wildos-settings/debian/postinst
@@ -23,6 +23,9 @@ if [ "$1" = "configure" ]; then
if [ -d /run/systemd/system ] && [ -x /usr/libexec/wildos/settings-protection ] && command -v nft >/dev/null; then
/usr/libexec/wildos/settings-protection boot || true
fi
+ # Steam's controller rules follow the 32-bit choice, including on PCs
+ # that turned it on before the rules came with it.
+ /usr/libexec/wildos/settings-32bit devices || true
fi
#DEBHELPER#
diff --git a/packages/wildos-settings/debian/postrm b/packages/wildos-settings/debian/postrm
index 22c1a11..2e0cb65 100644
--- a/packages/wildos-settings/debian/postrm
+++ b/packages/wildos-settings/debian/postrm
@@ -6,6 +6,13 @@ if [ "$1" = "remove" ] || [ "$1" = "purge" ] || [ "$1" = "abort-install" ]; then
dpkg-divert --package wildos-settings --remove --rename \
--divert "/usr/bin/$bin.kde" "/usr/bin/$bin" >/dev/null || true
done
+ for rule in 60-steam-input.rules 60-steam-vr.rules; do
+ if [ -L "/etc/udev/rules.d/$rule" ]; then
+ rm -f "/etc/udev/rules.d/$rule"
+ fi
+ dpkg-divert --package wildos-settings --remove --rename \
+ --divert "/usr/share/wildos/steam-devices/$rule" "/usr/lib/udev/rules.d/$rule" >/dev/null || true
+ done
# The kill switch's rules outlive its service on purpose (a crash must
# not let traffic out), so they go with the package.
nft delete table inet wildos_kill_switch 2>/dev/null || true
diff --git a/packages/wildos-settings/debian/preinst b/packages/wildos-settings/debian/preinst
index adcd1aa..fc545c3 100644
--- a/packages/wildos-settings/debian/preinst
+++ b/packages/wildos-settings/debian/preinst
@@ -8,6 +8,13 @@ if [ "$1" = "install" ] || [ "$1" = "upgrade" ]; then
dpkg-divert --package wildos-settings --add --rename \
--divert "/usr/bin/$bin.kde" "/usr/bin/$bin" >/dev/null
done
+ # Steam's controller rules are kept out of udev's folders and linked in
+ # only while Steam and 32-bit apps are on (settings-32bit).
+ mkdir -p /usr/share/wildos/steam-devices
+ for rule in 60-steam-input.rules 60-steam-vr.rules; do
+ dpkg-divert --package wildos-settings --add --rename \
+ --divert "/usr/share/wildos/steam-devices/$rule" "/usr/lib/udev/rules.d/$rule" >/dev/null
+ done
fi
#DEBHELPER#
diff --git a/packages/wildos-settings/qml/components/Pages.qml b/packages/wildos-settings/qml/components/Pages.qml
index ef3b333..360e696 100644
--- a/packages/wildos-settings/qml/components/Pages.qml
+++ b/packages/wildos-settings/qml/components/Pages.qml
@@ -204,7 +204,7 @@ QtObject {
keywords: "slow keys bounce keys filter keys repeated presses double letters tremor hold key delay" },
"privacy": { title: "Privacy and security", icon: "shield", component: "PrivacyPage",
- keywords: "security privacy protection protection level encryption firewall secure boot sandbox usb block usb usage data telemetry diagnostics windows security" },
+ keywords: "security privacy protection protection level encryption firewall secure boot sandbox usb block usb usage data telemetry diagnostics windows security steam 32-bit 32 bit ia32 i386 games old apps compatibility controller controllers gamepad joystick steam input remote play performance overlay fps frame rate frametime mangohud" },
"apppermissions": { title: "App permissions", parent: "privacy", icon: "sandbox", component: "AppPermissionsPage", fallback: "kcm_flatpak",
description: "What apps from the Store can reach",
keywords: "permissions sandbox app access store apps flatpak" },
diff --git a/packages/wildos-settings/qml/components/Protection.qml b/packages/wildos-settings/qml/components/Protection.qml
index b54ba32..6bafa0d 100644
--- a/packages/wildos-settings/qml/components/Protection.qml
+++ b/packages/wildos-settings/qml/components/Protection.qml
@@ -25,10 +25,14 @@ QtObject {
{ key: "apps", title: "App protection", icon: "sandbox", sentence: "app protection" },
{ key: "devices", title: "USB protection", icon: "plug", sentence: "USB protection" },
{ key: "secureboot", title: "Secure Boot", icon: "chip", sentence: "Secure Boot" },
- { key: "network", title: "Network protection", icon: "firewall", sentence: "network protection" }
+ { key: "network", title: "Network protection", icon: "firewall", sentence: "network protection" },
+ { key: "compat32", title: "32-bit apps", icon: "chip", sentence: "32-bit apps" }
]
- readonly property var items: known.filter(item => status[item.key] !== undefined)
+ // 32-bit apps get a row only while they are on: off is how Wild OS
+ // ships, and not a protection anyone needs to see listed.
+ readonly property bool compat32: status.compat32 === "on"
+ readonly property var items: known.filter(item => status[item.key] !== undefined && (item.key !== "compat32" || compat32))
readonly property bool checked: items.length > 0
// Warnings the person chose to ignore from the taskbar's security chip
@@ -54,6 +58,10 @@ QtObject {
// folder, say), so it is shown but never raised as a problem;
// the taskbar's security chip words it the same way.
return true;
+ case "compat32":
+ // A choice made in Settings with the trade-off spelled out, so
+ // it is shown (and lowers the headline) but never raised.
+ return true;
default:
return v === "on";
}
@@ -66,6 +74,7 @@ QtObject {
readonly property var leading: ["firewall", "encryption", "updates"]
readonly property var tiles: leading.map(key => items.find(item => item.key === key)).filter(item => item !== undefined)
.concat(attention.filter(item => !leading.includes(item.key)))
+ .concat(items.filter(item => item.key === "compat32"))
readonly property bool allOn: checked && attention.length === 0
function value(item) {
@@ -97,6 +106,8 @@ QtObject {
return count("devices_blocked") > 0 ? "On, " + Format.plural(count("devices_blocked"), "device", "devices") + " held back" : "On";
case "secureboot":
return v === "on" ? "On" : v === "unsupported" ? "Not supported by this computer" : "Off";
+ case "compat32":
+ return "On, for Steam and older apps";
case "network":
if (v === "on") {
return "On";
@@ -190,7 +201,8 @@ QtObject {
// What each protection means and what can be done about it, for the
// dialog a tile opens. action is one of "updates", "check", "usb",
- // "firmware", "restart" or empty when there is nothing to press.
+ // "firmware", "restart", "compat32" or empty when there is nothing to
+ // press.
function details(item) {
const v = status[item.key];
switch (item.key) {
@@ -245,6 +257,8 @@ QtObject {
return { text: "Nothing on this computer accepts connections from other computers.", action: "" };
}
return { text: Format.plural(Math.max(1, count("network_services")), "service accepts", "services accept") + " connections from other computers. Wild OS does not open any by itself, so an app you installed or a sharing feature you turned on started it. Remove or turn off the app that needs it if you do not use it.", action: "" };
+ case "compat32":
+ return { text: "Steam and 32-bit apps is on, so 32-bit programs such as Steam and older games can run. To run them, the system keeps a part that Wild OS normally leaves out, and that part has had serious security flaws over the years. Apps you run can also create a virtual keyboard or game controller, which Steam needs for controllers. Turn it off when you no longer need it. It takes a restart.", action: "compat32" };
default:
return { text: "", action: "" };
}
@@ -262,6 +276,7 @@ QtObject {
}
readonly property string headline: !checked ? "Wild OS could not check your protection"
+ : allOn && compat32 ? "Protected, with 32-bit apps on"
: allOn ? "Your computer is protected"
: attention.length === 1 && attention[0].key === "updates" && updatesWaiting ? "Security updates are waiting"
: attention.length === 1 && attention[0].key === "updates" ? (updatesNeverChecked ? "Updates not checked yet" : "Updates not checked lately")
@@ -273,6 +288,9 @@ QtObject {
if (!checked) {
return "The protection check is not installed on this computer.";
}
+ if (allOn && compat32) {
+ return "32-bit apps are on, which keeps a part of the system that has had serious security flaws. Everything else Wild OS checks is in order." + suffix;
+ }
if (allOn) {
const onNames = tiles.filter(item => status[item.key] === "on" || status[item.key] === "current")
.slice(0, 3).map(item => item.sentence);
diff --git a/packages/wildos-settings/qml/components/ProtectionDialog.qml b/packages/wildos-settings/qml/components/ProtectionDialog.qml
index 473aabe..a325847 100644
--- a/packages/wildos-settings/qml/components/ProtectionDialog.qml
+++ b/packages/wildos-settings/qml/components/ProtectionDialog.qml
@@ -14,7 +14,9 @@ UI.Dialog {
property bool startedGood: false
readonly property var info: item ? Protection.details(item) : ({ text: "", action: "" })
- readonly property string action: info.action === "firmware" && !firmwareRestart ? "" : info.action
+ // 32-bit apps already turned off wait for the restart, which the switch
+ // on Privacy and security offers.
+ readonly property string action: (info.action === "firmware" && !firmwareRestart) || (info.action === "compat32" && !Compat32.enabled) ? "" : info.action
function show(protection) {
item = protection;
@@ -64,6 +66,7 @@ UI.Dialog {
case "usb": return "Turn on";
case "firmware": return "Restart to firmware settings";
case "restart": return "Restart now";
+ case "compat32": return "Turn off";
default: return "";
}
}
@@ -85,6 +88,12 @@ UI.Dialog {
case "restart":
Updates.restart();
break;
+ case "compat32":
+ // Takes effect at the next start-up; the switch on
+ // Privacy and security offers the restart.
+ dialog.close();
+ Compat32.setEnabled(false);
+ break;
}
}
},
diff --git a/packages/wildos-settings/qml/components/SecurityCard.qml b/packages/wildos-settings/qml/components/SecurityCard.qml
index bfb83a0..ad93d0f 100644
--- a/packages/wildos-settings/qml/components/SecurityCard.qml
+++ b/packages/wildos-settings/qml/components/SecurityCard.qml
@@ -23,11 +23,14 @@ HomeCard {
// On Home the three most important, needs-a-look first; on Privacy and
// security the three the design names plus anything else needing a look.
+ // 32-bit apps, when on, come straight after anything needing a look:
+ // the card should not read as all on without saying so.
readonly property var shown: compact
- ? Protection.attention.concat(Protection.tiles.filter(item => !Protection.attention.includes(item))).slice(0, 3)
+ ? Protection.attention.concat(Protection.tiles.filter(item => item.key === "compat32"))
+ .concat(Protection.tiles.filter(item => !Protection.attention.includes(item) && item.key !== "compat32")).slice(0, 3)
: Protection.tiles
// The last line names the one people most often ask about first.
- readonly property var order: ["devices", "apps", "secureboot", "network", "encryption", "updates"]
+ readonly property var order: ["devices", "apps", "secureboot", "network", "encryption", "updates", "compat32"]
readonly property var hidden: Protection.items.filter(item => !shown.includes(item))
.sort((a, b) => order.indexOf(a.key) - order.indexOf(b.key))
readonly property var hiddenAttention: hidden.filter(item => !Protection.good(item))
@@ -36,7 +39,8 @@ HomeCard {
if (!Protection.good(item)) {
return "warn";
}
- if (Protection.ignored.includes(item.key)) {
+ // 32-bit apps on is a choice that lowers protection, never a tick.
+ if (Protection.ignored.includes(item.key) || item.key === "compat32") {
return "quiet";
}
const v = Protection.status[item.key];
@@ -55,6 +59,11 @@ HomeCard {
return "Couldn't check.";
}
const n = Protection.attention.length;
+ // 32-bit apps lower protection by choice, so the card says so
+ // rather than "All on".
+ if (n === 0 && Protection.compat32) {
+ return "32-bit apps allowed.";
+ }
return n === 0 ? "All on." : n === 1 ? "1 needs a look." : n + " need a look.";
}
@@ -140,7 +149,7 @@ HomeCard {
return rest.length + " more need a look";
}
const others = card.hidden.length - 1;
- const allOn = card.hidden.every(item => Protection.status[item.key] === "on" || Protection.status[item.key] === "current");
+ const allOn = card.hidden.every(item => item.key !== "compat32" && (Protection.status[item.key] === "on" || Protection.status[item.key] === "current"));
const head = card.hidden.length > 0 ? card.hidden[0].title : "";
const more = others > 0 ? head + " and " + others + " more" : head;
return more + (allOn ? (others > 0 ? ", all on" : ", on") : ", all fine");
diff --git a/packages/wildos-settings/qml/pages/PrivacyPage.qml b/packages/wildos-settings/qml/pages/PrivacyPage.qml
index e5531fd..b2be8ce 100644
--- a/packages/wildos-settings/qml/pages/PrivacyPage.qml
+++ b/packages/wildos-settings/qml/pages/PrivacyPage.qml
@@ -5,7 +5,8 @@ import WildOS.UI as UI
// Privacy and security, laid out as Settings.dc.html: the Security card
// (security-status, one row per protection), the protection level, what
-// apps can reach, searching files and activity history, then USB protection.
+// apps can reach, searching files and activity history, USB protection,
+// then Steam and 32-bit apps.
PageScroll {
id: page
@@ -111,6 +112,15 @@ PageScroll {
size: 12
color: UI.Style.danger
}
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: Compat32.enabled && !Compat32.locked
+ text: "Strict and Maximum turn Steam and 32-bit apps off again, from the next restart."
+ size: 12.5
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ }
}
ColumnLayout {
@@ -233,4 +243,125 @@ PageScroll {
}
}
}
+
+ // The kernel's 32-bit layer, which Steam and older games need. A boot
+ // option (settings-32bit), so a change offers a restart; Strict and
+ // Maximum keep it off.
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
+ visible: Compat32.available
+
+ RowLayout {
+ Layout.fillWidth: true
+
+ SectionTitle {
+ Layout.fillWidth: true
+ text: "Compatibility"
+ }
+
+ UI.LinkButton {
+ text: "Learn more"
+ Accessible.name: "Learn more about Steam and 32-bit apps"
+ onClicked: Qt.openUrlExternally("https://help.wildos.io/apps/steam-and-32-bit-apps/")
+ }
+ }
+
+ UI.Card {
+ id: compatCard
+ Layout.fillWidth: true
+ readonly property bool pending: Compat32.enabled !== Compat32.active
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ iconName: "games"
+ minHeight: 64
+ title: "Steam and 32-bit apps"
+ description: Compat32.locked
+ ? "Off at Strict and Maximum protection, which keep the 32-bit part of the system out."
+ : compatCard.pending
+ ? "Restart to finish turning it " + (Compat32.enabled ? "on." : "off.")
+ : Compat32.enabled
+ ? "On. Steam, older games and game controllers work, and your protection is a little lower while it is."
+ : "Off for security. Steam and many older games are 32-bit and need this on, and it also turns on Steam's game controller support. Turning it on lowers your protection a little and needs a restart."
+ status: Compat32.enabled && !Compat32.locked ? "On" : "Off"
+
+ UI.Toggle {
+ id: compatToggle
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Compat32.enabled && !Compat32.locked
+ enabled: !Compat32.busy && !Compat32.locked
+ locked: Compat32.locked
+ lockedReason: "Strict and Maximum protection keep this off"
+ Accessible.name: "Steam and 32-bit apps"
+ onToggled: {
+ compatError.text = "";
+ Compat32.setEnabled(checked);
+ }
+ }
+ }
+
+ // MangoHud for Flathub Steam (settings-game-overlay), only
+ // while 32-bit apps are on.
+ UI.SettingRow {
+ visible: Compat32.enabled && !Compat32.locked
+ title: "Show a performance overlay in games"
+ description: Compat32.overlayBusy
+ ? (Compat32.overlay ? "Turning it off…" : "Downloading the overlay…")
+ : !Compat32.steamInstalled && !Compat32.overlay
+ ? "Frame rate, frame time, and processor and graphics load and temperature. Install Steam from the Store first."
+ : "Frame rate, frame time, and processor and graphics load and temperature, in Vulkan and Proton games. Left Shift+F12 hides it."
+ status: overlayToggle.checked ? "On" : "Off"
+
+ UI.Toggle {
+ id: overlayToggle
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Compat32.overlay
+ enabled: !Compat32.overlayBusy && (Compat32.steamInstalled || Compat32.overlay)
+ Accessible.name: "Show a performance overlay in games"
+ onToggled: {
+ compatError.text = "";
+ Compat32.setOverlay(checked);
+ }
+ }
+ }
+
+ UI.SettingRow {
+ visible: compatCard.pending && !Compat32.locked
+ title: "Restart to apply"
+ description: "Open apps are asked to save first."
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Restart now"
+ onClicked: Updates.restart()
+ }
+ }
+ }
+
+ Connections {
+ target: Compat32
+ // A cancelled password leaves the choice as it was, so the switch goes back to it.
+ function onChanged() {
+ compatToggle.checked = Compat32.enabled && !Compat32.locked;
+ // Stays where it was flipped while the layer downloads.
+ if (!Compat32.overlayBusy) {
+ overlayToggle.checked = Compat32.overlay;
+ }
+ }
+ function onFailed(message) { compatError.text = message }
+ }
+ }
+
+ UI.Label {
+ id: compatError
+ visible: text.length > 0
+ Layout.fillWidth: true
+ wrapMode: Text.WordWrap
+ size: 13
+ color: UI.Style.warning
+ }
+ }
}
diff --git a/packages/wildos-settings/src/compat32.cpp b/packages/wildos-settings/src/compat32.cpp
new file mode 100644
index 0000000..b081ddf
--- /dev/null
+++ b/packages/wildos-settings/src/compat32.cpp
@@ -0,0 +1,145 @@
+#include "compat32.h"
+
+#include <QFile>
+#include <QDir>
+#include <QFileSystemWatcher>
+#include <QProcess>
+#include <QStandardPaths>
+
+namespace
+{
+const QString wildosDir = QStringLiteral("/etc/wildos");
+const QString choiceFile = QStringLiteral("/etc/wildos/32bit");
+const QString helper = QStringLiteral("/usr/libexec/wildos/settings-32bit");
+const QString overlayHelper = QStringLiteral("/usr/libexec/wildos/settings-game-overlay");
+const QString steamId = QStringLiteral("com.valvesoftware.Steam");
+
+QString userFlatpak()
+{
+ return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/flatpak");
+}
+}
+
+Compat32::Compat32(QObject *parent)
+ : QObject(parent)
+ , m_watcher(new QFileSystemWatcher(this))
+{
+ // The choice and the protection level both live in /etc/wildos, written
+ // by root helpers (the 32-bit prompt can turn it on too), so the switch
+ // follows them without Settings asking.
+ if (QFile::exists(wildosDir)) {
+ m_watcher->addPath(wildosDir);
+ }
+ connect(m_watcher, &QFileSystemWatcher::directoryChanged, this, &Compat32::changed);
+ // The overlay lives only while 32-bit apps are on: turned off here, or
+ // at Strict and Maximum, it goes too, the next time Settings sees it.
+ connect(this, &Compat32::changed, this, [this] {
+ if (!enabled() && overlay() && !m_overlayBusy) {
+ setOverlay(false);
+ }
+ });
+ if (!enabled() && overlay()) {
+ setOverlay(false);
+ }
+}
+
+bool Compat32::steamInstalled() const
+{
+ return QFile::exists(userFlatpak() + QStringLiteral("/app/") + steamId)
+ || QFile::exists(QStringLiteral("/var/lib/flatpak/app/") + steamId);
+}
+
+// Read straight from Steam's override file, as settings-game-overlay status
+// does through flatpak, without starting a process for every look.
+bool Compat32::overlay() const
+{
+ QFile file(userFlatpak() + QStringLiteral("/overrides/") + steamId);
+ if (!file.open(QIODevice::ReadOnly)) {
+ return false;
+ }
+ for (const QByteArray &line : file.readAll().split('\n')) {
+ if (line.trimmed() == "MANGOHUD=1") {
+ return true;
+ }
+ }
+ return false;
+}
+
+void Compat32::setOverlay(bool on)
+{
+ if (m_overlayBusy || on == overlay() || (on && (!enabled() || locked()))) {
+ return;
+ }
+ m_overlayBusy = true;
+ Q_EMIT changed();
+ auto process = new QProcess(this);
+ connect(process, &QProcess::finished, this, [this, process](int code) {
+ process->deleteLater();
+ m_overlayBusy = false;
+ if (code == 3) {
+ Q_EMIT failed(QStringLiteral("Install Steam from the Store first."));
+ } else if (code != 0) {
+ Q_EMIT failed(QStringLiteral("The overlay could not be downloaded. Check you're online and try again."));
+ }
+ Q_EMIT changed();
+ });
+ process->start(overlayHelper, {on ? QStringLiteral("on") : QStringLiteral("off")});
+}
+
+bool Compat32::available() const
+{
+ return QFile::exists(helper);
+}
+
+bool Compat32::enabled() const
+{
+ return QFile::exists(choiceFile);
+}
+
+// The kernel takes the last ia32_emulation= it was started with; without
+// one, 32-bit programs run.
+bool Compat32::active() const
+{
+ QFile file(QStringLiteral("/proc/cmdline"));
+ if (!file.open(QIODevice::ReadOnly)) {
+ return false;
+ }
+ QByteArray setting;
+ for (const QByteArray &word : file.readAll().simplified().split(' ')) {
+ if (word.startsWith("ia32_emulation=")) {
+ setting = word.mid(15);
+ }
+ }
+ static const QList<QByteArray> off{"0", "n", "N", "no", "off", "false"};
+ return !off.contains(setting);
+}
+
+bool Compat32::locked() const
+{
+ QFile file(QStringLiteral("/etc/wildos/protection-level"));
+ const QByteArray level = file.open(QIODevice::ReadOnly) ? file.readAll().trimmed() : QByteArray();
+ return level == "strict" || level == "maximum";
+}
+
+void Compat32::setEnabled(bool on)
+{
+ if (m_busy || on == enabled() || (on && locked())) {
+ return;
+ }
+ m_busy = true;
+ Q_EMIT changed();
+ auto process = new QProcess(this);
+ connect(process, &QProcess::finished, this, [this, process](int code) {
+ process->deleteLater();
+ m_busy = false;
+ if (code == 126 || code == 127) {
+ Q_EMIT failed(QStringLiteral("Nothing was changed because the password was not given."));
+ } else if (code == 3) {
+ Q_EMIT failed(QStringLiteral("Strict and Maximum protection keep 32-bit apps off."));
+ } else if (code != 0) {
+ Q_EMIT failed(QStringLiteral("The setting could not be changed."));
+ }
+ Q_EMIT changed();
+ });
+ process->start(QStringLiteral("pkexec"), {helper, on ? QStringLiteral("on") : QStringLiteral("off")});
+}
diff --git a/packages/wildos-settings/src/compat32.h b/packages/wildos-settings/src/compat32.h
new file mode 100644
index 0000000..2771da6
--- /dev/null
+++ b/packages/wildos-settings/src/compat32.h
@@ -0,0 +1,57 @@
+#pragma once
+
+#include <QObject>
+#include <QQmlEngine>
+
+class QFileSystemWatcher;
+
+// "Steam and 32-bit apps", in Privacy and security. Wild OS starts with the
+// kernel's 32-bit layer off (ia32_emulation=0); turning it on is a boot
+// option written by settings-32bit, so what was chosen and what the running
+// kernel does can differ until the next start-up. Strict and Maximum
+// protection keep it off, as they do hyper-threading.
+class Compat32 : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(bool available READ available CONSTANT)
+ // What was chosen; it applies from the next start-up.
+ Q_PROPERTY(bool enabled READ enabled NOTIFY changed)
+ // What the running kernel does.
+ Q_PROPERTY(bool active READ active CONSTANT)
+ // Strict or Maximum protection, which keep it off.
+ Q_PROPERTY(bool locked READ locked NOTIFY changed)
+ // A change is waiting for the password or being written.
+ Q_PROPERTY(bool busy READ busy NOTIFY changed)
+ // Steam from Flathub, which the performance overlay works with.
+ Q_PROPERTY(bool steamInstalled READ steamInstalled NOTIFY changed)
+ // "Show a performance overlay in games" (settings-game-overlay).
+ Q_PROPERTY(bool overlay READ overlay NOTIFY changed)
+ Q_PROPERTY(bool overlayBusy READ overlayBusy NOTIFY changed)
+
+public:
+ explicit Compat32(QObject *parent = nullptr);
+
+ bool available() const;
+ bool enabled() const;
+ bool active() const;
+ bool locked() const;
+ bool busy() const { return m_busy; }
+ bool steamInstalled() const;
+ bool overlay() const;
+ bool overlayBusy() const { return m_overlayBusy; }
+
+ Q_INVOKABLE void setEnabled(bool on);
+ Q_INVOKABLE void setOverlay(bool on);
+
+Q_SIGNALS:
+ void changed();
+ void failed(const QString &message);
+
+private:
+ QFileSystemWatcher *m_watcher = nullptr;
+ bool m_busy = false;
+ bool m_overlayBusy = false;
+};
diff --git a/packages/wildos-system-dialogs/CMakeLists.txt b/packages/wildos-system-dialogs/CMakeLists.txt
index b206bec..bfa07cb 100644
--- a/packages/wildos-system-dialogs/CMakeLists.txt
+++ b/packages/wildos-system-dialogs/CMakeLists.txt
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.25)
-project(wildos-system-dialogs VERSION 0.1.0 LANGUAGES CXX)
+project(wildos-system-dialogs VERSION 0.1.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -43,8 +43,15 @@ target_link_libraries(wildos-dialogs PRIVATE
PolkitQt6-1::Agent PolkitQt6-1::Core
)
+# Runs inside whatever started a 32-bit program, sandboxes included, so it
+# carries its own C library (see the file).
+add_executable(32bit-blocked src/32bit-blocked.c)
+target_link_options(32bit-blocked PRIVATE -static)
+
set(LIBEXEC ${CMAKE_INSTALL_PREFIX}/libexec/wildos)
-install(TARGETS wildos-dialogs RUNTIME DESTINATION ${LIBEXEC})
+install(TARGETS wildos-dialogs 32bit-blocked RUNTIME DESTINATION ${LIBEXEC})
+install(PROGRAMS data/32bit-prompt-setup DESTINATION ${LIBEXEC})
+install(FILES data/wildos-32bit-prompt.service DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/system)
install(PROGRAMS data/record-package-sources DESTINATION ${LIBEXEC})
install(FILES data/80wildos-package-sources DESTINATION ${CMAKE_INSTALL_FULL_SYSCONFDIR}/apt/apt.conf.d)
install(FILES data/org.wildos.security.desktop DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)
diff --git a/packages/wildos-system-dialogs/data/32bit-prompt-setup b/packages/wildos-system-dialogs/data/32bit-prompt-setup
new file mode 100644
index 0000000..b0d3ca1
--- /dev/null
+++ b/packages/wildos-system-dialogs/data/32bit-prompt-setup
@@ -0,0 +1,33 @@
+#!/bin/sh
+# Hands 32-bit programs to the prompt that offers to turn them on, but only
+# while the running kernel refuses them: the binfmt_misc entry is written to
+# /run/binfmt.d each start-up, before systemd-binfmt reads it, and only when
+# the kernel was started with ia32_emulation off. After "Steam and 32-bit
+# apps" is turned on and the computer restarted, nothing is written, so the
+# entry can never stand in for a program that would have run. Run by
+# wildos-32bit-prompt.service.
+
+set -eu
+
+ENTRY=/run/binfmt.d/wildos-32bit.conf
+
+# The kernel takes the last ia32_emulation= it is given.
+setting=
+for word in $(cat /proc/cmdline); do
+ case "$word" in
+ ia32_emulation=*) setting=${word#ia32_emulation=} ;;
+ esac
+done
+
+case "$setting" in
+0 | n | N | no | off | false)
+ mkdir -p /run/binfmt.d
+ # A 32-bit x86 ELF program or position-independent program (type 2 or 3,
+ # machine 3), whatever its OS/ABI byte says. F: the kernel opens the
+ # helper now, so it also runs inside sandboxes that have no /usr of ours.
+ printf '%s\n' ':wildos-32bit:M::\x7fELF\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x03\x00:\xff\xff\xff\xff\xff\xfe\xfe\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/usr/libexec/wildos/32bit-blocked:F' > "$ENTRY"
+ ;;
+*)
+ rm -f "$ENTRY"
+ ;;
+esac
diff --git a/packages/wildos-system-dialogs/data/wildos-32bit-prompt.service b/packages/wildos-system-dialogs/data/wildos-32bit-prompt.service
new file mode 100644
index 0000000..5dd87db
--- /dev/null
+++ b/packages/wildos-system-dialogs/data/wildos-32bit-prompt.service
@@ -0,0 +1,15 @@
+[Unit]
+Description=Explain 32-bit programs while 32-bit apps are off
+Documentation=https://help.wildos.io/apps/steam-and-32-bit-apps/
+DefaultDependencies=no
+After=local-fs.target
+Before=systemd-binfmt.service sysinit.target shutdown.target
+Conflicts=shutdown.target
+
+[Service]
+Type=oneshot
+RemainAfterExit=yes
+ExecStart=/usr/libexec/wildos/32bit-prompt-setup
+
+[Install]
+WantedBy=sysinit.target
diff --git a/packages/wildos-system-dialogs/debian/changelog b/packages/wildos-system-dialogs/debian/changelog
index 3ca3b2f..da12d71 100644
--- a/packages/wildos-system-dialogs/debian/changelog
+++ b/packages/wildos-system-dialogs/debian/changelog
@@ -1,3 +1,12 @@
+wildos-system-dialogs (0.1.10) trixie; urgency=medium
+
+ * Opening a 32-bit program, such as Steam, while 32-bit apps are off
+ shows a prompt instead of failing silently: turn them on and restart,
+ or not now. It asks once in five minutes however often the program
+ retries, and only while the running system refuses 32-bit programs.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 14:00:00 +0000
+
wildos-system-dialogs (0.1.9) trixie; urgency=medium
* Starting Windows: when Windows starts up from off, the card says it
diff --git a/packages/wildos-system-dialogs/debian/control b/packages/wildos-system-dialogs/debian/control
index 0bedfde..905efd7 100644
--- a/packages/wildos-system-dialogs/debian/control
+++ b/packages/wildos-system-dialogs/debian/control
@@ -49,4 +49,6 @@ Description: Wild OS system dialogs
* "not responding", in place of KWin's own;
* low battery with battery saver, restart to finish updating with a
time of the person's choosing, and the App Bridge's Windows mode
- prompt.
+ prompt;
+ * "32-bit apps are turned off", in place of a bare "Exec format error"
+ when a 32-bit program such as Steam is opened while they are off.
diff --git a/packages/wildos-system-dialogs/debian/wildos-system-dialogs.postinst b/packages/wildos-system-dialogs/debian/wildos-system-dialogs.postinst
index 8c1c7b0..a9585c5 100644
--- a/packages/wildos-system-dialogs/debian/wildos-system-dialogs.postinst
+++ b/packages/wildos-system-dialogs/debian/wildos-system-dialogs.postinst
@@ -9,3 +9,11 @@ if [ "$1" = configure ]; then
fi
#DEBHELPER#
+
+# The 32-bit prompt's entry, registered now rather than at the next start-up
+# (the service above has just written it, if this kernel refuses 32-bit
+# programs). Registering again also picks up a new copy of the helper, which
+# the kernel holds open.
+if [ "$1" = configure ] && [ -f /run/binfmt.d/wildos-32bit.conf ] && [ -x /usr/lib/systemd/systemd-binfmt ]; then
+ /usr/lib/systemd/systemd-binfmt /run/binfmt.d/wildos-32bit.conf || true
+fi
diff --git a/packages/wildos-system-dialogs/debian/wildos-system-dialogs.postrm b/packages/wildos-system-dialogs/debian/wildos-system-dialogs.postrm
index 905aaa0..72aaa08 100644
--- a/packages/wildos-system-dialogs/debian/wildos-system-dialogs.postrm
+++ b/packages/wildos-system-dialogs/debian/wildos-system-dialogs.postrm
@@ -13,6 +13,12 @@ if [ "$1" = remove ] || [ "$1" = abort-install ] || [ "$1" = disappear ]; then
--divert "$helper.kde" "$helper"
fi
+# The kernel holds the 32-bit helper open while its entry is registered.
+if [ "$1" = remove ]; then
+ [ -e /proc/sys/fs/binfmt_misc/wildos-32bit ] && echo -1 > /proc/sys/fs/binfmt_misc/wildos-32bit || true
+ rm -f /run/binfmt.d/wildos-32bit.conf
+fi
+
if [ "$1" = purge ]; then
rm -f /var/lib/wildos/package-sources /var/lib/wildos/package-sources.new
fi
diff --git a/packages/wildos-system-dialogs/qml/Compat32Card.qml b/packages/wildos-system-dialogs/qml/Compat32Card.qml
new file mode 100644
index 0000000..039cd02
--- /dev/null
+++ b/packages/wildos-system-dialogs/qml/Compat32Card.qml
@@ -0,0 +1,62 @@
+import QtQuick
+import WildOS.UI as UI
+
+// "32-bit apps are turned off", when a 32-bit program (Steam, an older
+// game) is opened while they are off. Shown by the session service when
+// 32bit-blocked, standing in for the program, asks for it. mode is "off",
+// "locked" (Strict or Maximum protection, which keep them off) or
+// "pending" (turned on, waiting for a restart).
+PromptCard {
+ id: card
+
+ property string appName
+ property string iconName
+ property string mode: "off"
+ property bool busy: false
+ property string error
+
+ signal cancelled()
+ signal accepted()
+
+ width: 440
+ title: mode === "pending" ? "Restart to use 32-bit apps" : "32-bit apps are turned off"
+ text: {
+ const what = card.appName.length > 0 ? card.appName + " is a 32-bit app" : "This is a 32-bit app";
+ let line;
+ if (mode === "pending") {
+ line = "32-bit apps are turned on and start working once you restart. Open apps are asked to save first.";
+ } else if (mode === "locked") {
+ line = what + ", and Strict and Maximum protection keep 32-bit apps off. To use it, choose Standard protection in Settings > Privacy and security first.";
+ } else {
+ line = what + ", and Wild OS keeps them off for security. Turning them on lets it run, but adds a part of the system that has had serious security flaws. It takes a restart.";
+ }
+ return card.error.length > 0 ? card.error + " " + line : line;
+ }
+
+ picture: AppPicture {
+ iconName: card.iconName.length > 0 ? card.iconName : "application-x-executable"
+ }
+
+ buttons: [
+ UI.Button {
+ id: notNowButton
+ text: "Not now"
+ onClicked: card.cancelled()
+ },
+ UI.Button {
+ id: mainButton
+ kind: "primary"
+ busy: card.busy
+ enabled: !card.busy
+ text: card.mode === "pending" ? "Restart now" : card.mode === "locked" ? "Open Settings" : "Turn on and restart"
+ onClicked: card.accepted()
+ }
+ ]
+
+ Keys.onEscapePressed: card.cancelled()
+ // Enter keeps things as they are: turning 32-bit apps on lowers
+ // protection, so it takes a deliberate click (and the password).
+ function takeFocus() {
+ notNowButton.forceActiveFocus();
+ }
+}
diff --git a/packages/wildos-system-dialogs/qml/PromptWindow.qml b/packages/wildos-system-dialogs/qml/PromptWindow.qml
index 7644d7a..f05a30d 100644
--- a/packages/wildos-system-dialogs/qml/PromptWindow.qml
+++ b/packages/wildos-system-dialogs/qml/PromptWindow.qml
@@ -43,6 +43,7 @@ Window {
case "windowsshutdown": return windowsShutdown;
case "windowsdevices": return windowsDevices;
case "windowsstarting": return windowsStarting;
+ case "compat32": return compat32;
default: return null;
}
}
@@ -134,6 +135,19 @@ Window {
}
}
+ Component {
+ id: compat32
+ Compat32Card {
+ appName: Prompts.info.appName || ""
+ iconName: Prompts.info.iconName || ""
+ mode: Prompts.info.mode || "off"
+ busy: Prompts.info.busy === true
+ error: Prompts.info.error || ""
+ onCancelled: Prompts.dismiss()
+ onAccepted: Prompts.turnOn32bit()
+ }
+ }
+
Component {
id: windowsMode
WindowsModeCard {
diff --git a/packages/wildos-system-dialogs/src/32bit-blocked.c b/packages/wildos-system-dialogs/src/32bit-blocked.c
new file mode 100644
index 0000000..dc15cdb
--- /dev/null
+++ b/packages/wildos-system-dialogs/src/32bit-blocked.c
@@ -0,0 +1,87 @@
+/*
+ * Runs in place of a 32-bit program while 32-bit apps are turned off, so the
+ * person gets a prompt instead of a bare "Exec format error".
+ *
+ * The kernel hands every 32-bit x86 program to this through binfmt_misc
+ * (wildos-32bit-prompt.service registers it only when the running kernel was
+ * started with ia32_emulation=0, so it never stands in for a program that
+ * could have run). It runs as whoever started the program, often inside a
+ * sandbox such as Steam's Flatpak, so it is built static (the sandbox has
+ * its own libraries, or none) and the kernel opens it once at registration
+ * (the F flag), which is why the sandbox's own /usr does not need it.
+ *
+ * It says why on stderr, then asks this user's wildos-dialogs, if there is
+ * one, to show the prompt: one datagram to an abstract socket named after
+ * the user. Abstract sockets belong to the network namespace, so this
+ * reaches the desktop from the host and from sandboxes that share the
+ * network (Steam's does); from one without network the message on stderr
+ * is all there is. The dialogs service checks the sender's uid itself and
+ * decides whether to show anything, so a launcher retrying in a loop can
+ * send as many as it likes.
+ *
+ * It exits 126, what a shell returns for a program it could not run.
+ */
+#include <errno.h>
+#include <fcntl.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+
+/* The app's id when running in a Flatpak, so the prompt can name the app
+ * rather than the program file inside it. */
+static void flatpak_app(char *out, size_t size)
+{
+ out[0] = '\0';
+ FILE *info = fopen("/.flatpak-info", "re");
+ if (!info) {
+ return;
+ }
+ char line[512];
+ int application = 0;
+ while (fgets(line, sizeof line, info)) {
+ line[strcspn(line, "\n")] = '\0';
+ if (line[0] == '[') {
+ application = strcmp(line, "[Application]") == 0;
+ } else if (application && strncmp(line, "name=", 5) == 0) {
+ snprintf(out, size, "%s", line + 5);
+ break;
+ }
+ }
+ fclose(info);
+}
+
+int main(int argc, char **argv)
+{
+ const char *program = argc > 1 ? argv[1] : "This program";
+ const char *name = strrchr(program, '/');
+ name = name ? name + 1 : program;
+
+ fprintf(stderr,
+ "%s: this is a 32-bit program, and 32-bit apps are turned off on this computer for security.\n"
+ "Turn them on in Settings > Privacy and security > Steam and 32-bit apps.\n",
+ name);
+
+ char app[256];
+ flatpak_app(app, sizeof app);
+
+ int fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
+ if (fd >= 0) {
+ struct sockaddr_un addr;
+ memset(&addr, 0, sizeof addr);
+ addr.sun_family = AF_UNIX;
+ int len = snprintf(addr.sun_path + 1, sizeof addr.sun_path - 1, "wildos-32bit-%u", (unsigned)getuid());
+ char message[1024];
+ /* "program\napp", each cut short rather than dropped. */
+ int n = snprintf(message, sizeof message, "%.700s\n%.255s", program, app);
+ if (n > (int)sizeof message - 1) {
+ n = sizeof message - 1;
+ }
+ sendto(fd, message, (size_t)n, MSG_DONTWAIT | MSG_NOSIGNAL, (struct sockaddr *)&addr,
+ (socklen_t)(offsetof(struct sockaddr_un, sun_path) + 1 + len));
+ close(fd);
+ }
+ return 126;
+}
diff --git a/packages/wildos-system-dialogs/src/prompts.cpp b/packages/wildos-system-dialogs/src/prompts.cpp
index b028d9d..d4853a5 100644
--- a/packages/wildos-system-dialogs/src/prompts.cpp
+++ b/packages/wildos-system-dialogs/src/prompts.cpp
@@ -21,9 +21,15 @@
#include <QLocale>
#include <QProcess>
#include <QRegularExpression>
+#include <QSocketNotifier>
#include <QStandardPaths>
#include <csignal>
+#include <cstddef>
+#include <cstring>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
namespace
{
@@ -40,6 +46,11 @@ constexpr int warningSeconds = 60;
// A restart picked for a time the computer slept through is not made
// later without asking again.
constexpr int lateMinutes = 30;
+// After the 32-bit prompt closes, further requests are dropped for this
+// long, so a launcher that retries in a loop raises it once.
+constexpr int compat32QuietMinutes = 5;
+const QString compat32Helper = QStringLiteral("/usr/libexec/wildos/settings-32bit");
+const QString compat32Choice = QStringLiteral("/etc/wildos/32bit");
// UPower's states: 2 discharging, 6 pending discharge.
bool discharging(uint state)
@@ -153,6 +164,9 @@ void Prompts::dismiss()
notNow();
return;
}
+ if (m_showing == QLatin1String("compat32")) {
+ m_compat32QuietUntil = QDateTime::currentDateTime().addSecs(compat32QuietMinutes * 60);
+ }
m_showing.clear();
Q_EMIT showingChanged();
if (m_oneShot) {
@@ -176,6 +190,145 @@ void Prompts::watch()
m_restartCheck.setInterval(30 * 1000);
connect(&m_restartCheck, &QTimer::timeout, this, &Prompts::checkRestart);
m_restartCheck.start();
+ listen32bit();
+}
+
+// One datagram per attempt from 32bit-blocked: "program\napp id". The
+// socket's name carries this user's uid, and the kernel's record of who
+// sent each message is checked as well, so another account cannot raise a
+// prompt here.
+void Prompts::listen32bit()
+{
+ const int fd = ::socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
+ if (fd < 0) {
+ return;
+ }
+ const int on = 1;
+ ::setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &on, sizeof on);
+ sockaddr_un addr{};
+ addr.sun_family = AF_UNIX;
+ const QByteArray name = "wildos-32bit-" + QByteArray::number(::getuid());
+ memcpy(addr.sun_path + 1, name.constData(), size_t(name.size()));
+ if (::bind(fd, reinterpret_cast<sockaddr *>(&addr), socklen_t(offsetof(sockaddr_un, sun_path) + 1 + name.size())) != 0) {
+ ::close(fd);
+ return;
+ }
+ m_compat32Socket = fd;
+ auto *notifier = new QSocketNotifier(fd, QSocketNotifier::Read, this);
+ connect(notifier, &QSocketNotifier::activated, this, &Prompts::read32bit);
+}
+
+void Prompts::read32bit()
+{
+ for (;;) {
+ char buffer[1024];
+ alignas(cmsghdr) char control[CMSG_SPACE(sizeof(ucred))];
+ iovec iov{buffer, sizeof buffer};
+ msghdr msg{};
+ msg.msg_iov = &iov;
+ msg.msg_iovlen = 1;
+ msg.msg_control = control;
+ msg.msg_controllen = sizeof control;
+ const ssize_t n = ::recvmsg(m_compat32Socket, &msg, MSG_DONTWAIT | MSG_CMSG_CLOEXEC);
+ if (n < 0) {
+ return;
+ }
+ bool mine = false;
+ for (cmsghdr *c = CMSG_FIRSTHDR(&msg); c; c = CMSG_NXTHDR(&msg, c)) {
+ if (c->cmsg_level == SOL_SOCKET && c->cmsg_type == SCM_CREDENTIALS) {
+ ucred cred;
+ memcpy(&cred, CMSG_DATA(c), sizeof cred);
+ mine = cred.uid == ::getuid();
+ }
+ }
+ if (!mine) {
+ continue;
+ }
+ const QString text = QString::fromUtf8(buffer, int(n));
+ ask32bit(text.section(QLatin1Char('\n'), 0, 0), text.section(QLatin1Char('\n'), 1, 1));
+ }
+}
+
+QString Prompts::state32bit() const
+{
+ QFile level(QStringLiteral("/etc/wildos/protection-level"));
+ const QByteArray value = level.open(QIODevice::ReadOnly) ? level.readAll().trimmed() : QByteArray();
+ if (value == "strict" || value == "maximum") {
+ return QStringLiteral("locked");
+ }
+ return QFileInfo::exists(compat32Choice) ? QStringLiteral("pending") : QStringLiteral("off");
+}
+
+void Prompts::ask32bit(const QString &program, const QString &appId)
+{
+ // Another prompt already on screen matters more, and one 32-bit prompt
+ // is enough for a while.
+ if (!m_showing.isEmpty() || (m_compat32QuietUntil.isValid() && QDateTime::currentDateTime() < m_compat32QuietUntil)) {
+ return;
+ }
+ // Inside a Flatpak the program is one of the app's files; the app's own
+ // name is the one people know.
+ QString name = QFileInfo(program).fileName();
+ QString icon;
+ if (!appId.isEmpty()) {
+ if (const KService::Ptr service = KService::serviceByDesktopName(appId)) {
+ name = service->name();
+ icon = service->icon();
+ }
+ }
+ m_info = {
+ {QStringLiteral("appName"), name.left(80)},
+ {QStringLiteral("iconName"), icon},
+ {QStringLiteral("mode"), state32bit()},
+ };
+ show(QStringLiteral("compat32"));
+}
+
+void Prompts::turnOn32bit()
+{
+ const QString mode = m_info.value(QStringLiteral("mode")).toString();
+ if (m_demo) {
+ dismiss();
+ return;
+ }
+ if (mode == QLatin1String("locked")) {
+ QProcess::startDetached(QStringLiteral("wildos-settings"), {QStringLiteral("--page"), QStringLiteral("privacy")});
+ dismiss();
+ return;
+ }
+ if (mode == QLatin1String("pending")) {
+ m_compat32QuietUntil = QDateTime::currentDateTime().addSecs(compat32QuietMinutes * 60);
+ restartNow();
+ return;
+ }
+ if (m_info.value(QStringLiteral("busy")).toBool()) {
+ return;
+ }
+ m_info.insert(QStringLiteral("busy"), true);
+ m_info.remove(QStringLiteral("error"));
+ Q_EMIT infoChanged();
+ auto *process = new QProcess(this);
+ connect(process, &QProcess::finished, this, [this, process](int code) {
+ process->deleteLater();
+ if (m_showing != QLatin1String("compat32")) {
+ return;
+ }
+ m_info.insert(QStringLiteral("busy"), false);
+ if (code == 0) {
+ m_compat32QuietUntil = QDateTime::currentDateTime().addSecs(compat32QuietMinutes * 60);
+ restartNow();
+ return;
+ }
+ // A cancelled password changes nothing; the card stays so it can be
+ // tried again or put away. Code 3: the protection level was raised
+ // meanwhile, which the card now says.
+ m_info.insert(QStringLiteral("mode"), state32bit());
+ if (code != 3 && code != 126 && code != 127) {
+ m_info.insert(QStringLiteral("error"), QStringLiteral("32-bit apps could not be turned on."));
+ }
+ Q_EMIT infoChanged();
+ });
+ process->start(QStringLiteral("pkexec"), {compat32Helper, QStringLiteral("on")});
}
void Prompts::readBattery()
@@ -669,5 +822,11 @@ void Prompts::demo(const QString &kind)
QDBusMessage());
} else if (kind == QLatin1String("windowsstarting")) {
windowsStarting(QStringLiteral("Word"), QString(), 60, true);
+ } else if (kind.startsWith(QLatin1String("compat32"))) {
+ // compat32, compat32-locked or compat32-pending
+ const QString mode = kind.section(QLatin1Char('-'), 1);
+ m_info = {{QStringLiteral("appName"), QStringLiteral("Steam")}, {QStringLiteral("iconName"), QStringLiteral("steam")},
+ {QStringLiteral("mode"), mode.isEmpty() ? QStringLiteral("off") : mode}};
+ show(QStringLiteral("compat32"));
}
}
diff --git a/packages/wildos-system-dialogs/src/prompts.h b/packages/wildos-system-dialogs/src/prompts.h
index 92a1139..59670fd 100644
--- a/packages/wildos-system-dialogs/src/prompts.h
+++ b/packages/wildos-system-dialogs/src/prompts.h
@@ -25,6 +25,10 @@
// windowsmode from the App Bridge when a Windows app is opened while
// Windows app support is turned off
//
+// Asked by 32bit-blocked, which stands in for a 32-bit program while the
+// kernel refuses them (a datagram on an abstract socket, see listen32bit):
+// compat32 32-bit apps are off: turn them on and restart, or not now
+//
// Asked by Windows mode over D-Bus (session.h), answered when chosen:
// windowsshutdown Windows apps are open as the session ends (9.9); the
// safe choice, keep, is taken after 60 seconds
@@ -71,6 +75,9 @@ public:
Q_INVOKABLE void answerWindowsShutdown(const QString &choice);
void askWindowsDevices(const QString &appName, const QString &devicesJson, const QDBusMessage &reply);
Q_INVOKABLE void answerWindowsDevices(bool allow, const QString &camera, const QString &microphone);
+ // 32-bit apps: Turn on and restart, Restart now or Open Settings,
+ // whichever the card offers.
+ Q_INVOKABLE void turnOn32bit();
// Windows is starting so an app can open; yields to any other prompt.
void windowsStarting(const QString &appName, const QString &iconName, int seconds, bool cold);
void windowsStartingDone();
@@ -89,6 +96,10 @@ Q_SIGNALS:
private:
void show(const QString &kind);
void readBattery();
+ void listen32bit();
+ void read32bit();
+ void ask32bit(const QString &program, const QString &appId);
+ QString state32bit() const;
void onBatteryChanged();
void checkRestart();
void buildTimes();
@@ -125,4 +136,7 @@ private:
QString safeShutdownAnswer() const;
QDBusMessage m_devicesReply;
QTimer m_shutdownTimer;
+
+ int m_compat32Socket = -1;
+ QDateTime m_compat32QuietUntil;
};