public void TestSendManyMessagesOnSingleConnections()
        {
            Func<ISession> connectionFactory = () =>
                new SmtpServerSession(new InMemoryCommandHandler(), new NullLog(), new SmtpServerSessionConfiguration());

            var serverConfiguration = new ServerConfiguration();

            var smtpServer = new Server(connectionFactory, new NullLog(), serverConfiguration);
            var runTask = smtpServer.RunAsync();
            
            using (var client = new SmtpClient(smtpServer.LocalEndpoint.Address.ToString(), smtpServer.LocalEndpoint.Port))
            {
                for (int i = 0; i < 50; i++)
                {
                    using (var message = new MailMessage())
                    {
                        message.From = new MailAddress("*****@*****.**");
                        message.To.Add(new MailAddress("*****@*****.**"));
                        message.To.Add(new MailAddress("*****@*****.**"));
                        message.Body = "Test";
                        client.Send(message);
                    }
                }
            }

            var stopTask = smtpServer.StopAsync();

            Assert.IsTrue(stopTask.Wait(TimeSpan.FromMilliseconds(2000)));
            Assert.IsTrue(runTask.Wait(TimeSpan.FromMilliseconds(2000)));
        }
예제 #2
0
 private void GetServerEndpoint()
 {
     var serverFactory = new ServerFactory();
     var serverConfig = new ServerConfiguration();
     var configLoaded = serverConfig.LoadConfigurationFile("C:\\Configs\\Config.text");
     server = serverFactory.MakeNew(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000), serverConfig);
 }
        public void TestSendManyMessagesOnSeparateConnections()
        {
            Func<ISession> connectionFactory = () =>
                new SmtpServerSession(new InMemoryCommandHandler(), new NullLog(), new SmtpServerSessionConfiguration());

            var serverConfiguration = new ServerConfiguration();

            var smtpServer = new Server(connectionFactory, new NullLog(), serverConfiguration);
            var runTask = smtpServer.RunAsync();

            var throttler = new SemaphoreSlim(initialCount: 5);

            var sendTasks = new List<Task>();

            for (int i = 0; i < 100; i++)
                sendTasks.Add(SendMessageThrottled(throttler, smtpServer.LocalEndpoint));

            Task.WaitAll(sendTasks.ToArray());
            

            var stopTask = smtpServer.StopAsync();

            Assert.IsTrue(stopTask.Wait(TimeSpan.FromMilliseconds(2000)));
            Assert.IsTrue(runTask.Wait(TimeSpan.FromMilliseconds(2000)));
        }
        private static async Task CreateServerAsync()
        {
            var httpClient = new HttpClient();
            var serverConfiguration = new ServerConfiguration
            {
                DefaultStorageTypeName = "voron",
                Port = Port,
                RunInMemory = true,
                Settings =
                {
                    { "Raven/ServerName", ServerName }
                }
            };

            var response = await httpClient
                .PutAsync("http://localhost:8585/servers", new JsonContent(RavenJObject.FromObject(serverConfiguration)))
                .ConfigureAwait(false);

            if (response.IsSuccessStatusCode == false)
                throw new InvalidOperationException("Failed to start server.");

            using (var stream = await response.GetResponseStreamWithHttpDecompression().ConfigureAwait(false))
            {
                var data = RavenJToken.TryLoad(stream);
                if (data == null)
                    throw new InvalidOperationException("Failed to retrieve server url.");

                ServerUrl = data.Value<string>("ServerUrl");
            }
        }
 public void UpdateConfiguration(ServerConfiguration config)
 {
     var client = ClientHelper.GetClient(authorizator);
     HttpResponseMessage response = client.Post(Url("Configuration"), new ObjectContent<ServerConfiguration>(config, JsonValueMediaTypeFormatter.DefaultMediaType));
     ClientHelper.HandleHTTPErrorCode(response);
     return;
 }
예제 #6
0
        public Server MakeNew(IPEndPoint _ipEndPoint, ServerConfiguration _serverConfiguration = null)
        {
            if (_ipEndPoint == null) throw new NullReferenceException("Server requires IPEndpoint.");

            if (_serverConfiguration != null)
                return new Server(new SessionManager(), _ipEndPoint, new TcpListener(_ipEndPoint), _serverConfiguration);
            return new Server(new SessionManager(), _ipEndPoint, new TcpListener(_ipEndPoint));
        }
예제 #7
0
 /// <summary>
 /// Creates a new server instance, which exposes dashboard and test runner at given ports
 /// </summary>
 /// <param name="configuration">The configuration.</param>
 /// <param name="testRunner">The test runner instance</param>
 /// <param name="dashboard">The dashboard instance</param>
 /// <param name="connectionsTracker">The connection tracker for the host</param>
 /// <param name="log">The logger</param>
 public ServerHost(ServerConfiguration configuration, Services.Server testRunner, DashboardService dashboard, AgentsTracker connectionsTracker, ILog log)
 {
     dashboardPort = configuration.DashboardPort;
     testRunnerPort = configuration.TestRunnerPort;
     this.testRunner = testRunner;
     this.dashboard = dashboard;
     this.log = log;
     ConnectionsTracker = connectionsTracker;
 }
        private ServerConfiguration ReadFromConfig()
        {
            ServerConfiguration config = new ServerConfiguration();
            config.ScrumFactorySenderEmail = System.Configuration.ConfigurationManager.AppSettings["ScrumFactorySenderEmail"];
            config.ScrumFactorySenderName = System.Configuration.ConfigurationManager.AppSettings["ScrumFactorySenderName"];
            config.DefaultCompanyName = System.Configuration.ConfigurationManager.AppSettings["DefaultCompanyName"];
            config.TrustedEmailDomains = System.Configuration.ConfigurationManager.AppSettings["TrustedEmailDomains"];

            return config;
        }
            public Server(ServerConfiguration configuration)
            {
                this.configuration = configuration;

                server = new AsynchronousServer.Server(configuration,
                    (handler, s) =>
                    {
                        return new ClientConnection(handler, s, configuration, webSocketServices);
                    });
            }
예제 #10
0
파일: Kernel.cs 프로젝트: sunl158/ide-as
 public Kernel(ServerConfiguration config)
 {
     if(config == null)
     {
         scadaApplication = null;
     }
     else
     {
         scadaApplication = new ScadaApplication(config.file);
     }
 }
예제 #11
0
파일: Server.cs 프로젝트: Zyruis11/netSharp
        public Server(SessionManager _sessionManager, IPEndPoint _ipEndPoint, TcpListener _tcpListener,
            ServerConfiguration _serverConfiguration = null)
        {
            sessionManager = _sessionManager;
            ipEndPoint = _ipEndPoint;
            tcpListener = _tcpListener;

            ApplyServerConfiguration(_serverConfiguration ?? new ServerConfiguration());

            Guid = ShortGuid.New();
        }
예제 #12
0
 public MainWindowViewModel(ServerConfiguration serverConfiguration, MessageCollaborator messageCollection, ApplicationSettings applicationSettings, GeneralView generalView, CallView callView,
     PortView portView, SMSView smsView)
 {
     this.serverConfiguration = serverConfiguration;
     this.messageCollection = messageCollection;
     this.applicationSettings = applicationSettings;
     this.generalView = generalView;
     this.callView = callView;
     this.portView = portView;
     this.smsView = smsView; 
 }
예제 #13
0
            public Server(ServerConfiguration configuration)
            {
                this.configuration = configuration;

                server = new AsynchronousServer.Server(configuration,
                    (handler, s) =>
                    {
                        return new ClientConnection(handler, this, configuration);
                    });

                requestChainOfResponsibility.Add(new FallBackRequestResponsibility());
            }
예제 #14
0
파일: Main.cs 프로젝트: sunl158/ide-as
        public static void Main(string[] args)
        {
            // Set up configuration from the logging config file
            XmlConfigurator.ConfigureAndWatch(new FileInfo("Logging.conf"));

            Kernel appKernel = null;

            if(args.Length == 0)
            {
                // If no argument was passed show help message
                ServerConfiguration.ShowHelp();
            }
            else
            {
                string[] newargs;

                // If there is only one arg, it is assumed that that is the file arg.
                if(!args[0].StartsWith("-"))
                {
                    newargs = new string[] {"-f", args[0]};
                }
                else
                {
                    newargs = args;
                }

                // Reads configuration
                ServerConfiguration config = new ServerConfiguration(newargs);

                try
                {
                    // Loads configuration to the application kernel
                    appKernel = new Kernel(config);

                    // Check if Kernel was successfully created
                    if(appKernel != null)
                    {
                        // Runs application kernel
                        appKernel.Run();
                    }

                }
                catch(Exception e)
                {
                    log.Fatal("Server could not be started.");
                    log.Fatal(e.Message);
                }

            }

            Console.ReadKey();
        }
예제 #15
0
        public static int Main(String[] args)
        {
            ServerConfiguration config = new ServerConfiguration();
            Server server = new Server(config);
            server.OnServerNotify += new Server.ServerNotify(serverOut);
            server.addHTTPResponsibility(new ElseResponsibility());
            server.addHTTPResponsibility(new RunningResponsibility());

            server.startServing();

            Console.Read();
            server.stopServing();
            return 0;
        }
예제 #16
0
        public void TestSmtpEndToEnd()
        {
            var commandHandler = new InMemoryCommandHandler();

            Func<ISession> connectionFactory = () =>
                new SmtpServerSession(commandHandler, new NullLog(), new SmtpServerSessionConfiguration());

            var serverConfiguration = new ServerConfiguration()
                {
                    IpAddress = IPAddress.Parse("127.0.0.1")
                };

            var smtpServer = new Server(connectionFactory, new NullLog(), serverConfiguration);
            var runTask = smtpServer.RunAsync();

            using (var message = new MailMessage())
            {
                message.From = new MailAddress("*****@*****.**");
                message.To.Add(new MailAddress("*****@*****.**"));
                message.To.Add(new MailAddress("*****@*****.**"));
                message.Body = "Test";

                using (
                    var client = new SmtpClient(smtpServer.LocalEndpoint.Address.ToString(),
                        smtpServer.LocalEndpoint.Port))

                {
                    client.Send(message);
                }
            }

            var stopTask = smtpServer.StopAsync();

            Assert.IsTrue(stopTask.Wait(TimeSpan.FromMilliseconds(2000)));
            Assert.IsTrue(runTask.Wait(TimeSpan.FromMilliseconds(2000)));

            Assert.AreEqual("*****@*****.**", commandHandler.MailFrom);
            Assert.AreEqual(2, commandHandler.Recipients.Count);
            Assert.AreEqual("*****@*****.**", commandHandler.Recipients[0]);
            Assert.AreEqual("*****@*****.**", commandHandler.Recipients[1]);

            var bodyStream = new MemoryStream();
            commandHandler.Body.CopyTo(bodyStream);
            string mailMessage = Encoding.UTF8.GetString(bodyStream.ToArray());
            var bodyStart = mailMessage.IndexOf("\r\n\r\n", StringComparison.InvariantCultureIgnoreCase);
            var body = mailMessage.Substring(bodyStart + 4);
            Assert.AreEqual("Test\r\n\r\n", body);
        }
예제 #17
0
        /// <summary>
        /// Initializes the server and game.
        /// </summary>
        /// <param name="startedCallback">The callback to invoke when initalization is completed.</param>
        public void Initialize(Action<IGame, StandardServer> startedCallback)
        {
            var serverConfig = new ServerConfiguration();
            var server = new StandardServer(new TestPlayerFactory(), new ConnectionFactory());
            server.Configure(serverConfig);
            server.Owner = "@Scionwest";
			this.Server = server;

            var gameConfig = new GameConfiguration();
            gameConfig.UseAdapter(server);

            var game = new MudGame();
            game.Configure(gameConfig);
			this.Game = game;

            game.BeginStart(runningGame => startedCallback(runningGame, server));
        }
        private static InMemoryCommandHandler SendMessageWithAttachment(Attachment attachment)
        {
            var commandHandler = new InMemoryCommandHandler();

            Func<ISession> connectionFactory = () =>
                new SmtpServerSession(commandHandler, new NullLog(), new SmtpServerSessionConfiguration());

            var serverConfiguration = new ServerConfiguration();

            var smtpServer = new Server(connectionFactory, new NullLog(),  serverConfiguration);
            var runTask = smtpServer.RunAsync();
            
            var stopwatch = new Stopwatch();
            stopwatch.Start();

            using (var client = new SmtpClient(smtpServer.LocalEndpoint.Address.ToString(), smtpServer.LocalEndpoint.Port))
            using (var message = new MailMessage())
            {
                message.From = new MailAddress("*****@*****.**");
                message.To.Add(new MailAddress("*****@*****.**"));
                message.To.Add(new MailAddress("*****@*****.**"));
                message.Body = "Test";
                message.Attachments.Add(attachment);


                client.Send(message);
            }
            stopwatch.Stop();

            var stopTask = smtpServer.StopAsync();

            Assert.IsTrue(stopTask.Wait(TimeSpan.FromMilliseconds(2000)));
            Assert.IsTrue(runTask.Wait(TimeSpan.FromMilliseconds(2000)));

            Console.WriteLine("Sending time was {0}", stopwatch.Elapsed);

            return commandHandler;
        }
예제 #19
0
        public MigrationTests()
        {
            serversToTest = new List<ServerConfiguration>();

            foreach (var version in ParseServers())
            {
                var configuration = new ServerConfiguration { Name = PackageName + "." + version };

                if (version.StartsWith("2.0") || version.StartsWith("2.5"))
                {
                    configuration.WaitForIndexingBeforeBackup = true;
                    configuration.StorageTypes = new[] { "esent" };
                }

                if (version.StartsWith("3.0"))
                {
                    configuration.WaitForIndexingBeforeBackup = true;
                    configuration.StorageTypes = new[] { "esent", "voron" };
                }

                serversToTest.Add(configuration);
            }
        }
예제 #20
0
        /// <summary>
        ///     Builds a web host according to Promitor standards
        /// </summary>
        /// <typeparam name="TStartup">type of startup class</typeparam>
        /// <param name="args">Startup arguments</param>
        /// <param name="configuration">General agent configuration</param>
        /// <param name="serverConfiguration">Configuration with regards to the web server</param>
        public static IHostBuilder CreatePromitorWebHost <TStartup>(string[] args, IConfiguration configuration, ServerConfiguration serverConfiguration) where TStartup : class
        {
            var httpPort        = DetermineHttpPort(serverConfiguration);
            var httpEndpointUrl = $"http://+:{httpPort}";

            IHostBuilder webHostBuilder =
                Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(configBuilder => configBuilder.AddConfiguration(configuration))
                .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureKestrel(kestrelServerOptions => kestrelServerOptions.AddServerHeader = false)
                .UseUrls(httpEndpointUrl)
                .UseSerilog()
                .UseStartup <TStartup>();
            });

            return(webHostBuilder);
        }
예제 #21
0
 public static void Configure()
 {
     Enabled        = ServerConfiguration.GetSetting("accountGold.enable", Core.TOL);
     ConvertOnBank  = ServerConfiguration.GetSetting("accountGold.convertOnBank", true);
     ConvertOnTrade = ServerConfiguration.GetSetting("accountGold.convertOnTrade", false);
 }
예제 #22
0
 public MainWindow()
 {
     InitializeComponent();
     serverUiConfiguration = LoadServerUiConfiguration();
     serverConfiguration   = LoadServerConfiguration();
 }
예제 #23
0
 public ServerEndpoint(ServerConfiguration config)
 {
     this.Configuration = config;
 }
예제 #24
0
 public ActionResult UpdateConfiguration([FromBody, Required] ServerConfiguration configuration)
 {
     _configurationManager.ReplaceConfiguration(configuration);
     return(NoContent());
 }
예제 #25
0
        /// <summary>
        /// Detect if a route matches any of whitelisted prefixes
        /// </summary>
        /// <param name="context">Http request context</param>
        /// <param name="authorizationService">Authorization service for each request</param>
        /// <returns>Response be set to 404 if the route is not whitelisted</returns>
        public async Task Invoke(HttpContext context, IAuthorizationService authorizationService = null)
        {
            DateTime requestTime = DateTime.UtcNow;

            // Step 1: if disguise host exists, replace the request header HOST to DISGUISED-HOST
            //         if disguist host does not exist, check and replace ~1 with regex
            if (context.Request.Headers.TryGetValue(DisguisedHostHeader, out StringValues value))
            {
                context.Request.Headers[HostHeader] = value;
            }
            else
            {
                context.Request.Host = new HostString(SanitizeScmUrl(
                                                          context.Request.Headers[HostHeader].FirstOrDefault()));
            }

            if (context.Request.Headers.TryGetValue(ForwardedProtocolHeader, out value))
            {
                context.Request.Scheme = value;
            }

            // Step 2: check if it is homepage route or favicon route, always return 200
            if (IsHomePageRoute(context.Request.Path) || IsFavIconRoute(context.Request.Path))
            {
                context.Response.StatusCode = 200;
                KuduEventGenerator.Log().ApiEvent(
                    ServerConfiguration.GetApplicationName(),
                    "LinuxConsumptionEndpoint",
                    context.Request.GetEncodedPathAndQuery(),
                    context.Request.Method,
                    System.Environment.GetEnvironmentVariable("x-ms-request-id") ?? string.Empty,
                    context.Response.StatusCode,
                    (DateTime.UtcNow - requestTime).Milliseconds,
                    context.Request.GetUserAgent());
                return;
            }

            // Step 3: check if the request endpoint is enabled in Linux Consumption
            if (!IsRouteWhitelisted(context.Request.Path))
            {
                context.Response.StatusCode = 404;
                KuduEventGenerator.Log().ApiEvent(
                    ServerConfiguration.GetApplicationName(),
                    "BlacklistedLinuxConsumptionEndpoint",
                    context.Request.GetEncodedPathAndQuery(),
                    context.Request.Method,
                    System.Environment.GetEnvironmentVariable("x-ms-request-id") ?? string.Empty,
                    context.Response.StatusCode,
                    (DateTime.UtcNow - requestTime).Milliseconds,
                    context.Request.GetUserAgent());
                return;
            }

            // Step 4: check if the request matches authorization policy
            AuthenticateResult authenticationResult = await context.AuthenticateAsync(ArmAuthenticationDefaults.AuthenticationScheme);

            if (!authenticationResult.Succeeded)
            {
                context.Response.StatusCode = 401;
                KuduEventGenerator.Log().ApiEvent(
                    ServerConfiguration.GetApplicationName(),
                    "UnauthenticatedLinuxConsumptionEndpoint",
                    context.Request.GetEncodedPathAndQuery(),
                    context.Request.Method,
                    System.Environment.GetEnvironmentVariable("x-ms-request-id") ?? string.Empty,
                    context.Response.StatusCode,
                    (DateTime.UtcNow - requestTime).Milliseconds,
                    context.Request.GetUserAgent());
                return;
            }

            if (authorizationService != null)
            {
                AuthorizationResult endpointAuthorization = await authorizationService.AuthorizeAsync(authenticationResult.Principal, AuthorizationPolicy);

                if (!endpointAuthorization.Succeeded)
                {
                    context.Response.StatusCode = 401;
                    KuduEventGenerator.Log().ApiEvent(
                        ServerConfiguration.GetApplicationName(),
                        "UnauthorizedLinuxConsumptionEndpoint",
                        context.Request.GetEncodedPathAndQuery(),
                        context.Request.Method,
                        System.Environment.GetEnvironmentVariable("x-ms-request-id") ?? string.Empty,
                        context.Response.StatusCode,
                        (DateTime.UtcNow - requestTime).Milliseconds,
                        context.Request.GetUserAgent());
                    return;
                }
            }

            await _next.Invoke(context);
        }
예제 #26
0
 public BackendCommunication(ServerConfiguration serverConfigurations)
 {
     _serverConfigurations = serverConfigurations;
 }
예제 #27
0
파일: Program.cs 프로젝트: corefan/SlimNet
        static void Main(string[] args)
        {
            #if WIN
            try
            {
                // On win32 we can try to set the
                // size of the console to give us
                // a better overview
                Console.WindowHeight = 50;
                Console.WindowWidth = 120;
                Console.BufferHeight = 6000;
                Console.BufferWidth = 120;
            }
            catch
            {
                // It might fail though, so catch it and ignore it
            }
            #endif
            printAsciiHeader();
            printVersionHeader();

            // Use the default console adapter
            Log.SetAdapter(new LogConsoleAdapter());
            Log log = Log.GetLogger(typeof(Program));

            CommandLineOptions options = new CommandLineOptions();
            ICommandLineParser parser = new CommandLineParser();

            // Parse the command line arguments
            if (parser.ParseArguments(args, options))
            {
                // Switch directory to the assembly path
                Directory.SetCurrentDirectory(options.AssemblyPath);

                // Our configuration
                SlimNet.ServerConfiguration serverConfig = null;

                try
                {
                    // Try to load configuration from command line params
                    XmlSerializer serializer = new XmlSerializer(typeof(ServerConfiguration));
                    serverConfig = (ServerConfiguration)serializer.Deserialize(new StringReader(File.ReadAllText(options.ConfigurationFile)));
                }
                catch (Exception exn)
                {
                    log.Error(exn);
                    log.Warn("Error while loading configuration file, using default configuration instead");

                    // Fallback to default configuration
                    serverConfig = new ServerConfiguration();
                }

                // Set port from command line
                serverConfig.Port = options.Port;

                while (true)
                {
                    try
                    {
                        // Create server
                        SlimNet.Server server = SlimNet.StandaloneServer.Create(serverConfig);
            #if WIN
                        // If on windows we have the option of attaching the debugger
                        if (options.AttachDebugger)
                        {
                            if (!System.Diagnostics.Debugger.IsAttached)
                            {
                                System.Diagnostics.Debugger.Launch();
                            }
                        }

                        if (options.ErrorAttachDebugger)
                        {
                            Log.AttachDebuggerOnError = true;
                        }
            #endif
                        // Start server
                        server.Start();
                    }
                    catch (SlimNet.RecycleException)
                    {
                        //TODO: Actually re-cycle the process
                        return;
                    }
                    catch (Exception exn)
                    {
                        log.Error(exn.GetBaseException());
                        return;
                    }
                }
            }
            else
            {
                // If parsing failed, print usage and exit
                Console.Write(options.GetUsage());
            }
        }
            public ClientConnection(Socket socket, AsynchronousServer.Server server,
                ServerConfiguration configuration, Dictionary<string, IWebSocketService> webSocketServices)
                : base(socket, server)
            {
                this.configuration = configuration;
                this.server = server;
                this.webSocketServices = webSocketServices;

                data = new List<byte>();
                frame = new WebSocketFrame();
                request = new HTTPRequest();

                ConnectionRead += StatefulWebSocketHandShake;
            }
 public FlatFileMusicRepository(ServerConfiguration config, IIdentityProvider converter)
 {
     _config    = config;
     _converter = converter;
 }
예제 #30
0
 public ClientSession(ServerConfiguration configuration, IEnumerable <IPacketController> packetControllers,
                      MapInstanceAccessService mapInstanceAccessService) : this(configuration, packetControllers)
 {
     _mapInstanceAccessService = mapInstanceAccessService;
 }
예제 #31
0
 public static void Configure()
 {
     Address    = ServerConfiguration.GetOrUpdateSetting("serverListing.address", null);
     AutoDetect = ServerConfiguration.GetOrUpdateSetting("serverListing.autoDetect", true);
     ServerName = ServerConfiguration.GetOrUpdateSetting("serverListing.serverName", "ModernUO");
 }
예제 #32
0
 public static void Configure()
 {
     Enabled = ServerConfiguration.GetOrUpdateSetting("questSystem.enableMLQuests", Core.ML);
 }
예제 #33
0
        /// <summary>
        ///     Determines HTTP port to expose agent on
        /// </summary>
        /// <param name="serverConfiguration">Configuration for server</param>
        protected static int DetermineHttpPort(ServerConfiguration serverConfiguration)
        {
            Guard.NotNull(serverConfiguration, nameof(serverConfiguration));

            return(serverConfiguration?.HttpPort ?? 80);
        }
예제 #34
0
파일: Server.cs 프로젝트: corefan/SlimNet
 Server(ServerConfiguration config)
     : base(config)
 {
     Instance = this;
 }
예제 #35
0
파일: SlaveServer.cs 프로젝트: wurunduk/SI
 protected SlaveServer(ServerConfiguration serverConfiguration, INetworkLocalizer localizer)
     : base(serverConfiguration, localizer)
 {
 }
예제 #36
0
    public void Enter()
    {
        Screen.sleepTimeout = SleepTimeout.NeverSleep;
        serverConfiguration = ServerConfigurationModel.ActiveConfiguration;
        Debug.Log($"Downloading files to {serverConfiguration.GetPathToSaveFiles()}");
        var port = int.Parse(serverConfiguration.FileDownloadServerPort);

        if (serverConfiguration.AllFilesDownloaded || Application.isEditor && string.IsNullOrEmpty(serverConfiguration.ClientPathForUnityEditor) == false)
        {
            StateManager.GoToState <GameState>();
        }
        else
        {
            downloadPresenter.gameObject.SetActive(true);

            //Figure out what kind of downloader we should use
            if (serverConfiguration.FileDownloadServerUrl.ToLowerInvariant().Contains("uooutlands.com"))
            {
                downloader = new OutlandsDownloader();
                downloader.Initialize(this, serverConfiguration, downloadPresenter);
            }
            else if (serverConfiguration.FileDownloadServerUrl.ToLowerInvariant().Contains("uorenaissance.com"))
            {
                downloader = new RenaissanceDownloader();
                downloader.Initialize(this, serverConfiguration, downloadPresenter);
            }
            else
            {
                //Get list of files to download from server
                var uri     = GetUri(serverConfiguration.FileDownloadServerUrl, port);
                var request = UnityWebRequest.Get(uri);
                //This request should not take more than 5 seconds, the amount of data being received is very small
                request.timeout = 5;
                request.SendWebRequest().completed += operation =>
                {
                    if (request.isHttpError || request.isNetworkError)
                    {
                        var error = $"Error while making initial request to server: {request.error}";
                        StopAndShowError(error);
                        return;
                    }

                    var headers = request.GetResponseHeaders();

                    if (headers.TryGetValue("Content-Type", out var contentType))
                    {
                        if (contentType.Contains("application/json"))
                        {
                            //Parse json response to get list of files
                            Debug.Log($"Json response: {request.downloadHandler.text}");
                            FilesToDownload = Newtonsoft.Json.JsonConvert.DeserializeObject <List <string> >(request.downloadHandler.text);
                        }
                        else if (contentType.Contains("text/html"))
                        {
                            FilesToDownload = new List <string>(Regex
                                                                .Matches(request.downloadHandler.text, H_REF_PATTERN, RegexOptions.IgnoreCase)
                                                                .Cast <Match>()
                                                                .Select(match => match.Groups[1].Value));
                        }
                    }

                    if (FilesToDownload != null)
                    {
                        FilesToDownload.RemoveAll(file => NeededUoFileExtensions.Any(file.Contains) == false);
                        SetFileListAndDownload(FilesToDownload);
                    }
                    else
                    {
                        StopAndShowError("Could not determine file list to download");
                    }
                };
            }
        }
    }
예제 #37
0
 private void updateSettings()
 {
     ServerConfiguration.getInstance().setIpAddress(serverAddressTextbox.Text);
     ServerConfiguration.getInstance().setPort(Convert.ToInt32(portTextbox.Text));
     this.Close();
 }
예제 #38
0
        public async Task Init()
        {
            IsRunning         = true;
            ExternalIPAddress = await Utilities.GetExternalIP();

            #region DATABASE
            _logger.LogInformation("Beginning database migration sync");
            Console.WriteLine(_translationLookup["MANAGER_MIGRATION_START"]);
            await ContextSeed.Seed(_serviceProvider.GetRequiredService <IDatabaseContextFactory>(), _tokenSource.Token);

            await DatabaseHousekeeping.RemoveOldRatings(_serviceProvider.GetRequiredService <IDatabaseContextFactory>(), _tokenSource.Token);

            _logger.LogInformation("Finished database migration sync");
            Console.WriteLine(_translationLookup["MANAGER_MIGRATION_END"]);
            #endregion

            #region PLUGINS
            foreach (var plugin in Plugins)
            {
                try
                {
                    if (plugin is ScriptPlugin scriptPlugin)
                    {
                        await scriptPlugin.Initialize(this, _scriptCommandFactory, _scriptPluginServiceResolver);

                        scriptPlugin.Watcher.Changed += async(sender, e) =>
                        {
                            try
                            {
                                await scriptPlugin.Initialize(this, _scriptCommandFactory, _scriptPluginServiceResolver);
                            }

                            catch (Exception ex)
                            {
                                Console.WriteLine(Utilities.CurrentLocalization.LocalizationIndex["PLUGIN_IMPORTER_ERROR"].FormatExt(scriptPlugin.Name));
                                _logger.LogError(ex, "Could not properly load plugin {plugin}", scriptPlugin.Name);
                            }
                        };
                    }

                    else
                    {
                        await plugin.OnLoadAsync(this);
                    }
                }

                catch (Exception ex)
                {
                    _logger.LogError(ex, $"{_translationLookup["SERVER_ERROR_PLUGIN"]} {plugin.Name}");
                }
            }
            #endregion

            #region CONFIG
            // copy over default config if it doesn't exist
            if (!_appConfig.Servers?.Any() ?? true)
            {
                var defaultConfig = new BaseConfigurationHandler <DefaultSettings>("DefaultSettings").Configuration();
                //ConfigHandler.Set((ApplicationConfiguration)new ApplicationConfiguration().Generate());
                //var newConfig = ConfigHandler.Configuration();

                _appConfig.AutoMessages          = defaultConfig.AutoMessages;
                _appConfig.GlobalRules           = defaultConfig.GlobalRules;
                _appConfig.DisallowedClientNames = defaultConfig.DisallowedClientNames;

                //if (newConfig.Servers == null)
                {
                    ConfigHandler.Set(_appConfig);
                    _appConfig.Servers = new ServerConfiguration[1];

                    do
                    {
                        var serverConfig = new ServerConfiguration();
                        foreach (var parser in AdditionalRConParsers)
                        {
                            serverConfig.AddRConParser(parser);
                        }

                        foreach (var parser in AdditionalEventParsers)
                        {
                            serverConfig.AddEventParser(parser);
                        }

                        _appConfig.Servers = _appConfig.Servers.Where(_servers => _servers != null).Append((ServerConfiguration)serverConfig.Generate()).ToArray();
                    } while (Utilities.PromptBool(_translationLookup["SETUP_SERVER_SAVE"]));

                    await ConfigHandler.Save();
                }
            }

            else
            {
                if (string.IsNullOrEmpty(_appConfig.Id))
                {
                    _appConfig.Id = Guid.NewGuid().ToString();
                    await ConfigHandler.Save();
                }

                if (string.IsNullOrEmpty(_appConfig.WebfrontBindUrl))
                {
                    _appConfig.WebfrontBindUrl = "http://0.0.0.0:1624";
                    await ConfigHandler.Save();
                }

#pragma warning disable 618
                if (_appConfig.Maps != null)
                {
                    _appConfig.Maps = null;
                }

                if (_appConfig.QuickMessages != null)
                {
                    _appConfig.QuickMessages = null;
                }
#pragma warning restore 618

                var validator        = new ApplicationConfigurationValidator();
                var validationResult = validator.Validate(_appConfig);

                if (!validationResult.IsValid)
                {
                    throw new ConfigurationException("MANAGER_CONFIGURATION_ERROR")
                          {
                              Errors = validationResult.Errors.Select(_error => _error.ErrorMessage).ToArray(),
                              ConfigurationFileName = ConfigHandler.FileName
                          };
                }

                foreach (var serverConfig in _appConfig.Servers)
                {
                    ConfigurationMigration.ModifyLogPath020919(serverConfig);

                    if (serverConfig.RConParserVersion == null || serverConfig.EventParserVersion == null)
                    {
                        foreach (var parser in AdditionalRConParsers)
                        {
                            serverConfig.AddRConParser(parser);
                        }

                        foreach (var parser in AdditionalEventParsers)
                        {
                            serverConfig.AddEventParser(parser);
                        }

                        serverConfig.ModifyParsers();
                    }
                    await ConfigHandler.Save();
                }
            }

            if (_appConfig.Servers.Length == 0)
            {
                throw new ServerException("A server configuration in IW4MAdminSettings.json is invalid");
            }

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Utilities.EncodingType = Encoding.GetEncoding(!string.IsNullOrEmpty(_appConfig.CustomParserEncoding) ? _appConfig.CustomParserEncoding : "windows-1252");

            foreach (var parser in AdditionalRConParsers)
            {
                if (!parser.Configuration.ColorCodeMapping.ContainsKey(ColorCodes.Accent.ToString()))
                {
                    parser.Configuration.ColorCodeMapping.Add(ColorCodes.Accent.ToString(),
                                                              parser.Configuration.ColorCodeMapping.TryGetValue(_appConfig.IngameAccentColorKey, out var colorCode)
                            ? colorCode
                            : "");
                }
            }

            #endregion

            #region COMMANDS
            if (await ClientSvc.HasOwnerAsync(_tokenSource.Token))
            {
                _commands.RemoveAll(_cmd => _cmd.GetType() == typeof(OwnerCommand));
            }

            List <IManagerCommand> commandsToAddToConfig = new List <IManagerCommand>();
            var cmdConfig = _commandConfiguration.Configuration();

            if (cmdConfig == null)
            {
                cmdConfig = new CommandConfiguration();
                commandsToAddToConfig.AddRange(_commands);
            }

            else
            {
                var unsavedCommands = _commands.Where(_cmd => !cmdConfig.Commands.Keys.Contains(_cmd.CommandConfigNameForType()));
                commandsToAddToConfig.AddRange(unsavedCommands);
            }

            // this is because I want to store the command prefix in IW4MAdminSettings, but can't easily
            // inject it to all the places that need it
            cmdConfig.CommandPrefix          = _appConfig?.CommandPrefix ?? "!";
            cmdConfig.BroadcastCommandPrefix = _appConfig?.BroadcastCommandPrefix ?? "@";

            foreach (var cmd in commandsToAddToConfig)
            {
                if (cmdConfig.Commands.ContainsKey(cmd.CommandConfigNameForType()))
                {
                    continue;
                }
                cmdConfig.Commands.Add(cmd.CommandConfigNameForType(),
                                       new CommandProperties
                {
                    Name               = cmd.Name,
                    Alias              = cmd.Alias,
                    MinimumPermission  = cmd.Permission,
                    AllowImpersonation = cmd.AllowImpersonation,
                    SupportedGames     = cmd.SupportedGames
                });
            }

            _commandConfiguration.Set(cmdConfig);
            await _commandConfiguration.Save();

            #endregion

            _metaRegistration.Register();

            #region CUSTOM_EVENTS
            foreach (var customEvent in _customParserEvents.SelectMany(_events => _events.Events))
            {
                foreach (var parser in AdditionalEventParsers)
                {
                    parser.RegisterCustomEvent(customEvent.Item1, customEvent.Item2, customEvent.Item3);
                }
            }
            #endregion

            Console.WriteLine(_translationLookup["MANAGER_COMMUNICATION_INFO"]);
            await InitializeServers();
        }
예제 #39
0
 public Server(ServerConfiguration configuration) : base(configuration)
 {
 }
예제 #40
0
            public ClientConnection(Socket socket, MinimalHTTPServer.Server server,
                ServerConfiguration configuration)
                : base(socket, server.getServer())
            {
                this.configuration = configuration;
                this.server = server;

                ConnectionRead += StatefulConnectionRead;
            }
예제 #41
0
 public TokenConfigurationProvider(IOptions <ServerConfiguration> serverConfig)
 {
     this.ServerConfiguration = serverConfig.Value;
 }
예제 #42
0
 /// <summary>
 /// Создание зависимого сервера, подключающегося к главному
 /// </summary>
 /// <param name="port">Имя порта для подключения</param>
 /// <param name="serverAddress">Адрес сервера</param>
 public TcpSlaveServer(int port, string serverAddress, ServerConfiguration serverConfiguration, INetworkLocalizer localizer)
     : base(serverConfiguration, localizer)
 {
     _serverAddress = serverAddress;
     _port          = port;
 }
예제 #43
0
        private static void RegisterServices(IKernel kernel)
        {
            var serverConfiguration = new ServerConfiguration();

            // Make sure %HOME% is correctly set
            EnsureHomeEnvironmentVariable();

            EnsureSiteBitnessEnvironmentVariable();

            IEnvironment environment = GetEnvironment();

            // Per request environment
            kernel.Bind <IEnvironment>().ToMethod(context => GetEnvironment(context.Kernel.Get <IDeploymentSettingsManager>()))
            .InRequestScope();

            // General
            kernel.Bind <HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current))
            .InRequestScope();
            kernel.Bind <IServerConfiguration>().ToConstant(serverConfiguration);

            kernel.Bind <IBuildPropertyProvider>().ToConstant(new BuildPropertyProvider());

            System.Func <ITracer> createTracerThunk = () => GetTracer(environment, kernel);
            System.Func <ILogger> createLoggerThunk = () => GetLogger(environment, kernel);

            // First try to use the current request profiler if any, otherwise create a new one
            var traceFactory = new TracerFactory(() => TraceServices.CurrentRequestTracer ?? createTracerThunk());

            kernel.Bind <ITracer>().ToMethod(context => TraceServices.CurrentRequestTracer ?? NullTracer.Instance);
            kernel.Bind <ITraceFactory>().ToConstant(traceFactory);
            TraceServices.SetTraceFactory(createTracerThunk, createLoggerThunk);

            // Setup the deployment lock
            string lockPath           = Path.Combine(environment.SiteRootPath, Constants.LockPath);
            string deploymentLockPath = Path.Combine(lockPath, Constants.DeploymentLockFile);
            string statusLockPath     = Path.Combine(lockPath, Constants.StatusLockFile);
            string sshKeyLockPath     = Path.Combine(lockPath, Constants.SSHKeyLockFile);
            string hooksLockPath      = Path.Combine(lockPath, Constants.HooksLockFile);

            _deploymentLock = new DeploymentLockFile(deploymentLockPath, kernel.Get <ITraceFactory>());
            _deploymentLock.InitializeAsyncLocks();

            var statusLock = new LockFile(statusLockPath, kernel.Get <ITraceFactory>());
            var sshKeyLock = new LockFile(sshKeyLockPath, kernel.Get <ITraceFactory>());
            var hooksLock  = new LockFile(hooksLockPath, kernel.Get <ITraceFactory>());

            kernel.Bind <IOperationLock>().ToConstant(sshKeyLock).WhenInjectedInto <SSHKeyController>();
            kernel.Bind <IOperationLock>().ToConstant(statusLock).WhenInjectedInto <DeploymentStatusManager>();
            kernel.Bind <IOperationLock>().ToConstant(hooksLock).WhenInjectedInto <WebHooksManager>();
            kernel.Bind <IOperationLock>().ToConstant(_deploymentLock);

            var shutdownDetector = new ShutdownDetector();

            shutdownDetector.Initialize();

            IDeploymentSettingsManager noContextDeploymentsSettingsManager =
                new DeploymentSettingsManager(new XmlSettings.Settings(GetSettingsPath(environment)));

            var noContextTraceFactory = new TracerFactory(() => GetTracerWithoutContext(environment, noContextDeploymentsSettingsManager));

            kernel.Bind <IAnalytics>().ToMethod(context => new Analytics(context.Kernel.Get <IDeploymentSettingsManager>(),
                                                                         context.Kernel.Get <IServerConfiguration>(),
                                                                         noContextTraceFactory));

            // Trace unhandled (crash) exceptions.
            AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
            {
                var ex = args.ExceptionObject as Exception;
                if (ex != null)
                {
                    kernel.Get <IAnalytics>().UnexpectedException(ex);
                }
            };

            // Trace shutdown event
            // Cannot use shutdownDetector.Token.Register because of race condition
            // with NinjectServices.Stop via WebActivator.ApplicationShutdownMethodAttribute
            Shutdown += () => TraceShutdown(environment, noContextDeploymentsSettingsManager);

            // LogStream service
            // The hooks and log stream start endpoint are low traffic end-points. Re-using it to avoid creating another lock
            var logStreamManagerLock = hooksLock;

            kernel.Bind <LogStreamManager>().ToMethod(context => new LogStreamManager(Path.Combine(environment.RootPath, Constants.LogFilesPath),
                                                                                      context.Kernel.Get <IEnvironment>(),
                                                                                      context.Kernel.Get <IDeploymentSettingsManager>(),
                                                                                      context.Kernel.Get <ITracer>(),
                                                                                      shutdownDetector,
                                                                                      logStreamManagerLock));

            kernel.Bind <InfoRefsController>().ToMethod(context => new InfoRefsController(t => context.Kernel.Get(t)))
            .InRequestScope();

            kernel.Bind <CustomGitRepositoryHandler>().ToMethod(context => new CustomGitRepositoryHandler(t => context.Kernel.Get(t)))
            .InRequestScope();

            // Deployment Service
            kernel.Bind <ISettings>().ToMethod(context => new XmlSettings.Settings(GetSettingsPath(environment)))
            .InRequestScope();
            kernel.Bind <IDeploymentSettingsManager>().To <DeploymentSettingsManager>()
            .InRequestScope();

            kernel.Bind <IDeploymentStatusManager>().To <DeploymentStatusManager>()
            .InRequestScope();

            kernel.Bind <ISiteBuilderFactory>().To <SiteBuilderFactory>()
            .InRequestScope();

            kernel.Bind <IWebHooksManager>().To <WebHooksManager>()
            .InRequestScope();

            ITriggeredJobsManager triggeredJobsManager = new TriggeredJobsManager(
                noContextTraceFactory,
                kernel.Get <IEnvironment>(),
                kernel.Get <IDeploymentSettingsManager>(),
                kernel.Get <IAnalytics>(),
                kernel.Get <IWebHooksManager>());

            kernel.Bind <ITriggeredJobsManager>().ToConstant(triggeredJobsManager)
            .InTransientScope();

            IContinuousJobsManager continuousJobManager = new ContinuousJobsManager(
                noContextTraceFactory,
                kernel.Get <IEnvironment>(),
                kernel.Get <IDeploymentSettingsManager>(),
                kernel.Get <IAnalytics>());

            triggeredJobsManager.CleanupDeletedJobs();
            continuousJobManager.CleanupDeletedJobs();

            kernel.Bind <IContinuousJobsManager>().ToConstant(continuousJobManager)
            .InTransientScope();

            kernel.Bind <ILogger>().ToMethod(context => GetLogger(environment, context.Kernel))
            .InRequestScope();

            kernel.Bind <IRepository>().ToMethod(context => new GitExeRepository(context.Kernel.Get <IEnvironment>(),
                                                                                 context.Kernel.Get <IDeploymentSettingsManager>(),
                                                                                 context.Kernel.Get <ITraceFactory>()))
            .InRequestScope();

            kernel.Bind <IDeploymentManager>().To <DeploymentManager>()
            .InRequestScope();
            kernel.Bind <ISSHKeyManager>().To <SSHKeyManager>()
            .InRequestScope();

            kernel.Bind <IRepositoryFactory>().ToMethod(context => _deploymentLock.RepositoryFactory = new RepositoryFactory(context.Kernel.Get <IEnvironment>(),
                                                                                                                             context.Kernel.Get <IDeploymentSettingsManager>(),
                                                                                                                             context.Kernel.Get <ITraceFactory>(),
                                                                                                                             context.Kernel.Get <HttpContextBase>()))
            .InRequestScope();

            kernel.Bind <IApplicationLogsReader>().To <ApplicationLogsReader>()
            .InSingletonScope();

            // Git server
            kernel.Bind <IDeploymentEnvironment>().To <DeploymentEnvrionment>();

            kernel.Bind <IGitServer>().ToMethod(context => new GitExeServer(context.Kernel.Get <IEnvironment>(),
                                                                            _deploymentLock,
                                                                            GetRequestTraceFile(context.Kernel),
                                                                            context.Kernel.Get <IRepositoryFactory>(),
                                                                            context.Kernel.Get <IDeploymentEnvironment>(),
                                                                            context.Kernel.Get <IDeploymentSettingsManager>(),
                                                                            context.Kernel.Get <ITraceFactory>()))
            .InRequestScope();

            // Git Servicehook parsers
            kernel.Bind <IServiceHookHandler>().To <GenericHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <GitHubHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <BitbucketHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <DropboxHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <CodePlexHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <CodebaseHqHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <GitlabHqHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <GitHubCompatHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <KilnHgHandler>().InRequestScope();

            // SiteExtensions
            kernel.Bind <ISiteExtensionManager>().To <SiteExtensionManager>().InRequestScope();

            // Command executor
            kernel.Bind <ICommandExecutor>().ToMethod(context => GetCommandExecutor(environment, context))
            .InRequestScope();

            MigrateSite(environment, noContextDeploymentsSettingsManager);

            // Temporary fix for https://github.com/npm/npm/issues/5905
            EnsureNpmGlobalDirectory();

            RegisterRoutes(kernel, RouteTable.Routes);

            // Register the default hubs route: ~/signalr
            GlobalHost.DependencyResolver = new SignalRNinjectDependencyResolver(kernel);
            GlobalConfiguration.Configuration.Filters.Add(
                new TraceDeprecatedActionAttribute(
                    kernel.Get <IAnalytics>(),
                    kernel.Get <ITraceFactory>()));
        }
예제 #44
0
        public static async Task RunMasterClient(string targetHost, int port, string password, MasterClient clientType, ServerConfiguration WebApi, int connectedAccountLimit = 0, int clientPort = 0, byte serverGroup = 0, string serverHost = "")
        {
            var group = new MultithreadEventLoopGroup();

            var bootstrap = new Bootstrap();

            bootstrap
            .Group(group)
            .Channel <TcpSocketChannel>()
            .Option(ChannelOption.TcpNodelay, true)
            .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;

                pipeline.AddLast(new LengthFieldPrepender(2));
                pipeline.AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                pipeline.AddLast(new StringEncoder(), new StringDecoder());
                pipeline.AddLast(new MasterClientSession(password));
            }));
            var connection = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(targetHost), port));

            await connection.WriteAndFlushAsync(new Channel()
            {
                Password               = password,
                ClientName             = clientType.Name,
                ClientType             = (byte)clientType.Type,
                ConnectedAccountsLimit = connectedAccountLimit,
                Port        = clientPort,
                ServerGroup = serverGroup,
                Host        = serverHost,
                WebApi      = WebApi
            });
        }
예제 #45
0
 public EventForwardHandler(ILogger log, IConnectionCollection <IClientPeer> connectionCollection, ServerConfiguration serverConfiguration, IClientCodeRemover clientCodeRemover)
 {
     Log = log;
     _connectionCollection = connectionCollection;
     _serverConfiguration  = serverConfiguration;
     _clientCodeRemover    = clientCodeRemover;
 }
예제 #46
0
 public static void Configure()
 {
     Enabled = ServerConfiguration.GetOrUpdateSetting("ethics.enable", false);
 }
예제 #47
0
 public Server(ServerConfiguration serverConfiguration)
 {
     this.configuration = serverConfiguration;
 }
예제 #48
0
        public async Task Init()
        {
            Running           = true;
            ExternalIPAddress = await Utilities.GetExternalIP();

            #region PLUGINS
            SharedLibraryCore.Plugins.PluginImporter.Load(this);

            foreach (var Plugin in SharedLibraryCore.Plugins.PluginImporter.ActivePlugins)
            {
                try
                {
                    await Plugin.OnLoadAsync(this);
                }

                catch (Exception ex)
                {
                    Logger.WriteError($"{Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_PLUGIN"]} {Plugin.Name}");
                    Logger.WriteDebug(ex.GetExceptionInfo());
                }
            }
            #endregion

            #region CONFIG
            var config = ConfigHandler.Configuration();

            // copy over default config if it doesn't exist
            if (config == null)
            {
                var defaultConfig = new BaseConfigurationHandler <DefaultConfiguration>("DefaultSettings").Configuration();
                ConfigHandler.Set((ApplicationConfiguration) new ApplicationConfiguration().Generate());
                var newConfig = ConfigHandler.Configuration();

                newConfig.AutoMessages          = defaultConfig.AutoMessages;
                newConfig.GlobalRules           = defaultConfig.GlobalRules;
                newConfig.Maps                  = defaultConfig.Maps;
                newConfig.DisallowedClientNames = defaultConfig.DisallowedClientNames;
                newConfig.QuickMessages         = defaultConfig.QuickMessages;

                if (newConfig.Servers == null)
                {
                    ConfigHandler.Set(newConfig);
                    newConfig.Servers = new List <ServerConfiguration>();

                    do
                    {
                        var serverConfig = new ServerConfiguration();
                        foreach (var parser in AdditionalRConParsers)
                        {
                            serverConfig.AddRConParser(parser);
                        }

                        foreach (var parser in AdditionalEventParsers)
                        {
                            serverConfig.AddEventParser(parser);
                        }

                        newConfig.Servers.Add((ServerConfiguration)serverConfig.Generate());
                    } while (Utilities.PromptBool(Utilities.CurrentLocalization.LocalizationIndex["SETUP_SERVER_SAVE"]));

                    config = newConfig;
                    await ConfigHandler.Save();
                }
            }

            else
            {
                if (string.IsNullOrEmpty(config.Id))
                {
                    config.Id = Guid.NewGuid().ToString();
                    await ConfigHandler.Save();
                }

                if (string.IsNullOrEmpty(config.WebfrontBindUrl))
                {
                    config.WebfrontBindUrl = "http://0.0.0.0:1624";
                    await ConfigHandler.Save();
                }

                foreach (var serverConfig in config.Servers)
                {
                    Migration.ConfigurationMigration.ModifyLogPath020919(serverConfig);

                    if (serverConfig.RConParserVersion == null || serverConfig.EventParserVersion == null)
                    {
                        foreach (var parser in AdditionalRConParsers)
                        {
                            serverConfig.AddRConParser(parser);
                        }

                        foreach (var parser in AdditionalEventParsers)
                        {
                            serverConfig.AddEventParser(parser);
                        }

                        serverConfig.ModifyParsers();
                    }
                    await ConfigHandler.Save();
                }
            }

            if (config.Servers.Count == 0)
            {
                throw new ServerException("A server configuration in IW4MAdminSettings.json is invalid");
            }

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Utilities.EncodingType = Encoding.GetEncoding(!string.IsNullOrEmpty(config.CustomParserEncoding) ? config.CustomParserEncoding : "windows-1252");

            #endregion

            #region DATABASE
            using (var db = new DatabaseContext(GetApplicationSettings().Configuration()?.ConnectionString,
                                                GetApplicationSettings().Configuration()?.DatabaseProvider))
            {
                await new ContextSeed(db).Seed();
            }

            PrivilegedClients = (await ClientSvc.GetPrivilegedClients()).ToDictionary(_client => _client.ClientId);
            #endregion

            #region COMMANDS
            if (ClientSvc.GetOwners().Result.Count == 0)
            {
                Commands.Add(new COwner());
            }

            Commands.Add(new CQuit());
            Commands.Add(new CKick());
            Commands.Add(new CSay());
            Commands.Add(new CTempBan());
            Commands.Add(new CBan());
            Commands.Add(new CWhoAmI());
            Commands.Add(new CList());
            Commands.Add(new CHelp());
            Commands.Add(new CFastRestart());
            Commands.Add(new CMapRotate());
            Commands.Add(new CSetLevel());
            Commands.Add(new CUsage());
            Commands.Add(new CUptime());
            Commands.Add(new CWarn());
            Commands.Add(new CWarnClear());
            Commands.Add(new CUnban());
            Commands.Add(new CListAdmins());
            Commands.Add(new CLoadMap());
            Commands.Add(new CFindPlayer());
            Commands.Add(new CListRules());
            Commands.Add(new CPrivateMessage());
            Commands.Add(new CFlag());
            Commands.Add(new CUnflag());
            Commands.Add(new CReport());
            Commands.Add(new CListReports());
            Commands.Add(new CListBanInfo());
            Commands.Add(new CListAlias());
            Commands.Add(new CExecuteRCON());
            Commands.Add(new CPlugins());
            Commands.Add(new CIP());
            Commands.Add(new CMask());
            Commands.Add(new CPruneAdmins());
            Commands.Add(new CKillServer());
            Commands.Add(new CSetPassword());
            Commands.Add(new CPing());
            Commands.Add(new CSetGravatar());
            Commands.Add(new CNextMap());
            Commands.Add(new RequestTokenCommand());

            foreach (Command C in SharedLibraryCore.Plugins.PluginImporter.ActiveCommands)
            {
                Commands.Add(C);
            }
            #endregion

            #region META
            async Task <List <ProfileMeta> > getProfileMeta(int clientId, int offset, int count, DateTime?startAt)
            {
                var metaList = new List <ProfileMeta>();

                // we don't want to return anything because it means we're trying to retrieve paged meta data
                if (count > 1)
                {
                    return(metaList);
                }

                var lastMapMeta = await _metaService.GetPersistentMeta("LastMapPlayed", new EFClient()
                {
                    ClientId = clientId
                });

                if (lastMapMeta != null)
                {
                    metaList.Add(new ProfileMeta()
                    {
                        Id    = lastMapMeta.MetaId,
                        Key   = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_CLIENT_META_LAST_MAP"],
                        Value = lastMapMeta.Value,
                        Show  = true,
                        Type  = ProfileMeta.MetaType.Information,
                    });
                }

                var lastServerMeta = await _metaService.GetPersistentMeta("LastServerPlayed", new EFClient()
                {
                    ClientId = clientId
                });

                if (lastServerMeta != null)
                {
                    metaList.Add(new ProfileMeta()
                    {
                        Id    = lastServerMeta.MetaId,
                        Key   = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_CLIENT_META_LAST_SERVER"],
                        Value = lastServerMeta.Value,
                        Show  = true,
                        Type  = ProfileMeta.MetaType.Information
                    });
                }

                var client = await GetClientService().Get(clientId);

                metaList.Add(new ProfileMeta()
                {
                    Id     = client.ClientId,
                    Key    = $"{Utilities.CurrentLocalization.LocalizationIndex["GLOBAL_TIME_HOURS"]} {Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_PROFILE_PLAYER"]}",
                    Value  = Math.Round(client.TotalConnectionTime / 3600.0, 1).ToString("#,##0", new System.Globalization.CultureInfo(Utilities.CurrentLocalization.LocalizationName)),
                    Show   = true,
                    Column = 1,
                    Order  = 0,
                    Type   = ProfileMeta.MetaType.Information
                });

                metaList.Add(new ProfileMeta()
                {
                    Id     = client.ClientId,
                    Key    = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_PROFILE_FSEEN"],
                    Value  = Utilities.GetTimePassed(client.FirstConnection, false),
                    Show   = true,
                    Column = 1,
                    Order  = 1,
                    Type   = ProfileMeta.MetaType.Information
                });

                metaList.Add(new ProfileMeta()
                {
                    Id     = client.ClientId,
                    Key    = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_PROFILE_LSEEN"],
                    Value  = Utilities.GetTimePassed(client.LastConnection, false),
                    Show   = true,
                    Column = 1,
                    Order  = 2,
                    Type   = ProfileMeta.MetaType.Information
                });

                metaList.Add(new ProfileMeta()
                {
                    Id     = client.ClientId,
                    Key    = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_CLIENT_META_CONNECTIONS"],
                    Value  = client.Connections.ToString("#,##0", new System.Globalization.CultureInfo(Utilities.CurrentLocalization.LocalizationName)),
                    Show   = true,
                    Column = 1,
                    Order  = 3,
                    Type   = ProfileMeta.MetaType.Information
                });

                metaList.Add(new ProfileMeta()
                {
                    Key       = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_CLIENT_META_MASKED"],
                    Value     = client.Masked ? Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_CLIENT_META_TRUE"] : Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_CLIENT_META_FALSE"],
                    Sensitive = true,
                    Column    = 1,
                    Order     = 4,
                    Type      = ProfileMeta.MetaType.Information
                });

                return(metaList);
            }

            async Task <List <ProfileMeta> > getPenaltyMeta(int clientId, int offset, int count, DateTime?startAt)
            {
                if (count <= 1)
                {
                    return(new List <ProfileMeta>());
                }

                var penalties = await GetPenaltyService().GetClientPenaltyForMetaAsync(clientId, count, offset, startAt);

                return(penalties.Select(_penalty => new ProfileMeta()
                {
                    Id = _penalty.Id,
                    Type = _penalty.PunisherId == clientId ? ProfileMeta.MetaType.Penalized : ProfileMeta.MetaType.ReceivedPenalty,
                    Value = _penalty,
                    When = _penalty.TimePunished,
                    Sensitive = _penalty.Sensitive
                })
                       .ToList());
            }

            MetaService.AddRuntimeMeta(getProfileMeta);
            MetaService.AddRuntimeMeta(getPenaltyMeta);
            #endregion

            #region INIT
            int       failedServers  = 0;
            int       successServers = 0;
            Exception lastException  = null;

            async Task Init(ServerConfiguration Conf)
            {
                // setup the event handler after the class is initialized

                Handler = new GameEventHandler(this);

                try
                {
                    var ServerInstance = new IW4MServer(this, Conf);
                    await ServerInstance.Initialize();

                    lock (_servers)
                    {
                        _servers.Add(ServerInstance);
                    }

                    Logger.WriteVerbose(Utilities.CurrentLocalization.LocalizationIndex["MANAGER_MONITORING_TEXT"].FormatExt(ServerInstance.Hostname));
                    // add the start event for this server

                    var e = new GameEvent()
                    {
                        Type  = GameEvent.EventType.Start,
                        Data  = $"{ServerInstance.GameName} started",
                        Owner = ServerInstance
                    };

                    Handler.AddEvent(e);
                    successServers++;
                }

                catch (ServerException e)
                {
                    Logger.WriteError(Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_UNFIXABLE"].FormatExt($"[{Conf.IPAddress}:{Conf.Port}]"));

                    if (e.GetType() == typeof(DvarException))
                    {
                        Logger.WriteDebug($"{Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_DVAR"].FormatExt((e as DvarException).Data["dvar_name"])} ({Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_DVAR_HELP"]})");
                    }

                    else if (e.GetType() == typeof(NetworkException))
                    {
                        Logger.WriteDebug(e.Message);
                    }

                    failedServers++;
                    lastException = e;
                }
            }

            await Task.WhenAll(config.Servers.Select(c => Init(c)).ToArray());

            if (successServers - failedServers <= 0)
            {
                if (!Utilities.PromptBool(Utilities.CurrentLocalization.LocalizationIndex["MANAGER_START_WITH_ERRORS"]))
                {
                    throw lastException;
                }
            }
            #endregion
        }
예제 #49
0
 public ScreenInstance(ServerConfiguration config, string session)
 {
     Config        = config;
     ScreenSession = session;
 }
 public ClientConnection(Socket socket, AsynchronousServer.Server server,
     ServerConfiguration configuration, Dictionary<string, IWebSocketService> webSocketServices,
     HTTPRequest request)
     : this(socket, server, configuration, webSocketServices)
 {
     this.request = request;
 }
예제 #51
0
 public bool tryParseAppend(ArraySegment<byte> input, ServerConfiguration configuration)
 {
     return tryParseAppend(input, configuration.maxRequestLength);
 }
예제 #52
0
 public static void Configure()
 {
     Enabled         = ServerConfiguration.GetOrUpdateSetting("vetRewards.enable", true);
     SkillCapRewards = ServerConfiguration.GetOrUpdateSetting("vetRewards.skillCapRewards", true);
     RewardInterval  = ServerConfiguration.GetOrUpdateSetting("vetRewards.rewardInterval", TimeSpan.FromDays(30.0));
 }
예제 #53
0
 public void UpdateConfiguration(ServerConfiguration config)
 {
     authorizationService.VerifyFactoryOwner();
 }
예제 #54
0
        public void TestSmtpEndToEndWithSsl()
        {
            var commandHandler = new InMemoryCommandHandler();

            var certificate = new X509Certificate2(Resources.debugcert, "secret", X509KeyStorageFlags.Exportable);

            var smtpSessionConfiguration = new SmtpServerSessionConfiguration()
            {
                SslCertificate = certificate
            };

            Func <ISession> connectionFactory = () =>
                                                new SmtpServerSession(commandHandler, new NullLog(), smtpSessionConfiguration);

            var serverConfiguration = new ServerConfiguration()
            {
                IpAddress = IPAddress.Parse("127.0.0.1")
            };


            var smtpServer = new Server(connectionFactory, new NullLog(), serverConfiguration);
            var runTask    = smtpServer.RunAsync();

            using (var message = new MailMessage())
            {
                message.From = new MailAddress("*****@*****.**");
                message.To.Add(new MailAddress("*****@*****.**"));
                message.To.Add(new MailAddress("*****@*****.**"));
                message.Body = "Test";

                using (var client = new SmtpClient(smtpServer.LocalEndpoint.Address.ToString(),
                                                   smtpServer.LocalEndpoint.Port))


                {
                    ServicePointManager.ServerCertificateValidationCallback = (sender, serverCertificate, chain, sslPolicyErrors) =>
                    {
                        var certificate2 = (X509Certificate2)serverCertificate;
                        return(certificate2.Thumbprint == certificate.Thumbprint);
                    };

                    client.EnableSsl = true;
                    client.Send(message);
                }
            }

            var stopTask = smtpServer.StopAsync();

            Assert.IsTrue(stopTask.Wait(TimeSpan.FromMilliseconds(2000)));
            Assert.IsTrue(runTask.Wait(TimeSpan.FromMilliseconds(2000)));

            Assert.AreEqual("*****@*****.**", commandHandler.MailFrom);
            Assert.AreEqual(2, commandHandler.Recipients.Count);
            Assert.AreEqual("*****@*****.**", commandHandler.Recipients[0]);
            Assert.AreEqual("*****@*****.**", commandHandler.Recipients[1]);

            var bodyStream = new MemoryStream();

            commandHandler.Body.CopyTo(bodyStream);

            string mailMessage = Encoding.UTF8.GetString(bodyStream.ToArray());
            var    bodyStart   = mailMessage.IndexOf("\r\n\r\n", StringComparison.InvariantCultureIgnoreCase);
            var    body        = mailMessage.Substring(bodyStart + 4);

            Assert.AreEqual("Test\r\n\r\n", body);
        }
예제 #55
0
 /// <summary>
 /// Initializes a new instance of dashboard service
 /// </summary>
 /// <param name="agents">The <see cref="AgentsCollection">connections tracker</see> for the server</param>
 /// <param name="log">The log to display for requests</param>
 /// <param name="serverConfiguration">The server configuration.</param>
 /// <param name="connectionProvider">The connection provider.</param>
 public DashboardService(AgentsCollection agents, 
     RollingLog log,
     ServerConfiguration serverConfiguration,
     IConnectionProvider connectionProvider)
 {
     this.agents = agents;
     this.log = log;
     this.serverConfiguration = serverConfiguration;
     this.connectionProvider = connectionProvider;
 }
예제 #56
0
        /// <summary>
        /// Main
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            Console.WriteLine("Starting LightLDS - The lightweight OPC UA Local Discovery Server");

            ApplicationInstance application = new ApplicationInstance();

            try
            {
                var applicationConfiguration = new ApplicationConfiguration();
                applicationConfiguration.ApplicationName = "Light OPC UA Local Discovery Server";
                applicationConfiguration.ApplicationUri  = "urn:localhost:K47S:LocalDiscoveryServer";
                applicationConfiguration.ProductUri      = "http://K47S/LocalDiscoveryServer";
                applicationConfiguration.ApplicationType = ApplicationType.DiscoveryServer;

                var securityConfiguration = new SecurityConfiguration();
                securityConfiguration.ApplicationCertificate = new CertificateIdentifier()
                {
                    StoreType   = @"Directory",
                    StorePath   = @"%CommonApplicationData%/LightLDS/PKI/own",
                    SubjectName = "CN=Local Discovery Server, O=K47S, DC=localhost",
                };
                securityConfiguration.TrustedIssuerCertificates = new CertificateTrustList()
                {
                    StoreType = @"Directory",
                    StorePath = @"%CommonApplicationData%/LightLDS/PKI/issuers",
                };
                securityConfiguration.TrustedPeerCertificates = new CertificateTrustList()
                {
                    StoreType = @"Directory",
                    StorePath = @"%CommonApplicationData%/LightLDS/PKI/trusted",
                };
                securityConfiguration.RejectedCertificateStore = new CertificateTrustList()
                {
                    StoreType = @"Directory",
                    StorePath = @"%CommonApplicationData%/LightLDS/PKI/rejected",
                };
                securityConfiguration.AutoAcceptUntrustedCertificates = true;
                securityConfiguration.RejectSHA1SignedCertificates    = false;
                securityConfiguration.MinimumCertificateKeySize       = 1024;
                applicationConfiguration.SecurityConfiguration        = securityConfiguration;

                var serverConfiguration = new ServerConfiguration();
                serverConfiguration.BaseAddresses = new StringCollection(new List <string>()
                {
                    "opc.tcp://localhost:4840"
                });
                serverConfiguration.SecurityPolicies = new ServerSecurityPolicyCollection(new List <ServerSecurityPolicy>()
                {
                    new ServerSecurityPolicy()
                    {
                        SecurityMode      = MessageSecurityMode.None,
                        SecurityPolicyUri = "http://opcfoundation.org/UA/SecurityPolicy#None",
                    }
                });
                serverConfiguration.UserTokenPolicies = new UserTokenPolicyCollection(new List <UserTokenPolicy>()
                {
                    new UserTokenPolicy()
                    {
                        TokenType         = UserTokenType.Anonymous,
                        SecurityPolicyUri = "http://opcfoundation.org/UA/SecurityPolicy#None"
                    }
                });
                serverConfiguration.DiagnosticsEnabled           = true;
                serverConfiguration.MaxSessionCount              = 100;
                serverConfiguration.MinSessionTimeout            = 10000;
                serverConfiguration.MaxSessionTimeout            = 3600000;
                serverConfiguration.MaxBrowseContinuationPoints  = 10;
                serverConfiguration.MaxQueryContinuationPoints   = 10;
                serverConfiguration.MaxHistoryContinuationPoints = 100;
                serverConfiguration.MaxRequestAge               = 600000;
                serverConfiguration.MinPublishingInterval       = 100;
                serverConfiguration.MaxPublishingInterval       = 3600000;
                serverConfiguration.PublishingResolution        = 100;
                serverConfiguration.MaxSubscriptionLifetime     = 3600000;
                serverConfiguration.MaxMessageQueueSize         = 100;
                serverConfiguration.MaxNotificationQueueSize    = 100;
                serverConfiguration.MaxNotificationsPerPublish  = 1000;
                serverConfiguration.MinMetadataSamplingInterval = 1000;
                applicationConfiguration.ServerConfiguration    = serverConfiguration;

                var transportQuotaConfig = new TransportQuotas();
                applicationConfiguration.TransportQuotas = transportQuotaConfig;

                var traceConfiguration = new TraceConfiguration();
                traceConfiguration.OutputFilePath           = "%CommonApplicationData%/LightLDS/Logs/LocalDiscoveryServer.log.txt";
                traceConfiguration.DeleteOnLoad             = true;
                traceConfiguration.TraceMasks               = 0x7FFFFFFF;
                applicationConfiguration.TraceConfiguration = traceConfiguration;

                application.ApplicationConfiguration = applicationConfiguration;
                application.ApplicationConfiguration.Validate(ApplicationType.Server);
                // check the application certificate.
                application.CheckApplicationInstanceCertificate(false, 0).Wait();

                // start the server.
                var server = new DiscoveryServerInstance();
                application.Start(server).Wait();

                Console.WriteLine("LightLDS running. Press ENTER to exit.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            Console.ReadLine();
        }
예제 #57
0
        private void tryBind(Socket listener, ServerConfiguration configuration)
        {
            IPEndPoint localEndPoint = new IPEndPoint(configuration.ipAddresses[0], configuration.port);

                listener.Bind(localEndPoint);
                listener.Listen(configuration.backLog);
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
        }
예제 #58
0
        /// <summary>
        /// Updates the XML document with the new configuration information.
        /// </summary>
        private static void UpdateDocument(XmlElement element, SecuredApplication application)
        {
            for (XmlNode node = element.FirstChild; node != null; node = node.NextSibling)
            {
                if (node.Name == "ApplicationName" && node.NamespaceURI == Namespaces.OpcUaConfig)
                {
                    node.InnerText = application.ApplicationName;
                    continue;
                }

                if (node.Name == "ApplicationUri" && node.NamespaceURI == Namespaces.OpcUaConfig)
                {
                    node.InnerText = application.ApplicationUri;
                    continue;
                }

                if (node.Name == "SecurityConfiguration" && node.NamespaceURI == Namespaces.OpcUaConfig)
                {
                    SecurityConfiguration security =
                        (SecurityConfiguration)GetObject(typeof(SecurityConfiguration), node);

                    if (application.ApplicationCertificate != null)
                    {
                        security.ApplicationCertificate =
                            SecuredApplication.FromCertificateIdentifier(application.ApplicationCertificate);
                    }

                    security.TrustedIssuerCertificates =
                        SecuredApplication.FromCertificateStoreIdentifierToTrustList(application
                                                                                     .IssuerCertificateStore);
                    security.TrustedIssuerCertificates.TrustedCertificates =
                        SecuredApplication.FromCertificateList(application.IssuerCertificates);
                    security.TrustedPeerCertificates =
                        SecuredApplication.FromCertificateStoreIdentifierToTrustList(
                            application.TrustedCertificateStore);
                    security.TrustedPeerCertificates.TrustedCertificates =
                        SecuredApplication.FromCertificateList(application.TrustedCertificates);
                    security.RejectedCertificateStore =
                        SecuredApplication.FromCertificateStoreIdentifier(application.RejectedCertificatesStore);

                    node.InnerXml = SetObject(typeof(SecurityConfiguration), security);
                    continue;
                }

                if (node.Name == "ServerConfiguration" && node.NamespaceURI == Namespaces.OpcUaConfig)
                {
                    ServerConfiguration configuration =
                        (ServerConfiguration)GetObject(typeof(ServerConfiguration), node);

                    SecuredApplication.FromListOfBaseAddresses(configuration, application.BaseAddresses);
                    configuration.SecurityPolicies =
                        SecuredApplication.FromListOfSecurityProfiles(application.SecurityProfiles);

                    node.InnerXml = SetObject(typeof(ServerConfiguration), configuration);
                    continue;
                }
                else if (node.Name == "DiscoveryServerConfiguration" && node.NamespaceURI == Namespaces.OpcUaConfig)
                {
                    DiscoveryServerConfiguration configuration =
                        (DiscoveryServerConfiguration)GetObject(typeof(DiscoveryServerConfiguration), node);

                    SecuredApplication.FromListOfBaseAddresses(configuration, application.BaseAddresses);
                    configuration.SecurityPolicies =
                        SecuredApplication.FromListOfSecurityProfiles(application.SecurityProfiles);

                    node.InnerXml = SetObject(typeof(DiscoveryServerConfiguration), configuration);
                    continue;
                }
            }
        }
예제 #59
0
 public Server(ServerConfiguration serverConfiguration, ClientConnectionBuilder clientConnectionBuilder)
     : this(serverConfiguration)
 {
     this.clientConnectionBuilder = clientConnectionBuilder;
 }
예제 #60
0
 public UserApi(ServerConfiguration config, IKernel kernel)
 {
     this.Config = config;
     this.Kernel = kernel;
 }