1 #if SECURITY_DEP && MONO_FEATURE_APPLETLS
6 // Martin Baulig <martin.baulig@xamarin.com>
8 // Copyright (c) 2015 Xamarin, Inc.
11 #if MONO_SECURITY_ALIAS
12 extern alias MonoSecurity;
19 using System.Globalization;
20 using System.Collections;
21 using System.Collections.Generic;
22 using System.Threading;
23 using System.Threading.Tasks;
24 using System.Runtime.InteropServices;
25 using SSA = System.Security.Authentication;
26 using System.Security.Cryptography.X509Certificates;
28 #if MONO_SECURITY_ALIAS
29 using MonoSecurity::Mono.Security.Interface;
31 using Mono.Security.Interface;
35 using Mono.Net.Security;
40 namespace Mono.AppleTls
42 class AppleTlsContext : MobileTlsContext
44 public const string SecurityLibrary = "/System/Library/Frameworks/Security.framework/Security";
50 SslWriteFunc writeFunc;
52 SecIdentity serverIdentity;
53 SecIdentity clientIdentity;
55 X509Certificate remoteCertificate;
56 X509Certificate localClientCertificate;
57 MonoTlsConnectionInfo connectionInfo;
60 bool handshakeFinished;
68 Exception lastException;
70 public AppleTlsContext (
71 MobileAuthenticatedStream parent, bool serverMode, string targetHost,
72 SSA.SslProtocols enabledProtocols, X509Certificate serverCertificate,
73 X509CertificateCollection clientCertificates, bool askForClientCert)
74 : base (parent, serverMode, targetHost, enabledProtocols,
75 serverCertificate, clientCertificates, askForClientCert)
77 handle = GCHandle.Alloc (this);
78 connectionId = GCHandle.ToIntPtr (handle);
79 readFunc = NativeReadCallback;
80 writeFunc = NativeWriteCallback;
83 if (serverCertificate == null)
84 throw new ArgumentNullException ("serverCertificate");
88 public IntPtr Handle {
91 throw new ObjectDisposedException ("AppleTlsContext");
96 public override bool HasContext {
97 get { return !disposed && context != IntPtr.Zero; }
100 [System.Diagnostics.Conditional ("APPLE_TLS_DEBUG")]
101 protected new void Debug (string message, params object[] args)
103 Console.Error.WriteLine ("MobileTlsStream({0}): {1}", Parent.ID, string.Format (message, args));
106 void CheckStatusAndThrow (SslStatus status, params SslStatus[] acceptable)
108 var last = Interlocked.Exchange (ref lastException, null);
112 if (status == SslStatus.Success || Array.IndexOf (acceptable, status) > -1)
116 case SslStatus.ClosedAbort:
117 throw new IOException ("Connection closed.");
119 case SslStatus.BadCert:
120 throw new TlsException (AlertDescription.BadCertificate);
122 case SslStatus.UnknownRootCert:
123 case SslStatus.NoRootCert:
124 case SslStatus.XCertChainInvalid:
125 throw new TlsException (AlertDescription.CertificateUnknown, status.ToString ());
127 case SslStatus.CertExpired:
128 case SslStatus.CertNotYetValid:
129 throw new TlsException (AlertDescription.CertificateExpired);
131 case SslStatus.Protocol:
132 throw new TlsException (AlertDescription.ProtocolVersion);
135 throw new TlsException (AlertDescription.InternalError, "Unknown Secure Transport error `{0}'.", status);
141 public override bool IsAuthenticated {
142 get { return isAuthenticated; }
145 public override void StartHandshake ()
147 Debug ("StartHandshake: {0}", IsServer);
149 if (Interlocked.CompareExchange (ref handshakeStarted, 1, 1) != 0)
150 throw new InvalidOperationException ();
152 InitializeConnection ();
154 SetSessionOption (SslSessionOption.BreakOnCertRequested, true);
155 SetSessionOption (SslSessionOption.BreakOnClientAuth, true);
156 SetSessionOption (SslSessionOption.BreakOnServerAuth, true);
159 SecCertificate[] intermediateCerts;
160 serverIdentity = AppleCertificateHelper.GetIdentity (LocalServerCertificate, out intermediateCerts);
161 if (serverIdentity == null)
162 throw new SSA.AuthenticationException ("Unable to get server certificate from keychain.");
164 SetCertificate (serverIdentity, intermediateCerts);
165 for (int i = 0; i < intermediateCerts.Length; i++)
166 intermediateCerts [i].Dispose ();
170 public override void FinishHandshake ()
172 InitializeSession ();
174 isAuthenticated = true;
177 public override void Flush ()
181 public override bool ProcessHandshake ()
183 if (handshakeFinished)
184 throw new NotSupportedException ("Handshake already finished.");
187 lastException = null;
188 var status = SSLHandshake (Handle);
189 Debug ("Handshake: {0} - {0:x}", status);
191 CheckStatusAndThrow (status, SslStatus.WouldBlock, SslStatus.PeerAuthCompleted, SslStatus.PeerClientCertRequested);
193 if (status == SslStatus.PeerAuthCompleted) {
195 } else if (status == SslStatus.PeerClientCertRequested) {
197 if (remoteCertificate == null)
198 throw new TlsException (AlertDescription.InternalError, "Cannot request client certificate before receiving one from the server.");
199 localClientCertificate = SelectClientCertificate (remoteCertificate, null);
200 if (localClientCertificate == null)
202 clientIdentity = AppleCertificateHelper.GetIdentity (localClientCertificate);
203 if (clientIdentity == null)
204 throw new TlsException (AlertDescription.CertificateUnknown);
205 SetCertificate (clientIdentity, new SecCertificate [0]);
206 } else if (status == SslStatus.WouldBlock) {
208 } else if (status == SslStatus.Success) {
209 handshakeFinished = true;
215 void RequirePeerTrust ()
217 if (!havePeerTrust) {
219 havePeerTrust = true;
223 void EvaluateTrust ()
225 InitializeSession ();
228 * We're using .NET's SslStream semantics here.
230 * A server must always provide a valid certificate.
232 * However, in server mode, "ask for client certificate" means that
233 * we ask the client to provide a certificate, then invoke the client
234 * certificate validator - passing 'null' if the client didn't provide
239 var trust = GetPeerTrust (!IsServer);
240 X509CertificateCollection certificates;
242 if (trust == null || trust.Count == 0) {
243 remoteCertificate = null;
245 throw new TlsException (AlertDescription.CertificateUnknown);
249 Debug ("WARNING: Got multiple certificates in SecTrust!");
251 certificates = new X509CertificateCollection ();
252 for (int i = 0; i < trust.Count; i++)
253 certificates.Add (trust [(IntPtr)i].ToX509Certificate ());
255 remoteCertificate = certificates [0];
256 Debug ("Got peer trust: {0}", remoteCertificate);
261 ok = ValidateCertificate (certificates);
262 } catch (Exception ex) {
263 Debug ("Certificate validation failed: {0}", ex);
264 throw new TlsException (AlertDescription.CertificateUnknown, "Certificate validation threw exception.");
268 throw new TlsException (AlertDescription.CertificateUnknown);
271 void InitializeConnection ()
273 context = SSLCreateContext (IntPtr.Zero, IsServer ? SslProtocolSide.Server : SslProtocolSide.Client, SslConnectionType.Stream);
275 var result = SSLSetIOFuncs (Handle, readFunc, writeFunc);
276 CheckStatusAndThrow (result);
278 result = SSLSetConnection (Handle, connectionId);
279 CheckStatusAndThrow (result);
281 if ((EnabledProtocols & SSA.SslProtocols.Tls) != 0)
282 MinProtocol = SslProtocol.Tls_1_0;
283 else if ((EnabledProtocols & SSA.SslProtocols.Tls11) != 0)
284 MinProtocol = SslProtocol.Tls_1_1;
286 MinProtocol = SslProtocol.Tls_1_2;
288 if ((EnabledProtocols & SSA.SslProtocols.Tls12) != 0)
289 MaxProtocol = SslProtocol.Tls_1_2;
290 else if ((EnabledProtocols & SSA.SslProtocols.Tls11) != 0)
291 MaxProtocol = SslProtocol.Tls_1_1;
293 MaxProtocol = SslProtocol.Tls_1_0;
296 foreach (var c in GetSupportedCiphers ())
297 Debug (" {0} SslCipherSuite.{1} {2:x} {3}", IsServer ? "Server" : "Client", c, (int)c, (CipherSuiteCode)c);
300 if (Settings != null && Settings.EnabledCiphers != null) {
301 SslCipherSuite [] ciphers = new SslCipherSuite [Settings.EnabledCiphers.Length];
302 for (int i = 0 ; i < Settings.EnabledCiphers.Length; ++i)
303 ciphers [i] = (SslCipherSuite)Settings.EnabledCiphers[i];
304 SetEnabledCiphers (ciphers);
307 if (AskForClientCertificate)
308 SetClientSideAuthenticate (SslAuthenticate.Try);
311 if (!IsServer && !string.IsNullOrEmpty (TargetHost) &&
312 !IPAddress.TryParse (TargetHost, out address)) {
313 PeerDomainName = ServerName;
317 void InitializeSession ()
319 if (connectionInfo != null)
322 var cipher = NegotiatedCipher;
323 var protocol = GetNegotiatedProtocolVersion ();
324 Debug ("GET CONNECTION INFO: {0:x}:{0} {1:x}:{1} {2}", cipher, protocol, (TlsProtocolCode)protocol);
326 connectionInfo = new MonoTlsConnectionInfo {
327 CipherSuiteCode = (CipherSuiteCode)cipher,
328 ProtocolVersion = GetProtocol (protocol),
329 PeerDomainName = PeerDomainName
333 static TlsProtocols GetProtocol (SslProtocol protocol)
336 case SslProtocol.Tls_1_0:
337 return TlsProtocols.Tls10;
338 case SslProtocol.Tls_1_1:
339 return TlsProtocols.Tls11;
340 case SslProtocol.Tls_1_2:
341 return TlsProtocols.Tls12;
343 throw new NotSupportedException ();
347 public override MonoTlsConnectionInfo ConnectionInfo {
348 get { return connectionInfo; }
351 internal override bool IsRemoteCertificateAvailable {
352 get { return remoteCertificate != null; }
355 internal override X509Certificate LocalClientCertificate {
356 get { return localClientCertificate; }
359 public override X509Certificate RemoteCertificate {
360 get { return remoteCertificate; }
363 public override TlsProtocols NegotiatedProtocol {
364 get { return connectionInfo.ProtocolVersion; }
369 #region General P/Invokes
371 [DllImport (SecurityLibrary )]
372 extern static /* OSStatus */ SslStatus SSLGetProtocolVersionMax (/* SSLContextRef */ IntPtr context, out SslProtocol maxVersion);
374 [DllImport (SecurityLibrary)]
375 extern static /* OSStatus */ SslStatus SSLSetProtocolVersionMax (/* SSLContextRef */ IntPtr context, SslProtocol maxVersion);
377 public SslProtocol MaxProtocol {
380 var result = SSLGetProtocolVersionMax (Handle, out value);
381 CheckStatusAndThrow (result);
385 var result = SSLSetProtocolVersionMax (Handle, value);
386 CheckStatusAndThrow (result);
390 [DllImport (SecurityLibrary)]
391 extern static /* OSStatus */ SslStatus SSLGetProtocolVersionMin (/* SSLContextRef */ IntPtr context, out SslProtocol minVersion);
393 [DllImport (SecurityLibrary)]
394 extern static /* OSStatus */ SslStatus SSLSetProtocolVersionMin (/* SSLContextRef */ IntPtr context, SslProtocol minVersion);
396 public SslProtocol MinProtocol {
399 var result = SSLGetProtocolVersionMin (Handle, out value);
400 CheckStatusAndThrow (result);
404 var result = SSLSetProtocolVersionMin (Handle, value);
405 CheckStatusAndThrow (result);
409 [DllImport (SecurityLibrary)]
410 extern static /* OSStatus */ SslStatus SSLGetNegotiatedProtocolVersion (/* SSLContextRef */ IntPtr context, out SslProtocol protocol);
412 public SslProtocol GetNegotiatedProtocolVersion ()
415 var result = SSLGetNegotiatedProtocolVersion (Handle, out value);
416 CheckStatusAndThrow (result);
420 [DllImport (SecurityLibrary)]
421 extern static /* OSStatus */ SslStatus SSLGetSessionOption (/* SSLContextRef */ IntPtr context, SslSessionOption option, out bool value);
423 public bool GetSessionOption (SslSessionOption option)
426 var result = SSLGetSessionOption (Handle, option, out value);
427 CheckStatusAndThrow (result);
431 [DllImport (SecurityLibrary)]
432 extern static /* OSStatus */ SslStatus SSLSetSessionOption (/* SSLContextRef */ IntPtr context, SslSessionOption option, bool value);
434 public void SetSessionOption (SslSessionOption option, bool value)
436 var result = SSLSetSessionOption (Handle, option, value);
437 CheckStatusAndThrow (result);
440 [DllImport (SecurityLibrary)]
441 extern static /* OSStatus */ SslStatus SSLSetClientSideAuthenticate (/* SSLContextRef */ IntPtr context, SslAuthenticate auth);
443 public void SetClientSideAuthenticate (SslAuthenticate auth)
445 var result = SSLSetClientSideAuthenticate (Handle, auth);
446 CheckStatusAndThrow (result);
449 [DllImport (SecurityLibrary)]
450 extern static /* OSStatus */ SslStatus SSLHandshake (/* SSLContextRef */ IntPtr context);
452 [DllImport (SecurityLibrary)]
453 extern static /* OSStatus */ SslStatus SSLGetSessionState (/* SSLContextRef */ IntPtr context, ref SslSessionState state);
455 public SslSessionState SessionState {
457 var value = SslSessionState.Invalid;
458 var result = SSLGetSessionState (Handle, ref value);
459 CheckStatusAndThrow (result);
464 [DllImport (SecurityLibrary)]
465 extern unsafe static /* OSStatus */ SslStatus SSLGetPeerID (/* SSLContextRef */ IntPtr context, /* const void** */ out IntPtr peerID, /* size_t* */ out IntPtr peerIDLen);
467 [DllImport (SecurityLibrary)]
468 extern unsafe static /* OSStatus */ SslStatus SSLSetPeerID (/* SSLContextRef */ IntPtr context, /* const void* */ byte* peerID, /* size_t */ IntPtr peerIDLen);
470 public unsafe byte[] PeerId {
474 var result = SSLGetPeerID (Handle, out id, out length);
475 CheckStatusAndThrow (result);
476 if ((result != SslStatus.Success) || ((int)length == 0))
478 var data = new byte [(int)length];
479 Marshal.Copy (id, data, 0, (int) length);
484 IntPtr length = (value == null) ? IntPtr.Zero : (IntPtr)value.Length;
485 fixed (byte *p = value) {
486 result = SSLSetPeerID (Handle, p, length);
488 CheckStatusAndThrow (result);
492 [DllImport (SecurityLibrary)]
493 extern unsafe static /* OSStatus */ SslStatus SSLGetBufferedReadSize (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr bufSize);
495 public IntPtr BufferedReadSize {
498 var result = SSLGetBufferedReadSize (Handle, out value);
499 CheckStatusAndThrow (result);
504 [DllImport (SecurityLibrary)]
505 extern unsafe static /* OSStatus */ SslStatus SSLGetNumberSupportedCiphers (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr numCiphers);
507 [DllImport (SecurityLibrary)]
508 extern unsafe static /* OSStatus */ SslStatus SSLGetSupportedCiphers (/* SSLContextRef */ IntPtr context, SslCipherSuite *ciphers, /* size_t* */ ref IntPtr numCiphers);
510 public unsafe IList<SslCipherSuite> GetSupportedCiphers ()
513 var result = SSLGetNumberSupportedCiphers (Handle, out n);
514 CheckStatusAndThrow (result);
515 if ((result != SslStatus.Success) || ((int)n <= 0))
518 var ciphers = new SslCipherSuite [(int)n];
519 fixed (SslCipherSuite *p = ciphers) {
520 result = SSLGetSupportedCiphers (Handle, p, ref n);
522 CheckStatusAndThrow (result);
526 [DllImport (SecurityLibrary)]
527 extern unsafe static /* OSStatus */ SslStatus SSLGetNumberEnabledCiphers (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr numCiphers);
529 [DllImport (SecurityLibrary)]
530 extern unsafe static /* OSStatus */ SslStatus SSLGetEnabledCiphers (/* SSLContextRef */ IntPtr context, SslCipherSuite *ciphers, /* size_t* */ ref IntPtr numCiphers);
532 public unsafe IList<SslCipherSuite> GetEnabledCiphers ()
535 var result = SSLGetNumberEnabledCiphers (Handle, out n);
536 CheckStatusAndThrow (result);
537 if ((result != SslStatus.Success) || ((int)n <= 0))
540 var ciphers = new SslCipherSuite [(int)n];
541 fixed (SslCipherSuite *p = ciphers) {
542 result = SSLGetEnabledCiphers (Handle, p, ref n);
544 CheckStatusAndThrow (result);
548 [DllImport (SecurityLibrary)]
549 extern unsafe static /* OSStatus */ SslStatus SSLSetEnabledCiphers (/* SSLContextRef */ IntPtr context, SslCipherSuite *ciphers, /* size_t */ IntPtr numCiphers);
551 public unsafe void SetEnabledCiphers (SslCipherSuite [] ciphers)
554 throw new ArgumentNullException ("ciphers");
558 fixed (SslCipherSuite *p = ciphers)
559 result = SSLSetEnabledCiphers (Handle, p, (IntPtr)ciphers.Length);
560 CheckStatusAndThrow (result);
563 [DllImport (SecurityLibrary)]
564 extern unsafe static /* OSStatus */ SslStatus SSLGetNegotiatedCipher (/* SSLContextRef */ IntPtr context, /* SslCipherSuite* */ out SslCipherSuite cipherSuite);
566 public SslCipherSuite NegotiatedCipher {
568 SslCipherSuite value;
569 var result = SSLGetNegotiatedCipher (Handle, out value);
570 CheckStatusAndThrow (result);
575 [DllImport (SecurityLibrary)]
576 extern unsafe static /* OSStatus */ SslStatus SSLGetPeerDomainNameLength (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr peerNameLen);
578 [DllImport (SecurityLibrary)]
579 extern unsafe static /* OSStatus */ SslStatus SSLGetPeerDomainName (/* SSLContextRef */ IntPtr context, /* char* */ byte[] peerName, /* size_t */ ref IntPtr peerNameLen);
581 [DllImport (SecurityLibrary)]
582 extern unsafe static /* OSStatus */ SslStatus SSLSetPeerDomainName (/* SSLContextRef */ IntPtr context, /* char* */ byte[] peerName, /* size_t */ IntPtr peerNameLen);
584 public string PeerDomainName {
587 var result = SSLGetPeerDomainNameLength (Handle, out length);
588 CheckStatusAndThrow (result);
589 if (result != SslStatus.Success || (int)length == 0)
591 var bytes = new byte [(int)length];
592 result = SSLGetPeerDomainName (Handle, bytes, ref length);
593 CheckStatusAndThrow (result);
595 int peerDomainLength = (int)length;
597 if (result != SslStatus.Success)
599 if (peerDomainLength > 0 && bytes [peerDomainLength-1] == 0)
600 peerDomainLength = peerDomainLength - 1;
601 return Encoding.UTF8.GetString (bytes, 0, peerDomainLength);
606 result = SSLSetPeerDomainName (Handle, null, (IntPtr)0);
608 var bytes = Encoding.UTF8.GetBytes (value);
609 result = SSLSetPeerDomainName (Handle, bytes, (IntPtr)bytes.Length);
611 CheckStatusAndThrow (result);
615 [DllImport (SecurityLibrary)]
616 extern unsafe static /* OSStatus */ SslStatus SSLSetCertificate (/* SSLContextRef */ IntPtr context, /* CFArrayRef */ IntPtr certRefs);
618 CFArray Bundle (SecIdentity identity, IEnumerable<SecCertificate> certificates)
620 if (identity == null)
621 throw new ArgumentNullException ("identity");
625 if (certificates != null) {
626 foreach (var obj in certificates)
630 var ptrs = new IntPtr [n + 1];
631 ptrs [0] = identity.Handle;
632 foreach (var certificate in certificates)
633 ptrs [++i] = certificate.Handle;
634 return CFArray.CreateArray (ptrs);
637 public void SetCertificate (SecIdentity identify, IEnumerable<SecCertificate> certificates)
639 using (var array = Bundle (identify, certificates)) {
640 var result = SSLSetCertificate (Handle, array.Handle);
641 CheckStatusAndThrow (result);
645 [DllImport (SecurityLibrary)]
646 extern unsafe static /* OSStatus */ SslStatus SSLGetClientCertificateState (/* SSLContextRef */ IntPtr context, out SslClientCertificateState clientState);
648 public SslClientCertificateState ClientCertificateState {
650 SslClientCertificateState value;
651 var result = SSLGetClientCertificateState (Handle, out value);
652 CheckStatusAndThrow (result);
657 [DllImport (SecurityLibrary)]
658 extern unsafe static /* OSStatus */ SslStatus SSLCopyPeerTrust (/* SSLContextRef */ IntPtr context, /* SecTrustRef */ out IntPtr trust);
660 public SecTrust GetPeerTrust (bool requireTrust)
663 var result = SSLCopyPeerTrust (Handle, out value);
665 CheckStatusAndThrow (result);
666 if (value == IntPtr.Zero)
667 throw new TlsException (AlertDescription.CertificateUnknown);
669 return (value == IntPtr.Zero) ? null : new SecTrust (value);
676 [DllImport (SecurityLibrary)]
677 extern static /* SSLContextRef */ IntPtr SSLCreateContext (/* CFAllocatorRef */ IntPtr alloc, SslProtocolSide protocolSide, SslConnectionType connectionType);
679 [DllImport (SecurityLibrary)]
680 extern static /* OSStatus */ SslStatus SSLSetConnection (/* SSLContextRef */ IntPtr context, /* SSLConnectionRef */ IntPtr connection);
682 [DllImport (SecurityLibrary)]
683 extern static /* OSStatus */ SslStatus SSLSetIOFuncs (/* SSLContextRef */ IntPtr context, /* SSLReadFunc */ SslReadFunc readFunc, /* SSLWriteFunc */ SslWriteFunc writeFunc);
685 [MonoPInvokeCallback (typeof (SslReadFunc))]
686 static SslStatus NativeReadCallback (IntPtr ptr, IntPtr data, ref IntPtr dataLength)
688 var handle = GCHandle.FromIntPtr (ptr);
689 if (!handle.IsAllocated)
690 return SslStatus.Internal;
692 var context = (AppleTlsContext) handle.Target;
693 if (context.disposed)
694 return SslStatus.ClosedAbort;
697 return context.NativeReadCallback (data, ref dataLength);
698 } catch (Exception ex) {
699 if (context.lastException == null)
700 context.lastException = ex;
701 return SslStatus.Internal;
705 [MonoPInvokeCallback (typeof (SslWriteFunc))]
706 static SslStatus NativeWriteCallback (IntPtr ptr, IntPtr data, ref IntPtr dataLength)
708 var handle = GCHandle.FromIntPtr (ptr);
709 if (!handle.IsAllocated)
710 return SslStatus.Internal;
712 var context = (AppleTlsContext) handle.Target;
713 if (context.disposed)
714 return SslStatus.ClosedAbort;
717 return context.NativeWriteCallback (data, ref dataLength);
718 } catch (Exception ex) {
719 if (context.lastException == null)
720 context.lastException = ex;
721 return SslStatus.Internal;
725 SslStatus NativeReadCallback (IntPtr data, ref IntPtr dataLength)
727 if (closed || disposed || Parent == null)
728 return SslStatus.ClosedAbort;
730 var len = (int)dataLength;
731 var readBuffer = new byte [len];
733 Debug ("NativeReadCallback: {0} {1}", dataLength, len);
736 var ret = Parent.InternalRead (readBuffer, 0, len, out wantMore);
737 dataLength = (IntPtr)ret;
739 Debug ("NativeReadCallback #1: {0} - {1} {2}", len, ret, wantMore);
742 return SslStatus.ClosedAbort;
744 Marshal.Copy (readBuffer, 0, data, ret);
747 return SslStatus.Success;
749 return SslStatus.WouldBlock;
751 closedGraceful = true;
752 return SslStatus.ClosedGraceful;
754 return SslStatus.Success;
758 SslStatus NativeWriteCallback (IntPtr data, ref IntPtr dataLength)
760 if (closed || disposed || Parent == null)
761 return SslStatus.ClosedAbort;
763 var len = (int)dataLength;
764 var writeBuffer = new byte [len];
766 Marshal.Copy (data, writeBuffer, 0, len);
768 Debug ("NativeWriteCallback: {0}", len);
770 var ok = Parent.InternalWrite (writeBuffer, 0, len);
772 Debug ("NativeWriteCallback done: {0} {1}", len, ok);
774 return ok ? SslStatus.Success : SslStatus.ClosedAbort;
777 [DllImport (SecurityLibrary)]
778 extern unsafe static /* OSStatus */ SslStatus SSLRead (/* SSLContextRef */ IntPtr context, /* const void* */ byte* data, /* size_t */ IntPtr dataLength, /* size_t* */ out IntPtr processed);
780 public override unsafe int Read (byte[] buffer, int offset, int count, out bool wantMore)
782 if (Interlocked.Exchange (ref pendingIO, 1) == 1)
783 throw new InvalidOperationException ();
785 Debug ("Read: {0},{1}", offset, count);
787 lastException = null;
793 fixed (byte *d = &buffer [offset])
794 status = SSLRead (Handle, d, (IntPtr)count, out processed);
796 Debug ("Read done: {0} {1} {2}", status, count, processed);
798 if (closedGraceful && (status == SslStatus.ClosedAbort || status == SslStatus.ClosedGraceful)) {
800 * This is really ugly, but unfortunately SSLRead() also returns 'SslStatus.ClosedAbort'
801 * when the first inner Read() returns 0. MobileAuthenticatedStream.InnerRead() attempts
802 * to distinguish between a graceful close and abnormal termination of connection.
808 CheckStatusAndThrow (status, SslStatus.WouldBlock, SslStatus.ClosedGraceful);
809 wantMore = status == SslStatus.WouldBlock;
810 return (int)processed;
811 } catch (Exception ex) {
812 Debug ("Read error: {0}", ex);
819 [DllImport (SecurityLibrary)]
820 extern unsafe static /* OSStatus */ SslStatus SSLWrite (/* SSLContextRef */ IntPtr context, /* const void* */ byte* data, /* size_t */ IntPtr dataLength, /* size_t* */ out IntPtr processed);
822 public override unsafe int Write (byte[] buffer, int offset, int count, out bool wantMore)
824 if (Interlocked.Exchange (ref pendingIO, 1) == 1)
825 throw new InvalidOperationException ();
827 Debug ("Write: {0},{1}", offset, count);
829 lastException = null;
832 SslStatus status = SslStatus.ClosedAbort;
833 IntPtr processed = (IntPtr)(-1);
835 fixed (byte *d = &buffer [offset])
836 status = SSLWrite (Handle, d, (IntPtr)count, out processed);
838 Debug ("Write done: {0} {1}", status, processed);
840 CheckStatusAndThrow (status, SslStatus.WouldBlock);
842 wantMore = status == SslStatus.WouldBlock;
843 return (int)processed;
849 [DllImport (SecurityLibrary)]
850 extern static /* OSStatus */ SslStatus SSLClose (/* SSLContextRef */ IntPtr context);
852 public override void Close ()
854 if (Interlocked.Exchange (ref pendingIO, 1) == 1)
855 throw new InvalidOperationException ();
859 lastException = null;
862 if (closed || disposed)
865 var status = SSLClose (Handle);
866 Debug ("Close done: {0}", status);
867 CheckStatusAndThrow (status);
876 protected override void Dispose (bool disposing)
883 if (serverIdentity != null) {
884 serverIdentity.Dispose ();
885 serverIdentity = null;
887 if (clientIdentity != null) {
888 clientIdentity.Dispose ();
889 clientIdentity = null;
891 if (remoteCertificate != null) {
892 remoteCertificate.Dispose ();
893 remoteCertificate = null;
898 if (context != IntPtr.Zero) {
899 CFObject.CFRelease (context);
900 context = IntPtr.Zero;
902 base.Dispose (disposing);