ConnectEntryPoint.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Connect;
  5. using MediaBrowser.Controller.Plugins;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Net;
  8. using System;
  9. using System.IO;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using MediaBrowser.Controller.Security;
  13. using MediaBrowser.Model.IO;
  14. using MediaBrowser.Model.Threading;
  15. namespace Emby.Server.Implementations.Connect
  16. {
  17. public class ConnectEntryPoint : IServerEntryPoint
  18. {
  19. private ITimer _timer;
  20. private readonly IHttpClient _httpClient;
  21. private readonly IApplicationPaths _appPaths;
  22. private readonly ILogger _logger;
  23. private readonly IConnectManager _connectManager;
  24. private readonly INetworkManager _networkManager;
  25. private readonly IApplicationHost _appHost;
  26. private readonly IFileSystem _fileSystem;
  27. private readonly ITimerFactory _timerFactory;
  28. private readonly IEncryptionManager _encryption;
  29. public ConnectEntryPoint(IHttpClient httpClient, IApplicationPaths appPaths, ILogger logger, INetworkManager networkManager, IConnectManager connectManager, IApplicationHost appHost, IFileSystem fileSystem, ITimerFactory timerFactory, IEncryptionManager encryption)
  30. {
  31. _httpClient = httpClient;
  32. _appPaths = appPaths;
  33. _logger = logger;
  34. _networkManager = networkManager;
  35. _connectManager = connectManager;
  36. _appHost = appHost;
  37. _fileSystem = fileSystem;
  38. _timerFactory = timerFactory;
  39. _encryption = encryption;
  40. }
  41. public void Run()
  42. {
  43. LoadCachedAddress();
  44. _timer = _timerFactory.Create(TimerCallback, null, TimeSpan.FromSeconds(5), TimeSpan.FromHours(1));
  45. ((ConnectManager)_connectManager).Start();
  46. }
  47. private readonly string[] _ipLookups =
  48. {
  49. "http://bot.whatismyipaddress.com",
  50. "https://connect.emby.media/service/ip"
  51. };
  52. private async void TimerCallback(object state)
  53. {
  54. IpAddressInfo validIpAddress = null;
  55. foreach (var ipLookupUrl in _ipLookups)
  56. {
  57. try
  58. {
  59. validIpAddress = await GetIpAddress(ipLookupUrl).ConfigureAwait(false);
  60. // Try to find the ipv4 address, if present
  61. if (validIpAddress.AddressFamily != IpAddressFamily.InterNetworkV6)
  62. {
  63. break;
  64. }
  65. }
  66. catch (HttpException)
  67. {
  68. }
  69. catch (Exception ex)
  70. {
  71. _logger.ErrorException("Error getting connection info", ex);
  72. }
  73. }
  74. // If this produced an ipv6 address, try again
  75. if (validIpAddress != null && validIpAddress.AddressFamily == IpAddressFamily.InterNetworkV6)
  76. {
  77. foreach (var ipLookupUrl in _ipLookups)
  78. {
  79. try
  80. {
  81. var newAddress = await GetIpAddress(ipLookupUrl, true).ConfigureAwait(false);
  82. // Try to find the ipv4 address, if present
  83. if (newAddress.AddressFamily != IpAddressFamily.InterNetworkV6)
  84. {
  85. validIpAddress = newAddress;
  86. break;
  87. }
  88. }
  89. catch (HttpException)
  90. {
  91. }
  92. catch (Exception ex)
  93. {
  94. _logger.ErrorException("Error getting connection info", ex);
  95. }
  96. }
  97. }
  98. if (validIpAddress != null)
  99. {
  100. ((ConnectManager)_connectManager).OnWanAddressResolved(validIpAddress);
  101. CacheAddress(validIpAddress);
  102. }
  103. }
  104. private async Task<IpAddressInfo> GetIpAddress(string lookupUrl, bool preferIpv4 = false)
  105. {
  106. // Sometimes whatismyipaddress might fail, but it won't do us any good having users raise alarms over it.
  107. var logErrors = false;
  108. #if DEBUG
  109. logErrors = true;
  110. #endif
  111. using (var stream = await _httpClient.Get(new HttpRequestOptions
  112. {
  113. Url = lookupUrl,
  114. UserAgent = "Emby/" + _appHost.ApplicationVersion,
  115. LogErrors = logErrors,
  116. // Seeing block length errors with our server
  117. EnableHttpCompression = false,
  118. PreferIpv4 = preferIpv4,
  119. BufferContent = false
  120. }).ConfigureAwait(false))
  121. {
  122. using (var reader = new StreamReader(stream))
  123. {
  124. var addressString = await reader.ReadToEndAsync().ConfigureAwait(false);
  125. return _networkManager.ParseIpAddress(addressString);
  126. }
  127. }
  128. }
  129. private string CacheFilePath
  130. {
  131. get { return Path.Combine(_appPaths.DataPath, "wan.dat"); }
  132. }
  133. private void CacheAddress(IpAddressInfo address)
  134. {
  135. var path = CacheFilePath;
  136. try
  137. {
  138. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  139. }
  140. catch (Exception ex)
  141. {
  142. }
  143. try
  144. {
  145. _fileSystem.WriteAllText(path, _encryption.EncryptString(address.ToString()), Encoding.UTF8);
  146. }
  147. catch (Exception ex)
  148. {
  149. _logger.ErrorException("Error saving data", ex);
  150. }
  151. }
  152. private void LoadCachedAddress()
  153. {
  154. var path = CacheFilePath;
  155. _logger.Info("Loading data from {0}", path);
  156. try
  157. {
  158. var endpoint = _encryption.DecryptString(_fileSystem.ReadAllText(path, Encoding.UTF8));
  159. IpAddressInfo ipAddress;
  160. if (_networkManager.TryParseIpAddress(endpoint, out ipAddress))
  161. {
  162. ((ConnectManager)_connectManager).OnWanAddressResolved(ipAddress);
  163. }
  164. }
  165. catch (IOException)
  166. {
  167. // File isn't there. no biggie
  168. }
  169. catch (Exception ex)
  170. {
  171. _logger.ErrorException("Error loading data", ex);
  172. }
  173. }
  174. public void Dispose()
  175. {
  176. if (_timer != null)
  177. {
  178. _timer.Dispose();
  179. _timer = null;
  180. }
  181. }
  182. }
  183. }