HttpEndPointManager.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. List<string> 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. int port;
  55. if (!int.TryParse(portString, out port) || port <= 0 || port >= 65536)
  56. {
  57. throw new HttpListenerException((int)HttpStatusCode.BadRequest, "net_invalid_port");
  58. }
  59. }
  60. ListenerPrefix lp = new ListenerPrefix(p);
  61. if (lp.Host != "*" && lp.Host != "+" && Uri.CheckHostName(lp.Host) == UriHostNameType.Unknown)
  62. throw new HttpListenerException((int)HttpStatusCode.BadRequest, "net_listener_host");
  63. if (lp.Path.IndexOf('%') != -1)
  64. throw new HttpListenerException((int)HttpStatusCode.BadRequest, "net_invalid_path");
  65. if (lp.Path.IndexOf("//", StringComparison.Ordinal) != -1)
  66. throw new HttpListenerException((int)HttpStatusCode.BadRequest, "net_invalid_path");
  67. // listens on all the interfaces if host name cannot be parsed by IPAddress.
  68. HttpEndPointListener epl = GetEPListener(logger, lp.Host, lp.Port, listener, lp.Secure);
  69. epl.AddPrefix(lp, listener);
  70. }
  71. private static IPAddress GetIpAnyAddress(HttpListener listener)
  72. {
  73. return listener.EnableDualMode ? IPAddress.IPv6Any : IPAddress.Any;
  74. }
  75. private static HttpEndPointListener GetEPListener(ILogger logger, string host, int port, HttpListener listener, bool secure)
  76. {
  77. IPAddress addr;
  78. if (host == "*" || host == "+")
  79. {
  80. addr = GetIpAnyAddress(listener);
  81. }
  82. else
  83. {
  84. const int NotSupportedErrorCode = 50;
  85. try
  86. {
  87. addr = Dns.GetHostAddresses(host)[0];
  88. }
  89. catch
  90. {
  91. // Throw same error code as windows, request is not supported.
  92. throw new HttpListenerException(NotSupportedErrorCode, "net_listener_not_supported");
  93. }
  94. if (IPAddress.Any.Equals(addr))
  95. {
  96. // Don't support listening to 0.0.0.0, match windows behavior.
  97. throw new HttpListenerException(NotSupportedErrorCode, "net_listener_not_supported");
  98. }
  99. }
  100. Dictionary<int, HttpEndPointListener> p = null;
  101. if (s_ipEndPoints.ContainsKey(addr))
  102. {
  103. p = s_ipEndPoints[addr];
  104. }
  105. else
  106. {
  107. p = new Dictionary<int, HttpEndPointListener>();
  108. s_ipEndPoints[addr] = p;
  109. }
  110. HttpEndPointListener epl = null;
  111. if (p.ContainsKey(port))
  112. {
  113. epl = p[port];
  114. }
  115. else
  116. {
  117. try
  118. {
  119. epl = new HttpEndPointListener(listener, addr, port, secure, listener.Certificate, logger, listener.CryptoProvider, listener.SocketFactory, listener.StreamHelper, listener.TextEncoding, listener.FileSystem, listener.EnvironmentInfo);
  120. }
  121. catch (SocketException ex)
  122. {
  123. throw new HttpListenerException(ex.ErrorCode, ex.Message);
  124. }
  125. p[port] = epl;
  126. }
  127. return epl;
  128. }
  129. public static void RemoveEndPoint(HttpEndPointListener epl, IPEndPoint ep)
  130. {
  131. lock ((s_ipEndPoints as ICollection).SyncRoot)
  132. {
  133. Dictionary<int, HttpEndPointListener> p = null;
  134. p = s_ipEndPoints[ep.Address];
  135. p.Remove(ep.Port);
  136. if (p.Count == 0)
  137. {
  138. s_ipEndPoints.Remove(ep.Address);
  139. }
  140. epl.Close();
  141. }
  142. }
  143. public static void RemoveListener(ILogger logger, HttpListener listener)
  144. {
  145. lock ((s_ipEndPoints as ICollection).SyncRoot)
  146. {
  147. foreach (string prefix in listener.Prefixes)
  148. {
  149. RemovePrefixInternal(logger, prefix, listener);
  150. }
  151. }
  152. }
  153. public static void RemovePrefix(ILogger logger, string prefix, HttpListener listener)
  154. {
  155. lock ((s_ipEndPoints as ICollection).SyncRoot)
  156. {
  157. RemovePrefixInternal(logger, prefix, listener);
  158. }
  159. }
  160. private static void RemovePrefixInternal(ILogger logger, string prefix, HttpListener listener)
  161. {
  162. ListenerPrefix lp = new ListenerPrefix(prefix);
  163. if (lp.Path.IndexOf('%') != -1)
  164. return;
  165. if (lp.Path.IndexOf("//", StringComparison.Ordinal) != -1)
  166. return;
  167. HttpEndPointListener epl = GetEPListener(logger, lp.Host, lp.Port, listener, lp.Secure);
  168. epl.RemovePrefix(lp, listener);
  169. }
  170. }
  171. }