From a8f0db3a37fdeeaecc932d18a11b08e2abf99769 Mon Sep 17 00:00:00 2001 From: sudo-py-dev Date: Tue, 24 Nov 2026 17:01:51 +0200 Subject: [PATCH 1/2] Add read-only drive diagnostics and sector viewer --- README.md | 10 + locales/ar.json | 61 +++++++ locales/de.json | 61 +++++++ locales/en.json | 61 +++++++ locales/es.json | 61 +++++++ locales/fr.json | 61 +++++++ locales/he.json | 61 +++++++ locales/it.json | 61 +++++++ locales/nl.json | 61 +++++++ locales/pt.json | 61 +++++++ locales/ru.json | 61 +++++++ src/drive_check.rs | 265 +++++++++++++++++++++++++++ src/drives.rs | 62 +++++++ src/drives/linux.rs | 167 ++++++++++++++++- src/drives/macos.rs | 154 +++++++++++++++- src/drives/windows.rs | 44 ++++- src/lib.rs | 1 + src/main.rs | 301 +++++++++++++++++++++++++++++- src/partition.rs | 414 ++++++++++++++++++++++++++++++++++++++++++ src/sector_view.rs | 211 +++++++++++++++++++++ src/slint_ui_tests.rs | 97 ++++++++++ src/ui_text.rs | 16 ++ ui/app.slint | 122 ++++++++++++- 23 files changed, 2459 insertions(+), 15 deletions(-) create mode 100644 src/drive_check.rs create mode 100644 src/partition.rs create mode 100644 src/sector_view.rs diff --git a/README.md b/README.md index 5874b3c..1229161 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,16 @@ Pick the file for your computer from the **[latest release](https://github.com/s ``` - **Portable ZIP:** unzip it into a folder (or onto a USB stick) and run the `reclaim` program inside. On Mac and Linux you may first need to run `chmod +x reclaim-*` in that folder. +## Check a drive or disk image + +In **Sources**, select a drive or open a raw image and choose **Quick Drive Check**. The report reads the source header, identifies recognized filesystem signatures, and shows the backing disk and its volumes when the operating system can resolve them. Locked volumes can be selected for diagnostics. + +**SMART and NVMe health** shows readings exposed by the device and operating system. Linux uses UDisks2's most recent readings, Windows queries the storage driver, and macOS reads the NVMe health log through IOKit or displays the SMART status exposed by the driver. Open **Device readings** for the available technical values. A disk image has no live health readings. + +**Partition table** lists primary MBR entries or compares the primary and backup GPT headers and entry arrays, including their checksums, usable bounds, and overlapping entries. Select an entry and choose **Inspect partition** to read its filesystem signature at the indicated offset. Image inspection detects 512-byte and 4096-byte GPT sectors and assumes 512-byte sectors for MBR images. Extended MBR containers are listed at the primary level. All three checks use read-only access. + +**Sector viewer** opens the disk at byte zero. **View bytes** beside a finding jumps to its metadata, and **View partition bytes** jumps to the start of the selected partition. Enter an absolute byte offset such as `1024` or `0x400`, or a logical sector such as `LBA 2`. Previous and Next move through 512-byte windows. **Compare image** shows the same absolute byte range in a second raw image, with differing bytes marked `^^` and missing bytes marked `--`. + ## How to recover your files 1. **Choose the drive** where the files were. Connected drives appear on their own; click **Refresh** after plugging one in. If the drive is encrypted (BitLocker, FileVault, LUKS), unlock it first. diff --git a/locales/ar.json b/locales/ar.json index 3b62cbb..f6ffd21 100644 --- a/locales/ar.json +++ b/locales/ar.json @@ -1,4 +1,65 @@ { + "Sector viewer": "عارض القطاعات", + "View bytes": "عرض البايتات", + "View partition bytes": "عرض بايتات القسم", + "Compare image": "مقارنة صورة", + "Close comparison": "إغلاق المقارنة", + "Byte offset or LBA": "إزاحة بالبايت أو LBA", + "Go": "انتقال", + "Previous": "السابق", + "Next": "التالي", + "Source on the left, comparison on the right. ^^ marks differences and -- marks missing bytes.": "المصدر يسارًا وصورة المقارنة يمينًا. تشير ^^ إلى الاختلافات و-- إلى البايتات المفقودة.", + "Address outside the image or drive.": "العنوان خارج نطاق الصورة أو القرص.", + "Enter a byte offset or LBA, for example 0x200 or LBA 1.": "أدخل إزاحة بالبايت أو عنوان LBA، مثل 0x200 أو LBA 1.", + "Capacity": "السعة", + "Encryption": "التشفير", + "Backing disk": "القرص الفعلي", + "Read access": "إمكانية القراءة", + "Filesystem signature": "توقيع نظام الملفات", + "Read check incomplete": "لم يكتمل فحص القراءة", + "Byte offset": "الإزاحة بالبايت", + "Length": "الطول", + "Temperature": "درجة الحرارة", + "Estimated endurance used": "نسبة التحمل المستهلكة تقديريًا", + "Media errors": "أخطاء الوسيط", + "Bad sectors": "قطاعات تالفة", + "Source header readable": "ترويسة المصدر قابلة للقراءة", + "Logical sector size": "حجم القطاع المنطقي", + "Unrecognized": "غير معروف", + "Header and array checksums verified": "تم التحقق من مجموعي تدقيق الترويسة والجدول", + "Unknown or unreported": "غير معروف أو لم يُبلّغ عنه", + "Unavailable. The device, adapter, or system driver did not expose health data.": "لم يوفّر الجهاز أو المحوّل أو برنامج التشغيل بيانات الحالة.", + "Disk images contain no live device health readings.": "لا تتضمن صور الأقراص قراءات مباشرة لحالة الجهاز.", + "Backing disk unavailable. Open a whole-disk image to inspect its partition table.": "القرص الفعلي غير متاح. افتح صورة للقرص بالكامل لفحص جدول أقسامه.", + "Partition check incomplete · {e}": "لم يكتمل فحص الأقسام · {e}", + "NVMe · no critical warnings reported": "NVMe · لا تحذيرات حرجة", + "NVMe warning · {}": "تحذير NVMe · {}", + "SMART · drive predicts failure": "SMART · يتوقع القرص حدوث عطل", + "SMART · no failure predicted": "SMART · لا يتوقع حدوث عطل", + "SMART · {status}": "SMART · {status}", + "NVMe critical warning · 0x{warning:02x}": "تحذير NVMe حرج · 0x{warning:02x}", + "Partition read incomplete · {e}": "لم تكتمل قراءة القسم · {e}", + "Missing protective MBR": "سجل MBR الوقائي مفقود", + "Primary GPT": "جدول GPT الأساسي", + "Backup GPT": "جدول GPT الاحتياطي", + "GPT copies disagree. Showing primary entries.": "تختلف نسختا GPT. تظهر الإدخالات الأساسية.", + "MBR · primary entries": "MBR · الإدخالات الأساسية", + "Entry {} has zero length": "طول الإدخال {} يساوي صفرًا", + "Extended container (logical entries uninspected)": "قسم ممتد (لم تُفحص الإدخالات المنطقية)", + "MBR type 0x{t:02x}": "نوع MBR ‏0x{t:02x}", + "No recognized disk partition table. A volume image may contain only a filesystem.": "لم يُتعرّف على جدول أقسام. قد تحتوي صورة وحدة التخزين على نظام ملفات فقط.", + "Entry {} exceeds usable bounds or is reversed": "يتجاوز الإدخال {} الحدود المتاحة أو أن نطاقه معكوس", + "Entry {} overlaps a previous entry": "يتداخل الإدخال {} مع إدخال سابق", + "Drive check interrupted": "انقطع فحص القرص", + "Invalid partition": "قسم غير صالح", + "Disk unavailable": "القرص غير متاح", + "Empty or unknown source size": "المصدر فارغ أو حجمه غير معروف", + "Quick Drive Check": "فحص سريع للقرص", + "SMART and NVMe health": "حالة SMART وNVMe", + "Partition table": "جدول الأقسام", + "Inspect partition": "فحص القسم", + "Device readings": "قراءات الجهاز", + "Reading drive information…": "جارٍ قراءة معلومات القرص…", "All files": "كل الملفات", "Appearance": "المظهر", "Debug logging": "تسجيل معلومات التصحيح", diff --git a/locales/de.json b/locales/de.json index 22d06cc..ad9a1e8 100644 --- a/locales/de.json +++ b/locales/de.json @@ -1,4 +1,65 @@ { + "Sector viewer": "Sektoransicht", + "View bytes": "Bytes anzeigen", + "View partition bytes": "Partitionsbytes anzeigen", + "Compare image": "Abbild vergleichen", + "Close comparison": "Vergleich schließen", + "Byte offset or LBA": "Byte-Offset oder LBA", + "Go": "Anzeigen", + "Previous": "Zurück", + "Next": "Weiter", + "Source on the left, comparison on the right. ^^ marks differences and -- marks missing bytes.": "Quelle links, Vergleich rechts. ^^ zeigt Unterschiede, -- fehlende Bytes.", + "Address outside the image or drive.": "Adresse außerhalb des Abbilds oder Laufwerks.", + "Enter a byte offset or LBA, for example 0x200 or LBA 1.": "Geben Sie einen Byte-Offset oder LBA ein, etwa 0x200 oder LBA 1.", + "Capacity": "Kapazität", + "Encryption": "Verschlüsselung", + "Backing disk": "Physischer Datenträger", + "Read access": "Lesezugriff", + "Filesystem signature": "Dateisystemsignatur", + "Read check incomplete": "Leseprüfung unvollständig", + "Byte offset": "Byte-Offset", + "Length": "Länge", + "Temperature": "Temperatur", + "Estimated endurance used": "Geschätzter Verschleiß", + "Media errors": "Medienfehler", + "Bad sectors": "Fehlerhafte Sektoren", + "Source header readable": "Quellkopf lesbar", + "Logical sector size": "Logische Sektorgröße", + "Unrecognized": "Nicht erkannt", + "Header and array checksums verified": "Prüfsummen von Kopf und Tabelle bestätigt", + "Unknown or unreported": "Unbekannt oder nicht gemeldet", + "Unavailable. The device, adapter, or system driver did not expose health data.": "Gerät, Adapter oder Treiber liefert keine Zustandsdaten.", + "Disk images contain no live device health readings.": "Datenträgerabbilder enthalten keine aktuellen Gerätemesswerte.", + "Backing disk unavailable. Open a whole-disk image to inspect its partition table.": "Physischer Datenträger nicht verfügbar. Öffnen Sie ein vollständiges Datenträgerabbild, um die Partitionstabelle zu prüfen.", + "Partition check incomplete · {e}": "Partitionsprüfung unvollständig · {e}", + "NVMe · no critical warnings reported": "NVMe · keine kritischen Warnungen", + "NVMe warning · {}": "NVMe-Warnung · {}", + "SMART · drive predicts failure": "SMART · Laufwerk meldet drohenden Ausfall", + "SMART · no failure predicted": "SMART · kein Ausfall vorhergesagt", + "SMART · {status}": "SMART · {status}", + "NVMe critical warning · 0x{warning:02x}": "Kritische NVMe-Warnung · 0x{warning:02x}", + "Partition read incomplete · {e}": "Partition unvollständig gelesen · {e}", + "Missing protective MBR": "Schutz-MBR fehlt", + "Primary GPT": "Primäre GPT", + "Backup GPT": "Sicherungs-GPT", + "GPT copies disagree. Showing primary entries.": "GPT-Kopien weichen ab. Primäre Einträge werden angezeigt.", + "MBR · primary entries": "MBR · primäre Einträge", + "Entry {} has zero length": "Eintrag {} hat die Länge null", + "Extended container (logical entries uninspected)": "Erweiterte Partition (logische Einträge ungeprüft)", + "MBR type 0x{t:02x}": "MBR-Typ 0x{t:02x}", + "No recognized disk partition table. A volume image may contain only a filesystem.": "Keine Partitionstabelle erkannt. Ein Volume-Abbild kann nur ein Dateisystem enthalten.", + "Entry {} exceeds usable bounds or is reversed": "Eintrag {} liegt außerhalb des nutzbaren Bereichs oder ist umgekehrt", + "Entry {} overlaps a previous entry": "Eintrag {} überschneidet sich mit einem vorherigen Eintrag", + "Drive check interrupted": "Laufwerksprüfung unterbrochen", + "Invalid partition": "Ungültige Partition", + "Disk unavailable": "Datenträger nicht verfügbar", + "Empty or unknown source size": "Quelle leer oder Größe unbekannt", + "Quick Drive Check": "Laufwerk prüfen", + "SMART and NVMe health": "SMART- und NVMe-Zustand", + "Partition table": "Partitionstabelle", + "Inspect partition": "Partition prüfen", + "Device readings": "Gerätemesswerte", + "Reading drive information…": "Laufwerksinformationen werden gelesen…", "All files": "Alle Dateien", "Appearance": "Darstellung", "Debug logging": "Debug-Protokollierung", diff --git a/locales/en.json b/locales/en.json index 2bc528f..73a0635 100644 --- a/locales/en.json +++ b/locales/en.json @@ -1,4 +1,65 @@ { + "Sector viewer": "Sector viewer", + "View bytes": "View bytes", + "View partition bytes": "View partition bytes", + "Compare image": "Compare image", + "Close comparison": "Close comparison", + "Byte offset or LBA": "Byte offset or LBA", + "Go": "Go", + "Previous": "Previous", + "Next": "Next", + "Source on the left, comparison on the right. ^^ marks differences and -- marks missing bytes.": "Source on the left, comparison on the right. ^^ marks differences and -- marks missing bytes.", + "Address outside the image or drive.": "Address outside the image or drive.", + "Enter a byte offset or LBA, for example 0x200 or LBA 1.": "Enter a byte offset or LBA, for example 0x200 or LBA 1.", + "Capacity": "Capacity", + "Encryption": "Encryption", + "Backing disk": "Backing disk", + "Read access": "Read access", + "Filesystem signature": "Filesystem signature", + "Read check incomplete": "Read check incomplete", + "Byte offset": "Byte offset", + "Length": "Length", + "Temperature": "Temperature", + "Estimated endurance used": "Estimated endurance used", + "Media errors": "Media errors", + "Bad sectors": "Bad sectors", + "Source header readable": "Source header readable", + "Logical sector size": "Logical sector size", + "Unrecognized": "Unrecognized", + "Header and array checksums verified": "Header and array checksums verified", + "Unknown or unreported": "Unknown or unreported", + "Unavailable. The device, adapter, or system driver did not expose health data.": "Unavailable. The device, adapter, or system driver did not expose health data.", + "Disk images contain no live device health readings.": "Disk images contain no live device health readings.", + "Backing disk unavailable. Open a whole-disk image to inspect its partition table.": "Backing disk unavailable. Open a whole-disk image to inspect its partition table.", + "Partition check incomplete · {e}": "Partition check incomplete · {e}", + "NVMe · no critical warnings reported": "NVMe · no critical warnings reported", + "NVMe warning · {}": "NVMe warning · {}", + "SMART · drive predicts failure": "SMART · drive predicts failure", + "SMART · no failure predicted": "SMART · no failure predicted", + "SMART · {status}": "SMART · {status}", + "NVMe critical warning · 0x{warning:02x}": "NVMe critical warning · 0x{warning:02x}", + "Partition read incomplete · {e}": "Partition read incomplete · {e}", + "Missing protective MBR": "Missing protective MBR", + "Primary GPT": "Primary GPT", + "Backup GPT": "Backup GPT", + "GPT copies disagree. Showing primary entries.": "GPT copies disagree. Showing primary entries.", + "MBR · primary entries": "MBR · primary entries", + "Entry {} has zero length": "Entry {} has zero length", + "Extended container (logical entries uninspected)": "Extended container (logical entries uninspected)", + "MBR type 0x{t:02x}": "MBR type 0x{t:02x}", + "No recognized disk partition table. A volume image may contain only a filesystem.": "No recognized disk partition table. A volume image may contain only a filesystem.", + "Entry {} exceeds usable bounds or is reversed": "Entry {} exceeds usable bounds or is reversed", + "Entry {} overlaps a previous entry": "Entry {} overlaps a previous entry", + "Drive check interrupted": "Drive check interrupted", + "Invalid partition": "Invalid partition", + "Disk unavailable": "Disk unavailable", + "Empty or unknown source size": "Empty or unknown source size", + "Quick Drive Check": "Quick Drive Check", + "SMART and NVMe health": "SMART and NVMe health", + "Partition table": "Partition table", + "Inspect partition": "Inspect partition", + "Device readings": "Device readings", + "Reading drive information…": "Reading drive information…", "All files": "All files", "Appearance": "Appearance", "Debug logging": "Debug logging", diff --git a/locales/es.json b/locales/es.json index 013ef43..039bfbd 100644 --- a/locales/es.json +++ b/locales/es.json @@ -1,4 +1,65 @@ { + "Sector viewer": "Visor de sectores", + "View bytes": "Ver bytes", + "View partition bytes": "Ver bytes de la partición", + "Compare image": "Comparar imagen", + "Close comparison": "Cerrar comparación", + "Byte offset or LBA": "Desplazamiento en bytes o LBA", + "Go": "Ir", + "Previous": "Anterior", + "Next": "Siguiente", + "Source on the left, comparison on the right. ^^ marks differences and -- marks missing bytes.": "Origen a la izquierda y comparación a la derecha. ^^ indica diferencias y -- bytes ausentes.", + "Address outside the image or drive.": "Dirección fuera de la imagen o la unidad.", + "Enter a byte offset or LBA, for example 0x200 or LBA 1.": "Introduzca un desplazamiento en bytes o LBA, por ejemplo 0x200 o LBA 1.", + "Capacity": "Capacidad", + "Encryption": "Cifrado", + "Backing disk": "Disco físico", + "Read access": "Acceso de lectura", + "Filesystem signature": "Firma del sistema de archivos", + "Read check incomplete": "Lectura incompleta", + "Byte offset": "Desplazamiento en bytes", + "Length": "Longitud", + "Temperature": "Temperatura", + "Estimated endurance used": "Resistencia consumida estimada", + "Media errors": "Errores del medio", + "Bad sectors": "Sectores defectuosos", + "Source header readable": "Cabecera de origen legible", + "Logical sector size": "Tamaño del sector lógico", + "Unrecognized": "No reconocido", + "Header and array checksums verified": "Sumas de la cabecera y la tabla verificadas", + "Unknown or unreported": "Desconocido o sin informar", + "Unavailable. The device, adapter, or system driver did not expose health data.": "El dispositivo, adaptador o controlador no proporciona datos de estado.", + "Disk images contain no live device health readings.": "Las imágenes de disco no contienen lecturas en vivo del dispositivo.", + "Backing disk unavailable. Open a whole-disk image to inspect its partition table.": "Disco físico no disponible. Abra una imagen del disco completo para inspeccionar su tabla.", + "Partition check incomplete · {e}": "Comprobación de particiones incompleta · {e}", + "NVMe · no critical warnings reported": "NVMe · sin alertas críticas", + "NVMe warning · {}": "Alerta NVMe · {}", + "SMART · drive predicts failure": "SMART · el disco prevé un fallo", + "SMART · no failure predicted": "SMART · no se prevé un fallo", + "SMART · {status}": "SMART · {status}", + "NVMe critical warning · 0x{warning:02x}": "Alerta crítica NVMe · 0x{warning:02x}", + "Partition read incomplete · {e}": "Lectura de partición incompleta · {e}", + "Missing protective MBR": "Falta el MBR protector", + "Primary GPT": "GPT principal", + "Backup GPT": "GPT de respaldo", + "GPT copies disagree. Showing primary entries.": "Las copias GPT difieren. Se muestran las entradas principales.", + "MBR · primary entries": "MBR · entradas principales", + "Entry {} has zero length": "La entrada {} tiene longitud cero", + "Extended container (logical entries uninspected)": "Partición extendida (entradas lógicas sin comprobar)", + "MBR type 0x{t:02x}": "Tipo MBR 0x{t:02x}", + "No recognized disk partition table. A volume image may contain only a filesystem.": "No se reconoce la tabla de particiones. Una imagen de volumen puede contener solo un sistema de archivos.", + "Entry {} exceeds usable bounds or is reversed": "La entrada {} excede los límites utilizables o está invertida", + "Entry {} overlaps a previous entry": "La entrada {} se solapa con una anterior", + "Drive check interrupted": "Comprobación interrumpida", + "Invalid partition": "Partición no válida", + "Disk unavailable": "Disco no disponible", + "Empty or unknown source size": "Fuente vacía o tamaño desconocido", + "Quick Drive Check": "Comprobar disco", + "SMART and NVMe health": "Estado SMART y NVMe", + "Partition table": "Tabla de particiones", + "Inspect partition": "Inspeccionar partición", + "Device readings": "Lecturas del dispositivo", + "Reading drive information…": "Leyendo información del disco…", "All files": "Todos los archivos", "Appearance": "Apariencia", "Debug logging": "Registro de depuración", diff --git a/locales/fr.json b/locales/fr.json index 44dd31f..13b5c5d 100644 --- a/locales/fr.json +++ b/locales/fr.json @@ -1,4 +1,65 @@ { + "Sector viewer": "Vue des secteurs", + "View bytes": "Voir les octets", + "View partition bytes": "Voir les octets de la partition", + "Compare image": "Comparer une image", + "Close comparison": "Fermer la comparaison", + "Byte offset or LBA": "Décalage en octets ou LBA", + "Go": "Aller", + "Previous": "Précédent", + "Next": "Suivant", + "Source on the left, comparison on the right. ^^ marks differences and -- marks missing bytes.": "Source à gauche, comparaison à droite. ^^ indique les différences et -- les octets manquants.", + "Address outside the image or drive.": "Adresse hors de l’image ou du disque.", + "Enter a byte offset or LBA, for example 0x200 or LBA 1.": "Saisissez un décalage en octets ou une LBA, par exemple 0x200 ou LBA 1.", + "Capacity": "Capacité", + "Encryption": "Chiffrement", + "Backing disk": "Disque physique", + "Read access": "Accès en lecture", + "Filesystem signature": "Signature du système de fichiers", + "Read check incomplete": "Vérification de lecture incomplète", + "Byte offset": "Décalage en octets", + "Length": "Longueur", + "Temperature": "Température", + "Estimated endurance used": "Endurance consommée estimée", + "Media errors": "Erreurs de support", + "Bad sectors": "Secteurs défectueux", + "Source header readable": "En-tête de la source lisible", + "Logical sector size": "Taille de secteur logique", + "Unrecognized": "Non reconnu", + "Header and array checksums verified": "Sommes de contrôle de l’en-tête et de la table vérifiées", + "Unknown or unreported": "Inconnu ou non communiqué", + "Unavailable. The device, adapter, or system driver did not expose health data.": "Le périphérique, l’adaptateur ou le pilote ne fournit aucune donnée de santé.", + "Disk images contain no live device health readings.": "Les images disque ne contiennent aucune mesure en direct.", + "Backing disk unavailable. Open a whole-disk image to inspect its partition table.": "Disque physique indisponible. Ouvrez une image du disque entier pour examiner sa table des partitions.", + "Partition check incomplete · {e}": "Vérification des partitions incomplète · {e}", + "NVMe · no critical warnings reported": "NVMe · aucune alerte critique", + "NVMe warning · {}": "Alerte NVMe · {}", + "SMART · drive predicts failure": "SMART · panne prévue par le disque", + "SMART · no failure predicted": "SMART · aucune panne prévue", + "SMART · {status}": "SMART · {status}", + "NVMe critical warning · 0x{warning:02x}": "Alerte NVMe critique · 0x{warning:02x}", + "Partition read incomplete · {e}": "Lecture de la partition incomplète · {e}", + "Missing protective MBR": "MBR de protection manquant", + "Primary GPT": "GPT principale", + "Backup GPT": "GPT de secours", + "GPT copies disagree. Showing primary entries.": "Les copies GPT diffèrent. Les entrées principales sont affichées.", + "MBR · primary entries": "MBR · entrées principales", + "Entry {} has zero length": "L’entrée {} est de longueur nulle", + "Extended container (logical entries uninspected)": "Partition étendue (entrées logiques non vérifiées)", + "MBR type 0x{t:02x}": "Type MBR 0x{t:02x}", + "No recognized disk partition table. A volume image may contain only a filesystem.": "Aucune table des partitions reconnue. Une image de volume peut contenir uniquement un système de fichiers.", + "Entry {} exceeds usable bounds or is reversed": "L’entrée {} dépasse les limites utilisables ou est inversée", + "Entry {} overlaps a previous entry": "L’entrée {} chevauche une entrée précédente", + "Drive check interrupted": "Vérification du disque interrompue", + "Invalid partition": "Partition non valide", + "Disk unavailable": "Disque indisponible", + "Empty or unknown source size": "Source vide ou taille inconnue", + "Quick Drive Check": "Vérification du disque", + "SMART and NVMe health": "État SMART et NVMe", + "Partition table": "Table des partitions", + "Inspect partition": "Inspecter la partition", + "Device readings": "Mesures du périphérique", + "Reading drive information…": "Lecture des informations du disque…", "All files": "Tous les fichiers", "Appearance": "Apparence", "Debug logging": "Journal de débogage", diff --git a/locales/he.json b/locales/he.json index 6237eec..957a028 100644 --- a/locales/he.json +++ b/locales/he.json @@ -1,4 +1,65 @@ { + "Sector viewer": "מציג סקטורים", + "View bytes": "הצגת בתים", + "View partition bytes": "הצגת בתי המחיצה", + "Compare image": "השוואת קובץ דמות", + "Close comparison": "סגירת השוואה", + "Byte offset or LBA": "היסט בבתים או LBA", + "Go": "מעבר", + "Previous": "הקודם", + "Next": "הבא", + "Source on the left, comparison on the right. ^^ marks differences and -- marks missing bytes.": "המקור משמאל וקובץ ההשוואה מימין. ^^ מסמן הבדלים ו־-- מסמן בתים חסרים.", + "Address outside the image or drive.": "הכתובת מחוץ לתחום הכונן או קובץ הדמות.", + "Enter a byte offset or LBA, for example 0x200 or LBA 1.": "יש להזין היסט בבתים או LBA, למשל 0x200 או LBA 1.", + "Capacity": "קיבולת", + "Encryption": "הצפנה", + "Backing disk": "כונן פיזי", + "Read access": "גישת קריאה", + "Filesystem signature": "חתימת מערכת הקבצים", + "Read check incomplete": "בדיקת הקריאה לא הושלמה", + "Byte offset": "היסט בבתים", + "Length": "אורך", + "Temperature": "טמפרטורה", + "Estimated endurance used": "בלאי משוער", + "Media errors": "שגיאות מדיה", + "Bad sectors": "סקטורים פגומים", + "Source header readable": "כותרת המקור קריאה", + "Logical sector size": "גודל סקטור לוגי", + "Unrecognized": "לא זוהה", + "Header and array checksums verified": "סכומי הביקורת של הכותרת והטבלה אומתו", + "Unknown or unreported": "לא ידוע או לא דווח", + "Unavailable. The device, adapter, or system driver did not expose health data.": "ההתקן, המתאם או מנהל ההתקן לא סיפקו נתוני תקינות.", + "Disk images contain no live device health readings.": "קובצי דמות כונן אינם כוללים נתוני תקינות בזמן אמת.", + "Backing disk unavailable. Open a whole-disk image to inspect its partition table.": "הכונן הפיזי אינו זמין. יש לפתוח קובץ דמות של כונן שלם כדי לבדוק את טבלת המחיצות.", + "Partition check incomplete · {e}": "בדיקת המחיצות לא הושלמה · {e}", + "NVMe · no critical warnings reported": "NVMe · לא דווחו אזהרות קריטיות", + "NVMe warning · {}": "אזהרת NVMe · {}", + "SMART · drive predicts failure": "SMART · הכונן צופה כשל", + "SMART · no failure predicted": "SMART · לא צפוי כשל", + "SMART · {status}": "SMART · {status}", + "NVMe critical warning · 0x{warning:02x}": "אזהרת NVMe קריטית · 0x{warning:02x}", + "Partition read incomplete · {e}": "קריאת המחיצה לא הושלמה · {e}", + "Missing protective MBR": "חסר MBR מגן", + "Primary GPT": "GPT ראשי", + "Backup GPT": "GPT לגיבוי", + "GPT copies disagree. Showing primary entries.": "עותקי GPT שונים. מוצגות הרשומות הראשיות.", + "MBR · primary entries": "MBR · רשומות ראשיות", + "Entry {} has zero length": "אורך רשומה {} הוא אפס", + "Extended container (logical entries uninspected)": "מחיצה מורחבת (הרשומות הלוגיות לא נבדקו)", + "MBR type 0x{t:02x}": "סוג MBR ‏0x{t:02x}", + "No recognized disk partition table. A volume image may contain only a filesystem.": "לא זוהתה טבלת מחיצות. ייתכן שקובץ דמות של אמצעי אחסון כולל מערכת קבצים בלבד.", + "Entry {} exceeds usable bounds or is reversed": "רשומה {} חורגת מהטווח המותר או הפוכה", + "Entry {} overlaps a previous entry": "רשומה {} חופפת לרשומה קודמת", + "Drive check interrupted": "בדיקת הכונן הופסקה", + "Invalid partition": "מחיצה לא תקינה", + "Disk unavailable": "הכונן אינו זמין", + "Empty or unknown source size": "המקור ריק או שגודלו אינו ידוע", + "Quick Drive Check": "בדיקת כונן מהירה", + "SMART and NVMe health": "מצב SMART ו־NVMe", + "Partition table": "טבלת מחיצות", + "Inspect partition": "בדיקת מחיצה", + "Device readings": "נתוני ההתקן", + "Reading drive information…": "נתוני הכונן נקראים…", "All files": "כל הקבצים", "Appearance": "מראה", "Debug logging": "תיעוד לצורכי איתור תקלות", diff --git a/locales/it.json b/locales/it.json index 5eed344..eab0685 100644 --- a/locales/it.json +++ b/locales/it.json @@ -1,4 +1,65 @@ { + "Sector viewer": "Visualizzatore settori", + "View bytes": "Mostra byte", + "View partition bytes": "Mostra byte della partizione", + "Compare image": "Confronta immagine", + "Close comparison": "Chiudi confronto", + "Byte offset or LBA": "Offset in byte o LBA", + "Go": "Vai", + "Previous": "Precedente", + "Next": "Successivo", + "Source on the left, comparison on the right. ^^ marks differences and -- marks missing bytes.": "Origine a sinistra, confronto a destra. ^^ indica differenze e -- byte mancanti.", + "Address outside the image or drive.": "Indirizzo fuori dall’immagine o dal disco.", + "Enter a byte offset or LBA, for example 0x200 or LBA 1.": "Inserire un offset in byte o LBA, ad esempio 0x200 o LBA 1.", + "Capacity": "Capacità", + "Encryption": "Cifratura", + "Backing disk": "Disco fisico", + "Read access": "Accesso in lettura", + "Filesystem signature": "Firma del file system", + "Read check incomplete": "Verifica di lettura incompleta", + "Byte offset": "Offset in byte", + "Length": "Lunghezza", + "Temperature": "Temperatura", + "Estimated endurance used": "Durata stimata consumata", + "Media errors": "Errori del supporto", + "Bad sectors": "Settori difettosi", + "Source header readable": "Intestazione sorgente leggibile", + "Logical sector size": "Dimensione settore logico", + "Unrecognized": "Non riconosciuto", + "Header and array checksums verified": "Checksum di intestazione e tabella verificati", + "Unknown or unreported": "Sconosciuto o non segnalato", + "Unavailable. The device, adapter, or system driver did not expose health data.": "Il dispositivo, l’adattatore o il driver non fornisce dati sullo stato.", + "Disk images contain no live device health readings.": "Le immagini disco non contengono letture in tempo reale.", + "Backing disk unavailable. Open a whole-disk image to inspect its partition table.": "Disco fisico non disponibile. Aprire un’immagine del disco intero per esaminare la tabella.", + "Partition check incomplete · {e}": "Controllo partizioni incompleto · {e}", + "NVMe · no critical warnings reported": "NVMe · nessun avviso critico", + "NVMe warning · {}": "Avviso NVMe · {}", + "SMART · drive predicts failure": "SMART · il disco prevede un guasto", + "SMART · no failure predicted": "SMART · nessun guasto previsto", + "SMART · {status}": "SMART · {status}", + "NVMe critical warning · 0x{warning:02x}": "Avviso critico NVMe · 0x{warning:02x}", + "Partition read incomplete · {e}": "Lettura della partizione incompleta · {e}", + "Missing protective MBR": "MBR protettivo mancante", + "Primary GPT": "GPT primaria", + "Backup GPT": "GPT di riserva", + "GPT copies disagree. Showing primary entries.": "Le copie GPT differiscono. Sono mostrate le voci primarie.", + "MBR · primary entries": "MBR · voci primarie", + "Entry {} has zero length": "La voce {} ha lunghezza zero", + "Extended container (logical entries uninspected)": "Partizione estesa (voci logiche non esaminate)", + "MBR type 0x{t:02x}": "Tipo MBR 0x{t:02x}", + "No recognized disk partition table. A volume image may contain only a filesystem.": "Nessuna tabella riconosciuta. Un’immagine del volume può contenere solo un file system.", + "Entry {} exceeds usable bounds or is reversed": "La voce {} supera i limiti utilizzabili o è invertita", + "Entry {} overlaps a previous entry": "La voce {} si sovrappone a una precedente", + "Drive check interrupted": "Controllo interrotto", + "Invalid partition": "Partizione non valida", + "Disk unavailable": "Disco non disponibile", + "Empty or unknown source size": "Sorgente vuota o dimensione sconosciuta", + "Quick Drive Check": "Controllo rapido disco", + "SMART and NVMe health": "Stato SMART e NVMe", + "Partition table": "Tabella delle partizioni", + "Inspect partition": "Ispeziona partizione", + "Device readings": "Letture del dispositivo", + "Reading drive information…": "Lettura delle informazioni del disco…", "All files": "Tutti i file", "Appearance": "Aspetto", "Debug logging": "Registro di debug", diff --git a/locales/nl.json b/locales/nl.json index 8a7db98..9b0c31f 100644 --- a/locales/nl.json +++ b/locales/nl.json @@ -1,4 +1,65 @@ { + "Sector viewer": "Sectorweergave", + "View bytes": "Bytes bekijken", + "View partition bytes": "Partitiebytes bekijken", + "Compare image": "Schijfkopie vergelijken", + "Close comparison": "Vergelijking sluiten", + "Byte offset or LBA": "Bytepositie of LBA", + "Go": "Ga", + "Previous": "Vorige", + "Next": "Volgende", + "Source on the left, comparison on the right. ^^ marks differences and -- marks missing bytes.": "Bron links, vergelijking rechts. ^^ markeert verschillen en -- ontbrekende bytes.", + "Address outside the image or drive.": "Adres buiten de schijfkopie of schijf.", + "Enter a byte offset or LBA, for example 0x200 or LBA 1.": "Voer een bytepositie of LBA in, bijvoorbeeld 0x200 of LBA 1.", + "Capacity": "Capaciteit", + "Encryption": "Versleuteling", + "Backing disk": "Fysieke schijf", + "Read access": "Leestoegang", + "Filesystem signature": "Bestandssysteemsignatuur", + "Read check incomplete": "Leescontrole onvolledig", + "Byte offset": "Bytepositie", + "Length": "Lengte", + "Temperature": "Temperatuur", + "Estimated endurance used": "Geschat verbruik van levensduur", + "Media errors": "Mediafouten", + "Bad sectors": "Defecte sectoren", + "Source header readable": "Bronheader leesbaar", + "Logical sector size": "Logische sectorgrootte", + "Unrecognized": "Niet herkend", + "Header and array checksums verified": "Controlesommen van header en tabel geverifieerd", + "Unknown or unreported": "Onbekend of niet gemeld", + "Unavailable. The device, adapter, or system driver did not expose health data.": "Het apparaat, de adapter of het stuurprogramma geeft geen gezondheidsgegevens door.", + "Disk images contain no live device health readings.": "Schijfkopieën bevatten geen actuele apparaatmetingen.", + "Backing disk unavailable. Open a whole-disk image to inspect its partition table.": "Fysieke schijf niet beschikbaar. Open een volledige schijfkopie om de partitietabel te bekijken.", + "Partition check incomplete · {e}": "Partitiecontrole onvolledig · {e}", + "NVMe · no critical warnings reported": "NVMe · geen kritieke waarschuwingen", + "NVMe warning · {}": "NVMe-waarschuwing · {}", + "SMART · drive predicts failure": "SMART · schijf voorspelt een storing", + "SMART · no failure predicted": "SMART · geen storing voorspeld", + "SMART · {status}": "SMART · {status}", + "NVMe critical warning · 0x{warning:02x}": "Kritieke NVMe-waarschuwing · 0x{warning:02x}", + "Partition read incomplete · {e}": "Partitie onvolledig gelezen · {e}", + "Missing protective MBR": "Beschermende MBR ontbreekt", + "Primary GPT": "Primaire GPT", + "Backup GPT": "Reserve-GPT", + "GPT copies disagree. Showing primary entries.": "GPT-kopieën verschillen. De primaire vermeldingen worden getoond.", + "MBR · primary entries": "MBR · primaire vermeldingen", + "Entry {} has zero length": "Vermelding {} heeft lengte nul", + "Extended container (logical entries uninspected)": "Uitgebreide partitie (logische vermeldingen niet onderzocht)", + "MBR type 0x{t:02x}": "MBR-type 0x{t:02x}", + "No recognized disk partition table. A volume image may contain only a filesystem.": "Geen partitietabel herkend. Een volumekopie kan alleen een bestandssysteem bevatten.", + "Entry {} exceeds usable bounds or is reversed": "Vermelding {} valt buiten de grenzen of is omgekeerd", + "Entry {} overlaps a previous entry": "Vermelding {} overlapt een eerdere vermelding", + "Drive check interrupted": "Schijfcontrole onderbroken", + "Invalid partition": "Ongeldige partitie", + "Disk unavailable": "Schijf niet beschikbaar", + "Empty or unknown source size": "Lege bron of onbekende grootte", + "Quick Drive Check": "Schijfcontrole", + "SMART and NVMe health": "SMART- en NVMe-status", + "Partition table": "Partitietabel", + "Inspect partition": "Partitie inspecteren", + "Device readings": "Apparaatmetingen", + "Reading drive information…": "Schijfinformatie lezen…", "All files": "Alle bestanden", "Appearance": "Uiterlijk", "Debug logging": "Foutopsporingslogboek", diff --git a/locales/pt.json b/locales/pt.json index f93dee5..1c032bc 100644 --- a/locales/pt.json +++ b/locales/pt.json @@ -1,4 +1,65 @@ { + "Sector viewer": "Visualizador de setores", + "View bytes": "Ver bytes", + "View partition bytes": "Ver bytes da partição", + "Compare image": "Comparar imagem", + "Close comparison": "Fechar comparação", + "Byte offset or LBA": "Deslocamento em bytes ou LBA", + "Go": "Ir", + "Previous": "Anterior", + "Next": "Próximo", + "Source on the left, comparison on the right. ^^ marks differences and -- marks missing bytes.": "Origem à esquerda, comparação à direita. ^^ marca diferenças e -- indica bytes ausentes.", + "Address outside the image or drive.": "Endereço fora da imagem ou do disco.", + "Enter a byte offset or LBA, for example 0x200 or LBA 1.": "Insira um deslocamento em bytes ou LBA, por exemplo 0x200 ou LBA 1.", + "Capacity": "Capacidade", + "Encryption": "Criptografia", + "Backing disk": "Disco físico", + "Read access": "Acesso de leitura", + "Filesystem signature": "Assinatura do sistema de arquivos", + "Read check incomplete": "Verificação de leitura incompleta", + "Byte offset": "Deslocamento em bytes", + "Length": "Comprimento", + "Temperature": "Temperatura", + "Estimated endurance used": "Vida útil consumida estimada", + "Media errors": "Erros de mídia", + "Bad sectors": "Setores defeituosos", + "Source header readable": "Cabeçalho da origem legível", + "Logical sector size": "Tamanho do setor lógico", + "Unrecognized": "Não reconhecido", + "Header and array checksums verified": "Somas de verificação do cabeçalho e da tabela verificadas", + "Unknown or unreported": "Desconhecido ou não informado", + "Unavailable. The device, adapter, or system driver did not expose health data.": "O dispositivo, adaptador ou driver não fornece dados de integridade.", + "Disk images contain no live device health readings.": "Imagens de disco não contêm leituras do dispositivo em tempo real.", + "Backing disk unavailable. Open a whole-disk image to inspect its partition table.": "Disco físico indisponível. Abra uma imagem do disco inteiro para inspecionar a tabela.", + "Partition check incomplete · {e}": "Verificação de partições incompleta · {e}", + "NVMe · no critical warnings reported": "NVMe · nenhum aviso crítico", + "NVMe warning · {}": "Aviso NVMe · {}", + "SMART · drive predicts failure": "SMART · o disco prevê uma falha", + "SMART · no failure predicted": "SMART · nenhuma falha prevista", + "SMART · {status}": "SMART · {status}", + "NVMe critical warning · 0x{warning:02x}": "Aviso crítico NVMe · 0x{warning:02x}", + "Partition read incomplete · {e}": "Leitura da partição incompleta · {e}", + "Missing protective MBR": "MBR de proteção ausente", + "Primary GPT": "GPT primária", + "Backup GPT": "GPT de backup", + "GPT copies disagree. Showing primary entries.": "As cópias da GPT divergem. As entradas primárias são exibidas.", + "MBR · primary entries": "MBR · entradas primárias", + "Entry {} has zero length": "A entrada {} tem comprimento zero", + "Extended container (logical entries uninspected)": "Partição estendida (entradas lógicas não verificadas)", + "MBR type 0x{t:02x}": "Tipo MBR 0x{t:02x}", + "No recognized disk partition table. A volume image may contain only a filesystem.": "Nenhuma tabela de partições reconhecida. Uma imagem de volume pode conter apenas um sistema de arquivos.", + "Entry {} exceeds usable bounds or is reversed": "A entrada {} excede os limites utilizáveis ou está invertida", + "Entry {} overlaps a previous entry": "A entrada {} se sobrepõe a uma anterior", + "Drive check interrupted": "Verificação interrompida", + "Invalid partition": "Partição inválida", + "Disk unavailable": "Disco indisponível", + "Empty or unknown source size": "Origem vazia ou tamanho desconhecido", + "Quick Drive Check": "Verificar disco", + "SMART and NVMe health": "Estado SMART e NVMe", + "Partition table": "Tabela de partições", + "Inspect partition": "Inspecionar partição", + "Device readings": "Leituras do dispositivo", + "Reading drive information…": "Lendo informações do disco…", " · ": " · ", "1. Stop using the drive you lost files from. Don't save, download or install anything to it.\n\n2. Choose that drive or a raw disk image, then scan its unused space. Stop any time and keep partial results.\n\n3. Inspect and select files, then save them to a different physical drive.": "1. Pare de usar a unidade da qual você perdeu os arquivos. Não salve, baixe ou instale nada nele.\n\n2. Escolha essa unidade ou uma imagem de disco bruta e, em seguida, analise o espaço não utilizado. Pare a qualquer momento e mantenha os resultados parciais.\n\n3. Inspecionar e selecionar arquivos e, em seguida, salvá-los em uma unidade física diferente.", "A native desktop session is required": "É necessária uma sessão de desktop nativa", diff --git a/locales/ru.json b/locales/ru.json index 1d5e393..30d8c33 100644 --- a/locales/ru.json +++ b/locales/ru.json @@ -1,4 +1,65 @@ { + "Sector viewer": "Просмотр секторов", + "View bytes": "Показать байты", + "View partition bytes": "Показать байты раздела", + "Compare image": "Сравнить образ", + "Close comparison": "Закрыть сравнение", + "Byte offset or LBA": "Смещение в байтах или LBA", + "Go": "Перейти", + "Previous": "Назад", + "Next": "Далее", + "Source on the left, comparison on the right. ^^ marks differences and -- marks missing bytes.": "Слева источник, справа образ для сравнения. ^^ отмечает различия, -- означает отсутствие байта.", + "Address outside the image or drive.": "Адрес за пределами образа или диска.", + "Enter a byte offset or LBA, for example 0x200 or LBA 1.": "Введите смещение в байтах или LBA, например 0x200 или LBA 1.", + "Capacity": "Ёмкость", + "Encryption": "Шифрование", + "Backing disk": "Физический диск", + "Read access": "Доступ для чтения", + "Filesystem signature": "Сигнатура файловой системы", + "Read check incomplete": "Проверка чтения не завершена", + "Byte offset": "Смещение в байтах", + "Length": "Длина", + "Temperature": "Температура", + "Estimated endurance used": "Расчётный износ", + "Media errors": "Ошибки носителя", + "Bad sectors": "Повреждённые секторы", + "Source header readable": "Заголовок источника доступен для чтения", + "Logical sector size": "Размер логического сектора", + "Unrecognized": "Не распознано", + "Header and array checksums verified": "Контрольные суммы заголовка и массива проверены", + "Unknown or unreported": "Неизвестно или нет данных", + "Unavailable. The device, adapter, or system driver did not expose health data.": "Устройство, адаптер или драйвер не предоставляет данные о состоянии.", + "Disk images contain no live device health readings.": "Образы дисков не содержат текущих показаний устройства.", + "Backing disk unavailable. Open a whole-disk image to inspect its partition table.": "Физический диск недоступен. Откройте образ всего диска для проверки таблицы разделов.", + "Partition check incomplete · {e}": "Проверка разделов не завершена · {e}", + "NVMe · no critical warnings reported": "NVMe · критических предупреждений нет", + "NVMe warning · {}": "Предупреждение NVMe · {}", + "SMART · drive predicts failure": "SMART · диск прогнозирует отказ", + "SMART · no failure predicted": "SMART · отказ не прогнозируется", + "SMART · {status}": "SMART · {status}", + "NVMe critical warning · 0x{warning:02x}": "Критическое предупреждение NVMe · 0x{warning:02x}", + "Partition read incomplete · {e}": "Чтение раздела не завершено · {e}", + "Missing protective MBR": "Отсутствует защитная MBR", + "Primary GPT": "Основная GPT", + "Backup GPT": "Резервная GPT", + "GPT copies disagree. Showing primary entries.": "Копии GPT различаются. Показаны основные записи.", + "MBR · primary entries": "MBR · основные записи", + "Entry {} has zero length": "Длина записи {} равна нулю", + "Extended container (logical entries uninspected)": "Расширенный раздел (логические записи не проверены)", + "MBR type 0x{t:02x}": "Тип MBR 0x{t:02x}", + "No recognized disk partition table. A volume image may contain only a filesystem.": "Таблица разделов не распознана. Образ тома может содержать только файловую систему.", + "Entry {} exceeds usable bounds or is reversed": "Запись {} выходит за границы или имеет обратный диапазон", + "Entry {} overlaps a previous entry": "Запись {} пересекается с предыдущей записью", + "Drive check interrupted": "Проверка диска прервана", + "Invalid partition": "Недопустимый раздел", + "Disk unavailable": "Диск недоступен", + "Empty or unknown source size": "Источник пуст или размер неизвестен", + "Quick Drive Check": "Проверка диска", + "SMART and NVMe health": "Состояние SMART и NVMe", + "Partition table": "Таблица разделов", + "Inspect partition": "Проверить раздел", + "Device readings": "Показания устройства", + "Reading drive information…": "Чтение сведений о диске…", "All files": "Все файлы", "Appearance": "Внешний вид", "Debug logging": "Журнал отладки", diff --git a/src/drive_check.rs b/src/drive_check.rs new file mode 100644 index 0000000..2b86dcb --- /dev/null +++ b/src/drive_check.rs @@ -0,0 +1,265 @@ +//! A report owns the read-only handle that its partition offsets refer to. +use crate::drives::{self, Drive}; +use reclaim::{SourceReader, i18n, partition}; +use std::{fmt::Write as _, fs::File, io, path::Path}; + +#[derive(Default)] +pub(crate) struct Report { + pub overview: String, + pub health: String, + pub raw: String, + pub layout: String, + pub findings: Vec<(u64, String)>, + pub viewer_path: std::path::PathBuf, + pub sector: u64, + pub choices: Vec, + regions: Vec<(u64, u64)>, + disk: Option, + alignment: usize, + pub size: u64, +} + +pub(crate) fn field(label: &str, value: impl std::fmt::Display) -> String { + format!("{} · {}", i18n::t(label), i18n::isolate(&value.to_string())) +} + +pub(crate) fn partition_detail(offset: u64, len: u64, fs: &str) -> String { + [ + field("Byte offset", offset), + field("Length", crate::format_bytes(len)), + field("Filesystem signature", i18n::t(fs)), + ] + .join("\n") +} + +impl Report { + pub fn reader(&self) -> io::Result> { + let disk = self + .disk + .as_ref() + .ok_or_else(|| io::Error::other("Disk unavailable"))?; + SourceReader::new(disk.try_clone()?, self.alignment, Some(self.size)) + } + + pub fn region_offset(&self, index: usize) -> Option { + self.regions.get(index).map(|&(offset, _)| offset) + } + pub fn open_partition(&self, index: usize) -> io::Result<(SourceReader, u64, u64)> { + let &(offset, len) = self + .regions + .get(index) + .ok_or_else(|| io::Error::other("Invalid partition"))?; + Ok((self.reader()?, offset, len)) + } + fn set_view_source(&mut self, path: &Path, disk: File, size: u64, alignment: usize) { + self.disk = Some(disk); + path.clone_into(&mut self.viewer_path); + self.size = size; + self.alignment = alignment; + self.sector = if alignment >= 512 { + alignment as u64 + } else { + 512 + }; + } + fn inspect_disk(&mut self, path: &Path, drive: Option<&Drive>, disk: File) -> io::Result<()> { + let size = if let Some(d) = drive { + d.size + } else { + disk.metadata()?.len() + }; + let alignment = drive.map_or(1, |d| d.sector_size); + self.set_view_source(path, disk, size, alignment); + let table = partition::inspect( + &mut self.reader()?, + size, + (alignment >= 512).then_some(alignment), + )?; + self.sector = table.sector; + self.layout = format!( + "{}\n{}", + path.display(), + field("Logical sector size", format!("{} B", table.sector)) + ); + self.findings = table.notes; + for p in table.partitions { + let label = format!( + "#{} {} · LBA {}–{}", + p.slot, + i18n::t(&p.kind), + p.first, + p.last + ); + if let (Some(start), Some(end)) = ( + p.first.checked_mul(table.sector), + p.last + .checked_add(1) + .and_then(|n| n.checked_mul(table.sector)), + ) && start < end + && end <= size + { + self.choices.push(label); + self.regions.push((start, end - start)); + } else { + write!(self.layout, "\n{label}").ok(); + } + } + Ok(()) + } +} + +fn backing<'a>(mut drive: &'a Drive, inventory: &'a [Drive]) -> Option<&'a Drive> { + for _ in 0..32 { + if matches!(drive.kind.as_str(), "Entire drive" | "USB drive") { + return Some(drive); + } + let parent = drive.parent.as_ref()?; + drive = inventory.iter().find(|d| &d.path == parent)?; + } + None +} + +pub(crate) fn check(path: &Path, selected: Option<&Drive>) -> Report { + let mut report = Report::default(); + let inventory = selected + .and_then(|_| drives::inventory(true).ok()) + .unwrap_or_default(); + let selected = inventory.iter().find(|d| d.path == path).or(selected); + let size = selected.map_or_else(|| path.metadata().map_or(0, |m| m.len()), |d| d.size); + let physical = selected.and_then(|d| backing(d, &inventory)); + report.overview = format!( + "{}\n{}", + path.display(), + field( + "Capacity", + format!("{} ({size} B)", crate::format_bytes(size)) + ) + ); + if let Some(d) = selected { + write!( + report.overview, + "\n{} · {}\n{}", + d.display_name(), + i18n::t(&d.location), + field( + "Encryption", + i18n::t(if d.unlocked || d.kind == "Unlocked volume" { + "Unlocked" + } else if d.encrypted { + "Encrypted" + } else { + "Unknown or unreported" + }) + ) + ) + .ok(); + if let Some(disk) = physical { + write!( + report.overview, + "\n{}", + field( + "Backing disk", + format!("{} ({})", disk.path.display(), disk.display_name()) + ) + ) + .ok(); + for volume in inventory.iter().filter(|v| { + v.path != disk.path && backing(v, &inventory).is_some_and(|b| b.path == disk.path) + }) { + write!( + report.overview, + "\n {} · {} · {}", + volume.path.display(), + volume.display_name(), + i18n::t(&volume.location) + ) + .ok(); + } + } + if let Some((health, raw)) = drives::health(&physical.unwrap_or(d).path) { + report.health = health.lines().map(i18n::t).collect::>().join("\n"); + report.raw = raw; + } else { + report.health = i18n::t( + "Unavailable. The device, adapter, or system driver did not expose health data.", + ); + } + } else { + report.health = i18n::t("Disk images contain no live device health readings."); + } + let opened = drives::open_source(path); + let probe = (|| { + if size == 0 { + return Err(io::Error::other("Empty or unknown source size")); + } + let mut reader = SourceReader::new( + opened + .as_ref() + .map_err(|e| io::Error::new(e.kind(), e.to_string()))? + .try_clone()?, + selected.map_or(1, |d| d.sector_size), + Some(size), + )?; + partition::filesystem(&mut reader, 0, size) + })(); + match probe { + Ok(fs) => write!( + report.overview, + "\n{}\n{}", + field("Read access", i18n::t("Source header readable")), + field("Filesystem signature", i18n::t(fs)) + ) + .ok(), + Err(e) => write!(report.overview, "\n{}", field("Read check incomplete", e)).ok(), + }; + // A readable volume remains inspectable when its physical disk cannot be opened. + if selected.is_some() + && physical.is_none_or(|d| d.path != path) + && let Ok(file) = &opened + && let Ok(file) = file.try_clone() + { + report.set_view_source(path, file, size, selected.map_or(1, |d| d.sector_size)); + } + if selected.is_some() && physical.is_none() { + report.layout = i18n::t( + "Backing disk unavailable. Open a whole-disk image to inspect its partition table.", + ); + } else { + let disk_path = physical.map_or(path, |d| &d.path); + let disk = if disk_path == path { + opened + } else { + drives::open_source(disk_path) + }; + if let Err(e) = disk.and_then(|disk| report.inspect_disk(disk_path, physical, disk)) { + report.layout = i18n::t(&format!("Partition check incomplete · {e}")); + } + } + report +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn image_report_opens_partition_at_its_actual_offset() { + let folder = tempfile::tempdir().unwrap(); + let path = folder.path().join("disk.img"); + let mut data = vec![0; 16384]; + data[510..512].copy_from_slice(&[0x55, 0xaa]); + data[450] = 7; + data[454] = 8; + data[458] = 8; + data[4099..4107].copy_from_slice(b"NTFS "); + std::fs::write(&path, &data).unwrap(); + let report = check(&path, None); + assert!(report.health.contains("images")); + let (mut reader, start, size) = report.open_partition(0).unwrap(); + assert_eq!(start, 4096); + assert_eq!( + partition::filesystem(&mut reader, start, size).unwrap(), + "NTFS" + ); + assert_eq!(std::fs::read(path).unwrap(), data); + } +} diff --git a/src/drives.rs b/src/drives.rs index ce05290..ea5bab7 100644 --- a/src/drives.rs +++ b/src/drives.rs @@ -142,10 +142,16 @@ mod macos; mod windows; #[cfg(target_os = "linux")] pub use linux::{destination, discover}; +#[cfg(target_os = "linux")] +pub(crate) use linux::{health, inventory}; #[cfg(target_os = "macos")] pub use macos::{destination, discover}; +#[cfg(target_os = "macos")] +pub(crate) use macos::{health, inventory}; #[cfg(target_os = "windows")] pub use windows::{destination, discover}; +#[cfg(target_os = "windows")] +pub(crate) use windows::{health, inventory}; #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))] pub fn discover() -> Result, String> { Ok(Vec::new()) @@ -239,6 +245,52 @@ fn open_via_desktop(path: &Path) -> io::Result { request().map_err(|e| io::Error::new(io::ErrorKind::PermissionDenied, format!("Could not get read-only drive access: {e}. Allow the desktop authentication prompt and try again. If no prompt appears, check that UDisks2 and a polkit authentication agent are installed, or open a disk image."))) } +/// Decode a complete `NVMe` SMART/Health log page (log identifier 02h). +#[cfg(any(windows, target_os = "macos", test))] +fn nvme_health(data: &[u8]) -> Option<(String, String)> { + use crate::drive_check::field; + let data = data.get(..512)?; + let &[warning, low, high, spare, threshold, used, ..] = data else { + return None; + }; + let temp = u16::from_le_bytes([low, high]); + let errors = u128::from_le_bytes(data.get(160..176)?.try_into().ok()?); + let mut summary = vec![if warning == 0 { + reclaim::i18n::t("NVMe · no critical warnings reported") + } else { + reclaim::i18n::t(&format!("NVMe critical warning · 0x{warning:02x}")) + }]; + if temp > 0 { + summary.push(field( + "Temperature", + format!("{:.0} °C", f64::from(temp) - 273.15), + )); + } + summary.push(field("Estimated endurance used", format!("{used}%"))); + summary.push(field("Media errors", errors)); + Some(( + summary.join("\n"), + format!( + "CriticalWarning=0x{warning:02x} Temperature={temp} K AvailableSpare={spare}% SpareThreshold={threshold}%" + ), + )) +} + +#[cfg(test)] +mod health_tests { + #[test] + fn nvme_counters_preserve_all_128_bits_and_reject_short_logs() { + let mut page = [0; 512]; + page[..6].copy_from_slice(&[4, 0x30, 1, 99, 10, 101]); + let errors = (1u128 << 80) + 5; + page[160..176].copy_from_slice(&errors.to_le_bytes()); + let (report, raw) = super::nvme_health(&page).unwrap(); + assert!(report.contains("31 °C") && report.contains("101%")); + assert!(report.contains(&errors.to_string()) && raw.contains("0x04")); + assert!(super::nvme_health(&page[..511]).is_none()); + } +} + #[cfg(all(test, target_os = "linux"))] mod tests { use super::*; @@ -357,3 +409,13 @@ mod nest_tests { assert!(tail.iter().all(|d| depth(&tail, d) == 0)); } } + +#[cfg(not(any(target_os = "linux", windows, target_os = "macos")))] +pub(crate) fn inventory(_: bool) -> Result, String> { + discover() +} + +#[cfg(not(any(target_os = "linux", windows, target_os = "macos")))] +pub(crate) fn health(_: &Path) -> Option<(String, String)> { + None +} diff --git a/src/drives/linux.rs b/src/drives/linux.rs index 0eada2a..0d006e4 100644 --- a/src/drives/linux.rs +++ b/src/drives/linux.rs @@ -14,15 +14,20 @@ use std::{ }; pub fn discover() -> Result, String> { + inventory(false) +} + +pub(crate) fn inventory(all: bool) -> Result, String> { // The sandbox exposes disk images through the file portal, not host drives. if Path::new("/.flatpak-info").exists() { return Ok(Vec::new()); } - let mut drives = discover_at( + let mut drives = inventory_at( Path::new("/sys/class/block"), Path::new("/dev"), Path::new("/proc/self/mountinfo"), Path::new("/run/udev/data"), + all, ) .map_err(|error| format!("Could not list drives: {error}. You can still open a disk image."))?; drives.extend(phones_at(Path::new("/sys/bus/usb/devices"))); @@ -163,7 +168,18 @@ struct Node { partition: bool, } +#[cfg(test)] fn discover_at(sys: &Path, dev: &Path, mounts: &Path, udev: &Path) -> std::io::Result> { + inventory_at(sys, dev, mounts, udev, false) +} + +fn inventory_at( + sys: &Path, + dev: &Path, + mounts: &Path, + udev: &Path, + all: bool, +) -> std::io::Result> { // Missing namespace metadata must not silently mark active drives unmounted. let mount_text = read_system_file(mounts)?; let mut mounted = HashMap::::new(); @@ -369,13 +385,16 @@ fn discover_at(sys: &Path, dev: &Path, mounts: &Path, udev: &Path) -> std::io::R phone: false, unlocked: opened, // Device-mapper layers (dm-crypt, LVM) nest under what they were opened from. - parent: (!node.partition) + parent: ((!node.partition || all) && node.parents.len() == 1) .then(|| node.parents.first()) .flatten() .map(|parent| dev.join(parent)), system: mount.is_some_and(|m| m == "/"), }); } + if all { + return Ok(drives); + } // Prefer named volumes over their parent disk. The volume retains its // filesystem label and is the source the user selected before deduplication. // Keep whole disks when no valid partition is available (e.g. lost tables). @@ -455,6 +474,150 @@ fn whole_disks(node: &Path) -> Option> { (!disks.is_empty()).then_some(disks) } +pub(crate) fn health(path: &Path) -> Option<(String, String)> { + use std::fmt::Write as _; + use zbus::{ + blocking::{Connection, Proxy}, + zvariant::{OwnedObjectPath, OwnedValue, Value}, + }; + type Attribute = ( + u8, + String, + u16, + i32, + i32, + i32, + i64, + i32, + HashMap, + ); + let bus = Connection::system().ok()?; + let service = "org.freedesktop.UDisks2"; + let object = super::object_path(path).ok()?; + let block = Proxy::new( + &bus, + service, + object.as_str(), + "org.freedesktop.UDisks2.Block", + ) + .ok()?; + let drive: OwnedObjectPath = block.get_property("Drive").ok()?; + let options = HashMap::<&str, Value<'_>>::new(); + let nvme = Proxy::new( + &bus, + service, + drive.as_str(), + "org.freedesktop.UDisks2.NVMe.Controller", + ) + .ok()?; + if let Ok(updated) = nvme.get_property::("SmartUpdated") + && updated > 0 + { + let warnings = nvme + .get_property::>("SmartCriticalWarning") + .ok()?; + let mut summary = if warnings.is_empty() { + "NVMe · no critical warnings reported".into() + } else { + format!("NVMe warning · {}", warnings.join(", ")) + }; + if let Ok(t) = nvme.get_property::("SmartTemperature") + && t > 0 + { + write!( + summary, + "\n{}", + crate::drive_check::field( + "Temperature", + format!("{:.0} °C", f64::from(t) - 273.15) + ) + ) + .ok(); + } + let mut raw = format!("SmartUpdated={updated} (Unix time)"); + if let Ok(attrs) = nvme.call::<_, _, std::collections::BTreeMap>( + "SmartGetAttributes", + &(options,), + ) { + for (key, v) in attrs { + match key.as_str() { + "percent_used" => { + if let Ok(n) = u8::try_from(&v) { + write!( + summary, + "\n{}", + crate::drive_check::field( + "Estimated endurance used", + format!("{n}%") + ) + ) + .ok(); + } + } + "media_errors" => { + if let Ok(n) = u64::try_from(&v) { + write!( + summary, + "\n{}", + crate::drive_check::field("Media errors", n) + ) + .ok(); + } + } + _ => {} + } + write!(raw, "\n{key} · {v:?}").ok(); + } + } + return Some((summary, raw)); + } + let ata = Proxy::new( + &bus, + service, + drive.as_str(), + "org.freedesktop.UDisks2.Drive.Ata", + ) + .ok()?; + if !ata.get_property::("SmartEnabled").ok()? { + return None; + } + let updated = ata.get_property::("SmartUpdated").ok()?; + if updated == 0 { + return None; + } + let mut summary = if ata.get_property::("SmartFailing").ok()? { + "SMART · drive predicts failure".to_owned() + } else { + "SMART · no failure predicted".to_owned() + }; + if let Ok(t) = ata.get_property::("SmartTemperature") + && t > 0.0 + { + write!( + summary, + "\n{}", + crate::drive_check::field("Temperature", format!("{:.0} °C", t - 273.15)) + ) + .ok(); + } + if let Ok(n) = ata.get_property::("SmartNumBadSectors") + && n >= 0 + { + write!(summary, "\n{}", crate::drive_check::field("Bad sectors", n)).ok(); + } + let mut raw = format!("SmartUpdated={updated} (Unix time)"); + if let Ok(attrs) = ata.call::<_, _, Vec>("SmartGetAttributes", &(options,)) { + for (id, name, _, value, worst, threshold, _, _, _) in attrs { + write!( + raw, + "\n{id} {name} · {value} / worst {worst} / threshold {threshold}" + ) + .ok(); + } + } + Some((summary, raw)) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/drives/macos.rs b/src/drives/macos.rs index 59148e1..7a96666 100644 --- a/src/drives/macos.rs +++ b/src/drives/macos.rs @@ -12,6 +12,7 @@ use core_foundation_sys::{ CFStringGetMaximumSizeForEncoding, CFStringGetTypeID, CFStringRef, kCFStringEncodingUTF8, }, url::{CFURLCopyFileSystemPath, CFURLGetTypeID, kCFURLPOSIXPathStyle}, + uuid::{CFUUIDBytes, CFUUIDCreateFromString, CFUUIDGetUUIDBytes, CFUUIDRef}, }; use std::{ collections::{HashMap, HashSet}, @@ -21,6 +22,14 @@ use std::{ #[link(name = "IOKit", kind = "framework")] unsafe extern "C" { + fn IOCreatePlugInInterfaceForService( + entry: u32, + client: CFUUIDRef, + interface_id: CFUUIDRef, + plugin: *mut *mut *const ComInterface, + score: *mut i32, + ) -> i32; + fn IODestroyPlugInInterface(plugin: *mut *const ComInterface) -> i32; fn IOServiceMatching(name: *const std::ffi::c_char) -> CFMutableDictionaryRef; fn IOServiceGetMatchingServices( port: u32, @@ -50,6 +59,7 @@ unsafe extern "C" { session: CFTypeRef, name: *const std::ffi::c_char, ) -> CFTypeRef; + fn DADiskCopyIOMedia(disk: CFTypeRef) -> u32; fn DADiskCopyDescription(disk: CFTypeRef) -> CFDictionaryRef; } @@ -349,7 +359,11 @@ pub fn discover() -> Result, String> { }, mounted: in_use, encrypted: locked, - sector_size: 1, + // audit-allow(I18N-MISSING): IOKit property key. + sector_size: number(property(entry.0, "Preferred Block Size").0) + .and_then(|n| usize::try_from(n).ok()) + .filter(|n| n.is_power_of_two() && (512..=65536).contains(n)) + .unwrap_or(1), phone: false, unlocked: false, parent: None, @@ -418,6 +432,144 @@ pub fn destination(source: &std::path::Path, folder: &std::path::Path) -> Destin } } +pub(crate) fn inventory(_: bool) -> Result, String> { + let mut rows = discover()?; + for row in &mut rows { + if row.kind == "Volume" { + row.parent = row + .path + .to_str() + .and_then(whole_disk) + .map(|id| format!("/dev/{id}").into()); + } + } + Ok(rows) +} + +// Prefixes of the IOKit C interfaces in IOCFPlugIn.h and NVMeSMARTLibExternal.h. +// QueryInterface selects the exact NVMe interface before its method is called. +#[repr(C)] +struct ComInterface { + reserved: *mut std::ffi::c_void, + query: + unsafe extern "C" fn(*mut std::ffi::c_void, CFUUIDBytes, *mut *mut std::ffi::c_void) -> i32, + add_ref: unsafe extern "C" fn(*mut std::ffi::c_void) -> u32, + release: unsafe extern "C" fn(*mut std::ffi::c_void) -> u32, +} + +#[repr(C)] +struct NvmeInterface { + base: ComInterface, + version: u16, + revision: u16, + read_data: unsafe extern "C" fn(*mut std::ffi::c_void, *mut [u8; 512]) -> i32, +} + +fn uuid(text: &str) -> Option { + let string = cf_string(text); + if string.0.is_null() { + return None; + } + // SAFETY: the CFString is live and the null allocator selects the default. + let value = Cf(unsafe { CFUUIDCreateFromString(ptr::null(), string.0.cast()) }.cast()); + (!value.0.is_null()).then_some(value) +} + +fn nvme_log(entry: u32) -> Option<[u8; 512]> { + let client = uuid("AA0FA6F9-C2D6-457F-B10B-59A13253292F")?; + let plugin_id = uuid("C244E858-109C-11D4-91D4-0050E4C6426F")?; + let interface_id = uuid("CCD1DB19-FD9A-4DAF-BF95-12454B230AB6")?; + let mut plugin = ptr::null_mut(); + let mut score = 0; + // SAFETY: entry belongs to the live registry walk, both UUIDs are live, + // and the two output pointers refer to initialized local storage. + let status = unsafe { + IOCreatePlugInInterfaceForService( + entry, + client.0.cast(), + plugin_id.0.cast(), + &raw mut plugin, + &raw mut score, + ) + }; + if status != 0 || plugin.is_null() { + return None; + } + // SAFETY: this is the Core Foundation UUID created above. + let id = unsafe { CFUUIDGetUUIDBytes(interface_id.0.cast()) }; + let mut interface = ptr::null_mut(); + // SAFETY: successful creation returns a live IOCFPlugInInterface** whose + // first table members are the COM prefix. QueryInterface fills the output. + let plugin_table = unsafe { *plugin }; + // SAFETY: the live plugin owns its COM table until destruction below. + let query = unsafe { (*plugin_table).query }; + // SAFETY: plugin is live, id identifies IONVMeSMARTInterface, and interface is writable. + let status = unsafe { query(plugin.cast(), id, &raw mut interface) }; + let result = if status == 0 && !interface.is_null() { + let handle = interface.cast::<*const NvmeInterface>(); + // SAFETY: a successful query for this UUID supplies that exact vtable, + // which remains owned by this function until Release below. + let table = unsafe { *handle }; + // SAFETY: the queried interface owns a live NVMe method table. + let methods = unsafe { &*table }; + let mut page = [0; 512]; + // SAFETY: SMARTReadData writes one complete 512-byte NVMe health page. + let read = unsafe { (methods.read_data)(interface, &raw mut page) }; + // SAFETY: balance the single successful QueryInterface before plugin destruction. + unsafe { (methods.base.release)(interface) }; + (read == 0).then_some(page) + } else { + None + }; + // SAFETY: plugin is the owned interface from IOCreatePlugInInterfaceForService. + unsafe { IODestroyPlugInInterface(plugin) }; + result +} + +pub(crate) fn health(path: &std::path::Path) -> Option<(String, String)> { + let name = CString::new(path.file_name()?.to_str()?).ok()?; + // SAFETY: the default allocator is selected with a null pointer. + let session = Cf(unsafe { DASessionCreate(ptr::null()) }); + if session.0.is_null() { + return None; + } + // SAFETY: the session is live and name is NUL-terminated. + let disk = Cf(unsafe { DADiskCreateFromBSDName(ptr::null(), session.0, name.as_ptr()) }); + if disk.0.is_null() { + return None; + } + // SAFETY: disk is live; the copy returns an owned IOMedia entry. + let media = unsafe { DADiskCopyIOMedia(disk.0) }; + if media == 0 { + return None; + } + let mut entry = Object(media); + for _ in 0..64 { + // audit-allow(I18N-MISSING): IOKit property key. + if boolean(property(entry.0, "NVMe SMART Capable").0) + && let Some(page) = nvme_log(entry.0) + { + return super::nvme_health(&page); + } + // audit-allow(I18N-MISSING): IOKit property key. + if let Some(status) = string(property(entry.0, "SMART Status").0) { + return Some(( + format!("SMART · {status}"), + format!("IOKit SMART Status={status}"), + )); + } + let mut parent = 0; + // SAFETY: entry owns a live registry entry; parent is a writable output. + if unsafe { IORegistryEntryGetParentEntry(entry.0, c"IOService".as_ptr(), &raw mut parent) } + != 0 + { + break; + } + entry = Object(parent); + } + None +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/drives/windows.rs b/src/drives/windows.rs index 7c3ef71..354b5dd 100644 --- a/src/drives/windows.rs +++ b/src/drives/windows.rs @@ -145,6 +145,10 @@ fn product(file: &File) -> Option { (!value.is_empty()).then_some(value) } pub fn discover() -> Result, String> { + inventory(false) +} + +pub(crate) fn inventory(all: bool) -> Result, String> { let mut names = vec![0u16; 65536]; // SAFETY: writable UTF-16 buffer, null name requests the device namespace. let count = unsafe { QueryDosDeviceW(ptr::null(), names.as_mut_ptr(), win32_len(names.len())) } @@ -292,7 +296,10 @@ pub fn discover() -> Result, String> { sector_size, phone: false, unlocked: false, - parent: None, + parent: all + .then(|| u32_at(&extents, extent_offset)) + .flatten() + .map(|n| format!(r"\\.\PhysicalDrive{n}").into()), // The volume Windows runs from, such as C:. system: std::env::var("SystemDrive") .is_ok_and(|drive| drive.eq_ignore_ascii_case(&format!("{letter}:"))), @@ -306,6 +313,9 @@ pub fn discover() -> Result, String> { rows[index].location = "Contains mounted volumes".into(); } } + if all { + return Ok(rows); + } let hidden: HashSet<_> = represented_disks .iter() .filter_map(|number| disk_rows.get(number).map(|&index| rows[index].path.clone())) @@ -375,6 +385,38 @@ fn win32_len(len: usize) -> u32 { u32::try_from(len).unwrap_or(u32::MAX) } +pub(crate) fn health(path: &Path) -> Option<(String, String)> { + use windows_sys::Win32::System::Ioctl::IOCTL_STORAGE_PREDICT_FAILURE; + let file = open(path.to_str()?)?; + // STORAGE_PROPERTY_QUERY + STORAGE_PROTOCOL_SPECIFIC_DATA, NVMe SMART log page 2. + let words = [50u32, 0, 3, 2, 2, 0, 40, 512, 0, 0, 0, 0]; + let input: Vec<_> = words.into_iter().flat_map(u32::to_le_bytes).collect(); + if let Some(reply) = query(&file, IOCTL_STORAGE_QUERY_PROPERTY, &input) + && u32_at(&reply, 0) == Some(48) + && u32_at(&reply, 4) == Some(48) + && u32_at(&reply, 8) == Some(3) + && u32_at(&reply, 12) == Some(2) + && let Some(offset) = u32_at(&reply, 24).filter(|n| *n >= 40) + && u32_at(&reply, 28).is_some_and(|len| len >= 512) + && let Some(data) = reply + .get(8 + offset as usize..) + .and_then(|log| log.get(..512)) + { + return super::nvme_health(data); + } + let data = query(&file, IOCTL_STORAGE_PREDICT_FAILURE, &[])?; + let code = u32_at(&data, 0)?; + Some(( + if code == 0 { + "SMART · no failure predicted" + } else { + "SMART · drive predicts failure" + } + .into(), + format!("PredictFailure={code}"), + )) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/lib.rs b/src/lib.rs index 12d5e47..dc83b87 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,6 +9,7 @@ mod large; use detection::{CandidateEnd, LIMIT}; pub mod i18n; mod ntfs; +pub mod partition; mod resilient; mod source; pub mod updater; diff --git a/src/main.rs b/src/main.rs index 8f90b01..d1de8d7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,7 @@ windows_subsystem = "windows" )] mod diagnostics; +mod drive_check; mod drives; mod installer; mod legacy_install; @@ -10,6 +11,7 @@ mod motion; #[cfg(any(target_os = "linux", windows))] mod native_process; mod preview; +mod sector_view; mod ui_text; mod update_runtime; mod updates; @@ -56,7 +58,15 @@ enum Message { Opened(Arc), Done(Result<(), String>), } +enum CheckResult { + Source(Box), + Partition(std::io::Result), + Sector(std::io::Result), +} struct Reclaim { + check_receiver: Option>, + check_report: Option, + viewer: sector_view::Viewer, inspected: Option, source: Option, source_handle: Option>, @@ -149,6 +159,9 @@ struct ShownFiles { impl Default for Reclaim { fn default() -> Self { Self { + check_receiver: None, + check_report: None, + viewer: sector_view::Viewer::default(), inspected: None, source: None, source_handle: None, @@ -632,6 +645,82 @@ impl Reclaim { Err(e) => self.drives_error = Some(e), } } + fn poll_check(&mut self, ui: &AppWindow) { + let Some(receiver) = &self.check_receiver else { + return; + }; + match receiver.try_recv() { + Ok(CheckResult::Source(report)) => { + ui.set_check_overview(report.overview.as_str().into()); + ui.set_check_health(report.health.as_str().into()); + ui.set_check_raw(report.raw.as_str().into()); + ui.set_check_layout(report.layout.as_str().into()); + ui.set_check_partitions(ModelRc::new(VecModel::from( + report + .choices + .iter() + .map(|s| s.as_str().into()) + .collect::>(), + ))); + ui.set_check_findings(ModelRc::new(VecModel::from( + report + .findings + .iter() + .map(|(_, note)| i18n::t(note).into()) + .collect::>(), + ))); + ui.set_can_view_sectors(report.size > 0); + ui.set_sector_source(report.viewer_path.display().to_string().into()); + self.check_report = Some(*report); + } + Ok(CheckResult::Sector(Ok(page))) => { + let offset = page.viewer.offset; + ui.set_sector_address(format!("0x{offset:X}").into()); + ui.set_sector_status( + format!( + "0x{offset:X} – 0x{:X} · LBA {}", + page.last, + offset / self.check_report.as_ref().map_or(512, |r| r.sector.max(1)) + ) + .into(), + ); + ui.set_sector_dump(page.dump.into()); + ui.set_sector_compare( + page.viewer + .image + .as_ref() + .map_or_default(|i| i.path.display().to_string()) + .into(), + ); + ui.set_sector_prev(offset > 0); + ui.set_sector_next(page.more); + self.viewer = page.viewer; + } + Ok(CheckResult::Sector(Err(e))) => ui.set_sector_error(e.to_string().into()), + Err(mpsc::TryRecvError::Disconnected) if ui.get_sector_loading() => { + ui.set_sector_error(i18n::t("Drive check interrupted").into()); + } + Ok(CheckResult::Partition(result)) => { + let detail = + result.unwrap_or_else(|e| i18n::t(&format!("Partition read incomplete · {e}"))); + ui.set_partition_detail(detail.into()); + } + Err(mpsc::TryRecvError::Disconnected) if ui.get_partition_loading() => { + ui.set_partition_detail(i18n::t("Drive check interrupted").into()); + } + Err(mpsc::TryRecvError::Empty) => return, + Err(mpsc::TryRecvError::Disconnected) => { + ui.set_check_layout(i18n::t("Drive check interrupted").into()); + ui.set_check_health("".into()); + ui.set_check_raw("".into()); + ui.set_check_partitions(ModelRc::default()); + } + } + self.check_receiver = None; + ui.set_sector_loading(false); + ui.set_partition_loading(false); + ui.set_check_running(false); + } fn poll(&mut self) -> bool { let mut changed = false; if let Some(result) = self @@ -849,7 +938,16 @@ impl Reclaim { ); ui.set_busy(self.busy); ui.set_drives_refreshing(self.drives_loading); - ui.set_can_scan(!self.working() && self.source.is_some()); + let can_check = !self.working() && self.source.is_some(); + ui.set_can_check(can_check); + ui.set_can_scan( + can_check + && self + .drives + .iter() + .find(|d| Some(&d.path) == self.source.as_ref()) + .is_none_or(drives::Drive::scannable), + ); // While recovering, the same button stops the recovery. ui.set_can_recover(self.exporting || selected > 0); ui.set_recovering(self.exporting); @@ -1393,11 +1491,12 @@ fn run() -> Result<(), slint::PlatformError> { s.choose_source(); } }); + register_drive_checks(&ui, &state); action!(on_refresh, |s: &mut Reclaim, _: &AppWindow| { s.refresh_drives(); }); action!(on_scan, |s: &mut Reclaim, ui: &AppWindow| { - if !s.working() { + if ui.get_can_scan() && !s.working() { s.start(); ui.set_page(1); ui.set_query("".into()); @@ -1437,7 +1536,7 @@ fn run() -> Result<(), slint::PlatformError> { action_with!(on_select_drive, |s, i: i32| { if !s.working() && let Ok(i) = usize::try_from(i) - && let Some(d) = s.drives.get(i).filter(|d| d.scannable()) + && let Some(d) = s.drives.get(i).filter(|d| !d.phone) { s.source = Some(d.path.clone()); s.needs_administrator = false; @@ -1549,6 +1648,7 @@ fn run() -> Result<(), slint::PlatformError> { let mut s = state.borrow_mut(); let changed_language = last_language.replace(i18n::preference()) != i18n::preference(); + s.poll_check(&ui); if s.poll() || changed_language { s.sync_ui(&ui); } @@ -1606,6 +1706,201 @@ fn run() -> Result<(), slint::PlatformError> { state.borrow().cancel.store(true, Ordering::Relaxed); result } +enum SectorAction { + Open(u64), + Jump, + Previous, + Next, + Compare(PathBuf), + Clear, +} +fn show_sectors(state: &mut Reclaim, ui: &AppWindow, action: SectorAction) { + if ui.get_check_running() { + return; + } + let Some(report) = &state.check_report else { + return; + }; + let offset = match &action { + SectorAction::Open(at) => *at, + SectorAction::Jump => { + let Some(at) = sector_view::address(&ui.get_sector_address(), report.sector) else { + ui.set_sector_error( + i18n::t("Enter a byte offset or LBA, for example 0x200 or LBA 1.").into(), + ); + return; + }; + at + } + SectorAction::Previous => state.viewer.offset.saturating_sub(sector_view::WINDOW), + SectorAction::Next => state.viewer.offset.saturating_add(sector_view::WINDOW), + SectorAction::Clear => state.viewer.offset.min(report.size.saturating_sub(1)), + SectorAction::Compare(_) => state.viewer.offset, + }; + let reader = report.reader(); + let size = report.size; + let current = state.viewer.image.clone(); + ui.set_sector_error("".into()); + ui.set_sector_loading(true); + ui.set_check_running(true); + ui.set_page(4); + let (sender, receiver) = mpsc::channel(); + state.check_receiver = Some(receiver); + std::thread::spawn(move || { + let result = reader.and_then(|reader| { + let image = match action { + SectorAction::Compare(path) => Some(sector_view::Image::open(path)?), + SectorAction::Clear => None, + SectorAction::Open(_) + | SectorAction::Jump + | SectorAction::Previous + | SectorAction::Next => current, + }; + sector_view::read(reader, size, offset, image) + }); + sender.send(CheckResult::Sector(result)).ok(); + }); +} +fn register_drive_checks(ui: &AppWindow, state: &Rc>) { + { + let state = Rc::clone(state); + let weak = ui.as_weak(); + ui.on_view_sectors(move |kind, index| { + let Some(ui) = weak.upgrade() else { + return; + }; + let mut state = state.borrow_mut(); + let Some(report) = &state.check_report else { + return; + }; + let index = usize::try_from(index).ok(); + let at = match kind { + 1 => index.and_then(|n| report.region_offset(n)), + 2 => index + .and_then(|n| report.findings.get(n)) + .map(|(at, _)| *at), + _ => Some(0), + }; + if let Some(at) = at { + show_sectors(&mut state, &ui, SectorAction::Open(at)); + } + }); + } + { + let state = Rc::clone(state); + let weak = ui.as_weak(); + ui.on_sector_navigate(move |direction| { + if let Some(ui) = weak.upgrade() { + let action = match direction { + -1 => SectorAction::Previous, + 1 => SectorAction::Next, + _ => SectorAction::Jump, + }; + show_sectors(&mut state.borrow_mut(), &ui, action); + } + }); + } + { + let state = Rc::clone(state); + let weak = ui.as_weak(); + ui.on_sector_comparison(move |choose| { + let Some(ui) = weak.upgrade() else { + return; + }; + if ui.get_check_running() { + return; + } + let action = if choose { + let Some(path) = rfd::FileDialog::new() + .set_title(i18n::t("Compare image")) + .pick_file() + else { + return; + }; + SectorAction::Compare(path) + } else { + SectorAction::Clear + }; + show_sectors(&mut state.borrow_mut(), &ui, action); + }); + } + { + let state = Rc::clone(state); + let weak = ui.as_weak(); + ui.on_check_drive(move || { + let Some(ui) = weak.upgrade() else { + return; + }; + let mut state = state.borrow_mut(); + let Some(path) = state.source.clone() else { + return; + }; + if state.working() || ui.get_check_running() { + return; + } + let drive = state.drives.iter().find(|d| d.path == path).cloned(); + ui.set_check_running(true); + ui.set_check_overview(path.display().to_string().into()); + ui.set_partition_detail("".into()); + ui.set_show_raw(false); + ui.set_check_index(0); + ui.set_page(3); + let (sender, receiver) = mpsc::channel(); + state.check_receiver = Some(receiver); + state.check_report = None; + state.viewer = sector_view::Viewer::default(); + ui.set_sector_compare("".into()); + ui.set_sector_dump("".into()); + ui.set_sector_status("".into()); + ui.set_sector_prev(false); + ui.set_sector_next(false); + ui.set_can_view_sectors(false); + std::thread::spawn(move || { + let report = drive_check::check(&path, drive.as_ref()); + sender.send(CheckResult::Source(Box::new(report))).ok(); + }); + }); + } + { + let state = Rc::clone(state); + let weak = ui.as_weak(); + let clear = weak.clone(); + ui.on_clear_partition(move || { + if let Some(ui) = clear.upgrade() { + ui.set_partition_detail("".into()); + } + }); + ui.on_open_partition(move |index| { + let Some(ui) = weak.upgrade() else { + return; + }; + if ui.get_check_running() { + return; + } + let mut state = state.borrow_mut(); + let Some(report) = &state.check_report else { + return; + }; + let Ok(index) = usize::try_from(index) else { + return; + }; + let source = report.open_partition(index); + ui.set_partition_detail("".into()); + ui.set_partition_loading(true); + ui.set_check_running(true); + let (sender, receiver) = mpsc::channel(); + state.check_receiver = Some(receiver); + std::thread::spawn(move || { + let result = source.and_then(|(mut reader, offset, len)| { + let fs = reclaim::partition::filesystem(&mut reader, offset, len)?; + Ok(drive_check::partition_detail(offset, len, fs)) + }); + sender.send(CheckResult::Partition(result)).ok(); + }); + }); + } +} + fn main() { // Velopack runs the app with a hook command during install, update and // uninstall; it must exit at once without opening a window. diff --git a/src/partition.rs b/src/partition.rs new file mode 100644 index 0000000..a5bcf10 --- /dev/null +++ b/src/partition.rs @@ -0,0 +1,414 @@ +//! Read-only, bounded inspection of primary MBR entries and both GPT copies. +use crate::bytes::{u16_le, u32_le, u64_le}; +use std::io::{self, Read, Seek, SeekFrom}; + +#[derive(Debug, PartialEq, Eq)] +pub struct Partition { + pub slot: usize, + pub first: u64, + pub last: u64, + pub kind: String, + /// Absolute byte offset of the entry that describes this partition. + pub entry_offset: u64, +} + +#[derive(Debug, Default)] +pub struct Layout { + pub sector: u64, + pub notes: Vec<(u64, String)>, + pub partitions: Vec, +} + +fn read_at(input: &mut (impl Read + Seek), offset: u64, buffer: &mut [u8]) -> io::Result<()> { + input.seek(SeekFrom::Start(offset))?; + input.read_exact(buffer) +} + +/// A boot or superblock signature, scoped to the selected volume. +pub fn filesystem( + input: &mut (impl Read + Seek), + offset: u64, + size: u64, +) -> io::Result<&'static str> { + let mut data = [0; 2048]; + let len = usize::try_from(size).unwrap_or(usize::MAX).min(data.len()); + read_at( + input, + offset, + data.get_mut(..len) + .ok_or_else(|| invalid("invalid probe length"))?, + )?; + Ok(match () { + () if data.starts_with(b"LUKS\xba\xbe") => "LUKS", + () if data.get(3..11) == Some(b"-FVE-FS-") => "BitLocker", + () if data.get(3..11) == Some(b"NTFS ") => "NTFS", + () if data.get(3..11) == Some(b"EXFAT ") => "exFAT", + () if data.get(82..90) == Some(b"FAT32 ") => "FAT32", + () if data.get(54..62) == Some(b"FAT16 ") => "FAT16", + () if data.get(54..62) == Some(b"FAT12 ") => "FAT12", + () if u16_le(&data, 1080) == 0xef53 => "ext2/3/4", + () if matches!(data.get(1024..1026), Some(b"H+" | b"HX")) => "HFS+", + () if data.get(32..36) == Some(b"NXSB") => "APFS", + () if data.starts_with(b"XFSB") => "XFS", + () => "Unrecognized", + }) +} + +#[derive(Debug, PartialEq, Eq)] +struct Gpt { + guid: [u8; 16], + first: u64, + last: u64, + count: usize, + stride: usize, + crc: u32, + entries: Vec, +} + +fn invalid(message: &'static str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} + +fn gpt( + input: &mut (impl Read + Seek), + sector: usize, + blocks: u64, + backup: bool, +) -> io::Result<(Gpt, u64)> { + let end = blocks - 1; + let (at, other) = if backup { (end, 1) } else { (1, end) }; + // audit-allow(DOS-ALLOC): logical sectors are validated to be at most 64 KiB. + let mut header = vec![0; sector]; + read_at(input, at * sector as u64, &mut header)?; + if !header.starts_with(b"EFI PART") { + return Err(invalid("missing signature")); + } + let len = u32_le(&header, 12) as usize; + let checksum = u32_le(&header, 16); + header + .get_mut(16..20) + .ok_or_else(|| invalid("short header"))? + .fill(0); + if !(92..=sector).contains(&len) + || crc32fast::hash(header.get(..len).ok_or_else(|| invalid("short header"))?) != checksum + { + return Err(invalid("invalid header length or checksum")); + } + let first = u64_le(&header, 40); + let last = u64_le(&header, 48); + if u64_le(&header, 24) != at + || u64_le(&header, 32) != other + || first < 2 + || last >= end + || first > last + { + return Err(invalid( + "header locations or usable bounds disagree with disk size", + )); + } + let start = u64_le(&header, 72); + let count = u32_le(&header, 80) as usize; + let stride = u32_le(&header, 84) as usize; + if count == 0 || count > 4096 || stride < 128 || !stride.is_power_of_two() { + return Err(invalid("invalid or unsupported partition entry dimensions")); + } + let bytes = count + .checked_mul(stride) + .filter(|n| *n <= 4 * 1024 * 1024) + .ok_or_else(|| invalid("entry array exceeds inspection limit"))?; + let limit = start + .checked_add(bytes.div_ceil(sector) as u64) + .ok_or_else(|| invalid("entry array overflow"))?; + if (!backup && (start < 2 || limit > first)) || (backup && (start <= last || limit > end)) { + return Err(invalid("entry array outside metadata area")); + } + // audit-allow(DOS-ALLOC): validated against the 4 MiB limit above. + let mut table = vec![0; bytes]; + read_at(input, start * sector as u64, &mut table)?; + let crc = u32_le(&header, 88); + if crc32fast::hash(&table) != crc { + return Err(invalid("partition array checksum mismatch")); + } + let entries = table + .chunks_exact(stride) + .enumerate() + .filter(|(_, e)| e.get(..16).is_some_and(|id| id != [0; 16])) + .map(|(index, e)| { + let name: Vec<_> = e + .get(56..128) + .unwrap_or_default() + .as_chunks::<2>() + .0 + .iter() + .copied() + .map(u16::from_le_bytes) + .take_while(|v| *v != 0) + .collect(); + let kind = String::from_utf16_lossy(&name) + .chars() + .filter(|c| c.is_alphanumeric() || " ._-".contains(*c)) + .collect(); + Partition { + slot: index + 1, + entry_offset: (index * stride) as u64, + first: u64_le(e, 32), + last: u64_le(e, 40), + kind, + } + }) + .collect(); + Ok(( + Gpt { + guid: header + .get(56..72) + .ok_or_else(|| invalid("short disk GUID"))? + .try_into() + .map_err(|_length| invalid("invalid disk GUID"))?, + first, + last, + count, + stride, + crc, + entries, + }, + start * sector as u64, + )) +} + +pub fn inspect( + input: &mut (impl Read + Seek), + size: u64, + known_sector: Option, +) -> io::Result { + let mut mbr = [0; 512]; + read_at(input, 0, &mut mbr)?; + let mut sector = known_sector.unwrap_or(512); + if !(512..=65536).contains(§or) || !sector.is_power_of_two() { + return Err(invalid("unknown logical sector size")); + } + let slots = mbr.get(446..510).unwrap_or_default(); + let protective = slots + .as_chunks::<16>() + .0 + .iter() + .any(|e| e.get(4).copied().unwrap_or(0) == 0xee); + let mut magic = [0; 8]; + let mut is_gpt = protective; + for width in [sector, 4096] { + if known_sector.is_some() && width != sector { + continue; + } + let blocks = size / width as u64; + if blocks >= 3 + && [1, blocks - 1].iter().any(|n| { + read_at(input, n * width as u64, &mut magic).is_ok() && &magic == b"EFI PART" + }) + { + sector = width; + is_gpt = true; + break; + } + } + let blocks = size / sector as u64; + let mut report = Layout { + sector: sector as u64, + ..Layout::default() + }; + let mut bounds = (1, blocks.saturating_sub(1)); + if is_gpt && blocks >= 3 { + if !protective || u16_le(&mbr, 510) != 0xaa55 { + report.notes.push((0, "Missing protective MBR".into())); + } + let primary = gpt(input, sector, blocks, false); + let backup = gpt(input, sector, blocks, true); + for (at, name, copy) in [ + (1, "Primary GPT", &primary), + (blocks - 1, "Backup GPT", &backup), + ] { + report.notes.push(( + at * sector as u64, + match copy { + Ok(_) => format!( + "{} · {}", + crate::i18n::t(name), + crate::i18n::t("Header and array checksums verified") + ), + Err(e) => format!("{} · {e}", crate::i18n::t(name)), + }, + )); + } + if let (Ok((a, _)), Ok((b, _))) = (&primary, &backup) + && a != b + { + report.notes.push(( + sector as u64, + "GPT copies disagree. Showing primary entries.".into(), + )); + } + if let Ok((copy, table_offset)) = primary.or(backup) { + bounds = (copy.first, copy.last); + report.partitions = copy.entries; + for entry in &mut report.partitions { + entry.entry_offset += table_offset; + } + } + } else if u16_le(&mbr, 510) == 0xaa55 && filesystem(input, 0, size)? == "Unrecognized" { + report.notes.push((0, "MBR · primary entries".into())); + for (i, e) in slots + .as_chunks::<16>() + .0 + .iter() + .enumerate() + .filter(|(_, e)| e.get(4).copied().unwrap_or(0) != 0) + { + let first = u64::from(u32_le(e.as_slice(), 8)); + let length = u32_le(e.as_slice(), 12); + if length == 0 { + report.notes.push(( + 446 + i as u64 * 16, + format!("Entry {} has zero length", i + 1), + )); + continue; + } + let kind = match e.get(4).copied().unwrap_or(0) { + 5 | 15 | 0x85 => "Extended container (logical entries uninspected)".into(), + t => format!("MBR type 0x{t:02x}"), + }; + report.partitions.push(Partition { + slot: i + 1, + entry_offset: 446 + i as u64 * 16, + first, + last: first + u64::from(length) - 1, + kind, + }); + } + } else { + report.notes.push(( + 0, + "No recognized disk partition table. A volume image may contain only a filesystem." + .into(), + )); + } + report.partitions.sort_by_key(|p| p.first); + let mut previous_end = None; + for p in &report.partitions { + let usable = bounds.0..=bounds.1; + if p.first > p.last || !usable.contains(&p.first) || !usable.contains(&p.last) { + report.notes.push(( + p.entry_offset, + format!("Entry {} exceeds usable bounds or is reversed", p.slot), + )); + } + if previous_end.is_some_and(|end| p.first <= end) { + report.notes.push(( + p.entry_offset, + format!("Entry {} overlaps a previous entry", p.slot), + )); + } + previous_end = Some(previous_end.unwrap_or(0).max(p.last)); + } + Ok(report) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + fn fixture(sector: usize) -> Vec { + let mut disk = vec![0; 128 * sector]; + disk[450] = 0xee; + disk[510..512].copy_from_slice(&[0x55, 0xaa]); + let mut entry = [0u8; 128]; + entry[0] = 1; + entry[32..40].copy_from_slice(&40u64.to_le_bytes()); + entry[40..48].copy_from_slice(&60u64.to_le_bytes()); + for (current, alternate, array) in [(1usize, 127u64, 2usize), (127, 1, 126)] { + let mut h = [0; 92]; + h[..8].copy_from_slice(b"EFI PART"); + h[8..12].copy_from_slice(&0x10000u32.to_le_bytes()); + h[12..16].copy_from_slice(&92u32.to_le_bytes()); + for (pos, value) in [ + (24, current as u64), + (32, alternate), + (40, 34), + (48, 94), + (72, array as u64), + ] { + h[pos..pos + 8].copy_from_slice(&value.to_le_bytes()); + } + h[80..84].copy_from_slice(&1u32.to_le_bytes()); + h[84..88].copy_from_slice(&128u32.to_le_bytes()); + h[88..92].copy_from_slice(&crc32fast::hash(&entry).to_le_bytes()); + let crc = crc32fast::hash(&h); + h[16..20].copy_from_slice(&crc.to_le_bytes()); + disk[current * sector..current * sector + 92].copy_from_slice(&h); + disk[array * sector..array * sector + 128].copy_from_slice(&entry); + } + disk + } + fn layout(disk: Vec) -> Layout { + let size = disk.len() as u64; + inspect(&mut Cursor::new(disk), size, None).unwrap() + } + #[test] + fn both_gpt_copies_and_4k_backup_survive_independent_checks() { + for sector in [512, 4096] { + let mut disk = fixture(sector); + let good = layout(disk.clone()); + assert_eq!(good.sector, sector as u64); + assert_eq!(good.partitions[0].last, 60); + assert!(good.notes.iter().all(|(_, s)| s.contains("verified"))); + disk[sector] = 0; + let backup = layout(disk); + assert_eq!(backup.sector, sector as u64); + assert_eq!(backup.partitions[0].first, good.partitions[0].first); + assert_eq!(backup.partitions[0].entry_offset, 126 * sector as u64); + assert_eq!(good.partitions[0].entry_offset, 2 * sector as u64); + assert!( + backup + .notes + .iter() + .any(|(_, s)| s.contains("missing signature")) + ); + } + } + #[test] + fn checksum_damage_and_valid_but_conflicting_copies_are_distinct() { + let mut disk = fixture(512); + let table = 126 * 512; + disk[table + 32] = 42; + assert!( + layout(disk.clone()) + .notes + .iter() + .any(|(_, s)| s.contains("array checksum mismatch")) + ); + let array_crc = crc32fast::hash(&disk[table..table + 128]); + let h = &mut disk[127 * 512..127 * 512 + 92]; + h[88..92].copy_from_slice(&array_crc.to_le_bytes()); + h[16..20].fill(0); + let crc = crc32fast::hash(h); + h[16..20].copy_from_slice(&crc.to_le_bytes()); + assert!( + layout(disk) + .notes + .iter() + .any(|(_, s)| s.contains("disagree")) + ); + } + #[test] + fn mbr_overlaps_and_out_of_bounds_entries_are_reported() { + let mut disk = vec![0; 512 * 8]; + disk[510..512].copy_from_slice(&[0x55, 0xaa]); + for (at, start, len) in [(446, 1u32, 4u32), (462, 4, 12)] { + disk[at + 4] = 0x83; + disk[at + 8..at + 12].copy_from_slice(&start.to_le_bytes()); + disk[at + 12..at + 16].copy_from_slice(&len.to_le_bytes()); + } + let result = layout(disk); + assert_eq!(result.partitions.len(), 2); + assert!(result.notes.iter().any(|(_, s)| s.contains("overlaps"))); + assert!(result.notes.iter().any(|(_, s)| s.contains("bounds"))); + } +} diff --git a/src/sector_view.rs b/src/sector_view.rs new file mode 100644 index 0000000..6fbd7d3 --- /dev/null +++ b/src/sector_view.rs @@ -0,0 +1,211 @@ +//! Read-only windows on a disk and an optional comparison image. +use reclaim::i18n; +use std::{ + fmt::Write as _, + fs::{File, OpenOptions}, + io::{self, Read, Seek, SeekFrom}, + path::PathBuf, + sync::Arc, +}; + +pub const WINDOW: u64 = 512; + +#[derive(Debug)] +pub struct Image { + pub path: PathBuf, + file: File, + size: u64, +} +impl Image { + pub fn open(path: PathBuf) -> io::Result> { + let mut options = OpenOptions::new(); + options.read(true); + // A named pipe selected in the image picker must never wait for a writer. + #[cfg(any(target_os = "linux", target_os = "macos"))] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NONBLOCK); + } + let file = options.open(&path)?; + let meta = file.metadata()?; + if !meta.is_file() { + return Err(io::Error::other(i18n::t("Choose a raw disk image"))); + } + Ok(Arc::new(Self { + path, + file, + size: meta.len(), + })) + } +} + +pub fn address(text: &str, sector: u64) -> Option { + let text = text.trim(); + let (number, multiplier) = match text.split_once(char::is_whitespace) { + Some((prefix, value)) if prefix.eq_ignore_ascii_case("LBA") => (value.trim(), sector), + _ => (text, 1), + }; + let value = if let Some(hex) = number + .strip_prefix("0x") + .or_else(|| number.strip_prefix("0X")) + { + u64::from_str_radix(hex, 16).ok()? + } else { + number.parse::().ok()? + }; + value.checked_mul(multiplier) +} + +#[derive(Default)] +pub struct Viewer { + pub offset: u64, + pub image: Option>, +} + +pub struct Page { + pub viewer: Viewer, + pub dump: String, + pub last: u64, + pub more: bool, +} +fn read_at(input: &mut (impl Read + Seek), offset: u64, size: u64) -> io::Result> { + let count = usize::try_from(size.saturating_sub(offset).min(WINDOW)).unwrap_or(0); + let mut block = [0; 512]; + let bytes = block + .get_mut(..count) + .ok_or_else(|| io::Error::other("Invalid read buffer length"))?; + if !bytes.is_empty() { + input.seek(SeekFrom::Start(offset))?; + input.read_exact(bytes)?; + } + Ok(bytes.to_vec()) +} + +fn column(bytes: &[u8], count: usize, width: usize) -> String { + let mut hex = String::new(); + let mut ascii = String::new(); + for i in 0..width { + if let Some(&byte) = bytes.get(i) { + write!(hex, "{byte:02X} ").ok(); + ascii.push(if byte.is_ascii_graphic() || byte == b' ' { + char::from(byte) + } else { + '.' + }); + } else if i < count { + hex.push_str("-- "); + ascii.push(' '); + } else { + hex.push_str(" "); + ascii.push(' '); + } + } + format!("{hex} |{ascii}|") +} + +fn dump(offset: u64, source: &[u8], comparison: Option<&[u8]>) -> String { + let width = if comparison.is_some() { 8 } else { 16 }; + let length = source.len().max(comparison.map_or(0, <[u8]>::len)); + let address_width = + if u32::try_from(offset.saturating_add(length.saturating_sub(1) as u64)).is_ok() { + 8 + } else { + 16 + }; + let mut out = String::new(); + for start in (0..length).step_by(width) { + let end = (start + width).min(length); + let count = end - start; + let left = source.get(start..).unwrap_or_default(); + write!( + out, + "{:0address_width$X} {}", + offset + start as u64, + column(left, count, width) + ) + .ok(); + if let Some(other) = comparison { + let right = other.get(start..).unwrap_or_default(); + write!(out, " {}", column(right, count, width)).ok(); + if (0..count).any(|i| left.get(i) != right.get(i)) { + // The marker line sits immediately below the different bytes of the second image. + write!( + out, + "\n{:padding$}", + "", + padding = address_width + 2 + width * 4 + 7 + ) + .ok(); + for i in 0..count { + out.push_str(if left.get(i) == right.get(i) { + " " + } else { + "^^ " + }); + } + } + } + out.push('\n'); + } + out +} + +pub fn read( + mut reader: impl Read + Seek, + size: u64, + offset: u64, + image: Option>, +) -> io::Result { + let end = size.max(image.as_ref().map_or(0, |i| i.size)); + if offset >= end { + return Err(io::Error::other(i18n::t( + "Address outside the image or drive.", + ))); + } + let left = read_at(&mut reader, offset, size)?; + let right = image + .as_ref() + .map(|i| read_at(&mut i.file.try_clone()?, offset, i.size)) + .transpose()?; + let last = offset + end.saturating_sub(offset).min(WINDOW) - 1; + Ok(Page { + dump: dump(offset, &left, right.as_deref()), + viewer: Viewer { offset, image }, + last, + more: last < end - 1, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn parses_large_offsets_and_uses_source_logical_sector_size() { + assert_eq!(address("0x100000000", 512), Some(1 << 32)); + assert_eq!(address(" lba 0x10 ", 4096), Some(65536)); + for bad in ["LBA 18446744073709551615", "-1", "x42", "LBA"] { + assert_eq!(address(bad, 512), None); + } + } + + #[test] + fn comparison_covers_both_files_and_marks_only_different_bytes() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("second.img"); + std::fs::write(&path, b"axcd!").unwrap(); + let image = Image::open(path).unwrap(); + let page = read(Cursor::new(b"abcd"), 4, 0, Some(Arc::clone(&image))).unwrap(); + let mut lines = page.dump.lines(); + let row = lines.next().unwrap(); + let markers = lines.next().unwrap(); + assert!(row.contains("61 62 63 64 --") && row.contains("61 78 63 64 21")); + assert_eq!(markers.find("^^"), row.find("78")); + assert_eq!(markers.rfind("^^"), row.find("21")); + let tail = read(Cursor::new(b"abcd"), 4, 4, Some(image)).unwrap(); + assert_eq!(tail.last, 4); + assert!(!tail.more); + assert!(read(Cursor::new(b"abcd"), 4, 4, None).is_err()); + } +} diff --git a/src/slint_ui_tests.rs b/src/slint_ui_tests.rs index 255a77f..08fa7d3 100644 --- a/src/slint_ui_tests.rs +++ b/src/slint_ui_tests.rs @@ -2247,3 +2247,100 @@ fn inspector_scrollbar_keeps_rtl_and_ltr_metadata_clear() { ); } } + +#[test] +fn quick_check_opens_a_read_only_image_report_from_sources() { + use i_slint_backend_testing::ElementHandle; + slint::platform::set_platform(Box::new(i_slint_backend_testing::TestingBackend::new( + i_slint_backend_testing::TestingBackendOptions { + renderer_name: Some("software".into()), + ..Default::default() + }, + ))) + .unwrap(); + let folder = tempfile::tempdir().unwrap(); + let path = folder.path().join("volume.img"); + let mut data = [0; 4096]; + data[510..512].copy_from_slice(&[0x55, 0xaa]); + data[450] = 7; + data[454] = 2; + data[458] = 4; + data[1027..1035].copy_from_slice(b"NTFS "); + std::fs::write(&path, data).unwrap(); + let ui = AppWindow::new().unwrap(); + let state = Rc::new(RefCell::new(Reclaim::default())); + state.borrow_mut().source = Some(path.clone()); + state.borrow_mut().opened_image = Some((path, 4096)); + register_drive_checks(&ui, &state); + state.borrow_mut().sync_ui(&ui); + ui.show().unwrap(); + ui.window().set_size(slint::PhysicalSize::new(900, 640)); + ElementHandle::find_by_accessible_label(&ui, "Quick Drive Check") + .next() + .unwrap() + .invoke_accessible_default_action(); + assert_eq!(ui.get_page(), 3); + let wait_for_check = || { + let start = std::time::Instant::now(); + while ui.get_check_running() { + state.borrow_mut().poll_check(&ui); + assert!(start.elapsed() < Duration::from_secs(5)); + std::thread::yield_now(); + } + }; + wait_for_check(); + assert!(ui.get_check_findings().iter().any(|s| s.contains("MBR"))); + assert!(ui.get_check_health().contains("Disk images")); + assert_eq!(ui.get_check_partitions().row_count(), 1); + ElementHandle::find_by_accessible_label(&ui, "Inspect partition") + .next() + .unwrap() + .invoke_accessible_default_action(); + wait_for_check(); + assert!(ui.get_partition_detail().contains("NTFS")); + assert!(ui.get_partition_detail().contains("1024")); + ui.window().take_snapshot().unwrap(); + layout_checks::assert_controls_clear(&ui, (900., 640.), "image report"); + ElementHandle::find_by_accessible_label(&ui, "View bytes") + .next() + .unwrap() + .invoke_accessible_default_action(); + wait_for_check(); + assert_eq!(ui.get_page(), 4); + assert_eq!(ui.get_sector_address(), "0x0"); + ui.set_page(3); + ElementHandle::find_by_accessible_label(&ui, "View partition bytes") + .next() + .unwrap() + .invoke_accessible_default_action(); + wait_for_check(); + assert_eq!(ui.get_sector_address(), "0x400"); + assert!(ui.get_sector_dump().contains("NTFS")); + ui.set_sector_address("LBA 3".into()); + ui.invoke_sector_navigate(0); + wait_for_check(); + assert_eq!(ui.get_sector_address(), "0x600"); + let image = folder.path().join("comparison.img"); + std::fs::write(&image, [b'A'; 1550]).unwrap(); + show_sectors(&mut state.borrow_mut(), &ui, SectorAction::Compare(image)); + wait_for_check(); + assert!(ui.get_sector_dump().contains("^^")); + assert!(ui.get_sector_dump().contains("--")); + let snapshot = ui.window().take_snapshot().unwrap(); + if let Ok(directory) = std::env::var("RECLAIM_PREVIEW_DIR") { + std::fs::create_dir_all(&directory).unwrap(); + image::save_buffer( + std::path::Path::new(&directory).join("sector-comparison.png"), + snapshot.as_bytes(), + snapshot.width(), + snapshot.height(), + image::ColorType::Rgba8, + ) + .unwrap(); + } + layout_checks::assert_controls_clear(&ui, (900., 640.), "sector comparison"); + ui.invoke_sector_comparison(false); + wait_for_check(); + assert!(ui.get_sector_compare().is_empty()); + ui.hide().unwrap(); +} diff --git a/src/ui_text.rs b/src/ui_text.rs index d1a7961..adf21de 100644 --- a/src/ui_text.rs +++ b/src/ui_text.rs @@ -27,6 +27,22 @@ macro_rules! ui_strings { } ui_strings! { + set_sector_viewer => "Sector viewer", + set_view_bytes => "View bytes", + set_partition_bytes => "View partition bytes", + set_compare_image => "Compare image", + set_close_comparison => "Close comparison", + set_viewer_address => "Byte offset or LBA", + set_jump => "Go", + set_previous => "Previous", + set_next => "Next", + set_byte_legend => "Source on the left, comparison on the right. ^^ marks differences and -- marks missing bytes.", + set_checking_drive => "Reading drive information…", + set_health_details => "Device readings", + set_inspect_partition => "Inspect partition", + set_partition_table => "Partition table", + set_drive_health => "SMART and NVMe health", + set_quick_check => "Quick Drive Check", set_no_source_selected => "No source selected", set_select_a_file_to_inspect => "Select a file to inspect its details.", set_reclaim => "Reclaim", diff --git a/ui/app.slint b/ui/app.slint index 6a642cf..8e70ecd 100644 --- a/ui/app.slint +++ b/ui/app.slint @@ -2,6 +2,22 @@ import "../assets/fonts/DejaVuSans.ttf"; import "../assets/fonts/DejaVuSans-Bold.ttf"; import "../assets/fonts/DejaVuSansMono.ttf"; export global Strings { + in-out property sector-viewer: "Sector viewer"; + in-out property view-bytes: "View bytes"; + in-out property partition-bytes: "View partition bytes"; + in-out property compare-image: "Compare image"; + in-out property close-comparison: "Close comparison"; + in-out property viewer-address: "Byte offset or LBA"; + in-out property jump: "Go"; + in-out property previous: "Previous"; + in-out property next: "Next"; + in-out property byte-legend: "Source on the left, comparison on the right. ^^ marks differences and -- marks missing bytes."; + in-out property checking-drive: "Reading drive information…"; + in-out property health-details: "Device readings"; + in-out property inspect-partition: "Inspect partition"; + in-out property partition-table: "Partition table"; + in-out property drive-health: "SMART and NVMe health"; + in-out property quick-check: "Quick Drive Check"; in-out property window-title: "Reclaim - File Recovery"; in-out property language: "Language"; in-out property appearance: "Appearance"; @@ -873,6 +889,32 @@ export component AppWindow inherits Window { callback open-link(AboutLink); callback apply-update(); callback dismiss-update(); + callback view-sectors(int, int); + callback sector-navigate(int); + callback sector-comparison(bool); + in property can-view-sectors; + in property <[string]> check-findings; + in property sector-source; + in-out property sector-address; + in property sector-compare; + in property sector-dump; + in property sector-status; + in property sector-error; + in property sector-prev; + in property sector-next; + in property sector-loading; + callback check-drive(); callback open-partition(int); callback clear-partition(); + in property can-check; + in property check-running; + in property partition-loading; + in property check-overview; + in property check-health; + in property check-raw; + in property check-layout; + in property <[string]> check-partitions; + in-out property check-index; + in property partition-detail; + in-out property show-raw; callback open-image(); callback refresh(); callback select-drive(int); callback scan(); callback stop(); // A recovery folder that may share a drive with the scanned source waits here // for the user's decision. A same-drive folder can only be replaced, never accepted. @@ -895,6 +937,7 @@ export component AppWindow inherits Window { } Rectangle { height: 20px; } NavItem { text: Strings.sources; icon: @image-url("icons/drive.svg"); current: root.page == 0; clicked => { root.page = 0; } } + if root.check-overview != "" : NavItem { text: Strings.quick-check; icon: @image-url("icons/shield.svg"); current: root.page == 3 || root.page == 4; clicked => { root.page = 3; } } NavItem { text: Strings.recovered-files; icon: @image-url("icons/files.svg"); current: root.page == 1; clicked => { root.page = 1; } } NavItem { text: Strings.settings-help; icon: @image-url("icons/settings.svg"); current: root.page == 2; clicked => { root.page = 2; } } Rectangle { vertical-stretch: 1; min-height: 24px; } @@ -919,8 +962,8 @@ export component AppWindow inherits Window { // ── Page ──────────────────────────────────────────────── VerticalLayout { horizontal-stretch: 1; padding: 24px; padding-top: root.custom-frame ? 40px : 20px; spacing: 16px; VerticalLayout { spacing: 4px; vertical-stretch: 0; - Label { text: root.page == 0 ? Strings.sources : root.page == 1 ? Strings.recovered-files : Strings.settings-help; color: Palette.ink; font-size: 24px; font-weight: 700; } - Body { text: root.page == 0 ? Strings.choose-a-drive-or-disk : root.page == 1 ? Strings.inspect-candidates-choose-your-files : Strings.appearance-updates-and-a-little; } + Label { text: root.page == 0 ? Strings.sources : root.page == 1 ? Strings.recovered-files : root.page == 3 ? Strings.quick-check : root.page == 4 ? Strings.sector-viewer : Strings.settings-help; color: Palette.ink; font-size: 24px; font-weight: 700; } + if root.page < 3 : Body { text: root.page == 0 ? Strings.choose-a-drive-or-disk : root.page == 1 ? Strings.inspect-candidates-choose-your-files : Strings.appearance-updates-and-a-little; } } // Sources: pick a drive, then start the scan. if root.page == 0 : VerticalLayout { vertical-stretch: 1; spacing: 12px; @@ -982,7 +1025,7 @@ export component AppWindow inherits Window { } VerticalLayout { horizontal-stretch: 1; min-width: 0px; spacing: 1px; alignment: center; Row { spacing: 6px; - Label { text: drive.name; color: drive.available ? Palette.ink : Palette.muted; font-size: 14px; font-weight: 500; overflow: elide; min-width: 0px; horizontal-stretch: 0; } + Label { text: drive.name; color: drive.icon != DriveIcon.phone ? Palette.ink : Palette.muted; font-size: 14px; font-weight: 500; overflow: elide; min-width: 0px; horizontal-stretch: 0; } if drive.device != "" : DeviceTag { text: drive.device; } Rectangle { horizontal-stretch: 1; } } @@ -995,19 +1038,19 @@ export component AppWindow inherits Window { Label { text: drive.size; color: Palette.muted; font-size: 13px; vertical-alignment: center; } } forward-focus: drive-focus; - // Unavailable rows (locked volumes, phones) still take focus, so keyboard and + // Phones still take focus, so keyboard and // screen reader users reach the line that says why they cannot be scanned. accessible-role: radio-button; accessible-label: drive.name; accessible-description: drive.warning != "" ? drive.detail + Strings.separator + drive.warning : drive.detail; accessible-checkable: true; accessible-checked: root.selected-drive == i; - accessible-enabled: !root.busy && drive.available; - accessible-action-default => { if !root.busy && drive.available { root.select-drive(i); } } + accessible-enabled: !root.busy && drive.icon != DriveIcon.phone; + accessible-action-default => { if !root.busy && drive.icon != DriveIcon.phone { root.select-drive(i); } } border-width: drive-focus.ring ? 2px : 0px; border-color: Palette.accent; drive-focus := KeyFocus { enabled: !root.busy; - key-pressed(event) => { if (event.text == Key.Space || event.text == Key.Return) && drive.available { root.select-drive(i); return accept; } return reject; } + key-pressed(event) => { if (event.text == Key.Space || event.text == Key.Return) && drive.icon != DriveIcon.phone { root.select-drive(i); return accept; } return reject; } } - area := TouchArea { enabled: !root.busy && drive.available; mouse-cursor: pointer; clicked => { drive-focus.focus(); root.select-drive(i); } } + area := TouchArea { enabled: !root.busy && drive.icon != DriveIcon.phone; mouse-cursor: pointer; clicked => { drive-focus.focus(); root.select-drive(i); } } } } } } @@ -1030,6 +1073,7 @@ export component AppWindow inherits Window { // Why Start scanning is unavailable, next to it. if !root.has-source : scan-hint := Label { text: Strings.choose-a-source-above; color: Palette.secondary; font-size: 13px; wrap: word-wrap; } } + Action { height: 40px; text: Strings.quick-check; enabled: root.can-check && !root.check-running; clicked => { root.check-drive(); } } Action { height: 40px; text: Strings.start-scanning; icon: @image-url("icons/search.svg"); primary: true; enabled: root.can-scan; clicked => { root.scan(); } } } if root.has-source && root.selected-drive >= 0 && root.selected-drive < root.drives.length && root.drives[root.selected-drive].warning != "" : HorizontalLayout { spacing: 8px; @@ -1042,6 +1086,68 @@ export component AppWindow inherits Window { } } Rectangle { vertical-stretch: 1; } } + if root.page == 3 : VerticalLayout { spacing: 12px; + Card { vertical-stretch: 1; ScrollView { VerticalLayout { padding: 16px; spacing: 12px; alignment: start; + SectionLabel { text: Strings.selected-source; } + Body { text: root.check-overview; color: Palette.ink; } + if root.check-running : Body { text: Strings.checking-drive; } + if !root.check-running || root.partition-loading : VerticalLayout { spacing: 10px; + Divider {} + SectionLabel { text: Strings.drive-health; } + Body { text: root.check-health; color: Palette.ink; } + if root.check-raw != "" : Action { text: Strings.health-details; clicked => { root.show-raw = !root.show-raw; } } + if root.show-raw : Body { text: root.check-raw; } + Divider {} + SectionLabel { text: Strings.partition-table; } + Body { text: root.check-layout; color: Palette.ink; } + for finding[i] in root.check-findings : Row { spacing: 10px; + Body { text: finding; horizontal-stretch: 1; min-width: 0px; } + Action { text: Strings.view-bytes; enabled: !root.check-running; clicked => { root.view-sectors(2, i); } } + } + if root.check-partitions.length > 0 && !root.partition-loading : Choice { model: root.check-partitions; current-index <=> root.check-index; selected(i) => {root.check-index = i; root.clear-partition();} } + if root.check-partitions.length > 0 : Action { enabled: !root.partition-loading; text: Strings.inspect-partition; clicked => { root.open-partition(root.check-index); } } + if root.check-partitions.length > 0 : Action { text: Strings.partition-bytes; enabled: !root.check-running; clicked => { root.view-sectors(1, root.check-index); } } + if root.partition-detail != "" : Body { text: root.partition-detail; color: Palette.ink; } + } + } } } + Row { alignment: start; spacing: 8px; + Action { text: Strings.sources; clicked => {root.page = 0;} } + Action { text: Strings.sector-viewer; enabled: root.can-view-sectors && !root.check-running; clicked => {root.view-sectors(0,0);} } + } + } + if root.page == 4 : VerticalLayout { spacing: 10px; + Body { text: Strings.selected-source + " " + root.sector-source; color: Palette.ink; } + if root.sector-compare != "" : Body { text: Strings.compare-image + " " + root.sector-compare; } + Row { spacing: 8px; height: Metrics.control; + Label { text: Strings.viewer-address; color: Palette.ink; vertical-alignment: center; } + Rectangle { height: Metrics.control; min-width: 110px; border-radius: Metrics.radius; background: Palette.surface; border-color: address-input.has-focus ? Palette.accent : Palette.line; border-width: 1px; horizontal-stretch: 1; + address-input := TextInput { x: 8px; width: parent.width - 16px; height: parent.height; single-line: true; enabled: !root.check-running; + text <=> root.sector-address; accessible-label: Strings.viewer-address; color: Palette.ink; vertical-alignment: center; + accepted => { root.sector-navigate(0); } + } + } + Action { text: Strings.jump; enabled: !root.check-running; clicked => {root.sector-navigate(0);} } + } + Row { spacing: 8px; alignment: start; + Action { text: Strings.compare-image; enabled: !root.check-running; clicked => { root.sector-comparison(true); } } + if root.sector-compare != "" : Action { text: Strings.close-comparison; enabled: !root.check-running; clicked => { root.sector-comparison(false); } } + } + if root.sector-error != "" : Body { text: root.sector-error; color: Palette.danger; } + Body { text: root.sector-loading ? Strings.checking-drive : root.sector-status; } + if root.sector-compare != "" : Body { text: Strings.byte-legend; } + Card { vertical-stretch: 1; + ScrollView { VerticalLayout { padding: 8px; alignment: start; + Text { text: root.sector-dump; font-family: "DejaVu Sans Mono"; font-size: root.width < 980px && root.sector-compare != "" ? 11px : 12px; color: Palette.ink; + horizontal-alignment: left; wrap: no-wrap; accessible-role: text; accessible-label: root.sector-dump; + } + } } + } + Row { spacing: 8px; alignment: start; + Action { text: Strings.previous; enabled: root.sector-prev && !root.check-running; clicked => {root.sector-navigate(-1);} } + Action { text: Strings.next; enabled: root.sector-next && !root.check-running; clicked => {root.sector-navigate(1);} } + Action { text: Strings.quick-check; clicked => {root.page = 3;} } + } + } // Recovered files: filter, inspect, select, recover. // Two columns all the way down: the list column (search, list, hint) and the // inspector column (category, details, Recover), so every edge lines up. From b0ee17745c218ac960969faf0ca5ff904aeb4f82 Mon Sep 17 00:00:00 2001 From: sudo-py-dev Date: Tue, 24 Nov 2026 18:31:45 +0200 Subject: [PATCH 2/2] Address drive diagnostics review findings --- locales/ar.json | 2 + locales/de.json | 2 + locales/en.json | 2 + locales/es.json | 2 + locales/fr.json | 2 + locales/he.json | 2 + locales/it.json | 2 + locales/nl.json | 2 + locales/pt.json | 2 + locales/ru.json | 2 + src/allocation.rs | 1 + src/allocation/fat.rs | 72 +++++++++++++++++++-- src/drive_check.rs | 3 +- src/drives/macos.rs | 94 ++++++++++++++++++++++------ src/main.rs | 3 +- src/partition.rs | 142 +++++++++++++++++++++++++++++++++++------- src/sector_view.rs | 59 +++++++++++++----- 17 files changed, 330 insertions(+), 64 deletions(-) diff --git a/locales/ar.json b/locales/ar.json index f6ffd21..54d5934 100644 --- a/locales/ar.json +++ b/locales/ar.json @@ -1,4 +1,6 @@ { + "Invalid protective MBR range": "نطاق سجل MBR الوقائي غير صالح", + "The comparison image changed. Select Compare image to reload it.": "تغيّرت صورة المقارنة. اختر «مقارنة صورة» لإعادة تحميلها.", "Sector viewer": "عارض القطاعات", "View bytes": "عرض البايتات", "View partition bytes": "عرض بايتات القسم", diff --git a/locales/de.json b/locales/de.json index ad9a1e8..76eda56 100644 --- a/locales/de.json +++ b/locales/de.json @@ -1,4 +1,6 @@ { + "Invalid protective MBR range": "Ungültiger Bereich im Schutz-MBR", + "The comparison image changed. Select Compare image to reload it.": "Das Vergleichsabbild wurde geändert. Wählen Sie „Abbild vergleichen“, um es neu zu laden.", "Sector viewer": "Sektoransicht", "View bytes": "Bytes anzeigen", "View partition bytes": "Partitionsbytes anzeigen", diff --git a/locales/en.json b/locales/en.json index 73a0635..07a9ecb 100644 --- a/locales/en.json +++ b/locales/en.json @@ -1,4 +1,6 @@ { + "Invalid protective MBR range": "Invalid protective MBR range", + "The comparison image changed. Select Compare image to reload it.": "The comparison image changed. Select Compare image to reload it.", "Sector viewer": "Sector viewer", "View bytes": "View bytes", "View partition bytes": "View partition bytes", diff --git a/locales/es.json b/locales/es.json index 039bfbd..32529cf 100644 --- a/locales/es.json +++ b/locales/es.json @@ -1,4 +1,6 @@ { + "Invalid protective MBR range": "Intervalo no válido en el MBR protector", + "The comparison image changed. Select Compare image to reload it.": "La imagen de comparación cambió. Selecciona «Comparar imagen» para volver a cargarla.", "Sector viewer": "Visor de sectores", "View bytes": "Ver bytes", "View partition bytes": "Ver bytes de la partición", diff --git a/locales/fr.json b/locales/fr.json index 13b5c5d..12bbe65 100644 --- a/locales/fr.json +++ b/locales/fr.json @@ -1,4 +1,6 @@ { + "Invalid protective MBR range": "Plage non valide dans le MBR protecteur", + "The comparison image changed. Select Compare image to reload it.": "L’image de comparaison a changé. Sélectionnez « Comparer une image » pour la recharger.", "Sector viewer": "Vue des secteurs", "View bytes": "Voir les octets", "View partition bytes": "Voir les octets de la partition", diff --git a/locales/he.json b/locales/he.json index 957a028..c68ff5f 100644 --- a/locales/he.json +++ b/locales/he.json @@ -1,4 +1,6 @@ { + "Invalid protective MBR range": "טווח לא תקין ב־MBR המגן", + "The comparison image changed. Select Compare image to reload it.": "תמונת ההשוואה השתנתה. יש לבחור באפשרות ״השוואת קובץ דמות״ כדי לטעון אותה מחדש.", "Sector viewer": "מציג סקטורים", "View bytes": "הצגת בתים", "View partition bytes": "הצגת בתי המחיצה", diff --git a/locales/it.json b/locales/it.json index eab0685..6b8e289 100644 --- a/locales/it.json +++ b/locales/it.json @@ -1,4 +1,6 @@ { + "Invalid protective MBR range": "Intervallo non valido nel MBR protettivo", + "The comparison image changed. Select Compare image to reload it.": "L’immagine di confronto è cambiata. Seleziona «Confronta immagine» per ricaricarla.", "Sector viewer": "Visualizzatore settori", "View bytes": "Mostra byte", "View partition bytes": "Mostra byte della partizione", diff --git a/locales/nl.json b/locales/nl.json index 9b0c31f..6913070 100644 --- a/locales/nl.json +++ b/locales/nl.json @@ -1,4 +1,6 @@ { + "Invalid protective MBR range": "Ongeldig bereik in de beschermende MBR", + "The comparison image changed. Select Compare image to reload it.": "De vergelijkingskopie is gewijzigd. Kies ‘Schijfkopie vergelijken’ om deze opnieuw te laden.", "Sector viewer": "Sectorweergave", "View bytes": "Bytes bekijken", "View partition bytes": "Partitiebytes bekijken", diff --git a/locales/pt.json b/locales/pt.json index 1c032bc..6440c99 100644 --- a/locales/pt.json +++ b/locales/pt.json @@ -1,4 +1,6 @@ { + "Invalid protective MBR range": "Intervalo inválido no MBR de proteção", + "The comparison image changed. Select Compare image to reload it.": "A imagem de comparação foi alterada. Selecione «Comparar imagem» para a recarregar.", "Sector viewer": "Visualizador de setores", "View bytes": "Ver bytes", "View partition bytes": "Ver bytes da partição", diff --git a/locales/ru.json b/locales/ru.json index 30d8c33..78ec859 100644 --- a/locales/ru.json +++ b/locales/ru.json @@ -1,4 +1,6 @@ { + "Invalid protective MBR range": "Недопустимый диапазон в защитной MBR", + "The comparison image changed. Select Compare image to reload it.": "Образ для сравнения изменился. Выберите «Сравнить образ», чтобы загрузить его заново.", "Sector viewer": "Просмотр секторов", "View bytes": "Показать байты", "View partition bytes": "Показать байты раздела", diff --git a/src/allocation.rs b/src/allocation.rs index efbb15a..a789306 100644 --- a/src/allocation.rs +++ b/src/allocation.rs @@ -7,6 +7,7 @@ use std::{ mod directory; mod ext; mod fat; +pub(crate) use fat::signature as fat_signature; mod hfs; mod indirect; mod journal; diff --git a/src/allocation/fat.rs b/src/allocation/fat.rs index ee00e12..4af425e 100644 --- a/src/allocation/fat.rs +++ b/src/allocation/fat.rs @@ -67,12 +67,21 @@ impl Table { }) } } -pub(super) fn classic( - input: &mut (impl Read + Seek), - b: &[u8], - total: u64, - cancel: &AtomicBool, -) -> io::Result { +struct Geometry { + sector: u64, + per: u64, + reserved: u64, + fats: u64, + roots: u64, + first: u64, + clusters: u64, + bits: u32, + name: &'static str, + fat_sectors: u64, + fat_length: u64, +} + +fn geometry(b: &[u8], total: u64) -> io::Result { let sector = u16at(b, 11); let per = u64::from(b[13]); let reserved = u16at(b, 14); @@ -122,6 +131,57 @@ pub(super) fn classic( if required > fat_length { return Err(invalid("FAT cannot describe every data cluster")); } + Ok(Geometry { + sector, + per, + reserved, + fats, + roots, + first, + clusters, + bits, + name, + fat_sectors, + fat_length, + }) +} + +pub(crate) fn signature(b: &[u8], total: u64) -> Option<&'static str> { + if b.len() < 512 + || u16at(b, 510) != 0xaa55 + || !(b.first() == Some(&0xe9) || (b.first() == Some(&0xeb) && b.get(2) == Some(&0x90))) + || !matches!(u16at(b, 11), 512 | 1024 | 2048 | 4096) + || !b.get(13).is_some_and(|n| n.is_power_of_two()) + || !matches!(b.get(21), Some(0xf0 | 0xf8..=0xff)) + { + return None; + } + let g = geometry(b, total).ok()?; + if g.bits == 32 && !(2..=g.clusters + 1).contains(&u32at(b, 44)) { + return None; + } + Some(g.name) +} + +pub(super) fn classic( + input: &mut (impl Read + Seek), + b: &[u8], + total: u64, + cancel: &AtomicBool, +) -> io::Result { + let Geometry { + sector, + per, + reserved, + fats, + roots, + first, + clusters, + bits, + name, + fat_sectors, + fat_length, + } = geometry(b, total)?; let flags = if bits == 32 { u16at(b, 40) } else { 0 }; let active = if flags & 0x80 != 0 { flags & 15 } else { 0 }; if active >= fats { diff --git a/src/drive_check.rs b/src/drive_check.rs index 2b86dcb..b05fdfd 100644 --- a/src/drive_check.rs +++ b/src/drive_check.rs @@ -95,7 +95,8 @@ impl Report { p.last .checked_add(1) .and_then(|n| n.checked_mul(table.sector)), - ) && start < end + ) && p.within_usable_bounds + && start < end && end <= size { self.choices.push(label); diff --git a/src/drives/macos.rs b/src/drives/macos.rs index 7a96666..bd361e5 100644 --- a/src/drives/macos.rs +++ b/src/drives/macos.rs @@ -49,6 +49,12 @@ unsafe extern "C" { plane: *const std::ffi::c_char, parent: *mut u32, ) -> i32; + fn IORegistryEntryGetParentIterator( + entry: u32, + plane: *const std::ffi::c_char, + iterator: *mut u32, + ) -> i32; + fn IOObjectConformsTo(object: u32, class: *const std::ffi::c_char) -> libc::boolean_t; fn IORegistryEntryGetRegistryEntryID(entry: u32, id: *mut u64) -> i32; } #[link(name = "DiskArbitration", kind = "framework")] @@ -187,10 +193,49 @@ fn registry_id(object: u32) -> Option { // SAFETY: object is a live registry entry and id a valid out-pointer. (unsafe { IORegistryEntryGetRegistryEntryID(object, &raw mut id) } == 0).then_some(id) } -fn ancestors(object: u32) -> Vec { +fn bsd_name(object: u32) -> Option { + // audit-allow(I18N-MISSING): an IOKit registry property name. + string(property(object, "BSD Name").0).filter(|id| valid_id(id)) +} + +/// The APFS container scheme has one `IOMedia` parent per physical store. +fn apfs_backing_disk(scheme: u32) -> Option { + let mut iterator = 0; + // SAFETY: scheme is live, the plane is static, and iterator is an out-pointer. + if unsafe { IORegistryEntryGetParentIterator(scheme, c"IOService".as_ptr(), &raw mut iterator) } + != 0 + { + return None; + } + let iterator = Object(iterator); + let mut backing = None; + for _ in 0..128 { + // SAFETY: iterator owns a live parent iterator. + let parent = unsafe { IOIteratorNext(iterator.0) }; + if parent == 0 { + return backing.map(Into::into); + } + let parent = Object(parent); + let path = format!("/dev/{}", bsd_name(parent.0)?); + let disk = format!("/dev/{}", whole_disk(&path)?); + if backing.as_ref().is_some_and(|other| other != &disk) { + return None; + } + backing = Some(disk); + } + None +} + +enum Backing { + Ordinary, + Apfs(Option), +} + +fn ancestors(object: u32, inspect_backing: bool) -> (Vec, Backing) { let mut ids = Vec::new(); let mut current = object; let mut owned = None; + let mut backing = Backing::Ordinary; for _ in 0..128 { let mut parent = 0; // SAFETY: current is a live entry, the plane name is a static C string, parent is an out-pointer. @@ -200,6 +245,12 @@ fn ancestors(object: u32) -> Vec { break; } let next = Object(parent); + if inspect_backing && matches!(backing, Backing::Ordinary) + // SAFETY: parent is live and the class name is static. + && unsafe { IOObjectConformsTo(parent, c"AppleAPFSContainerScheme".as_ptr()) } != 0 + { + backing = Backing::Apfs(apfs_backing_disk(parent)); + } if let Some(id) = registry_id(parent) { ids.push(id); } @@ -207,10 +258,14 @@ fn ancestors(object: u32) -> Vec { owned = Some(next); } drop(owned); - ids + (ids, backing) } pub fn discover() -> Result, String> { + discover_with_topology(false) +} + +fn discover_with_topology(inspect_backing: bool) -> Result, String> { // Own the mount snapshot; getmntinfo's process-global buffer is unsafe // to retain while other desktop libraries may query mounts concurrently. let mut capacity = 64usize; @@ -285,8 +340,7 @@ pub fn discover() -> Result, String> { break; } let entry = Object(entry); - // audit-allow(I18N-MISSING): an IOKit registry property name. - let Some(id) = string(property(entry.0, "BSD Name").0).filter(|id| valid_id(id)) else { + let Some(id) = bsd_name(entry.0) else { continue; }; let Some(size) = number(property(entry.0, "Size").0).filter(|n| *n > 0) else { @@ -339,7 +393,16 @@ pub fn discover() -> Result, String> { mount = string(value.0); } let in_use = mount.is_some() || boolean(property(entry.0, "Open").0); - topology.push((registry_id(entry.0), ancestors(entry.0))); + let (ancestors, backing) = ancestors(entry.0, inspect_backing); + topology.push((registry_id(entry.0), ancestors)); + let physical_whole = whole && matches!(backing, Backing::Ordinary); + let parent = match backing { + Backing::Apfs(physical) => physical, + Backing::Ordinary if inspect_backing && !whole => { + whole_disk(&path).map(|id| format!("/dev/{id}").into()) + } + Backing::Ordinary => None, + }; // The volume macOS runs from; read before `mount` moves into the location. let system = mount.as_deref() == Some("/"); rows.push(Drive { @@ -347,7 +410,12 @@ pub fn discover() -> Result, String> { name, name_is_message: false, size, - kind: if whole { "Entire drive" } else { "Volume" }.into(), + kind: if physical_whole { + "Entire drive" + } else { + "Volume" + } + .into(), location: if locked { "Locked: unlock in Disk Utility first".into() } else if let Some(point) = mount { @@ -366,7 +434,7 @@ pub fn discover() -> Result, String> { .unwrap_or(1), phone: false, unlocked: false, - parent: None, + parent, system, }); } @@ -433,17 +501,7 @@ pub fn destination(source: &std::path::Path, folder: &std::path::Path) -> Destin } pub(crate) fn inventory(_: bool) -> Result, String> { - let mut rows = discover()?; - for row in &mut rows { - if row.kind == "Volume" { - row.parent = row - .path - .to_str() - .and_then(whole_disk) - .map(|id| format!("/dev/{id}").into()); - } - } - Ok(rows) + discover_with_topology(true) } // Prefixes of the IOKit C interfaces in IOCFPlugIn.h and NVMeSMARTLibExternal.h. diff --git a/src/main.rs b/src/main.rs index d1de8d7..09db506 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1740,6 +1740,7 @@ fn show_sectors(state: &mut Reclaim, ui: &AppWindow, action: SectorAction) { let reader = report.reader(); let size = report.size; let current = state.viewer.image.clone(); + let previous_offset = matches!(action, SectorAction::Next).then_some(state.viewer.offset); ui.set_sector_error("".into()); ui.set_sector_loading(true); ui.set_check_running(true); @@ -1756,7 +1757,7 @@ fn show_sectors(state: &mut Reclaim, ui: &AppWindow, action: SectorAction) { | SectorAction::Previous | SectorAction::Next => current, }; - sector_view::read(reader, size, offset, image) + sector_view::read(reader, size, offset, image, previous_offset) }); sender.send(CheckResult::Sector(result)).ok(); }); diff --git a/src/partition.rs b/src/partition.rs index a5bcf10..4aee8e6 100644 --- a/src/partition.rs +++ b/src/partition.rs @@ -10,6 +10,8 @@ pub struct Partition { pub kind: String, /// Absolute byte offset of the entry that describes this partition. pub entry_offset: u64, + /// Whether the complete LBA range is ordered and inside the usable area. + pub within_usable_bounds: bool, } #[derive(Debug, Default)] @@ -38,19 +40,17 @@ pub fn filesystem( data.get_mut(..len) .ok_or_else(|| invalid("invalid probe length"))?, )?; + let data = data.get(..len).unwrap_or_default(); Ok(match () { () if data.starts_with(b"LUKS\xba\xbe") => "LUKS", () if data.get(3..11) == Some(b"-FVE-FS-") => "BitLocker", () if data.get(3..11) == Some(b"NTFS ") => "NTFS", () if data.get(3..11) == Some(b"EXFAT ") => "exFAT", - () if data.get(82..90) == Some(b"FAT32 ") => "FAT32", - () if data.get(54..62) == Some(b"FAT16 ") => "FAT16", - () if data.get(54..62) == Some(b"FAT12 ") => "FAT12", - () if u16_le(&data, 1080) == 0xef53 => "ext2/3/4", + () if u16_le(data, 1080) == 0xef53 => "ext2/3/4", () if matches!(data.get(1024..1026), Some(b"H+" | b"HX")) => "HFS+", () if data.get(32..36) == Some(b"NXSB") => "APFS", () if data.starts_with(b"XFSB") => "XFS", - () => "Unrecognized", + () => crate::allocation::fat_signature(data, size).unwrap_or("Unrecognized"), }) } @@ -154,6 +154,7 @@ fn gpt( first: u64_le(e, 32), last: u64_le(e, 40), kind, + within_usable_bounds: false, } }) .collect(); @@ -187,25 +188,42 @@ pub fn inspect( return Err(invalid("unknown logical sector size")); } let slots = mbr.get(446..510).unwrap_or_default(); - let protective = slots + let protective: Vec<_> = slots .as_chunks::<16>() .0 .iter() - .any(|e| e.get(4).copied().unwrap_or(0) == 0xee); + .enumerate() + .filter(|(_, entry)| entry.get(4) == Some(&0xee)) + .collect(); + let widths = [sector, 4096]; + let widths = if known_sector.is_some() { + widths.get(..1).unwrap_or_default() + } else { + &widths + }; + let mut copies = None; + let mut detected_signature = false; let mut magic = [0; 8]; - let mut is_gpt = protective; - for width in [sector, 4096] { - if known_sector.is_some() && width != sector { + for &width in widths { + let blocks = size / width as u64; + if blocks < 3 { continue; } - let blocks = size / width as u64; - if blocks >= 3 - && [1, blocks - 1].iter().any(|n| { - read_at(input, n * width as u64, &mut magic).is_ok() && &magic == b"EFI PART" - }) - { + let has_signature = [1, blocks - 1] + .iter() + .any(|n| read_at(input, n * width as u64, &mut magic).is_ok() && &magic == b"EFI PART"); + if !has_signature && protective.is_empty() { + continue; + } + let primary = gpt(input, width, blocks, false); + let backup = gpt(input, width, blocks, true); + let valid = primary.is_ok() || backup.is_ok(); + if valid || copies.is_none() || (has_signature && !detected_signature) { + copies = Some((width, primary, backup)); + detected_signature = has_signature; + } + if valid { sector = width; - is_gpt = true; break; } } @@ -215,18 +233,27 @@ pub fn inspect( ..Layout::default() }; let mut bounds = (1, blocks.saturating_sub(1)); - if is_gpt && blocks >= 3 { - if !protective || u16_le(&mbr, 510) != 0xaa55 { + if let Some((width, primary, backup)) = copies { + let blocks = size / width as u64; + if protective.is_empty() || u16_le(&mbr, 510) != 0xaa55 { report.notes.push((0, "Missing protective MBR".into())); } - let primary = gpt(input, sector, blocks, false); - let backup = gpt(input, sector, blocks, true); + for (slot, entry) in protective { + if u32_le(entry, 8) != 1 + || u64::from(u32_le(entry, 12)) != (blocks - 1).min(u64::from(u32::MAX)) + { + report.notes.push(( + 446 + slot as u64 * 16, + "Invalid protective MBR range".into(), + )); + } + } for (at, name, copy) in [ (1, "Primary GPT", &primary), (blocks - 1, "Backup GPT", &backup), ] { report.notes.push(( - at * sector as u64, + at * width as u64, match copy { Ok(_) => format!( "{} · {}", @@ -280,6 +307,7 @@ pub fn inspect( first, last: first + u64::from(length) - 1, kind, + within_usable_bounds: false, }); } } else { @@ -291,9 +319,11 @@ pub fn inspect( } report.partitions.sort_by_key(|p| p.first); let mut previous_end = None; - for p in &report.partitions { + for p in &mut report.partitions { let usable = bounds.0..=bounds.1; - if p.first > p.last || !usable.contains(&p.first) || !usable.contains(&p.last) { + p.within_usable_bounds = + p.first <= p.last && usable.contains(&p.first) && usable.contains(&p.last); + if !p.within_usable_bounds { report.notes.push(( p.entry_offset, format!("Entry {} exceeds usable bounds or is reversed", p.slot), @@ -318,6 +348,8 @@ mod tests { fn fixture(sector: usize) -> Vec { let mut disk = vec![0; 128 * sector]; disk[450] = 0xee; + disk[454..458].copy_from_slice(&1u32.to_le_bytes()); + disk[458..462].copy_from_slice(&127u32.to_le_bytes()); disk[510..512].copy_from_slice(&[0x55, 0xaa]); let mut entry = [0u8; 128]; entry[0] = 1; @@ -360,6 +392,13 @@ mod tests { assert_eq!(good.partitions[0].last, 60); assert!(good.notes.iter().all(|(_, s)| s.contains("verified"))); disk[sector] = 0; + if sector == 4096 { + disk[512..520].copy_from_slice(b"EFI PART"); + let size = disk.len() as u64; + let native = inspect(&mut Cursor::new(&disk), size, Some(512)).unwrap(); + assert_eq!(native.sector, 512); + assert_eq!(native.partitions, Vec::new()); + } let backup = layout(disk); assert_eq!(backup.sector, sector as u64); assert_eq!(backup.partitions[0].first, good.partitions[0].first); @@ -373,6 +412,61 @@ mod tests { ); } } + #[test] + fn damaged_protective_mbr_and_outside_entry_keep_the_gpt_findings() { + let mut disk = fixture(512); + disk[454..462].fill(0); + let table = &mut disk[1024..1152]; + table[32..40].copy_from_slice(&2u64.to_le_bytes()); + let table_crc = crc32fast::hash(table); + let header = &mut disk[512..604]; + header[88..92].copy_from_slice(&table_crc.to_le_bytes()); + header[16..20].fill(0); + let header_crc = crc32fast::hash(header); + header[16..20].copy_from_slice(&header_crc.to_le_bytes()); + + let result = layout(disk); + let entry = &result.partitions[0]; + assert!(!entry.within_usable_bounds); + assert_eq!(entry.entry_offset, 1024); + assert!( + result + .notes + .contains(&(446, "Invalid protective MBR range".into())) + ); + assert!( + result + .notes + .iter() + .any(|(at, note)| *at == 1024 && note.contains("bounds")) + ); + } + + #[test] + fn fat_variant_comes_from_valid_boot_geometry() { + let mut boot = [0; 2048]; + boot[..3].copy_from_slice(&[0xeb, 0x3c, 0x90]); + boot[11..13].copy_from_slice(&512u16.to_le_bytes()); + boot[13] = 1; + boot[14] = 1; + boot[16] = 2; + boot[17..19].copy_from_slice(&512u16.to_le_bytes()); + boot[19..21].copy_from_slice(&8192u16.to_le_bytes()); + boot[21] = 0xf8; + boot[22..24].copy_from_slice(&32u16.to_le_bytes()); + boot[54..62].copy_from_slice(b"FAT12 "); + boot[510..512].copy_from_slice(b"\x55\xaa"); + assert_eq!( + filesystem(&mut Cursor::new(boot), 0, 8192 * 512).unwrap(), + "FAT16" + ); + boot[13] = 3; + assert_eq!( + filesystem(&mut Cursor::new(boot), 0, 8192 * 512).unwrap(), + "Unrecognized" + ); + } + #[test] fn checksum_damage_and_valid_but_conflicting_copies_are_distinct() { let mut disk = fixture(512); diff --git a/src/sector_view.rs b/src/sector_view.rs index 6fbd7d3..1ecfd9f 100644 --- a/src/sector_view.rs +++ b/src/sector_view.rs @@ -14,7 +14,6 @@ pub const WINDOW: u64 = 512; pub struct Image { pub path: PathBuf, file: File, - size: u64, } impl Image { pub fn open(path: PathBuf) -> io::Result> { @@ -31,11 +30,7 @@ impl Image { if !meta.is_file() { return Err(io::Error::other(i18n::t("Choose a raw disk image"))); } - Ok(Arc::new(Self { - path, - file, - size: meta.len(), - })) + Ok(Arc::new(Self { path, file })) } } @@ -153,19 +148,38 @@ fn dump(offset: u64, source: &[u8], comparison: Option<&[u8]>) -> String { pub fn read( mut reader: impl Read + Seek, size: u64, - offset: u64, + mut offset: u64, image: Option>, + previous_offset: Option, ) -> io::Result { - let end = size.max(image.as_ref().map_or(0, |i| i.size)); + let comparison = image.as_ref().map(|i| &i.file); + let before = comparison.map(File::metadata).transpose()?; + let comparison_size = before.as_ref().map_or(0, std::fs::Metadata::len); + let end = size.max(comparison_size); + if offset >= end + && end > 0 + && let Some(previous) = previous_offset + { + offset = previous.min(end - 1); + } if offset >= end { return Err(io::Error::other(i18n::t( "Address outside the image or drive.", ))); } let left = read_at(&mut reader, offset, size)?; - let right = image - .as_ref() - .map(|i| read_at(&mut i.file.try_clone()?, offset, i.size)) + let right = comparison + .zip(before) + .map(|(mut file, before)| { + let bytes = read_at(&mut file, offset, comparison_size); + let after = file.metadata()?; + if after.len() != comparison_size || after.modified().ok() != before.modified().ok() { + return Err(io::Error::other(i18n::t( + "The comparison image changed. Select Compare image to reload it.", + ))); + } + bytes + }) .transpose()?; let last = offset + end.saturating_sub(offset).min(WINDOW) - 1; Ok(Page { @@ -190,22 +204,39 @@ mod tests { } } + #[test] + fn next_refreshes_the_page_if_the_comparison_was_truncated() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("second.img"); + let file = File::create(&path).unwrap(); + file.set_len(1024).unwrap(); + let image = Image::open(path).unwrap(); + let source = [0; 512]; + let page = read(Cursor::new(source), 512, 0, Some(Arc::clone(&image)), None).unwrap(); + assert!(page.more); + file.set_len(128).unwrap(); + let page = read(Cursor::new(source), 512, 512, Some(image), Some(0)).unwrap(); + assert_eq!(page.viewer.offset, 0); + assert!(!page.more); + assert!(page.dump.contains("--")); + } + #[test] fn comparison_covers_both_files_and_marks_only_different_bytes() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("second.img"); std::fs::write(&path, b"axcd!").unwrap(); let image = Image::open(path).unwrap(); - let page = read(Cursor::new(b"abcd"), 4, 0, Some(Arc::clone(&image))).unwrap(); + let page = read(Cursor::new(b"abcd"), 4, 0, Some(Arc::clone(&image)), None).unwrap(); let mut lines = page.dump.lines(); let row = lines.next().unwrap(); let markers = lines.next().unwrap(); assert!(row.contains("61 62 63 64 --") && row.contains("61 78 63 64 21")); assert_eq!(markers.find("^^"), row.find("78")); assert_eq!(markers.rfind("^^"), row.find("21")); - let tail = read(Cursor::new(b"abcd"), 4, 4, Some(image)).unwrap(); + let tail = read(Cursor::new(b"abcd"), 4, 4, Some(image), None).unwrap(); assert_eq!(tail.last, 4); assert!(!tail.more); - assert!(read(Cursor::new(b"abcd"), 4, 4, None).is_err()); + assert!(read(Cursor::new(b"abcd"), 4, 4, None, None).is_err()); } }