HttpEndPointListener.cs 17 KB

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