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()); }
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()); }
/// <summary> /// /// </summary> /// <param name="server"></param> /// <param name="callcontext"></param> /// <param name="callbackEndPoint"></param> /// <param name="cancel"></param> public void Run(IHostServer server, HttpListenerContext callcontext, string callbackEndPoint, CancellationToken cancel){ var abspath = callcontext.Request.Url.AbsolutePath; if (string.IsNullOrWhiteSpace(abspath) || abspath == "/") { abspath = DefaultPage; } var staticdescriptor = server.Static.Get(abspath, callcontext); if (null == staticdescriptor){ callcontext.Finish("no file found", "text/plain; charset=utf-8", status: 404); return; } var filetime = callcontext.SetLastModified(staticdescriptor.GetLastVersion()); if (filetime <= callcontext.GetIfModifiedSince()) { callcontext.Finish("", status: 304); } else { callcontext.Response.AddHeader("Qorpent-Disposition",staticdescriptor.FullName); if (staticdescriptor.IsFixedContent){ callcontext.Finish(staticdescriptor.FixedContent, staticdescriptor.MimeType + "; charset=utf-8"); } else{ using (var s = staticdescriptor.Open()) { callcontext.Finish(s, staticdescriptor.MimeType + "; charset=utf-8"); s.Close(); } } } }
/// <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); }
/// <summary> /// Выполняет указанный запрос /// </summary> /// <param name="server"></param> /// <param name="callcontext"></param> /// <param name="callbackEndPoint"></param> /// <param name="cancel"></param> public void Run(IHostServer server, HttpListenerContext callcontext, string callbackEndPoint, CancellationToken cancel) { SetCurrentUser(server, callcontext); callcontext.Response.ContentEncoding = Encoding.UTF8; callcontext.Response.Headers["Content-Encoding"] = "utf-8"; var context = server.Application.Container.Get<IMvcContext>(null,server, callcontext, callbackEndPoint, cancel); context.NotModified = false; try { BindContext(context); Execute(context); if (context.NotModified) { MvcHandler.ProcessNotModified(context); context.Output.Close(); } else { MvcHandler.SetModifiedHeader(context); RenderResult(context); } } catch (Exception ex) { ProcessError(context, ex); } finally { context.Release(); } }
/// <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"); }
/// <summary> /// /// </summary> /// <param name="server"></param> /// <param name="uri"></param> /// <param name="callbackEndPoint"></param> /// <returns></returns> public IRequestHandler GetHandler(IHostServer server, Uri uri, string callbackEndPoint){ var path = uri.AbsolutePath; if (path.IsEmpty() || path.Equals("/")) { return new StaticFileHandler(); } if (path.Split('/').Last().Contains(".") && !path.EndsWith(".qweb")) { return new StaticFileHandler(); } if (path.EndsWith("/xml")) { path = path.Substring(0, path.Length - 4); } if (path.StartsWith("/!") || path.StartsWith("/~") || path.StartsWith("/-")) { path = "/" + path.Substring(2); } if (_cache.ContainsKey(path)) { return _cache[path]; } if (path == "/wiki") { return new WikiHandler(); } if (path.SmartSplit().Count >= 2 || path.EndsWith(".qweb")) { return new HostQwebHandler(); } return new NotFoundHandler(); }
/// <summary> /// Выполняет указанный запрос /// </summary> /// <param name="server"></param> /// <param name="callcontext"></param> /// <param name="callbackEndPoint"></param> /// <param name="cancel"></param> public void Run(IHostServer server, HttpListenerContext callcontext, string callbackEndPoint, CancellationToken cancel) { callcontext.Response.StatusCode = 404; callcontext.Response.ContentType = "text/plain; charset=utf-8"; var buffer = Encoding.UTF8.GetBytes("command not found"); callcontext.Response.OutputStream.Write(buffer,0,buffer.Length); callcontext.Response.Close(); }
/// <summary> /// Возвращает хэндлер, соответствующий запросу /// </summary> /// <param name="server"></param> /// <param name="context"></param> /// <param name="callbackEndPoint"></param> /// <returns></returns> public IRequestHandler GetHandler(IHostServer server, HttpListenerContext context, string callbackEndPoint) { lock (this){ var uri = context.Request.Url; return GetHandler(server, uri, callbackEndPoint); } }
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 WcfHostClient(string address) { this.address = address; BasicHttpBinding binding = new BasicHttpBinding(); ChannelFactory<IHostServer> factory = new ChannelFactory<IHostServer>(binding, new EndpointAddress(address)); this.server = factory.CreateChannel(); if (Machine.Current != null) Machine.Current.RegisterHost(this); }
private static void SetCurrentUser(IHostServer server, HttpListenerContext callcontext) { var identity = callcontext.Request.Headers.Get("Qorpent-Impersonate"); if (string.IsNullOrWhiteSpace(identity)) { identity = "admin"; } server.Application.Principal.SetCurrentUser( new GenericPrincipal(new GenericIdentity(identity), null) ); }
/// <summary> /// Произведение авторизации и всех сопутствующих процедур /// </summary> /// <param name="user">Пользователь</param> /// <param name="server">Сервер</param> /// <param name="context">Контекст</param> /// <returns>HandlerResult</returns> private HandlerResult ProcessUserLogin(IUser user, IHostServer server, WebContext context) { var identity = new Identity(user) {AuthenticationType = "secure"}; context.User = new GenericPrincipal(identity, null); var logondata = new LogonInfo { Identity = identity, RemoteEndPoint = context.Request.RemoteEndPoint, LocalEndPoint = context.Request.LocalEndPoint, UserAgent = context.Request.UserAgent }; var token = TokenService.Create(context.Request); TokenService.Store(context.Response, context.Request.Uri, token); return new HandlerResult { Result = true, Data = logondata }; }
protected override HandlerResult GetResult(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var result = UserProcessor.DefineUser(context); var param = RequestParameters.Create(context); return new HandlerResult { Result = result, Data = new{ result, call = new { q = param.Query, j = param.Json.jsonify() } } }; }
/// <summary> /// /// </summary> /// <param name="server"></param> /// <param name="callcontext"></param> /// <param name="callbackEndPoint"></param> /// <param name="cancel"></param> public void Run(IHostServer server, HttpListenerContext callcontext, string callbackEndPoint, CancellationToken cancel){ var path = callcontext.Request.Url.AbsolutePath; if (path.StartsWith("/~")){ AsynchronousBegin(callcontext); } else if (path.StartsWith("/!")){ AsynchronousEnd(callcontext); } else if (path.StartsWith("/-")) { RunTrace(callcontext); } else{ RunSynchronous(callcontext); } }
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="callcontext"></param> /// <param name="callbackEndPoint"></param> /// <param name="cancel"></param> public void Run(IHostServer server, HttpListenerContext callcontext, string callbackEndPoint, CancellationToken cancel){ var code = callcontext.Request.Url.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); callcontext.Finish(wikipage,mimeType:"text/html"); }
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"); }
private void RunApplication(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel, string abspath) { if (!_applicationCache.ContainsKey(abspath)) { var appname = Path.GetFileNameWithoutExtension(abspath); var appexists = server.Static.Get(appname + "_controllers.js") != null; if (appexists) { var template = server.Static.Get("template.app.html", context).Read(); var apphtml = string.Format(template, appname); _applicationCache[abspath] = new FixedWebFileRecord(abspath, "text/html", apphtml); } else { _applicationCache[abspath] = null; } } Finish(server, context, abspath); }
/// <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"); }
/// <summary> /// </summary> /// <param name="server"></param> public void Initialize(IHostServer server) { _host = server; Resolver = new WebFileResolver(); foreach (var exf in _host.Config.ExtendedContentFolders) { _host.Config.Log.Info("Ex-Content from " + EnvironmentInfo.ResolvePath(exf) + " added"); Resolver.Register(new FileSystemWebFileProvider { ExactOnly = true, Root = EnvironmentInfo.ResolvePath(exf) }); } foreach (var f in _host.Config.ContentFolders) { _host.Config.Log.Info("Content from " + EnvironmentInfo.ResolvePath(f) + " added"); Resolver.Register(new FileSystemWebFileProvider { ExactOnly = false, Root = EnvironmentInfo.ResolvePath(f) }); } _host.Config.Log.Info("Root-Content from " + EnvironmentInfo.ResolvePath(_host.Config.RootFolder) + " added"); Resolver.Register(new FileSystemWebFileProvider { ExactOnly = false, Root = EnvironmentInfo.ResolvePath(_host.Config.RootFolder) }); foreach (var assembly in _host.Config.AutoconfigureAssemblies.Where(_ => !(_.Contains("\\") || _.Contains("/"))).Select(Assembly.Load).ToArray()) { _host.Config.Log.Info("Resource-Content from " + assembly.GetName().Name + " added"); Resolver.Register(new ResourceWebFileProvider { Assembly = assembly }); } _host.Config.Log.Info("Resource-Content from Qorpent.Host added"); Resolver.Register(new ResourceWebFileProvider { Assembly = typeof(HostServer).Assembly }); }
public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var path = context.Uri.AbsolutePath; if (path.StartsWith("/~")) { AsynchronousBegin(context); } else if (path.StartsWith("/!")) { AsynchronousEnd(context); } else if (path.StartsWith("/-")) { RunTrace(context); } else { RunSynchronous(context); } }
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 static string Call(this IHostServer host, string command) { var h = host.GetHandler(command); var ms = new MemoryStream(); var rs = new HttpResponseDescriptor { Stream = ms, NoCloseStream = true }; var rq = new HttpRequestDescriptor { Uri = new Uri("http://localhost" + command) }; var ctx = new WebContext { Request = rq, Response = rs }; h.Run(host, ctx, null, new CancellationToken()); var len = ms.Position; ms.Position = 0; var result = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)len); return(result); }
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); }
protected override HandlerResult GetResult(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { if ( !Roles.IsInRole(context.User.Identity, $"{SecurityConst.ROLE_SECURITY_ADMIN},{SecurityConst.ROLE_DOMAIN_ADMIN}")) { throw new SecurityException("only admins allowed to call this"); } var j = RequestParameters.Create(context).AsJson(); var uq = new UserSearchQuery(); uq.LoadFromJson(j); //check if not total admin if (!Roles.IsInRole(context.User.Identity, $"{SecurityConst.ROLE_SECURITY_ADMIN}")) { var domain = ((Identity) context.User.Identity).User.Domain; if (string.IsNullOrWhiteSpace(domain)) { throw new SecurityException("invalid domain for user "+domain); } if (!string.IsNullOrWhiteSpace(uq.Domain) && uq.Domain != domain) { throw new SecurityException("try access not self domain "+domain+" ("+uq.Domain+")"); } uq.Domain = domain; } var users = Users.SearchUsers(uq).ToArray(); return new HandlerResult { Result = new {items= users} }; }
protected override HandlerResult GetResult(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var j = RequestParameters.Create(context).Json; if (null == j) { throw new Exception("invalid json"); } var ir = new ClientRecord(); ir.LoadFromJson(j); var result = GetResult(context, ir); return new HandlerResult { Result = result, Data = new { result, call = new { ir } } }; }
/// <summary> /// 启动windows服务自动配置 /// </summary> /// <param name="QuartzServerType">任务调度器实例类型,必须继承自<see cref="BaseHostSchedulerTaskServer"/>,默认读取quartz.host.serverImplementationTypeName</param> /// <param name="nlogConfigPath">nlog配置文件路径,相对应AppDomain.CurrentDomain.BaseDirectory(eg:config/nlog.config)</param> /// <returns></returns> public static TopshelfExitCode AutoRun(Type QuartzServerType = null, string nlogConfigPath = null) { var baseAppPath = System.AppDomain.CurrentDomain.BaseDirectory; Directory.SetCurrentDirectory(baseAppPath); var code = HostFactory.Run(x => { x.StartAutomatically(); //自启动服务 x.EnablePauseAndContinue(); //服务可以暂停和继续 x.EnableShutdown(); //服务可以关闭 //NLog配置 if (!string.IsNullOrWhiteSpace(nlogConfigPath)) { var nlogFile = Path.Combine(baseAppPath, nlogConfigPath.Replace("/", "\\")); x.UseNLog(new NLog.LogFactory(new NLog.Config.XmlLoggingConfiguration(nlogConfigPath, true))); } else { x.UseNLog(); } x.BeforeUninstall(() => { ////卸载之前执行 //if (MessageBox.Show("服务卸载后数据会出错,请知悉!", "服务卸载", MessageBoxButtons.OK) == DialogResult.OK) //{ //} //string M = Interaction.InputBox("请输入卸载密码", "输入", "", 100, 100); //if (M != "fyxmt") //{ // MessageBox.Show("密码输入错误!"); // logger.Error("服务卸载失败,密码出错!"); // throw new Exception("服务卸载失败,密码出错!"); //} }); x.AfterUninstall(() => { //卸载后记录日志 logger.Debug("服务卸载完成!"); }); x.RunAsLocalSystem(); x.SetDescription(HostServiceConfigurationLoader.HostServiceCfg.serviceDescription); x.SetDisplayName(HostServiceConfigurationLoader.HostServiceCfg.serviceDisplayName); x.SetServiceName(HostServiceConfigurationLoader.HostServiceCfg.serviceName); x.Service <IHostServer>(sc => { sc.ConstructUsing(() => { var typeName = QuartzServerType == null ? null : QuartzServerType.FullName; IHostServer server = SchedulerTaskFactory.CreateHostSchedulerServer(typeName); server.Initialize(); return(server); }); sc.WhenStarted((s, hostControl) => s.Start(hostControl)); sc.WhenStopped((s, hostControl) => s.Stop(hostControl)); sc.WhenPaused((s, hostControl) => s.Pause(hostControl)); sc.WhenContinued((s, hostControl) => s.Continue(hostControl)); }); }); return(code); }
public void Initialize(IHostServer server) { InitializeKey(server.Config.EncryptBasis); }
public void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { context.Finish("It's not zero", "text/plain"); }
protected virtual HandlerResult GetResult(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { return(null); }
protected virtual HandlerResult GetResult(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { return null; }
private static void SetCurrentUser(IHostServer server, IPrincipal user) { server.Application.Principal.SetCurrentUser(user); }
/// <summary> /// </summary> /// <param name="server"></param> /// <param name="path"></param> /// <param name="handler"></param> /// <returns></returns> public static IHostServer OnResponse(this IHostServer server, string path, Action <IHttpResponseDescriptor> handler) { server.Factory.OnResponse(path, handler); return(server); }
/// <summary> /// Выполняет указанный запрос /// </summary> /// <param name="server"></param> /// <param name="callcontext"></param> /// <param name="callbackEndPoint"></param> /// <param name="cancel"></param> public void Run(IHostServer server, HttpListenerContext callcontext, string callbackEndPoint, CancellationToken cancel) { _handler(server, callcontext, callbackEndPoint, cancel); }
public static IHostServer Route(this IHostServer server, string pattern, string replace = null) { server.Router.Register(RewriteUri(pattern, replace)); return(server); }
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 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(); } } }
protected override HandlerResult GetResult(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { var p = RequestParameters.Create(context); var login = p.Get("login"); var email = p.Get("email"); if (string.IsNullOrWhiteSpace(login)) { return(GetError("no login", login, email)); } if (string.IsNullOrWhiteSpace(email)) { return(GetError("no email", login, email)); } var user = Users.GetUser(login); if (null == user) { return(GetError("not existed user", login, email)); } if (!CheckState.IsLogable(user)) { return(GetError("not for logon user", login, email)); } var state = CheckState.GetActivityState(user); if (state != UserActivityState.Ok) { return(GetError("invalid state " + state.ToStr(), login, email)); } if (user.Email != email) { return(GetError("invalid email", login, email)); } PasswordManager.MakeRequest(user, 10, email); Users.Store(user); var message = UserMessagingService.SendPasswordReset(user); bool sent = false; string senderror = ""; //try force try { if (null != Sender) { var savedmessage = Queue.GetMessage(message.Id); if (!savedmessage.WasSent) { Sender.Send(savedmessage); Queue.MarkSent(savedmessage.Id); } sent = true; } else { throw new Exception("no sender found"); } } catch (Exception e) { senderror = e.Message; } var result = new { messageid = message.Id, minutes = 10, sent, senderror }; return(new HandlerResult { Result = result, Data = new{ resetpwdreq = true, login, email, data = result } }); }
public static IHostServer Handle(this IHostServer server, string url, IRequestHandler handler) { server.Factory.Register(url, handler); return(server); }
/// <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) { _handler(server, context, callbackEndPoint, cancel); }
/// <summary> /// </summary> /// <param name="server"></param> /// <param name="path"></param> /// <param name="usonHandler"></param> /// <returns></returns> public static IHostServer On(this IHostServer server, string path, Func <dynamic, object> usonHandler) { server.Factory.On(path, usonHandler); return(server); }
public virtual void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { DefaultProcess(server, context, callbackEndPoint, cancel); }
/// <summary> /// Регистрирует статический хэндлер со статусом /// </summary> /// <param name="server"></param> /// <param name="path"></param> /// <param name="content"></param> /// <param name="mimeType"></param> /// <param name="status"></param> /// <returns></returns> public static IHostServer On(this IHostServer server, string path, IRequestHandler handler) { server.Factory.Register(path, handler); return(server); }
public void Initialize(IHostServer server) { server.Factory.Register("/report", ResolveService <IRequestHandler>("qorpent.report.handler")); }
public void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { context.Finish(context.User.Identity.IsAuthenticated.ToString().ToLowerInvariant()); }
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) { server.Static.DropCache(); }
public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { context.ContentEncoding = Encoding.UTF8; context.Finish(_content, _mime, _status); }
public abstract void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel);
private static void Finish200(IHostServer server, WebContext context, IWebFileRecord staticdescriptor) { var filetime = context.SetLastModified(staticdescriptor.Version); if (filetime <= context.GetIfModifiedSince()) { context.Finish("", status: 304); } else { context.SetHeader("Qorpent-Disposition", staticdescriptor.FullName); if (server.Config.Cached.Contains(Path.GetFileName(staticdescriptor.FullName))) { context.SetHeader("Cache-Control", "public, max-age=86400"); } else if (server.Config.ForceNoCache) { context.SetHeader("Cache-Control", "no-cache, must-revalidate"); } else { context.SetHeader("Cache-Control", "public"); } RangeDescriptor range = null; if (0 < staticdescriptor.Length && (staticdescriptor.MimeType.StartsWith("image/") || staticdescriptor.MimeType.StartsWith("video/"))) { context.Response.ConentLength = staticdescriptor.Length; if (staticdescriptor.Length > 4096) { context.Response.SetHeader("Accept-Ranges", "bytes"); } var rangeHeader = context.Request.GetHeader("Range"); if (!string.IsNullOrWhiteSpace(rangeHeader)) { var rangeparts = rangeHeader.Substring(6).SmartSplit(false, true, '-'); range = new RangeDescriptor { Total = staticdescriptor.Length }; range.Finish = range.Total - 1; range.Start = rangeparts[0].ToInt(); if (rangeparts.Count > 1) { range.Finish = rangeparts[1].ToInt(); } } } try { if (staticdescriptor.IsFixedContent) { if (null != staticdescriptor.FixedData) { context.Finish(staticdescriptor.FixedData, staticdescriptor.MimeType, range: range); } else { context.Finish(staticdescriptor.FixedContent, staticdescriptor.MimeType, range: range); } } else { using (var s = staticdescriptor.Open()) { context.Finish(s, staticdescriptor.MimeType, range: range); } } } catch (Exception e) { Console.WriteLine(e.GetType().Name); context.Finish(e.ToString(), status: 500); } finally { context.Response.Close(); } } }
/// <summary> /// Регистрирует статический хэндлер со статусом /// </summary> /// <param name="server"></param> /// <param name="path"></param> /// <param name="content"></param> /// <param name="mimeType"></param> /// <param name="status"></param> /// <returns></returns> public static IHostServer On(this IHostServer server, string path, string content, string mimeType = "text/plain", int status = 200) { server.Factory.On(path, content, mimeType, status); return(server); }
protected override HandlerResult GetResult(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) { TokenService.Store(context.Response, context.Request.Uri, null); return new HandlerResult {Result = true, Data = context.User.Identity }; }
/// <summary> /// </summary> /// <param name="server"></param> /// <param name="path"></param> /// <param name="handler"></param> /// <returns></returns> public static IHostServer OnContext(this IHostServer server, string path, Action <WebContext> handler) { server.Factory.OnContext(path, handler); return(server); }