示例#1
0
        public void Start(string serverName)
        {
            if (_servers.ContainsKey(serverName))
            {
                throw new ArgumentException(string.Format("{0} has already been started", serverName));
            }

            var config = ConfigurationManager.GetSection("royNet") as RoyNetConfiguration;
            Debug.Assert(config != null, "royNet Config node is undefined");
            var serverConfig = config.Servers.OfType<IServerConfig>().FirstOrDefault(sc => sc.Name == serverName);
            if (serverConfig == null)
            {
                throw new ArgumentException(string.Format("can't find the server named:{0}", serverName));
            }

            var configSection = new ServerConfig(serverConfig);
            var type = config.ServerTypes[configSection.ServerTypeName].TypeProvider;

            AppDomain newDomain = AppDomain.CreateDomain(configSection.Name);
            var assembly = newDomain.Load(type.AssemblyName);
            var obj = newDomain.CreateInstanceAndUnwrap(type.AssemblyName, type.ClassFullName,
                    true,
                    BindingFlags.CreateInstance,
                    null,
                    null,
                    null,
                    new object[0]);
            var instance = obj as ServerBase;
            if (instance != null)
            {
                instance.Configure(configSection);
                _servers.Add(instance.Name, new AppDomainServer(newDomain, instance));
                instance.Startup();
            }
        }
示例#2
0
        public void Ignition()
        {
            var config = ConfigurationManager.GetSection("royNet") as RoyNetConfiguration;
            Debug.Assert(config != null, "royNet Config node is undefined");
            foreach (IServerConfig serverConfig in config.Servers)
            {
                var configSection = new ServerConfig(serverConfig);
                var type = config.ServerTypes[configSection.ServerTypeName].TypeProvider;

                AppDomain newDomain = AppDomain.CreateDomain(configSection.Name);
                var assembly = newDomain.Load(type.AssemblyName);
                var obj = newDomain.CreateInstanceAndUnwrap(type.AssemblyName, type.ClassFullName,
                        true,
                        BindingFlags.CreateInstance,
                        null,
                        null,
                        null,
                        new object[0]);
                var instance = obj as ServerBase;
                if (instance != null)
                {
                    instance.Configure(configSection);
                    _servers.Add(instance.Name, new AppDomainServer(newDomain, instance));
                }
            }
            //初始化完成
            //开始启动
            foreach (ServerBase serverBase in Servers)
            {
                serverBase.Startup();
            }
        }
 public void Init()
 {
     var serverConfig = new ServerConfig
     {
         ServerType = ServerType.AsyncServer
     };
     serverRunner = ServerRunners.CreateStarted(serverConfig);
 }
示例#4
0
 public void Init()
 {
     var serverConfig = new ServerConfig
     {
         ServerType = ServerType.ASYNC_SERVER
     };
     serverRunner = ServerRunners.CreateStarted(serverConfig);
 }
示例#5
0
 // Post先設定読み込み. 基本的にPostごとに読み込み.
 public static ServerConfig loadServerConfig()
 {
     var r = new ServerConfig();
     var yn = YamlNode.FromYamlFile(serverConfFile).topMap();
     r.post_url = yn["post_url"].getString();
     r.key = yn["key"].getByteFromBase64();
     r.iv = yn["IV"].getByteFromBase64();
     return r;
 }
 public void Init()
 {
     var serverConfig = new ServerConfig
     {
         ServerType = ServerType.ASYNC_SERVER,
         PayloadConfig = new PayloadConfig
         {
             SimpleParams = new SimpleProtoParams
             {
                 RespSize = 100
             }
         }
     };
     serverRunner = ServerRunners.CreateStarted(serverConfig);
 }
示例#7
0
        /// <summary>
        /// Creates a started server runner.
        /// </summary>
        public static IServerRunner CreateStarted(ServerConfig config)
        {
            Grpc.Core.Utils.Preconditions.CheckArgument(config.ServerType == ServerType.ASYNC_SERVER);
            var credentials = config.SecurityParams != null ? TestCredentials.CreateSslServerCredentials() : ServerCredentials.Insecure;

            // TODO: qps_driver needs to setup payload properly...
            int responseSize = config.PayloadConfig != null ? config.PayloadConfig.SimpleParams.RespSize : 0;
            var server = new Server
            {
                Services = { BenchmarkService.BindService(new BenchmarkServiceImpl(responseSize)) },
                Ports = { new ServerPort(config.Host, config.Port, credentials) }
            };

            server.Start();
            return new ServerRunnerImpl(server);
        }
示例#8
0
        /// <summary>
        /// Creates a started server runner.
        /// </summary>
        public static IServerRunner CreateStarted(ServerConfig config)
        {
            Logger.Debug("ServerConfig: {0}", config);
            var credentials = config.SecurityParams != null ? TestCredentials.CreateSslServerCredentials() : ServerCredentials.Insecure;

            if (config.AsyncServerThreads != 0)
            {
                Logger.Warning("ServerConfig.AsyncServerThreads is not supported for C#. Ignoring the value");
            }
            if (config.CoreLimit != 0)
            {
                Logger.Warning("ServerConfig.CoreLimit is not supported for C#. Ignoring the value");
            }
            if (config.CoreList.Count > 0)
            {
                Logger.Warning("ServerConfig.CoreList is not supported for C#. Ignoring the value");
            }

            ServerServiceDefinition service = null;
            if (config.ServerType == ServerType.ASYNC_SERVER)
            {
                GrpcPreconditions.CheckArgument(config.PayloadConfig == null,
                    "ServerConfig.PayloadConfig shouldn't be set for BenchmarkService based server.");    
                service = BenchmarkService.BindService(new BenchmarkServiceImpl());
            }
            else if (config.ServerType == ServerType.ASYNC_GENERIC_SERVER)
            {
                var genericService = new GenericServiceImpl(config.PayloadConfig.BytebufParams.RespSize);
                service = GenericService.BindHandler(genericService.StreamingCall);
            }
            else
            {
                throw new ArgumentException("Unsupported ServerType");
            }

            var server = new Server
            {
                Services = { service },
                Ports = { new ServerPort("[::]", config.Port, credentials) }
            };

            server.Start();
            return new ServerRunnerImpl(server);
        }
示例#9
0
 private void btnSure_Click(object sender, EventArgs e)
 {
     //�������еļ�����
     //�������õ����л�
     //�����Ĭ�Ͽ��������
     string port = this.txtPort.Text.Trim();
     try
     {
         int tmp = Convert.ToInt32(port);
         ServerConfig config = new ServerConfig();
         config.Port = tmp;
         config.Ip = this.txtIp.Text.Trim();
         config.DefaultOpen = this.cbDefaultStart.Checked;
         ServerConfig.SaveConfig(config);
         MessageBoxHelper.Show("����ɹ�");
     }
     catch (Exception ex)
     {
         MessageBoxHelper.Show("�˿ڱ��������֣�");
     }
 }
示例#10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            var env = app.ApplicationServices.GetService<IHostingEnvironment>();
            var fileStorageFolder = env.WebRootPath;
            var metaStorageFolder = fileStorageFolder;
            var config = new ServerConfig(fileStorageFolder, metaStorageFolder, new Uri("http://localhost:38420"));

            app
                .UseDeveloperExceptionPage()
                .UseStaticFiles(new StaticFileOptions
                {
                    DefaultContentType = "application/octet-stream",
                    ServeUnknownFileTypes = true
                })
                .UseFileserver(config)
                .Run(context =>
                {
                    // Strange request, let's just say "BAD REQUEST"
                    // Instead, you could start your ASP.NET MVC handler here for instance  
                    context.Response.StatusCode = 400;
                    return Task.FromResult(0);
                });
        }
示例#11
0
 /// <summary>
 /// Some detail of the server configuration has changed
 /// </summary>
 /// <param name="serverConfig"></param>
 public virtual void ServerConfig(ServerConfig serverConfig)
 {
 }
示例#12
0
 public WorldPersistence(ServerProtobufSerializer serializer, ServerConfig config)
 {
     this.serializer = serializer;
     this.config     = config;
 }
示例#13
0
        private void LoadInit()
        {
            var deviceJson  = _settings.GetValue("device.id", "");
            var hapiCentral = _settings.GetValue("hapi.central", "");
            var hapiLocal   = _settings.GetValue("hapi.local", "");

            if (null == Device && !string.IsNullOrWhiteSpace(deviceJson))
            {
                Device = JsonConvert.DeserializeObject <Device>(deviceJson);
            }
            else
            {
                Device = _deviceSetupService.GetDefault(Serial);
                if (null == Device)
                {
                    Device = new Device();
                }
                else
                {
                    var json = JsonConvert.SerializeObject(Device);
                    _settings.AddOrUpdateValue("device.id", json);
                }
            }
            Code = Device.Code;


            if (null == Central && !string.IsNullOrWhiteSpace(hapiCentral))
            {
                Central = JsonConvert.DeserializeObject <ServerConfig>(hapiCentral);
            }
            else
            {
                Central = _deviceSetupService.GetCentral();
                if (null == Central)
                {
                    Central = new ServerConfig();
                }
                else
                {
                    var json = JsonConvert.SerializeObject(Central);
                    _settings.AddOrUpdateValue("hapi.central", json);
                }
            }
            CentralAddress = Central.Address;
            CentralName    = Central.Name;

            if (null == Local && !string.IsNullOrWhiteSpace(hapiLocal))
            {
                Local = JsonConvert.DeserializeObject <ServerConfig>(hapiLocal);
            }
            else
            {
                Local = _deviceSetupService.GetLocal();
                if (null == Local)
                {
                    Local = new ServerConfig();
                }
                else
                {
                    var json = JsonConvert.SerializeObject(Local);
                    _settings.AddOrUpdateValue("hapi.local", json);
                }
            }
            LocalAddress = Local.Address;
            LocalName    = Local.Name;
        }
示例#14
0
        /// <summary>
        /// Creates a started server runner.
        /// </summary>
        public static IServerRunner CreateStarted(ServerConfig config, ILogger logger)
        {
            logger.LogInformation("ServerConfig: {0}", config);

            var hostBuilder = Host.CreateDefaultBuilder();

            if (config.AsyncServerThreads != 0)
            {
                logger.LogWarning("ServerConfig.AsyncServerThreads is not supported for C#. Ignoring the value");
            }
            if (config.CoreLimit != 0)
            {
                logger.LogWarning("ServerConfig.CoreLimit is not supported for C#. Ignoring the value");
            }
            if (config.CoreList.Count > 0)
            {
                logger.LogWarning("ServerConfig.CoreList is not supported for C#. Ignoring the value");
            }
            if (config.ChannelArgs.Count > 0)
            {
                logger.LogWarning("ServerConfig.ChannelArgs is not supported for C#. Ignoring the value");
            }

            int port = config.Port;

            if (port == 0)
            {
                // TODO(jtattermusch): add support for port autoselection
                port = 50055;
                logger.LogWarning("Grpc.AspNetCore server doesn't support autoselecting of listening port. Setting port explictly to " + port);
            }

            hostBuilder.ConfigureWebHostDefaults(webHostBuilder =>
            {
                webHostBuilder.ConfigureKestrel((context, options) =>
                {
                    options.ListenAnyIP(port, listenOptions =>
                    {
                        // TODO(jtattermusch): use TLS if config.SecurityParams != null
                        listenOptions.Protocols = HttpProtocols.Http2;
                    });
                });

                if (config.ServerType == ServerType.AsyncServer)
                {
                    GrpcPreconditions.CheckArgument(config.PayloadConfig == null,
                                                    "ServerConfig.PayloadConfig shouldn't be set for BenchmarkService based server.");
                    webHostBuilder.UseStartup <BenchmarkServiceStartup>();
                }
                else if (config.ServerType == ServerType.AsyncGenericServer)
                {
                    var genericService = new GenericServiceImpl(config.PayloadConfig.BytebufParams.RespSize);
                    // TODO(jtattermusch): use startup with given generic service
                    throw new ArgumentException("Generice service is not yet implemented.");
                }
                else
                {
                    throw new ArgumentException("Unsupported ServerType");
                }
            });

            // Don't log requests handled by the benchmarking service
            hostBuilder.ConfigureLogging(logging => logging.SetMinimumLevel(LogLevel.Warning));

            var webHost = hostBuilder.Build();

            webHost.Start();
            return(new ServerRunnerImpl(webHost, logger, port));
        }
示例#15
0
        public override Result Execute(IOfferRemoteOperations remote, ServerConfig server, ConDepSettings settings, CancellationToken token)
        {
            var fullPath = _root + @"\" + _key;

            return(remote.Execute.PowerShell($@"New-ItemProperty -Path ""Microsoft.PowerShell.Core\Registry::{fullPath}"" -Name ""{_valueName}"" -PropertyType {_valueKind} -Value ""{_valueData}"" -force").Result);
        }
示例#16
0
 public WebService(ServerConfig config)
 {
     Config = config;
 }
        private void CopyFile(string srcPath, ServerConfig server, ConDepSettings settings)
        {
            var dstPath = Path.Combine(server.GetServerInfo().TempFolderDos, Path.GetFileName(srcPath));

            CopyFile(srcPath, dstPath, server, settings);
        }
示例#18
0
        // public static IMqttClient mqttClient = new MqttFactory().CreateMqttClient();
        public static void Main(string[] args)
        {
            User u = new User()
            {
                UserName = "******",
                Age      = 14
            };

            TUser user = Map <User, TUser>(u);

            ServerConfig payconfig = Config.Bind <ServerConfig>("thrift.json", "Pay");

            //string s = Redis.RedisHelper.Get("2A6B5EDF418F2046DE43F79E0CCE6773");

            // string temp = xElement.ToString();
            //int id = 0;
            //TServerSocket serverTransport = new TServerSocket(8090);

            //TBinaryProtocol.Factory factory = new TBinaryProtocol.Factory();

            //TServerEventHandler handler = new ServerEventHandler();



            //TServer server = new TThreadPoolServer(entity, serverTransport, new TTransportFactory(), factory);
            //server.setEventHandler(handler);

            //Console.WriteLine(string.Format("服务端正在监听{0}端口", serverPort));

            //server.Serve();


            //var response = client.Index(tweet, idx => idx.Index("mytweetindex"));
            //ElasticsearchHelper.Add(tweet);


            Tweet tweet = new Tweet
            {
                Id      = 33333,
                User    = "******",
                Message = "Trying out NEST, so far so good?"
            };
            //ElasticsearchHelper.Add(tweet);

            // Tweet product33 = ElasticsearchHelper.GetByID<Tweet>(33333);

            var response = ElasticsearchHelper.Query <ELog>(fs => fs.From(0).Size(100).Query(q =>
                                                                                             q.Bool(b => b.Filter(f => f.TermRange(r => r.Field(t => t.ExecTime).LessThan("2019-03-22")))))
                                                            );


            SearchRequest s = new SearchRequest()
            {
                From  = 0,
                Size  = 100,
                Query = new BoolQuery()
                {
                    Filter = new List <QueryContainer>()
                    {
                        new TermRangeQuery()
                        {
                            Field = "ExecTime", LessThan = "2019-03-22"
                        }
                    }
                }
            };
            var response3 = ElasticsearchHelper.Query <ELog>(s);
            //product33.User = "******";

            //ElasticsearchHelper.Update<Tweet>(product33);


            ProductIndex product = ElasticsearchHelper.GetByID <ProductIndex>(324);

            //var options = new MqttClientOptions
            //{
            //    ChannelOptions = new MqttClientWebSocketOptions()
            //    {
            //        Uri = "ws://jenkins.miaogo.com.cn:8083/mqtt",
            //        TlsOptions = new MqttClientTlsOptions
            //        {
            //            UseTls = false,
            //            IgnoreCertificateChainErrors = true,
            //            IgnoreCertificateRevocationErrors = true,
            //            AllowUntrustedCertificates = false
            //        }
            //    }
            //};
            //options.CleanSession = true;
            //options.KeepAlivePeriod = TimeSpan.FromSeconds(double.Parse("60"));

            //mqttClient.Connected += MqttClient_Connected;
            //mqttClient.Disconnected += MqttClient_Disconnected;
            //mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;

            //MqttClientConnectResult result = mqttClient.ConnectAsync(options).Result;

            //MqttApplicationMessage appMsg = new MqttApplicationMessage()
            //{
            //    Topic = "testtopic",
            //    Payload = Encoding.UTF8.GetBytes("Hello, World!"),
            //    QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
            //    Retain = false
            //};

            //Task task = MqttHelp<MqttClientTcpOptions>.Subscribe<Test>("topic1", t =>
            //{
            //    int i = t.Type;
            //});

            //Task tasks = MqttHelp<MqttClientTcpOptions>.Publish<Test>("topic1", new Test() { Type = 3232323 });

            //System.Console.ReadLine();
            //MqttClientOptions options = new MqttClientOptions
            //{
            //    ChannelOptions = new MqttClientTcpOptions()
            //    {
            //        Server = "192.168.3.166",
            //        Port = 1883,
            //    },
            //    KeepAlivePeriod = TimeSpan.FromSeconds(double.Parse("100")),
            //    ClientId = "zbl",
            //    CleanSession = true
            //};
            //mqttClient = new MqttFactory().CreateMqttClient();

            //MqttClientConnectResult result = mqttClient.ConnectAsync(options).Result;

            //mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; ;
            //mqttClient.Connected += MqttClient_Connected;
            //mqttClient.Disconnected += MqttClient_Disconnected;

            //var s = mqttClient.SubscribeAsync(new List<TopicFilter> { new TopicFilter("bzs", MqttQualityOfServiceLevel.AtMostOnce) }).Result;


            //MqttApplicationMessage appMsg = new MqttApplicationMessage()
            //{
            //    Topic = "bzs",
            //    Payload = Encoding.UTF8.GetBytes("Hello, World!"),
            //    QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
            //    Retain = false
            //};

            //var r = mqttClient.PublishAsync(appMsg);

            //"", Encoding.UTF8.GetBytes("消息内容"), MqttQualityOfServiceLevel.AtMostOnce, false

            //var list = DP.Create<ProductShelfRecord>().ToList().AsList();

            //RabbitMQService.QueueDelete("1030150513141879784");
            //long total = 0;
            //var sddd = DP.GetPage<Product>(1, 15, out total, "SELECT SaleTime ,SUM(Price) as Price from (SELECT date_format(SaleTime,'%Y-%m-%d') as SaleTime , Price ,SupplierCode from Product where StatusFlag=3 and DeleteFlag=0 and  SupplierCode='1040723159508193280' ) as T_Product GROUP BY SaleTime");


            //string url = "https://api.weixin.qq.com/sns/oauth2/access_token";
            //access_token token = new access_token()
            //{
            //    appid = WxConfig.appid,
            //    secret = WxConfig.secret,
            //    code = "021tasN40IlceK1UbAL40FBiN40tasNN",
            //};

            //RestClient client = new RestClient(url);
            //IRestRequest request = new RestRequest(Method.GET);
            //request.AddParameter("appid", token.appid);
            //request.AddParameter("secret", token.secret);
            //request.AddParameter("code", token.code);
            //request.AddParameter("grant_type", token.grant_type);
            ////
            //IRestResponse<access_tokenresult> response = client.Execute<access_tokenresult>(request);



            //int count = DP.DeleteEntity<RelationProductCategory>(p => p.Type == 2 && p.Code == "00001");

            //string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

            //XDocument document = new XDocument();

            //XElement root = new XElement("xml");

            //root.Add(new XElement("appid", 1));
            //root.Add(new XElement("mch_id", 1));
            //root.Add(new XElement("device_info", 1));
            //root.Add(new XElement("nonce_str", 1));
            //root.Add(new XElement("sign_type", 1));
            //root.Add(new XElement("body", 1));
            //root.Add(new XElement("attach", 1));
            //root.Add(new XElement("out_trade_no", 1));
            //root.Add(new XElement("fee_type", 1));
            //root.Add(new XElement("total_fee", 1));
            //root.Add(new XElement("spbill_create_ip", 1));
            //root.Add(new XElement("time_start", 1));
            //root.Add(new XElement("time_expire", 1));
            //root.Add(new XElement("goods_tag", 1));
            //root.Add(new XElement("notify_url", 1));
            //root.Add(new XElement("trade_type", 1));
            //root.Add(new XElement("limit_pay", 1));
            //root.Add(new XElement("scene_info", 1));
            //document.Add(root);
            //string xml = document.ToString();

            //byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);

            //System.Net.HttpWebResponse response = null;

            //byte[] type = HttpHelper.SendRequestData(url, data, ref response);

            //string t = System.Text.Encoding.UTF8.GetString(type);

            //CabinetHelp.SendMessage(101, new Cabinet.Entity.CabinetParam()
            //{
            //    Queue = "1043041192733970432",
            //    Message= "你好",
            //    Action = new List<object>() { "msg"}

            //});

            //RabbitMQService.Send("1043041192733970432", "33333");
            //RabbitMQService.Send("1043041192733970432", "33444");
            //RabbitMQService.Send("1043041192733970432", "5555");



            //ProductShelfItem shelfItem = new ProductShelfItem()
            //{
            //    ShelfCode = "3333",
            //    ShelfType = 1,
            //    ProductName = "",
            //    Price = 0,
            //    ProCount = 2,
            //    CategoryCode = "",
            //    RFIDs = "121212",
            //    ICO = "",
            //    ProductCode = "",
            //    Specifications = ""
            //};
            //transaction.AddTs(shelfItem);
            //string msg = string.Empty;

            //int f = DP.SaveEntity(shelfItem);
            //var config = new ConfigurationBuilder()
            //    .SetBasePath(Directory.GetCurrentDirectory())
            //    .AddJsonFile("hosting.json", optional: true)
            //    .Build();

            //var host = new WebHostBuilder()
            //    .UseConfiguration(config)
            //    .UseKestrel()
            //    .UseStartup<Startup>()
            //    .Build();
            //host.Run();


            //Config.Bind<CameraConfig>("Camera.json");

            ////CameraHelp help = new CameraHelp();

            //var result = CameraHelp.Start("C70425683");
        }
示例#19
0
 public DownloadController(IIndexerManagerService i, Logger l, IProtectionService ps, ServerConfig sConfig)
 {
     serverConfig      = sConfig;
     logger            = l;
     indexerService    = i;
     protectionService = ps;
 }
示例#20
0
 /// <summary>
 /// Ctor
 /// </summary>
 /// <param name="usermanager">User Manager</param>
 /// <param name="signin">Sign in manager</param>
 /// <param name="conf">Server Config</param>
 public AccountHelper(UserManager <ChandlerUser> usermanager, SignInManager <ChandlerUser> signin, ServerConfig conf)
 {
     this.UserManager   = usermanager;
     this.SignInManager = signin;
     this.Config        = conf;
 }
示例#21
0
 public IndexerManagerService(IIndexerConfigurationService config, IProtectionService protectionService, WebClient webClient, Logger l, ICacheService cache, IProcessService processService, IConfigurationService globalConfigService, ServerConfig serverConfig)
 {
     configService            = config;
     this.protectionService   = protectionService;
     this.webClient           = webClient;
     this.processService      = processService;
     this.globalConfigService = globalConfigService;
     this.serverConfig        = serverConfig;
     logger       = l;
     cacheService = cache;
 }
示例#22
0
        private async Task Client_MessageReceived(SocketMessage s)
        {
            var msg = s as SocketUserMessage;

            if (msg == null)
            {
                return;
            }
            var               context     = new SocketCommandContext(client, msg);
            ulong             guildID     = 0;
            SocketTextChannel generalchan = null;
            ServerConfig      config      = new ServerConfig();
            UserAccount       userAccount = null;

            Antispam.SpamAccount spamAccount = null;
            //Load Accounts
            UserAccounts.LoadUserAccts();
            SteamAccounts.LoadUserAccts();
            ServerConfigs.LoadServerConfigs();
            NanoPool.LoadAccounts();
            MemeLoader.LoadMemes();
            Antispam.LoadSpamAccount();
            GiveawayManager.LoadGiveaways();

            //----------Do Tests--------
            //if (!context.IsPrivate) await RepeatingTimer.UpdateAuditLog(context.Guild);]

            //Mute Check
            userAccount = UserAccounts.GetAccount(context.User);
            spamAccount = Antispam.GetAccount(context.User);

            if (oldMessage.Count > 0)
            {
                if (oldMessage[oldMessage.Count - 1].Content == s.Content)
                {
                    for (int i = 0; i < oldMessage.Count; i++)
                    {
                        if (oldMessage[i].Content == s.Content && oldMessage[i].Embeds.Count == 0)
                        {
                            msgCount++;
                            if (msgCount >= 5)
                            {
                                try
                                {
                                    await s.DeleteAsync();
                                }
                                catch (Exception ex)
                                {
                                    string exMsg = DateTime.Now + " | EXCEPTION: " + ex.Message;
                                    Console.WriteLine(exMsg);
                                    Log.LogException(exMsg);
                                }
                                string mes = DateTime.Now + " | " + context.User + " suspected raid account. Ban request....";
                                Console.WriteLine(mes);
                            }
                        }
                    }
                }
            }
            if (oldMessage.Count >= 20)
            {
                oldMessage.RemoveAt(0);
            }
            oldMessage.Add(s);
            if (!context.IsPrivate)
            {
                config = ServerConfigs.GetConfig(context.Guild);
                RepeatingTimer.channel = (SocketTextChannel)context.Channel;
                if (!updated.Contains(context.Guild))
                {
                    ServerConfigs.UpdateServerConfig(context.Guild, config);
                    updated.Add(context.Guild);
                }

                if (config.RequiresVerification)
                {
                    if (GetTChannel(context.Guild.TextChannels, "verification") == null)
                    {
                        await context.Guild.CreateTextChannelAsync("verification");
                    }
                }

                if (userAccount.IsMuted)
                {
                    await context.Message.DeleteAsync();

                    return;
                }

                //Get Guild ID
                guildID = context.Guild.Id;
                DataStorage.AddPairToStorage(context.Guild.Name + "ID", guildID.ToString());
                generalchan = GetTChannel(context.Guild.TextChannels, "general");
            }
            //Bot Check
            if (!context.User.IsBot)
            {
                if (!context.IsPrivate)
                {
                    if (!config.AllowAdvertising)
                    {
                        if (context.Message.Content.Contains(context.Guild.EveryoneRole.ToString()) &&
                            context.Message.Content.Contains("https://discord.gg/"))
                        {
                            await context.Message.DeleteAsync();

                            await context.Channel.SendMessageAsync(context.User.Mention + " Advertising discord servers is not allowed here.");

                            return;
                        }
                    }
                    if (config.BlockMentionEveryone)
                    {
                        if (context.Message.Content.Contains(context.Guild.EveryoneRole.ToString()))
                        {
                            await context.Message.DeleteAsync();

                            await context.Channel.SendMessageAsync(context.User.Mention + " mentioning everyone is prohibited!");

                            return;
                        }
                    }
                    //Check for raid from multiple account spam
                    //Add when you wake up...
                    spamAccount.LastMessages.Add(DateTime.Now);
                    if (spamAccount.BanAmount > 0)
                    {
                        if (Math.Abs(spamAccount.LastBan.Subtract(DateTime.Now).Days) > 10)          //Reset ban amount after 10 days
                        {
                            spamAccount.BanAmount = 0;
                        }
                    }
                    if (spamAccount.LastMessages.Count > 3)
                    {
                        //Get last 4 messages sent
                        DateTime d1 = spamAccount.LastMessages[0];
                        DateTime d2 = spamAccount.LastMessages[1];
                        DateTime d3 = spamAccount.LastMessages[2];
                        DateTime d4 = spamAccount.LastMessages[3];
                        TimeSpan t1 = new TimeSpan();
                        TimeSpan t2 = new TimeSpan();
                        TimeSpan t3 = new TimeSpan();
                        //Subtract them from each other by Milliseconds
                        t1 = d1.Subtract(d2);
                        t2 = d2.Subtract(d3);
                        t3 = d3.Subtract(d4);
                        double mil1 = Math.Abs(t1.TotalMilliseconds);
                        double mil2 = Math.Abs(t2.TotalMilliseconds);
                        double mil3 = Math.Abs(t3.TotalMilliseconds);
                        //Console.WriteLine(mil1 + "\n" + mil2 + "\n" + mil3);

                        //If all past 4 messages are within spam threshold then its considerd spam
                        if (mil1 <= Antispam.millisecondThreshold &&    //Threshold is 5 seconds
                            mil2 <= Antispam.millisecondThreshold &&
                            mil3 <= Antispam.millisecondThreshold)
                        {
                            spamAccount.BanAmount++;
                            string   message = "";
                            DateTime banTime = DateTime.Now;
                            if (spamAccount.BanAmount < config.AntiSpamWarn)
                            {
                                message = "\nPlease stop spamming you have been muted for 30 seconds!";
                                banTime = DateTime.Now.AddSeconds(30);
                            }
                            if (spamAccount.BanAmount >= config.AntiSpamWarn && spamAccount.BanAmount < config.AntiSpamThreshold)
                            {
                                int time = (int)config.AntiSpamTime;
                                message = "\nYou have been muted for " + time + " Minutes! " + context.Guild.Owner.Mention;
                                banTime = DateTime.Now.AddMinutes(time);
                            }
                            if (spamAccount.BanAmount > config.AntiSpamThreshold)
                            {
                                SocketGuildUser user = (SocketGuildUser)context.User;
                                await user.BanAsync(1, "Spamming");

                                await context.Channel.SendMessageAsync(context.User.Username + " was banned for 1 day for spamming!");

                                return;
                            }
                            spamAccount.BanTime = banTime;
                            spamAccount.LastBan = DateTime.Now;
                            await context.Channel.SendMessageAsync(context.User.Mention + message);

                            spamAccount.LastMessages.Clear();
                            Antispam.UpdateAccount(context.User, spamAccount);
                            Antispam.SaveAccounts();
                            userAccount.IsMuted = true;
                            UserAccounts.SaveAccounts();
                            return;
                        }
                        spamAccount.LastMessages.Clear();
                    }
                    Antispam.SaveAccounts();
                    if (config.EnableServerStats)
                    {
                        //If stat channels dont exist
                        await CreateStatChannels(context.Guild);
                        await updMemberChan(context.Guild);     //Update Stat channels
                    }

                    if (config.EnableLevelSystem)
                    {
                        uint oldlvl = userAccount.LevelNumber;
                        userAccount.XP     += 10;               //Xp gain
                        userAccount.Points += 10;               //Pointshop

                        if (oldlvl != userAccount.LevelNumber)
                        {
                            for (int i = 0; i < LevelingSytem.levelUp.Length; i++)
                            {
                                if (userAccount.LevelNumber == LevelingSytem.levelUp[i])
                                {
                                    IGuildUser user = (IGuildUser)context.User;

                                    IRole[] r       = user.Guild.Roles.ToArray();
                                    IRole   addrole = null;
                                    for (int i2 = 0; i2 < r.Length; i2++)
                                    {
                                        if (r[i2].Name.ToLower() == LevelingSytem.upgradeRoles[i].ToLower())
                                        {
                                            addrole = r[i2];
                                            break;
                                        }
                                    }
                                    if (addrole != null)
                                    {
                                        ulong?roleID = null;
                                        foreach (ulong r2 in user.RoleIds)
                                        {
                                            if (r2 == addrole.Id)
                                            {
                                                roleID = r2;
                                                break;
                                            }
                                        }//end foreach loop
                                        if (roleID == null)
                                        {
                                            await user.AddRoleAsync(addrole);

                                            await context.Channel.SendMessageAsync("__" + user.Username + "__ earned role **" + addrole + "**!", false);
                                        } //end if roleID
                                    }     //end if addrole != null
                                }         // end if level up
                            }             //end levels loop
                            string message = "Congrats " + context.User.Mention + ", You just advanced to **Level " + userAccount.LevelNumber + "!**";

                            await context.Channel.SendMessageAsync(message);
                        } //end level check
                    }     //end level system check
                }         //end if EnableLevelSystem
                UserAccounts.SaveAccounts();
            }             //end isPrivate check
            int argPos = 0;

            if (msg.HasStringPrefix("" + config.Prefix, ref argPos) ||
                msg.HasMentionPrefix(client.CurrentUser, ref argPos))
            {
                if (context.IsPrivate)
                {
                    config = new ServerConfig();
                }
                else
                {
                    config = ServerConfigs.GetConfig(context.Guild);
                }
                IResult result = null;
                result = await service.ExecuteAsync(context, argPos, null);

                if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
                {
                    bool errorCheck = true;
                    if (context.Message.Content.Contains("creatememe") && context.Message.Attachments.Count > 0)
                    {
                        if (result.ErrorReason.Contains("User not found"))
                        {
                            errorCheck = false;
                        }
                    }
                    if (errorCheck)
                    {
                        string message = "Error when running this command\n**" + result.ErrorReason + "**\n\nView console for more info";
                        var    embed   = new EmbedBuilder();
                        embed.WithTitle("Command Error");
                        embed.WithDescription(message);
                        embed.WithColor(config.EmbedColorRed, config.EmbedColorGreen, config.EmbedColorBlue);
                        if (config.FooterText != "")
                        {
                            embed.WithFooter(config.FooterText);
                        }
                        if (config.TimeStamp)
                        {
                            embed.WithCurrentTimestamp();
                        }

                        await context.Channel.SendMessageAsync("", false, embed.Build());

                        Console.WriteLine(result.ErrorReason);
                        Console.WriteLine(result.Error);
                    }
                }
            }
            GetAllVoiceChannels(context.Guild.VoiceChannels);
            GetAllTextChannels(context.Guild.TextChannels);
        }
        public void Load()
        {
            //
            // Check if instance file exists
            //
            if (!File.Exists(activeConfigFileName))
            {
                throw (new ConfigurationErrorsException(
                           string.Format(
                               "The Instance Repository File is missing, please check the configuration. File = \"{0}\"", activeConfigFileName)));
            }
            else
            {
                // Read content
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(ServerConfig));

                StreamReader reader = null;

                try
                {
                    try
                    {
                        reader = new StreamReader(activeConfigFileName);
                    }
                    catch (Exception ex)
                    {
                        throw (new ConfigurationErrorsException(
                                   string.Format(
                                       "Problems reading the Instance Repository File, file = \"{0}\"", activeConfigFileName), ex));
                    }

                    // Validate the contents
                    string       schemaFileName = string.Format("{0}.xsd.ServerConfig.xsd", defaultNameSpace);
                    StreamReader schemaReader;

                    try
                    {
                        schemaReader = new StreamReader(Assembly.GetCallingAssembly().GetManifestResourceStream(schemaFileName));
                    }
                    catch (Exception ex)
                    {
                        throw (new ConfigurationErrorsException(
                                   string.Format(
                                       "Failed to load embedded schema file, cannot validate instance repository file. Schema file = \"{0}\"", schemaFileName), ex));
                    }

                    // Validate file, get 10 errors max
                    XmlValidator xmlValidator = new XmlValidator();
                    string       errors       = xmlValidator.ValidateStream(reader.BaseStream, schemaReader.BaseStream, 10);

                    if (errors != "")
                    {
                        throw (new ConfigurationErrorsException(
                                   string.Format(
                                       "The instance repository file contains syntax errors, file = \"{0}\"\n{1}", activeConfigFileName, errors)));
                    }

                    try
                    {
                        reader.BaseStream.Position = 0;
                        ServerConfig = xmlSerializer.Deserialize(reader) as ServerConfig;

                        #region CompensateBadConfig
                        // make sure refreshrate is always specified
                        if (!ServerConfig.RefreshRateSpecified)
                        {
                            ServerConfig.RefreshRate = ServerConfigRefreshRate.Normal;
                        }

                        // Make sure at least one Broadcast entry exists
                        if ((ServerConfig.Broadcast == null) || (ServerConfig.Broadcast.Length == 0))
                        {
                            ServerConfig.Broadcast            = new BroadcastType[1];
                            ServerConfig.Broadcast[0].Ip      = "239.255.255.255";
                            ServerConfig.Broadcast[0].Port    = 11000;
                            ServerConfig.Broadcast[0].Timeout = 5000;
                        }
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        throw (new ConfigurationErrorsException(
                                   string.Format(
                                       "Problems reading the instance repository file, file = \"{0}\"", activeConfigFileName), ex));
                    }
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
        }
示例#24
0
 private void ConfigureListeners(ServerConfig serverConfig)
 {
     Listeners = serverConfig
                 .Listeners
                 .Select(l => new Listener(l)).ToArray();
 }
        public override void ServerConfig(ServerConfig serverConfig)
        {
            base.ServerConfig(serverConfig);

            if (serverConfigDelegate != null) serverConfigDelegate(this, serverConfig);
        }
示例#26
0
 public TCPServer(ServerConfig config) : base(config)
 {
     _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 }
示例#27
0
        public override void ServerConfig(ServerConfig serverConfig)
        {
            base.ServerConfig(serverConfig);

            Console.WriteLine(serverConfig.welcome_text);
        }
示例#28
0
        public NitroxServer(PacketHandler packetHandler, PlayerManager playerManager, EntitySimulation entitySimulation, ServerConfig serverConfig)
        {
            this.packetHandler    = packetHandler;
            this.playerManager    = playerManager;
            this.entitySimulation = entitySimulation;

            portNumber = serverConfig.ServerPort;
            maxConn    = serverConfig.MaxConnections;
        }
示例#29
0
 void InitServer()
 {
     server=new WebSocketServer();
     var config=new ServerConfig(){
         Ip="Any",
         Port=port,
         KeepAliveInterval=15,
         MaxRequestLength=1048576
     };
     server.NewMessageReceived+=OnNewMessageReceived;
     server.SessionClosed+=OnSessionClosed;
     server.Setup(config);
 }
示例#30
0
        /// <summary>
        /// 指定配置文件以初始化新实例
        /// </summary>
        /// <param name="configName"></param>
        public QueueServerPool(string configName)
        {
            if (string.IsNullOrEmpty(configName) == true)
            {
                throw new ArgumentNullException("configName");
            }
            //
            string topic         = "";
            ushort commitTimeout = 30;
            ushort timeout       = 5;

            //
            PoolMember[] poolMembers    = null;
            int          memberPoolSize = 800;
            int          hash           = 0;
            //
            var configuration = ServerConfig.GetConfiguration(configName);

            if (configuration.FileExist == true)
            {
                topic          = configuration.GetAttr("topic");
                commitTimeout  = configuration.GetAttrAsUInt16("commitTimeout", commitTimeout);
                timeout        = configuration.GetAttrAsUInt16("timeout", timeout);
                memberPoolSize = configuration.GetAttrAsInt32("memberPoolSize", memberPoolSize);
                hash           = configuration.GetAttrAsInt32("hash", 0);
                //
                if (string.IsNullOrEmpty(topic) == true)
                {
                    throw new ConfigException("no config topic from " + configName + ".config");
                }
                //
                var members = configuration.GetItems();
                var ipcount = members.Length;
                poolMembers = new PoolMember[ipcount];
                for (int i = 0; i < ipcount; i++)
                {
                    poolMembers[i] = new PoolMember(members[i].Ip, members[i].Port, topic, timeout, commitTimeout);
                }
            }
            else
            {
                topic          = Adf.ConfigHelper.GetSetting(configName + "Topic");
                commitTimeout  = Adf.ConfigHelper.GetSettingAsUInt16(configName + "CommitTimeout", commitTimeout);
                timeout        = Adf.ConfigHelper.GetSettingAsUInt16(configName + "Timeout", timeout);
                memberPoolSize = Adf.ConfigHelper.GetSettingAsInt(configName + "MemberPoolSize", memberPoolSize);
                //
                if (string.IsNullOrEmpty(topic) == true)
                {
                    throw new ConfigException("no config topic from application config");
                }
                //
                var config = (IpGroupSection)System.Configuration.ConfigurationManager.GetSection(configName);
                if (config == null)
                {
                    throw new Adf.ConfigException("No find configSection" + configName + " or " + configName + ".config");
                }

                var ipcount = config.IpList.Count;
                poolMembers = new PoolMember[ipcount];
                for (int i = 0; i < ipcount; i++)
                {
                    poolMembers[i] = new PoolMember(config.IpList[i].Ip, config.IpList[i].Port, topic, timeout, commitTimeout);
                }

                hash = config.Hash;
            }
            //
            this.Name           = configName;
            this.Topic          = topic;
            this.Timeout        = timeout;
            this.CommitTimeout  = commitTimeout;
            this.MemberPoolSize = memberPoolSize;
            //
            this.Pool = new Pool <QueueServerClient>(memberPoolSize, poolMembers, hash);
        }
示例#31
0
 public static string ToJsonString(this ServerConfig sc)
 {
     return(JsonHelper.SerializeObject(sc));
 }
示例#32
0
        public Configuration(string pathToConfig)
        {
            XmlReaderSettings configReaderSettings = new XmlReaderSettings();
            Stream s = typeof(Configuration).Assembly.GetManifestResourceStream("Project2Q.SDK.ConfigSchema.xsd");
            StreamReader configStreamReader = new StreamReader(pathToConfig);

            configReaderSettings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
            configReaderSettings.ValidationType = ValidationType.Schema;
            configReaderSettings.IgnoreWhitespace = true;
            configReaderSettings.IgnoreComments = true;
            configReaderSettings.ValidationEventHandler += new ValidationEventHandler(configReaderSettings_ValidationEventHandler);
            configReaderSettings.Schemas.Add(null, XmlReader.Create(s));

            XmlReader cfr = XmlReader.Create(configStreamReader, configReaderSettings);
            try {

                #region Config::Settings
                cfr.Read(); // jump from <Configuration> to <Settings>
                NextNode(cfr);
                string defaultNickName = cfr.Value;
                NextNode(cfr);
                string defaultAlternateNickName = cfr.Value;
                NextNode(cfr);
                string defaultUserName = cfr.Value;
                NextNode(cfr);
                string defaultUserInfo = cfr.Value;
                NextNode(cfr);
                int defaultPort = int.Parse(cfr.Value);
                NextNode(cfr);
                string defaultQuitMessage = cfr.Value;
                NextNode( cfr );
                bool defaultAutoJoinOnInvite = bool.Parse(cfr.Value);
                NextNode(cfr);
                int defaultOperationTimeout = int.Parse(cfr.Value);
                NextNode(cfr);
                int defaultRetryTimeout = int.Parse(cfr.Value);
                NextNode(cfr);
                int defaultSocketBufferSize = int.Parse(cfr.Value);
                NextNode(cfr);
                int defaultSendInhibit = int.Parse(cfr.Value);

                #endregion

                #region Config::Servers

                //<Servers>
                NextNode(cfr);

                ServerConfig serv;
                string[] hostList;
                string serverName, username, userInfo, nickName, altNick, quitMessage;
                int sendInhibit, serverPort, operationTimeout, retryTimeout, socketBufferSize;
                bool autoJoinOnInvite, jj;
                uint ii;
                this.serverTempList = new LinkedList<ServerConfig>();

                while (cfr.Name.Equals("Server")) { //Quick Cleanup
                    hostList = new string[32];
                    serverName = cfr.GetAttribute(0);
                    nickName = defaultNickName;
                    username = defaultUserName;
                    userInfo = defaultUserInfo;
                    altNick = defaultAlternateNickName;
                    autoJoinOnInvite = defaultAutoJoinOnInvite;
                    operationTimeout = defaultOperationTimeout;
                    retryTimeout = defaultRetryTimeout;
                    socketBufferSize = defaultSocketBufferSize;
                    sendInhibit = defaultSendInhibit;
                    serverPort = defaultPort;
                    quitMessage = defaultQuitMessage;

                    ii = 0;
                    jj = true;
                    cfr.Read();

                    while (jj) {
                        switch (cfr.Name) {
                        case "dns":
                            cfr.Read();
                            if (ii < 32) hostList[ii++] = cfr.Value;
                            cfr.Read(); //This will read past the data
                            cfr.Read(); //This will read to the next node.
                            break;
                        case "nickname":
                            cfr.Read();
                            nickName = cfr.Value;
                            cfr.Read(); //This will read past the data
                            cfr.Read(); //This will read to the next node.
                            break;
                        case "alternate":
                            cfr.Read();
                            altNick = cfr.Value;
                            cfr.Read(); //This will read past the data
                            cfr.Read(); //This will read to the next node.
                            break;
                        case "username":
                            cfr.Read();
                            username = cfr.Value;
                            cfr.Read();
                            cfr.Read();
                            break;
                        case "info":
                            cfr.Read();
                            userInfo = cfr.Value;
                            cfr.Read(); //This will read past the data
                            cfr.Read(); //This will read to the next node.
                            break;
                        case "port":
                            cfr.Read();
                            serverPort = int.Parse(cfr.Value);
                            cfr.Read(); //This will read past the data
                            cfr.Read(); //This will read to the next node.
                            break;
                        case "quitMessage":
                            cfr.Read();
                            quitMessage = cfr.Value;
                            cfr.Read();
                            cfr.Read();
                            break;
                        case "autoJoinOnInvite":
                            cfr.Read();
                            autoJoinOnInvite = bool.Parse(cfr.Value);
                            cfr.Read(); //This will read past the data
                            cfr.Read(); //This will read to the next node.
                            break;
                        case "operationTimeout":
                            cfr.Read();
                            operationTimeout = int.Parse( cfr.Value );
                            cfr.Read(); //This will read past the data
                            cfr.Read(); //This will read to the next node.
                            break;
                        case "retryTimeout":
                            cfr.Read();
                            retryTimeout = int.Parse( cfr.Value );
                            cfr.Read(); //This will read past the data
                            cfr.Read(); //This will read to the next node.
                            break;
                        case "socketBufferSize":
                            cfr.Read();
                            socketBufferSize = int.Parse( cfr.Value );
                            cfr.Read(); //This will read past the data
                            cfr.Read(); //This will read to the next node.
                            break;
                        case "sendInhibit":
                            cfr.Read();
                            sendInhibit = int.Parse(cfr.Value);
                            cfr.Read(); //This will read past the data
                            cfr.Read(); //This will read to the next node.
                            break;
                        default:
                            cfr.Read();
                            jj = false;
                            break;
                        }
                    }
                    serv = new ServerConfig(nickName, altNick, username, userInfo, serverName, autoJoinOnInvite,
                        hostList, serverPort, sendInhibit, operationTimeout, retryTimeout, socketBufferSize, quitMessage);

                    serverTempList.AddLast(serv);
                }

                #endregion

                #region Config::Modules

                if (cfr.Name.Equals("Modules")) {

                    moduleTempList = new LinkedList<ModuleConfig>();
                    string[] fileNames, servers = null;
                    string[] includes = new string[128];
                    string moduleName = null, moduleLang = null, prettyName = null;
                    ModuleConfig.ModulePath = cfr.GetAttribute( "modulePath" );
                    ModuleConfig.IncludePath = cfr.GetAttribute( "includePath" );
                    ModuleConfig.FrameworkPath = cfr.GetAttribute( "frameworkPath" );
                    ModuleConfig.ModulePrefix = cfr.GetAttribute( "prefix" );
                    ModuleConfig.ModulePrefix = ModuleConfig.ModulePrefix == null ? "?" : ModuleConfig.ModulePrefix;
                    ModuleConfig.FrameworkPath = ModuleConfig.FrameworkPath == null ?
                        System.IO.Path.Combine(System.Environment.GetEnvironmentVariable("WINDIR"), @"Microsoft.NET\Framework\v2.0.50727")
                        : ModuleConfig.FrameworkPath;

                    cfr.Read();

                    while (cfr.Name.Equals("Module")) {
                        moduleName = cfr.GetAttribute(0);
                        cfr.Read();

                        if ( cfr.Name.Equals( "prettyname" ) ) {
                            cfr.Read();
                            prettyName = cfr.Value;
                            cfr.Read(); cfr.Read(); cfr.Read();
                        }
                        else {
                            prettyName = moduleName;
                            cfr.Read();
                        }

                        fileNames = cfr.Value.Split(';');
                        cfr.Read(); cfr.Read();

                        servers = null;
                        bool isScript = false;

                        if (cfr.Name.Equals("script")) {
                            cfr.Read();
                            cfr.Read();
                            includes = cfr.Value.Split(';');

                            NextNode(cfr);
                            moduleLang = cfr.Value;
                            NextNode(cfr);

                            isScript = true;
                        }

                        if (cfr.Name.Equals("servers")) {
                            cfr.Read();
                            servers = cfr.Value.Split(';');
                            Array.Sort<string>( servers );
                            NextNode(cfr);
                        }

                        if ((cfr.Name.Equals("Module")) && (cfr.NodeType.Equals(System.Xml.XmlNodeType.EndElement)))
                            cfr.Read();

                        this.moduleTempList.AddLast(new ModuleConfig(moduleName, prettyName, moduleLang, fileNames, includes, servers, isScript));
                     }
                }

                #endregion

                #region Config::RemoteConsole

                cfr.Read();
                if (cfr.Name.Equals("RemoteConsole")) {
                    int rconOperationTimeout = defaultOperationTimeout;
                    int rconRetryTimeout = defaultRetryTimeout;
                    int rconSocketBufferSize = defaultSocketBufferSize;
                    int rconSendInhibit = defaultSendInhibit;
                    cfr.Read(); cfr.Read();
                    string initialAuth = cfr.Value;
                    NextNode(cfr);
                    int rconPort = int.Parse(cfr.Value);
                    cfr.Read(); cfr.Read();

                    if (cfr.Name.Equals("operationTimeout")) {
                        cfr.Read();
                        rconOperationTimeout = int.Parse(cfr.Value);
                        cfr.Read(); cfr.Read();
                    }
                    if (cfr.Name.Equals("retryTimeout")) {
                        cfr.Read();
                        rconRetryTimeout = int.Parse(cfr.Value);
                        cfr.Read(); cfr.Read();
                    }
                    if (cfr.Name.Equals("socketBufferSize")) {
                        cfr.Read();
                        rconSocketBufferSize = int.Parse(cfr.Value);
                        cfr.Read(); cfr.Read();
                    }
                    if (cfr.Name.Equals("sendInhibit")) {
                        cfr.Read();
                        rconSendInhibit = int.Parse(cfr.Value);
                        cfr.Read(); cfr.Read();
                    }

                    this.rconConfig = new RconConfig(initialAuth, rconOperationTimeout, rconRetryTimeout,
                        rconSendInhibit, rconSocketBufferSize, rconPort);
                }

                #endregion

            }

            finally {
                cfr.Close();
                configStreamReader.Close();
                s.Close();
            }
        }
 public ChangeServerPasswordCommand(ServerConfig serverConfig) : base("changeserverpassword", Perms.ADMIN, "[{password}]", "Changes server password. Clear it without argument")
 {
     this.serverConfig = serverConfig;
 }
示例#34
0
        public ChangeServerPasswordCommand(ServerConfig serverConfig) : base("changeserverpassword", Perms.ADMIN, "Changes server password. Clear it without argument")
        {
            AddParameter(new TypeString("password", false));

            this.serverConfig = serverConfig;
        }
示例#35
0
 public SecuityService(ServerConfig sc)
 {
     _serverConfig = sc;
 }
 public ServerConfigurationController(IConfigurationService c, IServerService s, IProcessService p, IIndexerManagerService i, ISecuityService ss, IUpdateService u, ILogCacheService lc, Logger l, ServerConfig sc)
 {
     configService   = c;
     serverConfig    = sc;
     serverService   = s;
     processService  = p;
     indexerService  = i;
     securityService = ss;
     updater         = u;
     logCache        = lc;
     logger          = l;
 }
示例#37
0
 public UnixSafeCurlWebClient(IProcessService p, Logger l, IConfigurationService c, ServerConfig sc)
     : base(p: p,
            l: l,
            c: c,
            sc: sc)
 {
 }
示例#38
0
        /// <summary>
        /// Create the voting server.
        /// </summary>
        public VotingRpcServer()
        {
            this.lastProcess = DateTime.Now;

              this.logger = new Logger(Pirate.PiVote.Logger.ServerLogFileName, LogLevel.Info);
              Logger.Log(LogLevel.Info, "Voting RPC server starting...");

              this.serverConfig = new ServerConfig(ServerConfigFileName);
              this.serverConfig.ValidateMail(Logger);
              Logger.Log(LogLevel.Info, "Config file is read.");

              RemoteConfig = new RemoteStoredConfig(RemoteConfigFileName);
              Logger.Log(LogLevel.Info, "Remote config file is read.");

              Mailer = new Mailer(this.serverConfig, this.logger);
              Logger.Log(LogLevel.Info, "Mailer is set up.");

              this.dbConnection = new MySqlConnection(this.serverConfig.MySqlConnectionString);
              this.dbConnection.Open();
              Logger.Log(LogLevel.Info, "Database connection is open.");

              CertificateStorage = new DatabaseCertificateStorage(this.dbConnection);

              if (!CertificateStorage.TryLoadRoot())
              {
            Logger.Log(LogLevel.Error, "Root certificate file not found.");
            this.dbConnection.Close();
            throw new InvalidOperationException("Root certificate file not found.");
              }

              CertificateStorage.ImportStorageIfNeed();
              Logger.Log(LogLevel.Info, "Certificate storage is loaded.");

              this.serverCertificate = CertificateStorage.LoadServerCertificate();
              Logger.Log(LogLevel.Info, "Server certificate is loaded.");

              LoadVotings();
              Logger.Log(LogLevel.Info, "Votings are loaded.");

              ////OutputReport();
        }
示例#39
0
        public static UserCapsula Run(Stream stream, Action <string> log, ServerConfig config)
        {
            ClientHandshake  clientHandshake   = TextEncoder.ReadClientHandshake(stream);
            X509Certificate2 clientCertificate = X509Certificate2Utils.ImportFromPem(clientHandshake.PemCertificate);

            log($"Logging user sent username {clientHandshake.UserName}\n Certificate:\n {clientHandshake.PemCertificate}");

            log("Generating random bytes");
            byte[] randomBytes = LUtils.GenerateRandomBytes(TcpConstants.HANDSHAKE_LENGHT);

            log("Sending encrypted bytes");
            BinaryEncoder.SendBytes(stream, RSAEncoder.Encrypt(randomBytes, clientCertificate));

            ServerHandshake errorHandshake = new ServerHandshake()
            {
                Errors    = "",
                NewUser   = false,
                Succeeded = false,
                UserId    = -1,
                UserName  = ""
            };

            byte[] received = BinaryEncoder.ReceiveBytes(stream);
            if (!randomBytes.SequenceEqual(received))
            {
                log("Sending error to client.");
                errorHandshake.Errors = "Client's certificate verification failed.";
                TextEncoder.SendJson(stream, errorHandshake);
                throw new Exception(errorHandshake.Errors);
            }

            log("Certificate verification succeeded.");

            Users   user;
            String  message;
            Clients client;
            bool    newUser = false;

            using (Context context = new Context(config))
            {
                SHA1   sha  = new SHA1CryptoServiceProvider();
                byte[] hash = sha.ComputeHash(clientCertificate.RawData);
                user = context.Users.SingleOrDefault(u => u.PublicCertificateSha1.SequenceEqual(hash));

                if (user == null)
                {
                    log("User doesn't exist yet. I'll try to create him.");
                    newUser = true;

                    log("Checking the uniquity of username.");
                    String userName = clientHandshake.UserName;
                    if (context.Users.SingleOrDefault(u => u.UserName.Equals(userName)) != null)
                    {
                        log("Username isn't unique.");
                        errorHandshake.Errors = "Username isn't unique.";
                        TextEncoder.SendJson(stream, errorHandshake);
                        throw new Exception(errorHandshake.Errors);
                    }

                    log("Creating user.");
                    user = new Users()
                    {
                        PublicCertificate     = clientHandshake.PemCertificate,
                        PublicCertificateSha1 = hash,
                        UserName = clientHandshake.UserName
                    };

                    context.Users.Add(user);
                    context.SaveChanges();

                    message = "User successfully created.";
                    log("User successfully created.");
                }
                else
                {
                    message = "User exists.";
                    log("User exists.");
                }

                client = new Clients()
                {
                    UserId = user.Id
                };

                if (clientHandshake.ClientId == null)
                {
                    context.Add(client);
                    context.SaveChanges();

                    log($"Added client with Id {client.Id}.");
                }
                else
                {
                    log($"Client with Id {client.Id} has logged in.");
                }
            }

            ServerHandshake toSend = new ServerHandshake()
            {
                Errors    = message,
                NewUser   = newUser,
                Succeeded = true,
                UserId    = user.Id,
                UserName  = user.UserName,
                ClientId  = client.Id
            };

            TextEncoder.SendJson(stream, toSend);

            UserCapsula ret = new UserCapsula(user, clientCertificate);

            log($"Handshake successeded. User {ret.UserName} with id {ret.UserId} has logged in");
            return(ret);
        }
示例#40
0
文件: CellApp.cs 项目: yinlei/Fishing
    //-------------------------------------------------------------------------
    public CellApp()
    {
        mCellApp = this;
        ServerConfig = new ServerConfig();

        // 初始化DataMgr
        {
            string path_media = ServerPath.getPathMediaRoot();
            string db_filename = Path.Combine(path_media, "Dragon\\Config\\Dragon.db");
            EbLog.Note(db_filename);
            TbDataMgr.setup(db_filename);
        }

        // 初始化ScriptMgr
        //{
        //string path_media = ServerPath.getPathMediaRoot();
        //string dir_script = Path.Combine(path_media, "Dragon\\Script\\S\\");
        //mScriptMgr.create(dir_script);

        //List<string> list_param = new List<string>();
        //list_param.Add("102");
        //Effect.doEffect(Entity, 1901, list_param);
        //}

        // 初始化单位模块
        UnitSys.setup(false);

        // 初始化效果系统
        EffectSys = new EffectSys(true);
        EffectSys.regEffect(new EffectActorPropAttackPoint());
        EffectSys.regEffect(new EffectActorPropAttackSpeed());
        EffectSys.regEffect(new EffectActorPropCriticalHitPoint());
        EffectSys.regEffect(new EffectActorPropDefencePoint());
        EffectSys.regEffect(new EffectActorPropDodgePoint());
        EffectSys.regEffect(new EffectActorPropEnergyPointCur());
        EffectSys.regEffect(new EffectActorPropEnergyPointMax());
        EffectSys.regEffect(new EffectActorPropFireEnhancementPoint());
        EffectSys.regEffect(new EffectActorPropFireResistancePoint());
        EffectSys.regEffect(new EffectActorPropHealthPointCur());
        EffectSys.regEffect(new EffectActorPropHealthPointMax());
        EffectSys.regEffect(new EffectActorPropHitPoint());
        EffectSys.regEffect(new EffectActorPropMetalEnhancementPoint());
        EffectSys.regEffect(new EffectActorPropMetalResistancePoint());
        EffectSys.regEffect(new EffectActorPropSoilEnhancementPoint());
        EffectSys.regEffect(new EffectActorPropSoilResistancePoint());
        EffectSys.regEffect(new EffectActorPropTenacityPoint());
        EffectSys.regEffect(new EffectActorPropWaterEnhancementPoint());
        EffectSys.regEffect(new EffectActorPropWaterResistancePoint());
        EffectSys.regEffect(new EffectActorPropWoodEnhancementPoint());
        EffectSys.regEffect(new EffectActorPropWoodResistancePoint());
        EffectSys.regEffect(new EffectCreateStatus());
        EffectSys.regEffect(new EffectLearnSkill());
        EffectSys.regEffect(new EffectSkillPropAttackPoint());
        EffectSys.regEffect(new EffectSkillPropAttackSpeed());
        EffectSys.regEffect(new EffectSkillPropCriticalHitPoint());
        EffectSys.regEffect(new EffectSkillPropDefencePoint());
        EffectSys.regEffect(new EffectSkillPropDodgePoint());
        EffectSys.regEffect(new EffectSkillPropEnergyPointCur());
        EffectSys.regEffect(new EffectSkillPropEnergyPointMax());
        EffectSys.regEffect(new EffectSkillPropFireEnhancementPoint());
        EffectSys.regEffect(new EffectSkillPropFireResistancePoint());
        EffectSys.regEffect(new EffectSkillPropHealthPointCur());
        EffectSys.regEffect(new EffectSkillPropHealthPointMax());
        EffectSys.regEffect(new EffectSkillPropHitPoint());
        EffectSys.regEffect(new EffectSkillPropMetalEnhancementPoint());
        EffectSys.regEffect(new EffectSkillPropMetalResistancePoint());
        EffectSys.regEffect(new EffectSkillPropSoilEnhancementPoint());
        EffectSys.regEffect(new EffectSkillPropSoilResistancePoint());
        EffectSys.regEffect(new EffectSkillPropTenacityPoint());
        EffectSys.regEffect(new EffectSkillPropWaterEnhancementPoint());
        EffectSys.regEffect(new EffectSkillPropWaterResistancePoint());
        EffectSys.regEffect(new EffectSkillPropWoodEnhancementPoint());
        EffectSys.regEffect(new EffectSkillPropWoodResistancePoint());
        EffectSys.regEffect(new EffectTakeoffEquip());
        EffectSys.regEffect(new EffectTakeonEquip());

        //// 创建EtWorld子Entity
        //Entity et_world = EntityMgr.createEntity<EtWorld>(null, Entity);
        //CoWorld = et_world.getComponent<CellWorld<ComponentDef>>();

        // 注册BtFactory
        _regBtFactory(new BtFactoryBossNoraml());
        _regBtFactory(new BtFactoryBossNoramlMirror());
        _regBtFactory(new BtFactoryBot());
        _regBtFactory(new BtFactoryBotMirror());
        _regBtFactory(new BtFactoryMonsterNormal());
        _regBtFactory(new BtFactoryMonsterNormalMirror());
        _regBtFactory(new BtFactoryPlayer());
        _regBtFactory(new BtFactoryPlayerMirror());

        // 加载所有Bot
        var map_databot = EbDataMgr.Instance.getMapData<TbDataBot>();
        foreach (var i in map_databot)
        {
            TbDataBot data_bot = (TbDataBot)i.Value;

            var player = GrainFactory.GetGrain<ICellPlayer>(new Guid(data_bot.EtGuid));
            player.botNewAndEnterWorld(data_bot.NickName);
        }
    }
示例#41
0
 public abstract Result Execute(IOfferRemoteOperations remote, ServerConfig server, ConDepSettings settings,
                                CancellationToken token);
示例#42
0
 public ServerService(IIndexerManagerService i, IProcessService p, ISerializeService s, IConfigurationService c, Logger l, Common.Utils.Clients.WebClient w, IUpdateService u, IProtectionService protectionService, ServerConfig serverConfig)
 {
     indexerService     = i;
     processService     = p;
     serializeService   = s;
     configService      = c;
     logger             = l;
     client             = w;
     updater            = u;
     config             = serverConfig;
     _protectionService = protectionService;
 }
示例#43
0
        private void OnDeserialized(StreamingContext ctx)
        {
            ServerConfig config = (ServerConfig)Config;

            if (config == null)
            {
                config = new ServerConfig();
            }

            config.SetFactory(this);
        }
示例#44
0
 internal TasksServerRequests(ServerConfig serverConfig)
 {
     this.serverConfig = serverConfig;
 }
示例#45
0
        /// <summary>
        /// ���������������
        /// </summary>
        /// <param name="config">��������</param>
        public void Start(ServerConfig config)
        {
            if (this.IsStarted)
            {
                this.Log("�������Ѿ����������");
                return;
            }
            this.Log("������׼�����������");
            try
            {
                this.listener = new TcpListener(System.Net.IPAddress.Parse(config.Ip), config.Port);
                this.listener.Start();
                this.IsStarted = true;
                this.Log("��������������ɹ���");

                this.Log(string.Format("��������{0}�˿ڵȴ��ͻ������ӣ�", config.Port));
                this.listener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), listener);

            }
            catch (Exception ex)
            {
                this.Log("�������������ʧ�ܣ�");
                this.Log(ex);
            }
        }
示例#46
0
 // - Standard Constructor and properties
 public Skeleton(ServerConfig serverData) => _serverData = serverData;
示例#47
0
        /// <summary>
        /// 替换IP和端口终结点地址键值队
        /// </summary>
        private IServerConfig ReplaceListenEndPoint(IServerConfig serverConfig, IDictionary<string, IPEndPoint> listenEndPointReplacement)
        {
            var config = new ServerConfig(serverConfig);

            if (serverConfig.Port > 0)
            {
                var endPointKey = serverConfig.Name + "_" + serverConfig.Port;

                IPEndPoint instanceEndpoint;

                if(!listenEndPointReplacement.TryGetValue(endPointKey, out instanceEndpoint))
                {
                    throw new Exception(string.Format("Failed to find Input Endpoint configuration {0}!", endPointKey));
                }

                config.Ip = instanceEndpoint.Address.ToString();
                config.Port = instanceEndpoint.Port;
            }

            if (config.Listeners != null && config.Listeners.Any())
            {
                var listeners = config.Listeners.ToArray();

                for (var i = 0; i < listeners.Length; i++)
                {
                    var listener = (ListenerConfig)listeners[i];

                    var endPointKey = serverConfig.Name + "_" + listener.Port;

                    IPEndPoint instanceEndpoint;

                    if (!listenEndPointReplacement.TryGetValue(endPointKey, out instanceEndpoint))
                    {
                        throw new Exception(string.Format("Failed to find Input Endpoint configuration {0}!", endPointKey));
                    }

                    listener.Ip = instanceEndpoint.Address.ToString();
                    listener.Port = instanceEndpoint.Port;
                }

                config.Listeners = listeners;
            }

            return config;
        }
示例#48
0
 public UpdateService(Logger l, WebClient c, IConfigurationService cfg, ITrayLockService ls, ServerConfig sc)
 {
     logger        = l;
     client        = c;
     configService = cfg;
     lockService   = ls;
     serverConfig  = sc;
 }
示例#49
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

            var            commandLineParser = new Parser(settings => settings.CaseSensitive = false);
            var            optionsResult     = commandLineParser.ParseArguments <ConsoleOptions>(args);
            var            runtimeDictionary = new Dictionary <string, string>();
            ConsoleOptions consoleOptions    = new ConsoleOptions();

            optionsResult.WithNotParsed(errors =>
            {
                var text       = HelpText.AutoBuild(optionsResult);
                text.Copyright = " ";
                text.Heading   = "Jackett v" + EnvironmentUtil.JackettVersion;
                Console.WriteLine(text);
                Environment.Exit(1);
                return;
            });

            optionsResult.WithParsed(options =>
            {
                if (string.IsNullOrEmpty(options.Client))
                {
                    if (DotNetCoreUtil.IsRunningOnDotNetCore)
                    {
                        options.Client = "httpclientnetcore";
                    }
                    else
                    {
                        options.Client = "httpclient";
                    }
                }

                Settings          = options.ToRunTimeSettings();
                consoleOptions    = options;
                runtimeDictionary = GetValues(Settings);
            });

            LogManager.Configuration = LoggingSetup.GetLoggingConfiguration(Settings);
            Logger logger = LogManager.GetCurrentClassLogger();

            logger.Info("Starting Jackett v" + EnvironmentUtil.JackettVersion);

            // create PID file early
            if (!string.IsNullOrWhiteSpace(Settings.PIDFile))
            {
                try
                {
                    var proc = Process.GetCurrentProcess();
                    File.WriteAllText(Settings.PIDFile, proc.Id.ToString());
                }
                catch (Exception e)
                {
                    logger.Error(e, "Error while creating the PID file");
                }
            }

            Initialisation.CheckEnvironmentalVariables(logger);
            Initialisation.ProcessSettings(Settings, logger);

            ISerializeService     serializeService     = new SerializeService();
            IProcessService       processService       = new ProcessService(logger);
            IConfigurationService configurationService = new ConfigurationService(serializeService, processService, logger, Settings);

            if (consoleOptions.Install || consoleOptions.Uninstall || consoleOptions.StartService || consoleOptions.StopService || consoleOptions.ReserveUrls)
            {
                bool isWindows = Environment.OSVersion.Platform == PlatformID.Win32NT;

                if (isWindows)
                {
                    ServerConfig serverConfig = configurationService.BuildServerConfig(Settings);
                    Initialisation.ProcessWindowsSpecificArgs(consoleOptions, processService, serverConfig, logger);
                }
                else
                {
                    logger.Error($"ReserveUrls and service arguments only apply to Windows, please remove them from your start arguments");
                    Environment.Exit(1);
                }
            }

            var builder = new ConfigurationBuilder();

            builder.AddInMemoryCollection(runtimeDictionary);
            builder.AddJsonFile(Path.Combine(configurationService.GetAppDataFolder(), "appsettings.json"), optional: true);

            Configuration = builder.Build();

            do
            {
                if (!isWebHostRestart)
                {
                    if (consoleOptions.Port != 0 || consoleOptions.ListenPublic || consoleOptions.ListenPrivate)
                    {
                        ServerConfig serverConfiguration = configurationService.BuildServerConfig(Settings);
                        Initialisation.ProcessConsoleOverrides(consoleOptions, processService, serverConfiguration, configurationService, logger);
                    }
                }

                ServerConfig serverConfig = configurationService.BuildServerConfig(Settings);
                Int32.TryParse(serverConfig.Port.ToString(), out Int32 configPort);
                string[] url = serverConfig.GetListenAddresses(serverConfig.AllowExternal);

                isWebHostRestart = false;

                try
                {
                    logger.Debug("Creating web host...");
                    string applicationFolder = Path.Combine(configurationService.ApplicationFolder(), "Content");
                    logger.Debug($"Content root path is: {applicationFolder}");

                    CreateWebHostBuilder(args, url, applicationFolder).Build().Run();
                }
                catch (Exception ex)
                {
                    if (ex.InnerException is Microsoft.AspNetCore.Connections.AddressInUseException)
                    {
                        logger.Error("Address already in use: Most likely Jackett is already running. " + ex.Message);
                        Environment.Exit(1);
                    }
                    logger.Error(ex);
                    throw;
                }
            } while (isWebHostRestart);
        }
 public PowerShellScriptPublisher(ConDepSettings settings, ServerConfig server)
 {
     _settings        = settings;
     _server          = server;
     _localTargetPath = Path.Combine(Path.GetTempPath(), @"PSScripts\ConDep");
 }
示例#51
0
        public void Harvest(ServerConfig server)
        {
            var networkInfo = @"$result = @()
$networkInterfaces = Get-WmiObject win32_networkadapterconfiguration | where { $_.IPEnabled }
foreach($interface in $networkInterfaces) {
    $ifaceInfo = @{}
    $ifaceInfo.IPAddresses = $interface.IPAddress
    $ifaceInfo.IPSubnets = $interface.IPSubnet
    $ifaceInfo.Description = $interface.Description
    $ifaceInfo.DefaultGateways = $interface.DefaultIPGateway
    $ifaceInfo.DHCPEnabled = $interface.DHCPEnabled
    $ifaceInfo.DNSDomain = $interface.DNSDomain
    $ifaceInfo.DNSHostName = $interface.DNSHostName
    $ifaceInfo.Index = $interface.Index
    $ifaceInfo.InterfaceIndex = $interface.InterfaceIndex

    $result += ,@($ifaceInfo)
}

return $result";

            var networkInfoResult = _executor.Execute(server, networkInfo, mod => mod.LoadConDepModule = false,
                                                      logOutput: false);

            if (networkInfoResult != null)
            {
                foreach (var network in networkInfoResult)
                {
                    //object[] ipAddresses = network.IPAddresses;
                    //IEnumerable<string> ipAddresses2 = ipAddresses.Cast<string>();
                    //object[] gateways = network.DefaultGateways;

                    var info = new NetworkInfo
                    {
                        Description    = network.Description,
                        DHCPEnabled    = network.DHCPEnabled,
                        DNSDomain      = network.DNSDomain,
                        DNSHostName    = network.DNSHostName,
                        Index          = Convert.ToInt32(network.Index),
                        InterfaceIndex = Convert.ToInt32(network.InterfaceIndex)
                    };

                    if (network.IPAddresses is string)
                    {
                        info.IPAddresses = new string[] { network.IPAddresses };
                    }
                    else
                    {
                        object[] addresses = network.IPAddresses;
                        info.IPAddresses = addresses.Cast <string>();
                    }

                    if (network.IPSubnets is string)
                    {
                        info.IPSubnets = new string[] { network.IPSubnets };
                    }
                    else
                    {
                        object[] subnets = network.IPSubnets;
                        info.IPSubnets = subnets.Cast <string>();
                    }

                    if (network.DefaultGateways != null)
                    {
                        if (network.DefaultGateways is string)
                        {
                            info.DefaultGateways = new string[] { network.DefaultGateways };
                        }
                        else
                        {
                            object[] gateways = network.DefaultGateways;
                            info.IPAddresses = gateways.Cast <string>();
                        }
                    }

                    server.GetServerInfo().Network.Add(info);
                }
            }
        }
示例#52
0
		public GameServer(ServerConfig config)
		{
			Config = config;
		}