Refactored some classes in WebSocketSharp.Net namespace
This commit is contained in:
parent
5a5874b90f
commit
11c576a8c7
@ -507,6 +507,19 @@ namespace WebSocketSharp {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal static string Unquote(this string value)
|
||||||
|
{
|
||||||
|
var start = value.IndexOf('\"');
|
||||||
|
var end = value.LastIndexOf('\"');
|
||||||
|
if (start < end)
|
||||||
|
{
|
||||||
|
value = value.Substring(start + 1, end - start - 1)
|
||||||
|
.Replace("\\\"", "\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
return value.Trim();
|
||||||
|
}
|
||||||
|
|
||||||
internal static void WriteBytes(this Stream stream, byte[] value)
|
internal static void WriteBytes(this Stream stream, byte[] value)
|
||||||
{
|
{
|
||||||
using (var input = new MemoryStream(value))
|
using (var input = new MemoryStream(value))
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
#region License
|
||||||
//
|
//
|
||||||
// HttpConnection.cs
|
// HttpConnection.cs
|
||||||
// Copied from System.Net.HttpConnection.cs
|
// Copied from System.Net.HttpConnection.cs
|
||||||
@ -6,7 +7,7 @@
|
|||||||
// Gonzalo Paniagua Javier (gonzalo@novell.com)
|
// Gonzalo Paniagua Javier (gonzalo@novell.com)
|
||||||
//
|
//
|
||||||
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
|
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
|
||||||
// Copyright (c) 2012 sta.blockhead (sta.blockhead@gmail.com)
|
// Copyright (c) 2012-2013 sta.blockhead (sta.blockhead@gmail.com)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining
|
// Permission is hereby granted, free of charge, to any person obtaining
|
||||||
// a copy of this software and associated documentation files (the
|
// a copy of this software and associated documentation files (the
|
||||||
@ -27,6 +28,7 @@
|
|||||||
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||||
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
//
|
//
|
||||||
|
#endregion
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
@ -41,7 +43,7 @@ using WebSocketSharp.Net.Security;
|
|||||||
|
|
||||||
namespace WebSocketSharp.Net {
|
namespace WebSocketSharp.Net {
|
||||||
|
|
||||||
sealed class HttpConnection {
|
internal sealed class HttpConnection {
|
||||||
|
|
||||||
#region Enums
|
#region Enums
|
||||||
|
|
||||||
@ -60,170 +62,176 @@ namespace WebSocketSharp.Net {
|
|||||||
|
|
||||||
#region Private Const Field
|
#region Private Const Field
|
||||||
|
|
||||||
const int BufferSize = 8192;
|
private const int BufferSize = 8192;
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region Private Static Field
|
|
||||||
|
|
||||||
static AsyncCallback onread_cb = new AsyncCallback (OnRead);
|
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Private Fields
|
#region Private Fields
|
||||||
|
|
||||||
byte [] buffer;
|
private byte [] _buffer;
|
||||||
bool chunked;
|
private bool _chunked;
|
||||||
HttpListenerContext context;
|
private HttpListenerContext _context;
|
||||||
bool context_bound;
|
private bool _contextWasBound;
|
||||||
StringBuilder current_line;
|
private StringBuilder _currentLine;
|
||||||
EndPointListener epl;
|
private EndPointListener _epListener;
|
||||||
InputState input_state;
|
private InputState _inputState;
|
||||||
RequestStream i_stream;
|
private RequestStream _inputStream;
|
||||||
AsymmetricAlgorithm key;
|
private AsymmetricAlgorithm _key;
|
||||||
HttpListener last_listener;
|
private HttpListener _lastListener;
|
||||||
LineState line_state;
|
private LineState _lineState;
|
||||||
// IPEndPoint local_ep; // never used
|
private ResponseStream _outputStream;
|
||||||
MemoryStream ms;
|
private int _position;
|
||||||
ResponseStream o_stream;
|
private ListenerPrefix _prefix;
|
||||||
int position;
|
private MemoryStream _requestBuffer;
|
||||||
ListenerPrefix prefix;
|
private int _reuses;
|
||||||
int reuses;
|
private bool _secure;
|
||||||
bool secure;
|
private Socket _socket;
|
||||||
Socket sock;
|
private Stream _stream;
|
||||||
Stream stream;
|
private int _timeout;
|
||||||
int s_timeout;
|
private Timer _timer;
|
||||||
Timer timer;
|
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Constructor
|
#region Public Constructors
|
||||||
|
|
||||||
public HttpConnection (
|
public HttpConnection (
|
||||||
Socket sock,
|
Socket socket,
|
||||||
EndPointListener epl,
|
EndPointListener listener,
|
||||||
bool secure,
|
bool secure,
|
||||||
X509Certificate2 cert,
|
X509Certificate2 cert,
|
||||||
AsymmetricAlgorithm key
|
AsymmetricAlgorithm key)
|
||||||
)
|
|
||||||
{
|
{
|
||||||
this.sock = sock;
|
_socket = socket;
|
||||||
this.epl = epl;
|
_epListener = listener;
|
||||||
this.secure = secure;
|
_secure = secure;
|
||||||
this.key = key;
|
_key = key;
|
||||||
// if (secure == false) {
|
|
||||||
// stream = new NetworkStream (sock, false);
|
var netStream = new NetworkStream (socket, false);
|
||||||
// } else {
|
|
||||||
// var ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, false);
|
|
||||||
// ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
|
|
||||||
// stream = ssl_stream;
|
|
||||||
// }
|
|
||||||
var net_stream = new NetworkStream (sock, false);
|
|
||||||
if (!secure) {
|
if (!secure) {
|
||||||
stream = net_stream;
|
_stream = netStream;
|
||||||
} else {
|
} else {
|
||||||
var ssl_stream = new SslStream(net_stream, false);
|
var sslStream = new SslStream (netStream, false);
|
||||||
ssl_stream.AuthenticateAsServer(cert);
|
sslStream.AuthenticateAsServer (cert);
|
||||||
stream = ssl_stream;
|
_stream = sslStream;
|
||||||
}
|
}
|
||||||
timer = new Timer (OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
|
|
||||||
|
_timer = new Timer (OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
|
||||||
Init ();
|
Init ();
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Properties
|
#region Public Properties
|
||||||
|
|
||||||
public bool IsClosed {
|
public bool IsClosed {
|
||||||
get { return (sock == null); }
|
get {
|
||||||
|
return _socket == null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool IsSecure {
|
public bool IsSecure {
|
||||||
get { return secure; }
|
get {
|
||||||
|
return _secure;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public IPEndPoint LocalEndPoint {
|
public IPEndPoint LocalEndPoint {
|
||||||
get { return (IPEndPoint) sock.LocalEndPoint; }
|
get {
|
||||||
|
return (IPEndPoint) _socket.LocalEndPoint;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public ListenerPrefix Prefix {
|
public ListenerPrefix Prefix {
|
||||||
get { return prefix; }
|
get {
|
||||||
set { prefix = value; }
|
return _prefix;
|
||||||
|
}
|
||||||
|
|
||||||
|
set {
|
||||||
|
_prefix = value;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public IPEndPoint RemoteEndPoint {
|
public IPEndPoint RemoteEndPoint {
|
||||||
get { return (IPEndPoint) sock.RemoteEndPoint; }
|
get {
|
||||||
|
return (IPEndPoint) _socket.RemoteEndPoint;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Reuses {
|
public int Reuses {
|
||||||
get { return reuses; }
|
get {
|
||||||
|
return _reuses;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Stream Stream {
|
public Stream Stream {
|
||||||
get { return stream; }
|
get {
|
||||||
|
return _stream;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Private Methods
|
#region Private Methods
|
||||||
|
|
||||||
void CloseSocket ()
|
private void CloseSocket ()
|
||||||
{
|
{
|
||||||
if (sock == null)
|
if (_socket == null)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
sock.Close ();
|
_socket.Close ();
|
||||||
} catch {
|
} catch {
|
||||||
} finally {
|
} finally {
|
||||||
sock = null;
|
_socket = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
RemoveConnection ();
|
RemoveConnection ();
|
||||||
}
|
}
|
||||||
|
|
||||||
void Init ()
|
private void Init ()
|
||||||
{
|
{
|
||||||
context_bound = false;
|
_chunked = false;
|
||||||
i_stream = null;
|
_context = new HttpListenerContext (this);
|
||||||
o_stream = null;
|
_contextWasBound = false;
|
||||||
prefix = null;
|
_inputState = InputState.RequestLine;
|
||||||
chunked = false;
|
_inputStream = null;
|
||||||
ms = new MemoryStream ();
|
_lineState = LineState.None;
|
||||||
position = 0;
|
_outputStream = null;
|
||||||
input_state = InputState.RequestLine;
|
_position = 0;
|
||||||
line_state = LineState.None;
|
_prefix = null;
|
||||||
context = new HttpListenerContext (this);
|
_requestBuffer = new MemoryStream ();
|
||||||
s_timeout = 90000; // 90k ms for first request, 15k ms from then on
|
_timeout = 90000; // 90k ms for first request, 15k ms from then on.
|
||||||
}
|
}
|
||||||
|
|
||||||
AsymmetricAlgorithm OnPVKSelection (X509Certificate certificate, string targetHost)
|
private AsymmetricAlgorithm OnPVKSelection (X509Certificate certificate, string targetHost)
|
||||||
{
|
{
|
||||||
return key;
|
return _key;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void OnRead (IAsyncResult ares)
|
private static void OnRead (IAsyncResult asyncResult)
|
||||||
{
|
{
|
||||||
HttpConnection cnc = (HttpConnection) ares.AsyncState;
|
var conn = (HttpConnection) asyncResult.AsyncState;
|
||||||
cnc.OnReadInternal (ares);
|
conn.OnReadInternal (asyncResult);
|
||||||
}
|
}
|
||||||
|
|
||||||
void OnReadInternal (IAsyncResult ares)
|
private void OnReadInternal (IAsyncResult asyncResult)
|
||||||
{
|
{
|
||||||
timer.Change (Timeout.Infinite, Timeout.Infinite);
|
_timer.Change (Timeout.Infinite, Timeout.Infinite);
|
||||||
int nread = -1;
|
var nread = -1;
|
||||||
try {
|
try {
|
||||||
nread = stream.EndRead (ares);
|
nread = _stream.EndRead (asyncResult);
|
||||||
ms.Write (buffer, 0, nread);
|
_requestBuffer.Write (_buffer, 0, nread);
|
||||||
if (ms.Length > 32768) {
|
if (_requestBuffer.Length > 32768) {
|
||||||
SendError ("Bad request", 400);
|
SendError ();
|
||||||
Close (true);
|
Close (true);
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
if (ms != null && ms.Length > 0)
|
if (_requestBuffer != null && _requestBuffer.Length > 0)
|
||||||
SendError ();
|
SendError ();
|
||||||
|
|
||||||
if (sock != null) {
|
if (_socket != null) {
|
||||||
CloseSocket ();
|
CloseSocket ();
|
||||||
Unbind ();
|
Unbind ();
|
||||||
}
|
}
|
||||||
@ -232,156 +240,140 @@ namespace WebSocketSharp.Net {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (nread == 0) {
|
if (nread == 0) {
|
||||||
//if (ms.Length > 0)
|
//if (_requestBuffer.Length > 0)
|
||||||
// SendError (); // Why bother?
|
// SendError (); // Why bother?
|
||||||
CloseSocket ();
|
CloseSocket ();
|
||||||
Unbind ();
|
Unbind ();
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ProcessInput (ms)) {
|
if (ProcessInput (_requestBuffer.GetBuffer ())) {
|
||||||
if (!context.HaveError)
|
if (!_context.HaveError)
|
||||||
context.Request.FinishInitialization ();
|
_context.Request.FinishInitialization ();
|
||||||
|
|
||||||
if (context.HaveError) {
|
if (_context.HaveError) {
|
||||||
SendError ();
|
SendError ();
|
||||||
Close (true);
|
Close (true);
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!epl.BindContext (context)) {
|
if (!_epListener.BindContext (_context)) {
|
||||||
SendError ("Invalid host", 400);
|
SendError ("Invalid host", 400);
|
||||||
Close (true);
|
Close (true);
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
HttpListener listener = context.Listener;
|
var listener = _context.Listener;
|
||||||
if (last_listener != listener) {
|
if (_lastListener != listener) {
|
||||||
RemoveConnection ();
|
RemoveConnection ();
|
||||||
listener.AddConnection (this);
|
listener.AddConnection (this);
|
||||||
last_listener = listener;
|
_lastListener = listener;
|
||||||
}
|
}
|
||||||
|
|
||||||
context_bound = true;
|
listener.RegisterContext (_context);
|
||||||
listener.RegisterContext (context);
|
_contextWasBound = true;
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
|
_stream.BeginRead (_buffer, 0, BufferSize, OnRead, this);
|
||||||
}
|
}
|
||||||
|
|
||||||
void OnTimeout (object unused)
|
private void OnTimeout (object unused)
|
||||||
{
|
{
|
||||||
CloseSocket ();
|
CloseSocket ();
|
||||||
Unbind ();
|
Unbind ();
|
||||||
}
|
}
|
||||||
|
|
||||||
// true -> done processing
|
// true -> Done processing.
|
||||||
// false -> need more input
|
// false -> Need more input.
|
||||||
bool ProcessInput (MemoryStream ms)
|
private bool ProcessInput (byte [] data)
|
||||||
{
|
{
|
||||||
byte [] buffer = ms.GetBuffer ();
|
var length = data.Length;
|
||||||
int len = (int) ms.Length;
|
var used = 0;
|
||||||
int used = 0;
|
|
||||||
string line;
|
string line;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
line = ReadLine (buffer, position, len - position, ref used);
|
while ((line = ReadLine (data, _position, length - _position, ref used)) != null) {
|
||||||
position += used;
|
_position += used;
|
||||||
} catch {
|
if (line.Length == 0) {
|
||||||
context.ErrorMessage = "Bad request";
|
if (_inputState == InputState.RequestLine)
|
||||||
context.ErrorStatus = 400;
|
continue;
|
||||||
|
|
||||||
|
_currentLine = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_inputState == InputState.RequestLine) {
|
||||||
|
_context.Request.SetRequestLine (line);
|
||||||
|
_inputState = InputState.Headers;
|
||||||
|
} else {
|
||||||
|
_context.Request.AddHeader (line);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_context.HaveError)
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
_context.ErrorMessage = e.Message;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
do {
|
_position += used;
|
||||||
if (line == null)
|
if (used == length) {
|
||||||
break;
|
_requestBuffer.SetLength (0);
|
||||||
if (line == "") {
|
_position = 0;
|
||||||
if (input_state == InputState.RequestLine)
|
|
||||||
continue;
|
|
||||||
current_line = null;
|
|
||||||
ms = null;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input_state == InputState.RequestLine) {
|
|
||||||
context.Request.SetRequestLine (line);
|
|
||||||
input_state = InputState.Headers;
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
context.Request.AddHeader (line);
|
|
||||||
} catch (Exception e) {
|
|
||||||
context.ErrorMessage = e.Message;
|
|
||||||
context.ErrorStatus = 400;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (context.HaveError)
|
|
||||||
return true;
|
|
||||||
|
|
||||||
if (position >= len)
|
|
||||||
break;
|
|
||||||
try {
|
|
||||||
line = ReadLine (buffer, position, len - position, ref used);
|
|
||||||
position += used;
|
|
||||||
} catch {
|
|
||||||
context.ErrorMessage = "Bad request";
|
|
||||||
context.ErrorStatus = 400;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
} while (line != null);
|
|
||||||
|
|
||||||
if (used == len) {
|
|
||||||
ms.SetLength (0);
|
|
||||||
position = 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
string ReadLine (byte [] buffer, int offset, int len, ref int used)
|
private string ReadLine (byte [] buffer, int offset, int length, ref int used)
|
||||||
{
|
{
|
||||||
if (current_line == null)
|
if (_currentLine == null)
|
||||||
current_line = new StringBuilder ();
|
_currentLine = new StringBuilder ();
|
||||||
|
|
||||||
int last = offset + len;
|
var last = offset + length;
|
||||||
used = 0;
|
used = 0;
|
||||||
for (int i = offset; i < last && line_state != LineState.LF; i++) {
|
for (int i = offset; i < last && _lineState != LineState.LF; i++) {
|
||||||
used++;
|
used++;
|
||||||
byte b = buffer [i];
|
var b = buffer [i];
|
||||||
if (b == 13) {
|
if (b == 13) {
|
||||||
line_state = LineState.CR;
|
_lineState = LineState.CR;
|
||||||
} else if (b == 10) {
|
}
|
||||||
line_state = LineState.LF;
|
else if (b == 10) {
|
||||||
} else {
|
_lineState = LineState.LF;
|
||||||
current_line.Append ((char) b);
|
}
|
||||||
|
else {
|
||||||
|
_currentLine.Append ((char) b);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
string result = null;
|
string result = null;
|
||||||
if (line_state == LineState.LF) {
|
if (_lineState == LineState.LF) {
|
||||||
line_state = LineState.None;
|
_lineState = LineState.None;
|
||||||
result = current_line.ToString ();
|
result = _currentLine.ToString ();
|
||||||
current_line.Length = 0;
|
_currentLine.Length = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
void RemoveConnection ()
|
private void RemoveConnection ()
|
||||||
{
|
{
|
||||||
if (last_listener == null)
|
if (_lastListener == null)
|
||||||
epl.RemoveConnection (this);
|
_epListener.RemoveConnection (this);
|
||||||
else
|
else
|
||||||
last_listener.RemoveConnection (this);
|
_lastListener.RemoveConnection (this);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Unbind ()
|
private void Unbind ()
|
||||||
{
|
{
|
||||||
if (context_bound) {
|
if (_contextWasBound) {
|
||||||
epl.UnbindContext (context);
|
_epListener.UnbindContext (_context);
|
||||||
context_bound = false;
|
_contextWasBound = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -389,49 +381,51 @@ namespace WebSocketSharp.Net {
|
|||||||
|
|
||||||
#region Internal Method
|
#region Internal Method
|
||||||
|
|
||||||
internal void Close (bool force_close)
|
internal void Close (bool force)
|
||||||
{
|
{
|
||||||
if (sock != null) {
|
if (_socket != null) {
|
||||||
Stream st = GetResponseStream ();
|
if (_outputStream != null) {
|
||||||
st.Close ();
|
_outputStream.Close ();
|
||||||
o_stream = null;
|
_outputStream = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (sock != null) {
|
force |= !_context.Request.KeepAlive;
|
||||||
force_close |= !context.Request.KeepAlive;
|
if (!force)
|
||||||
if (!force_close)
|
force = _context.Response.Headers ["Connection"] == "close";
|
||||||
force_close = (context.Response.Headers ["connection"] == "close");
|
|
||||||
|
|
||||||
if (!force_close && context.Request.FlushInput ()) {
|
if (!force && _context.Request.FlushInput ()) {
|
||||||
if (chunked && context.Response.ForceCloseChunked == false) {
|
if (_chunked && !_context.Response.ForceCloseChunked) {
|
||||||
// Don't close. Keep working.
|
// Don't close. Keep working.
|
||||||
reuses++;
|
_reuses++;
|
||||||
Unbind ();
|
Unbind ();
|
||||||
Init ();
|
Init ();
|
||||||
BeginReadRequest ();
|
BeginReadRequest ();
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
reuses++;
|
// _reuses++;
|
||||||
Unbind ();
|
// Unbind ();
|
||||||
Init ();
|
// Init ();
|
||||||
BeginReadRequest ();
|
// BeginReadRequest ();
|
||||||
return;
|
//
|
||||||
|
// return;
|
||||||
}
|
}
|
||||||
|
|
||||||
Socket s = sock;
|
var socket = _socket;
|
||||||
sock = null;
|
_socket = null;
|
||||||
try {
|
try {
|
||||||
if (s != null)
|
if (socket != null)
|
||||||
s.Shutdown (SocketShutdown.Both);
|
socket.Shutdown (SocketShutdown.Both);
|
||||||
} catch {
|
} catch {
|
||||||
} finally {
|
} finally {
|
||||||
if (s != null)
|
if (socket != null)
|
||||||
s.Close ();
|
socket.Close ();
|
||||||
}
|
}
|
||||||
|
|
||||||
Unbind ();
|
Unbind ();
|
||||||
RemoveConnection ();
|
RemoveConnection ();
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -442,17 +436,17 @@ namespace WebSocketSharp.Net {
|
|||||||
|
|
||||||
public void BeginReadRequest ()
|
public void BeginReadRequest ()
|
||||||
{
|
{
|
||||||
if (buffer == null)
|
if (_buffer == null)
|
||||||
buffer = new byte [BufferSize];
|
_buffer = new byte [BufferSize];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (reuses == 1)
|
if (_reuses == 1)
|
||||||
s_timeout = 15000;
|
_timeout = 15000;
|
||||||
|
|
||||||
timer.Change (s_timeout, Timeout.Infinite);
|
_timer.Change (_timeout, Timeout.Infinite);
|
||||||
stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
|
_stream.BeginRead (_buffer, 0, BufferSize, OnRead, this);
|
||||||
} catch {
|
} catch {
|
||||||
timer.Change (Timeout.Infinite, Timeout.Infinite);
|
_timer.Change (Timeout.Infinite, Timeout.Infinite);
|
||||||
CloseSocket ();
|
CloseSocket ();
|
||||||
Unbind ();
|
Unbind ();
|
||||||
}
|
}
|
||||||
@ -465,56 +459,54 @@ namespace WebSocketSharp.Net {
|
|||||||
|
|
||||||
public RequestStream GetRequestStream (bool chunked, long contentlength)
|
public RequestStream GetRequestStream (bool chunked, long contentlength)
|
||||||
{
|
{
|
||||||
if (i_stream == null) {
|
if (_inputStream == null) {
|
||||||
byte [] buffer = ms.GetBuffer ();
|
var buffer = _requestBuffer.GetBuffer ();
|
||||||
int length = (int) ms.Length;
|
var length = buffer.Length;
|
||||||
ms = null;
|
_requestBuffer = null;
|
||||||
if (chunked) {
|
if (chunked) {
|
||||||
this.chunked = true;
|
_chunked = true;
|
||||||
context.Response.SendChunked = true;
|
_context.Response.SendChunked = true;
|
||||||
i_stream = new ChunkedInputStream (context, stream, buffer, position, length - position);
|
_inputStream = new ChunkedInputStream (_context, _stream, buffer, _position, length - _position);
|
||||||
} else {
|
} else {
|
||||||
i_stream = new RequestStream (stream, buffer, position, length - position, contentlength);
|
_inputStream = new RequestStream (_stream, buffer, _position, length - _position, contentlength);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return i_stream;
|
return _inputStream;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ResponseStream GetResponseStream ()
|
public ResponseStream GetResponseStream ()
|
||||||
{
|
{
|
||||||
// TODO: can we get this stream before reading the input?
|
// TODO: Can we get this stream before reading the input?
|
||||||
if (o_stream == null) {
|
if (_outputStream == null) {
|
||||||
HttpListener listener = context.Listener;
|
var listener = _context.Listener;
|
||||||
bool ign = (listener == null) ? true : listener.IgnoreWriteExceptions;
|
var ignore = listener == null ? true : listener.IgnoreWriteExceptions;
|
||||||
o_stream = new ResponseStream (stream, context.Response, ign);
|
_outputStream = new ResponseStream (_stream, _context.Response, ignore);
|
||||||
}
|
}
|
||||||
|
|
||||||
return o_stream;
|
return _outputStream;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void SendError ()
|
public void SendError ()
|
||||||
{
|
{
|
||||||
SendError (context.ErrorMessage, context.ErrorStatus);
|
SendError (_context.ErrorMessage, _context.ErrorStatus);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void SendError (string msg, int status)
|
public void SendError (string message, int status)
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
HttpListenerResponse response = context.Response;
|
var response = _context.Response;
|
||||||
response.StatusCode = status;
|
response.StatusCode = status;
|
||||||
response.ContentType = "text/html";
|
response.ContentType = "text/html";
|
||||||
string description = status.GetStatusDescription ();
|
var description = status.GetStatusDescription ();
|
||||||
string str;
|
var error = !message.IsNullOrEmpty ()
|
||||||
if (msg != null)
|
? String.Format ("<h1>{0} ({1})</h1>", description, message)
|
||||||
str = String.Format ("<h1>{0} ({1})</h1>", description, msg);
|
: String.Format ("<h1>{0}</h1>", description);
|
||||||
else
|
|
||||||
str = String.Format ("<h1>{0}</h1>", description);
|
|
||||||
|
|
||||||
byte [] error = context.Response.ContentEncoding.GetBytes (str);
|
var entity = _context.Response.ContentEncoding.GetBytes (error);
|
||||||
response.Close (error, false);
|
response.Close (entity, false);
|
||||||
} catch {
|
} catch {
|
||||||
// response was already closed
|
// Response was already closed.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
#region License
|
||||||
//
|
//
|
||||||
// HttpListenerContext.cs
|
// HttpListenerContext.cs
|
||||||
// Copied from System.Net.HttpListenerContext.cs
|
// Copied from System.Net.HttpListenerContext.cs
|
||||||
@ -27,6 +28,7 @@
|
|||||||
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||||
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
//
|
//
|
||||||
|
#endregion
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Specialized;
|
using System.Collections.Specialized;
|
||||||
@ -47,12 +49,12 @@ namespace WebSocketSharp.Net {
|
|||||||
|
|
||||||
#region Private Fields
|
#region Private Fields
|
||||||
|
|
||||||
HttpConnection cnc;
|
private HttpConnection _connection;
|
||||||
string error;
|
private string _error;
|
||||||
int err_status;
|
private int _errorStatus;
|
||||||
HttpListenerRequest request;
|
private HttpListenerRequest _request;
|
||||||
HttpListenerResponse response;
|
private HttpListenerResponse _response;
|
||||||
IPrincipal user;
|
private IPrincipal _user;
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
@ -64,12 +66,12 @@ namespace WebSocketSharp.Net {
|
|||||||
|
|
||||||
#region Constructor
|
#region Constructor
|
||||||
|
|
||||||
internal HttpListenerContext (HttpConnection cnc)
|
internal HttpListenerContext (HttpConnection connection)
|
||||||
{
|
{
|
||||||
this.cnc = cnc;
|
_connection = connection;
|
||||||
err_status = 400;
|
_errorStatus = 400;
|
||||||
request = new HttpListenerRequest (this);
|
_request = new HttpListenerRequest (this);
|
||||||
response = new HttpListenerResponse (this);
|
_response = new HttpListenerResponse (this);
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@ -77,21 +79,35 @@ namespace WebSocketSharp.Net {
|
|||||||
#region Internal Properties
|
#region Internal Properties
|
||||||
|
|
||||||
internal HttpConnection Connection {
|
internal HttpConnection Connection {
|
||||||
get { return cnc; }
|
get {
|
||||||
|
return _connection;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal string ErrorMessage {
|
internal string ErrorMessage {
|
||||||
get { return error; }
|
get {
|
||||||
set { error = value; }
|
return _error;
|
||||||
|
}
|
||||||
|
|
||||||
|
set {
|
||||||
|
_error = value;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal int ErrorStatus {
|
internal int ErrorStatus {
|
||||||
get { return err_status; }
|
get {
|
||||||
set { err_status = value; }
|
return _errorStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
set {
|
||||||
|
_errorStatus = value;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal bool HaveError {
|
internal bool HaveError {
|
||||||
get { return (error != null); }
|
get {
|
||||||
|
return _error != null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@ -105,7 +121,9 @@ namespace WebSocketSharp.Net {
|
|||||||
/// A <see cref="HttpListenerRequest"/> that contains the HTTP request objects.
|
/// A <see cref="HttpListenerRequest"/> that contains the HTTP request objects.
|
||||||
/// </value>
|
/// </value>
|
||||||
public HttpListenerRequest Request {
|
public HttpListenerRequest Request {
|
||||||
get { return request; }
|
get {
|
||||||
|
return _request;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -116,7 +134,9 @@ namespace WebSocketSharp.Net {
|
|||||||
/// A <see cref="HttpListenerResponse"/> that contains the HTTP response objects.
|
/// A <see cref="HttpListenerResponse"/> that contains the HTTP response objects.
|
||||||
/// </value>
|
/// </value>
|
||||||
public HttpListenerResponse Response {
|
public HttpListenerResponse Response {
|
||||||
get { return response; }
|
get {
|
||||||
|
return _response;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -126,7 +146,9 @@ namespace WebSocketSharp.Net {
|
|||||||
/// A <see cref="IPrincipal"/> contains the client information.
|
/// A <see cref="IPrincipal"/> contains the client information.
|
||||||
/// </value>
|
/// </value>
|
||||||
public IPrincipal User {
|
public IPrincipal User {
|
||||||
get { return user; }
|
get {
|
||||||
|
return _user;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@ -138,54 +160,40 @@ namespace WebSocketSharp.Net {
|
|||||||
if (expectedSchemes == AuthenticationSchemes.Anonymous)
|
if (expectedSchemes == AuthenticationSchemes.Anonymous)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
// TODO: Handle NTLM/Digest modes
|
// TODO: Handle NTLM/Digest modes.
|
||||||
string header = request.Headers ["Authorization"];
|
var header = _request.Headers ["Authorization"];
|
||||||
if (header == null || header.Length < 2)
|
if (header == null || header.Length < 2)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
string [] authenticationData = header.Split (new char [] {' '}, 2);
|
var authData = header.Split (new char [] {' '}, 2);
|
||||||
if (string.Compare (authenticationData [0], "basic", true) == 0) {
|
if (authData [0].ToLower () == "basic")
|
||||||
user = ParseBasicAuthentication (authenticationData [1]);
|
_user = ParseBasicAuthentication (authData [1]);
|
||||||
}
|
|
||||||
// TODO: throw if malformed -> 400 bad request
|
// TODO: Throw if malformed -> 400 bad request.
|
||||||
}
|
}
|
||||||
|
|
||||||
internal IPrincipal ParseBasicAuthentication (string authData)
|
internal IPrincipal ParseBasicAuthentication (string authData)
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
// Basic AUTH Data is a formatted Base64 String
|
// HTTP Basic Authentication data is a formatted Base64 string.
|
||||||
//string domain = null;
|
var authString = Encoding.Default.GetString (Convert.FromBase64String (authData));
|
||||||
string user = null;
|
|
||||||
string password = null;
|
|
||||||
int pos = -1;
|
|
||||||
string authString = Encoding.Default.GetString (Convert.FromBase64String (authData));
|
|
||||||
|
|
||||||
// The format is DOMAIN\username:password
|
// The format is domain\username:password.
|
||||||
// Domain is optional
|
// Domain is optional.
|
||||||
|
|
||||||
pos = authString.IndexOf (':');
|
var pos = authString.IndexOf (':');
|
||||||
|
var user = authString.Substring (0, pos);
|
||||||
|
var password = authString.Substring (pos + 1);
|
||||||
|
|
||||||
// parse the password off the end
|
// Check if there is a domain.
|
||||||
password = authString.Substring (pos+1);
|
pos = user.IndexOf ('\\');
|
||||||
|
if (pos > 0)
|
||||||
// discard the password
|
user = user.Substring (pos + 1);
|
||||||
authString = authString.Substring (0, pos);
|
|
||||||
|
|
||||||
// check if there is a domain
|
|
||||||
pos = authString.IndexOf ('\\');
|
|
||||||
|
|
||||||
if (pos > 0) {
|
|
||||||
//domain = authString.Substring (0, pos);
|
|
||||||
user = authString.Substring (pos);
|
|
||||||
} else {
|
|
||||||
user = authString;
|
|
||||||
}
|
|
||||||
|
|
||||||
var identity = new System.Net.HttpListenerBasicIdentity (user, password);
|
var identity = new System.Net.HttpListenerBasicIdentity (user, password);
|
||||||
// TODO: What are the roles MS sets
|
// TODO: What are the roles MS sets?
|
||||||
return new GenericPrincipal (identity, new string [0]);
|
return new GenericPrincipal (identity, new string [0]);
|
||||||
} catch (Exception) {
|
} catch {
|
||||||
// Invalid auth data is swallowed silently
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
#region License
|
||||||
//
|
//
|
||||||
// HttpListenerRequest.cs
|
// HttpListenerRequest.cs
|
||||||
// Copied from System.Net.HttpListenerRequest.cs
|
// Copied from System.Net.HttpListenerRequest.cs
|
||||||
@ -27,12 +28,14 @@
|
|||||||
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||||
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
//
|
//
|
||||||
|
#endregion
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
using System.Collections;
|
using System.Collections.Generic;
|
||||||
using System.Collections.Specialized;
|
using System.Collections.Specialized;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Security.Cryptography.X509Certificates;
|
using System.Security.Cryptography.X509Certificates;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
@ -49,58 +52,60 @@ namespace WebSocketSharp.Net {
|
|||||||
|
|
||||||
#region Private Static Fields
|
#region Private Static Fields
|
||||||
|
|
||||||
static char [] separators = new char [] { ' ' };
|
private static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
|
||||||
static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
|
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Private Fields
|
#region Private Fields
|
||||||
|
|
||||||
string [] accept_types;
|
private string [] _acceptTypes;
|
||||||
// int client_cert_error;
|
private bool _chunked;
|
||||||
bool cl_set;
|
private Encoding _contentEncoding;
|
||||||
Encoding content_encoding;
|
private long _contentLength;
|
||||||
long content_length;
|
private bool _contentLengthWasSet;
|
||||||
HttpListenerContext context;
|
private HttpListenerContext _context;
|
||||||
CookieCollection cookies;
|
private CookieCollection _cookies;
|
||||||
WebHeaderCollection headers;
|
private WebHeaderCollection _headers;
|
||||||
Stream input_stream;
|
private Guid _identifier;
|
||||||
bool is_chunked;
|
private Stream _inputStream;
|
||||||
bool ka_set;
|
private bool _keepAlive;
|
||||||
bool keep_alive;
|
private bool _keepAliveWasSet;
|
||||||
string method;
|
private string _method;
|
||||||
// bool no_get_certificate;
|
private NameValueCollection _queryString;
|
||||||
Version version;
|
private string _rawUrl;
|
||||||
NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
|
private Uri _referer;
|
||||||
string raw_url;
|
private Uri _url;
|
||||||
Uri referrer;
|
private string [] _userLanguages;
|
||||||
Uri url;
|
private Version _version;
|
||||||
string [] user_languages;
|
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Constructor
|
#region Internal Constructors
|
||||||
|
|
||||||
internal HttpListenerRequest (HttpListenerContext context)
|
internal HttpListenerRequest (HttpListenerContext context)
|
||||||
{
|
{
|
||||||
this.context = context;
|
_context = context;
|
||||||
headers = new WebHeaderCollection ();
|
_contentLength = -1;
|
||||||
version = HttpVersion.Version10;
|
_headers = new WebHeaderCollection ();
|
||||||
|
_identifier = Guid.NewGuid ();
|
||||||
|
_version = HttpVersion.Version10;
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Properties
|
#region Public Properties
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the media types which are acceptable for the response.
|
/// Gets the media types which are acceptable for the response.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <value>
|
/// <value>
|
||||||
/// An array of <see cref="string"/> that contains the media type names in the Accept request-header field
|
/// An array of <see cref="string"/> that contains the media type names in the Accept request-header
|
||||||
/// or <see langword="null"/> if the request did not include an Accept header.
|
/// or <see langword="null"/> if the request did not include an Accept header.
|
||||||
/// </value>
|
/// </value>
|
||||||
public string [] AcceptTypes {
|
public string [] AcceptTypes {
|
||||||
get { return accept_types; }
|
get {
|
||||||
|
return _acceptTypes;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -110,12 +115,13 @@ namespace WebSocketSharp.Net {
|
|||||||
/// Always returns <c>0</c>.
|
/// Always returns <c>0</c>.
|
||||||
/// </value>
|
/// </value>
|
||||||
public int ClientCertificateError {
|
public int ClientCertificateError {
|
||||||
// TODO: Always returns 0
|
|
||||||
get {
|
get {
|
||||||
|
// TODO: Always returns 0.
|
||||||
/*
|
/*
|
||||||
if (no_get_certificate)
|
if (no_get_certificate)
|
||||||
throw new InvalidOperationException (
|
throw new InvalidOperationException (
|
||||||
"Call GetClientCertificate() before calling this method.");
|
"Call GetClientCertificate method before accessing this property.");
|
||||||
|
|
||||||
return client_cert_error;
|
return client_cert_error;
|
||||||
*/
|
*/
|
||||||
return 0;
|
return 0;
|
||||||
@ -123,17 +129,18 @@ namespace WebSocketSharp.Net {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the encoding that can be used with the entity body data included in the request.
|
/// Gets the encoding used with the entity body data included in the request.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <value>
|
/// <value>
|
||||||
/// A <see cref="Encoding"/> that contains the encoding that can be used with the entity body data.
|
/// A <see cref="Encoding"/> that indicates the encoding used with the entity body data
|
||||||
|
/// or <see cref="Encoding.Default"/> if the request did not include the information about the encoding.
|
||||||
/// </value>
|
/// </value>
|
||||||
public Encoding ContentEncoding {
|
public Encoding ContentEncoding {
|
||||||
// TODO: Always returns Encoding.Default
|
|
||||||
get {
|
get {
|
||||||
if (content_encoding == null)
|
if (_contentEncoding == null)
|
||||||
content_encoding = Encoding.Default;
|
_contentEncoding = Encoding.Default;
|
||||||
return content_encoding;
|
|
||||||
|
return _contentEncoding;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -141,21 +148,25 @@ namespace WebSocketSharp.Net {
|
|||||||
/// Gets the size of the entity body data included in the request.
|
/// Gets the size of the entity body data included in the request.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <value>
|
/// <value>
|
||||||
/// A <see cref="long"/> that contains the value of the Content-Length entity-header field.
|
/// A <see cref="long"/> that contains the value of the Content-Length entity-header.
|
||||||
/// The value is a number of bytes in the entity body data. <c>-1</c> if the size is not known.
|
/// The value is a number of bytes in the entity body data. <c>-1</c> if the size is not known.
|
||||||
/// </value>
|
/// </value>
|
||||||
public long ContentLength64 {
|
public long ContentLength64 {
|
||||||
get { return content_length; }
|
get {
|
||||||
|
return _contentLength;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the media type of the entity body included in the request.
|
/// Gets the media type of the entity body included in the request.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <value>
|
/// <value>
|
||||||
/// A <see cref="string"/> that contains the value of the Content-Type entity-header field.
|
/// A <see cref="string"/> that contains the value of the Content-Type entity-header.
|
||||||
/// </value>
|
/// </value>
|
||||||
public string ContentType {
|
public string ContentType {
|
||||||
get { return headers ["content-type"]; }
|
get {
|
||||||
|
return _headers ["Content-Type"];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -166,10 +177,10 @@ namespace WebSocketSharp.Net {
|
|||||||
/// </value>
|
/// </value>
|
||||||
public CookieCollection Cookies {
|
public CookieCollection Cookies {
|
||||||
get {
|
get {
|
||||||
// TODO: check if the collection is read-only
|
if (_cookies == null)
|
||||||
if (cookies == null)
|
_cookies = _headers.GetCookies (false);
|
||||||
cookies = new CookieCollection ();
|
|
||||||
return cookies;
|
return _cookies;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -180,7 +191,9 @@ namespace WebSocketSharp.Net {
|
|||||||
/// <c>true</c> if the request has the entity body; otherwise, <c>false</c>.
|
/// <c>true</c> if the request has the entity body; otherwise, <c>false</c>.
|
||||||
/// </value>
|
/// </value>
|
||||||
public bool HasEntityBody {
|
public bool HasEntityBody {
|
||||||
get { return (content_length > 0 || is_chunked); }
|
get {
|
||||||
|
return _contentLength > 0 || _chunked;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -190,7 +203,9 @@ namespace WebSocketSharp.Net {
|
|||||||
/// A <see cref="NameValueCollection"/> that contains the HTTP headers used in the request.
|
/// A <see cref="NameValueCollection"/> that contains the HTTP headers used in the request.
|
||||||
/// </value>
|
/// </value>
|
||||||
public NameValueCollection Headers {
|
public NameValueCollection Headers {
|
||||||
get { return headers; }
|
get {
|
||||||
|
return _headers;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -200,7 +215,9 @@ namespace WebSocketSharp.Net {
|
|||||||
/// A <see cref="string"/> that contains the HTTP method used in the request.
|
/// A <see cref="string"/> that contains the HTTP method used in the request.
|
||||||
/// </value>
|
/// </value>
|
||||||
public string HttpMethod {
|
public string HttpMethod {
|
||||||
get { return method; }
|
get {
|
||||||
|
return _method;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -211,14 +228,12 @@ namespace WebSocketSharp.Net {
|
|||||||
/// </value>
|
/// </value>
|
||||||
public Stream InputStream {
|
public Stream InputStream {
|
||||||
get {
|
get {
|
||||||
if (input_stream == null) {
|
if (_inputStream == null)
|
||||||
if (is_chunked || content_length > 0)
|
_inputStream = HasEntityBody
|
||||||
input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
|
? _context.Connection.GetRequestStream (_chunked, _contentLength)
|
||||||
else
|
: Stream.Null;
|
||||||
input_stream = Stream.Null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return input_stream;
|
return _inputStream;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -229,8 +244,10 @@ namespace WebSocketSharp.Net {
|
|||||||
/// Always returns <c>false</c>.
|
/// Always returns <c>false</c>.
|
||||||
/// </value>
|
/// </value>
|
||||||
public bool IsAuthenticated {
|
public bool IsAuthenticated {
|
||||||
// TODO: Always returns false
|
get {
|
||||||
get { return false; }
|
// TODO: Always returns false.
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -240,7 +257,9 @@ namespace WebSocketSharp.Net {
|
|||||||
/// <c>true</c> if the request is sent from the local computer; otherwise, <c>false</c>.
|
/// <c>true</c> if the request is sent from the local computer; otherwise, <c>false</c>.
|
||||||
/// </value>
|
/// </value>
|
||||||
public bool IsLocal {
|
public bool IsLocal {
|
||||||
get { return RemoteEndPoint.Address.IsLocal(); }
|
get {
|
||||||
|
return RemoteEndPoint.Address.IsLocal ();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -250,7 +269,9 @@ namespace WebSocketSharp.Net {
|
|||||||
/// <c>true</c> if the HTTP connection is secured; otherwise, <c>false</c>.
|
/// <c>true</c> if the HTTP connection is secured; otherwise, <c>false</c>.
|
||||||
/// </value>
|
/// </value>
|
||||||
public bool IsSecureConnection {
|
public bool IsSecureConnection {
|
||||||
get { return context.Connection.IsSecure; }
|
get {
|
||||||
|
return _context.Connection.IsSecure;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -261,19 +282,19 @@ namespace WebSocketSharp.Net {
|
|||||||
/// </value>
|
/// </value>
|
||||||
public bool IsWebSocketRequest {
|
public bool IsWebSocketRequest {
|
||||||
get {
|
get {
|
||||||
return method != "GET"
|
return _method != "GET"
|
||||||
? false
|
? false
|
||||||
: version < HttpVersion.Version11
|
: _version < HttpVersion.Version11
|
||||||
? false
|
? false
|
||||||
: !headers.Contains("Upgrade", "websocket")
|
: !_headers.Contains("Upgrade", "websocket")
|
||||||
? false
|
? false
|
||||||
: !headers.Contains("Connection", "Upgrade")
|
: !_headers.Contains("Connection", "Upgrade")
|
||||||
? false
|
? false
|
||||||
: !headers.Contains("Host")
|
: !_headers.Contains("Host")
|
||||||
? false
|
? false
|
||||||
: !headers.Contains("Sec-WebSocket-Key")
|
: !_headers.Contains("Sec-WebSocket-Key")
|
||||||
? false
|
? false
|
||||||
: headers.Contains("Sec-WebSocket-Version");
|
: _headers.Contains("Sec-WebSocket-Version");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -285,24 +306,17 @@ namespace WebSocketSharp.Net {
|
|||||||
/// </value>
|
/// </value>
|
||||||
public bool KeepAlive {
|
public bool KeepAlive {
|
||||||
get {
|
get {
|
||||||
if (ka_set)
|
if (!_keepAliveWasSet) {
|
||||||
return keep_alive;
|
_keepAlive = _headers.Contains ("Connection", "keep-alive") || _version == HttpVersion.Version11
|
||||||
|
? true
|
||||||
|
: _headers.Contains ("Keep-Alive")
|
||||||
|
? !_headers.Contains ("Keep-Alive", "closed")
|
||||||
|
: false;
|
||||||
|
|
||||||
ka_set = true;
|
_keepAliveWasSet = true;
|
||||||
// 1. Connection header
|
|
||||||
// 2. Protocol (1.1 == keep-alive by default)
|
|
||||||
// 3. Keep-Alive header
|
|
||||||
string cnc = headers ["Connection"];
|
|
||||||
if (!String.IsNullOrEmpty (cnc)) {
|
|
||||||
keep_alive = (0 == String.Compare (cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
|
|
||||||
} else if (version == HttpVersion.Version11) {
|
|
||||||
keep_alive = true;
|
|
||||||
} else {
|
|
||||||
cnc = headers ["keep-alive"];
|
|
||||||
if (!String.IsNullOrEmpty (cnc))
|
|
||||||
keep_alive = (0 != String.Compare (cnc, "closed", StringComparison.OrdinalIgnoreCase));
|
|
||||||
}
|
}
|
||||||
return keep_alive;
|
|
||||||
|
return _keepAlive;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -313,7 +327,9 @@ namespace WebSocketSharp.Net {
|
|||||||
/// A <see cref="IPEndPoint"/> that contains the server endpoint.
|
/// A <see cref="IPEndPoint"/> that contains the server endpoint.
|
||||||
/// </value>
|
/// </value>
|
||||||
public IPEndPoint LocalEndPoint {
|
public IPEndPoint LocalEndPoint {
|
||||||
get { return context.Connection.LocalEndPoint; }
|
get {
|
||||||
|
return _context.Connection.LocalEndPoint;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -323,7 +339,9 @@ namespace WebSocketSharp.Net {
|
|||||||
/// A <see cref="Version"/> that contains the HTTP version used in the request.
|
/// A <see cref="Version"/> that contains the HTTP version used in the request.
|
||||||
/// </value>
|
/// </value>
|
||||||
public Version ProtocolVersion {
|
public Version ProtocolVersion {
|
||||||
get { return version; }
|
get {
|
||||||
|
return _version;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -333,7 +351,9 @@ namespace WebSocketSharp.Net {
|
|||||||
/// A <see cref="NameValueCollection"/> that contains the collection of query string variables used in the request.
|
/// A <see cref="NameValueCollection"/> that contains the collection of query string variables used in the request.
|
||||||
/// </value>
|
/// </value>
|
||||||
public NameValueCollection QueryString {
|
public NameValueCollection QueryString {
|
||||||
get { return query_string; }
|
get {
|
||||||
|
return _queryString;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -343,7 +363,9 @@ namespace WebSocketSharp.Net {
|
|||||||
/// A <see cref="string"/> that contains the raw URL requested by the client.
|
/// A <see cref="string"/> that contains the raw URL requested by the client.
|
||||||
/// </value>
|
/// </value>
|
||||||
public string RawUrl {
|
public string RawUrl {
|
||||||
get { return raw_url; }
|
get {
|
||||||
|
return _rawUrl;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -353,18 +375,21 @@ namespace WebSocketSharp.Net {
|
|||||||
/// A <see cref="IPEndPoint"/> that contains the client endpoint.
|
/// A <see cref="IPEndPoint"/> that contains the client endpoint.
|
||||||
/// </value>
|
/// </value>
|
||||||
public IPEndPoint RemoteEndPoint {
|
public IPEndPoint RemoteEndPoint {
|
||||||
get { return context.Connection.RemoteEndPoint; }
|
get {
|
||||||
|
return _context.Connection.RemoteEndPoint;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the identifier of a request.
|
/// Gets the request identifier of a incoming HTTP request.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <value>
|
/// <value>
|
||||||
/// A <see cref="Guid"/> that contains the identifier of a request.
|
/// A <see cref="Guid"/> that contains the identifier of a request.
|
||||||
/// </value>
|
/// </value>
|
||||||
public Guid RequestTraceIdentifier {
|
public Guid RequestTraceIdentifier {
|
||||||
// TODO: Always returns Guid.Empty
|
get {
|
||||||
get { return Guid.Empty; }
|
return _identifier;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -374,27 +399,34 @@ namespace WebSocketSharp.Net {
|
|||||||
/// A <see cref="Uri"/> that contains the URL requested by the client.
|
/// A <see cref="Uri"/> that contains the URL requested by the client.
|
||||||
/// </value>
|
/// </value>
|
||||||
public Uri Url {
|
public Uri Url {
|
||||||
get { return url; }
|
get {
|
||||||
|
return _url;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the URL of the resource from which the requested URL was obtained.
|
/// Gets the URL of the resource from which the requested URL was obtained.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <value>
|
/// <value>
|
||||||
/// A <see cref="Uri"/> that contains the value of the Referer request-header field.
|
/// A <see cref="Uri"/> that contains the value of the Referer request-header
|
||||||
|
/// or <see langword="null"/> if the request did not include an Referer header.
|
||||||
/// </value>
|
/// </value>
|
||||||
public Uri UrlReferrer {
|
public Uri UrlReferrer {
|
||||||
get { return referrer; }
|
get {
|
||||||
|
return _referer;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the information about the user agent originating the request.
|
/// Gets the information about the user agent originating the request.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <value>
|
/// <value>
|
||||||
/// A <see cref="string"/> that contains the value of the User-Agent request-header field.
|
/// A <see cref="string"/> that contains the value of the User-Agent request-header.
|
||||||
/// </value>
|
/// </value>
|
||||||
public string UserAgent {
|
public string UserAgent {
|
||||||
get { return headers ["user-agent"]; }
|
get {
|
||||||
|
return _headers ["User-Agent"];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -404,52 +436,60 @@ namespace WebSocketSharp.Net {
|
|||||||
/// A <see cref="string"/> that contains the server endpoint.
|
/// A <see cref="string"/> that contains the server endpoint.
|
||||||
/// </value>
|
/// </value>
|
||||||
public string UserHostAddress {
|
public string UserHostAddress {
|
||||||
get { return LocalEndPoint.ToString (); }
|
get {
|
||||||
|
return LocalEndPoint.ToString ();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the internet host name and port number (if present) of the resource being requested.
|
/// Gets the internet host name and port number (if present) specified by the client.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <value>
|
/// <value>
|
||||||
/// A <see cref="string"/> that contains the value of the Host request-header field.
|
/// A <see cref="string"/> that contains the value of the Host request-header.
|
||||||
/// </value>
|
/// </value>
|
||||||
public string UserHostName {
|
public string UserHostName {
|
||||||
get { return headers ["host"]; }
|
get {
|
||||||
|
return _headers ["Host"];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the natural languages that are preferred as a response to the request.
|
/// Gets the natural languages which are preferred for the response.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <value>
|
/// <value>
|
||||||
/// An array of <see cref="string"/> that contains the natural language names in the Accept-Language request-header field.
|
/// An array of <see cref="string"/> that contains the natural language names in the Accept-Language request-header
|
||||||
|
/// or <see langword="null"/> if the request did not include an Accept-Language header.
|
||||||
/// </value>
|
/// </value>
|
||||||
public string [] UserLanguages {
|
public string [] UserLanguages {
|
||||||
get { return user_languages; }
|
get {
|
||||||
|
return _userLanguages;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Private Methods
|
#region Private Methods
|
||||||
|
|
||||||
void CreateQueryString (string query)
|
private void CreateQueryString (string query)
|
||||||
{
|
{
|
||||||
if (query == null || query.Length == 0) {
|
if (query == null || query.Length == 0) {
|
||||||
query_string = new NameValueCollection (1);
|
_queryString = new NameValueCollection (1);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
query_string = new NameValueCollection ();
|
_queryString = new NameValueCollection ();
|
||||||
if (query [0] == '?')
|
if (query [0] == '?')
|
||||||
query = query.Substring (1);
|
query = query.Substring (1);
|
||||||
string [] components = query.Split ('&');
|
|
||||||
foreach (string kv in components) {
|
var components = query.Split ('&');
|
||||||
int pos = kv.IndexOf ('=');
|
foreach (var kv in components) {
|
||||||
|
var pos = kv.IndexOf ('=');
|
||||||
if (pos == -1) {
|
if (pos == -1) {
|
||||||
query_string.Add (null, HttpUtility.UrlDecode (kv));
|
_queryString.Add (null, HttpUtility.UrlDecode (kv));
|
||||||
} else {
|
} else {
|
||||||
string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
|
var key = HttpUtility.UrlDecode (kv.Substring (0, pos));
|
||||||
string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
|
var val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
|
||||||
query_string.Add (key, val);
|
_queryString.Add (key, val);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -460,164 +500,143 @@ namespace WebSocketSharp.Net {
|
|||||||
|
|
||||||
internal void AddHeader (string header)
|
internal void AddHeader (string header)
|
||||||
{
|
{
|
||||||
int colon = header.IndexOf (':');
|
var colon = header.IndexOf (':');
|
||||||
if (colon == -1 || colon == 0) {
|
if (colon <= 0) {
|
||||||
context.ErrorMessage = "Bad Request";
|
_context.ErrorMessage = "Invalid header";
|
||||||
context.ErrorStatus = 400;
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
string name = header.Substring (0, colon).Trim ();
|
var name = header.Substring (0, colon).Trim ();
|
||||||
string val = header.Substring (colon + 1).Trim ();
|
var val = header.Substring (colon + 1).Trim ();
|
||||||
string lower = name.ToLower (CultureInfo.InvariantCulture);
|
var lower = name.ToLower (CultureInfo.InvariantCulture);
|
||||||
headers.SetInternal (name, val, false);
|
_headers.SetInternal (name, val, false);
|
||||||
switch (lower) {
|
|
||||||
case "accept-language":
|
|
||||||
user_languages = val.Split (','); // yes, only split with a ','
|
|
||||||
break;
|
|
||||||
case "accept":
|
|
||||||
accept_types = val.Split (','); // yes, only split with a ','
|
|
||||||
break;
|
|
||||||
case "content-length":
|
|
||||||
try {
|
|
||||||
//TODO: max. content_length?
|
|
||||||
content_length = Int64.Parse (val.Trim ());
|
|
||||||
if (content_length < 0)
|
|
||||||
context.ErrorMessage = "Invalid Content-Length.";
|
|
||||||
cl_set = true;
|
|
||||||
} catch {
|
|
||||||
context.ErrorMessage = "Invalid Content-Length.";
|
|
||||||
}
|
|
||||||
|
|
||||||
break;
|
if (lower == "accept") {
|
||||||
case "referer":
|
_acceptTypes = val.SplitHeaderValue (',').ToArray ();
|
||||||
try {
|
return;
|
||||||
referrer = new Uri (val);
|
|
||||||
} catch {
|
|
||||||
referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case "cookie":
|
|
||||||
if (cookies == null)
|
|
||||||
cookies = new CookieCollection();
|
|
||||||
|
|
||||||
string[] cookieStrings = val.Split(new char[] {',', ';'});
|
|
||||||
Cookie current = null;
|
|
||||||
int version = 0;
|
|
||||||
foreach (string cookieString in cookieStrings) {
|
|
||||||
string str = cookieString.Trim ();
|
|
||||||
if (str.Length == 0)
|
|
||||||
continue;
|
|
||||||
if (str.StartsWith ("$Version")) {
|
|
||||||
version = Int32.Parse (Unquote (str.Substring (str.IndexOf ('=') + 1)));
|
|
||||||
} else if (str.StartsWith ("$Path")) {
|
|
||||||
if (current != null)
|
|
||||||
current.Path = str.Substring (str.IndexOf ('=') + 1).Trim ();
|
|
||||||
} else if (str.StartsWith ("$Domain")) {
|
|
||||||
if (current != null)
|
|
||||||
current.Domain = str.Substring (str.IndexOf ('=') + 1).Trim ();
|
|
||||||
} else if (str.StartsWith ("$Port")) {
|
|
||||||
if (current != null)
|
|
||||||
current.Port = str.Substring (str.IndexOf ('=') + 1).Trim ();
|
|
||||||
} else {
|
|
||||||
if (current != null) {
|
|
||||||
cookies.Add (current);
|
|
||||||
}
|
|
||||||
current = new Cookie ();
|
|
||||||
int idx = str.IndexOf ('=');
|
|
||||||
if (idx > 0) {
|
|
||||||
current.Name = str.Substring (0, idx).Trim ();
|
|
||||||
current.Value = str.Substring (idx + 1).Trim ();
|
|
||||||
} else {
|
|
||||||
current.Name = str.Trim ();
|
|
||||||
current.Value = String.Empty;
|
|
||||||
}
|
|
||||||
current.Version = version;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (current != null) {
|
|
||||||
cookies.Add (current);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (lower == "accept-language") {
|
||||||
|
_userLanguages = val.Split (',');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lower == "content-length") {
|
||||||
|
long length;
|
||||||
|
if (Int64.TryParse (val, out length) && length >= 0) {
|
||||||
|
_contentLength = length;
|
||||||
|
_contentLengthWasSet = true;
|
||||||
|
} else {
|
||||||
|
_context.ErrorMessage = "Invalid Content-Length header";
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lower == "content-type") {
|
||||||
|
var contents = val.Split (';');
|
||||||
|
foreach (var content in contents) {
|
||||||
|
var tmp = content.Trim ();
|
||||||
|
if (tmp.StartsWith ("charset")) {
|
||||||
|
var charset = tmp.GetValue ("=");
|
||||||
|
if (!charset.IsNullOrEmpty ()) {
|
||||||
|
try {
|
||||||
|
_contentEncoding = Encoding.GetEncoding (charset);
|
||||||
|
} catch {
|
||||||
|
_context.ErrorMessage = "Invalid Content-Type header";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lower == "referer")
|
||||||
|
_referer = val.ToUri ();
|
||||||
}
|
}
|
||||||
|
|
||||||
internal void FinishInitialization ()
|
internal void FinishInitialization ()
|
||||||
{
|
{
|
||||||
string host = UserHostName;
|
var host = UserHostName;
|
||||||
if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
|
if (_version > HttpVersion.Version10 && host.IsNullOrEmpty ()) {
|
||||||
context.ErrorMessage = "Invalid host name";
|
_context.ErrorMessage = "Invalid Host header";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
string path;
|
Uri rawUri = null;
|
||||||
Uri raw_uri = null;
|
var path = _rawUrl.MaybeUri () && Uri.TryCreate (_rawUrl, UriKind.Absolute, out rawUri)
|
||||||
if (raw_url.MaybeUri () && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
|
? rawUri.PathAndQuery
|
||||||
path = raw_uri.PathAndQuery;
|
: HttpUtility.UrlDecode (_rawUrl);
|
||||||
else
|
|
||||||
path = HttpUtility.UrlDecode (raw_url);
|
|
||||||
|
|
||||||
if ((host == null || host.Length == 0))
|
if (host.IsNullOrEmpty ())
|
||||||
host = UserHostAddress;
|
host = UserHostAddress;
|
||||||
|
|
||||||
if (raw_uri != null)
|
if (rawUri != null)
|
||||||
host = raw_uri.Host;
|
host = rawUri.Host;
|
||||||
|
|
||||||
int colon = host.IndexOf (':');
|
var colon = host.IndexOf (':');
|
||||||
if (colon >= 0)
|
if (colon >= 0)
|
||||||
host = host.Substring (0, colon);
|
host = host.Substring (0, colon);
|
||||||
|
|
||||||
string base_uri = String.Format ("{0}://{1}:{2}",
|
var baseUri = String.Format ("{0}://{1}:{2}",
|
||||||
(IsSecureConnection) ? "https" : "http",
|
IsSecureConnection ? "https" : "http",
|
||||||
host,
|
host,
|
||||||
LocalEndPoint.Port);
|
LocalEndPoint.Port);
|
||||||
|
|
||||||
if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
|
if (!Uri.TryCreate (baseUri + path, UriKind.Absolute, out _url)) {
|
||||||
context.ErrorMessage = "Invalid url: " + base_uri + path;
|
_context.ErrorMessage = "Invalid request url: " + baseUri + path;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
CreateQueryString (url.Query);
|
CreateQueryString (_url.Query);
|
||||||
|
|
||||||
if (version >= HttpVersion.Version11) {
|
var encoding = Headers ["Transfer-Encoding"];
|
||||||
string t_encoding = Headers ["Transfer-Encoding"];
|
if (_version >= HttpVersion.Version11 && !encoding.IsNullOrEmpty ()) {
|
||||||
is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
|
_chunked = encoding.ToLower () == "chunked";
|
||||||
// 'identity' is not valid!
|
// 'identity' is not valid!
|
||||||
if (t_encoding != null && !is_chunked) {
|
if (!_chunked) {
|
||||||
context.Connection.SendError (null, 501);
|
_context.ErrorMessage = String.Empty;
|
||||||
|
_context.ErrorStatus = 501;
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!is_chunked && !cl_set) {
|
if (!_chunked && !_contentLengthWasSet) {
|
||||||
if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
|
var method = _method.ToLower ();
|
||||||
String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0) {
|
if (method == "post" || method == "put") {
|
||||||
context.Connection.SendError (null, 411);
|
_context.ErrorMessage = String.Empty;
|
||||||
|
_context.ErrorStatus = 411;
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (String.Compare (Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) {
|
var expect = Headers ["Expect"];
|
||||||
ResponseStream output = context.Connection.GetResponseStream ();
|
if (!expect.IsNullOrEmpty () && expect.ToLower () == "100-continue") {
|
||||||
|
var output = _context.Connection.GetResponseStream ();
|
||||||
output.InternalWrite (_100continue, 0, _100continue.Length);
|
output.InternalWrite (_100continue, 0, _100continue.Length);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// returns true is the stream could be reused.
|
// Returns true is the stream could be reused.
|
||||||
internal bool FlushInput ()
|
internal bool FlushInput ()
|
||||||
{
|
{
|
||||||
if (!HasEntityBody)
|
if (!HasEntityBody)
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
int length = 2048;
|
var length = 2048;
|
||||||
if (content_length > 0)
|
if (_contentLength > 0)
|
||||||
length = (int) Math.Min (content_length, (long) length);
|
length = (int) Math.Min (_contentLength, (long) length);
|
||||||
|
|
||||||
byte [] bytes = new byte [length];
|
var buffer = new byte [length];
|
||||||
while (true) {
|
while (true) {
|
||||||
// TODO: test if MS has a timeout when doing this
|
// TODO: Test if MS has a timeout when doing this.
|
||||||
try {
|
try {
|
||||||
IAsyncResult ares = InputStream.BeginRead (bytes, 0, length, null, null);
|
var ares = InputStream.BeginRead (buffer, 0, length, null, null);
|
||||||
if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (100))
|
if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (100))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
@ -629,54 +648,36 @@ namespace WebSocketSharp.Net {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal void SetRequestLine (string req)
|
internal void SetRequestLine (string requestLine)
|
||||||
{
|
{
|
||||||
string [] parts = req.Split (separators, 3);
|
var parts = requestLine.Split (new char [] { ' ' }, 3);
|
||||||
if (parts.Length != 3) {
|
if (parts.Length != 3) {
|
||||||
context.ErrorMessage = "Invalid request line (parts).";
|
_context.ErrorMessage = "Invalid request line (parts)";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
method = parts [0];
|
_method = parts [0];
|
||||||
foreach (char c in method){
|
if (!_method.IsToken ()) {
|
||||||
int ic = (int) c;
|
_context.ErrorMessage = "Invalid request line (method)";
|
||||||
|
|
||||||
if ((ic >= 'A' && ic <= 'Z') ||
|
|
||||||
(ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
|
|
||||||
c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
|
|
||||||
c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
|
|
||||||
c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
context.ErrorMessage = "(Invalid verb)";
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
raw_url = parts [1];
|
_rawUrl = parts [1];
|
||||||
|
|
||||||
if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
|
if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
|
||||||
context.ErrorMessage = "Invalid request line (version).";
|
_context.ErrorMessage = "Invalid request line (version)";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
version = new Version (parts [2].Substring (5));
|
_version = new Version (parts [2].Substring (5));
|
||||||
if (version.Major < 1)
|
if (_version.Major < 1)
|
||||||
throw new Exception ();
|
throw new Exception ();
|
||||||
} catch {
|
} catch {
|
||||||
context.ErrorMessage = "Invalid request line (version).";
|
_context.ErrorMessage = "Invalid request line (version)";
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static string Unquote (String str)
|
|
||||||
{
|
|
||||||
int start = str.IndexOf ('\"');
|
|
||||||
int end = str.LastIndexOf ('\"');
|
|
||||||
if (start >= 0 && end >=0)
|
|
||||||
str = str.Substring (start + 1, end - 1);
|
|
||||||
return str.Trim ();
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Public Methods
|
#region Public Methods
|
||||||
|
Loading…
Reference in New Issue
Block a user