| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Runtime.ConstrainedExecution; |
| | | 5 | | |
| | | 6 | | namespace System.Net.Security |
| | | 7 | | { |
| | | 8 | | // |
| | | 9 | | // This is a class holding a Credential handle reference, used for static handles cache |
| | | 10 | | // |
| | | 11 | | internal sealed class SafeCredentialReference : CriticalFinalizerObject, IDisposable |
| | | 12 | | { |
| | | 13 | | // |
| | | 14 | | // Static cache will return the target handle if found the reference in the table. |
| | | 15 | | // |
| | 0 | 16 | | internal SafeFreeCredentials? Target { get; private set; } |
| | | 17 | | |
| | | 18 | | internal static SafeCredentialReference? CreateReference(SafeFreeCredentials target) |
| | 0 | 19 | | { |
| | 0 | 20 | | if (target.IsInvalid || target.IsClosed) |
| | 0 | 21 | | { |
| | 0 | 22 | | return null; |
| | | 23 | | } |
| | | 24 | | |
| | | 25 | | try |
| | 0 | 26 | | { |
| | 0 | 27 | | return new SafeCredentialReference(target); |
| | | 28 | | } |
| | 0 | 29 | | catch (ObjectDisposedException) |
| | 0 | 30 | | { |
| | | 31 | | // Another owner may release the last reference after the checks above. |
| | 0 | 32 | | return null; |
| | | 33 | | } |
| | 0 | 34 | | } |
| | | 35 | | |
| | 0 | 36 | | private SafeCredentialReference(SafeFreeCredentials target) |
| | 0 | 37 | | { |
| | | 38 | | // Bumps up the refcount on Target to signify that target handle is statically cached so |
| | | 39 | | // its dispose should be postponed |
| | 0 | 40 | | bool ignore = false; |
| | 0 | 41 | | target.DangerousAddRef(ref ignore); |
| | 0 | 42 | | Target = target; |
| | 0 | 43 | | } |
| | | 44 | | |
| | | 45 | | public void Dispose() |
| | 0 | 46 | | { |
| | 0 | 47 | | DisposeInternal(); |
| | 0 | 48 | | GC.SuppressFinalize(this); |
| | 0 | 49 | | } |
| | | 50 | | |
| | | 51 | | private void DisposeInternal() |
| | 0 | 52 | | { |
| | 0 | 53 | | SafeFreeCredentials? target = Target; |
| | 0 | 54 | | target?.DangerousRelease(); |
| | 0 | 55 | | Target = null; |
| | 0 | 56 | | } |
| | | 57 | | |
| | | 58 | | ~SafeCredentialReference() |
| | 0 | 59 | | { |
| | 0 | 60 | | DisposeInternal(); |
| | 0 | 61 | | } |
| | | 62 | | } |
| | | 63 | | |
| | | 64 | | } |
| | | 65 | | |