Skip to content

Commit

Permalink
Merge pull request dotnet/corefx#15704 from Priya91/httptests
Browse files Browse the repository at this point in the history
Add some more HttpListener tests.

Commit migrated from dotnet/corefx@104397d
  • Loading branch information
Priya91 authored Feb 3, 2017
2 parents e248534 + f87feda commit eb10a4a
Show file tree
Hide file tree
Showing 12 changed files with 614 additions and 103 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,9 @@
<Compile Include="$(CommonPath)\System\Net\WebSockets\ManagedWebSocket.cs">
<Link>Common\System\Net\WebSockets\ManagedWebSocket.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Threading\Tasks\TaskToApm.cs">
<Link>Common\System\Threading\Tasks\TaskToApm.cs</Link>
</Compile>
<Reference Include="System.Buffers" />
<Reference Include="System.Net.Sockets" />
<Reference Include="System.Threading.ThreadPool" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,7 @@ private class ReadBufferState
public int Count;
public int InitialCount;
public HttpStreamAsyncResult Ares;
public ReadBufferState(byte[] buffer, int offset, int count,
HttpStreamAsyncResult ares)
public ReadBufferState(byte[] buffer, int offset, int count, HttpStreamAsyncResult ares)
{
Buffer = buffer;
Offset = offset;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,21 @@ public static void AddPrefix(string prefix, HttpListener listener)

private static void AddPrefixInternal(string p, HttpListener listener)
{
int start = p.IndexOf(':') + 3;
int colon = p.IndexOf(':', start);
if (colon != -1)
{
// root can't be -1 here, since we've already checked for ending '/' in ListenerPrefix.
int root = p.IndexOf('/', colon, p.Length - colon);
string portString = p.Substring(colon + 1, root - colon - 1);

int port;
if (!int.TryParse(portString, out port) || port <= 0 || port >= 65536)
{
throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.net_invalid_port);
}
}

ListenerPrefix lp = new ListenerPrefix(p);
if (lp.Path.IndexOf('%') != -1)
throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.net_invalid_path);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,26 +51,24 @@ public override ChannelBinding GetChannelBinding(ChannelBindingKind kind)
}
}

private string[] _accept_types;
private Encoding _content_encoding;
private long _content_length;
private bool _cl_set;
private string[] _acceptTypes;
private Encoding _contentEncoding;
private long _contentLength;
private bool _clSet;
private CookieCollection _cookies;
private WebHeaderCollection _headers;
private string _method;
private Stream _input_stream;
private Stream _inputStream;
private Version _version;
private NameValueCollection _query_string; // check if null is ok, check if read-only, check case-sensitiveness
private string _raw_url;
private NameValueCollection _queryString; // check if null is ok, check if read-only, check case-sensitiveness
private string _rawUrl;
private Uri _url;
private Uri _referrer;
private string[] _user_languages;
private string[] _userLanguages;
private HttpListenerContext _context;
private bool _is_chunked;
private bool _ka_set;
private bool _keep_alive;
private delegate X509Certificate2 GCCDelegate();
private GCCDelegate _gccDelegate;
private bool _isChunked;
private bool _kaSet;
private bool _keepAlive;

private static byte[] s_100continue = Encoding.ASCII.GetBytes("HTTP/1.1 100 Continue\r\n\r\n");

Expand Down Expand Up @@ -108,7 +106,7 @@ internal void SetRequestLine(string req)
return;
}

_raw_url = parts[1];
_rawUrl = parts[1];
if (parts[2].Length != 8 || !parts[2].StartsWith("HTTP/"))
{
_context.ErrorMessage = "Invalid request line (version).";
Expand All @@ -132,11 +130,11 @@ private void CreateQueryString(string query)
{
if (query == null || query.Length == 0)
{
_query_string = new NameValueCollection(1);
_queryString = new NameValueCollection(1);
return;
}

_query_string = new NameValueCollection();
_queryString = new NameValueCollection();
if (query[0] == '?')
query = query.Substring(1);
string[] components = query.Split('&');
Expand All @@ -145,14 +143,14 @@ private void CreateQueryString(string query)
int pos = kv.IndexOf('=');
if (pos == -1)
{
_query_string.Add(null, WebUtility.UrlDecode(kv));
_queryString.Add(null, WebUtility.UrlDecode(kv));
}
else
{
string key = WebUtility.UrlDecode(kv.Substring(0, pos));
string val = WebUtility.UrlDecode(kv.Substring(pos + 1));

_query_string.Add(key, val);
_queryString.Add(key, val);
}
}
}
Expand Down Expand Up @@ -206,10 +204,10 @@ internal void FinishInitialization()

string path;
Uri raw_uri = null;
if (MaybeUri(_raw_url.ToLowerInvariant()) && Uri.TryCreate(_raw_url, UriKind.Absolute, out raw_uri))
if (MaybeUri(_rawUrl.ToLowerInvariant()) && Uri.TryCreate(_rawUrl, UriKind.Absolute, out raw_uri))
path = raw_uri.PathAndQuery;
else
path = _raw_url;
path = _rawUrl;

if ((host == null || host.Length == 0))
host = UserHostAddress;
Expand All @@ -233,22 +231,22 @@ internal void FinishInitialization()

CreateQueryString(_url.Query);

_url = HttpListenerRequestUriBuilder.GetRequestUri(_raw_url, _url.Scheme,
_url = HttpListenerRequestUriBuilder.GetRequestUri(_rawUrl, _url.Scheme,
_url.Authority, _url.LocalPath, _url.Query);

if (_version >= HttpVersion.Version11)
{
string t_encoding = Headers["Transfer-Encoding"];
_is_chunked = (t_encoding != null && string.Equals(t_encoding, "chunked", StringComparison.OrdinalIgnoreCase));
_isChunked = (t_encoding != null && string.Equals(t_encoding, "chunked", StringComparison.OrdinalIgnoreCase));
// 'identity' is not valid!
if (t_encoding != null && !_is_chunked)
if (t_encoding != null && !_isChunked)
{
_context.Connection.SendError(null, 501);
return;
}
}

if (!_is_chunked && !_cl_set)
if (!_isChunked && !_clSet)
{
if (string.Equals(_method, "POST", StringComparison.OrdinalIgnoreCase) ||
string.Equals(_method, "PUT", StringComparison.OrdinalIgnoreCase))
Expand Down Expand Up @@ -291,18 +289,18 @@ internal void AddHeader(string header)
switch (lower)
{
case "accept-language":
_user_languages = val.Split(','); // yes, only split with a ','
_userLanguages = val.Split(','); // yes, only split with a ','
break;
case "accept":
_accept_types = val.Split(','); // yes, only split with a ','
_acceptTypes = val.Split(','); // yes, only split with a ','
break;
case "content-length":
try
{
_content_length = long.Parse(val.Trim());
if (_content_length < 0)
_contentLength = long.Parse(val.Trim());
if (_contentLength < 0)
_context.ErrorMessage = "Invalid Content-Length.";
_cl_set = true;
_clSet = true;
}
catch
{
Expand Down Expand Up @@ -388,8 +386,8 @@ internal bool FlushInput()
return true;

int length = 2048;
if (_content_length > 0)
length = (int)Math.Min(_content_length, (long)length);
if (_contentLength > 0)
length = (int)Math.Min(_contentLength, (long)length);

byte[] bytes = new byte[length];
while (true)
Expand All @@ -404,7 +402,7 @@ internal bool FlushInput()
}
catch (ObjectDisposedException)
{
_input_stream = null;
_inputStream = null;
return true;
}
catch
Expand All @@ -416,7 +414,7 @@ internal bool FlushInput()

public string[] AcceptTypes
{
get { return _accept_types; }
get { return _acceptTypes; }
}

public int ClientCertificateError
Expand All @@ -437,15 +435,21 @@ public Encoding ContentEncoding
{
get
{
if (_content_encoding == null)
_content_encoding = Encoding.Default;
return _content_encoding;
if (_contentEncoding == null)
_contentEncoding = Encoding.Default;
return _contentEncoding;
}
}

public long ContentLength64
{
get { return _content_length; }
get
{
if (_isChunked)
_contentLength = -1;

return _contentLength;
}
}

public string ContentType
Expand All @@ -465,7 +469,7 @@ public CookieCollection Cookies

public bool HasEntityBody
{
get { return (_content_length > 0 || _is_chunked); }
get { return (_contentLength > 0 || _isChunked); }
}

public NameValueCollection Headers
Expand All @@ -482,15 +486,15 @@ public Stream InputStream
{
get
{
if (_input_stream == null)
if (_inputStream == null)
{
if (_is_chunked || _content_length > 0)
_input_stream = _context.Connection.GetRequestStream(_is_chunked, _content_length);
if (_isChunked || _contentLength > 0)
_inputStream = _context.Connection.GetRequestStream(_isChunked, _contentLength);
else
_input_stream = Stream.Null;
_inputStream = Stream.Null;
}

return _input_stream;
return _inputStream;
}
}

Expand All @@ -513,29 +517,29 @@ public bool KeepAlive
{
get
{
if (_ka_set)
return _keep_alive;
if (_kaSet)
return _keepAlive;

_ka_set = true;
_kaSet = 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));
_keepAlive = (0 == String.Compare(cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
}
else if (_version == HttpVersion.Version11)
{
_keep_alive = true;
_keepAlive = true;
}
else
{
cnc = _headers["keep-alive"];
if (!String.IsNullOrEmpty(cnc))
_keep_alive = (0 != String.Compare(cnc, "closed", StringComparison.OrdinalIgnoreCase));
_keepAlive = (0 != String.Compare(cnc, "closed", StringComparison.OrdinalIgnoreCase));
}
return _keep_alive;
return _keepAlive;
}
}

Expand All @@ -551,12 +555,12 @@ public Version ProtocolVersion

public NameValueCollection QueryString
{
get { return _query_string; }
get { return _queryString; }
}

public string RawUrl
{
get { return _raw_url; }
get { return _rawUrl; }
}

public IPEndPoint RemoteEndPoint
Expand Down Expand Up @@ -596,25 +600,21 @@ public string UserHostName

public string[] UserLanguages
{
get { return _user_languages; }
get { return _userLanguages; }
}

public IAsyncResult BeginGetClientCertificate(AsyncCallback requestCallback, object state)
{
if (_gccDelegate == null)
_gccDelegate = new GCCDelegate(GetClientCertificate);
return _gccDelegate.BeginInvoke(requestCallback, state);
Task<X509Certificate2> getClientCertificate = new Task<X509Certificate2>(() => GetClientCertificate());
return TaskToApm.Begin(getClientCertificate, requestCallback, state);
}

public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));

if (_gccDelegate == null)
throw new InvalidOperationException();

return _gccDelegate.EndInvoke(asyncResult);

return TaskToApm.End<X509Certificate2>(asyncResult);
}

public X509Certificate2 GetClientCertificate()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
//

using System.Threading;
using System.Threading.Tasks;

namespace System.Net
{
Expand Down Expand Up @@ -64,7 +65,7 @@ public void Complete()
_handle.Set();

if (_callback != null)
_callback.BeginInvoke(this, null, null);
Task.Run(() => _callback(this));
}
}

Expand Down
Loading

0 comments on commit eb10a4a

Please sign in to comment.