Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Setup: say an unfinished download is incomplete instead of uninstalling
KnifeLemon6d4892d21c27
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 90e50d27..b3951e3d 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -436,7 +436,9 @@ have no semibold) instead of the app's embedded Noto fonts.counts as installed when `uninstall.exe` (or 1.x's `unins000.exe`) is next to it (`UpdateService.IsInstalled`).- **Uninstall**: `uninstall.exe` is Setup without its payload. Run from the install folder it copies itself to`%TEMP%` and waits for the copy, which removes what `uninstall.json` lists (other files in the folder stay), the- shortcuts, the PATH entry and the key. Files in use are moved out and deleted at the next restart.+ shortcuts, the PATH entry and the key. Files in use are moved out and deleted at the next restart. A program without+ a payload is the uninstaller only as `uninstall.exe`, as `Filee.Setup.exe` (a development build) or with `/UNINSTALL`+ (`SetupStart`); any other name is a Setup.exe whose download didn't finish, and it says so instead (exit code 1).- **Command line**: Inno Setup's switches (`SetupOptions`, documented at the top of the file), because Filee 1.xupdates itself with `/SILENT /NORESTART` and winget passes `/VERYSILENT /SUPPRESSMSGBOXES /NORESTART`. Exit codes asInno Setup's: 0 done, 1 could not start, 2 cancelled before installing (also a declined UAC prompt), 4 failed.diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.jsonindex 2381df77..4cd506df 100644--- a/src/Filee.App/Assets/i18n/ar.json+++ b/src/Filee.App/Assets/i18n/ar.json@@ -984,6 +984,7 @@"installer.error.uninstall_title": "لم تكتمل إزالة Filee","installer.error.space": "لا توجد مساحة كافية على {0}: يحتاج Filee إلى {1}، لكن المتاح {2} فقط.","installer.error.damaged": "ملف الإعداد هذا تالف. نزّله مجددًا من filee.sh.",+ "installer.error.incomplete": "ملف الإعداد هذا غير مكتمل، على الأرجح لأن التنزيل لم ينتهِ. نزّله مجددًا من filee.sh.","installer.error.files": "تعذّر على الإعداد كتابة ملفات Filee: {0}","installer.error.unexpected": "حدث خطأ: {0}","installer.error.windows": "يحتاج Filee إلى Windows 10 بإصدار 64 بت، الإصدار 1809 أو أحدث.",diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.jsonindex 6e770d91..3f60678b 100644--- a/src/Filee.App/Assets/i18n/de.json+++ b/src/Filee.App/Assets/i18n/de.json@@ -984,6 +984,7 @@"installer.error.uninstall_title": "Filee wurde nicht vollständig entfernt","installer.error.space": "Auf {0} ist nicht genug Speicherplatz frei: Filee benötigt {1}, verfügbar sind nur {2}.","installer.error.damaged": "Diese Installationsdatei ist beschädigt. Lade sie erneut von filee.sh herunter.",+ "installer.error.incomplete": "Diese Installationsdatei ist unvollständig, wahrscheinlich wurde der Download nicht abgeschlossen. Lade sie erneut von filee.sh herunter.","installer.error.files": "Die Filee-Dateien konnten nicht geschrieben werden: {0}","installer.error.unexpected": "Ein Fehler ist aufgetreten: {0}","installer.error.windows": "Filee benötigt Windows 10, Version 1809 oder neuer (64 Bit).",diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex 4e2adbbf..427a8e2b 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -1004,6 +1004,7 @@"installer.error.uninstall_title": "Filee was not removed completely","installer.error.space": "There isn't enough free space on {0}: Filee needs {1}, but only {2} is free.","installer.error.damaged": "This setup file is damaged. Download it again from filee.sh.",+ "installer.error.incomplete": "This setup file is incomplete, probably because the download didn't finish. Download it again from filee.sh.","installer.error.files": "Setup couldn't write Filee's files: {0}","installer.error.unexpected": "Something went wrong: {0}","installer.error.windows": "Filee needs 64-bit Windows 10 version 1809 or later.",diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.jsonindex 3ca5f061..c5596a21 100644--- a/src/Filee.App/Assets/i18n/es.json+++ b/src/Filee.App/Assets/i18n/es.json@@ -984,6 +984,7 @@"installer.error.uninstall_title": "Filee no se quitó por completo","installer.error.space": "No hay suficiente espacio libre en {0}: Filee necesita {1}, pero solo quedan {2}.","installer.error.damaged": "Este archivo de instalación está dañado. Descárgalo de nuevo desde filee.sh.",+ "installer.error.incomplete": "Este archivo de instalación está incompleto, probablemente porque la descarga no terminó. Descárgalo de nuevo desde filee.sh.","installer.error.files": "El instalador no pudo escribir los archivos de Filee: {0}","installer.error.unexpected": "Algo salió mal: {0}","installer.error.windows": "Filee necesita Windows 10 de 64 bits, versión 1809 o posterior.",diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.jsonindex a4add3cb..5719fa92 100644--- a/src/Filee.App/Assets/i18n/fr.json+++ b/src/Filee.App/Assets/i18n/fr.json@@ -1004,6 +1004,7 @@"installer.error.uninstall_title": "Filee n'a pas été entièrement supprimé","installer.error.space": "Espace libre insuffisant sur {0} : Filee nécessite {1}, mais seulement {2} sont disponibles.","installer.error.damaged": "Ce fichier d'installation est endommagé. Téléchargez-le de nouveau sur filee.sh.",+ "installer.error.incomplete": "Ce fichier d'installation est incomplet, sans doute parce que le téléchargement ne s'est pas terminé. Téléchargez-le de nouveau sur filee.sh.","installer.error.files": "Le programme d'installation n'a pas pu écrire les fichiers de Filee : {0}","installer.error.unexpected": "Une erreur s'est produite : {0}","installer.error.windows": "Filee nécessite Windows 10 64 bits version 1809 ou ultérieure.",diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.jsonindex 41ac49b1..19bd341f 100644--- a/src/Filee.App/Assets/i18n/hi.json+++ b/src/Filee.App/Assets/i18n/hi.json@@ -984,6 +984,7 @@"installer.error.uninstall_title": "Filee पूरी तरह नहीं हटा","installer.error.space": "{0} पर पर्याप्त खाली जगह नहीं है: Filee को {1} चाहिए, लेकिन सिर्फ़ {2} खाली है।","installer.error.damaged": "यह सेटअप फ़ाइल खराब है। इसे filee.sh से फिर डाउनलोड करें।",+ "installer.error.incomplete": "यह सेटअप फ़ाइल अधूरी है, शायद डाउनलोड पूरा नहीं हुआ। इसे filee.sh से फिर डाउनलोड करें।","installer.error.files": "सेटअप Filee की फ़ाइलें नहीं लिख सका: {0}","installer.error.unexpected": "कुछ गड़बड़ हो गई: {0}","installer.error.windows": "Filee को 64-बिट Windows 10 संस्करण 1809 या नया चाहिए।",diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.jsonindex fdac2598..f1b478a3 100644--- a/src/Filee.App/Assets/i18n/ja.json+++ b/src/Filee.App/Assets/i18n/ja.json@@ -984,6 +984,7 @@"installer.error.uninstall_title": "Fileeを完全には削除できませんでした","installer.error.space": "{0}の空き容量が足りません。Fileeには{1}が必要ですが、空きは{2}だけです。","installer.error.damaged": "このセットアップファイルは破損しています。filee.shからもう一度ダウンロードしてください。",+ "installer.error.incomplete": "このセットアップファイルは不完全です。ダウンロードが最後まで終わっていない可能性があります。filee.shからもう一度ダウンロードしてください。","installer.error.files": "Fileeのファイルを書き込めませんでした:{0}","installer.error.unexpected": "問題が発生しました:{0}","installer.error.windows": "Fileeには64ビット版のWindows 10 バージョン1809以降が必要です。",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex 8e89ad9b..796b7cac 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -1004,6 +1004,7 @@"installer.error.uninstall_title": "Filee를 모두 제거하지 못했어요","installer.error.space": "{0}에 빈 공간이 부족해요. Filee에 {1}이(가) 필요한데 {2}만 남아 있어요.","installer.error.damaged": "설치 파일이 손상됐어요. filee.sh에서 다시 내려받아 주세요.",+ "installer.error.incomplete": "설치 파일이 완전하지 않아요. 내려받기가 끝나지 않았을 수 있어요. filee.sh에서 다시 내려받아 주세요.","installer.error.files": "Filee 파일을 쓰지 못했어요: {0}","installer.error.unexpected": "문제가 생겼어요: {0}","installer.error.windows": "Filee는 64비트 Windows 10 버전 1809 이상이 필요해요.",diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.jsonindex 73395a70..15b653ed 100644--- a/src/Filee.App/Assets/i18n/ne.json+++ b/src/Filee.App/Assets/i18n/ne.json@@ -984,6 +984,7 @@"installer.error.uninstall_title": "Filee पूर्ण रूपमा हटाइएन","installer.error.space": "{0} मा पर्याप्त खाली ठाउँ छैन: Filee लाई {1} चाहिन्छ, तर {2} मात्र खाली छ।","installer.error.damaged": "यो सेटअप फाइल बिग्रिएको छ। यसलाई filee.sh बाट पुन: डाउनलोड गर्नुहोस्।",+ "installer.error.incomplete": "यो सेटअप फाइल अपूर्ण छ, सायद डाउनलोड पूरा भएन। यसलाई filee.sh बाट पुन: डाउनलोड गर्नुहोस्।","installer.error.files": "सेटअपले Filee का फाइलहरू लेख्न सकेन: {0}","installer.error.unexpected": "केही गलत भयो: {0}","installer.error.windows": "Filee लाई ६४-बिट Windows 10 संस्करण १८०९ वा नयाँ चाहिन्छ।",diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.jsonindex 4eb84c4d..05f48a49 100644--- a/src/Filee.App/Assets/i18n/pl.json+++ b/src/Filee.App/Assets/i18n/pl.json@@ -1004,6 +1004,7 @@"installer.error.uninstall_title": "Nie usunięto Filee całkowicie","installer.error.space": "Za mało miejsca na {0}: Filee potrzebuje {1}, a wolne jest tylko {2}.","installer.error.damaged": "Plik instalacyjny jest uszkodzony. Pobierz go ponownie z filee.sh.",+ "installer.error.incomplete": "Plik instalacyjny jest niekompletny, prawdopodobnie pobieranie się nie zakończyło. Pobierz go ponownie z filee.sh.","installer.error.files": "Instalator nie mógł zapisać plików Filee: {0}","installer.error.unexpected": "Coś poszło nie tak: {0}","installer.error.windows": "Filee wymaga 64-bitowego systemu Windows 10 w wersji 1809 lub nowszej.",diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.jsonindex 8e99ed33..9ebbc306 100644--- a/src/Filee.App/Assets/i18n/pt-BR.json+++ b/src/Filee.App/Assets/i18n/pt-BR.json@@ -1004,6 +1004,7 @@"installer.error.uninstall_title": "O Filee não foi removido por completo","installer.error.space": "Não há espaço livre suficiente em {0}: o Filee precisa de {1}, mas só {2} estão livres.","installer.error.damaged": "Este arquivo de instalação está danificado. Baixe de novo em filee.sh.",+ "installer.error.incomplete": "Este arquivo de instalação está incompleto, provavelmente porque o download não terminou. Baixe de novo em filee.sh.","installer.error.files": "A instalação não conseguiu gravar os arquivos do Filee: {0}","installer.error.unexpected": "Algo deu errado: {0}","installer.error.windows": "O Filee precisa do Windows 10 de 64 bits, versão 1809 ou posterior.",diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.jsonindex 9cc6e393..78023ab8 100644--- a/src/Filee.App/Assets/i18n/pt-PT.json+++ b/src/Filee.App/Assets/i18n/pt-PT.json@@ -1004,6 +1004,7 @@"installer.error.uninstall_title": "O Filee não foi totalmente removido","installer.error.space": "Não há espaço livre suficiente em {0}: o Filee precisa de {1}, mas só há {2} disponíveis.","installer.error.damaged": "Este instalador está danificado. Volta a descarregá-lo em filee.sh.",+ "installer.error.incomplete": "Este instalador está incompleto, provavelmente porque a transferência não terminou. Volta a descarregá-lo em filee.sh.","installer.error.files": "O instalador não conseguiu escrever os ficheiros do Filee: {0}","installer.error.unexpected": "Ocorreu um problema: {0}","installer.error.windows": "O Filee requer o Windows 10 de 64 bits, versão 1809 ou posterior.",diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.jsonindex c0b3a2fc..6c8dff5f 100644--- a/src/Filee.App/Assets/i18n/ru.json+++ b/src/Filee.App/Assets/i18n/ru.json@@ -1004,6 +1004,7 @@"installer.error.uninstall_title": "Filee удалён не полностью","installer.error.space": "На {0} недостаточно места: Filee нужно {1}, а свободно только {2}.","installer.error.damaged": "Файл установки повреждён. Скачайте его заново с filee.sh.",+ "installer.error.incomplete": "Файл установки неполный — вероятно, загрузка не завершилась. Скачайте его заново с filee.sh.","installer.error.files": "Не удалось записать файлы Filee: {0}","installer.error.unexpected": "Что-то пошло не так: {0}","installer.error.windows": "Для Filee нужна 64-разрядная Windows 10 версии 1809 или новее.",diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.jsonindex 83b3c7a5..1496fa93 100644--- a/src/Filee.App/Assets/i18n/th.json+++ b/src/Filee.App/Assets/i18n/th.json@@ -984,6 +984,7 @@"installer.error.uninstall_title": "ไม่สามารถลบ Filee ออกได้ทั้งหมด","installer.error.space": "พื้นที่ว่างบน {0} ไม่เพียงพอ: Filee ต้องการ {1} แต่มีพื้นที่ว่างเหลือเพียง {2}","installer.error.damaged": "ไฟล์ติดตั้งนี้เสียหาย โปรดดาวน์โหลดใหม่อีกครั้งจาก filee.sh",+ "installer.error.incomplete": "ไฟล์ติดตั้งนี้ไม่สมบูรณ์ อาจเป็นเพราะดาวน์โหลดไม่เสร็จ โปรดดาวน์โหลดใหม่อีกครั้งจาก filee.sh","installer.error.files": "ตัวติดตั้งไม่สามารถเขียนไฟล์ของ Filee ได้: {0}","installer.error.unexpected": "เกิดข้อผิดพลาด: {0}","installer.error.windows": "Filee ต้องการ Windows 10 64 บิต เวอร์ชัน 1809 ขึ้นไป",diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.jsonindex 09c66d35..d7a30638 100644--- a/src/Filee.App/Assets/i18n/tr.json+++ b/src/Filee.App/Assets/i18n/tr.json@@ -984,6 +984,7 @@"installer.error.uninstall_title": "Filee tamamen kaldırılamadı","installer.error.space": "{0} üzerinde yeterli boş alan yok: Filee için {1} gerekli, ancak yalnızca {2} boş.","installer.error.damaged": "Bu kurulum dosyası bozuk. filee.sh adresinden yeniden indirin.",+ "installer.error.incomplete": "Bu kurulum dosyası eksik, büyük olasılıkla indirme tamamlanmadı. filee.sh adresinden yeniden indirin.","installer.error.files": "Kurulum Filee dosyalarını yazamadı: {0}","installer.error.unexpected": "Bir sorun oluştu: {0}","installer.error.windows": "Filee için 64 bit Windows 10 sürüm 1809 veya üstü gereklidir.",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex fa125720..6e65159b 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -1004,6 +1004,7 @@"installer.error.uninstall_title": "Filee 未能完全移除","installer.error.space": "{0} 上的可用空间不足。Filee 需要 {1},但只剩 {2}。","installer.error.damaged": "安装文件已损坏。请从 filee.sh 重新下载。",+ "installer.error.incomplete": "安装文件不完整,可能是下载没有完成。请从 filee.sh 重新下载。","installer.error.files": "安装程序无法写入 Filee 的文件。{0}","installer.error.unexpected": "出现了问题。{0}","installer.error.windows": "Filee 需要 64 位 Windows 10 1809 或更高版本。",diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.jsonindex 03c538be..56a8acbc 100644--- a/src/Filee.App/Assets/i18n/zh-TW.json+++ b/src/Filee.App/Assets/i18n/zh-TW.json@@ -1004,6 +1004,7 @@"installer.error.uninstall_title": "Filee 未能完全移除","installer.error.space": "{0} 上的可用空間不足。Filee 需要 {1},但只剩 {2}。","installer.error.damaged": "安裝檔案已損壞。請從 filee.sh 重新下載。",+ "installer.error.incomplete": "安裝檔案不完整,可能是下載沒有完成。請從 filee.sh 重新下載。","installer.error.files": "安裝程式無法寫入 Filee 的檔案。{0}","installer.error.unexpected": "出現了問題。{0}","installer.error.windows": "Filee 需要 64 位 Windows 10 1809 或更高版本。",diff --git a/src/Filee.Setup/Payload/SetupPayload.cs b/src/Filee.Setup/Payload/SetupPayload.csindex 17298372..e5ac1d04 100644--- a/src/Filee.Setup/Payload/SetupPayload.cs+++ b/src/Filee.Setup/Payload/SetupPayload.cs@@ -117,6 +117,23 @@ public sealed class SetupPayload : IDisposablereturn certificates > 0 && size > 0 && certificates + (long)size == file.Length ? new ProgramSignature(certificates, (int)size) : null;}+ /// <summary>+ /// True when the PE header names a certificate table that runs past the end of the file: a signed program that was+ /// cut off (a download that didn't finish), the payload's trailer in front of the signature gone with it.+ /// </summary>+ internal static bool SignatureCutOff(Stream file)+ {+ var entry = SecurityDirectory(file);+ if (entry < 0)+ return false;+ Span<byte> buffer = stackalloc byte[8];+ file.Position = entry;+ file.ReadExactly(buffer);+ var certificates = BinaryPrimitives.ReadUInt32LittleEndian(buffer);+ var size = BinaryPrimitives.ReadUInt32LittleEndian(buffer[4..]);+ return certificates > 0 && size > 0 && certificates + (long)size > file.Length;+ }+/// <summary>File position of the PE header's security directory entry (IMAGE_DIRECTORY_ENTRY_SECURITY), or -1.</summary>private static long SecurityDirectory(Stream file){diff --git a/src/Filee.Setup/Program.cs b/src/Filee.Setup/Program.csindex c40be5a5..8f7a5da0 100644--- a/src/Filee.Setup/Program.cs+++ b/src/Filee.Setup/Program.cs@@ -1,5 +1,5 @@// Entry point of Setup (Filee-<version>-win-Setup.exe, which carries a payload) and of the uninstaller (uninstall.exe,-// the same program without one).+// the same program without one). SetupStart tells them apart, and from a Setup.exe whose download didn't finish.//// Rights: the program starts without administrator rights (asInvoker). An install for all users starts itself again// with them (one UAC prompt) and waits; the elevated copy writes what to start at the end into a file, and this@@ -43,17 +43,9 @@ internal static class Programvar paths = sandbox is null ? SetupPaths.Real() : SetupPaths.Sandbox(sandbox);Directory.CreateDirectory(paths.Temp);- SetupPayload? payload = null;- Exception? damaged = null;- try- {- payload = SetupPayload.Open(exe);- }- catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException)- {- damaged = ex;- }- var uninstall = options.Uninstall || (payload is null && damaged is null);+ var start = SetupStart.Of(exe, options.Uninstall);+ var payload = start.Payload;+ var uninstall = start.Mode == StartMode.Uninstall;var log = new SetupLog(options.LogFile ?? SetupLog.DefaultFile(paths.Temp, uninstall ? "Filee-Uninstall" : "Filee-Setup"));log.Info($"{(uninstall ? "Uninstaller" : "Setup")} {SetupInfo.Version}{(payload is null ? "" : $" with Filee {payload.Manifest.Version}")}: " +$"{exe} {SetupOptions.Join(args)}; administrator: {NativeMethods.IsElevated()}; Windows {Environment.OSVersion.Version} " +@@ -74,12 +66,18 @@ internal static class ProgramTell(options, texts["installer.error.windows"], NativeMethods.MB_ICONERROR);return ExitInitFailed;}- if (damaged is not null)+ if (start.Mode == StartMode.Damaged){- log.Error($"Damaged payload: {damaged.Message}");+ log.Error($"Damaged payload: {start.Problem}");Tell(options, texts["installer.error.damaged"], NativeMethods.MB_ICONERROR);return ExitInitFailed;}+ if (start.Mode == StartMode.Incomplete)+ {+ log.Error($"Incomplete download: {start.Problem}");+ Tell(options, texts["installer.error.incomplete"], NativeMethods.MB_ICONERROR);+ return ExitInitFailed;+ }return uninstall? Uninstall(args, options, exe, paths, sandbox, log, texts): Install(args, options, exe, payload!, paths, sandbox, log, texts);diff --git a/src/Filee.Setup/SetupStart.cs b/src/Filee.Setup/SetupStart.csnew file mode 100644index 00000000..df409a4e--- /dev/null+++ b/src/Filee.Setup/SetupStart.cs@@ -0,0 +1,69 @@+// What this program is when it starts. With a payload it is Setup. Without one it is the uninstaller only under the+// uninstaller's name (uninstall.exe: what Setup writes next to Filee.exe, and the copy it runs from %TEMP%), under the+// build output's name (Filee.Setup.exe, a development build) or with /UNINSTALL. Any other program without a payload is+// a Setup.exe whose download didn't finish: the payload's trailer is the last part of the file (only the signature+// comes after it), so a cut file has none. Run as the uninstaller, it said Filee isn't installed in the Downloads+// folder (#599).++using Filee.Setup.Installation;+using Filee.Setup.Payload;++namespace Filee.Setup;++internal enum StartMode+{+ Install,+ Uninstall,++ /// <summary>The payload is there but damaged.</summary>+ Damaged,++ /// <summary>No payload and not the uninstaller: a Setup.exe cut off by a download that didn't finish.</summary>+ Incomplete,+}++/// <param name="Problem">What is wrong, for the log (<see cref="StartMode.Damaged"/>, <see cref="StartMode.Incomplete"/>).</param>+internal sealed record SetupStart(StartMode Mode, SetupPayload? Payload = null, string? Problem = null)+{+ /// <summary>The build output's name. Releases rename it (Filee-<version>-win-Setup.exe, uninstall.exe).</summary>+ public const string DevelopmentExe = "Filee.Setup.exe";++ /// <param name="uninstall">/UNINSTALL: uninstall whatever the program carries.</param>+ public static SetupStart Of(string exe, bool uninstall)+ {+ SetupPayload? payload;+ try+ {+ payload = SetupPayload.Open(exe);+ }+ catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException)+ {+ return new SetupStart(StartMode.Damaged, Problem: ex.Message);+ }+ if (uninstall)+ {+ payload?.Dispose();+ return new SetupStart(StartMode.Uninstall);+ }+ if (payload is not null)+ return new SetupStart(StartMode.Install, payload);+ var name = Path.GetFileName(exe);+ if (name.Equals(SetupNames.UninstallerExe, StringComparison.OrdinalIgnoreCase) || name.Equals(DevelopmentExe, StringComparison.OrdinalIgnoreCase))+ return new SetupStart(StartMode.Uninstall);+ return new SetupStart(StartMode.Incomplete, Problem: Describe(exe));+ }++ private static string Describe(string exe)+ {+ try+ {+ using var file = new FileStream(exe, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);+ return $"{Path.GetFileName(exe)} ({file.Length} bytes) has no payload" ++ (SetupPayload.SignatureCutOff(file) ? " and its signature is cut off" : "") + "; the download didn't finish";+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ return $"{Path.GetFileName(exe)} has no payload ({ex.Message})";+ }+ }+}diff --git a/tests/Filee.Setup.Tests/SetupStartTests.cs b/tests/Filee.Setup.Tests/SetupStartTests.csnew file mode 100644index 00000000..2f6c2c79--- /dev/null+++ b/tests/Filee.Setup.Tests/SetupStartTests.cs@@ -0,0 +1,147 @@+// What the program is when it starts: Setup, the uninstaller, or a Setup.exe whose download didn't finish (#599).++using System.Buffers.Binary;+using Filee.Setup.Payload;++namespace Filee.Setup.Tests;++public class SetupStartTests+{+ [Fact]+ public void A_complete_setup_installs()+ {+ using var bench = new SetupBench();+ var start = SetupStart.Of(bench.SetupExe, uninstall: false);+ using var payload = start.Payload;+ Assert.Equal(StartMode.Install, start.Mode);+ Assert.Equal("2.0.0", payload!.Manifest.Version);+ }++ [Theory]+ [InlineData("Filee-2.0.0-win-Setup.exe")]+ [InlineData("Filee-2.0.0-win-Setup (1).exe")]+ [InlineData("setup.exe")]+ public void A_setup_cut_off_in_its_payload_is_incomplete_not_the_uninstaller(string name)+ {+ using var bench = new SetupBench(app: (temp, _) => temp.Write(@"app\data\big.bin", new string('z', 200_000)));+ var bytes = File.ReadAllBytes(bench.SetupExe);+ var cut = bench.Temp.Sub("Downloads", name);+ Directory.CreateDirectory(Path.GetDirectoryName(cut)!);+ File.WriteAllBytes(cut, bytes[..(bytes.Length / 2)]);++ var start = SetupStart.Of(cut, uninstall: false);+ Assert.Equal(StartMode.Incomplete, start.Mode);+ Assert.Null(start.Payload);+ Assert.Contains("no payload", start.Problem);+ }++ [Theory]+ [InlineData(1)]+ [InlineData(100)]+ [InlineData(511)]+ [InlineData(512 + 10)] // into the trailer in front of it+ public void A_signed_setup_cut_off_in_its_signature_is_incomplete(int missing)+ {+ using var temp = new TempFolder();+ var signed = SignedSetup(temp);+ var bytes = File.ReadAllBytes(signed);+ var cut = temp.Sub("Filee-2.0.0-win-Setup.exe");+ File.WriteAllBytes(cut, bytes[..^missing]);++ var start = SetupStart.Of(cut, uninstall: false);+ Assert.Equal(StartMode.Incomplete, start.Mode);+ Assert.Contains("signature is cut off", start.Problem);+ }++ [Fact]+ public void A_signed_setup_without_only_its_signature_still_installs()+ {+ // Cut exactly where the signature starts: the payload is whole, its checksum says so when installing.+ using var temp = new TempFolder();+ var bytes = File.ReadAllBytes(SignedSetup(temp));+ var cut = temp.Sub("Filee-2.0.0-win-Setup.exe");+ File.WriteAllBytes(cut, bytes[..^512]);+ var start = SetupStart.Of(cut, uninstall: false);+ using var payload = start.Payload;+ Assert.Equal(StartMode.Install, start.Mode);+ payload!.Verify(cancellation: TestContext.Current.CancellationToken);+ }++ [Theory]+ [InlineData("uninstall.exe")]+ [InlineData("Uninstall.EXE")]+ public void Uninstall_exe_without_payload_uninstalls(string name)+ {+ using var bench = new SetupBench();+ using (var payload = SetupPayload.Open(bench.SetupExe)!)+ payload.CopyProgramTo(bench.Temp.Sub(name));+ var start = SetupStart.Of(bench.Temp.Sub(name), uninstall: false);+ Assert.Equal(StartMode.Uninstall, start.Mode);+ Assert.Null(start.Payload);+ }++ [Fact]+ public void A_development_build_without_payload_still_runs_as_the_uninstaller()+ {+ using var temp = new TempFolder();+ var exe = temp.Write(SetupStart.DevelopmentExe, "MZ development build");+ Assert.Equal(StartMode.Uninstall, SetupStart.Of(exe, uninstall: false).Mode);+ }++ [Fact]+ public void The_uninstall_switch_uninstalls_under_any_name()+ {+ using var bench = new SetupBench();+ var plain = bench.Temp.Write("anything.exe", "MZ no payload");+ Assert.Equal(StartMode.Uninstall, SetupStart.Of(plain, uninstall: true).Mode);+ var start = SetupStart.Of(bench.SetupExe, uninstall: true);+ Assert.Equal(StartMode.Uninstall, start.Mode);+ Assert.Null(start.Payload);+ }++ [Fact]+ public void A_damaged_trailer_is_damaged()+ {+ using var bench = new SetupBench();+ var bytes = File.ReadAllBytes(bench.SetupExe);+ BinaryPrimitives.WriteInt64LittleEndian(bytes.AsSpan(bytes.Length - SetupPayload.TrailerLength + 16), 7);+ File.WriteAllBytes(bench.SetupExe, bytes);+ var start = SetupStart.Of(bench.SetupExe, uninstall: false);+ Assert.Equal(StartMode.Damaged, start.Mode);+ Assert.NotNull(start.Problem);+ }++ [Fact]+ public void Every_language_says_the_download_is_incomplete()+ {+ var english = new SetupTexts("en")["installer.error.incomplete"];+ Assert.Contains("filee.sh", english);+ Assert.All(SetupTexts.Languages, l =>+ {+ Assert.True(SetupTexts.Load(l.Code).TryGetValue("installer.error.incomplete", out var text), l.Code);+ Assert.Contains("filee.sh", text);+ });+ }++ /// <summary>A Setup.exe whose header points at a 512-byte certificate table at its end, as signtool leaves it.</summary>+ private static string SignedSetup(TempFolder temp)+ {+ temp.Write(@"app\Filee.exe", "Filee");+ var program = temp.Sub("program.exe");+ File.WriteAllBytes(program, PayloadTests.MinimalPe(0, 0));+ var unsigned = temp.Sub("unsigned.exe");+ SetupPayload.Write(program, temp.Sub("app"), unsigned, "2.0.0", [], "", fast: true);+ var body = File.ReadAllBytes(unsigned);+ var signed = new byte[body.Length + 512];+ body.CopyTo(signed, 0);+ var pe = BinaryPrimitives.ReadInt32LittleEndian(signed.AsSpan(0x3C));+ var security = pe + 4 + 20 + 112 + 4 * 8;+ BinaryPrimitives.WriteUInt32LittleEndian(signed.AsSpan(security), (uint)body.Length);+ BinaryPrimitives.WriteUInt32LittleEndian(signed.AsSpan(security + 4), 512);+ var path = temp.Sub("signed.exe");+ File.WriteAllBytes(path, signed);+ using (var payload = SetupPayload.Open(path))+ Assert.NotNull(payload);+ return path;+ }+}