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,337 +44,325 @@ 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 { #region Private Fields
None, private int _chunkRead;
Body, private int _chunkSize;
BodyFinished, private List<Chunk> _chunks;
Trailer private bool _gotit;
} private WebHeaderCollection _headers;
private StringBuilder _saved;
class Chunk { private bool _sawCR;
private InputChunkState _state;
public byte [] Bytes; private int _trailerState;
public int Offset;
#endregion
public Chunk (byte [] chunk)
{ #region Public Constructors
this.Bytes = chunk;
} public ChunkStream (byte [] buffer, int offset, int size, WebHeaderCollection headers)
: this (headers)
public int Read (byte [] buffer, int offset, int size) {
{ Write (buffer, offset, size);
int nread = (size > Bytes.Length - Offset) ? Bytes.Length - Offset : size; }
Buffer.BlockCopy (Bytes, Offset, buffer, offset, nread);
Offset += nread; public ChunkStream (WebHeaderCollection headers)
return nread; {
} _headers = headers;
} _chunkSize = -1;
_chunks = new List<Chunk> ();
#region Private Fields _saved = new StringBuilder ();
}
int chunkRead;
List<Chunk> chunks; #endregion
int chunkSize;
bool gotit; #region Internal Properties
StringBuilder saved;
bool sawCR; internal WebHeaderCollection Headers {
State state; get {
int trailerState; return _headers;
}
#endregion }
#region Internal Fields #endregion
internal WebHeaderCollection headers; #region Public Properties
#endregion public int ChunkLeft {
get {
#region Constructors return _chunkSize - _chunkRead;
}
public ChunkStream (byte [] buffer, int offset, int size, WebHeaderCollection headers) }
: this (headers)
{ public bool WantMore {
Write (buffer, offset, size); get {
} return _chunkRead != _chunkSize || _chunkSize != 0 || _state != InputChunkState.None;
}
public ChunkStream (WebHeaderCollection headers) }
{
this.headers = headers; #endregion
saved = new StringBuilder ();
chunks = new List<Chunk> (); #region Private Methods
chunkSize = -1;
} private InputChunkState readCRLF (byte [] buffer, ref int offset, int size)
{
#endregion if (!_sawCR) {
if ((char) buffer [offset++] != '\r')
#region Properties throwProtocolViolation ("Expecting \\r.");
public int ChunkLeft { _sawCR = true;
get { return chunkSize - chunkRead; } if (offset == size)
} return InputChunkState.BodyFinished;
}
public bool WantMore {
get { return (chunkRead != chunkSize || chunkSize != 0 || state != State.None); } if ((char) buffer [offset++] != '\n')
} throwProtocolViolation ("Expecting \\n.");
#endregion return InputChunkState.None;
}
#region Private Methods
private int readFromChunks (byte [] buffer, int offset, int size)
State GetChunkSize (byte [] buffer, ref int offset, int size) {
{ var count = _chunks.Count;
char c = '\0'; var nread = 0;
while (offset < size) { for (int i = 0; i < count; i++) {
c = (char) buffer [offset++]; var chunk = _chunks [i];
if (c == '\r') { if (chunk == null)
if (sawCR) continue;
ThrowProtocolViolation ("2 CR found.");
if (chunk.Offset == chunk.Length) {
sawCR = true; _chunks [i] = null;
continue; continue;
} }
if (sawCR && c == '\n') nread += chunk.Read (buffer, offset + nread, size - nread);
break; if (nread == size)
break;
if (c == ' ') }
gotit = true;
return nread;
if (!gotit) }
saved.Append (c);
private InputChunkState readTrailer (byte [] buffer, ref int offset, int size)
if (saved.Length > 20) {
ThrowProtocolViolation ("Chunk size too long."); var c = '\0';
}
// Short path
if (!sawCR || c != '\n') { if (_trailerState == 2 && (char) buffer [offset] == '\r' && _saved.Length == 0) {
if (offset < size) offset++;
ThrowProtocolViolation ("Missing \\n."); if (offset < size && (char) buffer [offset] == '\n') {
offset++;
try { return InputChunkState.None;
if (saved.Length > 0) { }
chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber);
} offset--;
} catch (Exception) { }
ThrowProtocolViolation ("Cannot parse chunk size.");
} var st = _trailerState;
var stString = "\r\n\r";
return State.None; while (offset < size && st < 4) {
} c = (char) buffer [offset++];
if ((st == 0 || st == 2) && c == '\r') {
chunkRead = 0; st++;
try { continue;
chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber); }
} catch (Exception) {
ThrowProtocolViolation ("Cannot parse chunk size."); if ((st == 1 || st == 3) && c == '\n') {
} st++;
continue;
if (chunkSize == 0) { }
trailerState = 2;
return State.Trailer; if (st > 0) {
} _saved.Append (stString.Substring (0, _saved.Length == 0 ? st - 2 : st));
st = 0;
return State.Body; if (_saved.Length > 4196)
} throwProtocolViolation ("Error reading trailer (too long).");
}
void InternalWrite (byte [] buffer, ref int offset, int size) }
{
if (state == State.None) { if (st < 4) {
state = GetChunkSize (buffer, ref offset, size); _trailerState = st;
if (state == State.None) if (offset < size)
return; throwProtocolViolation ("Error reading trailer.");
saved.Length = 0; return InputChunkState.Trailer;
sawCR = false; }
gotit = false;
} var reader = new StringReader (_saved.ToString ());
string line;
if (state == State.Body && offset < size) { while ((line = reader.ReadLine ()) != null && line != "")
state = ReadBody (buffer, ref offset, size); _headers.Add (line);
if (state == State.Body)
return; return InputChunkState.None;
} }
if (state == State.BodyFinished && offset < size) { private static string removeChunkExtension (string input)
state = ReadCRLF (buffer, ref offset, size); {
if (state == State.BodyFinished) var idx = input.IndexOf (';');
return; return idx > -1
? input.Substring (0, idx)
sawCR = false; : input;
} }
if (state == State.Trailer && offset < size) { private InputChunkState setChunkSize (byte [] buffer, ref int offset, int size)
state = ReadTrailer (buffer, ref offset, size); {
if (state == State.Trailer) var c = '\0';
return; while (offset < size) {
c = (char) buffer [offset++];
saved.Length = 0; if (c == '\r') {
sawCR = false; if (_sawCR)
gotit = false; throwProtocolViolation ("2 CR found.");
}
_sawCR = true;
if (offset < size) continue;
InternalWrite (buffer, ref offset, size); }
}
if (_sawCR && c == '\n')
State ReadBody (byte [] buffer, ref int offset, int size) break;
{
if (chunkSize == 0) if (c == ' ')
return State.BodyFinished; _gotit = true;
int diff = size - offset; if (!_gotit)
if (diff + chunkRead > chunkSize) _saved.Append (c);
diff = chunkSize - chunkRead;
if (_saved.Length > 20)
byte [] chunk = new byte [diff]; throwProtocolViolation ("Chunk size too long.");
Buffer.BlockCopy (buffer, offset, chunk, 0, diff); }
chunks.Add (new Chunk (chunk));
offset += diff; if (!_sawCR || c != '\n') {
chunkRead += diff; if (offset < size)
return (chunkRead == chunkSize) ? State.BodyFinished : State.Body; throwProtocolViolation ("Missing \\n.");
}
try {
State ReadCRLF (byte [] buffer, ref int offset, int size) if (_saved.Length > 0)
{ _chunkSize = Int32.Parse (
if (!sawCR) { removeChunkExtension (_saved.ToString ()), NumberStyles.HexNumber);
if ((char) buffer [offset++] != '\r') }
ThrowProtocolViolation ("Expecting \\r."); catch {
throwProtocolViolation ("Cannot parse chunk size.");
sawCR = true; }
if (offset == size)
return State.BodyFinished; return InputChunkState.None;
} }
if (sawCR && (char) buffer [offset++] != '\n') _chunkRead = 0;
ThrowProtocolViolation ("Expecting \\n."); try {
_chunkSize = Int32.Parse (
return State.None; removeChunkExtension (_saved.ToString ()), NumberStyles.HexNumber);
} }
catch {
int ReadFromChunks (byte [] buffer, int offset, int size) throwProtocolViolation ("Cannot parse chunk size.");
{ }
int count = chunks.Count;
int nread = 0; if (_chunkSize == 0) {
for (int i = 0; i < count; i++) { _trailerState = 2;
var chunk = chunks [i]; return InputChunkState.Trailer;
if (chunk == null) }
continue;
return InputChunkState.Body;
if (chunk.Offset == chunk.Bytes.Length) { }
chunks [i] = null;
continue; private static void throwProtocolViolation (string message)
} {
var ex = new WebException (message, null, WebExceptionStatus.ServerProtocolViolation, null);
nread += chunk.Read (buffer, offset + nread, size - nread); throw ex;
if (nread == size) }
break;
} private void write (byte [] buffer, ref int offset, int size)
{
return nread; if (_state == InputChunkState.None) {
} _state = setChunkSize (buffer, ref offset, size);
if (_state == InputChunkState.None)
State ReadTrailer (byte [] buffer, ref int offset, int size) return;
{
char c = '\0'; _saved.Length = 0;
_sawCR = false;
// short path _gotit = false;
if (trailerState == 2 && (char) buffer [offset] == '\r' && saved.Length == 0) { }
offset++;
if (offset < size && (char) buffer [offset] == '\n') { if (_state == InputChunkState.Body && offset < size) {
offset++; _state = writeBody (buffer, ref offset, size);
return State.None; if (_state == InputChunkState.Body)
} return;
}
offset--;
} if (_state == InputChunkState.BodyFinished && offset < size) {
_state = readCRLF (buffer, ref offset, size);
int st = trailerState; if (_state == InputChunkState.BodyFinished)
string stString = "\r\n\r"; return;
while (offset < size && st < 4) {
c = (char) buffer [offset++]; _sawCR = false;
if ((st == 0 || st == 2) && c == '\r') { }
st++;
continue; if (_state == InputChunkState.Trailer && offset < size) {
} _state = readTrailer (buffer, ref offset, size);
if (_state == InputChunkState.Trailer)
if ((st == 1 || st == 3) && c == '\n') { return;
st++;
continue; _saved.Length = 0;
} _sawCR = false;
_gotit = false;
if (st > 0) { }
saved.Append (stString.Substring (0, saved.Length == 0? st-2: st));
st = 0; if (offset < size)
if (saved.Length > 4196) write (buffer, ref offset, size);
ThrowProtocolViolation ("Error reading trailer (too long)."); }
}
} private InputChunkState writeBody (byte [] buffer, ref int offset, int size)
{
if (st < 4) { if (_chunkSize == 0)
trailerState = st; return InputChunkState.BodyFinished;
if (offset < size)
ThrowProtocolViolation ("Error reading trailer."); var diff = size - offset;
if (diff + _chunkRead > _chunkSize)
return State.Trailer; diff = _chunkSize - _chunkRead;
}
var body = new byte [diff];
var reader = new StringReader (saved.ToString ()); Buffer.BlockCopy (buffer, offset, body, 0, diff);
string line; _chunks.Add (new Chunk (body));
while ((line = reader.ReadLine ()) != null && line != "")
headers.Add (line); offset += diff;
_chunkRead += diff;
return State.None;
} return _chunkRead == _chunkSize
? InputChunkState.BodyFinished
static string RemoveChunkExtension (string input) : InputChunkState.Body;
{ }
int idx = input.IndexOf (';');
if (idx == -1) #endregion
return input;
#region Public Methods
return input.Substring (0, idx);
} public int Read (byte [] buffer, int offset, int size)
{
static void ThrowProtocolViolation (string message) return readFromChunks (buffer, offset, size);
{ }
var we = new WebException (message, null, WebExceptionStatus.ServerProtocolViolation, null);
throw we; public void ResetBuffer ()
} {
_chunkSize = -1;
#endregion _chunkRead = 0;
_chunks.Clear ();
#region Public Methods }
public int Read (byte [] buffer, int offset, int size) public void Write (byte [] buffer, int offset, int size)
{ {
return ReadFromChunks (buffer, offset, size); write (buffer, ref offset, size);
} }
public void ResetBuffer () public void WriteAndReadBack (byte [] buffer, int offset, int size, ref int read)
{ {
chunkSize = -1; if (offset + read > 0)
chunkRead = 0; Write (buffer, offset, offset + read);
chunks.Clear ();
} read = readFromChunks (buffer, offset, size);
}
public void Write (byte [] buffer, int offset, int size)
{ #endregion
InternalWrite (buffer, ref offset, size); }
}
public void WriteAndReadBack (byte [] buffer, int offset, int size, ref int read)
{
if (offset + read > 0)
Write (buffer, offset, offset + read);
read = Read (buffer, offset, size);
}
#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>