EndPointListener.cs 14 KB

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