Merge pull request #121 from LogosBible/processfixes
[mono.git] / mcs / class / Mono.Security / Mono.Security.Protocol.Tls / SslStreamBase.cs
1 // Transport Security Layer (TLS)
2 // Copyright (c) 2003-2004 Carlos Guzman Alvarez
3 // Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com)
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining
6 // a copy of this software and associated documentation files (the
7 // "Software"), to deal in the Software without restriction, including
8 // without limitation the rights to use, copy, modify, merge, publish,
9 // distribute, sublicense, and/or sell copies of the Software, and to
10 // permit persons to whom the Software is furnished to do so, subject to
11 // the following conditions:
12 // 
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
15 // 
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 //
24
25 using System;
26 using System.Collections;
27 using System.IO;
28 using System.Net;
29 using System.Net.Sockets;
30 using System.Security.Cryptography;
31 using System.Security.Cryptography.X509Certificates;
32 using System.Threading;
33
34 namespace Mono.Security.Protocol.Tls
35 {
36         public abstract class SslStreamBase: Stream, IDisposable
37         {
38                 private delegate void AsyncHandshakeDelegate(InternalAsyncResult asyncResult, bool fromWrite);
39                 
40                 #region Fields
41
42                 static ManualResetEvent record_processing = new ManualResetEvent (true);        
43
44                 internal Stream innerStream;
45                 internal MemoryStream inputBuffer;
46                 internal Context context;
47                 internal RecordProtocol protocol;
48                 internal bool ownsStream;
49                 private volatile bool disposed;
50                 private bool checkCertRevocationStatus;
51                 private object negotiate;
52                 private object read;
53                 private object write;
54                 private ManualResetEvent negotiationComplete;
55
56                 #endregion
57
58
59                 #region Constructors
60
61                 protected SslStreamBase(
62                         Stream stream,
63                         bool ownsStream)
64                 {
65                         if (stream == null)
66                         {
67                                 throw new ArgumentNullException("stream is null.");
68                         }
69                         if (!stream.CanRead || !stream.CanWrite)
70                         {
71                                 throw new ArgumentNullException("stream is not both readable and writable.");
72                         }
73
74                         this.inputBuffer = new MemoryStream();
75                         this.innerStream = stream;
76                         this.ownsStream = ownsStream;
77                         this.negotiate = new object();
78                         this.read = new object();
79                         this.write = new object();
80                         this.negotiationComplete = new ManualResetEvent(false);
81                 }
82
83                 #endregion
84
85                 #region Handshakes
86                 private void AsyncHandshakeCallback(IAsyncResult asyncResult)
87                 {
88                         InternalAsyncResult internalResult = asyncResult.AsyncState as InternalAsyncResult;
89
90                         try
91                         {
92                                 try
93                                 {
94                                         this.OnNegotiateHandshakeCallback(asyncResult);
95                                 }
96                                 catch (TlsException ex)
97                                 {
98                                         this.protocol.SendAlert(ex.Alert);
99
100                                         throw new IOException("The authentication or decryption has failed.", ex);
101                                 }
102                                 catch (Exception ex)
103                                 {
104                                         this.protocol.SendAlert(AlertDescription.InternalError);
105
106                                         throw new IOException("The authentication or decryption has failed.", ex);
107                                 }
108
109                                 if (internalResult.ProceedAfterHandshake)
110                                 {
111                                         //kick off the read or write process (whichever called us) after the handshake is complete
112                                         if (internalResult.FromWrite)
113                                         {
114                                                 InternalBeginWrite(internalResult);
115                                         }
116                                         else
117                                         {
118                                                 InternalBeginRead(internalResult);
119                                         }
120                                         negotiationComplete.Set();
121                                 }
122                                 else
123                                 {
124                                         negotiationComplete.Set();
125                                         internalResult.SetComplete();
126                                 }
127
128                         }
129                         catch (Exception ex)
130                         {
131                                 negotiationComplete.Set();
132                                 internalResult.SetComplete(ex);
133                         }
134                 }
135
136                 internal bool MightNeedHandshake
137                 {
138                         get
139                         {
140                                 if (this.context.HandshakeState == HandshakeState.Finished)
141                                 {
142                                         return false;
143                                 }
144                                 else
145                                 {
146                                         lock (this.negotiate)
147                                         {
148                                                 return (this.context.HandshakeState != HandshakeState.Finished);
149                                         }
150                                 }
151                         }
152                 }
153
154                 internal void NegotiateHandshake()
155                 {
156                         if (this.MightNeedHandshake)
157                         {
158                                 InternalAsyncResult ar = new InternalAsyncResult(null, null, null, 0, 0, false, false);
159
160                                 //if something already started negotiation, wait for it.
161                                 //otherwise end it ourselves.
162                                 if (!BeginNegotiateHandshake(ar))
163                                 {
164                                         this.negotiationComplete.WaitOne();
165                                 }
166                                 else
167                                 {
168                                         this.EndNegotiateHandshake(ar);
169                                 }
170                         }
171                 }
172
173                 #endregion
174
175                 #region Abstracts/Virtuals
176
177                 internal abstract IAsyncResult OnBeginNegotiateHandshake(AsyncCallback callback, object state);
178                 internal abstract void OnNegotiateHandshakeCallback(IAsyncResult asyncResult);
179
180                 internal abstract X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates,
181                                                                                                                         X509Certificate serverCertificate,
182                                                                                                                         string targetHost,
183                                                                                                                         X509CertificateCollection serverRequestedCertificates);
184
185                 internal abstract bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors);
186                 internal abstract ValidationResult OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection);
187                 internal abstract bool HaveRemoteValidation2Callback { get; }
188
189                 internal abstract AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost);
190
191                 #endregion
192
193                 #region Event Methods
194
195                 internal X509Certificate RaiseLocalCertificateSelection(X509CertificateCollection certificates,
196                                                                                                                         X509Certificate remoteCertificate,
197                                                                                                                         string targetHost,
198                                                                                                                         X509CertificateCollection requestedCertificates)
199                 {
200                         return OnLocalCertificateSelection(certificates, remoteCertificate, targetHost, requestedCertificates);
201                 }
202
203                 internal bool RaiseRemoteCertificateValidation(X509Certificate certificate, int[] errors)
204                 {
205                         return OnRemoteCertificateValidation(certificate, errors);
206                 }
207
208                 internal ValidationResult RaiseRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
209                 {
210                         return OnRemoteCertificateValidation2 (collection);
211                 }
212
213                 internal AsymmetricAlgorithm RaiseLocalPrivateKeySelection(
214                         X509Certificate certificate,
215                         string targetHost)
216                 {
217                         return OnLocalPrivateKeySelection(certificate, targetHost);
218                 }
219                 #endregion
220
221                 #region Security Properties
222
223                 public bool CheckCertRevocationStatus
224                 {
225                         get { return this.checkCertRevocationStatus; }
226                         set { this.checkCertRevocationStatus = value; }
227                 }
228
229                 public CipherAlgorithmType CipherAlgorithm
230                 {
231                         get
232                         {
233                                 if (this.context.HandshakeState == HandshakeState.Finished)
234                                 {
235                                         return this.context.Current.Cipher.CipherAlgorithmType;
236                                 }
237
238                                 return CipherAlgorithmType.None;
239                         }
240                 }
241
242                 public int CipherStrength
243                 {
244                         get
245                         {
246                                 if (this.context.HandshakeState == HandshakeState.Finished)
247                                 {
248                                         return this.context.Current.Cipher.EffectiveKeyBits;
249                                 }
250
251                                 return 0;
252                         }
253                 }
254
255                 public HashAlgorithmType HashAlgorithm
256                 {
257                         get
258                         {
259                                 if (this.context.HandshakeState == HandshakeState.Finished)
260                                 {
261                                         return this.context.Current.Cipher.HashAlgorithmType;
262                                 }
263
264                                 return HashAlgorithmType.None;
265                         }
266                 }
267
268                 public int HashStrength
269                 {
270                         get
271                         {
272                                 if (this.context.HandshakeState == HandshakeState.Finished)
273                                 {
274                                         return this.context.Current.Cipher.HashSize * 8;
275                                 }
276
277                                 return 0;
278                         }
279                 }
280
281                 public int KeyExchangeStrength
282                 {
283                         get
284                         {
285                                 if (this.context.HandshakeState == HandshakeState.Finished)
286                                 {
287                                         return this.context.ServerSettings.Certificates[0].RSA.KeySize;
288                                 }
289
290                                 return 0;
291                         }
292                 }
293
294                 public ExchangeAlgorithmType KeyExchangeAlgorithm
295                 {
296                         get
297                         {
298                                 if (this.context.HandshakeState == HandshakeState.Finished)
299                                 {
300                                         return this.context.Current.Cipher.ExchangeAlgorithmType;
301                                 }
302
303                                 return ExchangeAlgorithmType.None;
304                         }
305                 }
306
307                 public SecurityProtocolType SecurityProtocol
308                 {
309                         get
310                         {
311                                 if (this.context.HandshakeState == HandshakeState.Finished)
312                                 {
313                                         return this.context.SecurityProtocol;
314                                 }
315
316                                 return 0;
317                         }
318                 }
319
320                 public X509Certificate ServerCertificate
321                 {
322                         get
323                         {
324                                 if (this.context.HandshakeState == HandshakeState.Finished)
325                                 {
326                                         if (this.context.ServerSettings.Certificates != null &&
327                                                 this.context.ServerSettings.Certificates.Count > 0)
328                                         {
329                                                 return new X509Certificate(this.context.ServerSettings.Certificates[0].RawData);
330                                         }
331                                 }
332
333                                 return null;
334                         }
335                 }
336
337                 // this is used by Mono's certmgr tool to download certificates
338                 internal Mono.Security.X509.X509CertificateCollection ServerCertificates
339                 {
340                         get { return context.ServerSettings.Certificates; }
341                 }
342
343                 #endregion
344
345                 #region Internal Async Result/State Class
346
347                 private class InternalAsyncResult : IAsyncResult
348                 {
349                         private object locker = new object ();
350                         private AsyncCallback _userCallback;
351                         private object _userState;
352                         private Exception _asyncException;
353                         private ManualResetEvent handle;
354                         private bool completed;
355                         private int _bytesRead;
356                         private bool _fromWrite;
357                         private bool _proceedAfterHandshake;
358
359                         private byte[] _buffer;
360                         private int _offset;
361                         private int _count;
362
363                         public InternalAsyncResult(AsyncCallback userCallback, object userState, byte[] buffer, int offset, int count, bool fromWrite, bool proceedAfterHandshake)
364                         {
365                                 _userCallback = userCallback;
366                                 _userState = userState;
367                                 _buffer = buffer;
368                                 _offset = offset;
369                                 _count = count;
370                                 _fromWrite = fromWrite;
371                                 _proceedAfterHandshake = proceedAfterHandshake;
372                         }
373
374                         public bool ProceedAfterHandshake
375                         {
376                                 get { return _proceedAfterHandshake; }
377                         }
378
379                         public bool FromWrite
380                         {
381                                 get { return _fromWrite; }
382                         }
383
384                         public byte[] Buffer
385                         {
386                                 get { return _buffer; }
387                         }
388
389                         public int Offset
390                         {
391                                 get { return _offset; }
392                         }
393
394                         public int Count
395                         {
396                                 get { return _count; }
397                         }
398
399                         public int BytesRead
400                         {
401                                 get { return _bytesRead; }
402                         }
403
404                         public object AsyncState
405                         {
406                                 get { return _userState; }
407                         }
408
409                         public Exception AsyncException
410                         {
411                                 get { return _asyncException; }
412                         }
413
414                         public bool CompletedWithError
415                         {
416                                 get {
417                                         if (IsCompleted == false)
418                                                 return false;
419                                         return null != _asyncException;
420                                 }
421                         }
422
423                         public WaitHandle AsyncWaitHandle
424                         {
425                                 get {
426                                         lock (locker) {
427                                                 if (handle == null)
428                                                         handle = new ManualResetEvent (completed);
429                                         }
430                                         return handle;
431                                 }
432                         }
433
434                         public bool CompletedSynchronously
435                         {
436                                 get { return false; }
437                         }
438
439                         public bool IsCompleted
440                         {
441                                 get {
442                                         lock (locker)
443                                                 return completed;
444                                 }
445                         }
446
447                         private void SetComplete(Exception ex, int bytesRead)
448                         {
449                                 lock (locker) {
450                                         if (completed)
451                                                 return;
452
453                                         completed = true;
454                                         _asyncException = ex;
455                                         _bytesRead = bytesRead;
456                                         if (handle != null)
457                                                 handle.Set ();
458                                 }
459                                 if (_userCallback != null)
460                                         _userCallback.BeginInvoke (this, null, null);
461                         }
462
463                         public void SetComplete(Exception ex)
464                         {
465                                 SetComplete(ex, 0);
466                         }
467
468                         public void SetComplete(int bytesRead)
469                         {
470                                 SetComplete(null, bytesRead);
471                         }
472
473                         public void SetComplete()
474                         {
475                                 SetComplete(null, 0);
476                         }
477                 }
478                 #endregion
479
480                 #region Stream Overrides and Async Stream Operations
481
482                 private bool BeginNegotiateHandshake(InternalAsyncResult asyncResult)
483                 {
484                         try
485                         {
486                                 lock (this.negotiate)
487                                 {
488                                         if (this.context.HandshakeState == HandshakeState.None)
489                                         {
490                                                 this.OnBeginNegotiateHandshake(new AsyncCallback(AsyncHandshakeCallback), asyncResult);
491
492                                                 return true;
493                                         }
494                                         else
495                                         {
496                                                 return false;
497                                         }
498                                 }
499                         }
500                         catch (TlsException ex)
501                         {
502                                 this.negotiationComplete.Set();
503                                 this.protocol.SendAlert(ex.Alert);
504
505                                 throw new IOException("The authentication or decryption has failed.", ex);
506                         }
507                         catch (Exception ex)
508                         {
509                                 this.negotiationComplete.Set();
510                                 this.protocol.SendAlert(AlertDescription.InternalError);
511
512                                 throw new IOException("The authentication or decryption has failed.", ex);
513                         }
514                 }
515
516                 private void EndNegotiateHandshake(InternalAsyncResult asyncResult)
517                 {
518                         if (asyncResult.IsCompleted == false)
519                                 asyncResult.AsyncWaitHandle.WaitOne();
520
521                         if (asyncResult.CompletedWithError)
522                         {
523                                 throw asyncResult.AsyncException;
524                         }
525                 }
526
527                 public override IAsyncResult BeginRead(
528                         byte[] buffer,
529                         int offset,
530                         int count,
531                         AsyncCallback callback,
532                         object state)
533                 {
534                         this.checkDisposed();
535
536                         if (buffer == null)
537                         {
538                                 throw new ArgumentNullException("buffer is a null reference.");
539                         }
540                         if (offset < 0)
541                         {
542                                 throw new ArgumentOutOfRangeException("offset is less than 0.");
543                         }
544                         if (offset > buffer.Length)
545                         {
546                                 throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
547                         }
548                         if (count < 0)
549                         {
550                                 throw new ArgumentOutOfRangeException("count is less than 0.");
551                         }
552                         if (count > (buffer.Length - offset))
553                         {
554                                 throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
555                         }
556
557                         InternalAsyncResult asyncResult = new InternalAsyncResult(callback, state, buffer, offset, count, false, true);
558
559                         if (this.MightNeedHandshake)
560                         {
561                                 if (! BeginNegotiateHandshake(asyncResult))
562                                 {
563                                         //we made it down here so the handshake was not started.
564                                         //another thread must have started it in the mean time.
565                                         //wait for it to complete and then perform our original operation
566                                         this.negotiationComplete.WaitOne();
567
568                                         InternalBeginRead(asyncResult);
569                                 }
570                         }
571                         else
572                         {
573                                 InternalBeginRead(asyncResult);
574                         }
575
576                         return asyncResult;
577                 }
578
579                 // bigger than max record length for SSL/TLS
580                 private byte[] recbuf = new byte[16384];
581
582                 private void InternalBeginRead(InternalAsyncResult asyncResult)
583                 {
584                         try
585                         {
586                                 int preReadSize = 0;
587
588                                 lock (this.read)
589                                 {
590                                         // If actual buffer is fully read, reset it
591                                         bool shouldReset = this.inputBuffer.Position == this.inputBuffer.Length && this.inputBuffer.Length > 0;
592
593                                         // If the buffer isn't fully read, but does have data, we need to immediately
594                                         // read the info from the buffer and let the user know that they have more data.
595                                         bool shouldReadImmediately = (this.inputBuffer.Length > 0) && (asyncResult.Count > 0);
596
597                                         if (shouldReset)
598                                         {
599                                                 this.resetBuffer();
600                                         }
601                                         else if (shouldReadImmediately)
602                                         {
603                                                 preReadSize = this.inputBuffer.Read(asyncResult.Buffer, asyncResult.Offset, asyncResult.Count);
604                                         }
605                                 }
606
607                                 // This is explicitly done outside the synclock to avoid 
608                                 // any potential deadlocks in the delegate call.
609                                 if (0 < preReadSize)
610                                 {
611                                         asyncResult.SetComplete(preReadSize);
612                                 }
613                                 else if (!this.context.ReceivedConnectionEnd)
614                                 {
615                                         // this will read data from the network until we have (at least) one
616                                         // record to send back to the caller
617                                         this.innerStream.BeginRead(recbuf, 0, recbuf.Length,
618                                                 new AsyncCallback(InternalReadCallback), new object[] { recbuf, asyncResult });
619                                 }
620                                 else
621                                 {
622                                         // We're done with the connection so we need to let the caller know with 0 bytes read
623                                         asyncResult.SetComplete(0);
624                                 }
625                         }
626                         catch (TlsException ex)
627                         {
628                                 this.protocol.SendAlert(ex.Alert);
629
630                                 throw new IOException("The authentication or decryption has failed.", ex);
631                         }
632                         catch (Exception ex)
633                         {
634                                 throw new IOException("IO exception during read.", ex);
635                         }
636                 }
637
638
639                 private MemoryStream recordStream = new MemoryStream();
640
641                 // read encrypted data until we have enough to decrypt (at least) one
642                 // record and return are the records (may be more than one) we have
643                 private void InternalReadCallback(IAsyncResult result)
644                 {
645                         if (this.disposed)
646                                 return;
647
648                         object[] state = (object[])result.AsyncState;
649                         byte[] recbuf = (byte[])state[0];
650                         InternalAsyncResult internalResult = (InternalAsyncResult)state[1];
651
652                         try
653                         {
654                                 int n = innerStream.EndRead(result);
655                                 if (n > 0)
656                                 {
657                                         // Add the just received data to the waiting data
658                                         recordStream.Write(recbuf, 0, n);
659                                 }
660                                 else
661                                 {
662                                         // 0 length data means this read operation is done (lost connection in the case of a network stream).
663                                         internalResult.SetComplete(0);
664                                         return;
665                                 }
666
667                                 bool dataToReturn = false;
668                                 long pos = recordStream.Position;
669
670                                 recordStream.Position = 0;
671                                 byte[] record = null;
672
673                                 // don't try to decode record unless we have at least 5 bytes
674                                 // i.e. type (1), protocol (2) and length (2)
675                                 if (recordStream.Length >= 5)
676                                 {
677                                         record = this.protocol.ReceiveRecord(recordStream);
678                                 }
679
680                                 // a record of 0 length is valid (and there may be more record after it)
681                                 while (record != null)
682                                 {
683                                         // we probably received more stuff after the record, and we must keep it!
684                                         long remainder = recordStream.Length - recordStream.Position;
685                                         byte[] outofrecord = null;
686                                         if (remainder > 0)
687                                         {
688                                                 outofrecord = new byte[remainder];
689                                                 recordStream.Read(outofrecord, 0, outofrecord.Length);
690                                         }
691
692                                         lock (this.read)
693                                         {
694                                                 long position = this.inputBuffer.Position;
695
696                                                 if (record.Length > 0)
697                                                 {
698                                                         // Write new data to the inputBuffer
699                                                         this.inputBuffer.Seek(0, SeekOrigin.End);
700                                                         this.inputBuffer.Write(record, 0, record.Length);
701
702                                                         // Restore buffer position
703                                                         this.inputBuffer.Seek(position, SeekOrigin.Begin);
704                                                         dataToReturn = true;
705                                                 }
706                                         }
707
708                                         recordStream.SetLength(0);
709                                         record = null;
710
711                                         if (remainder > 0)
712                                         {
713                                                 recordStream.Write(outofrecord, 0, outofrecord.Length);
714                                                 // type (1), protocol (2) and length (2)
715                                                 if (recordStream.Length >= 5)
716                                                 {
717                                                         // try to see if another record is available
718                                                         recordStream.Position = 0;
719                                                         record = this.protocol.ReceiveRecord(recordStream);
720                                                         if (record == null)
721                                                                 pos = recordStream.Length;
722                                                 }
723                                                 else
724                                                         pos = remainder;
725                                         }
726                                         else
727                                                 pos = 0;
728                                 }
729
730                                 if (!dataToReturn && (n > 0))
731                                 {
732                                         if (context.ReceivedConnectionEnd) {
733                                                 internalResult.SetComplete (0);
734                                         } else {
735                                                 // there is no record to return to caller and (possibly) more data waiting
736                                                 // so continue reading from network (and appending to stream)
737                                                 recordStream.Position = recordStream.Length;
738                                                 this.innerStream.BeginRead(recbuf, 0, recbuf.Length,
739                                                         new AsyncCallback(InternalReadCallback), state);
740                                         }
741                                 }
742                                 else
743                                 {
744                                         // we have record(s) to return -or- no more available to read from network
745                                         // reset position for further reading
746                                         recordStream.Position = pos;
747
748                                         int bytesRead = 0;
749                                         lock (this.read)
750                                         {
751                                                 bytesRead = this.inputBuffer.Read(internalResult.Buffer, internalResult.Offset, internalResult.Count);
752                                         }
753
754                                         internalResult.SetComplete(bytesRead);
755                                 }
756                         }
757                         catch (Exception ex)
758                         {
759                                 internalResult.SetComplete(ex);
760                         }
761
762                 }
763
764                 private void InternalBeginWrite(InternalAsyncResult asyncResult)
765                 {
766                         try
767                         {
768                                 // Send the buffer as a TLS record
769
770                                 lock (this.write)
771                                 {
772                                         byte[] record = this.protocol.EncodeRecord(
773                                                 ContentType.ApplicationData, asyncResult.Buffer, asyncResult.Offset, asyncResult.Count);
774
775                                         this.innerStream.BeginWrite(
776                                                 record, 0, record.Length, new AsyncCallback(InternalWriteCallback), asyncResult);
777                                 }
778                         }
779                         catch (TlsException ex)
780                         {
781                                 this.protocol.SendAlert(ex.Alert);
782                                 this.Close();
783
784                                 throw new IOException("The authentication or decryption has failed.", ex);
785                         }
786                         catch (Exception ex)
787                         {
788                                 throw new IOException("IO exception during Write.", ex);
789                         }
790                 }
791
792                 private void InternalWriteCallback(IAsyncResult ar)
793                 {
794                         if (this.disposed)
795                                 return;
796                         
797                         InternalAsyncResult internalResult = (InternalAsyncResult)ar.AsyncState;
798
799                         try
800                         {
801                                 this.innerStream.EndWrite(ar);
802                                 internalResult.SetComplete();
803                         }
804                         catch (Exception ex)
805                         {
806                                 internalResult.SetComplete(ex);
807                         }
808                 }
809
810                 public override IAsyncResult BeginWrite(
811                         byte[] buffer,
812                         int offset,
813                         int count,
814                         AsyncCallback callback,
815                         object state)
816                 {
817                         this.checkDisposed();
818
819                         if (buffer == null)
820                         {
821                                 throw new ArgumentNullException("buffer is a null reference.");
822                         }
823                         if (offset < 0)
824                         {
825                                 throw new ArgumentOutOfRangeException("offset is less than 0.");
826                         }
827                         if (offset > buffer.Length)
828                         {
829                                 throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
830                         }
831                         if (count < 0)
832                         {
833                                 throw new ArgumentOutOfRangeException("count is less than 0.");
834                         }
835                         if (count > (buffer.Length - offset))
836                         {
837                                 throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
838                         }
839
840
841                         InternalAsyncResult asyncResult = new InternalAsyncResult(callback, state, buffer, offset, count, true, true);
842
843                         if (this.MightNeedHandshake)
844                         {
845                                 if (! BeginNegotiateHandshake(asyncResult))
846                                 {
847                                         //we made it down here so the handshake was not started.
848                                         //another thread must have started it in the mean time.
849                                         //wait for it to complete and then perform our original operation
850                                         this.negotiationComplete.WaitOne();
851
852                                         InternalBeginWrite(asyncResult);
853                                 }
854                         }
855                         else
856                         {
857                                 InternalBeginWrite(asyncResult);
858                         }
859
860                         return asyncResult;
861                 }
862
863                 public override int EndRead(IAsyncResult asyncResult)
864                 {
865                         this.checkDisposed();
866
867                         InternalAsyncResult internalResult = asyncResult as InternalAsyncResult;
868                         if (internalResult == null)
869                         {
870                                 throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginRead.");
871                         }
872
873                         // Always wait until the read is complete
874                         if (!asyncResult.IsCompleted)
875                         {
876                                 if (!asyncResult.AsyncWaitHandle.WaitOne ())
877                                         throw new TlsException (AlertDescription.InternalError, "Couldn't complete EndRead");
878                         }
879
880                         if (internalResult.CompletedWithError)
881                         {
882                                 throw internalResult.AsyncException;
883                         }
884
885                         return internalResult.BytesRead;
886                 }
887
888                 public override void EndWrite(IAsyncResult asyncResult)
889                 {
890                         this.checkDisposed();
891
892                         InternalAsyncResult internalResult = asyncResult as InternalAsyncResult;
893                         if (internalResult == null)
894                         {
895                                 throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginWrite.");
896                         }
897
898
899                         if (!asyncResult.IsCompleted)
900                         {
901                                 if (!internalResult.AsyncWaitHandle.WaitOne ())
902                                         throw new TlsException (AlertDescription.InternalError, "Couldn't complete EndWrite");
903                         }
904
905                         if (internalResult.CompletedWithError)
906                         {
907                                 throw internalResult.AsyncException;
908                         }
909                 }
910
911                 public override void Close()
912                 {
913                         base.Close ();
914                 }
915
916                 public override void Flush()
917                 {
918                         this.checkDisposed();
919
920                         this.innerStream.Flush();
921                 }
922
923                 public int Read(byte[] buffer)
924                 {
925                         return this.Read(buffer, 0, buffer.Length);
926                 }
927
928                 public override int Read(byte[] buffer, int offset, int count)
929                 {
930                         this.checkDisposed ();
931                         
932                         if (buffer == null)
933                         {
934                                 throw new ArgumentNullException ("buffer");
935                         }
936                         if (offset < 0)
937                         {
938                                 throw new ArgumentOutOfRangeException("offset is less than 0.");
939                         }
940                         if (offset > buffer.Length)
941                         {
942                                 throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
943                         }
944                         if (count < 0)
945                         {
946                                 throw new ArgumentOutOfRangeException("count is less than 0.");
947                         }
948                         if (count > (buffer.Length - offset))
949                         {
950                                 throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
951                         }
952
953                         if (this.context.HandshakeState != HandshakeState.Finished)
954                         {
955                                 this.NegotiateHandshake (); // Handshake negotiation
956                         }
957
958                         lock (this.read) {
959                                 try {
960                                         record_processing.Reset ();
961                                         // do we already have some decrypted data ?
962                                         if (this.inputBuffer.Position > 0) {
963                                                 // or maybe we used all the buffer before ?
964                                                 if (this.inputBuffer.Position == this.inputBuffer.Length) {
965                                                         this.inputBuffer.SetLength (0);
966                                                 } else {
967                                                         int n = this.inputBuffer.Read (buffer, offset, count);
968                                                         if (n > 0) {
969                                                                 record_processing.Set ();
970                                                                 return n;
971                                                         }
972                                                 }
973                                         }
974
975                                         bool needMoreData = false;
976                                         while (true) {
977                                                 // we first try to process the read with the data we already have
978                                                 if ((recordStream.Position == 0) || needMoreData) {
979                                                         needMoreData = false;
980                                                         // if we loop, then it either means we need more data
981                                                         byte[] recbuf = new byte[16384];
982                                                         int n = 0;
983                                                         if (count == 1) {
984                                                                 int value = innerStream.ReadByte ();
985                                                                 if (value >= 0) {
986                                                                         recbuf[0] = (byte) value;
987                                                                         n = 1;
988                                                                 }
989                                                         } else {
990                                                                 n = innerStream.Read (recbuf, 0, recbuf.Length);
991                                                         }
992                                                         if (n > 0) {
993                                                                 // Add the new received data to the waiting data
994                                                                 if ((recordStream.Length > 0) && (recordStream.Position != recordStream.Length))
995                                                                         recordStream.Seek (0, SeekOrigin.End);
996                                                                 recordStream.Write (recbuf, 0, n);
997                                                         } else {
998                                                                 // or that the read operation is done (lost connection in the case of a network stream).
999                                                                 record_processing.Set ();
1000                                                                 return 0;
1001                                                         }
1002                                                 }
1003
1004                                                 bool dataToReturn = false;
1005
1006                                                 recordStream.Position = 0;
1007                                                 byte[] record = null;
1008
1009                                                 // don't try to decode record unless we have at least 5 bytes
1010                                                 // i.e. type (1), protocol (2) and length (2)
1011                                                 if (recordStream.Length >= 5) {
1012                                                         record = this.protocol.ReceiveRecord (recordStream);
1013                                                         needMoreData = (record == null);
1014                                                 }
1015
1016                                                 // a record of 0 length is valid (and there may be more record after it)
1017                                                 while (record != null) {
1018                                                         // we probably received more stuff after the record, and we must keep it!
1019                                                         long remainder = recordStream.Length - recordStream.Position;
1020                                                         byte[] outofrecord = null;
1021                                                         if (remainder > 0) {
1022                                                                 outofrecord = new byte[remainder];
1023                                                                 recordStream.Read (outofrecord, 0, outofrecord.Length);
1024                                                         }
1025
1026                                                         long position = this.inputBuffer.Position;
1027
1028                                                         if (record.Length > 0) {
1029                                                                 // Write new data to the inputBuffer
1030                                                                 this.inputBuffer.Seek (0, SeekOrigin.End);
1031                                                                 this.inputBuffer.Write (record, 0, record.Length);
1032
1033                                                                 // Restore buffer position
1034                                                                 this.inputBuffer.Seek (position, SeekOrigin.Begin);
1035                                                                 dataToReturn = true;
1036                                                         }
1037
1038                                                         recordStream.SetLength (0);
1039                                                         record = null;
1040
1041                                                         if (remainder > 0) {
1042                                                                 recordStream.Write (outofrecord, 0, outofrecord.Length);
1043                                                         }
1044
1045                                                         if (dataToReturn) {
1046                                                                 // we have record(s) to return -or- no more available to read from network
1047                                                                 // reset position for further reading
1048                                                                 int i = inputBuffer.Read (buffer, offset, count);
1049                                                                 record_processing.Set ();
1050                                                                 return i;
1051                                                         }
1052                                                 }
1053                                         }
1054                                 }
1055                                 catch (TlsException ex)
1056                                 {
1057                                         throw new IOException("The authentication or decryption has failed.", ex);
1058                                 }
1059                                 catch (Exception ex)
1060                                 {
1061                                         throw new IOException("IO exception during read.", ex);
1062                                 }
1063                         }
1064                 }
1065
1066                 public override long Seek(long offset, SeekOrigin origin)
1067                 {
1068                         throw new NotSupportedException();
1069                 }
1070
1071                 public override void SetLength(long value)
1072                 {
1073                         throw new NotSupportedException();
1074                 }
1075
1076                 public void Write(byte[] buffer)
1077                 {
1078                         this.Write(buffer, 0, buffer.Length);
1079                 }
1080
1081                 public override void Write(byte[] buffer, int offset, int count)
1082                 {
1083                         this.checkDisposed ();
1084                         
1085                         if (buffer == null)
1086                         {
1087                                 throw new ArgumentNullException ("buffer");
1088                         }
1089                         if (offset < 0)
1090                         {
1091                                 throw new ArgumentOutOfRangeException("offset is less than 0.");
1092                         }
1093                         if (offset > buffer.Length)
1094                         {
1095                                 throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
1096                         }
1097                         if (count < 0)
1098                         {
1099                                 throw new ArgumentOutOfRangeException("count is less than 0.");
1100                         }
1101                         if (count > (buffer.Length - offset))
1102                         {
1103                                 throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
1104                         }
1105
1106                         if (this.context.HandshakeState != HandshakeState.Finished)
1107                         {
1108                                 this.NegotiateHandshake ();
1109                         }
1110
1111                         lock (this.write)
1112                         {
1113                                 try
1114                                 {
1115                                         // Send the buffer as a TLS record
1116                                         byte[] record = this.protocol.EncodeRecord (ContentType.ApplicationData, buffer, offset, count);
1117                                         this.innerStream.Write (record, 0, record.Length);
1118                                 }
1119                                 catch (TlsException ex)
1120                                 {
1121                                         this.protocol.SendAlert(ex.Alert);
1122                                         this.Close();
1123                                         throw new IOException("The authentication or decryption has failed.", ex);
1124                                 }
1125                                 catch (Exception ex)
1126                                 {
1127                                         throw new IOException("IO exception during Write.", ex);
1128                                 }
1129                         }
1130                 }
1131
1132                 public override bool CanRead
1133                 {
1134                         get { return this.innerStream.CanRead; }
1135                 }
1136
1137                 public override bool CanSeek
1138                 {
1139                         get { return false; }
1140                 }
1141
1142                 public override bool CanWrite
1143                 {
1144                         get { return this.innerStream.CanWrite; }
1145                 }
1146
1147                 public override long Length
1148                 {
1149                         get { throw new NotSupportedException(); }
1150                 }
1151
1152                 public override long Position
1153                 {
1154                         get
1155                         {
1156                                 throw new NotSupportedException();
1157                         }
1158                         set
1159                         {
1160                                 throw new NotSupportedException();
1161                         }
1162                 }
1163                 #endregion
1164
1165                 #region IDisposable Members and Finalizer
1166
1167                 ~SslStreamBase()
1168                 {
1169                         this.Dispose(false);
1170                 }
1171
1172                 protected override void Dispose (bool disposing)
1173                 {
1174                         if (!this.disposed)
1175                         {
1176                                 if (disposing)
1177                                 {
1178                                         if (this.innerStream != null)
1179                                         {
1180                                                 if (this.context.HandshakeState == HandshakeState.Finished &&
1181                                                         !this.context.SentConnectionEnd)
1182                                                 {
1183                                                         // Write close notify
1184                                                         try {
1185                                                                 this.protocol.SendAlert(AlertDescription.CloseNotify);
1186                                                         } catch {
1187                                                         }
1188                                                 }
1189
1190                                                 if (this.ownsStream)
1191                                                 {
1192                                                         // Close inner stream
1193                                                         this.innerStream.Close();
1194                                                 }
1195                                         }
1196                                         this.ownsStream = false;
1197                                         this.innerStream = null;
1198                                 }
1199
1200                                 this.disposed = true;
1201                                 base.Dispose (disposing);
1202                         }
1203                 }
1204
1205                 #endregion
1206
1207                 #region Misc Methods
1208
1209                 private void resetBuffer()
1210                 {
1211                         this.inputBuffer.SetLength(0);
1212                         this.inputBuffer.Position = 0;
1213                 }
1214
1215                 internal void checkDisposed()
1216                 {
1217                         if (this.disposed)
1218                         {
1219                                 throw new ObjectDisposedException("The Stream is closed.");
1220                         }
1221                 }
1222
1223                 #endregion
1224
1225         }
1226 }