Converted to NET Standard 2.0

This commit is contained in:
Michael Nolan
2022-04-03 10:36:38 -05:00
parent dc581343a4
commit 9244284c44
15 changed files with 128 additions and 245 deletions
@@ -0,0 +1,80 @@
using System.Collections.Generic;
using System.IO;
using System;
using System.Net;
namespace Tesses.WebServer
{
public class ServerContext
{
public string Method { get; set; }
public ServerContext(string method,Stream strm,string path,Dictionary<string,List<string>> headers)
{
Method = method;
NetworkStream = strm;
RequestHeaders = headers;
ResponseHeaders = new Dictionary<string, List<string>>();
QueryParams = new Dictionary<string, List<string>>();
StatusCode = 200;
// /joel/path/luigi?local=jim&john_surname=connor&demi_surname=lovato&local=tim
string[] splitUrl = path.Split(new char[] { '?' }, 2);
if (splitUrl.Length > 0)
{
UrlPath = splitUrl[0];
if (splitUrl.Length == 2)
{
//local=jim&john_surname=connor&demi_surname=lovato&local=tim
//we want to split on &
q_parm = splitUrl[1];
}
else
{
q_parm = "";
}
ResetQueryParms();
}
}
public void ResetQueryParms()
{
QueryParams.Clear();
foreach (var item in q_parm.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries))
{
//Console.WriteLine(item);
var itemSplit = item.Split(new char[] { '=' }, 2);
if (itemSplit.Length > 0)
{
string key = itemSplit[0];
string value = "";
if (itemSplit.Length == 2)
{
value = itemSplit[1];
}
QueryParams.Add(key, value);
}
}
}
private string get_host()
{
if(RequestHeaders.ContainsKey("Host"))
{
return RequestHeaders.GetFirst("Host");
}
return Server.Address.ToString();
}
string q_parm;
public IPEndPoint Server { get; set; }
public IPEndPoint Client { get; set; }
public string Host { get { return get_host(); } }
public string UrlPath { get; set; }
public Dictionary<string,List<string>> QueryParams { get; set; }
public Dictionary<string,List<string>> RequestHeaders { get; set; }
public Dictionary<string,List<string>> ResponseHeaders { get; set; }
public Stream NetworkStream { get; set; }
public int StatusCode { get; internal set; }
}
}
@@ -0,0 +1,475 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Tesses.WebServer
{
//This file contains modified code from https://github.com/dajuric/simple-http
/// <summary>
/// Delegate executed when a file is about to be read from a body stream.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="fileName">name of the file.</param>
/// <param name="contentType">Content type.</param>
/// <returns>Stream to be populated.</returns>
public delegate Stream OnFile(string fieldName, string fileName, string contentType);
public static class DajuricSimpleHttpExtensions
{
static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> tuple, out T1 key, out T2 value)
{
key = tuple.Key;
value = tuple.Value;
}
const string BYTES_RANGE_HEADER = "Range";
static bool ParseForm(this ServerContext ctx)
{
var args = ctx.QueryParams;
string content_type = ctx.RequestHeaders.GetFirst("Content-Type");
if (content_type != "application/x-www-form-urlencoded")
return false;
var str = ctx.BodyAsString();
if (str == null)
return false;
foreach (var pair in str.Split('&'))
{
var nameValue = pair.Split('=');
if (nameValue.Length != (1 + 1))
continue;
args.Add(nameValue[0], WebUtility.UrlDecode(nameValue[1]));
}
return true;
}
static string BodyAsString(this ServerContext ctx)
{
string str = null;
using (var reader = new StreamReader(ctx.NetworkStream))
{
str = reader.ReadToEnd();
}
return str;
}
public static async Task SendStreamAsync(this ServerContext ctx, Stream strm, string contentType = "application/octet-stream")
{
//ctx.StatusCode = 200;
int start = 0, end = (int)strm.Length - 1;
if (ctx.RequestHeaders.ContainsKey(BYTES_RANGE_HEADER))
{
if (ctx.RequestHeaders[BYTES_RANGE_HEADER].Count > 1)
{
throw new NotSupportedException("Multiple 'Range' headers are not supported.");
}
var range = ctx.RequestHeaders[BYTES_RANGE_HEADER][0].Replace("bytes=", String.Empty)
.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => Int32.Parse(x))
.ToArray();
start = (range.Length > 0) ? range[0] : 0;
end = (range.Length > 1) ? range[1] : (int)(strm.Length - 1);
var hdrs = ctx.ResponseHeaders;
hdrs.Add("Accept-Ranges", "bytes");
hdrs.Add("Content-Range", "bytes " + start + "-" + end + "/" + strm.Length);
ctx.StatusCode = 206;
}
ctx.ResponseHeaders.Add("Content-Length", (end - start + 1).ToString());
ctx.ResponseHeaders.Add("Content-Type", contentType);
await ctx.WriteHeadersAsync();
if (!ctx.Method.Equals("HEAD", StringComparison.Ordinal))
{
try
{
strm.Position = start;
strm.CopyTo(ctx.NetworkStream, Math.Min(8 * 1024 * 1024, end - start + 1));
}
finally
{
strm.Close();
ctx.NetworkStream.Close();
}
}
}
static Dictionary<string, HttpFile> ParseMultipartForm(ServerContext serverCtx, OnFile onFile)
{
var args = serverCtx.QueryParams;
string content_type=serverCtx.RequestHeaders.GetFirst("Content-Type");
if (content_type.StartsWith("multipart/form-data",StringComparison.Ordinal) == false)
throw new InvalidDataException("Not 'multipart/form-data'.");
var boundary = Regex.Match(content_type, "boundary=(.+)").Groups[1].Value;
boundary = "--" + boundary;
var files = new Dictionary<string, HttpFile>();
var inputStream = new BufferedStream(serverCtx.NetworkStream);
parseUntillBoundaryEnd(inputStream, new MemoryStream(), boundary);
while (true)
{
var (n, v, fn, ct) = parseSection(inputStream, "\r\n" + boundary, onFile);
if (String.IsNullOrEmpty(n)) break;
v.Position = 0;
if (!String.IsNullOrEmpty(fn))
files.Add(n, new HttpFile(fn, v, ct));
else
args.Add(n, readAsString(v));
}
return files;
}
private static (string Name, Stream Value, string FileName, string ContentType) parseSection(Stream source, string boundary, OnFile onFile)
{
var (n, fn, ct) = readContentDisposition(source);
source.ReadByte(); source.ReadByte(); //\r\n (empty row)
var dst = String.IsNullOrEmpty(fn) ? new MemoryStream() : onFile(n, fn, ct);
if (dst == null)
throw new ArgumentException(nameof(onFile), "The on-file callback must return a stream.");
parseUntillBoundaryEnd(source, dst, boundary);
return (n, dst, fn, ct);
}
private static (string Name, string FileName, string ContentType) readContentDisposition(Stream stream)
{
const string UTF_FNAME = "utf-8''";
var l = readLine(stream);
if (String.IsNullOrEmpty(l))
return (null, null, null);
//(regex matches are taken from NancyFX) and modified
var n = Regex.Match(l, @"name=""?(?<n>[^\""]*)").Groups["n"].Value;
var f = Regex.Match(l, @"filename\*?=""?(?<f>[^\"";]*)").Groups["f"]?.Value;
string cType = null;
if (!String.IsNullOrEmpty(f))
{
if (f.StartsWith(UTF_FNAME))
f = Uri.UnescapeDataString(f.Substring(UTF_FNAME.Length));
l = readLine(stream);
cType = Regex.Match(l, "Content-Type: (?<cType>.+)").Groups["cType"].Value;
}
return (n, f, cType);
}
private static void parseUntillBoundaryEnd(Stream source, Stream destination, string boundary)
{
var checkBuffer = new byte[boundary.Length]; //for boundary checking
int b, i = 0;
while ((b = source.ReadByte()) != -1)
{
if (i == boundary.Length) //boundary found -> go to the end of line
{
if (b == '\n') break;
continue;
}
if (b == boundary[i]) //start filling the check buffer
{
checkBuffer[i] = (byte)b;
i++;
}
else
{
var idx = 0;
while (idx < i) //write the buffer data to stream
{
destination.WriteByte(checkBuffer[idx]);
idx++;
}
i = 0;
destination.WriteByte((byte)b); //write the current byte
}
}
}
private static string readLine(Stream stream)
{
var sb = new StringBuilder();
int b;
while ((b = stream.ReadByte()) != -1 && b != '\n')
sb.Append((char)b);
if (sb.Length > 0 && sb[sb.Length - 1] == '\r')
sb.Remove(sb.Length - 1, 1);
return sb.ToString();
}
private static string readAsString(Stream stream)
{
var sb = new StringBuilder();
int b;
while ((b = stream.ReadByte()) != -1)
sb.Append((char)b);
return sb.ToString();
}
/// <summary>
/// Parses body of the request including form and multi-part form data.
/// </summary>
/// <param name="request">HTTP request.</param>
/// <param name="args">Key-value pairs populated by the form data by this function.</param>
/// <returns>Name-file pair collection.</returns>
public static Dictionary<string, HttpFile> ParseBody(this ServerContext ctx)
{
return ctx.ParseBody( (n, fn, ct) => new MemoryStream());
}
/// <summary>
/// Parses body of the request including form and multi-part form data.
/// </summary>
/// <param name="request">HTTP request.</param>
/// <param name="args">Key-value pairs populated by the form data by this function.</param>
/// <param name="onFile">
/// Function called if a file is about to be parsed. The stream is attached to a corresponding <see cref="HttpFile"/>.
/// <para>By default, <see cref="MemoryStream"/> is used, but for large files, it is recommended to open <see cref="FileStream"/> directly.</para>
/// </param>
/// <returns>Name-file pair collection.</returns>
public static Dictionary<string, HttpFile> ParseBody(this ServerContext request, OnFile onFile)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
if (!request.RequestHeaders.ContainsKey("Content-Type"))
throw new ArgumentNullException("request.RequestHeaders[\"Content-Type\"]");
if (onFile == null)
throw new ArgumentNullException(nameof(onFile));
var files = new Dictionary<string, HttpFile>();
string content_type = request.RequestHeaders.GetFirst("Content-Type");
if (content_type.StartsWith("application/x-www-form-urlencoded",StringComparison.Ordinal))
{
ParseForm(request);
}
else if (content_type.StartsWith("multipart/form-data",StringComparison.Ordinal))
{
files = ParseMultipartForm(request, onFile);
}
else
throw new NotSupportedException("The body content-type is not supported.");
return files;
}
}
/// <summary>
/// HTTP file data container.
/// </summary>
public class HttpFile : IDisposable
{
/// <summary>
/// Creates new HTTP file data container.
/// </summary>
/// <param name="fileName">File name.</param>
/// <param name="value">Data.</param>
/// <param name="contentType">Content type.</param>
internal HttpFile(string fileName, Stream value, string contentType)
{
Value = value;
FileName = fileName;
ContentType = contentType;
}
/// <summary>
/// Gets the name of the file.
/// </summary>
public string FileName { get; private set; }
/// <summary>
/// Gets the data.
/// <para>If a stream is created <see cref="OnFile"/> it will be closed when this HttpFile object is disposed.</para>
/// </summary>
public Stream Value { get; private set; }
/// <summary>
/// Content type.
/// </summary>
public string ContentType { get; private set; }
/// <summary>
/// Saves the data into a file.
/// <para>Directory path will be auto created if does not exists.</para>
/// </summary>
/// <param name="fileName">File path with name.</param>
/// <param name="overwrite">True to overwrite the existing file, false otherwise.</param>
/// <returns>True if the file is saved/overwritten, false otherwise.</returns>
public bool Save(string fileName, bool overwrite = false)
{
if (File.Exists(Path.GetFullPath(fileName)))
return false;
var dir = Path.GetDirectoryName(Path.GetFullPath(fileName));
Directory.CreateDirectory(dir);
Value.Position = 0;
using (var outStream = File.OpenWrite(fileName))
Value.CopyTo(outStream);
return true;
}
/// <summary>
/// Disposes the current instance.
/// </summary>
public void Dispose()
{
if (Value != null)
{
Value?.Dispose();
Value = null;
}
}
/// <summary>
/// Disposes the current instance.
/// </summary>
~HttpFile()
{
Dispose();
}
}
/// <summary>
/// Route server, Based on SimpleHTTP (Used most of the Route Source)
/// </summary>
public delegate bool ShouldProcessFunc(ServerContext ctx);
public delegate Task HttpActionAsync(ServerContext ctx);
public delegate void HttpAction(ServerContext ctx);
public class RouteServer : Server
{
public List<(ShouldProcessFunc ShouldProcessFunc, HttpActionAsync Action)> Methods = new List<(ShouldProcessFunc ShouldProcessFunc, HttpActionAsync Action)>();
public override async Task GetAsync(ServerContext ctx)
{
await Process(ctx);
}
public override async Task PostAsync(ServerContext ctx)
{
await Process(ctx);
}
public override async Task OtherAsync(ServerContext ctx)
{
await Process(ctx);
}
public override async Task OptionsAsync(ServerContext ctx)
{
await Process(ctx);
}
private async Task Process(ServerContext ctx)
{
foreach(var (shouldProcessFunc,action) in Methods)
{
if(!shouldProcessFunc(ctx))
{
ctx.ResetQueryParms();
continue;
}
await action(ctx);
return;
}
}
/// <summary>
/// Adds the specified action to the route collection.
/// <para>The order of actions defines the priority.</para>
/// </summary>
/// <param name="shouldProcess">Function defining whether the specified action should be executed or not.</param>
/// <param name="action">Action executed if the specified pattern matches the URL path.</param>
public void Add(ShouldProcessFunc shouldProcess, HttpActionAsync action)
{
Methods.Add((shouldProcess, action));
}
/// <summary>
/// Adds the specified action to the route collection.
/// <para>The order of actions defines the priority.</para>
/// </summary>
/// <param name="url">
/// String url
/// </param>
/// <param name="action">Action executed if the specified pattern matches the URL path.</param>
/// <param name="method">HTTP method (GET, POST, DELETE, HEAD).</param>
public void Add(string url,HttpActionAsync action,string method="GET")
{
Add((e) =>
{
if (!e.Method.Equals( method,StringComparison.Ordinal))
return false;
return e.UrlPath.Equals(url,StringComparison.Ordinal);
},
action);
}
/// <summary>
/// Adds the specified action to the route collection.
/// <para>The order of actions defines the priority.</para>
/// </summary>
/// <param name="url">
/// String url
/// </param>
/// <param name="action">Action executed if the specified pattern matches the URL path.</param>
/// <param name="method">HTTP method (GET, POST, DELETE, HEAD).</param>
public void Add(string url, HttpAction action, string method = "GET")
{
Add((e) =>
{
if (!e.Method.Equals(method, StringComparison.Ordinal))
return false;
return e.UrlPath.Equals(url, StringComparison.Ordinal);
},
action);
}
/// <summary>
/// Adds the specified action to the route collection.
/// <para>The order of actions defines the priority.</para>
/// </summary>
/// <param name="shouldProcess">Function defining whether the specified action should be executed or not.</param>
/// <param name="action">Action executed if the specified pattern matches the URL path.</param>
public void Add(ShouldProcessFunc shouldProcess,HttpAction action)
{
Methods.Add((shouldProcess, (e) =>
{
action(e);
return Task.FromResult(true);
}
));
}
}
}
@@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace Tesses.WebServer
{
public class StatusCodeMap
{
public StatusCodeMap()
{
}
public static string GetStatusString(int status_code)
{
string res;
if(_statusCodeMap.Value.TryGetValue(status_code,out res))
{
return res;
}
return "";
}
public static int GetStatusCode(string status)
{
return _statusCodeMap.Value.FirstOrDefault(e=> e.Value== status).Key;
}
private static Lazy<Dictionary<int, string>> _statusCodeMap = new Lazy<Dictionary<int, string>>(() => new Dictionary<int, string>()
{
[202] = "Accepted",
[502] = "Bad Gateway",
[400] = "Bad Request",
[409] = "Conflict",
[100] = "Continue",
[201] = "Created",
[417] = "Expectation Failed",
[403] = "Forbidden",
[302] = "Found",
[504] = "Gateway Timeout",
[410] = "Gone",
[505] = "HTTP Version Not Supported",
[500] = "Internal Server Error",
[411] = "Length Required",
[405] = "Method Not Allowed",
[301] = "Moved Permanently",
[300] = "Multiple Choices",
[204] = "No Content",
[203] = "Non Authoritative Information",
[406] = "Not Acceptable",
[404] = "Not Found",
[501] = "Not Implemented",
[304] = "Not Modified",
[200] = "OK",
[206] = "Partial Content",
[402] = "Payment Required",
[412] = "Precondition Failed",
[407] = "Proxy Authentication Required",
[302] = "Redirect",
[307] = "Redirect Keep Verb",
[303] = "Redirect Method",
[416] = "Requested Range Not Satisfiable",
[413] = "Request Entry Too Large",
[408] = "Request Timeout",
[414] = "Request Uri Too Long",
[205] = "Reset Content",
[503] = "Service Unavailable",
[101] = "Switching Protocols",
[307] = "Temporary Redirect",
[401] = "Unauthorized",
[415] = "Unsupported Media Type",
[306] = "Unused",
[426] = "Upgrade Required",
[305] = "Use Proxy",
[429] = "Too Many Requests"
});
}
}
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<PackageId>Tesses.WebServer</PackageId>
<Author>Mike Nolan</Author>
<Company>Tesses</Company>
<Description>A TCP Listener HTTP(s) Server</Description>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageTags>HTTP, WebServer, Website</PackageTags>
<RepositoryUrl>https://gitlab.tesses.cf/tesses50/tesses.webserver</RepositoryUrl>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MimeTypesMap" Version="1.0.8" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>
</Project>
@@ -0,0 +1,668 @@
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using HeyRed.Mime;
using Newtonsoft.Json;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Security.Authentication;
namespace Tesses.WebServer
{
public static class Extensions
{
public static async Task WriteHeadersAsync(this ServerContext ctx)
{
string status_line = $"HTTP/1.1 {ctx.StatusCode} {StatusCodeMap.GetStatusString(ctx.StatusCode)}\r\n";
StringBuilder b = new StringBuilder(status_line);
foreach (var hdr in ctx.ResponseHeaders)
{
foreach (var v in hdr.Value)
{
b.Append($"{hdr.Key}: {v}\r\n");
}
}
b.Append("\r\n");
var data = Encoding.UTF8.GetBytes(b.ToString());
await ctx.NetworkStream.WriteAsync(data, 0, data.Length);
}
public static async Task SendFileAsync(this ServerContext ctx, string file)
{
using (var strm = File.OpenRead(file))
{
await ctx.SendStreamAsync( strm, MimeTypesMap.GetMimeType(file));
}
}
public static async Task SendExceptionAsync(this ServerContext ctx, Exception ex)
{
string name = ex.GetType().FullName;
string j = $"<html><head><title>{WebUtility.HtmlEncode(name)} thrown</title></head><body><h1>{WebUtility.HtmlEncode(name)} thrown</h1><h3>Description: {WebUtility.HtmlEncode(ex.Message)}</h3></body></html>";
ctx.StatusCode = 500;
await ctx.SendTextAsync(j);
}
public static async Task SendJsonAsync(this ServerContext ctx,object value)
{
await ctx.SendTextAsync(JsonConvert.SerializeObject(value), "application/json");
}
public static async Task SendTextAsync(this ServerContext ctx, string data, string contentType = "text/html")
{
await ctx.SendBytesAsync(Encoding.UTF8.GetBytes(data), contentType);
}
public static async Task SendBytesAsync(this ServerContext ctx, byte[] array, string contentType = "application/octet-stream")
{
using (var ms = new MemoryStream(array))
{
await ctx.SendStreamAsync( ms, contentType);
}
}
public static T2 GetFirst<T1,T2>(this Dictionary<T1,List<T2>> args,T1 key)
{
return args[key][0];
}
public static bool TryGetFirst<T1,T2>(this Dictionary<T1,List<T2>> args,T1 key,out T2 value)
{
List<T2> ls;
if (args.TryGetValue(key,out ls))
{
if(ls.Count > 0)
{
value = ls[0];
return true;
}
}
value = default(T2);
return false;
}
public static void Add<T1,T2>(this Dictionary<T1,List<T2>> list,T1 key,T2 item)
{
if (list.ContainsKey(key))
{
list[key].Add(item);
}
else
{
List<T2> items = new List<T2>();
items.Add(item);
list.Add(key, items);
}
}
public static void AddRange<T1,T2>(this Dictionary<T1,List<T2>> list,T1 key,IEnumerable<T2> items)
{
if (list.ContainsKey(key))
{
list[key].AddRange(items);
}
else
{
List<T2> items2 = new List<T2>();
items2.AddRange(items);
list.Add(key, items2);
}
}
public static bool EndsWith(this StringBuilder sb, string test,
StringComparison comparison)
{
if (sb.Length < test.Length)
return false;
string end = sb.ToString(sb.Length - test.Length, test.Length);
return end.Equals(test, comparison);
}
}
public class NotFoundServer : Server
{
public NotFoundServer(string html)
{
_html = html;
}
public NotFoundServer()
{
_html = "<html><head><title>File {url} not found</title></head><body><h1>404 Not Found</h1><h4>{url}</h4></body></html>";
}
string _html;
public override async Task GetAsync(ServerContext ctx)
{
ctx.StatusCode = 404;
await ctx.SendTextAsync( _html.Replace("{url}", WebUtility.HtmlEncode(ctx.UrlPath)));
}
}
public class StaticServer : Server
{
string _path;
IServer _server;
public StaticServer(string path)
{
_path = path;
_server = new NotFoundServer();
_defaultFileNames = new string[] {"index.html","index.htm","default.html","default.htm" };
}
string[] _defaultFileNames;
public StaticServer(string path,string[] defaultFileNames,IServer notfoundserver)
{
_path = path;
_server = notfoundserver;
_defaultFileNames = defaultFileNames;
}
public bool DefaultFileExists(string path,out string name)
{
foreach(var def in _defaultFileNames)
{
name = Path.Combine(path, def);
if(File.Exists(name))
{
return true;
}
}
name = "";
return false;
}
public override async Task GetAsync(ServerContext ctx)
{
string someUrl = Path.Combine(_path,WebUtility.UrlDecode(ctx.UrlPath.Substring(1)).Replace('/', Path.DirectorySeparatorChar));
//Console.WriteLine(someUrl);
if (Directory.Exists(someUrl))
{
string name;
if(DefaultFileExists(someUrl,out name))
{
await ctx.SendFileAsync(name);
}
}
else if (File.Exists(someUrl))
{
await ctx.SendFileAsync(someUrl);
}
else
{
await _server.GetAsync(ctx);
}
}
}
public abstract class Server : IServer
{
public static readonly NotFoundServer ServerNull = new NotFoundServer();
public IServer Guaranteed(IServer svr)
{
if(svr != null)
{
return svr;
}
return ServerNull;
}
public bool CorsHeader = true;
public abstract Task GetAsync(ServerContext ctx);
public virtual async Task PostAsync(ServerContext ctx)
{
ctx.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
await ctx.SendTextAsync("Method Not Supported");
}
public virtual async Task OptionsAsync(ServerContext ctx)
{
await ctx.WriteHeadersAsync();
ctx.NetworkStream.Close();
}
public virtual async Task OtherAsync(ServerContext ctx)
{
ctx.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
await ctx.SendTextAsync("Method Not Supported");
}
public virtual async Task<bool> BeforeAsync(ServerContext ctx)
{
return await Task.FromResult(false);
}
public void AddCors(ServerContext ctx)
{
if (CorsHeader)
{
ctx.ResponseHeaders.Add("Access-Control-Allow-Origin", "*");
ctx.ResponseHeaders.Add("Access-Control-Allow-Headers", "Cache-Control, Pragma, Accept, Origin, Authorization, Content-Type, X-Requested-With");
ctx.ResponseHeaders.Add("Access-Control-Allow-Methods", "GET, POST");
ctx.ResponseHeaders.Add("Access-Control-Allow-Credentials", "true");
}
}
}
public sealed class MountableServer : Server
{
Dictionary<string, IServer> _servers = new Dictionary<string, IServer>();
public MountableServer(IServer root)
{
_root = root;
}
IServer _root;
private (string Key,IServer Value) GetFromPath(ServerContext ctx)
{
//bool j = false;
foreach(var item in _servers.Reverse())
{
if(ctx.UrlPath.StartsWith(item.Key,StringComparison.Ordinal))
{
return (item.Key,Guaranteed(item.Value));
}
if (ctx.UrlPath == item.Key.TrimEnd('/'))
{
ctx.UrlPath += "/";
return (item.Key,Guaranteed(item.Value));
}
}
//Console.WriteLine("HERE WE ARE");
return ("/",Guaranteed(_root));
}
/// <summary>
/// Mount the specified url and server.
/// Must mount like this
/// /somePath0
/// /somePath0/someSubPath0
/// /somePath0/someSubPath0/someSubSubPath0
/// /somePath0/someSubPath0/someSubSubPath1
/// /somePath0/someSubPath1
/// /somePath0/someSubPath1/someSubSubPath0
/// /somePath0/someSubPath1/someSubSubPath1
/// </summary>
/// <param name="url">URL.</param>
/// <param name="server">Server.</param>
public void Mount(string url,IServer server)
{
_servers.Add(url, server);
}
public void Unmount(string url)
{
_servers.Remove(url);
}
public void UnmountAll()
{
_servers.Clear();
}
public override async Task GetAsync(ServerContext ctx)
{
var v = GetFromPath(ctx);
string url = '/' + ctx.UrlPath.Substring(v.Key.Length).TrimStart('/');
ctx.UrlPath = url;
await v.Value.GetAsync(ctx);
}
public override async Task PostAsync(ServerContext ctx)
{
var v = GetFromPath(ctx);
string url = '/' + ctx.UrlPath.Substring(v.Key.Length).TrimStart('/');
ctx.UrlPath = url;
await v.Value.PostAsync(ctx);
}
public override async Task<bool> BeforeAsync(ServerContext ctx)
{
var v = GetFromPath(ctx);
string old=ctx.UrlPath;
string url = '/' + ctx.UrlPath.Substring(v.Key.Length).TrimStart('/');
ctx.UrlPath = url;
var res=await v.Value.BeforeAsync(ctx);
ctx.UrlPath = old;
return res;
}
public override async Task OptionsAsync(ServerContext ctx)
{
var v = GetFromPath(ctx);
string url = '/' + ctx.UrlPath.Substring(v.Key.Length).TrimStart('/');
ctx.UrlPath = url;
await v.Value.OptionsAsync(ctx);
}
public override async Task OtherAsync(ServerContext ctx)
{
var v = GetFromPath(ctx);
string url = '/' + ctx.UrlPath.Substring(v.Key.Length).TrimStart('/');
ctx.UrlPath = url;
await v.Value.OtherAsync(ctx);
}
}
public delegate bool Authenticate(string username, string password);
public class BasicAuthServer : Server
{
public BasicAuthServer(Authenticate auth,IServer inner,string realm="SampleRealm")
{
Authenticate = auth;
InnerServer = inner;
Realm = realm;
}
public override async Task<bool> BeforeAsync(ServerContext ctx)
{
if(await Authorize(ctx))
{
return await Guaranteed(InnerServer).BeforeAsync(ctx);
}
return true;
}
public override async Task GetAsync(ServerContext ctx)
{
await Guaranteed(InnerServer).GetAsync(ctx);
}
public override async Task PostAsync(ServerContext ctx)
{
await Guaranteed(InnerServer).PostAsync(ctx);
}
public override async Task OtherAsync(ServerContext ctx)
{
await Guaranteed(InnerServer).OtherAsync(ctx);
}
public override async Task OptionsAsync(ServerContext ctx)
{
await Guaranteed(InnerServer).OptionsAsync(ctx);
}
public IServer InnerServer { get; set; }
public Authenticate Authenticate { get; set; }
public string Realm { get; set; }
private bool ValidAuth(ServerContext ctx)
{
string auth;
if (ctx.RequestHeaders.TryGetFirst("Authorization", out auth))
{
string[] authorization = auth.Split(' ');
//authorization_basic
if (authorization[0] == "Basic")
{
string[] userPass = Encoding.UTF8.GetString(Convert.FromBase64String(authorization[1])).Split(new char[] { ':' },2);
//return userPass.Equals($"{config.UserName}:{config.Password}", StringComparison.Ordinal);
return Authenticate(userPass[0], userPass[1]);
}
}
return false;
}
private async Task<bool> Authorize(ServerContext ctx)
{
if (Authenticate == null)
return true;
if (ValidAuth(ctx))
return true;
ctx.ResponseHeaders.Add("WWW-Authenticate", $"Basic realm=\"{Realm}\"");
ctx.StatusCode = 401;
await UnauthorizedPage(ctx);
return false;
}
protected virtual async Task UnauthorizedPage(ServerContext ctx)
{
await ctx.SendTextAsync("Unauthorized");
}
}
public class HostDomainServer : Server
{
public HostDomainServer(IServer alt)
{
Default = alt;
Servers = new Dictionary<string, IServer>();
}
public void Clear()
{
Servers.Clear();
}
public void Remove(string fqdn_or_ip)
{
Servers.Remove(fqdn_or_ip);
}
public IServer Default { get; set; }
Dictionary<string, IServer> Servers;
public void AddDomain(string fqdn_or_ip,IServer svr)
{
Servers.Add(fqdn_or_ip, svr);
}
public override async Task<bool> BeforeAsync(ServerContext ctx)
{
return await GetDomain(ctx).BeforeAsync(ctx);
}
public override async Task PostAsync(ServerContext ctx)
{
await GetDomain(ctx).PostAsync(ctx);
}
public override async Task OtherAsync(ServerContext ctx)
{
await GetDomain(ctx).OtherAsync(ctx);
}
public override async Task OptionsAsync(ServerContext ctx)
{
await GetDomain(ctx).OptionsAsync(ctx);
}
public override async Task GetAsync(ServerContext ctx)
{
await GetDomain(ctx).GetAsync(ctx);
}
private IServer GetDomain(ServerContext ctx)
{
string fqdn_or_ip = ctx.Host;
foreach(var item in Servers)
{
if(item.Key.Equals(fqdn_or_ip,StringComparison.Ordinal))
{
return Guaranteed(item.Value);
}
}
return Guaranteed(Default);
}
}
public interface IServer
{
void AddCors(ServerContext ctx);
Task<bool> BeforeAsync(ServerContext ctx);
Task GetAsync(ServerContext ctx);
Task PostAsync(ServerContext ctx);
Task OptionsAsync(ServerContext ctx);
Task OtherAsync(ServerContext ctx);
}
public sealed class HttpServerListener
{
public bool PrintUrls {get;set;}
bool https;
X509Certificate cert;
IServer _server;
TcpListener _listener;
SslProtocols protocols;
//
public HttpServerListener(IPEndPoint endPoint,IServer server)
{
_listener = new TcpListener(endPoint);
_server = server;
https = false;
PrintUrls=false;
}
public HttpServerListener(IServer server)
{
_listener = new TcpListener(new IPEndPoint(IPAddress.Any, 3251));
_server = server;
https = false;
PrintUrls=false;
}
public HttpServerListener(IPEndPoint endpoint,IServer server,X509Certificate cert,SslProtocols protocols=SslProtocols.Default)
{
_listener = new TcpListener(endpoint);
_server = server;
https = cert != null;
this.cert = cert;
this.protocols=protocols;
PrintUrls=false;
}
public async Task ListenAsync(CancellationToken token)
{
_listener.Start();
using (var r = token.Register(() => _listener.Stop())) {
while (!token.IsCancellationRequested)
{
var socket=await _listener.AcceptTcpClientAsync();
await CommunicateHostAsync(socket).ConfigureAwait(false);
}
}
}
private string ReadHeaders(Stream strm)
{
StringBuilder s = new StringBuilder();
var decoder = Encoding.UTF8.GetDecoder();
var nextChar = new char[1];
while (!s.EndsWith("\r\n\r\n",StringComparison.Ordinal))
{
int data = strm.ReadByte();
if(data == -1)
{
break;
}
int charCount=decoder.GetChars(new byte[] { (byte)data }, 0, 1, nextChar, 0);
if (charCount == 0) continue;
s.Append(nextChar);
}
return s.ToString();
}
private Dictionary<string,List<string>> Headers(string s,out string req_line)
{
Dictionary<string, List<string>> items = new Dictionary<string, List<string>>();
string[] lines = s.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
req_line = lines[0];
for(int i=1;i<lines.Length;i++)
{
var line_split=lines[i].Split(new[] { ": " },2,StringSplitOptions.None);
if (line_split.Length == 2)
{
items.Add(line_split[0], line_split[1]);
}
}
return items;
}
public Stream GetStream(TcpClient clt)
{
if(https)
{
SslStream sslStream = new SslStream(
clt.GetStream(), false);
try
{
sslStream.AuthenticateAsServer(cert,false,protocols,true);
}
catch (Exception ex)
{
_ = ex;
}
return sslStream;
}
return clt.GetStream();
}
private async Task CommunicateHostAsync(TcpClient clt)
{
//<METHOD> <PATH> HTTP/1.1\r\n
//HEADER1\r\n
//HEADER2\r\n
//......
//HEADERN\r\n
//\r\n
//OPTIONAL REQUEST BODY
//RESPONSE
using (Stream strm = GetStream(clt))
{
string request_line = "";
string res=ReadHeaders(strm);
var headers=Headers(res,out request_line);
// {Method} {Path} HTTP/1.1
ServerContext ctx=null;
string[] request=request_line.Split(new char[] { ' ' }, 3);
string method = request[0];
try
{
string path = request[1];
string ver = request[2];
ctx = new ServerContext(method, strm, path, headers);
ctx.Server = clt.Client.LocalEndPoint as IPEndPoint;
ctx.Client = clt.Client.RemoteEndPoint as IPEndPoint;
_server.AddCors(ctx);
if(PrintUrls)
{
Console.WriteLine(path);
}
if (!await _server.BeforeAsync(ctx))
{
switch (method)
{
case "HEAD":
case "GET":
await _server.GetAsync(ctx);
break;
case "POST":
await _server.PostAsync(ctx);
break;
case "OPTIONS":
await _server.OptionsAsync(ctx);
break;
default:
await _server.OtherAsync(ctx);
break;
}
}
}catch(Exception ex)
{
try
{
await ctx.SendExceptionAsync(ex);
}catch(Exception ex2)
{
_ = ex2;
}
}
}
}
//protected abstract Task<IResult> Get(string url,Dictionary<string,string> headers);
//protected abstract Task GetAsync(ServerContext ctx);
}
}