Ejemplo n.º 1
0
        /// <summary>
        /// Create a test IPBanService
        /// </summary>
        /// <param name="directory">Root directory</param>
        /// <param name="configFileName">Config file name</param>
        /// <param name="defaultBannedIPAddressHandlerUrl">Url for banned ip handling or null to not handle banned ip</param>
        /// <param name="configFileModifier">Change config file (param are file text, returns new file text)</param>
        /// <returns>Service</returns>
        public static T CreateAndStartIPBanTestService <T>(string directory = null, string configFileName = null, string defaultBannedIPAddressHandlerUrl = null,
                                                           Func <string, string> configFileModifier = null) where T : IPBanService
        {
            DefaultHttpRequestMaker.DisableLiveRequests = true;

            // cleanup any db, set or tbl files
            foreach (string file in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.set")
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tbl"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.set6"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tbl6"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.sqlite*"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*journal*")))
            {
                IPBanExtensionMethods.FileDeleteWithRetry(file, 1000);
            }

            if (string.IsNullOrWhiteSpace(directory))
            {
                directory = Path.GetDirectoryName(IPBanAssembly.Location);
            }
            if (string.IsNullOrWhiteSpace(configFileName))
            {
                configFileName = IPBanService.ConfigFileName;
            }
            string configFilePath = Path.Combine(directory, configFileName);
            string configFileText = File.ReadAllText(configFilePath);

            configFilePath += ".tmp";
            if (configFileModifier != null)
            {
                configFileText = configFileModifier(configFileText);
            }
            IPBanExtensionMethods.FileWriteAllTextWithRetry(configFilePath, configFileText);
            T service = IPBanService.CreateService <T>() as T;

            service.ExternalIPAddressLookup = LocalMachineExternalIPAddressLookupTest.Instance;
            service.ConfigFilePath          = configFilePath;
            service.MultiThreaded           = false;
            service.ManualCycle             = true;
            if (defaultBannedIPAddressHandlerUrl is null)
            {
                service.BannedIPAddressHandler = service;
            }
            else
            {
                service.BannedIPAddressHandler = new DefaultBannedIPAddressHandler {
                    BaseUrl = defaultBannedIPAddressHandlerUrl
                };
            }
            service.Version = "1.1.1.1";
            service.StartAsync().Sync();
            service.DB.Truncate(true);
            service.Firewall.Truncate();
            return(service);
        }
Ejemplo n.º 2
0
 public static async Task MainService(string[] args, Func <string[], Task> start, Action stop, bool requireAdministrator = true)
 {
     try
     {
         using (IPBanServiceRunner runner = new IPBanServiceRunner(args, start, stop))
         {
             await runner.RunAsync(requireAdministrator);
         }
     }
     catch (Exception ex)
     {
         IPBanExtensionMethods.FileWriteAllTextWithRetry(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "startup_fail.txt"), ex.ToString());
         IPBanLog.Fatal("Fatal error starting service", ex);
     }
 }
Ejemplo n.º 3
0
        /* // makes nlog go haywire, revisit later
         * private static readonly CustomTimeSource timeSource = new CustomTimeSource();
         *
         * private class CustomTimeSource : NLog.Time.TimeSource
         * {
         *  private TimeZoneInfo zoneInfo = TimeZoneInfo.Utc;
         *
         *  [Required]
         *  public string Zone
         *  {
         *      get { return zoneInfo.DisplayName; }
         *      set { zoneInfo = TimeZoneInfo.FindSystemTimeZoneById(value); }
         *  }
         *
         *  public override DateTime Time => IPBanService.UtcNow;
         *
         *  public override DateTime FromSystemTime(DateTime systemTime)
         *  {
         *      return systemTime.ToUniversalTime();
         *  }
         *
         *  public DateTime CurrentTime { get; set; } = IPBanService.UtcNow;
         * }
         */

        static IPBanLog()
        {
            try
            {
                LogFactory factory = null;
                try
                {
                    factory = LogManager.LoadConfiguration(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath);
                }
                catch
                {
                    // if no config, exception is thrown that is OK
                }
                if (factory is null || factory.Configuration.AllTargets.Count == 0)
                {
                    string nlogConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "nlog.config");
                    if (!File.Exists(nlogConfigPath))
                    {
                        string logLevel = "Warn";
                        foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
                        {
                            if (a.FullName.IndexOf("nunit.framework", StringComparison.OrdinalIgnoreCase) >= 0)
                            {
                                logLevel = "Trace";
                                break;
                            }
                        }

                        Console.WriteLine("Creating default nlog.config file");

                        // storing this as a resource fails to use correct string in precompiled .exe with .net core, bug with Microsoft I think
                        string defaultNLogConfig = $@"<?xml version=""1.0""?>
<nlog xmlns=""http://www.nlog-project.org/schemas/NLog.xsd"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" throwExceptions=""false"" internalLogToConsole=""false"" internalLogToConsoleError=""false"" internalLogLevel=""Trace"">
  <targets>
    <target name=""logfile"" xsi:type=""File"" fileName=""${{basedir}}/logfile.txt"" archiveNumbering=""Sequence"" archiveEvery=""Day"" maxArchiveFiles=""28"" encoding=""UTF-8""/>
    <target name=""console"" xsi:type=""Console""/>
  </targets>
  <rules>
    <logger name=""*"" minlevel=""{logLevel}"" writeTo=""logfile""/>
    <logger name=""*"" minlevel=""{logLevel}"" writeTo=""console""/>
  </rules>
</nlog>";
                        IPBanExtensionMethods.FileWriteAllTextWithRetry(nlogConfigPath, defaultNLogConfig);
                    }
                    if (File.Exists(nlogConfigPath))
                    {
                        factory = LogManager.LoadConfiguration(nlogConfigPath);
                    }
                    else
                    {
                        throw new IOException("Unable to create nlog configuration file, nlog.config file failed to write default config.");
                    }
                }
                logger = factory.GetCurrentClassLogger();
                //NLog.Time.TimeSource.Current = timeSource;
            }
            catch (Exception ex)
            {
                // log to console as no other logger is available
                Console.WriteLine("Failed to initialize logger: {0}", ex);
            }
        }