public PipelineData Process(PipelineData Input) { HttpListenerRoutedContext context = Input.PrimaryData as HttpListenerRoutedContext; var path0 = context.Request.Url.LocalPath.Substring(1); StorageItem Result; if (context.Request.HttpMethod == HttpMethod.Get.Method) { if (ApplicationStorage.ObtainItemFromRelativeURL(path0, out Result, false)) { if (Result.StorageItemType == StorageItemType.Folder) { StorageFile DefaultPage; if (((StorageFolder)Result).GetFile(GlobalConfiguration.GetDefaultPage(LWMSCoreServer.TrustedInstallerAuth), out DefaultPage, false)) { Tools00.SendFile(context, DefaultPage); (Input.SecondaryData as HttpPipelineArguments).isHandled = true; return(Input); } } else { Tools00.SendFile(context, Result.ToStorageFile()); (Input.SecondaryData as HttpPipelineArguments).isHandled = true; return(Input); } } } return(Input); }
internal void ProcessContext_Internal(HttpListenerContext context) { var a = new HttpListenerRoutedContext(context, PipelineAuth); var output = HttpPipelineProcessor.Process(new PipelineData(a, new HttpPipelineArguments(), null, context.GetHashCode())); (output.PrimaryData as HttpListenerRoutedContext).Response.OutputStream.Close(); }
public PipelineData Process(PipelineData Input) { //if (((HttpPipelineArguments)Input.SecondaryData).isHandled == true) return Input; HttpListenerRoutedContext context = Input.PrimaryData as HttpListenerRoutedContext; Trace.WriteLine(Language.Query("LWMS.ErrorResponseUnit.UnhandledRequest", "Unhandled Http Pipeline. Request: {0}", HttpUtility.UrlDecode((context).Request.RawUrl))); if (context.Request.HttpMethod == HttpMethod.Get.Method) { var _404 = GlobalConfiguration.GetPage404(LWMSCoreServer.TrustedInstallerAuth); if (File.Exists(_404)) { Tools00.SendFile(context, new FileInfo(_404), HttpStatusCode.NotFound); } else { Tools00.SendMessage(context, "<html><body><h1>404 File Not Found</h1><hr/><p>Hosted with LWMS.</p></body></html>", HttpStatusCode.NotFound); } } else { Tools00.SendMessage(context, "<html><body><h1>Error 501</h1><hr/><p>Your request is not support yet by the server.</p></body></html>", HttpStatusCode.NotImplemented); } (Input.SecondaryData as HttpPipelineArguments).isHandled = true; return(Input); }
/// <summary> /// Send a message to specific http listener context with given status code. /// </summary> /// <param name="context"></param> /// <param name="Message"></param> /// <param name="StatusCode"></param> public static void SendMessage(HttpListenerRoutedContext context, string Message, HttpStatusCode StatusCode = HttpStatusCode.OK) { var bytes = Encoding.UTF8.GetBytes(Message); context.Response.Headers.Remove(HttpResponseHeader.Server); context.Response.Headers.Set(HttpResponseHeader.Server, "LWMS/" + LWMSCoreServer.ServerVersion); context.Response.ContentType = "text/html"; context.Response.ContentLength64 = bytes.Length; context.Response.StatusCode = (int)StatusCode; context.Response.ContentEncoding = Encoding.UTF8; context.Response.OutputStream.Write(bytes); context.Response.OutputStream.Flush(); }
public PipelineData Process(PipelineData Input) { { HttpListenerRoutedContext context = Input.PrimaryData as HttpListenerRoutedContext; if (requests is null) { requests = ApplicationConfiguration.Current.GetValueArray("RoutedRequests"); } if (RouteTargets == null) { var targets = ApplicationConfiguration.Current.GetValueArray("RouteTargets"); RouteTargets = new List <MappedType>(); //Initialize the targets. foreach (var item in targets) { var parted = item.Split(','); FileInfo fi = new(parted[0]); var asm = DomainManager.LoadFromFile(context.PipelineAuth, fi.FullName); var t = asm.GetType(parted[1]); MappedType mappedType = MappedType.CreateFrom(t); RouteTargets.Add(mappedType); } } else if (RouteTargets.Count is 0) { var targets = ApplicationConfiguration.Current.GetValueArray("RouteTargets"); foreach (var item in targets) { var parted = item.Split(','); FileInfo fi = new(parted[0]); var asm = DomainManager.LoadFromFile(context.PipelineAuth, fi.FullName); var t = asm.GetType(parted[1]); MappedType mappedType = MappedType.CreateFrom(t); RouteTargets.Add(mappedType); } } var path0 = context.Request.Url.LocalPath.Substring(1); //Dispose the first '/' if (path0 is not "") //Ignore when the path is empty to prevent potential problems when performing matching. { for (int i = 0; i < requests.Length; i++) { if (path0.ToUpper().StartsWith(requests[i].ToUpper()))//Ignore case { (Input.SecondaryData as HttpPipelineArguments).isHandled = (RouteTargets[i].TargetObject as IHttpEventHandler).Handle(context, requests[i]); return(Input); } } } } return(Input); }
public static void ProcessContent(HttpListenerRoutedContext content, string path) { string Content = File.ReadAllText(path); { //Process. StringBuilder stringBuilder = new StringBuilder(Content); stringBuilder = stringBuilder.Replace("{OS.Description}", RuntimeInformation.OSDescription); stringBuilder = stringBuilder.Replace("{Runtime.Framework}", RuntimeInformation.FrameworkDescription); stringBuilder = stringBuilder.Replace("{LWMS.Core.Version}", Assembly.GetAssembly(typeof(LWMSCoreServer)).GetName().Version.ToString()); stringBuilder = stringBuilder.Replace("{LWMS.Shell.Version}", Assembly.GetEntryAssembly().GetName().Version.ToString()); stringBuilder = stringBuilder.Replace("{LWMS.Architect}", RuntimeInformation.ProcessArchitecture.ToString()); stringBuilder = stringBuilder.Replace("{OS.Architect}", RuntimeInformation.OSArchitecture.ToString()); stringBuilder = stringBuilder.Replace("{DateTime.Now}", DateTime.Now.ToString()); foreach (var item in Prefixes) { stringBuilder = stringBuilder.Replace($"{item.Key}", item.Value); } Tools00.SendMessage(content, stringBuilder.ToString()); } }
public PipelineData Process(PipelineData Input) { HttpListenerRoutedContext context = Input.PrimaryData as HttpListenerRoutedContext; var path0 = context.Request.Url.LocalPath.Substring(1); var path1 = Path.Combine(GlobalConfiguration.GetWebSiteContentRoot(context.PipelineAuth), path0); if (Directory.Exists(path1)) { var DefaultPage = Path.Combine(path1, GlobalConfiguration.GetDefaultPage(context.PipelineAuth)); if (File.Exists(DefaultPage)) { if (path1.EndsWith("htm") || path1.EndsWith("html")) { ProcessContent(context, DefaultPage); (Input.SecondaryData as HttpPipelineArguments).isHandled = true; } } else { } } else { if (File.Exists(path1)) { if (path1.EndsWith("htm") || path1.EndsWith("html")) { ProcessContent(context, path1); (Input.SecondaryData as HttpPipelineArguments).isHandled = true; } } else { } //Console.WriteLine("Directory Not Found."); } return(Input); }
public PipelineData Process(PipelineData Input) { { HttpListenerRoutedContext context = Input.PrimaryData as HttpListenerRoutedContext; var path0 = context.Request.Url.LocalPath.Substring(1); if (path0.ToUpper().StartsWith("BLOGS")) { var path1 = path0.Substring(path0.IndexOf("/") + 1); StorageFile f; if (path1.ToUpper().EndsWith(".INFO")) { } else { if (SharedResources.Articles.GetFile(path1, out f, false)) { Trace.WriteLine("MDBlog>>Article:" + f.Name); if (!f.ItemPath.ToUpper().EndsWith(".MD")) { Tools00.SendFile(context, f); (Input.SecondaryData as HttpPipelineArguments).isHandled = true; return(Input); } var MDContnet = File.ReadAllText(f.ItemPath); if (SharedResources.isMarkdownUnavailable is false) { MDContnet = Markdown.ToHtml(MDContnet); Trace.WriteLine("MDBlog>>Article>>MD"); } string Title = f.Name; StorageFile info; if (SharedResources.Articles.GetFile(path1 + ".info", out info, false)) { var infos = File.ReadAllLines(info.ItemPath); if (infos.Length > 0) { Title = infos[0]; } } var FinalContent = SharedResources.ArticleTemplate_.Replace("%Content%", MDContnet).Replace("%Title%", Title); context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(FinalContent)); (Input.SecondaryData as HttpPipelineArguments).isHandled = true; return(Input); } } { Trace.WriteLine("MDBlog>>MainPage"); var list = SharedResources.Articles.GetFiles(); var MainContent = SharedResources.ArticleListTemplate_; var ItemTemplate = SharedResources.ArticleListItemTemplate_; var ItemList = ""; string LinkPrefix = "./Blogs/"; if (path0.ToUpper().StartsWith("BLOGS/")) { LinkPrefix = "./"; } foreach (var item in list) { if (item.Name.ToUpper().EndsWith(".INFO")) { var infos = File.ReadAllLines(item.ItemPath); if (infos.Length > 0) { ItemList += ItemTemplate.Replace("%Title%", infos[0]).Replace("%Link%", LinkPrefix + item.Name.Substring(0, item.Name.Length - 5)); } } } var FinalContent = MainContent.Replace("%Content%", ItemList).Replace("%Title%", ApplicationConfiguration.Current.GetValue("BlogTitle", "LWMS Blog")); Tools00.SendMessage(context, FinalContent); (Input.SecondaryData as HttpPipelineArguments).isHandled = true; return(Input); } } (Input.SecondaryData as HttpPipelineArguments).isHandled = false; return(Input); } }
public bool Handle(HttpListenerRoutedContext context, string HttpPrefix) { var MappedDirectory = ApplicationConfiguration.Current.GetValue(HttpPrefix, null); if (MappedDirectory == null) { MappedDirectory = ApplicationConfiguration.Current.GetValue("*"); if (MappedDirectory == null) { MappedDirectory = GlobalConfiguration.GetWebSiteContentRoot(context.PipelineAuth); } } string CutPath = context.Request.Url.LocalPath.Substring(1).Substring(HttpPrefix.Length); var path = Path.Combine(MappedDirectory, CutPath); Trace.WriteLine($"Final:{CutPath}"); if (Directory.Exists(path)) { //Visit Directory DirectoryInfo directoryInfo = new DirectoryInfo(path); StringBuilder folders = new StringBuilder(); StringBuilder files = new StringBuilder(); string Readme = ""; { if (CutPath != "") { folders.Append(SharedResources.DirectoryItemFolderTemplate.Replace("%Name%", "..").Replace("%Date%", "")).Replace("%Link%", "./../"); } foreach (var item in directoryInfo.EnumerateDirectories()) { folders.Append(SharedResources.DirectoryItemFolderTemplate.Replace("%Name%", item.Name).Replace("%Date%", item.LastWriteTimeUtc + "")).Replace("%Link%", "./" + item.Name + "/"); } foreach (var item in directoryInfo.EnumerateFiles()) { if (item.Name.ToUpper() == "README") { Readme = File.ReadAllText(item.FullName); } files.Append(SharedResources.DirectoryItemFileTemplate.Replace("%Name%", item.Name).Replace("%Date%", item.LastWriteTimeUtc + "").Replace("%Size%", Math.Round(((double)item.Length) / 1024.0) + " KB")).Replace("%Link%", "./" + item.Name); } } var content = SharedResources.DirectoryTemplate.Replace("%Folders%", folders.ToString()).Replace("%Files%", files.ToString()).Replace("%Address%", ToHTMLString(context.Request.Url.LocalPath)).Replace("%Readme%", Readme); Tools00.SendMessage(context, content); return(true); } else { //Visit File if (File.Exists(path)) { FileInfo fi = new FileInfo(path); if (Tools00.ObtainMimeType(fi.Extension).StartsWith("text")) { var content = SharedResources.TextViewerTemplate.Replace("%Content%", ToHTMLString(File.ReadAllText(fi.FullName))).Replace("%Address%", ToHTMLString(context.Request.Url.LocalPath)); Tools00.SendMessage(context, content); return(true); } else { Tools00.SendFile(context, fi); return(true); } } } return(false); }
/// <summary> /// Send a file to specific http listener context with given status code. /// </summary> /// <param name="context"></param> /// <param name="f"></param> /// <param name="StatusCode"></param> public static void SendFile(HttpListenerRoutedContext context, FileInfo f, HttpStatusCode StatusCode = HttpStatusCode.OK, string ContentType = null) { using (FileStream fs = f.OpenRead()) { try { Trace.WriteLine(Language.Query("LWMS.Utilities.Tools00.SendFile.Access", "Access:{0}", f.FullName.Substring(GlobalConfiguration.GetWebSiteContentRoot(LWMSCoreServer.TrustedInstallerAuth).Length))); var BUF_LENGTH = GlobalConfiguration.GetBUF_LENGTH(LWMSCoreServer.TrustedInstallerAuth); byte[] buf = new byte[BUF_LENGTH]; if (ContentType == null) { context.Response.ContentType = ObtainMimeType(f.Extension); } else { context.Response.ContentType = ContentType; } context.Response.ContentEncoding = Encoding.UTF8; bool EnableRange = GlobalConfiguration.GetEnableRange(LWMSCoreServer.TrustedInstallerAuth); if (EnableRange == true) { context.Response.AddHeader("Accept-Ranges", "bytes"); } else { context.Response.AddHeader("Accept-Ranges", "none"); } context.Response.Headers.Remove(HttpResponseHeader.Server); context.Response.Headers.Set(HttpResponseHeader.Server, "LWMS/" + LWMSCoreServer.ServerVersion); string range = null; List <Range> ranges = new List <Range>(); if (context.Request.HttpMethod == HttpMethod.Head.Method) { context.Response.OutputStream.Flush(); return; } if (EnableRange == true) { try { range = context.Request.Headers["Range"]; if (range != null) { range = range.Trim(); range = range.Substring(6); var rs = range.Split(','); foreach (var item in rs) { ranges.Add(Range.FromString(item)); } } } catch (Exception) { } } if (ranges.Count == 0) { context.Response.ContentLength64 = f.Length; context.Response.StatusCode = (int)StatusCode; int L = 0; while ((L = fs.Read(buf, 0, BUF_LENGTH)) != 0) { context.Response.OutputStream.Write(buf, 0, L); context.Response.OutputStream.Flush(); } } else { context.Response.StatusCode = 206; context.Response.StatusDescription = "Partial Content"; var OriginalContentType = "Content-Type: " + context.Response.ContentType; context.Response.ContentType = "multipart/byteranges; boundary=" + Boundary; string _Boundary = "--" + Boundary; var NewLine = Environment.NewLine; foreach (var item in ranges) { //string header = _Boundary+"\r\n"+OriginalContentType + "\r\n" + "Content-Range: bytes " + item.ToString() + "/" + fs.Length+"\r\n\r\n" ; context.Response.Headers.Add(HttpResponseHeader.ContentRange, "bytes " + item.ToString() + "/" + fs.Length); long length = 0; long L = 0; { //Calculate length to send and left-starting index. if (item.R == long.MinValue || item.R > fs.Length) { length = fs.Length - item.L; } else if (item.L == long.MinValue || item.L < 0) { length = item.R; } else { length = item.R - item.L; } if (item.L != long.MinValue) { L = item.L; } } fs.Seek(L, SeekOrigin.Begin); int _Length; while (L < length) { if (length - L > BUF_LENGTH) { L += (_Length = fs.Read(buf, 0, BUF_LENGTH)); } else { L += (_Length = fs.Read(buf, 0, (int)(length - L))); } context.Response.OutputStream.Write(buf, 0, _Length); context.Response.OutputStream.Flush(); } break; } context.Response.OutputStream.Flush(); } } catch (Exception e) { Trace.WriteLine(Language.Query("LWMS.Utilities.Tools00.SendFile.Failed", "Cannot send file:{0}.", e.HResult.ToString())); } } }
/// <summary> /// Send a file to specific http listener context with given status code. /// </summary> /// <param name="context"></param> /// <param name="f"></param> /// <param name="StatusCode"></param> /// <param name="ContentType"></param> public static void SendFile(HttpListenerRoutedContext context, StorageFile f, HttpStatusCode StatusCode = HttpStatusCode.OK, string ContentType = null) { SendFile(context, f.ToFileInfo(LWMSCoreServer.TrustedInstallerAuth), StatusCode, ContentType); }
public bool Handle(HttpListenerRoutedContext context, string HttpPrefix) { { var path0 = context.Request.Url.LocalPath.Substring(1); if (path0.ToUpper().StartsWith(HttpPrefix.ToUpper())) { var path1 = path0.Substring(HttpPrefix.Length); //path1 = path1.Substring(path1.IndexOf("/") + 1); StorageFile f; if (path1.ToUpper().EndsWith(".INFO")) { } else { if (SharedResources.Articles.GetFile(path1, out f, false)) { Trace.WriteLine("MDBlog>>Article:" + f.Name); if (!f.ItemPath.ToUpper().EndsWith(".MD")) { Tools00.SendFile(context, f); return(true); } var MDContnet = File.ReadAllText(f.ItemPath); if (SharedResources.isMarkdownUnavailable is false) { MDContnet = Markdown.ToHtml(MDContnet); } string Title = f.Name; StorageFile info; if (SharedResources.Articles.GetFile(path1 + ".info", out info, false)) { var infos = File.ReadAllLines(info.ItemPath); if (infos.Length > 0) { Title = infos[0]; } } var FinalContent = SharedResources.ArticleTemplate_.Replace("%Content%", MDContnet).Replace("%Title%", Title); context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(FinalContent)); return(true); } } { Trace.WriteLine("MDBlog>>MainPage"); try { var list = SharedResources.Articles.GetFiles(); var MainContent = SharedResources.ArticleListTemplate_; var ItemTemplate = SharedResources.ArticleListItemTemplate_; var ItemList = ""; //string LinkPrefix = "./" + (HttpPrefix.Split("/").Last()) + "/"; //if (path0.ToUpper().StartsWith(HttpPrefix.ToUpper())) var LinkPrefix = "./"; foreach (var item in list) { if (item.Name.ToUpper().EndsWith(".INFO")) { var infos = File.ReadAllLines(item.ItemPath); if (infos.Length > 0) { ItemList += ItemTemplate.Replace("%Title%", infos[0]).Replace("%Link%", LinkPrefix + item.Name.Substring(0, item.Name.Length - 5)); } } } var FinalContent = MainContent.Replace("%Content%", ItemList).Replace("%Title%", ApplicationConfiguration.Current.GetValue("BlogTitle", "LWMS Blog")); Tools00.SendMessage(context, FinalContent); //context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(FinalContent)); return(true); } catch (Exception e) { Trace.WriteLine(e); } } } return(false); } }