jellyfin/SocketHttpListener/Net/HttpConnection.cs

536 lines
16 KiB
C#
Raw Normal View History

2016-11-11 19:55:12 +00:00
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using MediaBrowser.Model.Cryptography;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Net;
2017-05-09 18:51:26 +00:00
using MediaBrowser.Model.System;
2016-11-11 19:55:12 +00:00
using MediaBrowser.Model.Text;
using SocketHttpListener.Primitives;
namespace SocketHttpListener.Net
{
sealed class HttpConnection
{
2017-05-25 13:00:14 +00:00
private static AsyncCallback s_onreadCallback = new AsyncCallback(OnRead);
2016-11-11 19:55:12 +00:00
const int BufferSize = 8192;
2017-05-25 13:00:14 +00:00
IAcceptSocket _socket;
Stream _stream;
EndPointListener _epl;
MemoryStream _memoryStream;
byte[] _buffer;
HttpListenerContext _context;
StringBuilder _currentLine;
ListenerPrefix _prefix;
HttpRequestStream _requestStream;
Stream _responseStream;
bool _chunked;
int _reuses;
bool _contextBound;
2016-11-11 19:55:12 +00:00
bool secure;
2017-05-25 13:00:14 +00:00
int _timeout = 300000; // 90k ms for first request, 15k ms from then on
2016-11-11 19:55:12 +00:00
IpEndPointInfo local_ep;
2017-05-25 13:00:14 +00:00
HttpListener _lastListener;
2016-11-11 19:55:12 +00:00
int[] client_cert_errors;
ICertificate cert;
Stream ssl_stream;
2017-03-12 19:27:26 +00:00
private readonly ILogger _logger;
2016-11-11 19:55:12 +00:00
private readonly ICryptoProvider _cryptoProvider;
private readonly IMemoryStreamFactory _memoryStreamFactory;
private readonly ITextEncoding _textEncoding;
private readonly IStreamFactory _streamFactory;
2017-03-12 19:27:26 +00:00
private readonly IFileSystem _fileSystem;
2017-05-09 18:51:26 +00:00
private readonly IEnvironmentInfo _environment;
2016-11-11 19:55:12 +00:00
2017-05-25 13:00:14 +00:00
private HttpConnection(ILogger logger, IAcceptSocket socket, EndPointListener epl, bool secure, ICertificate cert, ICryptoProvider cryptoProvider, IStreamFactory streamFactory, IMemoryStreamFactory memoryStreamFactory, ITextEncoding textEncoding, IFileSystem fileSystem, IEnvironmentInfo environment)
2016-11-11 19:55:12 +00:00
{
_logger = logger;
2017-05-25 13:00:14 +00:00
this._socket = socket;
this._epl = epl;
2016-11-11 19:55:12 +00:00
this.secure = secure;
this.cert = cert;
_cryptoProvider = cryptoProvider;
_memoryStreamFactory = memoryStreamFactory;
_textEncoding = textEncoding;
2017-03-12 19:27:26 +00:00
_fileSystem = fileSystem;
2017-05-09 18:51:26 +00:00
_environment = environment;
2016-11-11 19:55:12 +00:00
_streamFactory = streamFactory;
}
private async Task InitStream()
{
if (secure == false)
{
2017-05-25 13:00:14 +00:00
_stream = _streamFactory.CreateNetworkStream(_socket, false);
2016-11-11 19:55:12 +00:00
}
else
{
2017-05-25 13:00:14 +00:00
//ssl_stream = _epl.Listener.CreateSslStream(new NetworkStream(_socket, false), false, (t, c, ch, e) =>
2016-11-11 19:55:12 +00:00
//{
// if (c == null)
// return true;
// var c2 = c as X509Certificate2;
// if (c2 == null)
// c2 = new X509Certificate2(c.GetRawCertData());
// client_cert = c2;
// client_cert_errors = new int[] { (int)e };
// return true;
//});
2017-05-25 13:00:14 +00:00
//_stream = ssl_stream.AuthenticatedStream;
2016-11-11 19:55:12 +00:00
2017-05-25 13:00:14 +00:00
ssl_stream = _streamFactory.CreateSslStream(_streamFactory.CreateNetworkStream(_socket, false), false);
2016-11-11 19:55:12 +00:00
await _streamFactory.AuthenticateSslStreamAsServer(ssl_stream, cert).ConfigureAwait(false);
2017-05-25 13:00:14 +00:00
_stream = ssl_stream;
2016-11-11 19:55:12 +00:00
}
Init();
}
2017-05-09 18:51:26 +00:00
public static async Task<HttpConnection> Create(ILogger logger, IAcceptSocket sock, EndPointListener epl, bool secure, ICertificate cert, ICryptoProvider cryptoProvider, IStreamFactory streamFactory, IMemoryStreamFactory memoryStreamFactory, ITextEncoding textEncoding, IFileSystem fileSystem, IEnvironmentInfo environment)
2016-11-11 19:55:12 +00:00
{
2017-05-09 18:51:26 +00:00
var connection = new HttpConnection(logger, sock, epl, secure, cert, cryptoProvider, streamFactory, memoryStreamFactory, textEncoding, fileSystem, environment);
2016-11-11 19:55:12 +00:00
await connection.InitStream().ConfigureAwait(false);
return connection;
}
public Stream Stream
{
get
{
2017-05-25 13:00:14 +00:00
return _stream;
2016-11-11 19:55:12 +00:00
}
}
internal int[] ClientCertificateErrors
{
get { return client_cert_errors; }
}
void Init()
{
2017-05-25 13:00:14 +00:00
_contextBound = false;
_requestStream = null;
_responseStream = null;
_prefix = null;
_chunked = false;
_memoryStream = new MemoryStream();
_position = 0;
_inputState = InputState.RequestLine;
_lineState = LineState.None;
_context = new HttpListenerContext(this, _logger, _cryptoProvider, _memoryStreamFactory, _textEncoding, _fileSystem);
2016-11-11 19:55:12 +00:00
}
public bool IsClosed
{
2017-05-25 13:00:14 +00:00
get { return (_socket == null); }
2016-11-11 19:55:12 +00:00
}
public int Reuses
{
2017-05-25 13:00:14 +00:00
get { return _reuses; }
2016-11-11 19:55:12 +00:00
}
public IpEndPointInfo LocalEndPoint
{
get
{
if (local_ep != null)
return local_ep;
2017-05-25 13:00:14 +00:00
local_ep = (IpEndPointInfo)_socket.LocalEndPoint;
2016-11-11 19:55:12 +00:00
return local_ep;
}
}
public IpEndPointInfo RemoteEndPoint
{
2017-05-25 13:00:14 +00:00
get { return (IpEndPointInfo)_socket.RemoteEndPoint; }
2016-11-11 19:55:12 +00:00
}
public bool IsSecure
{
get { return secure; }
}
public ListenerPrefix Prefix
{
2017-05-25 13:00:14 +00:00
get { return _prefix; }
set { _prefix = value; }
2016-11-11 19:55:12 +00:00
}
2017-05-25 13:00:14 +00:00
public void BeginReadRequest()
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
if (_buffer == null)
_buffer = new byte[BufferSize];
2016-11-11 19:55:12 +00:00
try
{
2017-05-25 13:00:14 +00:00
if (_reuses == 1)
_timeout = 15000;
//_timer.Change(_timeout, Timeout.Infinite);
_stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this);
2016-11-11 19:55:12 +00:00
}
2017-05-25 13:00:14 +00:00
catch
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
//_timer.Change(Timeout.Infinite, Timeout.Infinite);
CloseSocket();
Unbind();
2016-11-11 19:55:12 +00:00
}
}
2017-05-24 19:12:55 +00:00
public HttpRequestStream GetRequestStream(bool chunked, long contentlength)
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
if (_requestStream == null)
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
byte[] buffer = _memoryStream.GetBuffer();
int length = (int)_memoryStream.Length;
_memoryStream = null;
2016-11-11 19:55:12 +00:00
if (chunked)
{
2017-05-25 13:00:14 +00:00
_chunked = true;
//_context.Response.SendChunked = true;
_requestStream = new ChunkedInputStream(_context, _stream, buffer, _position, length - _position);
2016-11-11 19:55:12 +00:00
}
else
{
2017-05-25 13:00:14 +00:00
_requestStream = new HttpRequestStream(_stream, buffer, _position, length - _position, contentlength);
2016-11-11 19:55:12 +00:00
}
}
2017-05-25 13:00:14 +00:00
return _requestStream;
2016-11-11 19:55:12 +00:00
}
2016-11-13 00:30:03 +00:00
public Stream GetResponseStream(bool isExpect100Continue = false)
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
// TODO: can we get this _stream before reading the input?
if (_responseStream == null)
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
var supportsDirectSocketAccess = !_context.Response.SendChunked && !isExpect100Continue && !secure;
2017-03-12 19:27:26 +00:00
2017-05-25 13:00:14 +00:00
_responseStream = new HttpResponseStream(_stream, _context.Response, false, _memoryStreamFactory, _socket, supportsDirectSocketAccess, _environment, _fileSystem, _logger);
2016-11-11 19:55:12 +00:00
}
2017-05-25 13:00:14 +00:00
return _responseStream;
2016-11-11 19:55:12 +00:00
}
2017-05-25 13:00:14 +00:00
private static void OnRead(IAsyncResult ares)
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
HttpConnection cnc = (HttpConnection)ares.AsyncState;
cnc.OnReadInternal(ares);
}
private void OnReadInternal(IAsyncResult ares)
{
//_timer.Change(Timeout.Infinite, Timeout.Infinite);
int nread = -1;
try
{
nread = _stream.EndRead(ares);
_memoryStream.Write(_buffer, 0, nread);
if (_memoryStream.Length > 32768)
{
SendError("Bad Request", 400);
Close(true);
return;
}
}
catch
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
if (_memoryStream != null && _memoryStream.Length > 0)
SendError();
if (_socket != null)
{
CloseSocket();
Unbind();
}
2016-11-11 19:55:12 +00:00
return;
}
if (nread == 0)
{
CloseSocket();
Unbind();
return;
}
2017-05-25 13:00:14 +00:00
if (ProcessInput(_memoryStream))
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
if (!_context.HaveError)
_context.Request.FinishInitialization();
2016-11-11 19:55:12 +00:00
2017-05-25 13:00:14 +00:00
if (_context.HaveError)
2016-11-11 19:55:12 +00:00
{
SendError();
Close(true);
return;
}
2017-05-25 13:00:14 +00:00
if (!_epl.BindContext(_context))
2016-11-11 19:55:12 +00:00
{
SendError("Invalid host", 400);
Close(true);
return;
}
2017-05-25 13:00:14 +00:00
HttpListener listener = _epl.Listener;
if (_lastListener != listener)
2016-11-11 19:55:12 +00:00
{
RemoveConnection();
listener.AddConnection(this);
2017-05-25 13:00:14 +00:00
_lastListener = listener;
2016-11-11 19:55:12 +00:00
}
2017-05-25 13:00:14 +00:00
_contextBound = true;
listener.RegisterContext(_context);
2016-11-11 19:55:12 +00:00
return;
}
2017-05-25 13:00:14 +00:00
_stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this);
2016-11-11 19:55:12 +00:00
}
2017-05-25 13:00:14 +00:00
private void RemoveConnection()
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
if (_lastListener == null)
_epl.RemoveConnection(this);
2016-11-11 19:55:12 +00:00
else
2017-05-25 13:00:14 +00:00
_lastListener.RemoveConnection(this);
2016-11-11 19:55:12 +00:00
}
2017-05-25 13:00:14 +00:00
private enum InputState
2016-11-11 19:55:12 +00:00
{
RequestLine,
Headers
}
2017-05-25 13:00:14 +00:00
private enum LineState
2016-11-11 19:55:12 +00:00
{
None,
CR,
LF
}
2017-05-25 13:00:14 +00:00
InputState _inputState = InputState.RequestLine;
LineState _lineState = LineState.None;
int _position;
2016-11-11 19:55:12 +00:00
// true -> done processing
// false -> need more input
2017-05-25 13:00:14 +00:00
private bool ProcessInput(MemoryStream ms)
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
byte[] buffer = ms.GetBuffer();
2016-11-11 19:55:12 +00:00
int len = (int)ms.Length;
int used = 0;
string line;
while (true)
{
2017-05-25 13:00:14 +00:00
if (_context.HaveError)
2016-11-11 19:55:12 +00:00
return true;
2017-05-25 13:00:14 +00:00
if (_position >= len)
2016-11-11 19:55:12 +00:00
break;
try
{
2017-05-25 13:00:14 +00:00
line = ReadLine(buffer, _position, len - _position, ref used);
_position += used;
2016-11-11 19:55:12 +00:00
}
catch
{
2017-05-25 13:00:14 +00:00
_context.ErrorMessage = "Bad request";
_context.ErrorStatus = 400;
2016-11-11 19:55:12 +00:00
return true;
}
if (line == null)
break;
if (line == "")
{
2017-05-25 13:00:14 +00:00
if (_inputState == InputState.RequestLine)
2016-11-11 19:55:12 +00:00
continue;
2017-05-25 13:00:14 +00:00
_currentLine = null;
2016-11-11 19:55:12 +00:00
ms = null;
return true;
}
2017-05-25 13:00:14 +00:00
if (_inputState == InputState.RequestLine)
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
_context.Request.SetRequestLine(line);
_inputState = InputState.Headers;
2016-11-11 19:55:12 +00:00
}
else
{
try
{
2017-05-25 13:00:14 +00:00
_context.Request.AddHeader(line);
2016-11-11 19:55:12 +00:00
}
catch (Exception e)
{
2017-05-25 13:00:14 +00:00
_context.ErrorMessage = e.Message;
_context.ErrorStatus = 400;
2016-11-11 19:55:12 +00:00
return true;
}
}
}
if (used == len)
{
ms.SetLength(0);
2017-05-25 13:00:14 +00:00
_position = 0;
2016-11-11 19:55:12 +00:00
}
return false;
}
2017-05-25 13:00:14 +00:00
private string ReadLine(byte[] buffer, int offset, int len, ref int used)
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
if (_currentLine == null)
_currentLine = new StringBuilder(128);
2016-11-11 19:55:12 +00:00
int last = offset + len;
used = 0;
2017-05-25 13:00:14 +00:00
for (int i = offset; i < last && _lineState != LineState.LF; i++)
2016-11-11 19:55:12 +00:00
{
used++;
byte b = buffer[i];
if (b == 13)
{
2017-05-25 13:00:14 +00:00
_lineState = LineState.CR;
2016-11-11 19:55:12 +00:00
}
else if (b == 10)
{
2017-05-25 13:00:14 +00:00
_lineState = LineState.LF;
2016-11-11 19:55:12 +00:00
}
else
{
2017-05-25 13:00:14 +00:00
_currentLine.Append((char)b);
2016-11-11 19:55:12 +00:00
}
}
string result = null;
2017-05-25 13:00:14 +00:00
if (_lineState == LineState.LF)
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
_lineState = LineState.None;
result = _currentLine.ToString();
_currentLine.Length = 0;
2016-11-11 19:55:12 +00:00
}
return result;
}
public void SendError(string msg, int status)
{
try
{
2017-05-25 13:00:14 +00:00
HttpListenerResponse response = _context.Response;
2016-11-11 19:55:12 +00:00
response.StatusCode = status;
response.ContentType = "text/html";
string description = HttpListenerResponse.GetStatusDescription(status);
string str;
if (msg != null)
2017-05-25 13:00:14 +00:00
str = string.Format("<h1>{0} ({1})</h1>", description, msg);
2016-11-11 19:55:12 +00:00
else
2017-05-25 13:00:14 +00:00
str = string.Format("<h1>{0}</h1>", description);
2016-11-11 19:55:12 +00:00
2017-05-25 13:00:14 +00:00
byte[] error = Encoding.Default.GetBytes(str);
response.Close(error, false);
2016-11-11 19:55:12 +00:00
}
catch
{
// response was already closed
}
}
public void SendError()
{
2017-05-25 13:00:14 +00:00
SendError(_context.ErrorMessage, _context.ErrorStatus);
2016-11-11 19:55:12 +00:00
}
2017-05-25 13:00:14 +00:00
private void Unbind()
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
if (_contextBound)
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
_epl.UnbindContext(_context);
_contextBound = false;
2016-11-11 19:55:12 +00:00
}
}
public void Close()
{
Close(false);
}
private void CloseSocket()
{
2017-05-25 13:00:14 +00:00
if (_socket == null)
2016-11-11 19:55:12 +00:00
return;
try
{
2017-05-25 13:00:14 +00:00
_socket.Close();
2016-11-11 19:55:12 +00:00
}
2017-05-25 13:00:14 +00:00
catch { }
2016-11-11 19:55:12 +00:00
finally
{
2017-05-25 13:00:14 +00:00
_socket = null;
2016-11-11 19:55:12 +00:00
}
2017-05-25 13:00:14 +00:00
2016-11-11 19:55:12 +00:00
RemoveConnection();
}
2017-05-25 13:00:14 +00:00
internal void Close(bool force)
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
if (_socket != null)
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
Stream st = GetResponseStream();
if (st != null)
st.Close();
2016-11-11 19:55:12 +00:00
2017-05-25 13:00:14 +00:00
_responseStream = null;
2016-11-11 19:55:12 +00:00
}
2017-05-25 13:00:14 +00:00
if (_socket != null)
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
force |= !_context.Request.KeepAlive;
if (!force)
force = (string.Equals(_context.Response.Headers["connection"], "close", StringComparison.OrdinalIgnoreCase));
if (!force && _context.Request.FlushInput())
2016-11-11 19:55:12 +00:00
{
2017-05-25 13:00:14 +00:00
if (_chunked && _context.Response.ForceCloseChunked == false)
{
// Don't close. Keep working.
_reuses++;
Unbind();
Init();
BeginReadRequest();
return;
}
_reuses++;
2016-11-11 19:55:12 +00:00
Unbind();
Init();
BeginReadRequest();
return;
}
2017-05-25 13:00:14 +00:00
IAcceptSocket s = _socket;
_socket = null;
2016-11-11 19:55:12 +00:00
try
{
if (s != null)
s.Shutdown(true);
}
catch
{
}
finally
{
if (s != null)
s.Close();
}
Unbind();
RemoveConnection();
return;
}
}
}
}