Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions src/DeskBox/Services/AppUpdateService.ForkDownload.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using System.Security.Cryptography;
using DeskBox.Models;

namespace DeskBox.Services;

public sealed partial class AppUpdateService
{
/// <summary>No bytes for this long fails the source (it used to sit at 0 B forever).</summary>
internal static TimeSpan ForkDownloadStallTimeout { get; set; } = TimeSpan.FromSeconds(30);

private async Task<(long BytesReceived, long? TotalBytes, string Sha256)> ForkDownloadToFileAsync(
Uri source,
string tempPath,
long manifestSize,
IProgress<AppUpdateDownloadProgress>? progress,
CancellationToken cancellationToken)
{
using var stallCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
stallCts.CancelAfter(ForkDownloadStallTimeout);
try
{
using var response = await _httpClient.GetAsync(
source,
HttpCompletionOption.ResponseHeadersRead,
stallCts.Token);
response.EnsureSuccessStatusCode();

long? totalBytes = response.Content.Headers.ContentLength;
if (totalBytes is null && manifestSize > 0)
{
totalBytes = manifestSize;
}

progress?.Report(new AppUpdateDownloadProgress(0, totalBytes));
long bytesReceived = 0;
await using var remoteStream = await response.Content.ReadAsStreamAsync(stallCts.Token);
await using var fileStream = new FileStream(
tempPath,
FileMode.Create,
FileAccess.Write,
FileShare.None,
bufferSize: 1024 * 128,
useAsync: true);
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
byte[] buffer = new byte[1024 * 128];
while (true)
{
stallCts.CancelAfter(ForkDownloadStallTimeout);
int bytesRead = await remoteStream.ReadAsync(buffer.AsMemory(0, buffer.Length), stallCts.Token);
if (bytesRead <= 0)
{
break;
}

await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken);
hash.AppendData(buffer, 0, bytesRead);
bytesReceived += bytesRead;
progress?.Report(new AppUpdateDownloadProgress(bytesReceived, totalBytes));
}

await fileStream.FlushAsync(cancellationToken);
return (bytesReceived, totalBytes, Convert.ToHexString(hash.GetHashAndReset()));
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
throw new TimeoutException(
$"No data from {source.Host} for {ForkDownloadStallTimeout.TotalSeconds:0} seconds.");
}
}
}
66 changes: 33 additions & 33 deletions src/DeskBox/Services/AppUpdateService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -375,48 +375,48 @@ private async Task<AppUpdateDownloadResult> DownloadUpdateCoreAsync(
File.Delete(tempPath);
}

using var response = await _httpClient.GetAsync(
// GOXF fork: try the user's download proxy first (if set), then
// github.com directly; a stalled or failed source moves on to the
// next. The SHA-256 below still comes from the GitHub API.
IReadOnlyList<Uri> candidates = ForkDownloadProxySettings.GetDownloadCandidates(
downloadUri,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken);
response.EnsureSuccessStatusCode();

long? totalBytes = response.Content.Headers.ContentLength;
if (totalBytes is null && manifest.Size > 0)
{
totalBytes = manifest.Size;
}

ForkDownloadProxySettings.Load());
long bytesReceived = 0;
string actualSha256;
await using (var remoteStream = await response.Content.ReadAsStreamAsync(cancellationToken))
await using (var fileStream = new FileStream(
tempPath,
FileMode.Create,
FileAccess.Write,
FileShare.None,
bufferSize: 1024 * 128,
useAsync: true))
using (var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256))
long? totalBytes = null;
Exception? lastError = null;
bool hashMatched = false;
foreach (Uri candidate in candidates)
{
byte[] buffer = new byte[1024 * 128];
int bytesRead;
while ((bytesRead = await remoteStream.ReadAsync(buffer.AsMemory(0, buffer.Length), cancellationToken)) > 0)
try
{
await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken);
hash.AppendData(buffer, 0, bytesRead);
bytesReceived += bytesRead;
progress?.Report(new AppUpdateDownloadProgress(bytesReceived, totalBytes));
(bytesReceived, totalBytes, string actualSha256) = await ForkDownloadToFileAsync(
candidate, tempPath, manifest.Size, progress, cancellationToken);
if (string.Equals(actualSha256, NormalizeSha256(manifest.Sha256), StringComparison.OrdinalIgnoreCase))
{
hashMatched = true;
break;
}

App.Log($"[Update] Hash mismatch from {candidate.Host}; trying next source.");
lastError = null;
}
catch (Exception ex) when (
!cancellationToken.IsCancellationRequested &&
ex is HttpRequestException or TaskCanceledException or TimeoutException)
{
App.Log($"[Update] Download from {candidate.Host} failed: {ex.GetType().Name}: {ex.Message}");
lastError = ex;
}

await fileStream.FlushAsync(cancellationToken);
actualSha256 = Convert.ToHexString(hash.GetHashAndReset());
TryDelete(tempPath);
}

if (!string.Equals(actualSha256, NormalizeSha256(manifest.Sha256), StringComparison.OrdinalIgnoreCase))
if (!hashMatched)
{
TryDelete(tempPath);
return AppUpdateDownloadResult.Failed(AppUpdateDownloadFailureKind.HashMismatch);
return lastError is null
? AppUpdateDownloadResult.Failed(AppUpdateDownloadFailureKind.HashMismatch)
: AppUpdateDownloadResult.Failed(AppUpdateDownloadFailureKind.Network, lastError.Message);
}

File.Move(tempPath, targetPath, overwrite: true);
Expand All @@ -428,7 +428,7 @@ private async Task<AppUpdateDownloadResult> DownloadUpdateCoreAsync(
TryDelete(tempPath);
return AppUpdateDownloadResult.Failed(AppUpdateDownloadFailureKind.Cancelled);
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or TimeoutException)
{
TryDelete(tempPath);
return AppUpdateDownloadResult.Failed(AppUpdateDownloadFailureKind.Network, ex.Message);
Expand Down
117 changes: 117 additions & 0 deletions src/DeskBox/Services/ForkDownloadProxySettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
using System.Text.Json;

namespace DeskBox.Services;

/// <summary>
/// GOXF/DeskBox fork: optional download proxy for update installers, for
/// networks where github.com release downloads stall. Stored in its own small
/// file (not the upstream settings model) so the settings process writes it
/// and the main process reads it at download time without any IPC, and
/// upstream settings changes never conflict with it.
///
/// The proxy only carries bytes. The installer's SHA-256 still comes from the
/// GitHub API (asset digest / .sha256), and the original URL must still pass
/// <see cref="ForkUpdateConfig.IsTrustedInstallerDownloadUri"/>, so a bad or
/// hostile proxy can at worst fail the download, never install other bytes.
///
/// Formats: a prefix such as "https://gh-proxy.com/" (original URL appended)
/// or a template containing "{url}" (replaced with the original URL).
/// </summary>
public static class ForkDownloadProxySettings
{
private const string FileName = "fork-update.json";
private const string UrlPlaceholder = "{url}";

private static string FilePath => Path.Combine(DeskBoxDataPathService.Current.RootPath, FileName);

public static string Load()
{
try
{
if (!File.Exists(FilePath))
{
return string.Empty;
}

using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(FilePath));
return doc.RootElement.TryGetProperty("downloadProxy", out JsonElement value) &&
value.ValueKind == JsonValueKind.String
? value.GetString()?.Trim() ?? string.Empty
: string.Empty;
}
catch (Exception)
{
// Missing data root (tests), unreadable or malformed file: no proxy.
return string.Empty;
}
}

/// <summary>Saves a normalized value; returns false when it is not a usable http(s) proxy.</summary>
public static bool TrySave(string? proxy)
{
string value = (proxy ?? string.Empty).Trim();
if (value.Length > 0 && !IsValidProxy(value))
{
return false;
}

try
{
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
File.WriteAllText(FilePath, "{\"downloadProxy\":" + JsonEncode(value) + "}");
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return false;
}
}

public static bool IsValidProxy(string proxy)
{
string probe = proxy.Trim().Replace(UrlPlaceholder, "x", StringComparison.OrdinalIgnoreCase);
return Uri.TryCreate(probe, UriKind.Absolute, out Uri? uri) &&
(uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp) &&
!string.IsNullOrEmpty(uri.Host);
}

public static Uri? BuildProxiedUri(string? proxy, Uri original)
{
if (string.IsNullOrWhiteSpace(proxy) || !IsValidProxy(proxy))
{
return null;
}

string value = proxy.Trim();
string url = value.Contains(UrlPlaceholder, StringComparison.OrdinalIgnoreCase)
? value.Replace(UrlPlaceholder, original.AbsoluteUri, StringComparison.OrdinalIgnoreCase)
: value.TrimEnd('/') + "/" + original.AbsoluteUri;
return Uri.TryCreate(url, UriKind.Absolute, out Uri? result) ? result : null;
}

/// <summary>Proxy first (when set), then the original GitHub URL as fallback.</summary>
public static IReadOnlyList<Uri> GetDownloadCandidates(Uri original, string? proxy)
{
Uri? proxied = BuildProxiedUri(proxy, original);
return proxied is null || proxied == original ? [original] : [proxied, original];
}

private static string JsonEncode(string value)
{
var sb = new System.Text.StringBuilder("\"");
foreach (char c in value)
{
switch (c)
{
case '"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
default:
if (c < 0x20) { sb.Append("\\u").Append(((int)c).ToString("x4")); }
else { sb.Append(c); }
break;
}
}

return sb.Append('"').ToString();
}
}
72 changes: 72 additions & 0 deletions src/DeskBox/ViewModels/SettingsViewModel.ForkDownloadProxy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using DeskBox.Services;
using Microsoft.UI.Xaml;

namespace DeskBox.ViewModels;

/// <summary>
/// GOXF/DeskBox fork: "update download proxy" field under the update details.
/// Text lives here (not Strings/*.json) for the same merge-conflict reason as
/// SettingsViewModel.ForkUpstream.cs. Saved to its own file on edit; the main
/// process reads it on the next download.
/// </summary>
public partial class SettingsViewModel
{
private string? _updateDownloadProxy;
private string _updateDownloadProxyStatus = string.Empty;

public Visibility UpdateDownloadProxyVisibility =>
IsDirectInstallerUpdateDelivery ? Visibility.Visible : Visibility.Collapsed;

public string UpdateDownloadProxy
{
get => _updateDownloadProxy ??= ForkDownloadProxySettings.Load();
set
{
string normalized = (value ?? string.Empty).Trim();
if (string.Equals(normalized, UpdateDownloadProxy, StringComparison.Ordinal))
{
return;
}

bool saved = ForkDownloadProxySettings.TrySave(normalized);
if (saved)
{
_updateDownloadProxy = normalized;
}

_updateDownloadProxyStatus = ForkProxyText(saved
? (normalized.Length == 0 ? ProxyText.Cleared : ProxyText.Saved)
: ProxyText.Invalid);
OnPropertyChanged(nameof(UpdateDownloadProxy));
OnPropertyChanged(nameof(UpdateDownloadProxyStatus));
}
}

public string UpdateDownloadProxyLabel => ForkProxyText(ProxyText.Label);

public string UpdateDownloadProxyStatus =>
_updateDownloadProxyStatus.Length > 0 ? _updateDownloadProxyStatus : ForkProxyText(ProxyText.Hint);

internal enum ProxyText { Label, Hint, Saved, Cleared, Invalid }

internal string ForkProxyText(ProxyText key) =>
FormatForkProxyText(_localizationService.CurrentCultureName, key);

internal static string FormatForkProxyText(string? cultureName, ProxyText key)
{
bool zhHans = cultureName == LocalizationService.LanguageChinese;
bool zhHant = cultureName == LocalizationService.LanguageChineseTraditional;
return key switch
{
ProxyText.Label => zhHans ? "更新下载代理(可选)" : zhHant ? "更新下載代理(可選)" : "Update download proxy (optional)",
ProxyText.Hint => zhHans
? "GitHub 下载慢时填写,如 https://gh-proxy.com/ 或含 {url} 的模板;先走代理,30 秒无数据自动改用 GitHub 直连。安装包仍按 GitHub 公布的 SHA-256 校验。"
: zhHant
? "GitHub 下載慢時填寫,如 https://gh-proxy.com/ 或含 {url} 的範本;先走代理,30 秒無資料自動改用 GitHub 直連。安裝包仍按 GitHub 公布的 SHA-256 校驗。"
: "For slow GitHub downloads, e.g. https://gh-proxy.com/ or a template containing {url}. The proxy is tried first; after 30 s without data DeskBox falls back to GitHub. Installers are still verified against GitHub's SHA-256.",
ProxyText.Saved => zhHans ? "已保存,下次下载更新时生效。" : zhHant ? "已儲存,下次下載更新時生效。" : "Saved. Used for the next update download.",
ProxyText.Cleared => zhHans ? "已清除,将直连 GitHub 下载。" : zhHant ? "已清除,將直連 GitHub 下載。" : "Cleared. Updates download directly from GitHub.",
_ => zhHans ? "地址无效,需以 http:// 或 https:// 开头。" : zhHant ? "位址無效,需以 http:// 或 https:// 開頭。" : "Invalid address: it must start with http:// or https://.",
};
}
}
10 changes: 10 additions & 0 deletions src/DeskBox/Views/SettingsWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -3409,6 +3409,16 @@ Text="DeskBox" />
Text="{x:Bind UpstreamReleaseNoticeText, Mode=OneWay}"
Visibility="{x:Bind UpstreamReleaseNoticeVisibility, Mode=OneWay}"
TextWrapping="Wrap" />
<StackPanel Spacing="4" Visibility="{x:Bind UpdateDownloadProxyVisibility, Mode=OneWay}">
<TextBlock Text="{x:Bind UpdateDownloadProxyLabel, Mode=OneWay}" />
<TextBox
PlaceholderText="https://gh-proxy.com/"
Text="{x:Bind UpdateDownloadProxy, Mode=TwoWay}" />
<TextBlock
Style="{StaticResource SettingDescriptionTextStyle}"
Text="{x:Bind UpdateDownloadProxyStatus, Mode=OneWay}"
TextWrapping="Wrap" />
</StackPanel>

<StackPanel Spacing="6" Visibility="{Binding UpdateProgressVisibility}">
<ProgressBar
Expand Down
Loading
Loading