Пример #1
0
        /// <summary>
        /// Attempts to start a server. If the server is already running, stops it first.
        /// Does not throw any exceptions if the server cannot be started, but  shows a
        /// warning to the user that the server could not be started. The outcome can be
        /// determined via <see cref="ServerRunning"/>.
        /// </summary>
        public void StartServer(HttpServerOptions hsOptions, FileSystemOptions fsOptions = null)
        {
            if (ServerRunning)
            {
                StopServer();
            }

            try
            {
                Resolver = new UrlResolver();
                Server   = new HttpServer(hsOptions)
                {
                    Handler = Resolver.Handle
                };
                Server.StartListening();
                _navLinksPages.Clear();
                RegisterHandlers(fsOptions);
            }
            catch
            {
                try { Server.StopListening(true); }
                catch { }
                Server = null;
                DlgMessage.ShowWarning("The server could not be started. Try a different port (current port is {0}).".Fmt(hsOptions.Endpoints.JoinString()));
            }
        }
Пример #2
0
        public async Task StartAsync(HttpServerOptions options)
        {
            _options = options ?? throw new ArgumentNullException(nameof(options));
            if (RequestHandler == null)
            {
                throw new InvalidOperationException("RequestHandler is not set.");
            }

            try
            {
                _cancellationTokenSource = new CancellationTokenSource();
                _socketWrapper           = _socketWrapperFactory(options);

                await _socketWrapper.StartAsync();

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                Task.Factory.StartNew(() => AcceptConnectionsAsync(_cancellationTokenSource.Token).ConfigureAwait(false), _cancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default).ConfigureAwait(false);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }
            catch (Exception)
            {
                await StopAsync();

                throw;
            }
        }
Пример #3
0
        static void Net_Test9_WebServer()
        {
            var cfg = new HttpServerOptions();

            using (HttpServer <TestHttpServerBuilder> svr = new HttpServer <TestHttpServerBuilder>(cfg, "Hello"))
            {
                Con.ReadLine(">");
            }
        }
Пример #4
0
 public HttpServer(IBootstrapWrapperFactory wrapperFactory,
                   ISigningCredentialsService signingCredentials,
                   DotNettyDependency dependency,
                   ILoggerFactory loggerFactory)
     : base(wrapperFactory, signingCredentials, dependency, loggerFactory)
 {
     _serverOptions             = Options.HttpServer;
     ResourceLeakDetector.Level = _serverOptions.LeakDetector;
 }
Пример #5
0
        public RawHttpRequestReader(Stream receiveStream, HttpServerOptions options)
        {
            _receiveStream = receiveStream ?? throw new ArgumentNullException(nameof(receiveStream));
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            _chunkBuffer = new byte[options.ReceiveChunkSize];
        }
Пример #6
0
        public ClientSession(IClientSocketWrapper client, HttpServer httpServer, HttpServerOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            _httpServer = httpServer ?? throw new ArgumentNullException(nameof(httpServer));
            Client      = client ?? throw new ArgumentNullException(nameof(client));

            _sessionHandler = new HttpSessionHandler(this, options);
        }
Пример #7
0
    public EasyJsonRpcServer(HttpServerOptions httpConfig, CancellationToken cancel = default, JsonRpcServerConfig?rpcCfg = null, object?targetObject = null) : base(cancel, targetObject)
    {
        try
        {
            rpcCfg ??= new JsonRpcServerConfig();

            this.HttpServer = JsonRpcHttpServerBuilder.StartServer(httpConfig, rpcCfg, this, cancel);
        }
        catch
        {
            this._DisposeSafe();
            throw;
        }
    }
Пример #8
0
        public WebServer(int Port, bool IsHttps)
        {
            this.port = Port;

            bool https = IsHttps;

            var options = new HttpServerOptions()
            {
                HttpHandler       = new ServerHandler(r => this.StartWare.Invoke(r)),
                SelectCertificate = Kooboo.Data.Server.SslCertificateProvider.SelectCertificate,
                IsHttps           = https
            };

            this.Server = new Kooboo.HttpServer.HttpServer(new System.Net.IPEndPoint(System.Net.IPAddress.Any, this.port), options);
        }
Пример #9
0
        static void Main(string[] args)
        {
            var options = new HttpServerOptions()
            {
                // SslCertificateProvider = new KoobooCertificateManager(),
                //IsHttps=true
            };
            var server = new HttpServer(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 81), options);

            //var server = new HttpServer(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 81));
            server.Start();

            Console.WriteLine($"Server started on http://localhost:{server.EndPoint.Port}");

            Console.ReadKey();
        }
Пример #10
0
 public GncFileWrapper()
 {
     ServerOptions = new HttpServerOptions();
     ServerOptions.AddEndpoint("main", "127.0.0.1", 1771);
     FileSystemOptions = new FileSystemOptions();
     BaseCurrency      = Program.Tr.GncWrapper.DefaultBaseCurrency;
     BalsnapPrefix     = Program.Tr.GncWrapper.DefaultBalsnapPrefix;
     UserLinks         = new List <UserLink>()
     {
         new UserLink()
         {
             Name = Program.Tr.GncWrapper.DefaultExampleUserlink, Href = "/MonthlyTotals?MaxDepth=1"
         }
     };
     UserScripts = new UserScripts();
 }
Пример #11
0
    public CgiHttpServer(CgiHandlerBase handler, HttpServerOptions options, bool autoDisposeHandler = false)
    {
        try
        {
            this.Handler            = handler;
            this.AutoDisposeHandler = autoDisposeHandler;

            this.Handler.ShowDetailError.TrySet(options.ShowDetailError);

            HttpSvr = CgiHttpServerBuilder.StartServer(options, this);
        }
        catch (Exception ex)
        {
            this._DisposeSafe(ex);
            throw;
        }
    }
Пример #12
0
        public WebServer(int Port, ISslCertificateProvider SslCertProvider)
        {
            this.port = Port;

            bool https = false;

            if (Port == 443)
            {
                https = true;
            }
            var options = new HttpServerOptions()
            {
                HttpHandler            = new ServerHandler(r => this.StartWare.Invoke(r)),
                SslCertificateProvider = SslCertProvider,
                IsHttps = https
            };

            this.Server = new Kooboo.HttpServer.HttpServer(new System.Net.IPEndPoint(System.Net.IPAddress.Any, this.port), options);
        }
Пример #13
0
    protected override async Task StartImplAsync(DaemonStartupMode startupMode, object?param)
    {
        Con.WriteLine("MikakaDDnsServerDaemon: Starting...");

        MikakaDDnsServiceGlobal.Init();

        HttpServerOptions httpOpt = new HttpServerOptions
        {
            AutomaticRedirectToHttpsIfPossible = false,
            DenyRobots            = true,
            DebugKestrelToConsole = true,
            DebugKestrelToLog     = true,
            HttpPortsList         = new int[] { 80, 88 }.ToList(),
                          HttpsPortsList = new int[] { 443 }.ToList(),
                          UseKestrelWithIPACoreStack = false,
        };

        MikakaDDnsServiceStartupParam startup = new MikakaDDnsServiceStartupParam
        {
        };

        this.SvcInstance = new MikakaDDnsService(startup, new MikakaDDnsServiceHook());

        JsonRpcServerConfig rpcConfig = new JsonRpcServerConfig
        {
            MaxRequestBodyLen             = 1_000_000,
            EnableBuiltinRichWebPages     = true,
            EnableGetMyIpServer           = true,
            EnableHealthCheckServer       = true,
            TopPageRedirectToControlPanel = true,
            HadbBasedServicePoint         = SvcInstance,
        };

        this.RpcInstance = new EasyJsonRpcServer <MikakaDDnsService.IRpc>(httpOpt, rpcCfg: rpcConfig, targetObject: SvcInstance);

        SvcInstance.Start();

        await Task.CompletedTask;

        Con.WriteLine("MikakaDDnsServerDaemon: Started.");
    }
Пример #14
0
        public DaemonCenterServerRpcHttpHost(Server daemonCenterServer)
        {
            try
            {
                // Start Log Server
                string certVaultDir = Lfs.ConfigPathStringToPhysicalDirectoryPath(@"Local/DaemonCenterRpc_CertVault/");

                this.CertVault = new CertVault(certVaultDir,
                                               new CertVaultSettings(EnsureSpecial.Yes)
                {
                    ReloadIntervalMsecs = 3600 * 1000,
                    UseAcme             = false,
                    NonAcmeEnableAutoGenerateSubjectNameCert = false,
                });

                PalSslServerAuthenticationOptions sslOptions = new PalSslServerAuthenticationOptions(this.CertVault.X509CertificateSelector("dummy", true), true, null);

                this.DaemonCenterServer = daemonCenterServer;

                JsonRpcServerConfig rpcCfg = new JsonRpcServerConfig();

                HttpServerOptions httpConfig = new HttpServerOptions
                {
                    HttpPortsList  = new List <int>(),
                    HttpsPortsList = Consts.Ports.DaemonCenterHttps._SingleList(),
                    UseStaticFiles = false,
                    AutomaticRedirectToHttpsIfPossible = false,
                    HiveName           = "DaemonCenterRpcHttpServer",
                    DenyRobots         = true,
                    UseGlobalCertVault = false,
                    ServerCertSelector = (param, sni) => (X509Certificate2)(this.CertVault.X509CertificateSelector(sni, true).NativeCertificate),
                };

                this.HttpServer = JsonRpcHttpServerBuilder.StartServer(httpConfig, rpcCfg, this.DaemonCenterServer);
            }
            catch
            {
                this._DisposeSafe();
                throw;
            }
        }
Пример #15
0
        public void Start()
        {
            if (IsRunning)
            {
                throw new InvalidOperationException();
            }

            var server = _factory.CreateHttpServer();

            Configure(server);

            var startOptions = new HttpServerOptions {
                Port = _port
            };

            server.StartAsync(startOptions).GetAwaiter().GetResult();

            _server = server;

            IsRunning = true;
        }
Пример #16
0
 public static new HttpServer <DataVaultLogBrowserHttpServerBuilder> StartServer(HttpServerOptions httpCfg, LogBrowserHttpServerOptions options, CancellationToken cancel = default)
 => new HttpServer <DataVaultLogBrowserHttpServerBuilder>(httpCfg, options, cancel);
        public static void jsonrpc_client_server_both_test()
        {
            //jsonrpc_server_invoke_test().Wait();return;

            // start server
            HttpServerOptions http_cfg = new HttpServerOptions()
            {
                DebugKestrelToConsole = false,
            };
            JsonRpcServerConfig rpc_cfg = new JsonRpcServerConfig()
            {
            };

            using (RpcServerApiTest h = new RpcServerApiTest())
                using (var s = JsonRpcHttpServerBuilder.StartServer(http_cfg, rpc_cfg, h))
                {
                    Ref <bool> client_stop_flag = new Ref <bool>();

                    // start client
                    ThreadObj client_thread = ThreadObj.Start(param =>
                    {
                        //Kernel.SleepThread(-1);

                        //using ()
                        {
                            //c.AddHeader("X-1", "Hello");

                            rpctmp1 t = new rpctmp1();
                            t.a       = new rpc_t()
                            {
                                Int1 = 2,
                                Str1 = "Neko",
                            };

                            //JsonRpcResponse<object> ret = c.CallOne<object>("Test1", t).Result;
                            //JsonRpcResponse<object> ret = c.CallOne<object>("Test2", t).Result;

                            Benchmark b = new Benchmark("rpccall");

                            JsonRpcHttpClient <rpc_server_api_interface_test> c = new JsonRpcHttpClient <rpc_server_api_interface_test>("http://127.0.0.1:88/rpc");
                            var threads = ThreadObj.StartMany(256, par =>
                            {
                                while (client_stop_flag.Value == false)
                                {
                                    //c.Call.Divide(8, 2).Wait();
                                    TMP1 a = new TMP1()
                                    {
                                        a = 4, b = 2
                                    };
                                    c.MT_Call <object>("Divide", a, true)._GetResult();
                                    //c.ST_CallOne<object>("Divide", a, true).Wait();
                                    b.IncrementMe++;
                                }
                            }
                                                              );

                            foreach (var thread in threads)
                            {
                                thread.WaitForEnd();
                            }

                            //c.Call.Divide(8, 2).Result.Print();
                            //c.Call.Divide(8, 2).Result.Print();
                            //c.Call.Test3(1, 2, 3).Result.Print();
                            //c.Call.Test5(1, "2").Result.ObjectToJson().Print();
                            //var fnlist = c.Call.Test6().Result;
                            ////foreach (var fn in fnlist) fn.Print();
                            //c.Call.Test7(fnlist).Result.Print();

                            //Con.WriteLine(ret.ObjectToJson());
                        }
                    }, null);

                    Con.ReadLine("Enter to quit>");

                    client_stop_flag.Set(true);

                    client_thread.WaitForEnd();
                }
        }
Пример #18
0
 public ServerSocketWrapper(HttpServerOptions options)
 {
     _options = options ?? throw new ArgumentNullException(nameof(options));
 }
Пример #19
0
 public HttpServerDualDaemon(string name, string friendlyName, HttpServerOptions httpOptions1, HttpServerOptions httpOptions2)
     : base(new DaemonOptions(name, friendlyName, true))
 {
     this.HttpOptions1 = httpOptions1;
     this.HttpOptions2 = httpOptions2;
 }
Пример #20
0
 public HttpServerDaemon(string name, string friendlyName, HttpServerOptions httpOptions)
     : base(new DaemonOptions(name, friendlyName, true))
 {
     this.HttpOptions = httpOptions;
 }
Пример #21
0
 public static HttpServer <CgiHttpServerBuilder> StartServer(HttpServerOptions httpCfg, CgiHttpServer cgiHttpServer, CancellationToken cancel = default)
 => new HttpServer <CgiHttpServerBuilder>(httpCfg, cgiHttpServer, cancel);
Пример #22
0
    public DaemonUtil(string daemonName, CancellationToken cancel = default) : base(cancel)
    {
        if (daemonName._IsEmpty())
        {
            throw new ArgumentNullException(nameof(daemonName));
        }

        daemonName = daemonName._NonNullTrim();

        try
        {
            // 起動パラメータ
            this.Params = new OneLineParams(GlobalDaemonStateManager.StartupArguments);

            if (Params._HasKey(Consts.DaemonArgKeys.StartLogFileBrowser))
            {
                // Log Browser で利用されるべきポート番号の決定
                int httpPort = Params._GetFirstValueOrDefault(Consts.DaemonArgKeys.LogFileBrowserPort, StrComparer.IgnoreCaseComparer)._ToInt();
                if (httpPort == 0)
                {
                    httpPort = Util.GenerateDynamicListenableTcpPortWithSeed(Env.DnsFqdnHostName + "_seed_daemonutil_logbrowser_http" + Env.AppRootDir + "@" + daemonName);
                }

                int httpsPort = Params._GetFirstValueOrDefault(Consts.DaemonArgKeys.LogFileBrowserPort, StrComparer.IgnoreCaseComparer)._ToInt();
                if (httpsPort == 0)
                {
                    httpsPort = Util.GenerateDynamicListenableTcpPortWithSeed(Env.DnsFqdnHostName + "_seed_daemonutil_logbrowser_https" + Env.AppRootDir + "@" + daemonName, excludePorts: httpPort._SingleArray());
                }

                // Log Browser 用の CertVault の作成
                CertVault certVault = new CertVault(PP.Combine(Env.AppLocalDir, "Config/DaemonUtil_LogBrowser/CertVault"),
                                                    new CertVaultSettings(defaultSetting: EnsureSpecial.Yes)
                {
                    UseAcme = false
                });

                DisposeList.Add(certVault);

                // Log Browser の起動
                HttpServerOptions httpServerOptions = new HttpServerOptions
                {
                    UseStaticFiles = false,
                    UseSimpleBasicAuthentication = false,
                    HttpPortsList                      = httpPort._SingleList(),
                    HttpsPortsList                     = httpsPort._SingleList(),
                    DebugKestrelToConsole              = false,
                    UseKestrelWithIPACoreStack         = true,
                    AutomaticRedirectToHttpsIfPossible = false,
                    LocalHostOnly                      = false,
                    UseGlobalCertVault                 = false, // Disable Global CertVault
                    DisableHiveBasedSetting            = true,  // Disable Hive based settings
                    ServerCertSelector                 = certVault.X509CertificateSelectorForHttpsServerNoAcme,
                    DenyRobots = true,                          // Deny robots
                };

                LogBrowserOptions browserOptions = new LogBrowserOptions(
                    Env.AppRootDir,
                    systemTitle: $"{Env.DnsFqdnHostName}",
                    zipEncryptPassword: GlobalDaemonStateManager.DaemonZipEncryptPassword,
                    clientIpAcl: (ip) =>
                {
                    // 接続元 IP アドレスの種類を取得
                    IPAddressType type = ip._GetIPAddressType();

                    if (type.Bit(IPAddressType.GlobalIp))
                    {
                        // 接続元がグローバル IP の場合
                        if (GlobalDaemonStateManager.IsDaemonClientLocalIpAddressGlobal == false)
                        {
                            // DaemonCenter との接続にプライベート IP を利用している場合: 接続拒否
                            return(false);
                        }
                    }

                    // それ以外の場合: 接続許可
                    return(true);
                }
                    );

                DisposeList.Add(LogBrowserHttpServerBuilder.StartServer(httpServerOptions, new LogBrowserHttpServerOptions(browserOptions, "/" + GlobalDaemonStateManager.DaemonSecret)));

                GlobalDaemonStateManager.FileBrowserHttpsPortNumber = httpsPort;
            }
        }
        catch (Exception ex)
        {
            ex._Debug();

            this._DisposeSafe();

            throw;
        }
    }
Пример #23
0
 public RawHttpResponseWriter(Stream sendStream, HttpServerOptions options)
 {
     _sendStream = sendStream ?? throw new ArgumentNullException(nameof(sendStream));
     _options    = options ?? throw new ArgumentNullException(nameof(options));
 }