EndPointListener.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Net;
  6. using System.Threading;
  7. using MediaBrowser.Model.Cryptography;
  8. using MediaBrowser.Model.IO;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Net;
  11. using MediaBrowser.Model.System;
  12. using MediaBrowser.Model.Text;
  13. using SocketHttpListener.Primitives;
  14. namespace SocketHttpListener.Net
  15. {
  16. sealed class EndPointListener
  17. {
  18. HttpListener listener;
  19. IpEndPointInfo endpoint;
  20. IAcceptSocket sock;
  21. Dictionary<ListenerPrefix,HttpListener> prefixes; // Dictionary <ListenerPrefix, HttpListener>
  22. List<ListenerPrefix> unhandled; // List<ListenerPrefix> unhandled; host = '*'
  23. List<ListenerPrefix> all; // List<ListenerPrefix> all; host = '+'
  24. ICertificate cert;
  25. bool secure;
  26. Dictionary<HttpConnection, HttpConnection> unregistered;
  27. private readonly ILogger _logger;
  28. private bool _closed;
  29. private bool _enableDualMode;
  30. private readonly ICryptoProvider _cryptoProvider;
  31. private readonly IStreamFactory _streamFactory;
  32. private readonly ISocketFactory _socketFactory;
  33. private readonly ITextEncoding _textEncoding;
  34. private readonly IMemoryStreamFactory _memoryStreamFactory;
  35. private readonly IFileSystem _fileSystem;
  36. private readonly IEnvironmentInfo _environment;
  37. public EndPointListener(HttpListener listener, IpAddressInfo addr, int port, bool secure, ICertificate cert, ILogger logger, ICryptoProvider cryptoProvider, IStreamFactory streamFactory, ISocketFactory socketFactory, IMemoryStreamFactory memoryStreamFactory, ITextEncoding textEncoding, IFileSystem fileSystem, IEnvironmentInfo environment)
  38. {
  39. this.listener = listener;
  40. _logger = logger;
  41. _cryptoProvider = cryptoProvider;
  42. _streamFactory = streamFactory;
  43. _socketFactory = socketFactory;
  44. _memoryStreamFactory = memoryStreamFactory;
  45. _textEncoding = textEncoding;
  46. _fileSystem = fileSystem;
  47. _environment = environment;
  48. this.secure = secure;
  49. this.cert = cert;
  50. _enableDualMode = addr.Equals(IpAddressInfo.IPv6Any);
  51. endpoint = new IpEndPointInfo(addr, port);
  52. prefixes = new Dictionary<ListenerPrefix, HttpListener>();
  53. unregistered = new Dictionary<HttpConnection, HttpConnection>();
  54. CreateSocket();
  55. }
  56. internal HttpListener Listener
  57. {
  58. get
  59. {
  60. return listener;
  61. }
  62. }
  63. private void CreateSocket()
  64. {
  65. try
  66. {
  67. sock = _socketFactory.CreateSocket(endpoint.IpAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp, _enableDualMode);
  68. }
  69. catch (SocketCreateException ex)
  70. {
  71. if (_enableDualMode && endpoint.IpAddress.Equals(IpAddressInfo.IPv6Any) &&
  72. (string.Equals(ex.ErrorCode, "AddressFamilyNotSupported", StringComparison.OrdinalIgnoreCase) ||
  73. // mono on bsd is throwing this
  74. string.Equals(ex.ErrorCode, "ProtocolNotSupported", StringComparison.OrdinalIgnoreCase)))
  75. {
  76. endpoint = new IpEndPointInfo(IpAddressInfo.Any, endpoint.Port);
  77. _enableDualMode = false;
  78. sock = _socketFactory.CreateSocket(endpoint.IpAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp, _enableDualMode);
  79. }
  80. else
  81. {
  82. throw;
  83. }
  84. }
  85. sock.Bind(endpoint);
  86. // This is the number TcpListener uses.
  87. sock.Listen(2147483647);
  88. sock.StartAccept(ProcessAccept, () => _closed);
  89. _closed = false;
  90. }
  91. private async void ProcessAccept(IAcceptSocket accepted)
  92. {
  93. try
  94. {
  95. var listener = this;
  96. if (listener.secure && listener.cert == null)
  97. {
  98. accepted.Close();
  99. return;
  100. }
  101. HttpConnection conn = await HttpConnection.Create(_logger, accepted, listener, listener.secure, listener.cert, _cryptoProvider, _streamFactory, _memoryStreamFactory, _textEncoding, _fileSystem, _environment).ConfigureAwait(false);
  102. //_logger.Debug("Adding unregistered connection to {0}. Id: {1}", accepted.RemoteEndPoint, connectionId);
  103. lock (listener.unregistered)
  104. {
  105. listener.unregistered[conn] = conn;
  106. }
  107. conn.BeginReadRequest();
  108. }
  109. catch (Exception ex)
  110. {
  111. _logger.ErrorException("Error in ProcessAccept", ex);
  112. }
  113. }
  114. internal void RemoveConnection(HttpConnection conn)
  115. {
  116. lock (unregistered)
  117. {
  118. unregistered.Remove(conn);
  119. }
  120. }
  121. public bool BindContext(HttpListenerContext context)
  122. {
  123. HttpListenerRequest req = context.Request;
  124. ListenerPrefix prefix;
  125. HttpListener listener = SearchListener(req.Url, out prefix);
  126. if (listener == null)
  127. return false;
  128. context.Connection.Prefix = prefix;
  129. return true;
  130. }
  131. public void UnbindContext(HttpListenerContext context)
  132. {
  133. if (context == null || context.Request == null)
  134. return;
  135. listener.UnregisterContext(context);
  136. }
  137. HttpListener SearchListener(Uri uri, out ListenerPrefix prefix)
  138. {
  139. prefix = null;
  140. if (uri == null)
  141. return null;
  142. string host = uri.Host;
  143. int port = uri.Port;
  144. string path = WebUtility.UrlDecode(uri.AbsolutePath);
  145. string path_slash = path[path.Length - 1] == '/' ? path : path + "/";
  146. HttpListener best_match = null;
  147. int best_length = -1;
  148. if (host != null && host != "")
  149. {
  150. var p_ro = prefixes;
  151. foreach (ListenerPrefix p in p_ro.Keys)
  152. {
  153. string ppath = p.Path;
  154. if (ppath.Length < best_length)
  155. continue;
  156. if (p.Host != host || p.Port != port)
  157. continue;
  158. if (path.StartsWith(ppath) || path_slash.StartsWith(ppath))
  159. {
  160. best_length = ppath.Length;
  161. best_match = (HttpListener)p_ro[p];
  162. prefix = p;
  163. }
  164. }
  165. if (best_length != -1)
  166. return best_match;
  167. }
  168. List<ListenerPrefix> list = unhandled;
  169. best_match = MatchFromList(host, path, list, out prefix);
  170. if (path != path_slash && best_match == null)
  171. best_match = MatchFromList(host, path_slash, list, out prefix);
  172. if (best_match != null)
  173. return best_match;
  174. list = all;
  175. best_match = MatchFromList(host, path, list, out prefix);
  176. if (path != path_slash && best_match == null)
  177. best_match = MatchFromList(host, path_slash, list, out prefix);
  178. if (best_match != null)
  179. return best_match;
  180. return null;
  181. }
  182. HttpListener MatchFromList(string host, string path, List<ListenerPrefix> list, out ListenerPrefix prefix)
  183. {
  184. prefix = null;
  185. if (list == null)
  186. return null;
  187. HttpListener best_match = null;
  188. int best_length = -1;
  189. foreach (ListenerPrefix p in list)
  190. {
  191. string ppath = p.Path;
  192. if (ppath.Length < best_length)
  193. continue;
  194. if (path.StartsWith(ppath))
  195. {
  196. best_length = ppath.Length;
  197. best_match = p.Listener;
  198. prefix = p;
  199. }
  200. }
  201. return best_match;
  202. }
  203. void AddSpecial(List<ListenerPrefix> coll, ListenerPrefix prefix)
  204. {
  205. if (coll == null)
  206. return;
  207. foreach (ListenerPrefix p in coll)
  208. {
  209. if (p.Path == prefix.Path) //TODO: code
  210. throw new HttpListenerException(400, "Prefix already in use.");
  211. }
  212. coll.Add(prefix);
  213. }
  214. bool RemoveSpecial(List<ListenerPrefix> coll, ListenerPrefix prefix)
  215. {
  216. if (coll == null)
  217. return false;
  218. int c = coll.Count;
  219. for (int i = 0; i < c; i++)
  220. {
  221. ListenerPrefix p = (ListenerPrefix)coll[i];
  222. if (p.Path == prefix.Path)
  223. {
  224. coll.RemoveAt(i);
  225. return true;
  226. }
  227. }
  228. return false;
  229. }
  230. void CheckIfRemove()
  231. {
  232. if (prefixes.Count > 0)
  233. return;
  234. List<ListenerPrefix> list = unhandled;
  235. if (list != null && list.Count > 0)
  236. return;
  237. list = all;
  238. if (list != null && list.Count > 0)
  239. return;
  240. EndPointManager.RemoveEndPoint(this, endpoint);
  241. }
  242. public void Close()
  243. {
  244. _closed = true;
  245. sock.Close();
  246. lock (unregistered)
  247. {
  248. //
  249. // Clone the list because RemoveConnection can be called from Close
  250. //
  251. var connections = new List<HttpConnection>(unregistered.Keys);
  252. foreach (HttpConnection c in connections)
  253. c.Close(true);
  254. unregistered.Clear();
  255. }
  256. }
  257. public void AddPrefix(ListenerPrefix prefix, HttpListener listener)
  258. {
  259. List<ListenerPrefix> current;
  260. List<ListenerPrefix> future;
  261. if (prefix.Host == "*")
  262. {
  263. do
  264. {
  265. current = unhandled;
  266. future = (current != null) ? current.ToList() : new List<ListenerPrefix>();
  267. prefix.Listener = listener;
  268. AddSpecial(future, prefix);
  269. } while (Interlocked.CompareExchange(ref unhandled, future, current) != current);
  270. return;
  271. }
  272. if (prefix.Host == "+")
  273. {
  274. do
  275. {
  276. current = all;
  277. future = (current != null) ? current.ToList() : new List<ListenerPrefix>();
  278. prefix.Listener = listener;
  279. AddSpecial(future, prefix);
  280. } while (Interlocked.CompareExchange(ref all, future, current) != current);
  281. return;
  282. }
  283. Dictionary<ListenerPrefix, HttpListener> prefs;
  284. Dictionary<ListenerPrefix, HttpListener> p2;
  285. do
  286. {
  287. prefs = prefixes;
  288. if (prefs.ContainsKey(prefix))
  289. {
  290. HttpListener other = (HttpListener)prefs[prefix];
  291. if (other != listener) // TODO: code.
  292. throw new HttpListenerException(400, "There's another listener for " + prefix);
  293. return;
  294. }
  295. p2 = new Dictionary<ListenerPrefix, HttpListener>(prefs);
  296. p2[prefix] = listener;
  297. } while (Interlocked.CompareExchange(ref prefixes, p2, prefs) != prefs);
  298. }
  299. public void RemovePrefix(ListenerPrefix prefix, HttpListener listener)
  300. {
  301. List<ListenerPrefix> current;
  302. List<ListenerPrefix> future;
  303. if (prefix.Host == "*")
  304. {
  305. do
  306. {
  307. current = unhandled;
  308. future = (current != null) ? current.ToList() : new List<ListenerPrefix>();
  309. if (!RemoveSpecial(future, prefix))
  310. break; // Prefix not found
  311. } while (Interlocked.CompareExchange(ref unhandled, future, current) != current);
  312. CheckIfRemove();
  313. return;
  314. }
  315. if (prefix.Host == "+")
  316. {
  317. do
  318. {
  319. current = all;
  320. future = (current != null) ? current.ToList() : new List<ListenerPrefix>();
  321. if (!RemoveSpecial(future, prefix))
  322. break; // Prefix not found
  323. } while (Interlocked.CompareExchange(ref all, future, current) != current);
  324. CheckIfRemove();
  325. return;
  326. }
  327. Dictionary<ListenerPrefix, HttpListener> prefs;
  328. Dictionary<ListenerPrefix, HttpListener> p2;
  329. do
  330. {
  331. prefs = prefixes;
  332. if (!prefs.ContainsKey(prefix))
  333. break;
  334. p2 = new Dictionary<ListenerPrefix, HttpListener>(prefs);
  335. p2.Remove(prefix);
  336. } while (Interlocked.CompareExchange(ref prefixes, p2, prefs) != prefs);
  337. CheckIfRemove();
  338. }
  339. }
  340. }