Created
December 12, 2016 23:32
-
-
Save Drawaes/009d39f80ba6caf045b2b8372d4917fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ReadableBuffer currentPayload; | |
int expectedPayloadSize = 0; | |
while (true) | |
{ | |
var result = await _lowerConnection.Input.ReadAsync(); | |
var buffer = result.Buffer; | |
try | |
{ | |
if (buffer.IsEmpty && result.IsCompleted) | |
{ | |
new InvalidOperationException("Connection closed before the handshake completed"); | |
} | |
ReadableBuffer messageBuffer; | |
TlsFrameType frameType; | |
while (TryGetFrameType(ref buffer, out messageBuffer, out frameType)) | |
{ | |
//We have a frame, | |
if(connectionState.IsEncrypted) | |
{ | |
messageBuffer = Decrypt(ref messageBuffer); | |
} | |
//Remove header if it was encrypted the decrypt removed the trailer anyway | |
messageBuffer = messageBuffer.Slice(5); | |
if(expectedPayloadSize == 0) | |
{ | |
expectedPayloadSize = messageBuffer.ReadBigEndian<ushort>(); | |
currentPayload = messageBuffer; | |
} | |
else | |
{ | |
currentPayload.Add(messageBuffer); | |
} | |
while(true) | |
{ | |
if(currentPayload.Length < expectedPayloadSize || expectedPayloadSize == 0) | |
{ | |
break; | |
} | |
var finishedPayload = currentPayload.Slice(0,expectedPayloadSize); | |
currentPayload = currentPayload.Slice(expectedPayloadSize); | |
if(currentPayload.Length >= 2) | |
{ | |
expectedPayloadSize = currentPayload.ReadBigEndian<ushort>(); | |
} | |
else | |
{ | |
expectedPayloadSize = 0; | |
} | |
ProcessPayload(finishedPayload); | |
} | |
} | |
} | |
finally | |
{ | |
_lowerConnection.Input.Advance(buffer.Start, buffer.End); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment