Added BasicAuth, HostName Server, HTTPS (Maybe)
This commit is contained in:
@@ -14,8 +14,7 @@ namespace Tesses.WebServer
|
||||
NetworkStream = strm;
|
||||
RequestHeaders = headers;
|
||||
ResponseHeaders = new Dictionary<string, List<string>>();
|
||||
var qp = 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
|
||||
@@ -29,24 +28,35 @@ namespace Tesses.WebServer
|
||||
{
|
||||
//local=jim&john_surname=connor&demi_surname=lovato&local=tim
|
||||
//we want to split on &
|
||||
foreach(var item in splitUrl[1].Split(new char[] { '&'},StringSplitOptions.RemoveEmptyEntries))
|
||||
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)
|
||||
{
|
||||
//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];
|
||||
}
|
||||
qp.Add(key, value);
|
||||
}
|
||||
value = itemSplit[1];
|
||||
}
|
||||
QueryParams.Add(key, value);
|
||||
}
|
||||
}
|
||||
QueryParams = qp;
|
||||
|
||||
}
|
||||
private string get_host()
|
||||
{
|
||||
@@ -54,8 +64,11 @@ namespace Tesses.WebServer
|
||||
{
|
||||
return RequestHeaders.GetFirst("Host");
|
||||
}
|
||||
return "";
|
||||
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; }
|
||||
|
||||
@@ -22,6 +22,11 @@ namespace Tesses.WebServer
|
||||
|
||||
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)
|
||||
@@ -360,5 +365,111 @@ namespace Tesses.WebServer
|
||||
}
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using HeyRed.Mime;
|
||||
using Newtonsoft.Json;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Net.Security;
|
||||
|
||||
namespace Tesses.WebServer
|
||||
{
|
||||
@@ -64,6 +66,20 @@ namespace Tesses.WebServer
|
||||
{
|
||||
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))
|
||||
@@ -178,6 +194,16 @@ namespace Tesses.WebServer
|
||||
}
|
||||
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)
|
||||
@@ -199,17 +225,21 @@ namespace Tesses.WebServer
|
||||
}
|
||||
public virtual async Task<bool> BeforeAsync(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");
|
||||
|
||||
}
|
||||
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
|
||||
@@ -220,21 +250,23 @@ namespace Tesses.WebServer
|
||||
_root = root;
|
||||
}
|
||||
IServer _root;
|
||||
private KeyValuePair<string,IServer> GetFromPath(ServerContext ctx)
|
||||
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;
|
||||
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 new KeyValuePair<string, IServer>("/",_root);
|
||||
//Console.WriteLine("HERE WE ARE");
|
||||
return ("/",Guaranteed(_root));
|
||||
}
|
||||
/// <summary>
|
||||
/// Mount the specified url and server.
|
||||
@@ -305,9 +337,150 @@ namespace Tesses.WebServer
|
||||
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);
|
||||
@@ -317,14 +490,29 @@ namespace Tesses.WebServer
|
||||
|
||||
public sealed class HttpServerListener
|
||||
{
|
||||
bool https;
|
||||
X509Certificate cert;
|
||||
IServer _server;
|
||||
TcpListener _listener;
|
||||
public HttpServerListener(IPEndPoint endPoint,IServer server)
|
||||
{
|
||||
_listener = new TcpListener(endPoint);
|
||||
_server = server;
|
||||
https = false;
|
||||
}
|
||||
public HttpServerListener(IServer server)
|
||||
{
|
||||
_listener = new TcpListener(new IPEndPoint(IPAddress.Any, 3251));
|
||||
_server = server;
|
||||
https = false;
|
||||
}
|
||||
public HttpServerListener(IPEndPoint endpoint,IServer server,X509Certificate cert)
|
||||
{
|
||||
_listener = new TcpListener(endpoint);
|
||||
_server = server;
|
||||
https = cert != null;
|
||||
this.cert = cert;
|
||||
}
|
||||
|
||||
public async Task ListenAsync(CancellationToken token)
|
||||
{
|
||||
_listener.Start();
|
||||
@@ -332,12 +520,12 @@ namespace Tesses.WebServer
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
var socket=await _listener.AcceptTcpClientAsync();
|
||||
await CommunicateHostAsync(socket);
|
||||
await CommunicateHostAsync(socket).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private string ReadHeaders(NetworkStream strm)
|
||||
private string ReadHeaders(Stream strm)
|
||||
{
|
||||
StringBuilder s = new StringBuilder();
|
||||
|
||||
@@ -375,6 +563,25 @@ namespace Tesses.WebServer
|
||||
}
|
||||
return items;
|
||||
}
|
||||
public Stream GetStream(TcpClient clt)
|
||||
{
|
||||
if(https)
|
||||
{
|
||||
SslStream sslStream = new SslStream(
|
||||
clt.GetStream(), false);
|
||||
try
|
||||
{
|
||||
sslStream.AuthenticateAsServer(cert, clientCertificateRequired: false, checkCertificateRevocation: true);
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_ = ex;
|
||||
}
|
||||
return sslStream;
|
||||
}
|
||||
return clt.GetStream();
|
||||
}
|
||||
private async Task CommunicateHostAsync(TcpClient clt)
|
||||
{
|
||||
//<METHOD> <PATH> HTTP/1.1\r\n
|
||||
@@ -387,7 +594,7 @@ namespace Tesses.WebServer
|
||||
|
||||
//RESPONSE
|
||||
|
||||
using (NetworkStream strm = clt.GetStream())
|
||||
using (Stream strm = GetStream(clt))
|
||||
{
|
||||
|
||||
string request_line = "";
|
||||
@@ -403,6 +610,9 @@ namespace Tesses.WebServer
|
||||
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 (!await _server.BeforeAsync(ctx))
|
||||
{
|
||||
switch (method)
|
||||
|
||||
Reference in New Issue
Block a user