jellyfin/SocketHttpListener/Net/ChunkStream.cs

396 lines
12 KiB
C#
Raw Normal View History

2016-11-11 19:55:12 +00:00
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
namespace SocketHttpListener.Net
{
2017-05-24 19:12:55 +00:00
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Net.ResponseStream
//
// Author:
2019-01-07 23:24:34 +00:00
// Gonzalo Paniagua Javier (gonzalo@novell.com)
2017-05-24 19:12:55 +00:00
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
//
// 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:
2019-01-07 23:24:34 +00:00
//
2017-05-24 19:12:55 +00:00
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
2019-01-07 23:24:34 +00:00
//
2017-05-24 19:12:55 +00:00
// 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.
//
internal sealed class ChunkStream
2016-11-11 19:55:12 +00:00
{
2017-05-24 19:12:55 +00:00
private enum State
2016-11-11 19:55:12 +00:00
{
None,
PartialSize,
Body,
BodyFinished,
Trailer
}
2017-05-24 19:12:55 +00:00
private class Chunk
2016-11-11 19:55:12 +00:00
{
public byte[] Bytes;
public int Offset;
public Chunk(byte[] chunk)
{
2017-05-24 19:12:55 +00:00
Bytes = chunk;
2016-11-11 19:55:12 +00:00
}
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;
}
}
2017-05-24 19:12:55 +00:00
internal WebHeaderCollection _headers;
private int _chunkSize;
private int _chunkRead;
private int _totalWritten;
private State _state;
private StringBuilder _saved;
private bool _sawCR;
private bool _gotit;
private int _trailerState;
private List<Chunk> _chunks;
2016-11-11 19:55:12 +00:00
public ChunkStream(WebHeaderCollection headers)
{
2017-05-24 19:12:55 +00:00
_headers = headers;
_saved = new StringBuilder();
_chunks = new List<Chunk>();
_chunkSize = -1;
_totalWritten = 0;
2016-11-11 19:55:12 +00:00
}
public void ResetBuffer()
{
2017-05-24 19:12:55 +00:00
_chunkSize = -1;
_chunkRead = 0;
_totalWritten = 0;
_chunks.Clear();
2016-11-11 19:55:12 +00:00
}
public int Read(byte[] buffer, int offset, int size)
{
return ReadFromChunks(buffer, offset, size);
}
2017-05-24 19:12:55 +00:00
private int ReadFromChunks(byte[] buffer, int offset, int size)
2016-11-11 19:55:12 +00:00
{
2017-05-24 19:12:55 +00:00
int count = _chunks.Count;
2016-11-11 19:55:12 +00:00
int nread = 0;
var chunksForRemoving = new List<Chunk>(count);
for (int i = 0; i < count; i++)
{
2017-05-24 19:12:55 +00:00
Chunk chunk = _chunks[i];
2016-11-11 19:55:12 +00:00
if (chunk.Offset == chunk.Bytes.Length)
{
chunksForRemoving.Add(chunk);
continue;
}
nread += chunk.Read(buffer, offset + nread, size - nread);
if (nread == size)
break;
}
foreach (var chunk in chunksForRemoving)
2017-05-24 19:12:55 +00:00
_chunks.Remove(chunk);
2016-11-11 19:55:12 +00:00
return nread;
}
public void Write(byte[] buffer, int offset, int size)
{
2017-06-21 14:50:54 +00:00
// Note, the logic here only works when offset is 0 here.
// Otherwise, it would treat "size" as the end offset instead of an actual byte count from offset.
2016-11-11 19:55:12 +00:00
if (offset < size)
InternalWrite(buffer, ref offset, size);
}
2017-05-24 19:12:55 +00:00
private void InternalWrite(byte[] buffer, ref int offset, int size)
2016-11-11 19:55:12 +00:00
{
2017-05-24 19:12:55 +00:00
if (_state == State.None || _state == State.PartialSize)
2016-11-11 19:55:12 +00:00
{
2017-05-24 19:12:55 +00:00
_state = GetChunkSize(buffer, ref offset, size);
if (_state == State.PartialSize)
2016-11-11 19:55:12 +00:00
return;
2017-05-24 19:12:55 +00:00
_saved.Length = 0;
_sawCR = false;
_gotit = false;
2016-11-11 19:55:12 +00:00
}
2017-05-24 19:12:55 +00:00
if (_state == State.Body && offset < size)
2016-11-11 19:55:12 +00:00
{
2017-05-24 19:12:55 +00:00
_state = ReadBody(buffer, ref offset, size);
if (_state == State.Body)
2016-11-11 19:55:12 +00:00
return;
}
2017-05-24 19:12:55 +00:00
if (_state == State.BodyFinished && offset < size)
2016-11-11 19:55:12 +00:00
{
2017-05-24 19:12:55 +00:00
_state = ReadCRLF(buffer, ref offset, size);
if (_state == State.BodyFinished)
2016-11-11 19:55:12 +00:00
return;
2017-05-24 19:12:55 +00:00
_sawCR = false;
2016-11-11 19:55:12 +00:00
}
2017-05-24 19:12:55 +00:00
if (_state == State.Trailer && offset < size)
2016-11-11 19:55:12 +00:00
{
2017-05-24 19:12:55 +00:00
_state = ReadTrailer(buffer, ref offset, size);
if (_state == State.Trailer)
2016-11-11 19:55:12 +00:00
return;
2017-05-24 19:12:55 +00:00
_saved.Length = 0;
_sawCR = false;
_gotit = false;
2016-11-11 19:55:12 +00:00
}
if (offset < size)
InternalWrite(buffer, ref offset, size);
}
public bool WantMore
{
2017-05-24 19:12:55 +00:00
get { return (_chunkRead != _chunkSize || _chunkSize != 0 || _state != State.None); }
2016-11-11 19:55:12 +00:00
}
public bool DataAvailable
{
get
{
2017-05-24 19:12:55 +00:00
int count = _chunks.Count;
2016-11-11 19:55:12 +00:00
for (int i = 0; i < count; i++)
{
2017-05-24 19:12:55 +00:00
Chunk ch = _chunks[i];
2016-11-11 19:55:12 +00:00
if (ch == null || ch.Bytes == null)
continue;
if (ch.Bytes.Length > 0 && ch.Offset < ch.Bytes.Length)
2017-05-24 19:12:55 +00:00
return (_state != State.Body);
2016-11-11 19:55:12 +00:00
}
return false;
}
}
public int TotalDataSize
{
2017-05-24 19:12:55 +00:00
get { return _totalWritten; }
2016-11-11 19:55:12 +00:00
}
public int ChunkLeft
{
2017-05-24 19:12:55 +00:00
get { return _chunkSize - _chunkRead; }
2016-11-11 19:55:12 +00:00
}
2017-05-24 19:12:55 +00:00
private State ReadBody(byte[] buffer, ref int offset, int size)
2016-11-11 19:55:12 +00:00
{
2017-05-24 19:12:55 +00:00
if (_chunkSize == 0)
2016-11-11 19:55:12 +00:00
return State.BodyFinished;
int diff = size - offset;
2017-05-24 19:12:55 +00:00
if (diff + _chunkRead > _chunkSize)
diff = _chunkSize - _chunkRead;
2016-11-11 19:55:12 +00:00
byte[] chunk = new byte[diff];
Buffer.BlockCopy(buffer, offset, chunk, 0, diff);
2017-05-24 19:12:55 +00:00
_chunks.Add(new Chunk(chunk));
2016-11-11 19:55:12 +00:00
offset += diff;
2017-05-24 19:12:55 +00:00
_chunkRead += diff;
_totalWritten += diff;
2016-11-11 19:55:12 +00:00
2017-05-24 19:12:55 +00:00
return (_chunkRead == _chunkSize) ? State.BodyFinished : State.Body;
2016-11-11 19:55:12 +00:00
}
2017-05-24 19:12:55 +00:00
private State GetChunkSize(byte[] buffer, ref int offset, int size)
2016-11-11 19:55:12 +00:00
{
2017-05-24 19:12:55 +00:00
_chunkRead = 0;
_chunkSize = 0;
2016-11-11 19:55:12 +00:00
char c = '\0';
while (offset < size)
{
c = (char)buffer[offset++];
if (c == '\r')
{
2017-05-24 19:12:55 +00:00
if (_sawCR)
2016-11-11 19:55:12 +00:00
ThrowProtocolViolation("2 CR found");
2017-05-24 19:12:55 +00:00
_sawCR = true;
2016-11-11 19:55:12 +00:00
continue;
}
2017-05-24 19:12:55 +00:00
if (_sawCR && c == '\n')
2016-11-11 19:55:12 +00:00
break;
if (c == ' ')
2017-05-24 19:12:55 +00:00
_gotit = true;
2016-11-11 19:55:12 +00:00
2017-05-24 19:12:55 +00:00
if (!_gotit)
_saved.Append(c);
2016-11-11 19:55:12 +00:00
2017-05-24 19:12:55 +00:00
if (_saved.Length > 20)
2016-11-11 19:55:12 +00:00
ThrowProtocolViolation("chunk size too long.");
}
2017-05-24 19:12:55 +00:00
if (!_sawCR || c != '\n')
2016-11-11 19:55:12 +00:00
{
if (offset < size)
ThrowProtocolViolation("Missing \\n");
try
{
2017-05-24 19:12:55 +00:00
if (_saved.Length > 0)
2016-11-11 19:55:12 +00:00
{
_chunkSize = int.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber);
2016-11-11 19:55:12 +00:00
}
}
catch (Exception)
{
ThrowProtocolViolation("Cannot parse chunk size.");
}
return State.PartialSize;
}
2017-05-24 19:12:55 +00:00
_chunkRead = 0;
2016-11-11 19:55:12 +00:00
try
{
_chunkSize = int.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber);
2016-11-11 19:55:12 +00:00
}
catch (Exception)
{
ThrowProtocolViolation("Cannot parse chunk size.");
}
2017-05-24 19:12:55 +00:00
if (_chunkSize == 0)
2016-11-11 19:55:12 +00:00
{
2017-05-24 19:12:55 +00:00
_trailerState = 2;
2016-11-11 19:55:12 +00:00
return State.Trailer;
}
return State.Body;
}
2017-05-24 19:12:55 +00:00
private static string RemoveChunkExtension(string input)
2016-11-11 19:55:12 +00:00
{
int idx = input.IndexOf(';');
if (idx == -1)
return input;
return input.Substring(0, idx);
}
2017-05-24 19:12:55 +00:00
private State ReadCRLF(byte[] buffer, ref int offset, int size)
2016-11-11 19:55:12 +00:00
{
2017-05-24 19:12:55 +00:00
if (!_sawCR)
2016-11-11 19:55:12 +00:00
{
if ((char)buffer[offset++] != '\r')
ThrowProtocolViolation("Expecting \\r");
2017-05-24 19:12:55 +00:00
_sawCR = true;
2016-11-11 19:55:12 +00:00
if (offset == size)
return State.BodyFinished;
}
2017-05-24 19:12:55 +00:00
if (_sawCR && (char)buffer[offset++] != '\n')
2016-11-11 19:55:12 +00:00
ThrowProtocolViolation("Expecting \\n");
return State.None;
}
2017-05-24 19:12:55 +00:00
private State ReadTrailer(byte[] buffer, ref int offset, int size)
2016-11-11 19:55:12 +00:00
{
char c = '\0';
// short path
2017-05-24 19:12:55 +00:00
if (_trailerState == 2 && (char)buffer[offset] == '\r' && _saved.Length == 0)
2016-11-11 19:55:12 +00:00
{
offset++;
if (offset < size && (char)buffer[offset] == '\n')
{
offset++;
return State.None;
}
offset--;
}
2017-05-24 19:12:55 +00:00
int st = _trailerState;
2016-11-11 19:55:12 +00:00
string stString = "\r\n\r";
while (offset < size && st < 4)
{
c = (char)buffer[offset++];
if ((st == 0 || st == 2) && c == '\r')
{
st++;
continue;
}
if ((st == 1 || st == 3) && c == '\n')
{
st++;
continue;
}
if (st > 0)
{
2017-05-24 19:12:55 +00:00
_saved.Append(stString.Substring(0, _saved.Length == 0 ? st - 2 : st));
2016-11-11 19:55:12 +00:00
st = 0;
2017-05-24 19:12:55 +00:00
if (_saved.Length > 4196)
2016-11-11 19:55:12 +00:00
ThrowProtocolViolation("Error reading trailer (too long).");
}
}
if (st < 4)
{
2017-05-24 19:12:55 +00:00
_trailerState = st;
2016-11-11 19:55:12 +00:00
if (offset < size)
ThrowProtocolViolation("Error reading trailer.");
return State.Trailer;
}
2017-05-24 19:12:55 +00:00
StringReader reader = new StringReader(_saved.ToString());
2016-11-11 19:55:12 +00:00
string line;
while ((line = reader.ReadLine()) != null && line != "")
2017-05-24 19:12:55 +00:00
_headers.Add(line);
2016-11-11 19:55:12 +00:00
return State.None;
}
2017-05-24 19:12:55 +00:00
private static void ThrowProtocolViolation(string message)
2016-11-11 19:55:12 +00:00
{
2017-05-24 19:12:55 +00:00
WebException we = new WebException(message, null, WebExceptionStatus.ServerProtocolViolation, null);
2016-11-11 19:55:12 +00:00
throw we;
}
}
}