HttpEndPointListener.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. // TODO Investigate or properly fix.
  149. }
  150. catch (Exception ex)
  151. {
  152. HttpEndPointListener epl = (HttpEndPointListener)acceptEventArg.UserToken;
  153. epl._logger.LogError(ex, "Error in socket.AcceptAsync");
  154. }
  155. }
  156. // This method is the callback method associated with Socket.AcceptAsync
  157. // operations and is invoked when an accept operation is complete
  158. //
  159. private static void OnAccept(object sender, SocketAsyncEventArgs e)
  160. {
  161. ProcessAccept(e);
  162. }
  163. private static async void ProcessAccept(SocketAsyncEventArgs args)
  164. {
  165. HttpEndPointListener epl = (HttpEndPointListener)args.UserToken;
  166. if (epl._closed)
  167. {
  168. return;
  169. }
  170. // http://msdn.microsoft.com/en-us/library/system.net.sockets.acceptSocket.acceptasync%28v=vs.110%29.aspx
  171. // Under certain conditions ConnectionReset can occur
  172. // Need to attept to re-accept
  173. var socketError = args.SocketError;
  174. var accepted = args.AcceptSocket;
  175. epl.Accept(args);
  176. if (socketError == SocketError.ConnectionReset)
  177. {
  178. epl._logger.LogError("SocketError.ConnectionReset reported. Attempting to re-accept.");
  179. return;
  180. }
  181. if(accepted == null)
  182. {
  183. return;
  184. }
  185. if (epl._secure && epl._cert == null)
  186. {
  187. TryClose(accepted);
  188. return;
  189. }
  190. try
  191. {
  192. var remoteEndPointString = accepted.RemoteEndPoint == null ? string.Empty : accepted.RemoteEndPoint.ToString();
  193. var localEndPointString = accepted.LocalEndPoint == null ? string.Empty : accepted.LocalEndPoint.ToString();
  194. //_logger.LogInformation("HttpEndPointListener Accepting connection from {0} to {1} secure connection requested: {2}", remoteEndPointString, localEndPointString, _secure);
  195. HttpConnection conn = new HttpConnection(epl._logger, accepted, epl, epl._secure, epl._cert, epl._cryptoProvider, epl._streamHelper, epl._textEncoding, epl._fileSystem, epl._environment);
  196. await conn.Init().ConfigureAwait(false);
  197. //_logger.LogDebug("Adding unregistered connection to {0}. Id: {1}", accepted.RemoteEndPoint, connectionId);
  198. lock (epl._unregisteredConnections)
  199. {
  200. epl._unregisteredConnections[conn] = conn;
  201. }
  202. conn.BeginReadRequest();
  203. }
  204. catch (Exception ex)
  205. {
  206. epl._logger.LogError(ex, "Error in ProcessAccept");
  207. TryClose(accepted);
  208. epl.Accept();
  209. return;
  210. }
  211. }
  212. private Socket CreateSocket(AddressFamily addressFamily, bool dualMode)
  213. {
  214. try
  215. {
  216. var socket = new Socket(addressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
  217. if (dualMode)
  218. {
  219. socket.DualMode = true;
  220. }
  221. return socket;
  222. }
  223. catch (SocketException ex)
  224. {
  225. throw new SocketCreateException(ex.SocketErrorCode.ToString(), ex);
  226. }
  227. catch (ArgumentException ex)
  228. {
  229. if (dualMode)
  230. {
  231. // Mono for BSD incorrectly throws ArgumentException instead of SocketException
  232. throw new SocketCreateException("AddressFamilyNotSupported", ex);
  233. }
  234. else
  235. {
  236. throw;
  237. }
  238. }
  239. }
  240. internal void RemoveConnection(HttpConnection conn)
  241. {
  242. lock (_unregisteredConnections)
  243. {
  244. _unregisteredConnections.Remove(conn);
  245. }
  246. }
  247. public bool BindContext(HttpListenerContext context)
  248. {
  249. HttpListenerRequest req = context.Request;
  250. ListenerPrefix prefix;
  251. HttpListener listener = SearchListener(req.Url, out prefix);
  252. if (listener == null)
  253. return false;
  254. context.Connection.Prefix = prefix;
  255. return true;
  256. }
  257. public void UnbindContext(HttpListenerContext context)
  258. {
  259. if (context == null || context.Request == null)
  260. return;
  261. _listener.UnregisterContext(context);
  262. }
  263. private HttpListener SearchListener(Uri uri, out ListenerPrefix prefix)
  264. {
  265. prefix = null;
  266. if (uri == null)
  267. return null;
  268. string host = uri.Host;
  269. int port = uri.Port;
  270. string path = WebUtility.UrlDecode(uri.AbsolutePath);
  271. string pathSlash = path[path.Length - 1] == '/' ? path : path + "/";
  272. HttpListener bestMatch = null;
  273. int bestLength = -1;
  274. if (host != null && host != "")
  275. {
  276. Dictionary<ListenerPrefix, HttpListener> localPrefixes = _prefixes;
  277. foreach (ListenerPrefix p in localPrefixes.Keys)
  278. {
  279. string ppath = p.Path;
  280. if (ppath.Length < bestLength)
  281. continue;
  282. if (p.Host != host || p.Port != port)
  283. continue;
  284. if (path.StartsWith(ppath) || pathSlash.StartsWith(ppath))
  285. {
  286. bestLength = ppath.Length;
  287. bestMatch = localPrefixes[p];
  288. prefix = p;
  289. }
  290. }
  291. if (bestLength != -1)
  292. return bestMatch;
  293. }
  294. List<ListenerPrefix> list = _unhandledPrefixes;
  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. list = _allPrefixes;
  301. bestMatch = MatchFromList(host, path, list, out prefix);
  302. if (path != pathSlash && bestMatch == null)
  303. bestMatch = MatchFromList(host, pathSlash, list, out prefix);
  304. if (bestMatch != null)
  305. return bestMatch;
  306. return null;
  307. }
  308. private HttpListener MatchFromList(string host, string path, List<ListenerPrefix> list, out ListenerPrefix prefix)
  309. {
  310. prefix = null;
  311. if (list == null)
  312. return null;
  313. HttpListener bestMatch = null;
  314. int bestLength = -1;
  315. foreach (ListenerPrefix p in list)
  316. {
  317. string ppath = p.Path;
  318. if (ppath.Length < bestLength)
  319. continue;
  320. if (path.StartsWith(ppath))
  321. {
  322. bestLength = ppath.Length;
  323. bestMatch = p._listener;
  324. prefix = p;
  325. }
  326. }
  327. return bestMatch;
  328. }
  329. private void AddSpecial(List<ListenerPrefix> list, ListenerPrefix prefix)
  330. {
  331. if (list == null)
  332. return;
  333. foreach (ListenerPrefix p in list)
  334. {
  335. if (p.Path == prefix.Path)
  336. throw new Exception("net_listener_already");
  337. }
  338. list.Add(prefix);
  339. }
  340. private bool RemoveSpecial(List<ListenerPrefix> list, ListenerPrefix prefix)
  341. {
  342. if (list == null)
  343. return false;
  344. int c = list.Count;
  345. for (int i = 0; i < c; i++)
  346. {
  347. ListenerPrefix p = list[i];
  348. if (p.Path == prefix.Path)
  349. {
  350. list.RemoveAt(i);
  351. return true;
  352. }
  353. }
  354. return false;
  355. }
  356. private void CheckIfRemove()
  357. {
  358. if (_prefixes.Count > 0)
  359. return;
  360. List<ListenerPrefix> list = _unhandledPrefixes;
  361. if (list != null && list.Count > 0)
  362. return;
  363. list = _allPrefixes;
  364. if (list != null && list.Count > 0)
  365. return;
  366. HttpEndPointManager.RemoveEndPoint(this, _endpoint);
  367. }
  368. public void Close()
  369. {
  370. _closed = true;
  371. _socket.Close();
  372. lock (_unregisteredConnections)
  373. {
  374. // Clone the list because RemoveConnection can be called from Close
  375. var connections = new List<HttpConnection>(_unregisteredConnections.Keys);
  376. foreach (HttpConnection c in connections)
  377. c.Close(true);
  378. _unregisteredConnections.Clear();
  379. }
  380. }
  381. public void AddPrefix(ListenerPrefix prefix, HttpListener listener)
  382. {
  383. List<ListenerPrefix> current;
  384. List<ListenerPrefix> future;
  385. if (prefix.Host == "*")
  386. {
  387. do
  388. {
  389. current = _unhandledPrefixes;
  390. future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
  391. prefix._listener = listener;
  392. AddSpecial(future, prefix);
  393. } while (Interlocked.CompareExchange(ref _unhandledPrefixes, future, current) != current);
  394. return;
  395. }
  396. if (prefix.Host == "+")
  397. {
  398. do
  399. {
  400. current = _allPrefixes;
  401. future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
  402. prefix._listener = listener;
  403. AddSpecial(future, prefix);
  404. } while (Interlocked.CompareExchange(ref _allPrefixes, future, current) != current);
  405. return;
  406. }
  407. Dictionary<ListenerPrefix, HttpListener> prefs, p2;
  408. do
  409. {
  410. prefs = _prefixes;
  411. if (prefs.ContainsKey(prefix))
  412. {
  413. throw new Exception("net_listener_already");
  414. }
  415. p2 = new Dictionary<ListenerPrefix, HttpListener>(prefs);
  416. p2[prefix] = listener;
  417. } while (Interlocked.CompareExchange(ref _prefixes, p2, prefs) != prefs);
  418. }
  419. public void RemovePrefix(ListenerPrefix prefix, HttpListener listener)
  420. {
  421. List<ListenerPrefix> current;
  422. List<ListenerPrefix> future;
  423. if (prefix.Host == "*")
  424. {
  425. do
  426. {
  427. current = _unhandledPrefixes;
  428. future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
  429. if (!RemoveSpecial(future, prefix))
  430. break; // Prefix not found
  431. } while (Interlocked.CompareExchange(ref _unhandledPrefixes, future, current) != current);
  432. CheckIfRemove();
  433. return;
  434. }
  435. if (prefix.Host == "+")
  436. {
  437. do
  438. {
  439. current = _allPrefixes;
  440. future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
  441. if (!RemoveSpecial(future, prefix))
  442. break; // Prefix not found
  443. } while (Interlocked.CompareExchange(ref _allPrefixes, future, current) != current);
  444. CheckIfRemove();
  445. return;
  446. }
  447. Dictionary<ListenerPrefix, HttpListener> prefs, p2;
  448. do
  449. {
  450. prefs = _prefixes;
  451. if (!prefs.ContainsKey(prefix))
  452. break;
  453. p2 = new Dictionary<ListenerPrefix, HttpListener>(prefs);
  454. p2.Remove(prefix);
  455. } while (Interlocked.CompareExchange(ref _prefixes, p2, prefs) != prefs);
  456. CheckIfRemove();
  457. }
  458. }
  459. }