Skip to content

Commit

Permalink
Pre 1.13.0 (#147)
Browse files Browse the repository at this point in the history
* Code Review

* Upgrade SWAN before publish
  • Loading branch information
geoperez authored Mar 7, 2018
1 parent ebb69cd commit 989c2be
Show file tree
Hide file tree
Showing 11 changed files with 58 additions and 172 deletions.
6 changes: 4 additions & 2 deletions src/Unosquare.Labs.EmbedIO/Modules/StaticFilesModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,11 @@ public StaticFilesModule(
_virtualPaths = new VirtualPaths(Path.GetFullPath(fileSystemPath), useDirectoryBrowser);

UseGzip = true;
#if DEBUG // When debugging, disable RamCache
#if DEBUG
// When debugging, disable RamCache
UseRamCache = false;
#else // Otherwise, enable it by default
#else
// Otherwise, enable it by default
UseRamCache = true;
#endif
DefaultDocument = DefaultDocumentName;
Expand Down
22 changes: 9 additions & 13 deletions src/Unosquare.Labs.EmbedIO/System.Net/HttpBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -157,34 +157,30 @@ private static async Task<byte[]> ReadEntityBodyAsync(Stream stream, string leng
? await stream.ReadBytesAsync((int) len, ct)
: null;
}

private static bool EqualsWith(int value, char c, Action<int> action)
{
action(value);
return value == c - 0;
}


private static string[] ReadHeaders(Stream stream)
{
var buff = new List<byte>();
var cnt = 0;

void Add(int i)
bool EqualsWith(int i, char c)
{
if (i == -1)
throw new EndOfStreamException("The header cannot be read from the data source.");

buff.Add((byte) i);
cnt++;

return i == c - 0;
}

var read = false;
while (cnt < HeadersMaxLength)
{
if (EqualsWith(stream.ReadByte(), '\r', Add) &&
EqualsWith(stream.ReadByte(), '\n', Add) &&
EqualsWith(stream.ReadByte(), '\r', Add) &&
EqualsWith(stream.ReadByte(), '\n', Add))
if (EqualsWith(stream.ReadByte(), '\r') &&
EqualsWith(stream.ReadByte(), '\n') &&
EqualsWith(stream.ReadByte(), '\r') &&
EqualsWith(stream.ReadByte(), '\n'))
{
read = true;
break;
Expand Down
7 changes: 2 additions & 5 deletions src/Unosquare.Labs.EmbedIO/System.Net/HttpListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -234,14 +234,11 @@ internal void RegisterContext(HttpListenerContext context)
throw new Exception("Unable to register context");
}

internal void UnregisterContext(HttpListenerContext context)
{
_ctxQueue.TryRemove(context.Id, out var removedContext);
}
internal void UnregisterContext(HttpListenerContext context) => _ctxQueue.TryRemove(context.Id, out var _);

internal void AddConnection(HttpConnection cnc) => _connections[cnc] = cnc;

internal void RemoveConnection(HttpConnection cnc) => _connections.TryRemove(cnc, out var instance);
internal void RemoveConnection(HttpConnection cnc) => _connections.TryRemove(cnc, out var _);

private void Close(bool closeExisting)
{
Expand Down
4 changes: 2 additions & 2 deletions src/Unosquare.Labs.EmbedIO/System.Net/HttpListenerRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ namespace Unosquare.Net
/// </summary>
public sealed class HttpListenerRequest
{
private static readonly byte[] _100Continue = Encoding.UTF8.GetBytes("HTTP/1.1 100 Continue\r\n\r\n");
private static readonly byte[] HttpStatus100 = Encoding.UTF8.GetBytes("HTTP/1.1 100 Continue\r\n\r\n");
private static readonly char[] Separators = { ' ' };

private readonly HttpListenerContext _context;
Expand Down Expand Up @@ -419,7 +419,7 @@ internal void FinishInitialization()

if (string.Compare(Headers["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0)
{
_context.Connection.GetResponseStream().InternalWrite(_100Continue, 0, _100Continue.Length);
_context.Connection.GetResponseStream().InternalWrite(HttpStatus100, 0, HttpStatus100.Length);
}
}

Expand Down
10 changes: 0 additions & 10 deletions src/Unosquare.Labs.EmbedIO/System.Net/HttpSysSettings.cs

This file was deleted.

116 changes: 7 additions & 109 deletions src/Unosquare.Labs.EmbedIO/System.Net/NetExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,7 @@ internal static string Unquote(this string str)

return str.Trim();
}

internal static bool IsData(this byte opcode) => opcode == 0x1 || opcode == 0x2;

internal static bool IsData(this Opcode opcode) => opcode == Opcode.Text || opcode == Opcode.Binary;


internal static byte[] InternalToByteArray(this ushort value, Endianness order)
{
var bytes = BitConverter.GetBytes(value);
Expand All @@ -92,76 +88,22 @@ internal static byte[] InternalToByteArray(this ulong value, Endianness order)

return bytes;
}

internal static bool IsControl(this byte opcode) => opcode > 0x7 && opcode < 0x10;

internal static bool IsReserved(this CloseStatusCode code)
{
return code == CloseStatusCode.Undefined ||
code == CloseStatusCode.NoStatus ||
code == CloseStatusCode.Abnormal ||
code == CloseStatusCode.TlsHandshakeFailure;
}

/// <summary>
/// Converts the order of the specified array of <see cref="byte"/> to the host byte order.
/// </summary>
/// <returns>
/// An array of <see cref="byte"/> converted from <paramref name="source"/>.
/// </returns>
/// <param name="source">
/// An array of <see cref="byte"/> to convert.
/// </param>
/// <param name="sourceOrder">
/// One of the <see cref="Endianness"/> enum values, specifies the byte order of
/// <paramref name="source"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> is <see langword="null"/>.
/// </exception>

internal static byte[] ToHostOrder(this byte[] source, Endianness sourceOrder)
{
if (source == null)
throw new ArgumentNullException(nameof(source));

return source.Length > 1 && !sourceOrder.IsHostOrder() ? source.Reverse().ToArray() : source;
}

/// <summary>
/// Determines whether the specified <see cref="Endianness"/> is host (this computer
/// architecture) byte order.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="order"/> is host byte order; otherwise, <c>false</c>.
/// </returns>
/// <param name="order">
/// One of the <see cref="Endianness"/> enum values, to test.
/// </param>

internal static bool IsHostOrder(this Endianness order)
{
// true: !(true ^ true) or !(false ^ false)
// false: !(true ^ false) or !(false ^ true)
return !(BitConverter.IsLittleEndian ^ (order == Endianness.Little));
}

/// <summary>
/// Tries to create a <see cref="Uri"/> for WebSocket with
/// the specified <paramref name="uriString"/>.
/// </summary>
/// <returns>
/// <c>true</c> if a <see cref="Uri"/> is successfully created; otherwise, <c>false</c>.
/// </returns>
/// <param name="uriString">
/// A <see cref="string"/> that represents a WebSocket URL to try.
/// </param>
/// <param name="result">
/// When this method returns, a <see cref="Uri"/> that represents a WebSocket URL,
/// or <see langword="null"/> if <paramref name="uriString"/> is invalid.
/// </param>
/// <param name="message">
/// When this method returns, a <see cref="string"/> that represents an error message,
/// or <see cref="String.Empty"/> if <paramref name="uriString"/> is valid.
/// </param>

internal static bool TryCreateWebSocketUri(
this string uriString, out Uri result, out string message)
{
Expand Down Expand Up @@ -211,20 +153,7 @@ internal static bool TryCreateWebSocketUri(

internal static bool IsToken(this string value) =>
value.All(c => c >= 0x20 && c < 0x7f && !Tspecials.Contains(c));

/// <summary>
/// Gets the collection of the HTTP cookies from the specified HTTP <paramref name="headers"/>.
/// </summary>
/// <returns>
/// A <see cref="CookieCollection"/> that receives a collection of the HTTP cookies.
/// </returns>
/// <param name="headers">
/// A <see cref="NameValueCollection"/> that contains a collection of the HTTP headers.
/// </param>
/// <param name="response">
/// <c>true</c> if <paramref name="headers"/> is a collection of the response headers;
/// otherwise, <c>false</c>.
/// </param>

internal static CookieCollection GetCookies(this NameValueCollection headers, bool response)
{
var name = response ? "Set-Cookie" : Headers.Cookie;
Expand All @@ -242,42 +171,11 @@ internal static string ToExtensionString(this CompressionMethod method, params s

return parameters == null || parameters.Length == 0 ? m : $"{m}; {string.Join("; ", parameters)}";
}

/// <summary>
/// Determines whether the specified <see cref="NameValueCollection"/> contains the entry with
/// the specified both <paramref name="name"/> and <paramref name="value"/>.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="collection"/> contains the entry with both
/// <paramref name="name"/> and <paramref name="value"/>; otherwise, <c>false</c>.
/// </returns>
/// <param name="collection">
/// A <see cref="NameValueCollection"/> to test.
/// </param>
/// <param name="name">
/// A <see cref="string"/> that represents the key of the entry to find.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the entry to find.
/// </param>

internal static bool Contains(this NameValueCollection collection, string name, string value)
=> collection[name]?.Split(Strings.CommaSplitChar)
.Any(val => val.Trim().Equals(value, StringComparison.OrdinalIgnoreCase)) == true;

/// <summary>
/// Determines whether the specified <see cref="string"/> contains any of characters in
/// the specified array of <see cref="char"/>.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="value"/> contains any of <paramref name="chars"/>;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="value">
/// A <see cref="string"/> to test.
/// </param>
/// <param name="chars">
/// An array of <see cref="char"/> that contains characters to find.
/// </param>

internal static bool Contains(this string value, params char[] chars)
=> chars?.Length == 0 || (!string.IsNullOrEmpty(value) && value.IndexOfAny(chars) > -1);

Expand Down
17 changes: 3 additions & 14 deletions src/Unosquare.Labs.EmbedIO/System.Net/PayloadData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ namespace Unosquare.Net

internal class PayloadData : IEnumerable<byte>
{
public static readonly ulong MaxLength;
public static readonly ulong MaxLength = long.MaxValue;

private readonly byte[] _data;
private readonly long _length;
Expand All @@ -46,11 +46,6 @@ internal class PayloadData : IEnumerable<byte>
private string _reason;
private bool _reasonSet;

static PayloadData()
{
MaxLength = Int64.MaxValue;
}

internal PayloadData()
{
_code = 1005;
Expand Down Expand Up @@ -136,15 +131,9 @@ internal string Reason
}
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

public IEnumerator<byte> GetEnumerator()
{
return ((IEnumerable<byte>)_data).GetEnumerator();
}
public IEnumerator<byte> GetEnumerator() => ((IEnumerable<byte>)_data).GetEnumerator();

public override string ToString() => BitConverter.ToString(_data);

Expand Down
26 changes: 17 additions & 9 deletions src/Unosquare.Labs.EmbedIO/System.Net/WebSocket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,9 @@ public class WebSocket : IDisposable
/// Represents the random number generator used internally.
/// </summary>
internal static readonly RandomNumberGenerator RandomNumber = RandomNumberGenerator.Create();

private const string Guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

private readonly Action<MessageEventArgs> _message;
private readonly bool _client;
private readonly object _forState = new object();
Expand Down Expand Up @@ -165,7 +165,7 @@ public WebSocket(string url)
IsSecure = _uri.Scheme == "wss";
#endif
_waitTime = TimeSpan.FromSeconds(5);
_forMessageEventQueue = ((ICollection) _messageEventQueue).SyncRoot;
_forMessageEventQueue = ((ICollection)_messageEventQueue).SyncRoot;
_validator = new WebSocketValidator(this);
}

Expand All @@ -183,7 +183,7 @@ internal WebSocket(WebSocketContext context)
_forMessageEventQueue = ((ICollection)_messageEventQueue).SyncRoot;
_validator = new WebSocketValidator(this);
}

/// <summary>
/// Occurs when the WebSocket connection has been closed.
/// </summary>
Expand All @@ -203,7 +203,7 @@ internal WebSocket(WebSocketContext context)
/// Occurs when the WebSocket connection has been established.
/// </summary>
public event EventHandler OnOpen;

/// <summary>
/// Gets or sets the compression method used to compress a message on the WebSocket connection.
/// </summary>
Expand Down Expand Up @@ -513,7 +513,7 @@ public async Task CloseAsync(CloseStatusCode code = CloseStatusCode.Undefined, s
return;
}

var send = !code.IsReserved();
var send = !IsOpcodeReserved(code);
await InternalCloseAsync(new CloseEventArgs(code, reason), send, send, ct: ct);
}

Expand Down Expand Up @@ -669,7 +669,7 @@ public void SetCookie(Cookie cookie)
CookieCollection.Add(cookie);
}
}

/// <inheritdoc />
public void Dispose()
{
Expand Down Expand Up @@ -795,6 +795,14 @@ private static HttpResponse CreateHandshakeFailureResponse(HttpStatusCode code)
return ret;
}

private static bool IsOpcodeReserved(CloseStatusCode code)
{
return code == CloseStatusCode.Undefined ||
code == CloseStatusCode.NoStatus ||
code == CloseStatusCode.Abnormal ||
code == CloseStatusCode.TlsHandshakeFailure;
}

// As server
private async Task<bool> AcceptHandshakeAsync()
{
Expand Down Expand Up @@ -992,7 +1000,7 @@ private void Fatal(string message, Exception exception = null)
private void Fatal(string message, CloseStatusCode code)
{
// TODO: Wait?
InternalCloseAsync(new CloseEventArgs(code, message), !code.IsReserved(), false).Wait();
InternalCloseAsync(new CloseEventArgs(code, message), !IsOpcodeReserved(code), false).Wait();
}

private void Message()
Expand Down Expand Up @@ -1561,7 +1569,7 @@ private async Task SetClientStream()
#endif
}
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

private void StartReceiving()
{
if (_messageEventQueue.Count > 0)
Expand Down
Loading

0 comments on commit 989c2be

Please sign in to comment.