... cosmetics

This commit is contained in:
UbitUmarov
2022-11-10 11:29:30 +00:00
parent 4cac42ab98
commit 022ea478d1
8 changed files with 103 additions and 81 deletions

View File

@@ -26,7 +26,7 @@ namespace OSHttpServer
static private int basecontextID;
Queue<HttpRequest> m_requests;
object m_requestsLock = new object();
readonly object m_requestsLock = new();
public int m_maxRequests = MAXREQUESTS;
public bool m_waitingResponse;
@@ -130,10 +130,10 @@ namespace OSHttpServer
{
SslStream _ssl = (SslStream)m_stream;
X509Certificate _cert1 = _ssl.RemoteCertificate;
if (_cert1 != null)
if (_cert1 is not null)
{
X509Certificate2 _cert2 = new X509Certificate2(_cert1);
if (_cert2 != null)
X509Certificate2 _cert2 = new(_cert1);
if (_cert2 is not null)
SSLCommonName = _cert2.GetNameInfo(X509NameType.SimpleName, false);
}
}
@@ -150,7 +150,7 @@ namespace OSHttpServer
if (contextID < 0 || m_isClosing)
return false;
if (m_stream == null || m_sock == null || !m_sock.Connected)
if (m_stream is null || m_sock is null || !m_sock.Connected)
return false;
return true;
@@ -230,7 +230,7 @@ namespace OSHttpServer
contextID = -100;
if (m_stream != null)
if (m_stream is not null)
{
m_stream.Close();
m_stream = null;
@@ -322,7 +322,7 @@ namespace OSHttpServer
{
try
{
if (m_stream != null)
if (m_stream is not null)
{
if (error == SocketError.Success)
{
@@ -437,8 +437,8 @@ namespace OSHttpServer
catch (IOException err)
{
LogWriter.Write(this, LogPrio.Debug, "Failed to end receive: " + err.Message);
if (err.InnerException is SocketException)
Disconnect((SocketError)((SocketException)err.InnerException).ErrorCode);
if (err.InnerException is SocketException exception)
Disconnect((SocketError)exception.ErrorCode);
else
Disconnect(SocketError.ConnectionReset);
}
@@ -466,7 +466,7 @@ namespace OSHttpServer
FullRequestReceived = true;
LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount();
if (m_maxRequests <= 0 || RequestReceived == null)
if (m_maxRequests <= 0 || RequestReceived is null)
return;
if (--m_maxRequests == 0)
@@ -477,7 +477,7 @@ namespace OSHttpServer
// should not happen
try
{
Uri uri = new Uri(m_currentRequest.Secure ? "https://" : "http://" + m_currentRequest.UriPath);
Uri uri = new(m_currentRequest.Secure ? "https://" : "http://" + m_currentRequest.UriPath);
m_currentRequest.Uri = uri;
m_currentRequest.UriPath = uri.AbsolutePath;
}
@@ -641,7 +641,7 @@ namespace OSHttpServer
/// <exception cref="ArgumentNullException"></exception>
public bool Send(byte[] buffer)
{
if (buffer == null)
if (buffer is null)
throw new ArgumentNullException("buffer");
return Send(buffer, 0, buffer.Length);
}
@@ -655,7 +655,7 @@ namespace OSHttpServer
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>
private object sendLock = new object();
private readonly object sendLock = new();
public bool Send(byte[] buffer, int offset, int size)
{
@@ -759,7 +759,7 @@ namespace OSHttpServer
m_currentRequest = null;
m_currentResponse?.Clear();
m_currentResponse = null;
if (m_requests != null)
if (m_requests is not null)
{
while (m_requests.Count > 0)
{

View File

@@ -15,7 +15,7 @@ namespace OSHttpServer
/// </summary>
public class HttpContextFactory : IHttpContextFactory
{
private readonly ConcurrentDictionary<int, HttpClientContext> m_activeContexts = new ConcurrentDictionary<int, HttpClientContext>();
private readonly ConcurrentDictionary<int, HttpClientContext> m_activeContexts = new();
private readonly ILogWriter m_logWriter;
/// <summary>

View File

@@ -11,8 +11,8 @@ namespace OSHttpServer
public class HttpInput : IHttpInput
{
/// <summary> Representation of a non-initialized class instance </summary>
public static readonly HttpInput Empty = new HttpInput("Empty", true);
private readonly IDictionary<string, HttpInputItem> _items = new Dictionary<string, HttpInputItem>();
public static readonly HttpInput Empty = new("Empty", true);
private readonly Dictionary<string, HttpInputItem> _items = new();
private string _name;
/// <summary> Variable telling the class that it is non-initialized <see cref="Empty"/> </summary>
@@ -70,7 +70,7 @@ namespace OSHttpServer
/// <exception cref="InvalidOperationException">Cannot add stuff to <see cref="HttpInput.Empty"/>.</exception>
public void Add(string name, string value)
{
if (name == null)
if (name is null)
throw new ArgumentNullException("name");
if (_ignoreChanges)
throw new InvalidOperationException("Cannot add stuff to HttpInput.Empty.");
@@ -80,16 +80,19 @@ namespace OSHttpServer
int pos = name.IndexOf('[');
if (pos != -1)
{
string name1 = name.Substring(0, pos);
string name1 = name[..pos];
string name2 = ExtractOne(name);
if (!_items.ContainsKey(name1))
_items.Add(name1, new HttpInputItem(name1, null));
_items[name1].Add(name2, value);
if (!_items.TryGetValue(name1, out HttpInputItem it))
{
it = new HttpInputItem(name1, null);
_items.Add(name1, it);
}
it.Add(name2, value);
}
else
{
if (_items.ContainsKey(name))
_items[name].Add(value);
if (_items.TryGetValue(name, out HttpInputItem it))
it.Add(value);
else
_items.Add(name, new HttpInputItem(name, value));
}
@@ -115,7 +118,7 @@ namespace OSHttpServer
/// <returns>True if the value exists</returns>
public bool Contains(string name)
{
return _items.ContainsKey(name) && _items[name].Value != null;
return _items.TryGetValue(name, out HttpInputItem it) && it.Value is not null;
}
/// <summary>
@@ -134,10 +137,12 @@ namespace OSHttpServer
int pos = name.IndexOf('[');
if (pos != -1)
{
string name1 = name.Substring(0, pos);
string name1 = name[..pos];
string name2 = ExtractOne(name);
item = new HttpInputItem(name1, null);
item.Add(name2, value);
item = new HttpInputItem(name1, null)
{
{ name2, value }
};
}
else
item = new HttpInputItem(name, value);
@@ -166,7 +171,7 @@ namespace OSHttpServer
foreach (KeyValuePair<string, HttpInputItem> item in _items)
temp += item.Value.ToString(null, true) + '&';
return temp.Length > 0 ? temp.Substring(0, temp.Length - 1) : string.Empty;
return temp.Length > 0 ? temp[..^1] : string.Empty;
}
/// <summary>
@@ -190,7 +195,7 @@ namespace OSHttpServer
++pos;
int gotMore = value.IndexOf('[', pos + 1);
if (gotMore != -1)
value = value.Substring(pos, gotMore - pos - 1) + value.Substring(gotMore);
value = string.Concat(value.AsSpan(pos, gotMore - pos - 1), value.AsSpan(gotMore));
else
value = value.Substring(pos, value.Length - pos - 1);
}

View File

@@ -18,9 +18,9 @@ namespace OSHttpServer
public class HttpInputItem : IHttpInput
{
/// <summary> Representation of a non-initialized <see cref="HttpInputItem"/>.</summary>
public static readonly HttpInputItem Empty = new HttpInputItem(string.Empty, true);
public static readonly HttpInputItem Empty = new(string.Empty, true);
private readonly IDictionary<string, HttpInputItem> _items = new Dictionary<string, HttpInputItem>();
private readonly List<string> _values = new List<string>();
private readonly List<string> _values = new();
private string _name;
private readonly bool _ignoreChanges;
@@ -109,7 +109,7 @@ namespace OSHttpServer
{
get
{
return _values.Count == 0 ? null : _values[_values.Count - 1];
return _values.Count == 0 ? null : _values[^1];
}
}
@@ -129,7 +129,7 @@ namespace OSHttpServer
/// <exception cref="InvalidOperationException">Cannot add stuff to <see cref="HttpInput.Empty"/>.</exception>
public void Add(string value)
{
if (value == null)
if (value is null)
return;
if (_ignoreChanges)
throw new InvalidOperationException("Cannot add stuff to HttpInput.Empty.");
@@ -185,7 +185,7 @@ namespace OSHttpServer
foreach (KeyValuePair<string, HttpInputItem> item in _items)
temp += item.Value.ToString(name, true) + '&';
return _items.Count > 0 ? temp.Substring(0, temp.Length - 1) : temp;
return _items.Count > 0 ? temp[..^1] : temp;
}
else
{
@@ -239,11 +239,15 @@ namespace OSHttpServer
int pos = name.IndexOf('[');
if (pos != -1)
{
string name1 = name.Substring(0, pos);
string name1 = name[..pos];
string name2 = HttpInput.ExtractOne(name);
if (!_items.ContainsKey(name1))
_items.Add(name1, new HttpInputItem(name1, null));
_items[name1].Add(name2, value);
if (!_items.TryGetValue(name1, out HttpInputItem it))
{
it = new HttpInputItem(name1, null);
_items.Add(name1, it);
}
it.Add(name2, value);
/*
HttpInputItem item = HttpInput.ParseItem(name, value);
@@ -256,8 +260,8 @@ namespace OSHttpServer
}
else
{
if (_items.ContainsKey(name))
_items[name].Add(value);
if (_items.TryGetValue(name, out HttpInputItem it2))
it2.Add(value);
else
_items.Add(name, new HttpInputItem(name, value));
}

View File

@@ -22,8 +22,8 @@ namespace OSHttpServer
public static readonly char[] UriSplitters = new[] { '/' };
public static uint baseID = 0;
private readonly NameValueCollection m_headers = new NameValueCollection();
private readonly HttpParam m_param = new HttpParam(HttpInput.Empty, HttpInput.Empty);
private readonly NameValueCollection m_headers = new();
//private readonly HttpParam m_param = new(HttpInput.Empty, HttpInput.Empty);
private Stream m_body = new MemoryStream();
private int m_bodyBytesLeft;
private ConnectionType m_connection = ConnectionType.KeepAlive;
@@ -151,9 +151,9 @@ namespace OSHttpServer
{
get
{
if(m_queryString == null)
if(m_queryString is null)
{
if(m_uri == null || m_uri.Query.Length == 0)
if(m_uri is null || m_uri.Query.Length == 0)
m_queryString = new NameValueCollection();
else
{
@@ -169,7 +169,7 @@ namespace OSHttpServer
}
}
public static readonly Uri EmptyUri = new Uri("http://localhost/");
public static readonly Uri EmptyUri = new("http://localhost/");
/// <summary>
/// Gets or sets requested URI.
/// </summary>
@@ -179,6 +179,7 @@ namespace OSHttpServer
set { m_uri = value ?? EmptyUri; } // not safe
}
/*
/// <summary>
/// Gets parameter from <see cref="QueryString"/> or <see cref="Form"/>.
/// </summary>
@@ -186,6 +187,7 @@ namespace OSHttpServer
{
get { return m_param; }
}
*/
/// <summary>
/// Gets form parameters.
@@ -219,16 +221,18 @@ namespace OSHttpServer
{
// this method was mainly created for testing.
// dont use it that much...
var request = new HttpRequest(Context);
request.Method = m_method;
var request = new HttpRequest(Context)
{
Method = m_method,
m_httpVersion = m_httpVersion,
m_queryString = m_queryString,
Uri = m_uri
};
if (AcceptTypes != null)
{
request.AcceptTypes = new string[AcceptTypes.Length];
AcceptTypes.CopyTo(request.AcceptTypes, 0);
}
request.m_httpVersion = m_httpVersion;
request.m_queryString = m_queryString;
request.Uri = m_uri;
var buffer = new byte[m_body.Length];
m_body.Read(buffer, 0, (int)m_body.Length);
@@ -296,8 +300,7 @@ namespace OSHttpServer
}
}
}
if (m_remoteIPEndPoint == null)
m_remoteIPEndPoint = m_context.LocalIPEndPoint;
m_remoteIPEndPoint ??= m_context.LocalIPEndPoint;
return m_remoteIPEndPoint;
}
@@ -375,7 +378,7 @@ namespace OSHttpServer
int indx = s.IndexOf("=", 3);
if(indx < 0 || indx >= s.Length - 1)
continue;
s = s.Substring(indx);
s = s[indx..];
addr = s.Trim();
}
}

View File

@@ -11,8 +11,8 @@ namespace OSHttpServer
{
private const string DefaultContentType = "text/html;charset=UTF-8";
private readonly IHttpClientContext m_context;
private readonly ResponseCookies m_cookies = new ResponseCookies();
private readonly NameValueCollection m_headers = new NameValueCollection();
private readonly ResponseCookies m_cookies = new();
private readonly NameValueCollection m_headers = new();
private string m_httpVersion;
private Stream m_body;
private long m_contentLength;
@@ -86,8 +86,7 @@ namespace OSHttpServer
{
get
{
if(m_body == null)
m_body = new MemoryStream();
m_body ??= new MemoryStream();
return m_body;
}
}
@@ -245,13 +244,13 @@ namespace OSHttpServer
sb.AppendFormat("Date: {0}\r\n", DateTime.Now.ToString("r"));
long len = 0;
if(m_body!= null)
if(m_body is not null)
len = m_body.Length;
if (RawBuffer != null && RawBufferLen > 0)
if (RawBuffer is not null && RawBufferLen > 0)
len += RawBufferLen;
sb.AppendFormat("Content-Length: {0}\r\n", len);
if (m_headers["Content-Type"] == null)
if (m_headers["Content-Type"] is null)
sb.AppendFormat("Content-Type: {0}\r\n", m_contentType ?? DefaultContentType);
switch(Status)
@@ -295,7 +294,7 @@ namespace OSHttpServer
continue;
}
string[] values = m_headers.GetValues(i);
if (values == null) continue;
if (values is null) continue;
foreach (string value in values)
sb.AppendFormat("{0}: {1}\r\n", headerName, value);
}
@@ -331,7 +330,7 @@ namespace OSHttpServer
m_context.TimeoutKeepAlive = m_keepAlive * 1000;
}
if (RawBuffer != null)
if (RawBuffer is not null)
{
if (RawBufferStart > RawBuffer.Length)
return;
@@ -348,7 +347,7 @@ namespace OSHttpServer
m_headerBytes = GetHeaders();
if (RawBuffer != null && RawBufferLen > 0)
if (RawBuffer is not null && RawBufferLen > 0)
{
int tlen = m_headerBytes.Length + RawBufferLen;
if(tlen < 8 * 1024)
@@ -366,13 +365,13 @@ namespace OSHttpServer
RawBuffer = null;
}
if (m_body != null && m_body.Length == 0)
if (m_body is not null && m_body.Length == 0)
{
m_body.Dispose();
m_body = null;
}
if (m_headerBytes == null && RawBuffer == null && m_body == null)
if (m_headerBytes is null && RawBuffer is null && m_body is null)
{
Sent = true;
m_context.EndSendResponse(requestID, Connection);
@@ -383,14 +382,14 @@ namespace OSHttpServer
public bool SendNextAsync(int bytesLimit)
{
if (m_headerBytes != null)
if (m_headerBytes is not null)
{
byte[] b = m_headerBytes;
m_headerBytes = null;
if (!m_context.SendAsyncStart(b, 0, b.Length))
{
if (m_body != null)
if (m_body is not null)
{
m_body.Dispose();
m_body = null;
@@ -403,7 +402,7 @@ namespace OSHttpServer
}
bool sendRes;
if (RawBuffer != null)
if (RawBuffer is not null)
{
if(RawBufferLen > 0)
{
@@ -429,7 +428,7 @@ namespace OSHttpServer
if (!sendRes)
{
RawBuffer = null;
if(m_body != null)
if(m_body is not null)
{
m_body.Dispose();
m_body = null;
@@ -443,7 +442,7 @@ namespace OSHttpServer
RawBuffer = null;
}
if (m_body != null)
if (m_body is not null)
{
if(m_body.Length != 0)
{
@@ -500,7 +499,7 @@ namespace OSHttpServer
public void CheckSendNextAsyncContinue()
{
if(m_headerBytes == null && RawBuffer == null && m_body == null)
if(m_headerBytes is null && RawBuffer is null && m_body is null)
{
Sent = true;
m_context.EndSendResponse(requestID, Connection);
@@ -513,8 +512,12 @@ namespace OSHttpServer
public void Clear()
{
if(m_body != null && m_body.CanRead)
if(m_body is not null && m_body.CanRead)
{
m_body.Dispose();
m_body = null;
}
RawBuffer = null;
}
#endregion
}

View File

@@ -72,10 +72,12 @@ namespace OSHttpServer
/// <see cref="Method"/>
string Method { get; set; }
/*
/// <summary>
/// Gets parameter from <see cref="QueryString"/> or <see cref="Form"/>.
/// </summary>
HttpParam Param { get; }
*/
/// <summary>
/// Gets variables sent in the query string