HttpEndPointListener.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Security.Cryptography.X509Certificates;
  6. using System.Threading;
  7. using MediaBrowser.Model.Cryptography;
  8. using MediaBrowser.Model.IO;
  9. using MediaBrowser.Model.Net;
  10. using MediaBrowser.Model.System;
  11. using MediaBrowser.Model.Text;
  12. using Microsoft.Extensions.Logging;
  13. namespace SocketHttpListener.Net
  14. {
  15. internal sealed class HttpEndPointListener
  16. {
  17. private HttpListener _listener;
  18. private IPEndPoint _endpoint;
  19. private Socket _socket;
  20. private Dictionary<ListenerPrefix, HttpListener> _prefixes;
  21. private List<ListenerPrefix> _unhandledPrefixes; // host = '*'
  22. private List<ListenerPrefix> _allPrefixes; // host = '+'
  23. private X509Certificate _cert;
  24. private bool _secure;
  25. private Dictionary<HttpConnection, HttpConnection> _unregisteredConnections;
  26. private readonly ILogger _logger;
  27. private bool _closed;
  28. private bool _enableDualMode;
  29. private readonly ICryptoProvider _cryptoProvider;
  30. private readonly ISocketFactory _socketFactory;
  31. private readonly ITextEncoding _textEncoding;
  32. private readonly IStreamHelper _streamHelper;
  33. private readonly IFileSystem _fileSystem;
  34. private readonly IEnvironmentInfo _environment;
  35. public HttpEndPointListener(HttpListener listener, IPAddress addr, int port, bool secure, X509Certificate cert, ILogger logger, ICryptoProvider cryptoProvider, ISocketFactory socketFactory, IStreamHelper streamHelper, ITextEncoding textEncoding, IFileSystem fileSystem, IEnvironmentInfo environment)
  36. {
  37. this._listener = listener;
  38. _logger = logger;
  39. _cryptoProvider = cryptoProvider;
  40. _socketFactory = socketFactory;
  41. _streamHelper = streamHelper;
  42. _textEncoding = textEncoding;
  43. _fileSystem = fileSystem;
  44. _environment = environment;
  45. this._secure = secure;
  46. this._cert = cert;
  47. _enableDualMode = addr.Equals(IPAddress.IPv6Any);
  48. _endpoint = new IPEndPoint(addr, port);
  49. _prefixes = new Dictionary<ListenerPrefix, HttpListener>();
  50. _unregisteredConnections = new Dictionary<HttpConnection, HttpConnection>();
  51. CreateSocket();
  52. }
  53. internal HttpListener Listener
  54. {
  55. get
  56. {
  57. return _listener;
  58. }
  59. }
  60. private void CreateSocket()
  61. {
  62. try
  63. {
  64. _socket = CreateSocket(_endpoint.Address.AddressFamily, _enableDualMode);
  65. }
  66. catch (SocketCreateException ex)
  67. {
  68. if (_enableDualMode && _endpoint.Address.Equals(IPAddress.IPv6Any) &&
  69. (string.Equals(ex.ErrorCode, "AddressFamilyNotSupported", StringComparison.OrdinalIgnoreCase) ||
  70. // mono 4.8.1 and lower on bsd is throwing this
  71. string.Equals(ex.ErrorCode, "ProtocolNotSupported", StringComparison.OrdinalIgnoreCase) ||
  72. // mono 5.2 on bsd is throwing this
  73. string.Equals(ex.ErrorCode, "OperationNotSupported", StringComparison.OrdinalIgnoreCase)))
  74. {
  75. _endpoint = new IPEndPoint(IPAddress.Any, _endpoint.Port);
  76. _enableDualMode = false;
  77. _socket = CreateSocket(_endpoint.Address.AddressFamily, _enableDualMode);
  78. }
  79. else
  80. {
  81. throw;
  82. }
  83. }
  84. try
  85. {
  86. _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  87. }
  88. catch (SocketException)
  89. {
  90. // This is not supported on all operating systems (qnap)
  91. }
  92. _socket.Bind(_endpoint);
  93. // This is the number TcpListener uses.
  94. _socket.Listen(2147483647);
  95. Accept();
  96. _closed = false;
  97. }
  98. private void Accept()
  99. {
  100. var acceptEventArg = new SocketAsyncEventArgs();
  101. acceptEventArg.UserToken = this;
  102. acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(OnAccept);
  103. Accept(acceptEventArg);
  104. }
  105. private static void TryCloseAndDispose(Socket socket)
  106. {
  107. try
  108. {
  109. using (socket)
  110. {
  111. socket.Close();
  112. }
  113. }
  114. catch
  115. {
  116. }
  117. }
  118. private static void TryClose(Socket socket)
  119. {
  120. try
  121. {
  122. socket.Close();
  123. }
  124. catch
  125. {
  126. }
  127. }
  128. private void Accept(SocketAsyncEventArgs acceptEventArg)
  129. {
  130. // acceptSocket must be cleared since the context object is being reused
  131. acceptEventArg.AcceptSocket = null;
  132. try
  133. {
  134. bool willRaiseEvent = _socket.AcceptAsync(acceptEventArg);
  135. if (!willRaiseEvent)
  136. {
  137. ProcessAccept(acceptEventArg);
  138. }
  139. }
  140. catch (ObjectDisposedException)
  141. {
  142. // TODO Investigate or properly fix.
  143. }
  144. catch (Exception ex)
  145. {
  146. HttpEndPointListener epl = (HttpEndPointListener)acceptEventArg.UserToken;
  147. epl._logger.LogError(ex, "Error in socket.AcceptAsync");
  148. }
  149. }
  150. // This method is the callback method associated with Socket.AcceptAsync
  151. // operations and is invoked when an accept operation is complete
  152. //
  153. private static void OnAccept(object sender, SocketAsyncEventArgs e)
  154. {
  155. ProcessAccept(e);
  156. }
  157. private static async void ProcessAccept(SocketAsyncEventArgs args)
  158. {
  159. HttpEndPointListener epl = (HttpEndPointListener)args.UserToken;
  160. if (epl._closed)
  161. {
  162. return;
  163. }
  164. // http://msdn.microsoft.com/en-us/library/system.net.sockets.acceptSocket.acceptasync%28v=vs.110%29.aspx
  165. // Under certain conditions ConnectionReset can occur
  166. // Need to attept to re-accept
  167. var socketError = args.SocketError;
  168. var accepted = args.AcceptSocket;
  169. epl.Accept(args);
  170. if (socketError == SocketError.ConnectionReset)
  171. {
  172. epl._logger.LogError("SocketError.ConnectionReset reported. Attempting to re-accept.");
  173. return;
  174. }
  175. if (accepted == null)
  176. {
  177. return;
  178. }
  179. if (epl._secure && epl._cert == null)
  180. {
  181. TryClose(accepted);
  182. return;
  183. }
  184. try
  185. {
  186. var remoteEndPointString = accepted.RemoteEndPoint == null ? string.Empty : accepted.RemoteEndPoint.ToString();
  187. var localEndPointString = accepted.LocalEndPoint == null ? string.Empty : accepted.LocalEndPoint.ToString();
  188. //_logger.LogInformation("HttpEndPointListener Accepting connection from {0} to {1} secure connection requested: {2}", remoteEndPointString, localEndPointString, _secure);
  189. HttpConnection conn = new HttpConnection(epl._logger, accepted, epl, epl._secure, epl._cert, epl._cryptoProvider, epl._streamHelper, epl._textEncoding, epl._fileSystem, epl._environment);
  190. await conn.Init().ConfigureAwait(false);
  191. //_logger.LogDebug("Adding unregistered connection to {0}. Id: {1}", accepted.RemoteEndPoint, connectionId);
  192. lock (epl._unregisteredConnections)
  193. {
  194. epl._unregisteredConnections[conn] = conn;
  195. }
  196. conn.BeginReadRequest();
  197. }
  198. catch (Exception ex)
  199. {
  200. epl._logger.LogError(ex, "Error in ProcessAccept");
  201. TryClose(accepted);
  202. epl.Accept();
  203. return;
  204. }
  205. }
  206. private Socket CreateSocket(AddressFamily addressFamily, bool dualMode)
  207. {
  208. try
  209. {
  210. var socket = new Socket(addressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
  211. if (dualMode)
  212. {
  213. socket.DualMode = true;
  214. }
  215. return socket;
  216. }
  217. catch (SocketException ex)
  218. {
  219. throw new SocketCreateException(ex.SocketErrorCode.ToString(), ex);
  220. }
  221. catch (ArgumentException ex)
  222. {
  223. if (dualMode)
  224. {
  225. // Mono for BSD incorrectly throws ArgumentException instead of SocketException
  226. throw new SocketCreateException("AddressFamilyNotSupported", ex);
  227. }
  228. else
  229. {
  230. throw;
  231. }
  232. }
  233. }
  234. internal void RemoveConnection(HttpConnection conn)
  235. {
  236. lock (_unregisteredConnections)
  237. {
  238. _unregisteredConnections.Remove(conn);
  239. }
  240. }
  241. public bool BindContext(HttpListenerContext context)
  242. {
  243. HttpListenerRequest req = context.Request;
  244. ListenerPrefix prefix;
  245. HttpListener listener = SearchListener(req.Url, out prefix);
  246. if (listener == null)
  247. return false;
  248. context.Connection.Prefix = prefix;
  249. return true;
  250. }
  251. public void UnbindContext(HttpListenerContext context)
  252. {
  253. if (context == null || context.Request == null)
  254. return;
  255. _listener.UnregisterContext(context);
  256. }
  257. private HttpListener SearchListener(Uri uri, out ListenerPrefix prefix)
  258. {
  259. prefix = null;
  260. if (uri == null)
  261. return null;
  262. string host = uri.Host;
  263. int port = uri.Port;
  264. string path = WebUtility.UrlDecode(uri.AbsolutePath);
  265. string pathSlash = path[path.Length - 1] == '/' ? path : path + "/";
  266. HttpListener bestMatch = null;
  267. int bestLength = -1;
  268. if (host != null && host != "")
  269. {
  270. Dictionary<ListenerPrefix, HttpListener> localPrefixes = _prefixes;
  271. foreach (ListenerPrefix p in localPrefixes.Keys)
  272. {
  273. string ppath = p.Path;
  274. if (ppath.Length < bestLength)
  275. continue;
  276. if (p.Host != host || p.Port != port)
  277. continue;
  278. if (path.StartsWith(ppath) || pathSlash.StartsWith(ppath))
  279. {
  280. bestLength = ppath.Length;
  281. bestMatch = localPrefixes[p];
  282. prefix = p;
  283. }
  284. }
  285. if (bestLength != -1)
  286. return bestMatch;
  287. }
  288. List<ListenerPrefix> list = _unhandledPrefixes;
  289. bestMatch = MatchFromList(host, path, list, out prefix);
  290. if (path != pathSlash && bestMatch == null)
  291. bestMatch = MatchFromList(host, pathSlash, list, out prefix);
  292. if (bestMatch != null)
  293. return bestMatch;
  294. list = _allPrefixes;
  295. bestMatch = MatchFromList(host, path, list, out prefix);
  296. if (path != pathSlash && bestMatch == null)
  297. bestMatch = MatchFromList(host, pathSlash, list, out prefix);
  298. if (bestMatch != null)
  299. return bestMatch;
  300. return null;
  301. }
  302. private HttpListener MatchFromList(string host, string path, List<ListenerPrefix> list, out ListenerPrefix prefix)
  303. {
  304. prefix = null;
  305. if (list == null)
  306. return null;
  307. HttpListener bestMatch = null;
  308. int bestLength = -1;
  309. foreach (ListenerPrefix p in list)
  310. {
  311. string ppath = p.Path;
  312. if (ppath.Length < bestLength)
  313. continue;
  314. if (path.StartsWith(ppath))
  315. {
  316. bestLength = ppath.Length;
  317. bestMatch = p._listener;
  318. prefix = p;
  319. }
  320. }
  321. return bestMatch;
  322. }
  323. private void AddSpecial(List<ListenerPrefix> list, ListenerPrefix prefix)
  324. {
  325. if (list == null)
  326. return;
  327. foreach (ListenerPrefix p in list)
  328. {
  329. if (p.Path == prefix.Path)
  330. throw new Exception("net_listener_already");
  331. }
  332. list.Add(prefix);
  333. }
  334. private bool RemoveSpecial(List<ListenerPrefix> list, ListenerPrefix prefix)
  335. {
  336. if (list == null)
  337. return false;
  338. int c = list.Count;
  339. for (int i = 0; i < c; i++)
  340. {
  341. ListenerPrefix p = list[i];
  342. if (p.Path == prefix.Path)
  343. {
  344. list.RemoveAt(i);
  345. return true;
  346. }
  347. }
  348. return false;
  349. }
  350. private void CheckIfRemove()
  351. {
  352. if (_prefixes.Count > 0)
  353. return;
  354. List<ListenerPrefix> list = _unhandledPrefixes;
  355. if (list != null && list.Count > 0)
  356. return;
  357. list = _allPrefixes;
  358. if (list != null && list.Count > 0)
  359. return;
  360. HttpEndPointManager.RemoveEndPoint(this, _endpoint);
  361. }
  362. public void Close()
  363. {
  364. _closed = true;
  365. _socket.Close();
  366. lock (_unregisteredConnections)
  367. {
  368. // Clone the list because RemoveConnection can be called from Close
  369. var connections = new List<HttpConnection>(_unregisteredConnections.Keys);
  370. foreach (HttpConnection c in connections)
  371. c.Close(true);
  372. _unregisteredConnections.Clear();
  373. }
  374. }
  375. public void AddPrefix(ListenerPrefix prefix, HttpListener listener)
  376. {
  377. List<ListenerPrefix> current;
  378. List<ListenerPrefix> future;
  379. if (prefix.Host == "*")
  380. {
  381. do
  382. {
  383. current = _unhandledPrefixes;
  384. future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
  385. prefix._listener = listener;
  386. AddSpecial(future, prefix);
  387. } while (Interlocked.CompareExchange(ref _unhandledPrefixes, future, current) != current);
  388. return;
  389. }
  390. if (prefix.Host == "+")
  391. {
  392. do
  393. {
  394. current = _allPrefixes;
  395. future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
  396. prefix._listener = listener;
  397. AddSpecial(future, prefix);
  398. } while (Interlocked.CompareExchange(ref _allPrefixes, future, current) != current);
  399. return;
  400. }
  401. Dictionary<ListenerPrefix, HttpListener> prefs, p2;
  402. do
  403. {
  404. prefs = _prefixes;
  405. if (prefs.ContainsKey(prefix))
  406. {
  407. throw new Exception("net_listener_already");
  408. }
  409. p2 = new Dictionary<ListenerPrefix, HttpListener>(prefs);
  410. p2[prefix] = listener;
  411. } while (Interlocked.CompareExchange(ref _prefixes, p2, prefs) != prefs);
  412. }
  413. public void RemovePrefix(ListenerPrefix prefix, HttpListener listener)
  414. {
  415. List<ListenerPrefix> current;
  416. List<ListenerPrefix> future;
  417. if (prefix.Host == "*")
  418. {
  419. do
  420. {
  421. current = _unhandledPrefixes;
  422. future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
  423. if (!RemoveSpecial(future, prefix))
  424. break; // Prefix not found
  425. } while (Interlocked.CompareExchange(ref _unhandledPrefixes, future, current) != current);
  426. CheckIfRemove();
  427. return;
  428. }
  429. if (prefix.Host == "+")
  430. {
  431. do
  432. {
  433. current = _allPrefixes;
  434. future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
  435. if (!RemoveSpecial(future, prefix))
  436. break; // Prefix not found
  437. } while (Interlocked.CompareExchange(ref _allPrefixes, future, current) != current);
  438. CheckIfRemove();
  439. return;
  440. }
  441. Dictionary<ListenerPrefix, HttpListener> prefs, p2;
  442. do
  443. {
  444. prefs = _prefixes;
  445. if (!prefs.ContainsKey(prefix))
  446. break;
  447. p2 = new Dictionary<ListenerPrefix, HttpListener>(prefs);
  448. p2.Remove(prefix);
  449. } while (Interlocked.CompareExchange(ref _prefixes, p2, prefs) != prefs);
  450. CheckIfRemove();
  451. }
  452. }
  453. }