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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 56 additions & 7 deletions src/Foundation/NSUrlSessionHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,7 @@ internal void EnsureModifiability ()
static Exception createExceptionForNSError (NSError error)
{
var innerException = new NSErrorException (error);
var requestError = HttpRequestError.Unknown;

// errors that exists in both share the same error code, so we can use a single switch/case
// this also ease watchOS integration as if does not expose CFNetwork but (I would not be
Expand All @@ -392,10 +393,28 @@ static Exception createExceptionForNSError (NSError error)
case (NSUrlError) NSNetServicesStatus.CancelledError:
// No more processing is required so just return.
return new OperationCanceledException (error.LocalizedDescription, innerException);
case NSUrlError.CannotFindHost:
case NSUrlError.DNSLookupFailed:
requestError = HttpRequestError.NameResolutionError;
break;
case NSUrlError.CannotConnectToHost:
case NSUrlError.NetworkConnectionLost:
case NSUrlError.NotConnectedToInternet:
requestError = HttpRequestError.ConnectionError;
break;
case NSUrlError.SecureConnectionFailed:
case NSUrlError.ServerCertificateHasBadDate:
case NSUrlError.ServerCertificateUntrusted:
case NSUrlError.ServerCertificateHasUnknownRoot:
case NSUrlError.ServerCertificateNotYetValid:
case NSUrlError.ClientCertificateRejected:
case NSUrlError.ClientCertificateRequired:
requestError = HttpRequestError.SecureConnectionError;
break;
}
}

return new HttpRequestException (error.LocalizedDescription, innerException);
return new HttpRequestException (requestError, error.LocalizedDescription, innerException);
}

string GetHeaderSeparator (string name)
Expand Down Expand Up @@ -972,6 +991,17 @@ void UpdateManagedCookieContainer (Uri absoluteUri, NSHttpCookie [] cookies)
}
}

void ClearClientCertificateException (InflightData inflight)
{
lock (inflight.Lock) {
if (!inflight.IsClientCertificateException)
return;

inflight.Exception = null;
inflight.IsClientCertificateException = false;
}
}

[Preserve (Conditional = true)]
public override void DidReceiveResponse (NSUrlSession session, NSUrlSessionDataTask dataTask, NSUrlResponse response, Action<NSUrlSessionResponseDisposition> completionHandler)
{
Expand All @@ -992,6 +1022,8 @@ void DidReceiveResponseImpl (NSUrlSession session, NSUrlSessionDataTask dataTask
return;
}

ClearClientCertificateException (inflight);

try {
var urlResponse = (NSHttpUrlResponse) response;
var status = (int) urlResponse.StatusCode;
Expand Down Expand Up @@ -1120,7 +1152,19 @@ public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTas
inflight.CancellationTokenSource.Cancel ();
inflight.Errored = true;

var exc = inflight.Exception ?? createExceptionForNSError (error ?? serverError!); // client errors wont happen if we get server errors
var nativeException = createExceptionForNSError (error ?? serverError!);
var nativeExceptionIsSecureConnectionError = nativeException is HttpRequestException requestException &&
requestException.HttpRequestError == HttpRequestError.SecureConnectionError;
Exception? exception;
bool isClientCertificateException;
lock (inflight.Lock) {
exception = inflight.Exception;
isClientCertificateException = inflight.IsClientCertificateException;
}
if (isClientCertificateException && !nativeExceptionIsSecureConnectionError)
exception = null;
Comment thread
rolfbjarne marked this conversation as resolved.
Resolved

var exc = exception ?? nativeException; // client errors wont happen if we get server errors
inflight.CompletionSource.TrySetException (exc);
inflight.Stream.TrySetException (exc);
} else {
Expand Down Expand Up @@ -1188,14 +1232,16 @@ void WillCacheResponseImpl (NSUrlSession session, NSUrlSessionDataTask dataTask,
[Preserve (Conditional = true)]
public override void WillPerformHttpRedirection (NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action<NSUrlRequest?> completionHandler)
{
if (!sessionHandler.AllowAutoRedirect) {
var inflight = GetInflightData (task);

if (inflight is null) {
completionHandler (null);
return;
}

var inflight = GetInflightData (task);
ClearClientCertificateException (inflight);

if (inflight is null) {
if (!sessionHandler.AllowAutoRedirect) {
completionHandler (null);
return;
}
Expand Down Expand Up @@ -1257,7 +1303,8 @@ void DidReceiveChallengeImpl (NSUrlSession session, NSUrlSessionTask task, NSUrl
// user callback rejected the certificate, we want to set the exception, else the user will
// see as if the request was cancelled.
lock (inflight.Lock) {
inflight.Exception = new HttpRequestException ("An error occurred while sending the request.", new WebException ("Error: TrustFailure"));
inflight.IsClientCertificateException = false;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm holding off on another push to avoid a review/fix cycle. This is another test for an earlier review fix, so I need human input on whether to add it to this PR.

Note

Copilot-generated reply.

Auto-replied by the GitHub Copilot app

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't implement this, it seems unrelated to the purpose of this PR.

inflight.Exception = new HttpRequestException (HttpRequestError.SecureConnectionError, "An error occurred while sending the request.", new WebException ("Error: TrustFailure"));
}
completionHandler (NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null!);
}
Expand All @@ -1277,7 +1324,8 @@ void DidReceiveChallengeImpl (NSUrlSession session, NSUrlSessionTask task, NSUrl
// that allows the developer to identify this, ask the user for a certificate, add it to the ClientCertificates collection
// and then re-try the request.
lock (inflight.Lock) {
inflight.Exception = new HttpRequestException ("An error occurred while sending the request.",
inflight.IsClientCertificateException = true;
inflight.Exception = new HttpRequestException (HttpRequestError.SecureConnectionError, "An error occurred while sending the request.",
new WebException ("Error: Certificate Required",
new AuthenticationException ("Error: Certificate Required"),
WebExceptionStatus.SecureChannelFailure, null));
Expand Down Expand Up @@ -1486,6 +1534,7 @@ class InflightData {
public HttpResponseMessage? Response { get; set; }

public Exception? Exception { get; set; }
public bool IsClientCertificateException { get; set; }
public bool ResponseSent { get; set; }
public bool Errored { get; set; }
public bool Disposed { get; set; }
Expand Down
16 changes: 11 additions & 5 deletions tests/monotouch-test/System.Net.Http/MessageHandlers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -831,11 +831,17 @@ public void TestNSUrlSessionHandlerDetectMissingClientCertificate ()
await client.GetAsync ($"https://localhost:{port}/");
}, out var ex);
Assert.That (done, Is.True, "Request to localhost timed out.");
Assert.That (ex, Is.Not.Null, "Exception was expected.");
Assert.That (ex, Is.InstanceOf (typeof (HttpRequestException)), "Exception");
Assert.That (ex!.InnerException, Is.InstanceOf (typeof (WebException)), "InnerException Type");
Assert.That (((WebException) ex.InnerException!).Status, Is.EqualTo (WebExceptionStatus.SecureChannelFailure), "InnerException Status");
Assert.That (ex.InnerException.InnerException, Is.InstanceOf (typeof (AuthenticationException)), "InnerException.InnerException Type");
var requestException = ex as HttpRequestException;
Assert.That (requestException, Is.Not.Null, "Exception was expected.");
if (requestException is null)
return;
Assert.That (requestException.HttpRequestError, Is.EqualTo (HttpRequestError.SecureConnectionError), "HttpRequestError");
var webException = requestException.InnerException as WebException;
Assert.That (webException, Is.Not.Null, "InnerException Type");
if (webException is null)
return;
Assert.That (webException.Status, Is.EqualTo (WebExceptionStatus.SecureChannelFailure), "InnerException Status");
Assert.That (webException.InnerException, Is.InstanceOf (typeof (AuthenticationException)), "InnerException.InnerException Type");
} finally {
listener?.Cancel ();
listener?.Dispose ();
Expand Down
Loading
Loading