public void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var ctx = RequestParameters.Create(context); var login = ctx.Get("login"); var role = ctx.Get("role"); var exact = ctx.Get("exact").ToBool(); if (string.IsNullOrWhiteSpace(role)) { context.Finish("{\"error\":\"emptyrole\"}", status: 500); return; } if (string.IsNullOrWhiteSpace(login)) { login = context.User.Identity.Name; } var result = false; if (login != context.User.Identity.Name) { if (!Roles.IsInRole(context.User.Identity, SecurityConst.ROLE_ADMIN)) { context.Finish("{\"error\":\"adminrequire\"}", status: 500); return; } result = Roles.IsInRole(login, role, exact); } else { result = Roles.IsInRole(context.User.Identity, role, exact); } context.Finish(result.ToString().ToLowerInvariant()); }
#pragma warning restore 219 private void AsynchronousEnd(WebContext context) { if (null == currentAsyncCall) { context.Finish("no asynchronous task ever started", "text/plain", 500); } currentAsyncCall.Wait(); if (currentAsyncCall.IsFaulted) { context.Finish("last call to async fail with " + currentAsyncCall.Exception, "text/plain", 500); } else if (currentAsyncCall.IsCanceled) { context.Finish("last call to async was cancelled", "text/plain", 500); } else { if (context.Uri.AbsolutePath.EndsWith("/xml")) { context.Finish(((UObj)currentAsyncCall.Result).ToXmlString(), "text/xml"); } else { context.Finish(((UObj)currentAsyncCall.Result).ToJson(), "application/json"); } } }
private void RunTrace(WebContext context) { try { #pragma warning disable 219 var sb = new StringBuilder(); var sw = Stopwatch.StartNew(); var parameters = PrepareParameters(context); sw.Stop(); sb.AppendLine("Prepare: " + sw.Elapsed); sw = Stopwatch.StartNew(); var result = _handler(parameters); sw.Stop(); sb.AppendLine("Execute: " + sw.Elapsed); sw = Stopwatch.StartNew(); var uson = result.ToUson(); sw.Stop(); sb.AppendLine("Usonify: " + sw.Elapsed); sw = Stopwatch.StartNew(); var json = uson.ToJson(); sw.Stop(); sb.AppendLine("Jsonify: " + sw.Elapsed); sw = Stopwatch.StartNew(); json = new JsonSerializer().Serialize("", result); sw.Stop(); sb.AppendLine("Jsonify 2: " + sw.Elapsed); context.Finish(sb.ToString()); } catch (Exception ex) { context.Finish(ex.ToString(), "text/plain", 500); } }
private bool CheckInvalidStartupConditions(WebContext ctx) { if (Application.IsInStartup) { ctx.Finish("application is in startup", status: 500); return(true); } if (Application.StartupError != null) { ctx.Finish("startup error \r\n" + Application.StartupError, status: 500); return(true); } return(false); }
public void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { if (!context.User.Identity.IsAuthenticated) { context.Finish("{\"notauth\":true}"); } bool fullinfo = context.Request.Uri.Query.Contains("full"); if (fullinfo) { CheckAllowFull(context.User.Identity); } context.Finish(context.User.Identity.stringify(fullinfo?"admin":"ui")); }
private void AsynchronousBegin(WebContext context) { if (null != currentAsyncCall) { if (!currentAsyncCall.IsCompleted) { context.Finish("{\"state\":\"run\"}"); return; } } var parameters = PrepareParameters(context); currentAsyncCall = Task.Run(() => _handler(parameters)); context.Finish("{\"state\":\"start\"}"); }
public void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var id = context.User.Identity as Identity; if(null==id)throw new Exception("invalid identity type"); if (null == id.ImpersonationSource) { if(!id.IsAdmin)throw new Exception("not admin"); } var src = id.ImpersonationSource ?? id; var p = RequestParameters.Create(context); var to = p.Get("login"); Identity newid = null; if (string.IsNullOrWhiteSpace(to)) { newid = (Identity)src; } else { var user = Users.GetUser(to); if (null != user) { newid = new Identity(user); } else { newid =new Identity{Name = to, IsAuthenticated = true}; } newid.ImpersonationSource = src; } context.User = new GenericPrincipal(newid,null); var token = TokenService.Create(context.Request); newid.Token = token; TokenService.Store(context.Response,context.Request.Uri,token); context.Finish(newid.stringify()); }
private void RenderAsWiki(XElement x, WebContext r) { var sb = new StringBuilder(); BuildWiki(sb, x); r.Finish(sb.ToString(), "text/html"); }
public void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { if (null != Override) { if (Override(this, server, context)) { return; } } var error = GetError?.Invoke(this, server, context) ?? Error; if (null != error) { throw error; } var status = GetStatus?.Invoke(this, server, context) ?? Status; var mime = GetMime?.Invoke(this, server, context) ?? Mime; var content = GetContent?.Invoke(this, server, context) ?? Content; var timeout = GetTimeout?.Invoke(this, server, context) ?? Timeout; if (0 < timeout) { Thread.Sleep(timeout); } context.Finish(content, mime, status); }
public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var data = RequestParameters.Create(context); var name = data.Get("name"); var root = EnvironmentInfo.ResolvePath("@repos@/.appdata"); Directory.CreateDirectory(root); var fileName = Path.Combine(root, name); var contentType = "text/plain"; if (fileName.EndsWith(".json")) { contentType = "application/json"; } var content = ""; if (File.Exists(fileName)) { content = File.ReadAllText(fileName); } context.Finish(content, contentType); }
public void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { this.loggy = this.loggy ?? LoggyManager.Get("handler.sendmail"); if (!Roles.IsInRole(context.User, SecurityConst.ROLE_ADMIN)) { context.Finish(new { error = "notauth" }.stringify(), status: 500); return; } var p = RequestParameters.Create(context); var count = p.num("count"); var messages = Queue.GetRequireSendMessages(count).ToArray(); var sent = 0; IList <object> errors = new List <object>(); foreach (var message in messages) { try { Sender.Send(message); Queue.MarkSent(message.Id); sent++; } catch (Exception e) { var inner = null == e.InnerException ? "" : e.InnerException.ToString(); var erinfo = new { message, error = e.ToString(), inner }; errors.Add(erinfo); if (loggy.IsForError()) { loggy.Error(erinfo.stringify()); } } } if (errors.Count == 0) { if (loggy.IsForTrace()) { loggy.Trace(new{ sent = messages.Length, ids = string.Join(", ", messages.Select(_ => _.Id)) }); } } context.Finish(new { src = messages.Length, sent, errors }.stringify(), status: errors.Count == 0?200:500); }
public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var code = context.Uri.Query.Replace("?", ""); string wikicode = "*** страница с данным кодом не найдена ***"; string tpl = "<html><body>${wikipage}</body></html>"; var wikidesc = server.Static.Get(code + ".wiki", withextensions: true); if (null == wikidesc) { wikidesc = server.Static.Get(code, withextensions: true); } if (null != wikidesc) { using (var s = wikidesc.Open()) { using (var r = new StreamReader(s)) { wikicode = r.ReadToEnd(); } if (!wikidesc.FullName.EndsWith(".wiki")) { if (wikidesc.FullName.EndsWith(".bxl") || wikidesc.FullName.EndsWith(".bxls") || wikidesc.FullName.EndsWith(".bsproj")) { wikicode = "[[code]]\r\n" + wikicode + "\r\n[[/code]]\r\n[[script-last type=bxl]]"; } else if (wikidesc.FullName.EndsWith(".js") || wikidesc.FullName.EndsWith(".css") || wikidesc.FullName.EndsWith(".cs")) { wikicode = "[[code]]\r\n" + wikicode + "\r\n[[/code]]"; } else { wikicode = wikicode.Replace("\r\n", "\r\n\r\n "); } wikicode = "= Файл: [href:" + wikidesc.FullName + "]\r\n\r\n" + wikicode; } } } var tpldesc = server.Static.Get("wiki.html"); if (null != tpldesc) { using (var s = tpldesc.Open()) { using (var r = new StreamReader(s)) { tpl = r.ReadToEnd(); } } } var wikipage = tpl.Replace("${wikipage}", wikicode); context.Finish(wikipage, "text/html"); }
private void RunSynchronous(WebContext context) { try{ var parameters = PrepareParameters(context); var obj = _handler(parameters); var result = obj.ToUson(); if (context.Uri.AbsolutePath.EndsWith("/xml")) { context.Finish(result.ToXmlString(), "text/xml"); } else { context.Finish(result.ToJson()); } } catch (Exception ex) { context.Finish(ex.ToString(), "text/plain", 500); } }
public void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var wait = context.Uri.Query.Split('=')[1].ToInt(); var api = server.Container.Get <IApi>(); try { context.Finish(api.Execute(wait).ToStr().ToLowerInvariant()); } finally { server.Container.Release(api); } }
/// <summary> /// /// </summary> /// <param name="server"></param> /// <param name="context"></param> /// <param name="callbackEndPoint"></param> /// <param name="cancel"></param> public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var container = server.Container; if (container == null) { throw new Exception("Cannot access container"); } var caProxy = container.Get <ICaWrapper>(); if (caProxy == null) { throw new Exception("Cannot access CA proxy"); } if (context.PreparedParameters == null) { context.PreparedParameters = RequestParameters.Create(context); } var certId = context.PreparedParameters.Get("cert"); var message = context.PreparedParameters.Get("message"); if (string.IsNullOrWhiteSpace(certId)) { throw new ArgumentException("Empty certificate fingerprint"); } if (string.IsNullOrWhiteSpace(message)) { throw new ArgumentException("Empty encrypted message"); } var user = caProxy.ProcessAuth(certId, message); if (user != null) { var result = ProcessUserLogin(user, server, context); var strResult = result.Result.stringify(); context.Finish(strResult); return; } context.Finish("false"); }
private bool BeforeHandlerProcessed(WebContext wc, AuthorizationReaction authorization) { if (authorization.Process) { return(false); } if (!string.IsNullOrWhiteSpace(authorization.Redirect)) { wc.Redirect(authorization.Redirect); return(true); } wc.Finish(new{ error = "not auth" }.stringify(), status: 403); return(true); }
public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var request = ResolveService <IReportRequest>("", context); request.NoFinalizeOnError = true; var waiter = Reports.Execute(request); waiter.Wait(); var result = waiter.Result; if (null != result.Error) { context.Finish(GetErrorJson(result.Error).stringify(), status: 500); } }
protected virtual HandlerResult DefaultProcess(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var result = GetResult(server, context, callbackEndPoint, cancel) ?? HandlerResult.Null; var outer = result.Result; if (result.Mime == "application/json") { var str = outer as string; if (null != str && ((str.StartsWith("{") && str.EndsWith("}")) || (str.StartsWith("[") && str.EndsWith("]")))) { outer = str.jsonify(); } outer = outer.stringify(); context.Finish(outer, result.Mime, result.State); } return result; }
private void OnRequest(Task <HttpListenerContext> task) { WebContext wc = null; try { StartWaitNextRequest(); wc = task.Result; if (CheckInvalidStartupConditions(wc)) { return; } PrepareForCrossSiteScripting(task); if (CheckOptionsMethodIsCalled(task)) { return; } if (wc.Request.ContentLength > Config.MaxRequestSize) { throw new Exception("Exceed max request size"); } CopyCookies(wc); Authenticator.Authenticate(wc.Request, wc.Response); if (Applications.Application.HasCurrent) { Applications.Application.Current.Principal.SetCurrentUser(wc.User); } var authorization = Authorizer.Authorize(wc.Request); if (BeforeHandlerProcessed(wc, authorization)) { if (!wc.Response.WasClosed) { wc.Response.Close(); } return; } new HostRequestHandler(this, wc).Execute(); } catch (Exception ex) { if (!wc.Response.WasClosed) { wc.Finish("some error occured " + ex, status: 500); } } }
protected virtual HandlerResult DefaultProcess(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var result = GetResult(server, context, callbackEndPoint, cancel) ?? HandlerResult.Null; var outer = result.Result; if (result.Mime == "application/json") { var str = outer as string; if (null != str && ((str.StartsWith("{") && str.EndsWith("}")) || (str.StartsWith("[") && str.EndsWith("]")))) { outer = str.jsonify(); } outer = outer.stringify(); context.Finish(outer, result.Mime, result.State); } return(result); }
/// <summary> /// /// </summary> /// <param name="server"></param> /// <param name="context"></param> /// <param name="callbackEndPoint"></param> /// <param name="cancel"></param> public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { if (context.PreparedParameters == null) { context.PreparedParameters = RequestParameters.Create(context); } var preparedParams = context.PreparedParameters; var fingerprint = preparedParams.Get("cert"); var cms = preparedParams.Get("message"); var container = server.Container; var caConfigProvider = container.Get <ICaConfigProvider>(); if (caConfigProvider == null) { throw new Exception("Cannot get CA config"); } var caConfig = caConfigProvider.GetConfig(); if (caConfig == null || !caConfig.GetIsValid()) { throw new Exception("Not valid CA config"); } var cmsDecryptor = new CmsDecryptor(); cmsDecryptor.Initialize(caConfig); var cmsMessage = new CmsMessage { CertificateFingerprint = fingerprint, EncryptedMessage = cms }; context.ContentType = MimeHelper.JSON; string salt; lock (TokenAuthGetSaltHandler.Sync) { salt = TokenAuthGetSaltHandler.Salts[fingerprint].Value; } var message = cmsDecryptor.Descrypt(cmsMessage); var result = message != salt ? "false" : "true"; context.Finish(result); }
public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var data = RequestParameters.Create(context); var name = data.Get("name"); var content = data.Get("content"); if (data.PostData.StartsWith("{")) { var json = Experiments.Json.Parse(data.PostData); name = (string)Experiments.Json.Get(json, "name"); content = (string)Experiments.Json.Get(json, "content"); } if (name.StartsWith("/") || name.Contains("..")) { throw new Exception("wrong and not-secure path " + name); } var root = EnvironmentInfo.ResolvePath("@repos@/.appdata"); var fileName = Path.Combine(root, name); Directory.CreateDirectory(Path.GetDirectoryName(fileName)); File.WriteAllText(fileName, content); context.Finish("OK"); }
public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { context.ContentEncoding = Encoding.UTF8; context.Finish(_content, _mime, _status); }
private void FinishAsyncRequest() { _context.Finish("true"); }
public void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { context.Finish("It's not zero", "text/plain"); }
public void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { context.Finish(""); }
public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { lock (sync) { var config = server.Config.Definition; var pdfprintpath = EnvironmentInfo.ResolvePath(config.Attr("pdfprintpath", "@repos@/../bin/pdf/bullzip/API/EXE/config.exe")); var mozillapath = EnvironmentInfo.ResolvePath(config.Attr("mozillapath", "@repos@/../bin/firefox/firefox.exe")); var reportpath = EnvironmentInfo.ResolvePath(config.Attr("reportpath", "@repos@/.reports")); Directory.CreateDirectory(reportpath); var dict = context.Uri.Query.Split('&') .Select(_ => _.Split('=')) .ToDictionary(_ => _[0], _ => Uri.UnescapeDataString(_.Length == 1 ? "1" : _[1])); var reporturl = dict["reporturl"]; var title = dict["title"]; bool cached = false; if (dict.ContainsKey("cached")) { cached = dict["cached"].ToBool(); } var hashFileName = Path.Combine(reportpath, (reporturl + "_" + title).GetMd5() + ".pdf"); if (!cached || !File.Exists(hashFileName)) { if (File.Exists(hashFileName)) { File.Delete(hashFileName); } Process.Start(pdfprintpath, "/S Output \"" + hashFileName + "\"").WaitForExit(); Process.Start(pdfprintpath, "/S ShowSettings never").WaitForExit(); Process.Start(pdfprintpath, "/S ShowPdf no").WaitForExit(); Process.Start(pdfprintpath, "/S confirmoverwrite no").WaitForExit(); var p = Process.Start(mozillapath, "-no-remote -height 300 -width 300 -p dev -url \"" + reporturl + "\""); var now = DateTime.Now; while ((DateTime.Now - now).TotalSeconds < 30) { Thread.Sleep(300); if (!File.Exists(hashFileName)) { continue; } if (new FileInfo(hashFileName).Length > 50000) { break; } } p.CloseMainWindow(); p.Close(); Process.Start(pdfprintpath, "/C ").WaitForExit(); } if (!File.Exists(hashFileName)) { throw new Exception("some errors in report generation " + hashFileName); } var pseudofileName = title.ToSafeFileName() + ".pdf"; context.SetHeader("Content-Disposition", "attachment; filename*=UTF-8''" + Uri.EscapeDataString(pseudofileName)); using (var s = File.OpenRead(hashFileName)) { context.Finish(s, "application/pdf; charset=utf-8"); s.Close(); } } }
private static void FinishWirh404(WebContext context) { context.Finish("no file found", "text/plain; charset=utf-8", 404); }
/// <summary> /// /// </summary> /// <param name="server"></param> /// <param name="request"></param> /// <param name="response"></param> /// <param name="callbackEndPoint"></param> /// <param name="cancel"></param> public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { context.Finish("command not found","text/plain; charset=utf-8",404); }
public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var container = server.Container; if (container == null) { throw new Exception("Cannot access container"); } if (context.PreparedParameters == null) { context.PreparedParameters = RequestParameters.Create(context); } var certId = context.PreparedParameters.Get("cert"); if (string.IsNullOrWhiteSpace(certId)) { throw new ArgumentException("Empty certificate fingerprint"); } var hostConfigProvider = container.Get <IHostConfigProvider>(); if (hostConfigProvider == null) { throw new Exception("Cannot resolve server role"); } var hostConfig = hostConfigProvider.GetConfig(); if (hostConfig == null) { throw new Exception("Cannot resolve server role"); } var definition = hostConfig.Definition; if (definition == null) { throw new Exception("Cannot resolve server role"); } var caAttr = definition.Attr("ca"); if (!string.IsNullOrWhiteSpace(caAttr) && caAttr.To <bool>()) { lock (Sync) { Salt saltObj; if (Salts.ContainsKey(certId)) { saltObj = Salts[certId]; if (saltObj.Expire <= DateTime.UtcNow) { saltObj = new Salt { Value = Guid.NewGuid().ToString(), Expire = DateTime.UtcNow.AddHours(1) }; Salts[certId] = saltObj; } } else { saltObj = new Salt { Value = Guid.NewGuid().ToString(), Expire = DateTime.UtcNow.AddHours(1) }; Salts[certId] = saltObj; } context.Finish("\"" + saltObj.Value + "\""); CleanUpExpiredSaltsInternal(); return; } } var caProxy = container.Get <ICaWrapper>(); if (caProxy == null) { throw new Exception("Cannot access CA proxy"); } context.ContentType = MimeHelper.JSON; var salt = caProxy.GetSalt(certId); context.Finish(salt); }
public void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { context.Finish(context.User.Identity.IsAuthenticated.ToString().ToLowerInvariant()); }
private void RenderAsNative(XElement x, WebContext r) { r.Finish(x.ToString(), "text/xml"); }