driver-updater

Windows app that checks Windows Update and hardware vendors for newer drivers and silently installs the driver.
git clone https://dittus.dev/git/driver-updater.git
Log | Files | Refs | README | Download

VendorPackage.cs (4144B)


      1 using System.IO;
      2 using System.Net.Http;
      3 
      4 namespace DriverUpdater;
      5 
      6 // A vendor's driver package. It's downloaded, signature checked, and unpacked the first time a row
      7 // needs it. Every row that installs from it then shares the unpacked folder.
      8 sealed class VendorPackage(Uri url, Uri? referrer, string signer, string folder, Func<string, string, Task> unpack)
      9 {
     10     Task<string>? unpacked;
     11 
     12     // Packages normally unpack to the temp folder and get deleted after the install. AMD's chipset
     13     // package is kept, because each scan reads its INFs to compare versions.
     14     public bool KeepAfterInstall { get; init; }
     15 
     16     public static string TempFolderFor(Uri url) =>
     17         Path.Combine(Path.GetTempPath(), "DriverUpdater", Path.GetFileNameWithoutExtension(url.LocalPath));
     18 
     19     // Returns the unpacked folder. Rows that share the package wait on the same download.
     20     public async Task<string> UnpackAsync(Action<string> status)
     21     {
     22         unpacked ??= DownloadAndUnpackAsync(status);
     23         try
     24         {
     25             return await unpacked;
     26         }
     27         catch
     28         {
     29             unpacked = null;
     30             throw;
     31         }
     32     }
     33 
     34     public void Delete()
     35     {
     36         unpacked = null;
     37         if (Directory.Exists(folder))
     38             Directory.Delete(folder, recursive: true);
     39     }
     40 
     41     async Task<string> DownloadAndUnpackAsync(Action<string> status)
     42     {
     43         // A finished unpack gets moved into place last, so an existing folder is a complete one.
     44         if (Directory.Exists(folder))
     45             return folder;
     46 
     47         string parent = Path.GetDirectoryName(folder)!;
     48         Directory.CreateDirectory(parent);
     49         string download = Path.Combine(parent, Path.GetFileName(url.LocalPath));
     50         string partial = folder + ".partial";
     51         try
     52         {
     53             await DownloadAsync(download, status);
     54 
     55             status("Checking signature");
     56             if (!await Task.Run(() => Authenticode.IsSignedBy(download, signer)))
     57                 throw new InvalidOperationException($"The download isn't signed by {signer}, so it was deleted");
     58 
     59             status("Unpacking");
     60             if (Directory.Exists(partial))
     61                 Directory.Delete(partial, recursive: true);
     62             await unpack(download, partial);
     63             Directory.Move(partial, folder);
     64             return folder;
     65         }
     66         finally
     67         {
     68             File.Delete(download);
     69             if (Directory.Exists(partial))
     70                 Directory.Delete(partial, recursive: true);
     71         }
     72     }
     73 
     74     // Big downloads sometimes drop partway. Try three times before giving up.
     75     async Task DownloadAsync(string path, Action<string> status)
     76     {
     77         for (int attempt = 1; ; attempt++)
     78         {
     79             try
     80             {
     81                 await DownloadOnceAsync(path, status);
     82                 return;
     83             }
     84             catch (Exception ex) when (attempt < 3 && ex is HttpRequestException or IOException or TaskCanceledException)
     85             {
     86                 status($"Download failed, retrying: {ex.Message}");
     87                 await Task.Delay(TimeSpan.FromSeconds(5 * attempt));
     88             }
     89         }
     90     }
     91 
     92     async Task DownloadOnceAsync(string path, Action<string> status)
     93     {
     94         using var request = new HttpRequestMessage(HttpMethod.Get, url) { Headers = { Referrer = referrer } };
     95         using var response = await Web.Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
     96         response.EnsureSuccessStatusCode();
     97         long? totalBytes = response.Content.Headers.ContentLength;
     98 
     99         await using var source = await response.Content.ReadAsStreamAsync();
    100         await using var target = File.Create(path);
    101         var buffer = new byte[1 << 20];
    102         long receivedBytes = 0;
    103         int read;
    104         while ((read = await source.ReadAsync(buffer)) > 0)
    105         {
    106             await target.WriteAsync(buffer.AsMemory(0, read));
    107             receivedBytes += read;
    108             status(totalBytes > 0
    109                 ? $"Downloading {receivedBytes * 100 / totalBytes.Value}%"
    110                 : $"Downloading {receivedBytes / 1_048_576} MB");
    111         }
    112     }
    113 }