HttpEndPointManager.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using Microsoft.Extensions.Logging;
  7. namespace SocketHttpListener.Net
  8. {
  9. internal sealed class HttpEndPointManager
  10. {
  11. private static Dictionary<IPAddress, Dictionary<int, HttpEndPointListener>> s_ipEndPoints = new Dictionary<IPAddress, Dictionary<int, HttpEndPointListener>>();
  12. private HttpEndPointManager()
  13. {
  14. }
  15. public static void AddListener(ILogger logger, HttpListener listener)
  16. {
  17. var added = new List<string>();
  18. try
  19. {
  20. lock ((s_ipEndPoints as ICollection).SyncRoot)
  21. {
  22. foreach (string prefix in listener.Prefixes)
  23. {
  24. AddPrefixInternal(logger, prefix, listener);
  25. added.Add(prefix);
  26. }
  27. }
  28. }
  29. catch
  30. {
  31. foreach (string prefix in added)
  32. {
  33. RemovePrefix(logger, prefix, listener);
  34. }
  35. throw;
  36. }
  37. }
  38. public static void AddPrefix(ILogger logger, string prefix, HttpListener listener)
  39. {
  40. lock ((s_ipEndPoints as ICollection).SyncRoot)
  41. {
  42. AddPrefixInternal(logger, prefix, listener);
  43. }
  44. }
  45. private static void AddPrefixInternal(ILogger logger, string p, HttpListener listener)
  46. {
  47. int start = p.IndexOf(':') + 3;
  48. int colon = p.IndexOf(':', start);
  49. if (colon != -1)
  50. {
  51. // root can't be -1 here, since we've already checked for ending '/' in ListenerPrefix.
  52. int root = p.IndexOf('/', colon, p.Length - colon);
  53. string portString = p.Substring(colon + 1, root - colon - 1);
  54. if (!int.TryParse(portString, out var port) || port <= 0 || port >= 65536)
  55. {
  56. throw new HttpListenerException((int)HttpStatusCode.BadRequest, "net_invalid_port");
  57. }
  58. }
  59. var lp = new ListenerPrefix(p);
  60. if (lp.Host != "*" && lp.Host != "+" && Uri.CheckHostName(lp.Host) == UriHostNameType.Unknown)
  61. throw new HttpListenerException((int)HttpStatusCode.BadRequest, "net_listener_host");
  62. if (lp.Path.IndexOf('%') != -1)
  63. throw new HttpListenerException((int)HttpStatusCode.BadRequest, "net_invalid_path");
  64. if (lp.Path.IndexOf("//", StringComparison.Ordinal) != -1)
  65. throw new HttpListenerException((int)HttpStatusCode.BadRequest, "net_invalid_path");
  66. // listens on all the interfaces if host name cannot be parsed by IPAddress.
  67. HttpEndPointListener epl = GetEPListener(logger, lp.Host, lp.Port, listener, lp.Secure);
  68. epl.AddPrefix(lp, listener);
  69. }
  70. private static IPAddress GetIpAnyAddress(HttpListener listener)
  71. {
  72. return listener.EnableDualMode ? IPAddress.IPv6Any : IPAddress.Any;
  73. }
  74. private static HttpEndPointListener GetEPListener(ILogger logger, string host, int port, HttpListener listener, bool secure)
  75. {
  76. IPAddress addr;
  77. if (host == "*" || host == "+")
  78. {
  79. addr = GetIpAnyAddress(listener);
  80. }
  81. else
  82. {
  83. const int NotSupportedErrorCode = 50;
  84. try
  85. {
  86. addr = Dns.GetHostAddresses(host)[0];
  87. }
  88. catch
  89. {
  90. // Throw same error code as windows, request is not supported.
  91. throw new HttpListenerException(NotSupportedErrorCode, "net_listener_not_supported");
  92. }
  93. if (IPAddress.Any.Equals(addr))
  94. {
  95. // Don't support listening to 0.0.0.0, match windows behavior.
  96. throw new HttpListenerException(NotSupportedErrorCode, "net_listener_not_supported");
  97. }
  98. }
  99. Dictionary<int, HttpEndPointListener> p = null;
  100. if (s_ipEndPoints.ContainsKey(addr))
  101. {
  102. p = s_ipEndPoints[addr];
  103. }
  104. else
  105. {
  106. p = new Dictionary<int, HttpEndPointListener>();
  107. s_ipEndPoints[addr] = p;
  108. }
  109. HttpEndPointListener epl = null;
  110. if (p.ContainsKey(port))
  111. {
  112. epl = p[port];
  113. }
  114. else
  115. {
  116. try
  117. {
  118. epl = new HttpEndPointListener(listener, addr, port, secure, listener.Certificate, logger, listener.CryptoProvider, listener.SocketFactory, listener.StreamHelper, listener.TextEncoding, listener.FileSystem, listener.EnvironmentInfo);
  119. }
  120. catch (SocketException ex)
  121. {
  122. throw new HttpListenerException(ex.ErrorCode, ex.Message);
  123. }
  124. p[port] = epl;
  125. }
  126. return epl;
  127. }
  128. public static void RemoveEndPoint(HttpEndPointListener epl, IPEndPoint ep)
  129. {
  130. lock ((s_ipEndPoints as ICollection).SyncRoot)
  131. {
  132. Dictionary<int, HttpEndPointListener> p = null;
  133. p = s_ipEndPoints[ep.Address];
  134. p.Remove(ep.Port);
  135. if (p.Count == 0)
  136. {
  137. s_ipEndPoints.Remove(ep.Address);
  138. }
  139. epl.Close();
  140. }
  141. }
  142. public static void RemoveListener(ILogger logger, HttpListener listener)
  143. {
  144. lock ((s_ipEndPoints as ICollection).SyncRoot)
  145. {
  146. foreach (string prefix in listener.Prefixes)
  147. {
  148. RemovePrefixInternal(logger, prefix, listener);
  149. }
  150. }
  151. }
  152. public static void RemovePrefix(ILogger logger, string prefix, HttpListener listener)
  153. {
  154. lock ((s_ipEndPoints as ICollection).SyncRoot)
  155. {
  156. RemovePrefixInternal(logger, prefix, listener);
  157. }
  158. }
  159. private static void RemovePrefixInternal(ILogger logger, string prefix, HttpListener listener)
  160. {
  161. var lp = new ListenerPrefix(prefix);
  162. if (lp.Path.IndexOf('%') != -1)
  163. return;
  164. if (lp.Path.IndexOf("//", StringComparison.Ordinal) != -1)
  165. return;
  166. HttpEndPointListener epl = GetEPListener(logger, lp.Host, lp.Port, listener, lp.Secure);
  167. epl.RemovePrefix(lp, listener);
  168. }
  169. }
  170. }