Change license to GPL, add VFS, directory listing and upload support

This commit is contained in:
Mike Nolan
2022-12-14 12:08:52 -06:00
parent 9277fda0d5
commit 7f44596e22
4 changed files with 1230 additions and 56 deletions
+607 -32
View File
@@ -12,10 +12,12 @@ using Newtonsoft.Json;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Security.Authentication;
using System.Web;
using Tesses.VirtualFilesystem;
namespace Tesses.WebServer
{
internal class SendEventArgs : EventArgs
internal class SendEventArgs : EventArgs
{
public string Data {get;set;}
}
@@ -493,61 +495,192 @@ namespace Tesses.WebServer
/// <summary>
/// returns 404 not found page
/// </summary>
public class NotFoundServer : Server
public class NotFoundServer : SameServer
{
/// <summary>
/// 404 not found custom html use "{url}" in your html as url
/// </summary>
/// <param name="html">the custom html</param>
public NotFoundServer(string html)
public NotFoundServer(string html) : base(html)
{
_html = html;
}
/// <summary>
///404 not found default html
/// </summary>
public NotFoundServer()
public NotFoundServer() : base("<html><head><title>File {url} not found</title></head><body><h1>404 Not Found</h1><h4>{url}</h4></body></html>")
{
_html = "<html><head><title>File {url} not found</title></head><body><h1>404 Not Found</h1><h4>{url}</h4></body></html>";
}
}
public class SameServer : Server
{
/// <summary>
/// html use "{url}" in your html as url
/// </summary>
/// <param name="html">the custom html</param>
/// <param name="statusCode">the status code</param>
public SameServer(string html,int statusCode=404)
{
_html=html;
_statusCode = statusCode;
}
int _statusCode;
string _html;
public override async Task GetAsync(ServerContext ctx)
{
ctx.StatusCode = 404;
ctx.StatusCode = _statusCode;
await ctx.SendTextAsync( _html.Replace("{url}", WebUtility.HtmlEncode(ctx.OriginalUrlPath)));
}
}
/// <summary>
/// Serve static files (doesnt allow listing files)
/// </summary>
public class StaticServer : Server
public enum WebServerPathType
{
NotFound=-1,
File=0,
Directory=1
}
public sealed class WebServerPathEntry
{
public WebServerPathEntry(string fname,WebServerPathType type,string url)
{
FileName = fname;
Type =type;
Url = url;
}
public string FileName {get;set;}
public string Url {get;set;}
public WebServerPathType Type {get;set;}
}
public interface IFileHandler
{
IEnumerable<string> ListDirectory(string path);
bool DefaultFileExists(string path,out string name);
WebServerPathEntry GetPath(string path);
Stream CreateFile(string path);
Stream Open(WebServerPathEntry entry);
void CreateDirectory(string dir);
}
public sealed class WebServerStyleFilesystemHandler : IFileHandler
{
string[] _defaultFileNames;
IVirtualFilesystem _fs;
/// <summary>
/// construct with filesystem
/// </summary>
/// <param name="fs">filesystem for root</param>
public WebServerStyleFilesystemHandler(IVirtualFilesystem fs)
{
_defaultFileNames = new string[] {"index.html","index.htm","default.html","default.htm" };
_fs=fs;
}
/// <summary>
/// construct with filesystem, custom filenames
/// </summary>
/// <param name="path">filesystem for root</param>
/// <param name="defaultFileNames">like index.html, index.htm, default.html, default.htm</param>
public WebServerStyleFilesystemHandler(IVirtualFilesystem fs,string[] defaultFileNames)
{
_fs = fs;
_defaultFileNames = defaultFileNames;
}
public void CreateDirectory(string dir)
{
_fs.CreateDirectory(Special.Root / dir);
}
public Stream CreateFile(string name)
{
return _fs.Open(Special.Root / name,FileMode.Create,FileAccess.ReadWrite,FileShare.None);
}
public bool DefaultFileExists(string path, out string name)
{
foreach(var def in _defaultFileNames)
{
var _name = Special.Root / path;
name=_name.Path;
if(_fs.FileExists(_name))
{
return true;
}
}
name = "";
return false;
}
public WebServerPathEntry GetPath(string path)
{
UnixPath someUrl = WebUtility.UrlDecode(path);
if (_fs.DirectoryExists(someUrl))
{
string name;
if(DefaultFileExists(someUrl.Path,out name))
{
return new WebServerPathEntry(name,WebServerPathType.File,path);
}else{
return new WebServerPathEntry(someUrl.Path,WebServerPathType.Directory,path);
}
}
else if (_fs.FileExists(someUrl))
{
return new WebServerPathEntry(someUrl.Path,WebServerPathType.File,path);
}
else
{
return new WebServerPathEntry(someUrl.Path,WebServerPathType.NotFound,path);
}
}
public IEnumerable<string> ListDirectory(string path)
{
foreach(var item in _fs.EnumerateDirectories(Special.Root/path))
{
yield return item.Name + "/";
}
foreach(var item in _fs.EnumerateFiles(Special.Root/path))
{
yield return item.Name;
}
}
public Stream Open(WebServerPathEntry path)
{
return _fs.Open(Special.Root / path.FileName,FileMode.Open,FileAccess.Read,FileShare.Read);
}
}
public sealed class WebServerStyleFileHandler : IFileHandler
{
string[] _defaultFileNames;
string _path;
IServer _server;
/// <summary>
/// construct with path
/// </summary>
/// <param name="path">directory for server</param>
public StaticServer(string path)
/// <param name="path">directory for root</param>
public WebServerStyleFileHandler(string path)
{
_path = path;
_server = new NotFoundServer();
_defaultFileNames = new string[] {"index.html","index.htm","default.html","default.htm" };
_defaultFileNames = new string[] {"index.html","index.htm","default.html","default.htm" };
_path=path;
}
string[] _defaultFileNames;
/// <summary>
/// construct with path, custom filenames, and server for not found
/// <summary>
/// construct with path, custom filenames
/// </summary>
/// <param name="path">directory for server</param>
/// <param name="path">directory for root</param>
/// <param name="defaultFileNames">like index.html, index.htm, default.html, default.htm</param>
/// <param name="notfoundserver">404 not found server</param>
public StaticServer(string path,string[] defaultFileNames,IServer notfoundserver)
public WebServerStyleFileHandler(string path,string[] defaultFileNames)
{
_path = path;
_server = notfoundserver;
_defaultFileNames = defaultFileNames;
}
public bool DefaultFileExists(string path,out string name)
public bool DefaultFileExists(string path,out string name)
{
foreach(var def in _defaultFileNames)
{
@@ -560,31 +693,473 @@ namespace Tesses.WebServer
name = "";
return false;
}
public override async Task GetAsync(ServerContext ctx)
public WebServerPathEntry GetPath(string url)
{
string someUrl = Path.Combine(_path,WebUtility.UrlDecode(ctx.UrlPath.Substring(1)).Replace('/', Path.DirectorySeparatorChar));
string someUrl = Path.Combine(_path,WebUtility.UrlDecode(url.Substring(1)).Replace('/', Path.DirectorySeparatorChar));
//Console.WriteLine(someUrl);
if (Directory.Exists(someUrl))
{
string name;
if(DefaultFileExists(someUrl,out name))
{
await ctx.SendFileAsync(name);
return new WebServerPathEntry(name,WebServerPathType.File,url);
}else{
return new WebServerPathEntry(someUrl,WebServerPathType.Directory,url);
}
}
else if (File.Exists(someUrl))
{
await ctx.SendFileAsync(someUrl);
return new WebServerPathEntry(someUrl,WebServerPathType.File,url);
}
else
{
await _server.GetAsync(ctx);
return new WebServerPathEntry(someUrl,WebServerPathType.NotFound,url);
}
}
public IEnumerable<string> ListDirectory(string path)
{
string someUrl = Path.Combine(_path,WebUtility.UrlDecode(path.Substring(1)).Replace('/', Path.DirectorySeparatorChar));
foreach(var item in Directory.GetDirectories(someUrl))
{
yield return $"{Path.GetFileName(item)}/";
}
foreach(var item in Directory.GetFiles(someUrl))
{
yield return Path.GetFileName(item);
}
}
public Stream CreateFile(string entry)
{
string someUrl = Path.Combine(_path,WebUtility.UrlDecode(entry.Substring(1)).Replace('/', Path.DirectorySeparatorChar));
return File.Create(someUrl);
}
public Stream Open(WebServerPathEntry entry)
{
return File.OpenRead(entry.FileName);
}
public void CreateDirectory(string dir)
{
Directory.CreateDirectory(Path.Combine(_path,dir.Substring(1).Replace('/', Path.DirectorySeparatorChar)));
}
}
public class StaticServerFileHandler : EventArgs
{
public string RealPath {get;set;}
public string CurrentHttpPath {get;set;}
public bool HasBeenHandled {get;set;}=false;
public ServerContext Context {get;set;}
public bool Cancel {get;set;}=false;
}
public enum UploadAllowedResponse
{
Yes=0,
NoISentResponse=1,
No=2
}
/// <summary>
/// Serve static files (doesnt allow listing files)
/// </summary>
public class StaticServer : Server
{
public bool AllowUpload {get;set;}=false;
bool allow=false;
public Func<ServerContext,UploadAllowedResponse> AllowedToUpload {get;set;}=DefaultAllowedToUpload;
public static UploadAllowedResponse DefaultAllowedToUpload(ServerContext ctx)
{
return UploadAllowedResponse.Yes;
}
private bool? getEnvVar()
{
string allowListStr=Environment.GetEnvironmentVariable("TESSES_WEBSERVER_ALLOW_LISTING");
if(!string.IsNullOrWhiteSpace(allowListStr))
{
string allowLst = allowListStr.ToLower();
if(allowLst == "1" || allowLst == "true" || allowLst == "on" || allowLst == "yes" || allowLst == "y" || allowLst == "t" || allowLst == "allow" || allowLst=="allowed" || allowLst == "a")
{
return true;
}
if(allowLst == "0" || allowLst == "false" || allowLst == "off" || allowLst == "no" || allowLst == "n" || allowLst == "f" || allowLst == "deny" || allowLst == "denied" || allowLst == "d")
{
return false;
}
}
return null;
}
public bool AllowListingDirectories {get {
bool? var= getEnvVar();
if(!var.HasValue)
{
return allow;
}
return var.Value;
} set {
allow=value;
}}
public EventHandler<StaticServerFileHandler> FileHandler;
IServer _server;
IFileHandler fileHandler;
IServer _forbidden;
/// <summary>
/// construct with filesystem
/// </summary>
/// <param name="path">filesystem for server</param>
public StaticServer(IVirtualFilesystem fs)
{
_server = new NotFoundServer();
fileHandler=new WebServerStyleFilesystemHandler(fs);
_forbidden = new SameServer("<html><head><title>File {url} not accessable</title></head><body><h1>403 Forbidden</h1><h4>{url}</h4></body></html>",403);
}
/// <summary>
/// construct with filesystem, custom filenames, and server for not found
/// </summary>
/// <param name="path">filesystem for server</param>
/// <param name="defaultFileNames">like index.html, index.htm, default.html, default.htm</param>
/// <param name="notfoundserver">404 not found server</param>
public StaticServer(IVirtualFilesystem fs,string[] defaultFileNames,IServer notfoundserver)
{
_server = notfoundserver;
fileHandler=new WebServerStyleFilesystemHandler(fs,defaultFileNames);
_forbidden = new SameServer("<html><head><title>File {url} not accessable</title></head><body><h1>403 Forbidden</h1><h4>{url}</h4></body></html>",403);
}
/// <summary>
/// construct with filesystem, custom filenames, and server for not found
/// </summary>
/// <param name="path">filesystem for server</param>
/// <param name="defaultFileNames">like index.html, index.htm, default.html, default.htm</param>
/// <param name="notfoundserver">404 not found server</param>
/// <param name="allowListing">whether to allow listing directory or not (overridable by environment variable with TESSES_WEBSERVER_ALLOW_LISTING=true|false)
public StaticServer(IVirtualFilesystem fs,string[] defaultFileNames,IServer notfoundserver,bool allowListing)
{
_server = notfoundserver;
fileHandler=new WebServerStyleFilesystemHandler(fs,defaultFileNames);
AllowListingDirectories = allowListing;
_forbidden = new SameServer("<html><head><title>File {url} not accessable</title></head><body><h1>403 Forbidden</h1><h4>{url}</h4></body></html>",403);
}
/// <summary>
/// construct with filesystem, custom filenames, and server for not found, server for forbidden and with option to allow/deny listing directories
/// </summary>
/// <param name="path">filesystem for server</param>
/// <param name="defaultFileNames">like index.html, index.htm, default.html, default.htm</param>
/// <param name="notfoundserver">404 not found server</param>
/// <param name="forbidden">server for forbidden files/denied listing</param>
/// <param name="allowListing">whether to allow listing directory or not (overridable by environment variable with TESSES_WEBSERVER_ALLOW_LISTING=true|false)
public StaticServer(IVirtualFilesystem fs,string[] defaultFileNames,IServer notfoundserver,IServer forbidden,bool allowListing)
{
_server = notfoundserver;
fileHandler= fileHandler=new WebServerStyleFilesystemHandler(fs,defaultFileNames);
AllowListingDirectories = allowListing;
_forbidden=forbidden;
}
/// <summary>
/// construct with filesystem, custom filenames and with option to allow/deny listing directories
/// </summary>
/// <param name="path">filesystem for server</param>
/// <param name="defaultFileNames">like index.html, index.htm, default.html, default.htm</param>
/// <param name="allowListing">whether to allow listing directory or not (overridable by environment variable with TESSES_WEBSERVER_ALLOW_LISTING=true|false)
public StaticServer(IVirtualFilesystem fs,string[] defaultFileNames,bool allowListing)
{
_server = new NotFoundServer();
fileHandler=new WebServerStyleFilesystemHandler(fs,defaultFileNames);
AllowListingDirectories = allowListing;
_forbidden = new SameServer("<html><head><title>File {url} not accessable</title></head><body><h1>403 Forbidden</h1><h4>{url}</h4></body></html>",403);
}
/// <summary>
/// construct with filesystem and with option to allow/deny listing directories
/// </summary>
/// <param name="path">filesystem for server</param>
/// <param name="allowListing">whether to allow listing directory or not (overridable by environment variable with TESSES_WEBSERVER_ALLOW_LISTING=true|false)
public StaticServer(IVirtualFilesystem fs,bool allowListing)
{
_server = new NotFoundServer();
fileHandler=new WebServerStyleFilesystemHandler(fs);
AllowListingDirectories = allowListing;
_forbidden = new SameServer("<html><head><title>File {url} not accessable</title></head><body><h1>403 Forbidden</h1><h4>{url}</h4></body></html>",403);
}
/// <summary>
/// construct with path
/// </summary>
/// <param name="path">directory for server</param>
public StaticServer(string path)
{
_server = new NotFoundServer();
fileHandler=new WebServerStyleFileHandler(path);
_forbidden = new SameServer("<html><head><title>File {url} not accessable</title></head><body><h1>403 Forbidden</h1><h4>{url}</h4></body></html>",403);
}
/// <summary>
/// construct with path, custom filenames, and server for not found
/// </summary>
/// <param name="path">directory for server</param>
/// <param name="defaultFileNames">like index.html, index.htm, default.html, default.htm</param>
/// <param name="notfoundserver">404 not found server</param>
public StaticServer(string path,string[] defaultFileNames,IServer notfoundserver)
{
_server = notfoundserver;
fileHandler=new WebServerStyleFileHandler(path,defaultFileNames);
_forbidden = new SameServer("<html><head><title>File {url} not accessable</title></head><body><h1>403 Forbidden</h1><h4>{url}</h4></body></html>",403);
}
/// <summary>
/// construct with path, custom filenames, and server for not found
/// </summary>
/// <param name="path">directory for server</param>
/// <param name="defaultFileNames">like index.html, index.htm, default.html, default.htm</param>
/// <param name="notfoundserver">404 not found server</param>
/// <param name="allowListing">whether to allow listing directory or not (overridable by environment variable with TESSES_WEBSERVER_ALLOW_LISTING=true|false)
public StaticServer(string path,string[] defaultFileNames,IServer notfoundserver,bool allowListing)
{
_server = notfoundserver;
fileHandler=new WebServerStyleFileHandler(path,defaultFileNames);
AllowListingDirectories = allowListing;
_forbidden = new SameServer("<html><head><title>File {url} not accessable</title></head><body><h1>403 Forbidden</h1><h4>{url}</h4></body></html>",403);
}
/// <summary>
/// construct with path, custom filenames, and server for not found, server for forbidden and with option to allow/deny listing directories
/// </summary>
/// <param name="path">directory for server</param>
/// <param name="defaultFileNames">like index.html, index.htm, default.html, default.htm</param>
/// <param name="notfoundserver">404 not found server</param>
/// <param name="forbidden">server for forbidden files/denied listing</param>
/// <param name="allowListing">whether to allow listing directory or not (overridable by environment variable with TESSES_WEBSERVER_ALLOW_LISTING=true|false)
public StaticServer(string path,string[] defaultFileNames,IServer notfoundserver,IServer forbidden,bool allowListing)
{
_server = notfoundserver;
fileHandler=new WebServerStyleFileHandler(path,defaultFileNames);
AllowListingDirectories = allowListing;
_forbidden=forbidden;
}
/// <summary>
/// construct with path, custom filenames and with option to allow/deny listing directories
/// </summary>
/// <param name="path">directory for server</param>
/// <param name="defaultFileNames">like index.html, index.htm, default.html, default.htm</param>
/// <param name="allowListing">whether to allow listing directory or not (overridable by environment variable with TESSES_WEBSERVER_ALLOW_LISTING=true|false)
public StaticServer(string path,string[] defaultFileNames,bool allowListing)
{
_server = new NotFoundServer();
fileHandler=new WebServerStyleFileHandler(path,defaultFileNames);
AllowListingDirectories = allowListing;
_forbidden = new SameServer("<html><head><title>File {url} not accessable</title></head><body><h1>403 Forbidden</h1><h4>{url}</h4></body></html>",403);
}
/// <summary>
/// construct with path and with option to allow/deny listing directories
/// </summary>
/// <param name="path">directory for server</param>
/// <param name="allowListing">whether to allow listing directory or not (overridable by environment variable with TESSES_WEBSERVER_ALLOW_LISTING=true|false)
public StaticServer(string path,bool allowListing)
{
_server = new NotFoundServer();
fileHandler=new WebServerStyleFileHandler(path);
AllowListingDirectories = allowListing;
_forbidden = new SameServer("<html><head><title>File {url} not accessable</title></head><body><h1>403 Forbidden</h1><h4>{url}</h4></body></html>",403);
}
public bool DefaultFileExists(string path,out string name)
{
return fileHandler.DefaultFileExists(path,out name);
}
public override async Task OtherAsync(ServerContext ctx)
{
if(ctx.Method == "PUT")
{
if(AllowUpload)
{
var res=AllowedToUpload(ctx);
if(res == UploadAllowedResponse.Yes)
{
bool fileExists = fileHandler.GetPath(ctx.UrlPath).Type == WebServerPathType.File;
using(var file = fileHandler.CreateFile(ctx.UrlPath))
{
await ctx.ReadToStreamAsync(file);
}
ctx.StatusCode = fileExists ? 204 : 201;
ctx.ResponseHeaders.Add("Content-Location",ctx.UrlPath);
await ctx.WriteHeadersAsync();
}else if(res == UploadAllowedResponse.No)
{
await _forbidden.GetAsync(ctx);
}
}
}
}
public override async Task PostAsync(ServerContext ctx)
{
var fileEntry = fileHandler.GetPath(ctx.UrlPath);
if(fileEntry.Type == WebServerPathType.Directory)
{
if(AllowUpload)
{
var res=AllowedToUpload(ctx);
if(res == UploadAllowedResponse.Yes)
{
//upload files and dirs
var res0= ctx.ParseBody((fieldName,fileName,ctype)=>{
return fileHandler.CreateFile($"{ctx.UrlPath}/{fileName.TrimStart('/')}");
});
foreach(var item in res0)
{
item.Value.Dispose();
}
List<string> dirs=new List<string>();
if(ctx.QueryParams.TryGetValue("mkdir",out dirs))
{
foreach(var dir in dirs)
{
fileHandler.CreateDirectory($"{ctx.UrlPath}/{dir.TrimStart('/')}");
}
}
}else if(res == UploadAllowedResponse.No)
{
await _forbidden.GetAsync(ctx);
}
}
}
}
public override async Task GetAsync(ServerContext ctx)
{
var fileEntry = fileHandler.GetPath(ctx.UrlPath);
try{
switch(fileEntry.Type)
{
case WebServerPathType.File:
using(var strm = fileHandler.Open(fileEntry))
await ctx.SendStreamAsync(strm,HeyRed.Mime.MimeTypesMap.GetMimeType(fileEntry.FileName));
break;
case WebServerPathType.Directory:
if(AllowListingDirectories)
{
DirectoryLister lister=new DirectoryLister();
lister.FromDirectory(fileHandler,ctx.UrlPath,ctx.OriginalUrlPath);
await lister.GetAsync(ctx);
}
else
{
await _forbidden.GetAsync(ctx);
}
break;
case WebServerPathType.NotFound:
await _server.GetAsync(ctx);
break;
}
}catch(UnauthorizedAccessException ex)
{
_=ex;
await _forbidden.GetAsync(ctx);
}
}
}
public class DirectoryLister : Server
{
public static string GetFileName(string url)
{
if(Path.DirectorySeparatorChar == '/')
{
return Path.GetFileName(url);
}
return Path.GetFileName(url.Replace('/',Path.DirectorySeparatorChar));
}
private static string _getFileNameWithoutQuery(string url)
{
int r = url.IndexOf('?');
if(r > -1)
{
return GetFileName(url.Remove(r).TrimEnd('/')) + (url.EndsWith("/") ? "/" : "");
}
return GetFileName(url.TrimEnd('/')) + (url.EndsWith("/") ? "/" : "");
}
static string defaultText=GetEnumerable("Default","",new string[0]);
string curText=defaultText;
public static string GetEnumerable(string title,string desc,IEnumerable<string> entries)
{
/*if(!this.ln.Path.EndsWith("/"))
{
SendRedirect(this.ln.Path + '/');
return;
}*/
StringBuilder b=new StringBuilder();
b.Append($"<!doctype><html><head><title>{HttpUtility.HtmlEncode(title)}</title></head><body><center><h1>{HttpUtility.HtmlEncode(title)}</h1></center><center>{HttpUtility.HtmlEncode(desc)}</center><hr><a href=\"..\">../</a><br>");
foreach(var entry in entries)
{
//<a href=
b.Append($"<a href=\"{HttpUtility.HtmlAttributeEncode(entry)}\">{HttpUtility.HtmlEncode(_getFileNameWithoutQuery(entry))}</a><br>");
}
b.Append("<hr><br><center><a href=\"https://www.nuget.org/packages/Tesses.WebServer\">Tesses.WebServer</a></center></body></html>");
return b.ToString();
}
public string Title {get;set;}="Directory Listing";
public string Description {get;set;}="";
public void FromEnumerable(string title,string desc,IEnumerable<string> entries)
{
curText = GetEnumerable(title,desc,entries);
}
public void FromDirectory(string title,string desc,string directory,string reqPath)
{
List<string> items=new List<string>();
foreach(var item in Directory.EnumerateDirectories(directory))
{
items.Add(item + "/");
}
foreach(var item in Directory.EnumerateFiles(directory))
{
items.Add(item);
}
FromEnumerable(title,desc,items);
}
public void FromDirectory(string directory,string reqPath)
{
FromDirectory($"Index of {reqPath}","Directory listing",directory,reqPath);
}
public void FromDirectory(IFileHandler handler,string reqPath,string ogPath="/")
{
FromEnumerable($"Index of {ogPath}","Directory listing",handler.ListDirectory(reqPath));
}
public override async Task GetAsync(ServerContext ctx)
{
await ctx.SendTextAsync(curText);
}
}
/// <summary>
/// Server where you can change inner server
/// </summary>