Refactored ChunkStream.cs

This commit is contained in:
sta 2014-05-17 20:52:34 +09:00
parent 696cfd686d
commit 2a1f706051
4 changed files with 509 additions and 361 deletions

View File

@ -0,0 +1,97 @@
#region License
/*
* Chunk.cs
*
* This code is derived from System.Net.ChunkStream.cs of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2003 Ximian, Inc (http://www.ximian.com)
* Copyright (c) 2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
*/
#endregion
using System;
namespace WebSocketSharp.Net
{
internal class Chunk
{
#region Private Fields
private byte [] _data;
private int _offset;
#endregion
#region Public Constructors
public Chunk (byte [] data)
{
_data = data;
}
#endregion
#region Public Properties
public int Length {
get {
return _data.Length;
}
}
public int Offset {
get {
return _offset;
}
}
#endregion
#region Public Methods
public int Read (byte [] buffer, int offset, int size)
{
var left = _data.Length - _offset;
if (left == 0)
return left;
if (size > left)
size = left;
Buffer.BlockCopy (_data, _offset, buffer, offset, size);
_offset += size;
return size;
}
#endregion
}
}

View File

@ -1,31 +1,41 @@
// #region License
// ChunkStream.cs /*
// Copied from System.Net.ChunkStream.cs * ChunkStream.cs
// *
// Authors: * This code is derived from System.Net.ChunkStream.cs of Mono
// Gonzalo Paniagua Javier (gonzalo@ximian.com) * (http://www.mono-project.com).
// *
// (C) 2003 Ximian, Inc (http://www.ximian.com) * The MIT License
// *
// Permission is hereby granted, free of charge, to any person obtaining * Copyright (c) 2003 Ximian, Inc (http://www.ximian.com)
// a copy of this software and associated documentation files (the * Copyright (c) 2012-2014 sta.blockhead
// "Software"), to deal in the Software without restriction, including *
// without limitation the rights to use, copy, modify, merge, publish, * Permission is hereby granted, free of charge, to any person obtaining a copy
// distribute, sublicense, and/or sell copies of the Software, and to * of this software and associated documentation files (the "Software"), to deal
// permit persons to whom the Software is furnished to do so, subject to * in the Software without restriction, including without limitation the rights
// the following conditions: * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// * copies of the Software, and to permit persons to whom the Software is
// The above copyright notice and this permission notice shall be * furnished to do so, subject to the following conditions:
// included in all copies or substantial portions of the Software. *
// * The above copyright notice and this permission notice shall be included in
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * all copies or substantial portions of the Software.
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
*/
#endregion
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -34,57 +44,25 @@ using System.IO;
using System.Net; using System.Net;
using System.Text; using System.Text;
namespace WebSocketSharp.Net { namespace WebSocketSharp.Net
{
class ChunkStream { internal class ChunkStream
enum State {
None,
Body,
BodyFinished,
Trailer
}
class Chunk {
public byte [] Bytes;
public int Offset;
public Chunk (byte [] chunk)
{ {
this.Bytes = chunk;
}
public int Read (byte [] buffer, int offset, int size)
{
int nread = (size > Bytes.Length - Offset) ? Bytes.Length - Offset : size;
Buffer.BlockCopy (Bytes, Offset, buffer, offset, nread);
Offset += nread;
return nread;
}
}
#region Private Fields #region Private Fields
int chunkRead; private int _chunkRead;
List<Chunk> chunks; private int _chunkSize;
int chunkSize; private List<Chunk> _chunks;
bool gotit; private bool _gotit;
StringBuilder saved; private WebHeaderCollection _headers;
bool sawCR; private StringBuilder _saved;
State state; private bool _sawCR;
int trailerState; private InputChunkState _state;
private int _trailerState;
#endregion #endregion
#region Internal Fields #region Public Constructors
internal WebHeaderCollection headers;
#endregion
#region Constructors
public ChunkStream (byte [] buffer, int offset, int size, WebHeaderCollection headers) public ChunkStream (byte [] buffer, int offset, int size, WebHeaderCollection headers)
: this (headers) : this (headers)
@ -94,169 +72,70 @@ namespace WebSocketSharp.Net {
public ChunkStream (WebHeaderCollection headers) public ChunkStream (WebHeaderCollection headers)
{ {
this.headers = headers; _headers = headers;
saved = new StringBuilder (); _chunkSize = -1;
chunks = new List<Chunk> (); _chunks = new List<Chunk> ();
chunkSize = -1; _saved = new StringBuilder ();
} }
#endregion #endregion
#region Properties #region Internal Properties
internal WebHeaderCollection Headers {
get {
return _headers;
}
}
#endregion
#region Public Properties
public int ChunkLeft { public int ChunkLeft {
get { return chunkSize - chunkRead; } get {
return _chunkSize - _chunkRead;
}
} }
public bool WantMore { public bool WantMore {
get { return (chunkRead != chunkSize || chunkSize != 0 || state != State.None); } get {
return _chunkRead != _chunkSize || _chunkSize != 0 || _state != InputChunkState.None;
}
} }
#endregion #endregion
#region Private Methods #region Private Methods
State GetChunkSize (byte [] buffer, ref int offset, int size) private InputChunkState readCRLF (byte [] buffer, ref int offset, int size)
{ {
char c = '\0'; if (!_sawCR) {
while (offset < size) {
c = (char) buffer [offset++];
if (c == '\r') {
if (sawCR)
ThrowProtocolViolation ("2 CR found.");
sawCR = true;
continue;
}
if (sawCR && c == '\n')
break;
if (c == ' ')
gotit = true;
if (!gotit)
saved.Append (c);
if (saved.Length > 20)
ThrowProtocolViolation ("Chunk size too long.");
}
if (!sawCR || c != '\n') {
if (offset < size)
ThrowProtocolViolation ("Missing \\n.");
try {
if (saved.Length > 0) {
chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber);
}
} catch (Exception) {
ThrowProtocolViolation ("Cannot parse chunk size.");
}
return State.None;
}
chunkRead = 0;
try {
chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber);
} catch (Exception) {
ThrowProtocolViolation ("Cannot parse chunk size.");
}
if (chunkSize == 0) {
trailerState = 2;
return State.Trailer;
}
return State.Body;
}
void InternalWrite (byte [] buffer, ref int offset, int size)
{
if (state == State.None) {
state = GetChunkSize (buffer, ref offset, size);
if (state == State.None)
return;
saved.Length = 0;
sawCR = false;
gotit = false;
}
if (state == State.Body && offset < size) {
state = ReadBody (buffer, ref offset, size);
if (state == State.Body)
return;
}
if (state == State.BodyFinished && offset < size) {
state = ReadCRLF (buffer, ref offset, size);
if (state == State.BodyFinished)
return;
sawCR = false;
}
if (state == State.Trailer && offset < size) {
state = ReadTrailer (buffer, ref offset, size);
if (state == State.Trailer)
return;
saved.Length = 0;
sawCR = false;
gotit = false;
}
if (offset < size)
InternalWrite (buffer, ref offset, size);
}
State ReadBody (byte [] buffer, ref int offset, int size)
{
if (chunkSize == 0)
return State.BodyFinished;
int diff = size - offset;
if (diff + chunkRead > chunkSize)
diff = chunkSize - chunkRead;
byte [] chunk = new byte [diff];
Buffer.BlockCopy (buffer, offset, chunk, 0, diff);
chunks.Add (new Chunk (chunk));
offset += diff;
chunkRead += diff;
return (chunkRead == chunkSize) ? State.BodyFinished : State.Body;
}
State ReadCRLF (byte [] buffer, ref int offset, int size)
{
if (!sawCR) {
if ((char) buffer [offset++] != '\r') if ((char) buffer [offset++] != '\r')
ThrowProtocolViolation ("Expecting \\r."); throwProtocolViolation ("Expecting \\r.");
sawCR = true; _sawCR = true;
if (offset == size) if (offset == size)
return State.BodyFinished; return InputChunkState.BodyFinished;
} }
if (sawCR && (char) buffer [offset++] != '\n') if ((char) buffer [offset++] != '\n')
ThrowProtocolViolation ("Expecting \\n."); throwProtocolViolation ("Expecting \\n.");
return State.None; return InputChunkState.None;
} }
int ReadFromChunks (byte [] buffer, int offset, int size) private int readFromChunks (byte [] buffer, int offset, int size)
{ {
int count = chunks.Count; var count = _chunks.Count;
int nread = 0; var nread = 0;
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
var chunk = chunks [i]; var chunk = _chunks [i];
if (chunk == null) if (chunk == null)
continue; continue;
if (chunk.Offset == chunk.Bytes.Length) { if (chunk.Offset == chunk.Length) {
chunks [i] = null; _chunks [i] = null;
continue; continue;
} }
@ -268,23 +147,23 @@ namespace WebSocketSharp.Net {
return nread; return nread;
} }
State ReadTrailer (byte [] buffer, ref int offset, int size) private InputChunkState readTrailer (byte [] buffer, ref int offset, int size)
{ {
char c = '\0'; var c = '\0';
// short path // Short path
if (trailerState == 2 && (char) buffer [offset] == '\r' && saved.Length == 0) { if (_trailerState == 2 && (char) buffer [offset] == '\r' && _saved.Length == 0) {
offset++; offset++;
if (offset < size && (char) buffer [offset] == '\n') { if (offset < size && (char) buffer [offset] == '\n') {
offset++; offset++;
return State.None; return InputChunkState.None;
} }
offset--; offset--;
} }
int st = trailerState; var st = _trailerState;
string stString = "\r\n\r"; var stString = "\r\n\r";
while (offset < size && st < 4) { while (offset < size && st < 4) {
c = (char) buffer [offset++]; c = (char) buffer [offset++];
if ((st == 0 || st == 2) && c == '\r') { if ((st == 0 || st == 2) && c == '\r') {
@ -298,42 +177,161 @@ namespace WebSocketSharp.Net {
} }
if (st > 0) { if (st > 0) {
saved.Append (stString.Substring (0, saved.Length == 0? st-2: st)); _saved.Append (stString.Substring (0, _saved.Length == 0 ? st - 2 : st));
st = 0; st = 0;
if (saved.Length > 4196) if (_saved.Length > 4196)
ThrowProtocolViolation ("Error reading trailer (too long)."); throwProtocolViolation ("Error reading trailer (too long).");
} }
} }
if (st < 4) { if (st < 4) {
trailerState = st; _trailerState = st;
if (offset < size) if (offset < size)
ThrowProtocolViolation ("Error reading trailer."); throwProtocolViolation ("Error reading trailer.");
return State.Trailer; return InputChunkState.Trailer;
} }
var reader = new StringReader (saved.ToString ()); var reader = new StringReader (_saved.ToString ());
string line; string line;
while ((line = reader.ReadLine ()) != null && line != "") while ((line = reader.ReadLine ()) != null && line != "")
headers.Add (line); _headers.Add (line);
return State.None; return InputChunkState.None;
} }
static string RemoveChunkExtension (string input) private static string removeChunkExtension (string input)
{ {
int idx = input.IndexOf (';'); var idx = input.IndexOf (';');
if (idx == -1) return idx > -1
return input; ? input.Substring (0, idx)
: input;
return input.Substring (0, idx);
} }
static void ThrowProtocolViolation (string message) private InputChunkState setChunkSize (byte [] buffer, ref int offset, int size)
{ {
var we = new WebException (message, null, WebExceptionStatus.ServerProtocolViolation, null); var c = '\0';
throw we; while (offset < size) {
c = (char) buffer [offset++];
if (c == '\r') {
if (_sawCR)
throwProtocolViolation ("2 CR found.");
_sawCR = true;
continue;
}
if (_sawCR && c == '\n')
break;
if (c == ' ')
_gotit = true;
if (!_gotit)
_saved.Append (c);
if (_saved.Length > 20)
throwProtocolViolation ("Chunk size too long.");
}
if (!_sawCR || c != '\n') {
if (offset < size)
throwProtocolViolation ("Missing \\n.");
try {
if (_saved.Length > 0)
_chunkSize = Int32.Parse (
removeChunkExtension (_saved.ToString ()), NumberStyles.HexNumber);
}
catch {
throwProtocolViolation ("Cannot parse chunk size.");
}
return InputChunkState.None;
}
_chunkRead = 0;
try {
_chunkSize = Int32.Parse (
removeChunkExtension (_saved.ToString ()), NumberStyles.HexNumber);
}
catch {
throwProtocolViolation ("Cannot parse chunk size.");
}
if (_chunkSize == 0) {
_trailerState = 2;
return InputChunkState.Trailer;
}
return InputChunkState.Body;
}
private static void throwProtocolViolation (string message)
{
var ex = new WebException (message, null, WebExceptionStatus.ServerProtocolViolation, null);
throw ex;
}
private void write (byte [] buffer, ref int offset, int size)
{
if (_state == InputChunkState.None) {
_state = setChunkSize (buffer, ref offset, size);
if (_state == InputChunkState.None)
return;
_saved.Length = 0;
_sawCR = false;
_gotit = false;
}
if (_state == InputChunkState.Body && offset < size) {
_state = writeBody (buffer, ref offset, size);
if (_state == InputChunkState.Body)
return;
}
if (_state == InputChunkState.BodyFinished && offset < size) {
_state = readCRLF (buffer, ref offset, size);
if (_state == InputChunkState.BodyFinished)
return;
_sawCR = false;
}
if (_state == InputChunkState.Trailer && offset < size) {
_state = readTrailer (buffer, ref offset, size);
if (_state == InputChunkState.Trailer)
return;
_saved.Length = 0;
_sawCR = false;
_gotit = false;
}
if (offset < size)
write (buffer, ref offset, size);
}
private InputChunkState writeBody (byte [] buffer, ref int offset, int size)
{
if (_chunkSize == 0)
return InputChunkState.BodyFinished;
var diff = size - offset;
if (diff + _chunkRead > _chunkSize)
diff = _chunkSize - _chunkRead;
var body = new byte [diff];
Buffer.BlockCopy (buffer, offset, body, 0, diff);
_chunks.Add (new Chunk (body));
offset += diff;
_chunkRead += diff;
return _chunkRead == _chunkSize
? InputChunkState.BodyFinished
: InputChunkState.Body;
} }
#endregion #endregion
@ -342,19 +340,19 @@ namespace WebSocketSharp.Net {
public int Read (byte [] buffer, int offset, int size) public int Read (byte [] buffer, int offset, int size)
{ {
return ReadFromChunks (buffer, offset, size); return readFromChunks (buffer, offset, size);
} }
public void ResetBuffer () public void ResetBuffer ()
{ {
chunkSize = -1; _chunkSize = -1;
chunkRead = 0; _chunkRead = 0;
chunks.Clear (); _chunks.Clear ();
} }
public void Write (byte [] buffer, int offset, int size) public void Write (byte [] buffer, int offset, int size)
{ {
InternalWrite (buffer, ref offset, size); write (buffer, ref offset, size);
} }
public void WriteAndReadBack (byte [] buffer, int offset, int size, ref int read) public void WriteAndReadBack (byte [] buffer, int offset, int size, ref int read)
@ -362,7 +360,7 @@ namespace WebSocketSharp.Net {
if (offset + read > 0) if (offset + read > 0)
Write (buffer, offset, offset + read); Write (buffer, offset, offset + read);
read = Read (buffer, offset, size); read = readFromChunks (buffer, offset, size);
} }
#endregion #endregion

View File

@ -0,0 +1,51 @@
#region License
/*
* InputChunkState.cs
*
* This code is derived from System.Net.ChunkStream.cs of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2003 Ximian, Inc (http://www.ximian.com)
* Copyright (c) 2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
*/
#endregion
using System;
namespace WebSocketSharp.Net
{
internal enum InputChunkState
{
None,
Body,
BodyFinished,
Trailer
}
}

View File

@ -132,6 +132,8 @@
<Compile Include="Net\LineState.cs" /> <Compile Include="Net\LineState.cs" />
<Compile Include="WebSocketStream.cs" /> <Compile Include="WebSocketStream.cs" />
<Compile Include="Net\ReadBufferState.cs" /> <Compile Include="Net\ReadBufferState.cs" />
<Compile Include="Net\Chunk.cs" />
<Compile Include="Net\InputChunkState.cs" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup> <ItemGroup>