HttpEndPointListener.cs 18 KB

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