2
0

HttpEndPointListener.cs 17 KB

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