ConnectEntryPoint.cs 7.1 KB

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