MaxMind.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2021 Shreyas Zare (shreyas@technitium.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using DnsServerCore.ApplicationCommon;
  16. using MaxMind.GeoIP2;
  17. using System;
  18. using System.IO;
  19. namespace GeoCountry
  20. {
  21. class MaxMind : IDisposable
  22. {
  23. #region variables
  24. static MaxMind _maxMind;
  25. readonly DatabaseReader _mmCountryReader;
  26. #endregion
  27. #region constructor
  28. private MaxMind(IDnsServer dnsServer)
  29. {
  30. string mmFile = Path.Combine(dnsServer.ApplicationFolder, "GeoIP2-Country.mmdb");
  31. if (!File.Exists(mmFile))
  32. mmFile = Path.Combine(dnsServer.ApplicationFolder, "GeoLite2-Country.mmdb");
  33. if (!File.Exists(mmFile))
  34. throw new FileNotFoundException("MaxMind Country file is missing!");
  35. _mmCountryReader = new DatabaseReader(mmFile);
  36. }
  37. #endregion
  38. #region IDisposable
  39. bool _disposed;
  40. protected virtual void Dispose(bool disposing)
  41. {
  42. if (_disposed)
  43. return;
  44. if (disposing)
  45. {
  46. if (_mmCountryReader is not null)
  47. _mmCountryReader.Dispose();
  48. }
  49. _disposed = true;
  50. }
  51. public void Dispose()
  52. {
  53. Dispose(true);
  54. GC.SuppressFinalize(this);
  55. }
  56. #endregion
  57. #region public
  58. public static MaxMind Create(IDnsServer dnsServer)
  59. {
  60. if (_maxMind is null)
  61. _maxMind = new MaxMind(dnsServer);
  62. return _maxMind;
  63. }
  64. #endregion
  65. #region properties
  66. public DatabaseReader DatabaseReader
  67. { get { return _mmCountryReader; } }
  68. #endregion
  69. }
  70. }