From e9643c5995808123e9bfc63c9419fa2e9e275464 Mon Sep 17 00:00:00 2001 From: Alexandros Patsouros Date: Fri, 25 Sep 2026 09:38:40 +0300 Subject: [PATCH] Fix review findings: reliable failed-report retries, Windows 11, signing (2.1.0) Failed reports - Save exception text with control characters exactly (XML character references), keep \r\n, replace lone surrogates; write atomically (temp file + rename). - Queue per application (%TEMP%\CrashReporterNET\) with unique timestamp+GUID file names. - Persist the full snapshot (title, versions, developer/user message, screenshot choice, crash time) and resend it unchanged on retry, without recapturing a screenshot; DrDump retries report the saved application title/version. - Add RetryFailedReportsAsync(CancellationToken): runs entirely on the thread pool; one retry per application at a time (exclusive queue lock, also across processes); DeliveryTimeout per report; cancellation interrupts SMTP delivery on .NET Framework (SendAsyncCancel). - Delete a delivered report before optionally opening the browser. Doctor Dump - Share HttpClient instances (per proxy; pooled connection lifetime on .NET 10). - Reject non-success HTTP statuses, report SOAP faults with their reason, reject missing/nil results. - Replace characters that are invalid in XML before sending. - Do not send an anonymous report from the dialog when AnalyzeWithDoctorDump is false. - Tolerate missing network when computing the anonymous machine ID and always restore the thread culture. Other - Show Windows 11 (build >= 22000 workstation) in local reports. - Embed the screenshot in reports saved from the dialog (#40). - Always strong-name sign with a committed key (sn.exe generated). - Add xUnit test project (net10.0-windows + net48) and run it in CI. Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/publish.yml | 9 + .gitignore | 2 + .../CrashReporter.NET.Tests.csproj | 32 ++ .../DrDumpSoapClientTests.cs | 181 ++++++ CrashReporter.NET.Tests/FailedReportTests.cs | 181 ++++++ CrashReporter.NET.Tests/ReportContentTests.cs | 151 +++++ CrashReporter.NET.Tests/RetryDeliveryTests.cs | 317 +++++++++++ .../RetryFailedReportsTests.cs | 249 +++++++++ CrashReporter.NET.Tests/TestInfrastructure.cs | 210 +++++++ CrashReporter.NET.sln | 44 +- CrashReporter.NET/CrashReport.cs | 26 +- CrashReporter.NET/CrashReporter.NET.csproj | 10 +- CrashReporter.NET/CrashReporter.NET.snk | Bin 0 -> 596 bytes CrashReporter.NET/DrDump/AnonymousData.cs | 16 + CrashReporter.NET/DrDump/DrDumpService.cs | 49 +- CrashReporter.NET/DrDump/DrDumpSoapClient.cs | 183 ++++-- CrashReporter.NET/DrDump/SendRequestState.cs | 99 ++-- CrashReporter.NET/FailedReport.cs | 223 +++++++- CrashReporter.NET/HelperMethods.cs | 43 +- CrashReporter.NET/ReportCrash.cs | 523 ++++++++++++++---- CrashReporter.NET/XmlText.cs | 73 +++ CrashReporterWPFTest/App.xaml.cs | 3 +- README.md | 17 +- 23 files changed, 2411 insertions(+), 230 deletions(-) create mode 100644 CrashReporter.NET.Tests/CrashReporter.NET.Tests.csproj create mode 100644 CrashReporter.NET.Tests/DrDumpSoapClientTests.cs create mode 100644 CrashReporter.NET.Tests/FailedReportTests.cs create mode 100644 CrashReporter.NET.Tests/ReportContentTests.cs create mode 100644 CrashReporter.NET.Tests/RetryDeliveryTests.cs create mode 100644 CrashReporter.NET.Tests/RetryFailedReportsTests.cs create mode 100644 CrashReporter.NET.Tests/TestInfrastructure.cs create mode 100644 CrashReporter.NET/CrashReporter.NET.snk create mode 100644 CrashReporter.NET/XmlText.cs diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index ead9ef5..9b8fdc8 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -46,6 +46,15 @@ jobs: - name: Build run: dotnet build CrashReporter.NET.sln -c Release --no-restore -p:Version=${{ steps.version.outputs.version }} -p:ContinuousIntegrationBuild=true + - name: Test + run: dotnet test CrashReporter.NET.sln -c Release --no-build --logger "trx" --results-directory TestResults + + - uses: actions/upload-artifact@v7 + if: failure() + with: + name: test-results + path: TestResults + - name: Pack run: dotnet pack CrashReporter.NET/CrashReporter.NET.csproj -c Release --no-build -p:Version=${{ steps.version.outputs.version }} -o artifacts diff --git a/.gitignore b/.gitignore index e29414f..7dc3b86 100644 --- a/.gitignore +++ b/.gitignore @@ -251,4 +251,6 @@ paket-files/ .idea/ *.sln.iml *.snk +# Public strong-name key of this library (intentionally committed, see README). +!CrashReporter.NET/CrashReporter.NET.snk /CrashReporter.NET/build/lib/net20 diff --git a/CrashReporter.NET.Tests/CrashReporter.NET.Tests.csproj b/CrashReporter.NET.Tests/CrashReporter.NET.Tests.csproj new file mode 100644 index 0000000..416a0e0 --- /dev/null +++ b/CrashReporter.NET.Tests/CrashReporter.NET.Tests.csproj @@ -0,0 +1,32 @@ + + + + net10.0-windows;net48 + true + latest + false + true + CrashReporterDotNET.Tests + + true + ..\CrashReporter.NET\CrashReporter.NET.snk + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + diff --git a/CrashReporter.NET.Tests/DrDumpSoapClientTests.cs b/CrashReporter.NET.Tests/DrDumpSoapClientTests.cs new file mode 100644 index 0000000..fbb1e66 --- /dev/null +++ b/CrashReporter.NET.Tests/DrDumpSoapClientTests.cs @@ -0,0 +1,181 @@ +using System; +using System.Net; +using System.Net.Http; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using CrashReporterDotNET.com.drdump; +using CrashReporterDotNET.DrDump; +using Xunit; + +namespace CrashReporterDotNET.Tests +{ + public sealed class DrDumpSoapClientTests + { + private const string Namespace = "https://www.drdump.com/services"; + + private static string Envelope(string body) => + "" + body + ""; + + private static string AnonymousResult(string type, string extra = "") => Envelope( + $"" + + $"cidAQIDBA==https://drdump.com/p/1{extra}"); + + private static readonly string Fault = Envelope( + "s:ReceiverServer is sad"); + + private static DrDumpSoapClient CreateClient(FakeHttpHandler handler) => + new DrDumpSoapClient(new HttpClient(handler)) { Url = "https://drdump.test/Service/CrashReporterReportUploader.svc" }; + + private static Task SendAnonymous(DrDumpSoapClient client, CancellationToken cancellationToken = default) => + client.SendAnonymousReportAsync(new ClientLib { V1 = 2, V2 = 1 }, + new Application { AppName = "App", MainModule = "App", Email = "a@b.c" }, + new ExceptionDescription { ClrVersion = "10.0", OS = "os", CrashDate = DateTime.UtcNow }, + cancellationToken); + + [Fact] + public async Task SuccessfulResponse_IsParsed() + { + var handler = new FakeHttpHandler(HttpStatusCode.OK, AnonymousResult("NeedReportResponse")); + + var response = await SendAnonymous(CreateClient(handler)); + + Assert.IsType(response); + Assert.Equal(new byte[] { 1, 2, 3, 4 }, response.Context); + Assert.Equal("https://drdump.com/p/1", response.UrlToProblem); + Assert.StartsWith("application/soap+xml", handler.LastRequestContentType); + Assert.Contains("SendAnonymousReport\"", handler.LastRequestContentType); + } + + [Fact] + public async Task ErrorResponse_IsReturnedAsTypedResult() + { + var handler = new FakeHttpHandler(HttpStatusCode.OK, AnonymousResult("ErrorResponse", "Valid e-mail is required")); + + var response = await SendAnonymous(CreateClient(handler)); + + Assert.Equal("Valid e-mail is required", Assert.IsType(response).Error); + } + + [Theory] + [InlineData(HttpStatusCode.InternalServerError)] + [InlineData(HttpStatusCode.OK)] + public async Task SoapFault_IsReportedWithItsReason(HttpStatusCode statusCode) + { + var handler = new FakeHttpHandler(statusCode, Fault); + + var error = await Assert.ThrowsAsync(() => SendAnonymous(CreateClient(handler))); + + Assert.Equal("Server is sad", error.Message); + } + + [Fact] + public async Task UnsuccessfulStatus_WithValidEnvelope_IsRejected() + { + var handler = new FakeHttpHandler(HttpStatusCode.InternalServerError, AnonymousResult("StopResponse")); + + var error = await Assert.ThrowsAsync(() => SendAnonymous(CreateClient(handler))); + + Assert.Contains("HTTP 500", error.Message); + } + + [Fact] + public async Task UnsuccessfulStatus_WithNonSoapBody_IsRejected() + { + var handler = new FakeHttpHandler(HttpStatusCode.BadGateway, "Bad gateway", "text/html"); + + var error = await Assert.ThrowsAsync(() => SendAnonymous(CreateClient(handler))); + + Assert.Contains("HTTP 502", error.Message); + } + + [Fact] + public async Task NilResult_IsRejected() + { + var handler = new FakeHttpHandler(HttpStatusCode.OK, Envelope( + $"")); + + var error = await Assert.ThrowsAsync(() => SendAnonymous(CreateClient(handler))); + + Assert.Contains("no result", error.Message); + } + + [Fact] + public async Task MissingResult_IsRejected() + { + var handler = new FakeHttpHandler(HttpStatusCode.OK, Envelope($"")); + + await Assert.ThrowsAsync(() => SendAnonymous(CreateClient(handler))); + } + + [Fact] + public async Task MalformedSuccessfulResponse_IsRejected() + { + var handler = new FakeHttpHandler(HttpStatusCode.OK, "this is not xml"); + + var error = await Assert.ThrowsAsync(() => SendAnonymous(CreateClient(handler))); + + Assert.Contains("invalid response", error.Message); + } + + [Fact] + public async Task Cancellation_AbortsTheRequest() + { + var handler = new FakeHttpHandler(async (request, token) => + { + await Task.Delay(Timeout.Infinite, token).ConfigureAwait(false); + return new HttpResponseMessage(HttpStatusCode.OK); + }); + using (var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(100))) + { + await Assert.ThrowsAnyAsync(() => SendAnonymous(CreateClient(handler), cancellation.Token)); + } + } + + [Fact] + public async Task InvalidXmlCharactersInReport_AreReplacedBeforeSending() + { + Exception exception; + try + { + throw new InvalidOperationException("bad \u0001 char \uD800 and ￿"); + } + catch (Exception e) + { + exception = e; + } + + var state = new SendRequestState + { + AnonymousData = new AnonymousData { Exception = exception, ToEmail = "a@b.c" }, + PrivateData = new PrivateData { UserMessage = "user \u0002 message", DeveloperMessage = "dev", UserEmail = "u@x.y" } + }; + var handler = new FakeHttpHandler(HttpStatusCode.OK, Envelope( + $"u")); + + var response = await CreateClient(handler).SendAdditionalDataAsync(new byte[] { 1 }, state.GetDetailedExceptionDescription()); + + Assert.IsType(response); + Assert.Contains("bad � char � and �", handler.LastRequestBody); + Assert.Contains("user � message", handler.LastRequestBody); + } + + [Fact] + public void HttpClients_AreSharedPerProxy() + { + var field = typeof(DrDumpSoapClient).GetField("_httpClient", BindingFlags.Instance | BindingFlags.NonPublic); + var proxy = new WebProxy("http://proxy.test:8080"); + + var defaultA = field.GetValue(new DrDumpSoapClient()); + var defaultB = field.GetValue(new DrDumpSoapClient()); + var proxyA = field.GetValue(new DrDumpSoapClient(proxy)); + var proxyB = field.GetValue(new DrDumpSoapClient(proxy)); + var otherProxy = field.GetValue(new DrDumpSoapClient(new WebProxy("http://other.test:8080"))); + + Assert.Same(defaultA, defaultB); + Assert.Same(proxyA, proxyB); + Assert.NotSame(defaultA, proxyA); + Assert.NotSame(proxyA, otherProxy); + } + } +} diff --git a/CrashReporter.NET.Tests/FailedReportTests.cs b/CrashReporter.NET.Tests/FailedReportTests.cs new file mode 100644 index 0000000..fbc91ed --- /dev/null +++ b/CrashReporter.NET.Tests/FailedReportTests.cs @@ -0,0 +1,181 @@ +using System; +using System.IO; +using System.Linq; +using Xunit; + +namespace CrashReporterDotNET.Tests +{ + [Collection(QueueCollection.Name)] + public sealed class FailedReportTests : IDisposable + { + private readonly TemporaryDirectory _directory = new TemporaryDirectory(); + + public void Dispose() => _directory.Dispose(); + + private static Exception Throw(Func create) + { + try + { + throw create(); + } + catch (Exception e) + { + return e; + } + } + + [Fact] + public void RoundTrip_PreservesControlCharactersMarkupAndNestedExceptions() + { + const string hostile = "ctl\u0001\u001F nul\u0000 & ]]> ￾ end \U0001F600"; + var exception = Throw(() => new InvalidOperationException("outer " + hostile, + Throw(() => new FormatException("inner " + hostile, Throw(() => new ArgumentException("innermost")))))); + + var path = Path.Combine(_directory.Path, "report.xml"); + var original = new FailedReport + { + FormatVersion = FailedReport.CurrentFormatVersion, + Exception = ExceptionData.FromException(exception), + ScreenShot = new byte[] { 0, 1, 2, 255 }, + ApplicationTitle = "App " + hostile, + ApplicationVersion = "1.2.3.4", + DeveloperMessage = "dev " + hostile, + UserEmail = "user@example.com", + UserMessage = "user " + hostile, + IncludeScreenshot = true, + CrashDateUtc = new DateTime(2026, 9, 25, 1, 2, 3, DateTimeKind.Utc) + }; + + original.Save(path); + var loaded = FailedReport.Load(path); + + Assert.Equal(FailedReport.CurrentFormatVersion, loaded.FormatVersion); + Assert.Equal(original.ScreenShot, loaded.ScreenShot); + Assert.Equal(original.ApplicationTitle, loaded.ApplicationTitle); + Assert.Equal(original.ApplicationVersion, loaded.ApplicationVersion); + Assert.Equal(original.DeveloperMessage, loaded.DeveloperMessage); + Assert.Equal(original.UserEmail, loaded.UserEmail); + Assert.Equal(original.UserMessage, loaded.UserMessage); + Assert.True(loaded.IncludeScreenshot); + Assert.Equal(original.CrashDateUtc, loaded.CrashDateUtc); + + var replayed = loaded.Exception.ToException(); + Assert.Equal("System.InvalidOperationException", ReplayedException.GetTypeName(replayed)); + Assert.Equal(exception.Message, replayed.Message); + Assert.Equal(exception.StackTrace, replayed.StackTrace); + Assert.Equal(exception.ToString(), replayed.ToString()); + Assert.Equal(exception.HResult, replayed.HResult); + Assert.Equal("System.FormatException", ReplayedException.GetTypeName(replayed.InnerException)); + Assert.Equal(exception.InnerException.Message, replayed.InnerException.Message); + Assert.Equal("System.ArgumentException", ReplayedException.GetTypeName(replayed.InnerException.InnerException)); + } + + [Fact] + public void Save_ReplacesUnpairedSurrogatesInsteadOfFailing() + { + var path = Path.Combine(_directory.Path, "report.xml"); + var report = new FailedReport + { + Exception = ExceptionData.FromException(new Exception("broken \uD800 text \uDC00 end")), + UserMessage = "\uD83D" + }; + + report.Save(path); + var loaded = FailedReport.Load(path); + + Assert.Equal("broken � text � end", loaded.Exception.Message); + Assert.Equal("�", loaded.UserMessage); + // The report being saved is not modified. + Assert.Equal("\uD83D", report.UserMessage); + } + + [Fact] + public void Load_ReadsVersion1ReportsWrittenBy20() + { + // Format written by CrashReporter.NET 2.0.x. + var path = Path.Combine(_directory.Path, "failed-report-v1.xml"); + File.WriteAllText(path, + "" + + "" + + "System.InvalidOperationExceptionoldSrc" + + " at X.Y()-2146233079System.InvalidOperationException: old" + + "AQID"); + + var loaded = FailedReport.Load(path); + + Assert.Equal(0, loaded.FormatVersion); + Assert.Equal("old", loaded.Exception.Message); + Assert.Equal(new byte[] { 1, 2, 3 }, loaded.ScreenShot); + Assert.Null(loaded.ApplicationTitle); + Assert.Null(loaded.IncludeScreenshot); + } + + [Fact] + public void AtomicWrite_InterruptedWriteLeavesNoFile() + { + var path = Path.Combine(_directory.Path, "failed-report-x.xml"); + + Assert.Throws(() => AtomicFile.Write(path, stream => + { + stream.Write(new byte[1024], 0, 1024); + throw new IOException("disk full"); + })); + + Assert.False(File.Exists(path)); + Assert.Empty(Directory.GetFiles(_directory.Path)); + } + + [Fact] + public void AtomicWrite_NeverOverwritesAnExistingReport() + { + var path = Path.Combine(_directory.Path, "failed-report-x.xml"); + File.WriteAllText(path, "existing"); + + Assert.ThrowsAny(() => AtomicFile.Write(path, stream => stream.WriteByte(1))); + + Assert.Equal("existing", File.ReadAllText(path)); + Assert.Single(Directory.GetFiles(_directory.Path)); + } + + [Fact] + public void Queue_FileNamesAreUniqueEvenWithinTheSameMillisecond() + { + var now = new DateTime(2026, 9, 25, 10, 0, 0, DateTimeKind.Utc); + var names = Enumerable.Range(0, 1000).Select(_ => FailedReportQueue.CreateFileName(now)).ToList(); + + Assert.Equal(names.Count, names.Distinct().Count()); + Assert.All(names, name => Assert.StartsWith("failed-report-20260925T100000000-", name)); + } + + [Fact] + public void Queue_IsSeparatedPerApplication() + { + FailedReportQueue.RootDirectory = _directory.Path; + + var first = FailedReportQueue.GetDirectory("App One"); + var second = FailedReportQueue.GetDirectory("App:Two?"); + + Assert.NotEqual(first.FullName, second.FullName); + Assert.Equal(_directory.Path, first.Parent.FullName); + Assert.Equal("App_Two_", second.Name); + Assert.Equal("default", FailedReportQueue.GetSafeName(" ")); + } + + [Fact] + public void Queue_ListsOnlyCompletedReportsOldestFirst() + { + var queue = new DirectoryInfo(_directory.Path); + var older = FailedReportQueue.CreateFileName(new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc)); + var newer = FailedReportQueue.CreateFileName(new DateTime(2026, 2, 1, 0, 0, 0, DateTimeKind.Utc)); + File.WriteAllText(Path.Combine(queue.FullName, newer), ""); + File.WriteAllText(Path.Combine(queue.FullName, older), ""); + File.WriteAllText(Path.Combine(queue.FullName, newer + ".abc" + AtomicFile.TemporaryExtension), ""); + File.WriteAllText(Path.Combine(queue.FullName, "failed-report-legacy.bin"), ""); + File.WriteAllText(Path.Combine(queue.FullName, "unrelated.xml"), ""); + + var files = FailedReportQueue.GetFiles(queue).Select(f => f.Name).ToList(); + + Assert.Equal(new[] { older, newer }, files); + } + } +} diff --git a/CrashReporter.NET.Tests/ReportContentTests.cs b/CrashReporter.NET.Tests/ReportContentTests.cs new file mode 100644 index 0000000..92af1f9 --- /dev/null +++ b/CrashReporter.NET.Tests/ReportContentTests.cs @@ -0,0 +1,151 @@ +using System; +using Microsoft.Win32; +using Xunit; + +namespace CrashReporterDotNET.Tests +{ + public sealed class WindowsVersionTests + { + [Theory] + [InlineData("Windows 10 Pro", 22631, "Client", "Windows 11 Pro")] + [InlineData("Windows 10 Education", 22631, null, "Windows 11 Education")] + [InlineData("Windows 10 Enterprise", 22000, "Client", "Windows 11 Enterprise")] + [InlineData("Windows 10 Pro", 26100, "Client", "Windows 11 Pro")] + [InlineData("Windows 10 Pro", 19045, "Client", "Windows 10 Pro")] + [InlineData("Windows 10 Enterprise LTSC 2021", 19044, "Client", "Windows 10 Enterprise LTSC 2021")] + [InlineData("Windows 11 Pro", 26100, "Client", "Windows 11 Pro")] + [InlineData("Windows Server 2022 Datacenter", 20348, "Server", "Windows Server 2022 Datacenter")] + [InlineData("Windows Server 2025 Datacenter", 26100, "Server Core", "Windows Server 2025 Datacenter")] + [InlineData("Windows 10 Server Something", 26100, null, "Windows 10 Server Something")] + [InlineData("Windows 7 Professional", 7601, "Client", "Windows 7 Professional")] + public void ProductName_IsCorrectedOnlyForWindows11Workstations(string registryName, int build, string installationType, string expected) + { + Assert.Equal(expected, HelperMethods.GetWindowsProductName(registryName, build, installationType)); + } + + [Fact] + public void GetWindowsVersion_ReportsWindows11OnWindows11Workstations() + { + using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion")) + { + int.TryParse(key?.GetValue("CurrentBuildNumber") as string, out var build); + var installationType = key?.GetValue("InstallationType") as string; + var version = HelperMethods.GetWindowsVersion(); + + Assert.Contains($"(OS Build {build}", version); + if (build >= HelperMethods.Windows11FirstBuild && installationType == "Client") + Assert.Contains("Windows 11", version); + } + } + } + + public sealed class XmlTextTests + { + [Fact] + public void ToValidXml_ReplacesAllInvalidCharacters() + { + Assert.Equal("a�b�c�d�\t\r\n\U0001F600", + XmlText.ToValidXml("a\u0001b\u0000c￾d\uD800\t\r\n\U0001F600")); + } + + [Fact] + public void ReplaceLoneSurrogates_KeepsControlCharacters() + { + Assert.Equal("a\u0001��\U0001F600", XmlText.ReplaceLoneSurrogates("a\u0001\uDC00\uD800\U0001F600")); + } + + [Fact] + public void ValidText_IsReturnedUnchanged() + { + const string text = "plain text <&> \U0001F600"; + Assert.Same(text, XmlText.ToValidXml(text)); + Assert.Null(XmlText.ToValidXml(null)); + } + } + + public sealed class HtmlReportTests + { + private static Exception CreateException() + { + try + { + throw new InvalidOperationException("boom "); + } + catch (Exception e) + { + return e; + } + } + + [Fact] + public void SavedReport_EmbedsTheScreenshot() + { + var screenshot = new byte[] { 137, 80, 78, 71, 1, 2, 3 }; + + var html = ReportCrash.CreateHtmlReport("App", "1.0", CreateException(), "dev", "user", screenshot); + + Assert.Contains("src=\"data:image/png;base64," + Convert.ToBase64String(screenshot) + "\"", html); + Assert.Contains("boom <b>", html); + } + + [Theory] + [InlineData(" at A.B()\r\n at C.D()")] + [InlineData(" at A.B()\n at C.D()")] + public void StackTrace_LineBreaksAreKept(string stackTrace) + { + var exception = new ExceptionData { TypeName = "System.Exception", Message = "m", StackTrace = stackTrace }.ToException(); + + var html = ReportCrash.CreateHtmlReport("App", "1.0", exception, null, null, null); + + Assert.Contains(" at A.B()
at C.D()", html); + } + + [Fact] + public void Report_WithoutScreenshot_HasNoImage() + { + var html = ReportCrash.CreateHtmlReport("App", "1.0", CreateException(), null, null, null); + + Assert.DoesNotContain(" new ReportCrash("to@example.com") + { + AnalyzeWithDoctorDump = false, + SmtpHost = "127.0.0.1", + Port = port, + FromEmail = "from@example.com" + }; + + private static void SaveReport(string message = "queued", string title = "Original App", string assemblyVersion = "1.2.3.4") + { + Exception exception; + try + { + throw new InvalidOperationException(message); + } + catch (Exception e) + { + exception = e; + } + + var reporter = new ReportCrash("to@example.com") + { + Exception = exception, + ApplicationTitle = title, + ApplicationVersion = assemblyVersion, + ApplicationAssemblyVersion = assemblyVersion + }; + reporter.SaveFailedReport("user@example.com", "user message", includeScreenshot: false); + } + + private static int QueuedCount() => FailedReportQueue.GetFiles(FailedReportQueue.GetDirectory()).Count(); + + // ---------------- only one retry at a time ---------------- + + [Fact] + public async Task OverlappingRetries_SendEachReportOnce() + { + SaveReport(); + using (var smtp = new SmtpStub()) + { + var retries = Enumerable.Range(0, 20).Select(_ => SmtpReporter(smtp.Port).RetryFailedReportsAsync()).ToArray(); + var results = await Task.WhenAll(retries); + + Assert.Equal(1, results.Sum(r => r.FailedReportsSent)); + Assert.Equal(0, QueuedCount()); + Assert.True(smtp.Messages.TryTake(out _, MailTimeout)); + // Give any duplicate delivery a chance to arrive before asserting there was none. + Assert.False(smtp.Messages.TryTake(out _, TimeSpan.FromMilliseconds(500)), "report was sent more than once"); + } + } + + [Fact] + public async Task Retry_SkipsWhileAnotherProcessHoldsTheQueueLock() + { + SaveReport(); + var queue = FailedReportQueue.GetDirectory(); + using (var smtp = new SmtpStub()) + { + // Same lock another process takes while retrying. + using (var otherProcessLock = FailedReportQueue.TryLock(queue)) + { + Assert.NotNull(otherProcessLock); + + var whileLocked = await SmtpReporter(smtp.Port).RetryFailedReportsAsync(); + + Assert.Equal(0, whileLocked.FailedReports); + Assert.Equal(0, whileLocked.FailedReportsSent); + Assert.Equal(1, QueuedCount()); + } + + var afterRelease = await SmtpReporter(smtp.Port).RetryFailedReportsAsync(); + + Assert.Equal(1, afterRelease.FailedReportsSent); + Assert.Equal(0, QueuedCount()); + } + } + + [Fact] + public async Task Retry_IsNotBlockedByALockFileLeftByAnInterruptedRetry() + { + SaveReport(); + var queue = FailedReportQueue.GetDirectory(); + File.WriteAllText(Path.Combine(queue.FullName, FailedReportQueue.LockFileName), "left behind by a crashed process"); + + using (var smtp = new SmtpStub()) + { + var result = await SmtpReporter(smtp.Port).RetryFailedReportsAsync(); + + Assert.Equal(1, result.FailedReportsSent); + } + } + + // ---------------- cancellation and timeout while the SMTP server stalls ---------------- + + [Theory] + [InlineData(0)] // right after the connection is accepted, while the client is still connecting + [InlineData(500)] // while the client waits for the server greeting + public async Task Cancellation_InterruptsAStalledSmtpDelivery(int cancelAfterMilliseconds) + { + SaveReport(); + var stalled = SmtpStub.StartStalledServer(out var port); + try + { + using (var cancellation = new CancellationTokenSource()) + { + var retry = SmtpReporter(port).RetryFailedReportsAsync(cancellation.Token); + using (await stalled.AcceptTcpClientAsync()) + { + await Task.Delay(cancelAfterMilliseconds); + Assert.False(retry.IsCompleted, "delivery should be waiting for the server greeting"); + + cancellation.Cancel(); + // The connection is kept open: delivery must stop because of the cancellation, not the server. + var finished = await Task.WhenAny(retry, Task.Delay(TimeSpan.FromSeconds(1))); + + Assert.Same(retry, finished); + await Assert.ThrowsAnyAsync(() => retry); + } + } + } + finally + { + stalled.Stop(); + } + + Assert.Equal(1, QueuedCount()); + } + + [Fact] + public async Task Cancellation_InterruptsAStalledSmtpDelivery_ReviewerProbe() + { + // Regression probe from the 2.1 review: a version 1 report, cancelled as soon as the connection is accepted. + // On .NET Framework, SendAsyncCancel alone did not stop this delivery until the server closed the connection. + // The window in which that happens is widest on the first SMTP connection of a process, so this test reliably + // reproduces the bug when run on its own (--filter ReviewerProbe) and may not when other SMTP tests ran first. + var directory = FailedReportQueue.GetDirectory(); + new FailedReport { Exception = ExceptionData.FromException(new Exception("probe")) } + .Save(Path.Combine(directory.FullName, FailedReportQueue.CreateFileName(DateTime.UtcNow))); + var listener = SmtpStub.StartStalledServer(out var port); + try + { + using (var cancellation = new CancellationTokenSource()) + { + var retry = SmtpReporter(port).RetryFailedReportsAsync(cancellation.Token); + using (var connection = await listener.AcceptTcpClientAsync()) + { + cancellation.Cancel(); + var completed = await Task.WhenAny(retry, Task.Delay(1000)); + connection.Close(); + try + { + await retry; + } + catch (OperationCanceledException) + { + } + + Assert.Same(retry, completed); + } + } + } + finally + { + listener.Stop(); + } + } + + [Fact] + public async Task DeliveryTimeout_StopsAStalledDeliveryAndKeepsTheReport() + { + SaveReport("first"); + SaveReport("second"); + var stalled = SmtpStub.StartStalledServer(out var port); + try + { + var reporter = SmtpReporter(port); + reporter.DeliveryTimeout = TimeSpan.FromMilliseconds(300); + var stopwatch = Stopwatch.StartNew(); + + var result = await reporter.RetryFailedReportsAsync(); + + Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(5), $"took {stopwatch.Elapsed}"); + Assert.Equal(2, result.FailedReports); + Assert.Equal(0, result.FailedReportsSent); + } + finally + { + stalled.Stop(); + } + + Assert.Equal(2, QueuedCount()); + } + + [Fact] + public async Task SendMail_CancellationRacingWithCompletionIsHandled() + { + // Cancel right after a successful delivery completes: the send must still report success, not hang or throw. + using (var smtp = new SmtpStub()) + { + for (var i = 0; i < 10; i++) + { + using (var cancellation = new CancellationTokenSource()) + using (var client = new System.Net.Mail.SmtpClient("127.0.0.1", smtp.Port)) + using (var message = new System.Net.Mail.MailMessage("from@example.com", "to@example.com", "race", "body")) + { + var send = ReportCrash.SendMailAsync(client, message, cancellation.Token); + var sent = await Task.WhenAny(send, Task.Delay(MailTimeout)); + cancellation.Cancel(); + + Assert.Same(send, sent); + await send; + } + } + + Assert.Equal(10, smtp.Messages.Count); + } + } + + // ---------------- Doctor Dump retries ---------------- + + private static string DrDumpResponse(string operation, string type) => + "" + + $"<{operation}Response xmlns=\"https://www.drdump.com/services\"><{operation}Result xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" i:type=\"{type}\">" + + $"AQIDhttps://drdump.test/problem/{operation}"; + + private static FakeHttpHandler DrDumpServer() => new FakeHttpHandler((request, token) => + { + var body = request.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + var response = body.Contains(" openedUrls, + Action opener = null) => new ReportCrash("to@example.com") + { + AnalyzeWithDoctorDump = true, + DoctorDumpSettings = new DoctorDumpSettings { OpenReportInBrowser = true }, + DrDumpServiceFactory = () => new DrDumpService(new DrDumpSoapClient(new HttpClient(server))), + ReportUrlOpener = opener ?? openedUrls.Enqueue + }; + + [Fact] + public async Task DrDumpRetry_ReportsTheSavedApplicationVersionAfterAnUpgrade() + { + // Crashed as version 1.2.3.4; the application was upgraded (the test host has a different version) before retrying. + SaveReport(title: "Original App", assemblyVersion: "1.2.3.4"); + var server = DrDumpServer(); + var openedUrls = new ConcurrentQueue(); + + var result = await DrDumpReporter(server, openedUrls).RetryFailedReportsAsync(); + + Assert.Equal(1, result.FailedReportsSent); + var anonymousRequest = server.RequestBodies.First(body => body.Contains(".*?
", RegexOptions.Singleline).Value; + Assert.Contains("Original App", app); + Assert.Contains("1234", app); + Assert.Equal(new[] { "https://drdump.test/problem/SendAdditionalData" }, openedUrls); + } + + [Fact] + public async Task DrDumpRetry_BrowserFailureDoesNotCauseASecondUpload() + { + SaveReport(); + var server = DrDumpServer(); + + var first = await DrDumpReporter(server, null, url => throw new InvalidOperationException("no default browser")) + .RetryFailedReportsAsync(); + var second = await DrDumpReporter(server, new ConcurrentQueue()).RetryFailedReportsAsync(); + + Assert.Equal(1, first.FailedReportsSent); + Assert.Equal(0, second.FailedReports); + Assert.Equal(0, QueuedCount()); + Assert.Equal(1, server.RequestBodies.Count(body => body.Contains(" new ReportCrash("to@example.com") + { + AnalyzeWithDoctorDump = false, + SmtpHost = "127.0.0.1", + Port = smtpPort, + FromEmail = "from@example.com" + }; + + private static Exception CreateException(string message) + { + try + { + throw new InvalidOperationException(message); + } + catch (Exception e) + { + return e; + } + } + + private static void SaveReport(int smtpPort, string message, byte[] screenshot) + { + var reporter = CreateReporter(smtpPort); + reporter.Exception = CreateException(message); + reporter.ApplicationTitle = "Original App"; + reporter.ApplicationVersion = "9.8.7.6"; + reporter.DeveloperMessage = "original developer message"; + reporter.ScreenShotBinary = screenshot; + reporter.SaveFailedReport("user@example.com", "what the user typed", includeScreenshot: true); + } + + private static string[] QueuedFiles() => + FailedReportQueue.GetFiles(FailedReportQueue.GetDirectory()).Select(f => f.FullName).ToArray(); + + [Fact] + public async Task RetryAsync_SendsTheSavedSnapshotWithoutRecapturing() + { + using (var smtp = new SmtpStub()) + { + var screenshot = Enumerable.Range(0, 48).Select(i => (byte) (i * 5)).ToArray(); + SaveReport(smtp.Port, "saved crash", screenshot); + + // Simulates the next start of the application: different settings, no screenshot of its own. + var reporter = CreateReporter(smtp.Port); + reporter.DeveloperMessage = "message of the new session"; + reporter.IncludeScreenshot = false; + + var result = await reporter.RetryFailedReportsAsync(); + + Assert.Equal(1, result.FailedReports); + Assert.Equal(1, result.FailedReportsSent); + Assert.True(result.AnyReportSent); + Assert.Empty(QueuedFiles()); + Assert.Null(reporter.ScreenShotBinary); + + Assert.True(smtp.Messages.TryTake(out var raw, MailTimeout), "no e-mail received"); + var mail = SmtpStub.Decode(raw); + Assert.Contains("saved crash", mail); + Assert.Contains("Original App 9.8.7.6", mail); + Assert.Contains("original developer message", mail); + Assert.DoesNotContain("message of the new session", mail); + Assert.Contains("what the user typed", mail); + Assert.Contains("Crash Report by user@example.com", mail); + Assert.Contains("System.InvalidOperationException", mail); + // The original screenshot is attached, even though the new session disabled screenshots. + Assert.Contains(Convert.ToBase64String(screenshot), raw.Replace("\r\n", "")); + } + } + + private sealed class RecordingSynchronizationContext : SynchronizationContext + { + public int Calls; + + public override void Post(SendOrPostCallback d, object state) + { + Interlocked.Increment(ref Calls); + base.Post(d, state); + } + + public override void Send(SendOrPostCallback d, object state) + { + Interlocked.Increment(ref Calls); + base.Send(d, state); + } + + public override SynchronizationContext CreateCopy() => this; + } + + [Fact] + public async Task RetryAsync_NeverUsesTheCallersSynchronizationContext() + { + using (var smtp = new SmtpStub()) + { + SaveReport(smtp.Port, "from ui thread", null); + var reporter = CreateReporter(smtp.Port); + + // Simulates calling from a UI thread (e.g. WPF Application.OnStartup) without awaiting. + var uiContext = new RecordingSynchronizationContext(); + var previous = SynchronizationContext.Current; + Task retry; + SynchronizationContext.SetSynchronizationContext(uiContext); + try + { + retry = reporter.RetryFailedReportsAsync(); + } + finally + { + SynchronizationContext.SetSynchronizationContext(previous); + } + + var result = await retry; + + Assert.Equal(1, result.FailedReportsSent); + Assert.Equal(0, uiContext.Calls); + } + } + + [Fact] + public async Task RetryAsync_StopsAtFirstFailureAndKeepsTheReports() + { + var closedPort = SmtpStub.GetClosedPort(); + SaveReport(closedPort, "first", null); + SaveReport(closedPort, "second", null); + + var result = await CreateReporter(closedPort).RetryFailedReportsAsync(); + + Assert.Equal(2, result.FailedReports); + Assert.Equal(0, result.FailedReportsSent); + Assert.False(result.AnyReportSent); + Assert.Equal(2, QueuedFiles().Length); + } + + [Fact] + public async Task RetryAsync_CancellationKeepsTheReports() + { + SaveReport(SmtpStub.GetClosedPort(), "queued", null); + using (var cancellation = new CancellationTokenSource()) + { + cancellation.Cancel(); + + await Assert.ThrowsAnyAsync(() => + CreateReporter(SmtpStub.GetClosedPort()).RetryFailedReportsAsync(cancellation.Token)); + } + + Assert.Single(QueuedFiles()); + } + + [Fact] + public async Task RetryAsync_DoesNotTouchReportsOfOtherApplications() + { + var otherApplication = FailedReportQueue.GetDirectory("Some Other App"); + otherApplication.Create(); + var otherReport = Path.Combine(otherApplication.FullName, FailedReportQueue.CreateFileName(DateTime.UtcNow)); + new FailedReport { Exception = ExceptionData.FromException(new Exception("not mine")) }.Save(otherReport); + + using (var smtp = new SmtpStub()) + { + var result = await CreateReporter(smtp.Port).RetryFailedReportsAsync(); + + Assert.Equal(0, result.FailedReports); + Assert.True(File.Exists(otherReport)); + Assert.Empty(smtp.Messages); + } + } + + [Fact] + public void Retry_SynchronousWrapperReportsCounts() + { + using (var smtp = new SmtpStub()) + { + SaveReport(smtp.Port, "sync retry", null); + + var anySent = CreateReporter(smtp.Port).RetryFailedReports(out var found, out var sent); + + Assert.True(anySent); + Assert.Equal(1, found); + Assert.Equal(1, sent); + Assert.True(smtp.Messages.TryTake(out _, MailTimeout)); + } + } + + [Fact] + public async Task RetryAsync_SendsVersion1ReportsWithCurrentSettings() + { + // A report saved by 2.0.x only contains the exception and screenshot. + var queue = FailedReportQueue.GetDirectory(); + queue.Create(); + new FailedReport { Exception = ExceptionData.FromException(CreateException("from 2.0")) } + .Save(Path.Combine(queue.FullName, FailedReportQueue.CreateFileName(DateTime.UtcNow))); + + using (var smtp = new SmtpStub()) + { + var reporter = CreateReporter(smtp.Port); + reporter.DeveloperMessage = "current developer message"; + + var result = await reporter.RetryFailedReportsAsync(); + + Assert.Equal(1, result.FailedReportsSent); + Assert.True(smtp.Messages.TryTake(out var raw, MailTimeout)); + var mail = SmtpStub.Decode(raw); + Assert.Contains("from 2.0", mail); + Assert.Contains("current developer message", mail); + } + } + + [Fact] + public async Task RetryAsync_DeletesCorruptReports() + { + var queue = FailedReportQueue.GetDirectory(); + queue.Create(); + var corrupt = Path.Combine(queue.FullName, FailedReportQueue.CreateFileName(DateTime.UtcNow)); + File.WriteAllText(corrupt, " + /// Tests that change must not run in parallel. + /// + [CollectionDefinition(Name, DisableParallelization = true)] + public sealed class QueueCollection + { + public const string Name = "Failed report queue"; + } + + internal sealed class TemporaryDirectory : IDisposable + { + public TemporaryDirectory() + { + Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "CrashReporterNET.Tests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(Path); + } + + public string Path { get; } + + public void Dispose() + { + try + { + Directory.Delete(Path, true); + } + catch (IOException) + { + } + } + } + + /// + /// Minimal SMTP server on the loopback interface that records received messages. + /// + internal sealed class SmtpStub : IDisposable + { + private readonly TcpListener _listener; + + public SmtpStub() + { + _listener = new TcpListener(IPAddress.Loopback, 0); + _listener.Start(); + Port = ((IPEndPoint) _listener.LocalEndpoint).Port; + Task.Run(AcceptLoop); + } + + public int Port { get; } + + public BlockingCollection Messages { get; } = new BlockingCollection(); + + /// + /// A server that accepts connections but never answers (no greeting), to simulate a stalled SMTP server. + /// + public static TcpListener StartStalledServer(out int port) + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + port = ((IPEndPoint) listener.LocalEndpoint).Port; + return listener; + } + + /// + /// A port on which nothing listens, to simulate an unreachable SMTP server. + /// + public static int GetClosedPort() + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint) listener.LocalEndpoint).Port; + listener.Stop(); + return port; + } + + public void Dispose() => _listener.Stop(); + + private async Task AcceptLoop() + { + while (true) + { + TcpClient client; + try + { + client = await _listener.AcceptTcpClientAsync().ConfigureAwait(false); + } + catch (Exception) + { + return; + } + + try + { + Serve(client); + } + catch (IOException) + { + } + } + } + + private void Serve(TcpClient client) + { + using (client) + using (var stream = client.GetStream()) + using (var reader = new StreamReader(stream, Encoding.ASCII)) + using (var writer = new StreamWriter(stream, Encoding.ASCII) { NewLine = "\r\n", AutoFlush = true }) + { + writer.WriteLine("220 localhost ESMTP"); + string line; + while ((line = reader.ReadLine()) != null) + { + var command = line.ToUpperInvariant(); + if (command.StartsWith("DATA")) + { + writer.WriteLine("354 End data with ."); + var message = new StringBuilder(); + while ((line = reader.ReadLine()) != null && line != ".") + message.Append(line).Append("\r\n"); + Messages.Add(message.ToString()); + writer.WriteLine("250 OK"); + } + else if (command.StartsWith("QUIT")) + { + writer.WriteLine("221 Bye"); + return; + } + else + { + writer.WriteLine("250 OK"); + } + } + } + } + + /// + /// Returns the raw message plus the decoded content of all base64 and quoted-printable MIME parts. + /// + public static string Decode(string rawMessage) + { + var text = new StringBuilder(rawMessage); + foreach (var part in Regex.Split(rawMessage, "\r\n\r\n")) + { + var candidate = part.Replace("\r\n", "").Trim(); + if (candidate.Length < 8 || !Regex.IsMatch(candidate, "^[A-Za-z0-9+/=]+$")) + continue; + try + { + text.Append(Encoding.UTF8.GetString(Convert.FromBase64String(candidate))); + } + catch (FormatException) + { + } + } + + text.Append(rawMessage.Replace("=\r\n", "").Replace("=3D", "=")); + return text.ToString(); + } + } + + /// + /// HttpMessageHandler that returns a fixed response and records the request. + /// + internal sealed class FakeHttpHandler : HttpMessageHandler + { + private readonly Func> _respond; + + public FakeHttpHandler(HttpStatusCode statusCode, string body, string contentType = "application/soap+xml; charset=utf-8") + : this((request, token) => Task.FromResult(new HttpResponseMessage(statusCode) + { + Content = new StringContent(body, Encoding.UTF8) + { + Headers = { ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(contentType) } + } + })) + { + } + + public FakeHttpHandler(Func> respond) + { + _respond = respond; + } + + public string LastRequestBody { get; private set; } + + public string LastRequestContentType { get; private set; } + + public ConcurrentQueue RequestBodies { get; } = new ConcurrentQueue(); + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + LastRequestBody = await request.Content.ReadAsStringAsync().ConfigureAwait(false); + LastRequestContentType = request.Content.Headers.ContentType?.ToString(); + RequestBodies.Enqueue(LastRequestBody); + return await _respond(request, cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/CrashReporter.NET.sln b/CrashReporter.NET.sln index 71cd9c6..ea19ca5 100644 --- a/CrashReporter.NET.sln +++ b/CrashReporter.NET.sln @@ -1,4 +1,4 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 @@ -16,24 +16,66 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution README.md = README.md EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CrashReporter.NET.Tests", "CrashReporter.NET.Tests\CrashReporter.NET.Tests.csproj", "{6463E448-188E-4113-BB16-9EFE389ACA19}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {67912BDA-1572-46B0-8623-5872D9DADBC8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {67912BDA-1572-46B0-8623-5872D9DADBC8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {67912BDA-1572-46B0-8623-5872D9DADBC8}.Debug|x64.ActiveCfg = Debug|Any CPU + {67912BDA-1572-46B0-8623-5872D9DADBC8}.Debug|x64.Build.0 = Debug|Any CPU + {67912BDA-1572-46B0-8623-5872D9DADBC8}.Debug|x86.ActiveCfg = Debug|Any CPU + {67912BDA-1572-46B0-8623-5872D9DADBC8}.Debug|x86.Build.0 = Debug|Any CPU {67912BDA-1572-46B0-8623-5872D9DADBC8}.Release|Any CPU.ActiveCfg = Release|Any CPU {67912BDA-1572-46B0-8623-5872D9DADBC8}.Release|Any CPU.Build.0 = Release|Any CPU + {67912BDA-1572-46B0-8623-5872D9DADBC8}.Release|x64.ActiveCfg = Release|Any CPU + {67912BDA-1572-46B0-8623-5872D9DADBC8}.Release|x64.Build.0 = Release|Any CPU + {67912BDA-1572-46B0-8623-5872D9DADBC8}.Release|x86.ActiveCfg = Release|Any CPU + {67912BDA-1572-46B0-8623-5872D9DADBC8}.Release|x86.Build.0 = Release|Any CPU {895AE503-6920-4BFF-9D47-3A91F90E8606}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {895AE503-6920-4BFF-9D47-3A91F90E8606}.Debug|Any CPU.Build.0 = Debug|Any CPU + {895AE503-6920-4BFF-9D47-3A91F90E8606}.Debug|x64.ActiveCfg = Debug|Any CPU + {895AE503-6920-4BFF-9D47-3A91F90E8606}.Debug|x64.Build.0 = Debug|Any CPU + {895AE503-6920-4BFF-9D47-3A91F90E8606}.Debug|x86.ActiveCfg = Debug|Any CPU + {895AE503-6920-4BFF-9D47-3A91F90E8606}.Debug|x86.Build.0 = Debug|Any CPU {895AE503-6920-4BFF-9D47-3A91F90E8606}.Release|Any CPU.ActiveCfg = Release|Any CPU {895AE503-6920-4BFF-9D47-3A91F90E8606}.Release|Any CPU.Build.0 = Release|Any CPU + {895AE503-6920-4BFF-9D47-3A91F90E8606}.Release|x64.ActiveCfg = Release|Any CPU + {895AE503-6920-4BFF-9D47-3A91F90E8606}.Release|x64.Build.0 = Release|Any CPU + {895AE503-6920-4BFF-9D47-3A91F90E8606}.Release|x86.ActiveCfg = Release|Any CPU + {895AE503-6920-4BFF-9D47-3A91F90E8606}.Release|x86.Build.0 = Release|Any CPU {0DC93E03-047D-4664-BE24-2215BF98C8A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0DC93E03-047D-4664-BE24-2215BF98C8A1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0DC93E03-047D-4664-BE24-2215BF98C8A1}.Debug|x64.ActiveCfg = Debug|Any CPU + {0DC93E03-047D-4664-BE24-2215BF98C8A1}.Debug|x64.Build.0 = Debug|Any CPU + {0DC93E03-047D-4664-BE24-2215BF98C8A1}.Debug|x86.ActiveCfg = Debug|Any CPU + {0DC93E03-047D-4664-BE24-2215BF98C8A1}.Debug|x86.Build.0 = Debug|Any CPU {0DC93E03-047D-4664-BE24-2215BF98C8A1}.Release|Any CPU.ActiveCfg = Release|Any CPU {0DC93E03-047D-4664-BE24-2215BF98C8A1}.Release|Any CPU.Build.0 = Release|Any CPU + {0DC93E03-047D-4664-BE24-2215BF98C8A1}.Release|x64.ActiveCfg = Release|Any CPU + {0DC93E03-047D-4664-BE24-2215BF98C8A1}.Release|x64.Build.0 = Release|Any CPU + {0DC93E03-047D-4664-BE24-2215BF98C8A1}.Release|x86.ActiveCfg = Release|Any CPU + {0DC93E03-047D-4664-BE24-2215BF98C8A1}.Release|x86.Build.0 = Release|Any CPU + {6463E448-188E-4113-BB16-9EFE389ACA19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6463E448-188E-4113-BB16-9EFE389ACA19}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6463E448-188E-4113-BB16-9EFE389ACA19}.Debug|x64.ActiveCfg = Debug|Any CPU + {6463E448-188E-4113-BB16-9EFE389ACA19}.Debug|x64.Build.0 = Debug|Any CPU + {6463E448-188E-4113-BB16-9EFE389ACA19}.Debug|x86.ActiveCfg = Debug|Any CPU + {6463E448-188E-4113-BB16-9EFE389ACA19}.Debug|x86.Build.0 = Debug|Any CPU + {6463E448-188E-4113-BB16-9EFE389ACA19}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6463E448-188E-4113-BB16-9EFE389ACA19}.Release|Any CPU.Build.0 = Release|Any CPU + {6463E448-188E-4113-BB16-9EFE389ACA19}.Release|x64.ActiveCfg = Release|Any CPU + {6463E448-188E-4113-BB16-9EFE389ACA19}.Release|x64.Build.0 = Release|Any CPU + {6463E448-188E-4113-BB16-9EFE389ACA19}.Release|x86.ActiveCfg = Release|Any CPU + {6463E448-188E-4113-BB16-9EFE389ACA19}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CrashReporter.NET/CrashReport.cs b/CrashReporter.NET/CrashReport.cs index a273afe..85707ac 100644 --- a/CrashReporter.NET/CrashReport.cs +++ b/CrashReporter.NET/CrashReport.cs @@ -17,6 +17,10 @@ internal partial class CrashReport : Form private ProgressDialog _progressDialog; + private string _from; + + private string _userMessage; + #region Form Events public CrashReport(ReportCrash reportCrashObject) @@ -36,8 +40,7 @@ public CrashReport(ReportCrash reportCrashObject) pictureBoxScreenshot.Show(); } - if (_reportCrash.DoctorDumpSettings != null && - _reportCrash.DoctorDumpSettings.SendAnonymousReportSilently) + if (_reportCrash.SendAnonymousReportWhenDialogOpens) _reportCrash.SendAnonymousReport(SendRequestCompleted); if (!_reportCrash.ShowScreenshotTab) @@ -105,6 +108,9 @@ private void ButtonSendReportClick(object sender, EventArgs e) } } + _from = from; + _userMessage = textBoxUserMessage.Text.Trim(); + try { _reportCrash.SendReport(checkBoxIncludeScreenshot.Checked, SendRequestCompleted, @@ -127,7 +133,8 @@ private void ButtonSaveClick(object sender, EventArgs e) private void SaveFileDialogFileOk(object sender, CancelEventArgs e) { - File.WriteAllText(saveFileDialog.FileName, _reportCrash.CreateHtmlReport(textBoxUserMessage.Text.Trim())); + File.WriteAllText(saveFileDialog.FileName, + _reportCrash.CreateHtmlReport(textBoxUserMessage.Text.Trim(), checkBoxIncludeScreenshot.Checked)); } private void LinkLabelViewLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) @@ -191,8 +198,17 @@ private void ReportSuccess() private void ReportFailure(Exception exception) { - // Save crash report for later retry. - _reportCrash.SaveFailedReport(); + // Save crash report, including what the user entered, for later retry. + try + { + _reportCrash.SaveFailedReport(_from, _userMessage, checkBoxIncludeScreenshot.Checked); + } + catch (Exception saveException) when (saveException is IOException || saveException is UnauthorizedAccessException) + { + // The crash reporter itself must not crash; the report just can't be retried later. + Debug.WriteLine(saveException); + } + _progressDialog?.Close(); MessageBox.Show(exception.Message, exception.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error); } diff --git a/CrashReporter.NET/CrashReporter.NET.csproj b/CrashReporter.NET/CrashReporter.NET.csproj index 9f82477..fd7aedd 100644 --- a/CrashReporter.NET/CrashReporter.NET.csproj +++ b/CrashReporter.NET/CrashReporter.NET.csproj @@ -12,7 +12,7 @@ - 2.0.0 + 2.1.0 RBSoft CrashReporter.NET CrashReporter.NET @@ -20,7 +20,9 @@ en - + + true CrashReporter.NET.snk @@ -51,6 +53,10 @@ + + + + diff --git a/CrashReporter.NET/CrashReporter.NET.snk b/CrashReporter.NET/CrashReporter.NET.snk new file mode 100644 index 0000000000000000000000000000000000000000..180621036c016c7a91c1c63ef7852bc5d4ea1b4e GIT binary patch literal 596 zcmV-a0;~N80ssI2Bme+XQ$aES1ONa50097{l1Fj=bOT7oTUK%{sqk{3-ugeCm5ti< zNNyQ9Jt^sXY5p-!s6fPp>(cIFfGw_o`_x5M5){fz@N1eAxSV7lag%&HUM;}S6wfw4 z1efUOOXHLt$n&JyRxBS+yS=Dy zDT0y#W%MSTZ-a-AavG6zF}1E~tL;G=_wfW~ksDwb0y;3^LKlBqarND*N~vIe8tDcv zLE0+!;q33SMl{qbv#w`4(x|5$Zg}`XR-o6E*k#Jg`Gr?JIg8)Ddj(3H(Io)B8+Yc= z{)tO`o2T-4YR=1*bb&5pvpHlM8j;K0iB5Z8{d^V%v~92#B0^)sCRcV_*yQ5kNl>yg zr`Xe+glc*lVBMSQlf5^8*?2TF2n$XH5wl|SywAe_SCXIms2VOz1Ln_&9Zz?}Bpt;z zB9X6{*ADh@R(0~GFPhWj+G7Ol+S_Q}9&Fr~sY!N27uTyVk_3JxN5<-BB2u>I#5B)p zJxMVr#WntmlP&Ul#gO2;P(Jo+nE848w{Sn?y>FUw*@MnoVZGx;M~32Qz#J7lO(fZT z4l2MXjWb& + /// Time of the crash. When not set (a new report), the time the report is sent is used. + /// + public DateTime? CrashDateUtc { get; set; } + + /// + /// Application title saved with a failed report. When not set, the running application's title is used. + /// + public string ApplicationTitle { get; set; } + + /// + /// Entry assembly version saved with a failed report. When not set, the running application's version is used, + /// so a report retried after an upgrade is still attributed to the version that crashed. + /// + public string ApplicationVersion { get; set; } } } \ No newline at end of file diff --git a/CrashReporter.NET/DrDump/DrDumpService.cs b/CrashReporter.NET/DrDump/DrDumpService.cs index fe14693..bca2b91 100644 --- a/CrashReporter.NET/DrDump/DrDumpService.cs +++ b/CrashReporter.NET/DrDump/DrDumpService.cs @@ -1,6 +1,7 @@ using System; using System.ComponentModel; using System.Net; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using CrashReporterDotNET.com.drdump; @@ -17,6 +18,14 @@ internal class DrDumpService private readonly DrDumpSoapClient _uploader; + /// + /// Uses the given client (tests). + /// + internal DrDumpService(DrDumpSoapClient uploader) + { + _uploader = uploader; + } + public DrDumpService(IWebProxy webProxy = null) { _uploader = new DrDumpSoapClient(webProxy); @@ -60,13 +69,30 @@ public void SendAnonymousReportAsync(Exception exception, string toEmail, Guid? public string SendReportSilently(Exception exception, string toEmail, Guid? applicationId, string developerMessage, string from, string userMessage, byte[] screenshot) { - _sendRequestState = new SendRequestState + // Task.Run avoids deadlocks when called from a thread with a synchronization context (e.g. the UI thread). + return Task.Run(() => SendReportAsync(exception, toEmail, applicationId, developerMessage, from, userMessage, + screenshot, null, null, null, CancellationToken.None)).GetAwaiter().GetResult(); + } + + /// + /// Sends the complete report without any UI and returns the URL of the problem page. + /// For a retried report, , and + /// (entry assembly version) are the saved values; null means now / the running application. + /// + public async Task SendReportAsync(Exception exception, string toEmail, Guid? applicationId, + string developerMessage, string from, string userMessage, byte[] screenshot, DateTime? crashDateUtc, + string applicationTitle, string applicationVersion, CancellationToken cancellationToken) + { + var state = new SendRequestState { AnonymousData = new AnonymousData { Exception = exception, ToEmail = toEmail, - ApplicationID = applicationId + ApplicationID = applicationId, + CrashDateUtc = crashDateUtc, + ApplicationTitle = applicationTitle, + ApplicationVersion = applicationVersion }, PrivateData = new PrivateData { @@ -76,20 +102,17 @@ public string SendReportSilently(Exception exception, string toEmail, Guid? appl Screenshot = screenshot } }; + _sendRequestState = state; - var clientLib = SendRequestState.GetClientLib(); - var application = _sendRequestState.GetApplication(); - var exceptionDescription = _sendRequestState.GetExceptionDescription(true); - var response = RunSynchronously(() => - _uploader.SendAnonymousReportAsync(clientLib, application, exceptionDescription)); + var response = await _uploader.SendAnonymousReportAsync(SendRequestState.GetClientLib(), + state.GetApplication(), state.GetExceptionDescription(true), cancellationToken).ConfigureAwait(false); if (response is ErrorResponse errorResponse) throw new Exception(errorResponse.Error); if (response is NeedReportResponse) { - var detailedExceptionDescription = _sendRequestState.GetDetailedExceptionDescription(); - var additionalDataResponse = RunSynchronously(() => - _uploader.SendAdditionalDataAsync(response.Context, detailedExceptionDescription)); + var additionalDataResponse = await _uploader.SendAdditionalDataAsync(response.Context, + state.GetDetailedExceptionDescription(), cancellationToken).ConfigureAwait(false); if (additionalDataResponse is ErrorResponse errorAdditionalDataResponse) throw new Exception(errorAdditionalDataResponse.Error); return additionalDataResponse.UrlToProblem; @@ -223,12 +246,6 @@ private static void RunAsync(Func> request, Action }, TaskScheduler.Default); } - private static Response RunSynchronously(Func> request) - { - // Task.Run avoids deadlocks when called from a thread with a synchronization context (e.g. the UI thread). - return Task.Run(request).GetAwaiter().GetResult(); - } - internal sealed class RequestResult { public RequestResult(Response result, Exception error, bool cancelled) diff --git a/CrashReporter.NET/DrDump/DrDumpSoapClient.cs b/CrashReporter.NET/DrDump/DrDumpSoapClient.cs index c1cbe9c..5d3322a 100644 --- a/CrashReporter.NET/DrDump/DrDumpSoapClient.cs +++ b/CrashReporter.NET/DrDump/DrDumpSoapClient.cs @@ -3,7 +3,9 @@ using System.Net; using System.Net.Http; using System.Net.Http.Headers; +using System.Runtime.CompilerServices; using System.Text; +using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Schema; @@ -38,41 +40,69 @@ internal class DrDumpSoapClient Member("context", typeof(byte[]), "base64Binary"), Member("addInfo", typeof(DetailedExceptionDescription))); + // HttpClient instances are long-lived and shared, as recommended by + // https://learn.microsoft.com/dotnet/fundamentals/networking/http/httpclient-guidelines. + // One client without a custom proxy, plus one per IWebProxy instance (released together with the proxy). + private static readonly Lazy SharedClient = new Lazy(() => CreateHttpClient(null)); + + private static readonly ConditionalWeakTable ProxyClients = + new ConditionalWeakTable(); + private readonly HttpClient _httpClient; public DrDumpSoapClient(IWebProxy webProxy = null) + : this(webProxy == null ? SharedClient.Value : ProxyClients.GetValue(webProxy, CreateHttpClient)) { - var handler = new HttpClientHandler(); - if (webProxy != null) - { - handler.Proxy = webProxy; - handler.UseProxy = true; - } + } - _httpClient = new HttpClient(handler); + /// + /// Uses the given client. The caller owns it; this class never disposes it. + /// + internal DrDumpSoapClient(HttpClient httpClient) + { + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); } public string Url { get; set; } = DefaultUrl; public Task SendAnonymousReportAsync(ClientLib clientLib, Application app, - ExceptionDescription exception) + ExceptionDescription exception, CancellationToken cancellationToken = default) { - return InvokeAsync(SendAnonymousReportOperation, clientLib, app, exception); + return InvokeAsync(SendAnonymousReportOperation, cancellationToken, clientLib, app, exception); } - public Task SendAdditionalDataAsync(byte[] context, DetailedExceptionDescription addInfo) + public Task SendAdditionalDataAsync(byte[] context, DetailedExceptionDescription addInfo, + CancellationToken cancellationToken = default) { - return InvokeAsync(SendAdditionalDataOperation, context, addInfo); + return InvokeAsync(SendAdditionalDataOperation, cancellationToken, context, addInfo); } - private async Task InvokeAsync(Operation operation, params object[] parameters) + private static HttpClient CreateHttpClient(IWebProxy webProxy) + { +#if NETFRAMEWORK + var handler = new HttpClientHandler(); +#else + // Recycle pooled connections periodically so DNS changes are picked up by the long-lived client. + var handler = new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(5) }; +#endif + if (webProxy != null) + { + handler.Proxy = webProxy; + handler.UseProxy = true; + } + + return new HttpClient(handler); + } + + private async Task InvokeAsync(Operation operation, CancellationToken cancellationToken, + params object[] parameters) { using (var content = new ByteArrayContent(operation.WriteRequest(parameters))) { content.Headers.ContentType = MediaTypeHeaderValue.Parse( $"application/soap+xml; charset=utf-8; action=\"{ActionPrefix}{operation.Name}\""); - using (var httpResponse = await _httpClient.PostAsync(Url, content).ConfigureAwait(false)) + using (var httpResponse = await _httpClient.PostAsync(Url, content, cancellationToken).ConfigureAwait(false)) { var body = await httpResponse.Content.ReadAsByteArrayAsync().ConfigureAwait(false); return operation.ReadResponse(body, httpResponse); @@ -135,71 +165,112 @@ public byte[] WriteRequest(object[] parameters) } } + /// + /// Validates and reads the response: + /// SOAP faults are reported with their reason (whatever the HTTP status), other unsuccessful HTTP statuses + /// are reported as , and a missing or nil result is rejected. + /// public Response ReadResponse(byte[] body, HttpResponseMessage httpResponse) { + Envelope envelope; try { - var settings = new XmlReaderSettings - { - IgnoreWhitespace = true, - DtdProcessing = DtdProcessing.Prohibit, - XmlResolver = null - }; - using (var reader = XmlReader.Create(new MemoryStream(body), settings)) + envelope = ReadEnvelope(body); + } + catch (XmlException e) + { + if (!httpResponse.IsSuccessStatusCode) + throw CreateHttpError(httpResponse, e); + throw new InvalidOperationException( + $"The Doctor Dump service returned an invalid response to {Name}.", e); + } + + if (envelope.IsFault) + throw new InvalidOperationException(string.IsNullOrEmpty(envelope.FaultReason) + ? $"Doctor Dump service returned a SOAP fault ({envelope.FaultCode})." + : envelope.FaultReason); + + if (!httpResponse.IsSuccessStatusCode) + throw CreateHttpError(httpResponse, null); + + if (!(envelope.Result is Response response)) + throw new InvalidOperationException( + $"The Doctor Dump service returned no result for {Name}."); + + return response; + } + + private Envelope ReadEnvelope(byte[] body) + { + var settings = new XmlReaderSettings + { + IgnoreWhitespace = true, + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null + }; + using (var reader = XmlReader.Create(new MemoryStream(body), settings)) + { + reader.MoveToContent(); + reader.ReadStartElement("Envelope", SoapNamespace); + reader.MoveToContent(); + if (reader.IsStartElement("Header", SoapNamespace)) { + reader.Skip(); reader.MoveToContent(); - reader.ReadStartElement("Envelope", SoapNamespace); - reader.MoveToContent(); - if (reader.IsStartElement("Header", SoapNamespace)) - { - reader.Skip(); - reader.MoveToContent(); - } + } - reader.ReadStartElement("Body", SoapNamespace); - reader.MoveToContent(); - if (reader.IsStartElement("Fault", SoapNamespace)) - { - throw ReadFault(reader); - } + reader.ReadStartElement("Body", SoapNamespace); + reader.MoveToContent(); + if (reader.IsStartElement("Fault", SoapNamespace)) + return ReadFault(reader); - var results = (object[]) _responseSerializer.Deserialize(reader); - return (Response) results[0]; + object[] results; + try + { + results = (object[]) _responseSerializer.Deserialize(reader); } - } - catch (XmlException) when (!httpResponse.IsSuccessStatusCode) - { - // Not a SOAP message (e.g. proxy or gateway error page), report the HTTP failure instead. - httpResponse.EnsureSuccessStatusCode(); - throw; - } - catch (InvalidOperationException e) when (e.InnerException is XmlException && !httpResponse.IsSuccessStatusCode) - { - httpResponse.EnsureSuccessStatusCode(); - throw; + catch (InvalidOperationException e) + { + // XmlSerializer reports malformed or unexpected content as InvalidOperationException. + throw new XmlException(e.InnerException?.Message ?? e.Message, e); + } + + return new Envelope { Result = results != null && results.Length > 0 ? results[0] : null }; } } - private static Exception ReadFault(XmlReader reader) + private static Envelope ReadFault(XmlReader reader) { - string code = null; - string reason = null; + var envelope = new Envelope { IsFault = true }; using (var fault = reader.ReadSubtree()) { while (fault.Read()) { if (fault.NodeType != XmlNodeType.Element || fault.NamespaceURI != SoapNamespace) continue; - if (fault.LocalName == "Value" && code == null) - code = fault.ReadElementContentAsString(); - else if (fault.LocalName == "Text" && reason == null) - reason = fault.ReadElementContentAsString(); + if (fault.LocalName == "Value" && envelope.FaultCode == null) + envelope.FaultCode = fault.ReadElementContentAsString(); + else if (fault.LocalName == "Text" && envelope.FaultReason == null) + envelope.FaultReason = fault.ReadElementContentAsString(); } } - return new InvalidOperationException(string.IsNullOrEmpty(reason) - ? $"Doctor Dump service returned a SOAP fault ({code})." - : reason); + return envelope; + } + + private static HttpRequestException CreateHttpError(HttpResponseMessage httpResponse, Exception inner) + { + return new HttpRequestException( + $"The Doctor Dump service returned HTTP {(int) httpResponse.StatusCode} ({httpResponse.ReasonPhrase}).", + inner); + } + + private sealed class Envelope + { + public bool IsFault; + public string FaultCode; + public string FaultReason; + public object Result; } } } diff --git a/CrashReporter.NET/DrDump/SendRequestState.cs b/CrashReporter.NET/DrDump/SendRequestState.cs index b2ee728..abde28e 100644 --- a/CrashReporter.NET/DrDump/SendRequestState.cs +++ b/CrashReporter.NET/DrDump/SendRequestState.cs @@ -19,11 +19,11 @@ private static ExceptionInfo ConvertToExceptionInfo(Exception e, bool anonymous) return null; return new ExceptionInfo { - Type = ReplayedException.GetTypeName(e), + Type = XmlText.ToValidXml(ReplayedException.GetTypeName(e)), HResult = e.HResult, - StackTrace = e.StackTrace, - Source = e.Source, - Message = anonymous ? null : e.Message, + StackTrace = XmlText.ToValidXml(e.StackTrace), + Source = XmlText.ToValidXml(e.Source), + Message = anonymous ? null : XmlText.ToValidXml(e.Message), InnerException = ConvertToExceptionInfo(e.InnerException, anonymous) }; } @@ -50,7 +50,18 @@ private static System.Net.NetworkInformation.PhysicalAddress GetMacAddress() private int GetAnonymousMachineID() { - System.Net.NetworkInformation.PhysicalAddress mac = GetMacAddress(); + System.Net.NetworkInformation.PhysicalAddress mac; + try + { + mac = GetMacAddress(); + } + catch (Exception e) when (e is System.Net.Sockets.SocketException || + e is System.Net.NetworkInformation.NetworkInformationException) + { + // No network route (e.g. offline): the machine ID is optional, the report must still be created. + return 0; + } + if (mac == null) return 0; using (var md5 = System.Security.Cryptography.MD5.Create()) @@ -64,67 +75,75 @@ internal DetailedExceptionDescription GetDetailedExceptionDescription() return new DetailedExceptionDescription { Exception = GetExceptionDescription(false), - DeveloperMessage = PrivateData.DeveloperMessage, - UserDescription = PrivateData.UserMessage, - UserEmail = PrivateData.UserEmail, + DeveloperMessage = XmlText.ToValidXml(PrivateData.DeveloperMessage), + UserDescription = XmlText.ToValidXml(PrivateData.UserMessage), + UserEmail = XmlText.ToValidXml(PrivateData.UserEmail), PngScreenShot = PrivateData.Screenshot }; } - + internal ExceptionDescription GetExceptionDescription(bool anonymous) { var oldCulture = System.Threading.Thread.CurrentThread.CurrentCulture; var oldUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; - - var osVersion = Environment.OSVersion; - var os = $"os={osVersion.Platform};v={HelperMethods.GetOSVersion()};spname={osVersion.ServicePack}"; - - var exceptionDescription = new ExceptionDescription + try { - ClrVersion = Environment.Version.ToString(), - OS = os, - CrashDate = DateTime.UtcNow, - PCID = GetAnonymousMachineID(), - Exception = ConvertToExceptionInfo(AnonymousData.Exception, anonymous), - ExceptionString = anonymous ? null : AnonymousData.Exception.ToString(), - }; + var osVersion = Environment.OSVersion; + // The numeric version is reported as-is (Windows 11 is 10.0.22000+); the service maps it to a product name. + var os = $"os={osVersion.Platform};v={HelperMethods.GetOSVersion()};spname={osVersion.ServicePack}"; - System.Threading.Thread.CurrentThread.CurrentCulture = oldCulture; - System.Threading.Thread.CurrentThread.CurrentUICulture = oldUICulture; - - return exceptionDescription; + return new ExceptionDescription + { + ClrVersion = Environment.Version.ToString(), + OS = os, + CrashDate = AnonymousData.CrashDateUtc ?? DateTime.UtcNow, + PCID = GetAnonymousMachineID(), + Exception = ConvertToExceptionInfo(AnonymousData.Exception, anonymous), + ExceptionString = anonymous ? null : XmlText.ToValidXml(AnonymousData.Exception.ToString()), + }; + } + finally + { + System.Threading.Thread.CurrentThread.CurrentCulture = oldCulture; + System.Threading.Thread.CurrentThread.CurrentUICulture = oldUICulture; + } } internal Application GetApplication() { var mainAssembly = System.Reflection.Assembly.GetEntryAssembly(); - string moduleName = mainAssembly.GetName().Name; + string moduleName = mainAssembly?.GetName().Name ?? FailedReportQueue.GetApplicationName(); - var attributes = mainAssembly.GetCustomAttributes(typeof(System.Reflection.AssemblyCompanyAttribute), true); - string appCompany = attributes.Length > 0 + var attributes = mainAssembly?.GetCustomAttributes(typeof(System.Reflection.AssemblyCompanyAttribute), true); + string appCompany = attributes?.Length > 0 ? ((System.Reflection.AssemblyCompanyAttribute) attributes[0]).Company : AnonymousData.ToEmail; - var attributes2 = mainAssembly.GetCustomAttributes(typeof(System.Reflection.AssemblyTitleAttribute), true); - string appTitle = attributes2.Length > 0 - ? ((System.Reflection.AssemblyTitleAttribute) attributes2[0]).Title - : moduleName; + var attributes2 = mainAssembly?.GetCustomAttributes(typeof(System.Reflection.AssemblyTitleAttribute), true); + string appTitle = !string.IsNullOrEmpty(AnonymousData.ApplicationTitle) + ? AnonymousData.ApplicationTitle + : attributes2?.Length > 0 + ? ((System.Reflection.AssemblyTitleAttribute) attributes2[0]).Title + : moduleName; - var appVersion = mainAssembly.GetName().Version; + Version appVersion = null; + if (!string.IsNullOrEmpty(AnonymousData.ApplicationVersion)) + Version.TryParse(AnonymousData.ApplicationVersion, out appVersion); + appVersion = appVersion ?? mainAssembly?.GetName().Version ?? new Version(0, 0, 0, 0); return new Application { ApplicationGUID = AnonymousData.ApplicationID?.ToString("D"), - AppName = appTitle, - CompanyName = appCompany, - Email = AnonymousData.ToEmail, - V1 = (ushort) appVersion.Major, - V2 = (ushort) appVersion.Minor, - V3 = (ushort) appVersion.Build, - V4 = (ushort) appVersion.Revision, + AppName = XmlText.ToValidXml(appTitle), + CompanyName = XmlText.ToValidXml(appCompany), + Email = XmlText.ToValidXml(AnonymousData.ToEmail), + V1 = (ushort) Math.Max(0, appVersion.Major), + V2 = (ushort) Math.Max(0, appVersion.Minor), + V3 = (ushort) Math.Max(0, appVersion.Build), + V4 = (ushort) Math.Max(0, appVersion.Revision), MainModule = moduleName }; } diff --git a/CrashReporter.NET/FailedReport.cs b/CrashReporter.NET/FailedReport.cs index 33bf398..83a976f 100644 --- a/CrashReporter.NET/FailedReport.cs +++ b/CrashReporter.NET/FailedReport.cs @@ -1,12 +1,15 @@ using System; +using System.Collections.Generic; using System.IO; +using System.Linq; +using System.Reflection; using System.Runtime.Serialization; using System.Xml; namespace CrashReporterDotNET { /// - /// Crash report persisted to disk when sending fails, so it can be retried later. + /// Snapshot of a crash report persisted to disk when sending fails, so exactly the same report can be retried later. /// Replaces the BinaryFormatter based format, which is not supported on .NET 9+. /// [DataContract(Name = "FailedReport", Namespace = Namespace)] @@ -14,6 +17,12 @@ internal sealed class FailedReport { internal const string Namespace = "https://github.com/ravibpatel/CrashReporter.NET/failed-report"; + /// + /// Version 1 (2.0.x) only contained and . + /// Version 2 (2.1+) also stores the report metadata, so retries do not recapture or replace it. + /// + internal const int CurrentFormatVersion = 2; + private static readonly DataContractSerializer Serializer = new DataContractSerializer(typeof(FailedReport)); [DataMember(Order = 1)] @@ -22,22 +31,85 @@ internal sealed class FailedReport [DataMember(Order = 2)] public byte[] ScreenShot { get; set; } + [DataMember(Order = 3, EmitDefaultValue = false)] + public int FormatVersion { get; set; } + + [DataMember(Order = 4, EmitDefaultValue = false)] + public string ApplicationTitle { get; set; } + + [DataMember(Order = 5, EmitDefaultValue = false)] + public string ApplicationVersion { get; set; } + + [DataMember(Order = 6, EmitDefaultValue = false)] + public string DeveloperMessage { get; set; } + + [DataMember(Order = 7, EmitDefaultValue = false)] + public string UserEmail { get; set; } + + [DataMember(Order = 8, EmitDefaultValue = false)] + public string UserMessage { get; set; } + + [DataMember(Order = 9, EmitDefaultValue = false)] + public bool? IncludeScreenshot { get; set; } + + [DataMember(Order = 10, EmitDefaultValue = false)] + public DateTime? CrashDateUtc { get; set; } + + /// + /// Entry assembly version at the time of the crash, reported to Doctor Dump. + /// + [DataMember(Order = 11, EmitDefaultValue = false)] + public string ApplicationAssemblyVersion { get; set; } + + /// + /// Writes the report atomically: the file only appears under once it has been written completely. + /// public void Save(string path) { - using (var writer = XmlWriter.Create(path, new XmlWriterSettings { Indent = true })) + AtomicFile.Write(path, stream => { - Serializer.WriteObject(writer, this); - } + // CheckCharacters = false writes characters that are invalid in XML (e.g. U+0001 in an exception message) + // as character references instead of throwing, and NewLineHandling.Entitize writes \r as so that + // XML line-break normalization does not turn \r\n into \n. Arbitrary text round-trips exactly. + var settings = new XmlWriterSettings + { + Indent = true, + CheckCharacters = false, + NewLineHandling = NewLineHandling.Entitize + }; + using (var writer = XmlWriter.Create(stream, settings)) + { + Serializer.WriteObject(writer, Sanitized()); + } + }); } public static FailedReport Load(string path) { using (var stream = File.OpenRead(path)) - using (var reader = XmlReader.Create(stream, new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null })) + using (var reader = XmlReader.Create(stream, new XmlReaderSettings + { + CheckCharacters = false, + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null + })) { return (FailedReport) Serializer.ReadObject(reader); } } + + private FailedReport Sanitized() + { + var copy = (FailedReport) MemberwiseClone(); + copy.Exception = Exception?.Sanitized(); + copy.ApplicationTitle = XmlText.ReplaceLoneSurrogates(ApplicationTitle); + copy.ApplicationVersion = XmlText.ReplaceLoneSurrogates(ApplicationVersion); + copy.ApplicationAssemblyVersion = XmlText.ReplaceLoneSurrogates(ApplicationAssemblyVersion); + copy.DeveloperMessage = XmlText.ReplaceLoneSurrogates(DeveloperMessage); + copy.UserEmail = XmlText.ReplaceLoneSurrogates(UserEmail); + copy.UserMessage = XmlText.ReplaceLoneSurrogates(UserMessage); + return copy; + } } [DataContract(Name = "Exception", Namespace = FailedReport.Namespace)] @@ -85,6 +157,20 @@ public Exception ToException() { return new ReplayedException(this); } + + internal ExceptionData Sanitized() + { + return new ExceptionData + { + TypeName = XmlText.ReplaceLoneSurrogates(TypeName), + Message = XmlText.ReplaceLoneSurrogates(Message), + Source = XmlText.ReplaceLoneSurrogates(Source), + StackTrace = XmlText.ReplaceLoneSurrogates(StackTrace), + HResult = HResult, + Text = XmlText.ReplaceLoneSurrogates(Text), + InnerException = InnerException?.Sanitized() + }; + } } /// @@ -122,4 +208,131 @@ public static string GetTypeName(Exception exception) : exception.GetType().ToString(); } } + + /// + /// Per-application queue of failed reports in the user's temporary directory. + /// + internal static class FailedReportQueue + { + private const string FilePrefix = "failed-report-"; + + private const string FileExtension = ".xml"; + + /// + /// Root directory of all queues. Can be overridden for tests. + /// + internal static string RootDirectory { get; set; } = Path.Combine(Path.GetTempPath(), "CrashReporterNET"); + + /// + /// Queue directory of the current application, so applications never retry each other's reports. + /// + public static DirectoryInfo GetDirectory(string applicationName = null) + { + return new DirectoryInfo(Path.Combine(RootDirectory, GetSafeName(applicationName ?? GetApplicationName()))); + } + + /// + /// Returns a new, unique file name. Reports saved in the same millisecond, or by several processes, never collide. + /// + public static string CreateFileName(DateTime utcNow) + { + return $"{FilePrefix}{utcNow:yyyyMMdd'T'HHmmssfff}-{Guid.NewGuid():N}{FileExtension}"; + } + + /// + /// Queued reports, oldest first. Files still being written (see ) are not included. + /// + public static IEnumerable GetFiles(DirectoryInfo directory) + { + if (!directory.Exists) + return Enumerable.Empty(); + + return directory.GetFiles(FilePrefix + "*" + FileExtension) + .Where(file => file.Extension.Equals(FileExtension, StringComparison.OrdinalIgnoreCase)) + .OrderBy(file => file.Name, StringComparer.Ordinal); + } + + internal const string LockFileName = ".retry.lock"; + + /// + /// Takes the exclusive retry lock of a queue, or returns null if another retry (in this or another process) holds it. + /// The lock is an open file handle without sharing, so the operating system releases it when the owning process + /// exits or crashes; a lock file left behind by an interrupted retry never blocks later retries. + /// + public static IDisposable TryLock(DirectoryInfo directory) + { + try + { + return new FileStream(Path.Combine(directory.FullName, LockFileName), FileMode.OpenOrCreate, + FileAccess.ReadWrite, FileShare.None, 1, FileOptions.None); + } + catch (IOException) when (directory.Exists) + { + // Sharing violation: the queue is locked by another retry. + return null; + } + } + + internal static string GetApplicationName() + { + var entryAssembly = Assembly.GetEntryAssembly(); + return entryAssembly?.GetName().Name ?? AppDomain.CurrentDomain.FriendlyName; + } + + internal static string GetSafeName(string name) + { + if (string.IsNullOrWhiteSpace(name)) + return "default"; + + var invalid = Path.GetInvalidFileNameChars(); + var chars = name.Trim().Select(c => invalid.Contains(c) ? '_' : c).ToArray(); + return new string(chars); + } + } + + /// + /// Writes a file via a temporary file and a rename, so readers never see partially written content. + /// + internal static class AtomicFile + { + internal const string TemporaryExtension = ".tmp"; + + public static void Write(string path, Action write) + { + var directory = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + + var temporaryPath = path + "." + Guid.NewGuid().ToString("N") + TemporaryExtension; + try + { + using (var stream = new FileStream(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + write(stream); + stream.Flush(true); + } + + File.Move(temporaryPath, path); + } + catch + { + TryDelete(temporaryPath); + throw; + } + } + + private static void TryDelete(string path) + { + try + { + File.Delete(path); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + } + } } diff --git a/CrashReporter.NET/HelperMethods.cs b/CrashReporter.NET/HelperMethods.cs index 2336e59..e83ae13 100644 --- a/CrashReporter.NET/HelperMethods.cs +++ b/CrashReporter.NET/HelperMethods.cs @@ -77,16 +77,51 @@ public static string GetWindowsVersion() osArchitecture = "32/64-bit (Undetermined)"; } - string productName = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName"); - string csdVersion = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CSDVersion"); - string currentBuild = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentBuildNumber"); + const string currentVersionKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion"; + string productName = HKLM_GetString(currentVersionKey, "ProductName"); + string csdVersion = HKLM_GetString(currentVersionKey, "CSDVersion"); + string currentBuild = HKLM_GetString(currentVersionKey, "CurrentBuildNumber"); + string updateBuildRevision = HKLM_GetString(currentVersionKey, "UBR"); + string installationType = HKLM_GetString(currentVersionKey, "InstallationType"); if (!string.IsNullOrEmpty(productName)) { + int.TryParse(currentBuild, out var build); + productName = GetWindowsProductName(productName, build, installationType); + var osBuild = string.IsNullOrEmpty(updateBuildRevision) ? currentBuild : $"{currentBuild}.{updateBuildRevision}"; return - $"{(productName.StartsWith("Microsoft") ? "" : "Microsoft ")}{productName}{(!string.IsNullOrEmpty(csdVersion) ? " " + csdVersion : String.Empty)} {osArchitecture} (OS Build {currentBuild})"; + $"{(productName.StartsWith("Microsoft") ? "" : "Microsoft ")}{productName}{(!string.IsNullOrEmpty(csdVersion) ? " " + csdVersion : String.Empty)} {osArchitecture} (OS Build {osBuild})"; } return String.Empty; } + + /// + /// First build number of Windows 11. Windows 11 still reports version 10.0 and its registry ProductName + /// still says "Windows 10", so the build number is the only reliable way to tell them apart. + /// + internal const int Windows11FirstBuild = 22000; + + /// + /// Corrects the registry ProductName of Windows 11 workstations, which Windows reports as "Windows 10 ...". + /// Server editions (e.g. Windows Server 2022, build 20348; Windows Server 2025, build 26100) are left untouched. + /// + internal static string GetWindowsProductName(string productName, int build, string installationType) + { + if (string.IsNullOrEmpty(productName)) + return productName; + + var isServer = string.IsNullOrEmpty(installationType) + ? productName.IndexOf("Server", StringComparison.OrdinalIgnoreCase) >= 0 + : installationType.StartsWith("Server", StringComparison.OrdinalIgnoreCase); + + const string windows10 = "Windows 10"; + var index = productName.IndexOf(windows10, StringComparison.Ordinal); + if (!isServer && build >= Windows11FirstBuild && index >= 0) + { + return productName.Substring(0, index) + "Windows 11" + productName.Substring(index + windows10.Length); + } + + return productName; + } } } \ No newline at end of file diff --git a/CrashReporter.NET/ReportCrash.cs b/CrashReporter.NET/ReportCrash.cs index bba63ec..8616d0f 100644 --- a/CrashReporter.NET/ReportCrash.cs +++ b/CrashReporter.NET/ReportCrash.cs @@ -12,6 +12,7 @@ using System.Reflection; using System.Runtime.Serialization; using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; using CrashReporterDotNET.DrDump; @@ -114,13 +115,37 @@ public class ReportCrash internal string ApplicationTitle; internal string ApplicationVersion; - + + /// + /// Version of the entry assembly, which Doctor Dump uses to identify the application version. + /// Can differ from , which is the ClickOnce version when deployed with ClickOnce. + /// + internal string ApplicationAssemblyVersion; + internal byte[] ScreenShotBinary; + internal DateTime? CrashDateUtc; + + /// + /// Maximum time to deliver one failed report when retrying (). + /// A report that is not delivered in time stays queued, and retrying stops until the next attempt. + /// + public TimeSpan DeliveryTimeout = TimeSpan.FromSeconds(100); + + /// + /// Creates the Doctor Dump service used for retries. Replaced by tests. + /// [NonSerialized] - private DrDumpService _doctorDumpService; + internal Func DrDumpServiceFactory; + + /// + /// Opens the Doctor Dump problem page. Replaced by tests. + /// + [NonSerialized] + internal Action ReportUrlOpener = url => Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); - private static readonly DirectoryInfo tempDirectory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), "CrashReporterNET")); + [NonSerialized] + private DrDumpService _doctorDumpService; /// /// Object use to send exception report to your Inbox. @@ -132,89 +157,283 @@ public ReportCrash(string toEmail) } /// /// Save the exception to the user's temporary directory for later retry. + /// Reports are kept per application in %TEMP%\CrashReporterNET\<application name>. /// public void SaveFailedReport() { - var fileName = $"failed-report-{DateTime.Now.ToString("yyyy-MM-ddTHH_mm_ss")}.xml"; - var fileInfo = new FileInfo(Path.Combine(tempDirectory.FullName, fileName)); - if (!tempDirectory.Exists) - tempDirectory.Create(); - new FailedReport { Exception = ExceptionData.FromException(Exception), ScreenShot = ScreenShotBinary } - .Save(fileInfo.FullName); + SaveFailedReport(null, null, IncludeScreenshot); } + + internal void SaveFailedReport(string userEmail, string userMessage, bool includeScreenshot) + { + if (ApplicationTitle == null || ApplicationVersion == null) + CaptureApplicationInfo(); + + var directory = FailedReportQueue.GetDirectory(); + var path = Path.Combine(directory.FullName, FailedReportQueue.CreateFileName(DateTime.UtcNow)); + new FailedReport + { + FormatVersion = FailedReport.CurrentFormatVersion, + Exception = ExceptionData.FromException(Exception), + ScreenShot = ScreenShotBinary, + ApplicationTitle = ApplicationTitle, + ApplicationVersion = ApplicationVersion, + ApplicationAssemblyVersion = ApplicationAssemblyVersion, + DeveloperMessage = DeveloperMessage, + UserEmail = userEmail, + UserMessage = userMessage, + IncludeScreenshot = includeScreenshot, + CrashDateUtc = CrashDateUtc ?? DateTime.UtcNow + }.Save(path); + } + /// /// Retries any previously failed report silently. If the first fails, it will stop. + /// This method blocks until all reports are sent; use to avoid blocking the UI thread. /// /// Whether any report has been sent. - public bool RetryFailedReports() => RetryFailedReports(out var failedReports, out var failedReportsSent); + public bool RetryFailedReports() => RetryFailedReports(out _, out _); + /// /// Retries any previously failed report silently. If the first fails, it will stop. + /// This method blocks until all reports are sent; use to avoid blocking the UI thread. /// /// The amount of failed reports found. /// The amount of failed reports sent. /// Whether any report has been sent. public bool RetryFailedReports(out int failedReports, out int failedReportsSent) { - failedReports = 0; - failedReportsSent = 0; - if (!tempDirectory.Exists) return false; + // RetryFailedReportsAsync runs on the thread pool, so blocking on it cannot deadlock a UI thread. + var result = RetryFailedReportsAsync(CancellationToken.None).GetAwaiter().GetResult(); + failedReports = result.FailedReports; + failedReportsSent = result.FailedReportsSent; + return result.AnyReportSent; + } + + /// + /// Retries any previously failed report of this application in the background, without blocking the calling thread. + /// Each report is sent exactly as it was saved (same exception, screenshot, messages and application version). + /// Retrying stops at the first report that fails to send, or is not delivered within ; + /// it stays queued for the next attempt. + /// Only one retry per application runs at a time, also across processes: if another retry is already in progress, + /// this call returns immediately without sending anything, so no report is ever sent twice. + /// + /// Cancels the retry. Reports that were not sent stay queued. + /// The number of failed reports found and sent. + /// The retry was cancelled. + public Task RetryFailedReportsAsync(CancellationToken cancellationToken = default) + { + // All work, including reading the queue, runs on the thread pool: nothing blocks or is posted back to the + // calling (UI) thread, so it is safe to call from e.g. Application.OnStartup without awaiting it. + return Task.Run(() => RetryFailedReportsCoreAsync(cancellationToken), cancellationToken); + } - List loadedFailedReports = new List(); - foreach (var fileInfo in tempDirectory.GetFiles("failed-report-*.xml")) + private async Task RetryFailedReportsCoreAsync(CancellationToken cancellationToken) + { + var directory = FailedReportQueue.GetDirectory(); + if (!directory.Exists) + return new FailedReportsRetryResult(0, 0); + + var queued = new List>(); + IDisposable queueLock = null; + try { - var loadedFailedReport = SelectFailedReport(fileInfo); - if (loadedFailedReport.Exception != null) + // Exclusive for the whole retry (across processes too), and released by the OS if the process dies. + queueLock = FailedReportQueue.TryLock(directory); + if (queueLock == null) + return new FailedReportsRetryResult(0, 0); + + foreach (var file in FailedReportQueue.GetFiles(directory)) { - loadedFailedReports.Add(loadedFailedReport); + var report = LoadFailedReport(file); + if (report != null) + queued.Add(new KeyValuePair(file, report)); } } + catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is System.Security.SecurityException) + { + // The queue can't be read right now (e.g. access denied); the reports stay queued for the next attempt. + Debug.WriteLine(e); + queueLock?.Dispose(); + return new FailedReportsRetryResult(0, 0); + } - failedReports = loadedFailedReports.Count; - - foreach (var failedReport in loadedFailedReports) + using (queueLock) { - try - { - ScreenShotBinary = failedReport.ScreenShot; - if (ScreenShotBinary != null) - File.WriteAllBytes(Path.Combine(tempDirectory.FullName, "screenshot.png"), ScreenShotBinary); - SendSilently(failedReport.Exception); - failedReportsSent++; - failedReport.FileInfo.Delete(); - } - catch (Exception) + var sent = 0; + foreach (var entry in queued) { - break; + cancellationToken.ThrowIfCancellationRequested(); + string reportUrl; + using (var delivery = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) + { + delivery.CancelAfter(DeliveryTimeout); + try + { + reportUrl = await SendFailedReportAsync(entry.Value, delivery.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception) + { + // Delivery failed or timed out: keep this and all later reports for the next attempt. + break; + } + } + + // The report is delivered: remove it before doing anything optional, so it is never sent twice. + sent++; + TryDelete(entry.Key); + TryOpenReportInBrowser(reportUrl); } + + return new FailedReportsRetryResult(queued.Count, sent); } - ScreenShotBinary = null; - return failedReportsSent > 0; } - private LoadFailedReportResult SelectFailedReport(FileInfo fileInfo) + private static FailedReport LoadFailedReport(FileInfo file) { - FailedReport failedReport; + FailedReport report; try { - failedReport = FailedReport.Load(fileInfo.FullName); + report = FailedReport.Load(file.FullName); } catch (Exception e) when (e is SerializationException || e is XmlException) { - failedReport = null; + report = null; + } + catch (IOException) + { + // Locked by another process of the same application; try again next time. + return null; } - if (failedReport?.Exception == null) + if (report?.Exception == null) { - fileInfo.Delete(); - return default(LoadFailedReportResult); + // Corrupt or empty report: it can never be sent. + TryDelete(file); + return null; } - return new LoadFailedReportResult + return report; + } + + private static void TryDelete(FileInfo file) + { + try + { + file.Delete(); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) { - Exception = failedReport.Exception.ToException(), - ScreenShot = failedReport.ScreenShot, - FileInfo = fileInfo + } + } + + /// + /// Sends a saved report as it was captured, without capturing a new screenshot or changing this instance. + /// + /// The Doctor Dump problem page, or null. + private async Task SendFailedReportAsync(FailedReport report, CancellationToken cancellationToken) + { + var exception = report.Exception.ToException(); + var isCurrentFormat = report.FormatVersion >= 2; + var developerMessage = isCurrentFormat ? report.DeveloperMessage : DeveloperMessage; + var includeScreenshot = report.IncludeScreenshot ?? IncludeScreenshot; + var screenshot = includeScreenshot && report.ScreenShot?.Length > 0 ? report.ScreenShot : null; + var from = !string.IsNullOrEmpty(report.UserEmail) ? report.UserEmail : FromEmail; + + if (AnalyzeWithDoctorDump) + { + // The saved application identity is reported, not the (possibly upgraded) running application. + var service = DrDumpServiceFactory?.Invoke() ?? new DrDumpService(WebProxy); + return await service.SendReportAsync(exception, ToEmail, + DoctorDumpSettings?.ApplicationID, developerMessage, from, report.UserMessage, screenshot, + report.CrashDateUtc, report.ApplicationTitle, report.ApplicationAssemblyVersion, + cancellationToken).ConfigureAwait(false); + } + + ValidateSmtpSettings(); + string applicationTitle = report.ApplicationTitle, applicationVersion = report.ApplicationVersion; + if (applicationTitle == null || applicationVersion == null) + { + GetApplicationInfo(out var currentTitle, out var currentVersion); + applicationTitle = applicationTitle ?? currentTitle; + applicationVersion = applicationVersion ?? currentVersion; + } + + var subject = string.IsNullOrEmpty(report.UserEmail) + ? $"{applicationTitle} {applicationVersion} Crash Report" + : $"{applicationTitle} {applicationVersion} Crash Report by {report.UserEmail}"; + var html = CreateHtmlReport(applicationTitle, applicationVersion, exception, developerMessage, + report.UserMessage, null); + + using (var smtpClient = CreateSmtpClient()) + using (var message = CreateMailMessage(subject, html, screenshot)) + { + await SendMailAsync(smtpClient, message, cancellationToken).ConfigureAwait(false); + } + + return null; + } + + /// + /// Sends the message and aborts the delivery when is cancelled, + /// including while connecting or waiting for the server. + /// + internal static async Task SendMailAsync(SmtpClient smtpClient, MailMessage message, CancellationToken cancellationToken) + { +#if NETFRAMEWORK + // SendMailAsync on .NET Framework has no cancellation: use SendAsync and SendAsyncCancel instead. + cancellationToken.ThrowIfCancellationRequested(); + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + SendCompletedEventHandler completed = null; + completed = (sender, e) => + { + smtpClient.SendCompleted -= completed; + if (e.Cancelled) + completion.TrySetCanceled(cancellationToken); + else if (e.Error != null) + completion.TrySetException(e.Error); + else + completion.TrySetResult(true); }; + smtpClient.SendCompleted += completed; + try + { + smtpClient.SendAsync(message, null); + } + catch + { + smtpClient.SendCompleted -= completed; + throw; + } + + // Registered after the send started: a cancellation that already happened runs the callback immediately. + // The task is cancelled right away, because SendAsyncCancel does not interrupt a send that is still connecting + // (e.g. waiting for the server greeting). The caller then disposes the SmtpClient, which aborts the pending + // operation and closes its connection. Both calls are ignored if the send completed in the meantime. + using (cancellationToken.Register(() => + { + completion.TrySetCanceled(cancellationToken); + try + { + smtpClient.SendAsyncCancel(); + } + catch (ObjectDisposedException) + { + } + })) + { + await completion.Task.ConfigureAwait(false); + } +#else + await smtpClient.SendMailAsync(message, cancellationToken).ConfigureAwait(false); +#endif } /// @@ -238,17 +457,8 @@ public void Send(Exception exception) private void Send(Exception exception, bool silent) { Exception = exception; - - var mainAssembly = Assembly.GetEntryAssembly(); - string appTitle = null; - var attributes = mainAssembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), true); - if (attributes.Length > 0) - { - appTitle = ((AssemblyTitleAttribute)attributes[0]).Title; - } - - ApplicationTitle = !string.IsNullOrEmpty(appTitle) ? appTitle : mainAssembly.GetName().Name; - ApplicationVersion = GetClickOnceVersion() ?? mainAssembly.GetName().Version.ToString(); + CrashDateUtc = DateTime.UtcNow; + CaptureApplicationInfo(); try { if (CaptureScreen) @@ -263,15 +473,7 @@ private void Send(Exception exception, bool silent) if (!AnalyzeWithDoctorDump) { - if (string.IsNullOrEmpty(FromEmail)) - { - throw new ArgumentNullException(@"FromEmail"); - } - - if (string.IsNullOrEmpty(SmtpHost)) - { - throw new ArgumentNullException("SmtpHost"); - } + ValidateSmtpSettings(); } if (!Application.MessageLoop) @@ -300,6 +502,74 @@ private void Send(Exception exception, bool silent) } } + private void ValidateSmtpSettings() + { + if (string.IsNullOrEmpty(FromEmail)) + { + throw new ArgumentNullException(@"FromEmail"); + } + + if (string.IsNullOrEmpty(SmtpHost)) + { + throw new ArgumentNullException("SmtpHost"); + } + } + + /// + /// Whether the crash dialog should send an anonymous report to Doctor Dump as soon as it opens. + /// Never when reports are delivered by SMTP only. + /// + internal bool SendAnonymousReportWhenDialogOpens => + AnalyzeWithDoctorDump && DoctorDumpSettings != null && DoctorDumpSettings.SendAnonymousReportSilently; + + private void CaptureApplicationInfo() + { + GetApplicationInfo(out ApplicationTitle, out ApplicationVersion); + ApplicationAssemblyVersion = Assembly.GetEntryAssembly()?.GetName().Version?.ToString(); + } + + private static void GetApplicationInfo(out string title, out string version) + { + var mainAssembly = Assembly.GetEntryAssembly(); + if (mainAssembly == null) + { + title = FailedReportQueue.GetApplicationName(); + version = GetClickOnceVersion() ?? string.Empty; + return; + } + + string appTitle = null; + var attributes = mainAssembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), true); + if (attributes.Length > 0) + { + appTitle = ((AssemblyTitleAttribute)attributes[0]).Title; + } + + title = !string.IsNullOrEmpty(appTitle) ? appTitle : mainAssembly.GetName().Name; + version = GetClickOnceVersion() ?? mainAssembly.GetName().Version.ToString(); + } + + private void OpenReportInBrowser(string reportUrl) + { + if (DoctorDumpSettings != null && DoctorDumpSettings.OpenReportInBrowser && !string.IsNullOrEmpty(reportUrl)) + ReportUrlOpener(reportUrl); + } + + /// + /// Opening the problem page is optional: failing to do so (e.g. no default browser) never affects delivery. + /// + private void TryOpenReportInBrowser(string reportUrl) + { + try + { + OpenReportInBrowser(reportUrl); + } + catch (Exception e) + { + Debug.WriteLine(e); + } + } + private static string GetClickOnceVersion() { #if NETFRAMEWORK @@ -352,23 +622,9 @@ private void SendEmail(bool includeScreenshot, SendCompletedEventHandler smtpCli subject = $"{ApplicationTitle} {ApplicationVersion} Crash Report"; } - var smtpClient = new SmtpClient - { - Host = SmtpHost, - Port = Port, - EnableSsl = EnableSSL, - DeliveryMethod = SmtpDeliveryMethod.Network, - UseDefaultCredentials = false, - Credentials = new NetworkCredential(UserName, Password) - }; - - var message = new MailMessage(new MailAddress(FromEmail), new MailAddress(ToEmail)) - {IsBodyHtml = true, Subject = subject, Body = CreateHtmlReport(userMessage)}; - - if (ScreenShotBinary?.Length > 0 && includeScreenshot) - { - message.Attachments.Add(new Attachment(new MemoryStream(ScreenShotBinary), "Screenshot.png", "image/png")); - } + var smtpClient = CreateSmtpClient(); + var message = CreateMailMessage(subject, CreateHtmlReport(userMessage), + includeScreenshot ? ScreenShotBinary : null); if (smtpClientSendCompleted != null) { @@ -388,11 +644,50 @@ private void SendEmail(bool includeScreenshot, SendCompletedEventHandler smtpCli } } + private SmtpClient CreateSmtpClient() + { + return new SmtpClient + { + Host = SmtpHost, + Port = Port, + EnableSsl = EnableSSL, + DeliveryMethod = SmtpDeliveryMethod.Network, + UseDefaultCredentials = false, + Credentials = new NetworkCredential(UserName, Password) + }; + } + + private MailMessage CreateMailMessage(string subject, string htmlReport, byte[] screenshot) + { + var message = new MailMessage(new MailAddress(FromEmail), new MailAddress(ToEmail)) + {IsBodyHtml = true, Subject = subject, Body = htmlReport}; + + if (screenshot?.Length > 0) + { + message.Attachments.Add(new Attachment(new MemoryStream(screenshot), "Screenshot.png", "image/png")); + } + + return message; + } + #endregion #region HTML Report Generator - internal string CreateHtmlReport(string userMessage) + /// + /// Creates the HTML report of the current crash. + /// + /// Comment entered by the user. + /// Embed the screenshot as an inline image, for reports saved to a file. + /// E-mails attach the screenshot instead, because many mail clients block inline data images. + internal string CreateHtmlReport(string userMessage, bool embedScreenshot = false) + { + return CreateHtmlReport(ApplicationTitle, ApplicationVersion, Exception, DeveloperMessage, userMessage, + embedScreenshot ? ScreenShotBinary : null); + } + + internal static string CreateHtmlReport(string applicationTitle, string applicationVersion, Exception exception, + string developerMessage, string userMessage, byte[] embeddedScreenshot) { string report = string.Format( @@ -454,11 +749,11 @@ internal string CreateHtmlReport(string userMessage)
{4}
- ", WebUtility.HtmlEncode(ApplicationTitle), - WebUtility.HtmlEncode(ApplicationVersion), + ", WebUtility.HtmlEncode(applicationTitle), + WebUtility.HtmlEncode(applicationVersion), WebUtility.HtmlEncode(HelperMethods.GetWindowsVersion()), WebUtility.HtmlEncode(Environment.Version.ToString()), - CreateReport(Exception)); + CreateReport(exception)); if (!String.IsNullOrEmpty(userMessage)) { report += $@"
@@ -472,7 +767,7 @@ internal string CreateHtmlReport(string userMessage) "; } - if (!String.IsNullOrEmpty(DeveloperMessage.Trim())) + if (!String.IsNullOrEmpty(developerMessage?.Trim())) { report += $@"
@@ -480,7 +775,20 @@ internal string CreateHtmlReport(string userMessage)

Developer Message

-

{WebUtility.HtmlEncode(DeveloperMessage.Trim())}

+

{WebUtility.HtmlEncode(developerMessage.Trim())}

+
+ "; + } + + if (embeddedScreenshot?.Length > 0) + { + report += $@"
+
+
+

Screenshot

+
+
+

"; } @@ -489,7 +797,7 @@ internal string CreateHtmlReport(string userMessage) return report; } - private string CreateReport(Exception exception) + private static string CreateReport(Exception exception) { string report = $@"
@@ -522,7 +830,7 @@ private string CreateReport(Exception exception)

{ - WebUtility.HtmlEncode(exception.StackTrace ?? "No stack trace").Replace("\r\n", "
") + WebUtility.HtmlEncode(exception.StackTrace ?? "No stack trace").Replace("\r\n", "\n").Replace("\n", "
") }

"; @@ -593,21 +901,38 @@ private void SendFullReport(bool includeScreenshot, { _doctorDumpService = new DrDumpService(WebProxy); var reportUrl = _doctorDumpService.SendReportSilently(Exception, ToEmail, DoctorDumpSettings?.ApplicationID, DeveloperMessage, from, userMessage, screenshot); - if (DoctorDumpSettings != null && DoctorDumpSettings.OpenReportInBrowser) - { - if (!string.IsNullOrEmpty(reportUrl)) - Process.Start(new ProcessStartInfo(reportUrl) { UseShellExecute = true }); - } + OpenReportInBrowser(reportUrl); } } #endregion - private struct LoadFailedReportResult + } + + /// + /// Result of . + /// + public sealed class FailedReportsRetryResult + { + internal FailedReportsRetryResult(int failedReports, int failedReportsSent) { - public Exception Exception; - public byte[] ScreenShot; - public FileInfo FileInfo; + FailedReports = failedReports; + FailedReportsSent = failedReportsSent; } + + /// + /// The amount of failed reports found. + /// + public int FailedReports { get; } + + /// + /// The amount of failed reports sent (and removed from the queue). + /// + public int FailedReportsSent { get; } + + /// + /// Whether any report has been sent. + /// + public bool AnyReportSent => FailedReportsSent > 0; } /// diff --git a/CrashReporter.NET/XmlText.cs b/CrashReporter.NET/XmlText.cs new file mode 100644 index 0000000..341f001 --- /dev/null +++ b/CrashReporter.NET/XmlText.cs @@ -0,0 +1,73 @@ +using System.Text; +using System.Xml; + +namespace CrashReporterDotNET +{ + /// + /// Helpers for putting arbitrary text (exception messages, user input) into XML. + /// + internal static class XmlText + { + private const char ReplacementCharacter = '�'; + + /// + /// Replaces unpaired surrogates, which cannot be encoded at all, with U+FFFD. + /// Other characters that are invalid in XML (e.g. U+0001) are kept; the failed report writer escapes them + /// as character references, so they round-trip exactly. + /// + public static string ReplaceLoneSurrogates(string text) + { + return Replace(text, false); + } + + /// + /// Replaces every character that is not allowed in an XML 1.0 document (control characters, U+FFFE, U+FFFF + /// and unpaired surrogates) with U+FFFD, so the text can be sent to services that validate XML strictly. + /// + public static string ToValidXml(string text) + { + return Replace(text, true); + } + + private static string Replace(string text, bool replaceInvalidXmlCharacters) + { + if (string.IsNullOrEmpty(text)) + return text; + + StringBuilder builder = null; + for (var i = 0; i < text.Length; i++) + { + var c = text[i]; + bool valid; + if (char.IsHighSurrogate(c)) + { + valid = i + 1 < text.Length && char.IsLowSurrogate(text[i + 1]); + if (valid) + { + builder?.Append(c).Append(text[i + 1]); + i++; + continue; + } + } + else if (char.IsLowSurrogate(c)) + { + valid = false; + } + else + { + valid = !replaceInvalidXmlCharacters || XmlConvert.IsXmlChar(c); + } + + if (!valid && builder == null) + { + builder = new StringBuilder(text.Length); + builder.Append(text, 0, i); + } + + builder?.Append(valid ? c : ReplacementCharacter); + } + + return builder?.ToString() ?? text; + } + } +} diff --git a/CrashReporterWPFTest/App.xaml.cs b/CrashReporterWPFTest/App.xaml.cs index 34ac298..4a5c55b 100644 --- a/CrashReporterWPFTest/App.xaml.cs +++ b/CrashReporterWPFTest/App.xaml.cs @@ -24,7 +24,8 @@ protected override void OnStartup(StartupEventArgs e) DeveloperMessage = "Retry attempt", Silent = true }; - _reportCrash.RetryFailedReports(); + // Retry reports that could not be sent earlier, in the background so startup is not blocked. + _ = _reportCrash.RetryFailedReportsAsync(); } private void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs) diff --git a/README.md b/README.md index 8f7f30f..7b1d182 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,20 @@ Send crash reports of your desktop application developed using .NET 10 or .NET F | `net10.0-windows` | Windows Forms and WPF applications on .NET 10. | | `net48` | Windows Forms and WPF applications on .NET Framework 4.8. | +### What's new in 2.1 + +* `RetryFailedReportsAsync(CancellationToken)` retries failed reports without blocking the UI thread. The synchronous `RetryFailedReports()` still works, but blocks until all reports are sent. +* Failed reports are resent exactly as they were captured, including the original screenshot, application version, developer message and what the user typed. Retrying no longer takes a new screenshot. +* Failed reports are queued per application in `%TEMP%\CrashReporterNET\\`, with unique file names, and are written atomically. Exception messages containing control characters no longer prevent a report from being saved. +* E-mail reports, saved HTML reports and the crash dialog show Windows 11 correctly: Windows 11 still reports version 10.0 and its registry product name still says "Windows 10", so the name is now derived from the build number (22000 or later) on workstation editions. Doctor Dump receives the unchanged numeric version (e.g. `10.0.22631`); how its dashboard labels that version is up to the service. +* Only one retry per application runs at a time, also across processes, so a report is never sent twice by overlapping retries. Each retried report must be delivered within `DeliveryTimeout` (100 seconds by default), and cancelling `RetryFailedReportsAsync` also interrupts an SMTP delivery in progress on .NET Framework. +* Doctor Dump retries report the application title and version that crashed, not the version running when the report is retried. +* The *Save report* button embeds the screenshot in the saved HTML file when *Include screenshot* is checked. +* When `AnalyzeWithDoctorDump` is `false`, the crash dialog no longer sends an anonymous report to Doctor Dump. +* Doctor Dump responses are validated: HTTP errors, SOAP faults and empty responses are reported as errors instead of being treated as success. +* `CrashReporter.NET.dll` is always strong-name signed with the key committed in this repository (public key token `dee93ec6287efbf0`). This identity differs from the upstream `CrashReporter.NET.Official` package, which was signed with RBSoft's private key. Versions 2.0.0 and 2.0.1 of `d3sync.CrashReporter.NET` were not signed; strong-named applications need 2.1.0 or later. +* Reports saved by 2.0.x in `%TEMP%\CrashReporterNET\` (not in an application folder) are not retried. + ### Upgrading from 1.x Version 2.0 is a breaking release: @@ -128,7 +142,8 @@ public partial class App : Application { Silent = true }; - _reportCrash.RetryFailedReports(); + // Retry reports that could not be sent earlier, in the background so startup is not blocked. + _ = _reportCrash.RetryFailedReportsAsync(); } private void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)