EndPointListener.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. #region License
  2. /*
  3. * EndPointListener.cs
  4. *
  5. * This code is derived from EndPointListener.cs (System.Net) of Mono
  6. * (http://www.mono-project.com).
  7. *
  8. * The MIT License
  9. *
  10. * Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
  11. * Copyright (c) 2012-2020 sta.blockhead
  12. *
  13. * Permission is hereby granted, free of charge, to any person obtaining a copy
  14. * of this software and associated documentation files (the "Software"), to deal
  15. * in the Software without restriction, including without limitation the rights
  16. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17. * copies of the Software, and to permit persons to whom the Software is
  18. * furnished to do so, subject to the following conditions:
  19. *
  20. * The above copyright notice and this permission notice shall be included in
  21. * all copies or substantial portions of the Software.
  22. *
  23. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  24. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  25. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  26. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  27. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  28. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  29. * THE SOFTWARE.
  30. */
  31. #endregion
  32. #region Authors
  33. /*
  34. * Authors:
  35. * - Gonzalo Paniagua Javier <gonzalo@novell.com>
  36. */
  37. #endregion
  38. #region Contributors
  39. /*
  40. * Contributors:
  41. * - Liryna <liryna.stark@gmail.com>
  42. * - Nicholas Devenish
  43. */
  44. #endregion
  45. using System;
  46. using System.Collections;
  47. using System.Collections.Generic;
  48. using System.IO;
  49. using System.Net;
  50. using System.Net.Sockets;
  51. using System.Security.Cryptography;
  52. using System.Security.Cryptography.X509Certificates;
  53. using System.Threading;
  54. namespace WebSocketSharp.Net
  55. {
  56. internal sealed class EndPointListener
  57. {
  58. #region Private Fields
  59. private List<HttpListenerPrefix> _all; // host == '+'
  60. private Dictionary<HttpConnection, HttpConnection> _connections;
  61. private object _connectionsSync;
  62. private static readonly string _defaultCertFolderPath;
  63. private IPEndPoint _endpoint;
  64. private List<HttpListenerPrefix> _prefixes;
  65. private bool _secure;
  66. private Socket _socket;
  67. private ServerSslConfiguration _sslConfig;
  68. private List<HttpListenerPrefix> _unhandled; // host == '*'
  69. #endregion
  70. #region Static Constructor
  71. static EndPointListener ()
  72. {
  73. _defaultCertFolderPath = Environment.GetFolderPath (
  74. Environment.SpecialFolder.ApplicationData
  75. );
  76. }
  77. #endregion
  78. #region Internal Constructors
  79. internal EndPointListener (
  80. IPEndPoint endpoint,
  81. bool secure,
  82. string certificateFolderPath,
  83. ServerSslConfiguration sslConfig,
  84. bool reuseAddress
  85. )
  86. {
  87. _endpoint = endpoint;
  88. if (secure) {
  89. var cert = getCertificate (
  90. endpoint.Port,
  91. certificateFolderPath,
  92. sslConfig.ServerCertificate
  93. );
  94. if (cert == null) {
  95. var msg = "No server certificate could be found.";
  96. throw new ArgumentException (msg);
  97. }
  98. _secure = true;
  99. _sslConfig = new ServerSslConfiguration (sslConfig);
  100. _sslConfig.ServerCertificate = cert;
  101. }
  102. _prefixes = new List<HttpListenerPrefix> ();
  103. _connections = new Dictionary<HttpConnection, HttpConnection> ();
  104. _connectionsSync = ((ICollection) _connections).SyncRoot;
  105. _socket = new Socket (
  106. endpoint.Address.AddressFamily,
  107. SocketType.Stream,
  108. ProtocolType.Tcp
  109. );
  110. if (reuseAddress) {
  111. _socket.SetSocketOption (
  112. SocketOptionLevel.Socket,
  113. SocketOptionName.ReuseAddress,
  114. true
  115. );
  116. }
  117. _socket.Bind (endpoint);
  118. _socket.Listen (500);
  119. _socket.BeginAccept (onAccept, this);
  120. }
  121. #endregion
  122. #region Public Properties
  123. public IPAddress Address {
  124. get {
  125. return _endpoint.Address;
  126. }
  127. }
  128. public bool IsSecure {
  129. get {
  130. return _secure;
  131. }
  132. }
  133. public int Port {
  134. get {
  135. return _endpoint.Port;
  136. }
  137. }
  138. public ServerSslConfiguration SslConfiguration {
  139. get {
  140. return _sslConfig;
  141. }
  142. }
  143. #endregion
  144. #region Private Methods
  145. private static void addSpecial (
  146. List<HttpListenerPrefix> prefixes, HttpListenerPrefix prefix
  147. )
  148. {
  149. var path = prefix.Path;
  150. foreach (var pref in prefixes) {
  151. if (pref.Path == path) {
  152. var msg = "The prefix is already in use.";
  153. throw new HttpListenerException (87, msg);
  154. }
  155. }
  156. prefixes.Add (prefix);
  157. }
  158. private void clearConnections ()
  159. {
  160. HttpConnection[] conns = null;
  161. lock (_connectionsSync) {
  162. var cnt = _connections.Count;
  163. if (cnt == 0)
  164. return;
  165. conns = new HttpConnection[cnt];
  166. var vals = _connections.Values;
  167. vals.CopyTo (conns, 0);
  168. _connections.Clear ();
  169. }
  170. foreach (var conn in conns)
  171. conn.Close (true);
  172. }
  173. private static RSACryptoServiceProvider createRSAFromFile (string path)
  174. {
  175. var rsa = new RSACryptoServiceProvider ();
  176. var key = File.ReadAllBytes (path);
  177. rsa.ImportCspBlob (key);
  178. return rsa;
  179. }
  180. private static X509Certificate2 getCertificate (
  181. int port, string folderPath, X509Certificate2 defaultCertificate
  182. )
  183. {
  184. if (folderPath == null || folderPath.Length == 0)
  185. folderPath = _defaultCertFolderPath;
  186. try {
  187. var cer = Path.Combine (folderPath, String.Format ("{0}.cer", port));
  188. var key = Path.Combine (folderPath, String.Format ("{0}.key", port));
  189. if (File.Exists (cer) && File.Exists (key)) {
  190. var cert = new X509Certificate2 (cer);
  191. cert.PrivateKey = createRSAFromFile (key);
  192. return cert;
  193. }
  194. }
  195. catch {
  196. }
  197. return defaultCertificate;
  198. }
  199. private void leaveIfNoPrefix ()
  200. {
  201. if (_prefixes.Count > 0)
  202. return;
  203. var prefs = _unhandled;
  204. if (prefs != null && prefs.Count > 0)
  205. return;
  206. prefs = _all;
  207. if (prefs != null && prefs.Count > 0)
  208. return;
  209. Close ();
  210. }
  211. private static void onAccept (IAsyncResult asyncResult)
  212. {
  213. var lsnr = (EndPointListener) asyncResult.AsyncState;
  214. Socket sock = null;
  215. try {
  216. sock = lsnr._socket.EndAccept (asyncResult);
  217. }
  218. catch (ObjectDisposedException) {
  219. return;
  220. }
  221. catch (Exception) {
  222. // TODO: Logging.
  223. }
  224. try {
  225. lsnr._socket.BeginAccept (onAccept, lsnr);
  226. }
  227. catch (Exception) {
  228. // TODO: Logging.
  229. if (sock != null)
  230. sock.Close ();
  231. return;
  232. }
  233. if (sock == null)
  234. return;
  235. processAccepted (sock, lsnr);
  236. }
  237. private static void processAccepted (
  238. Socket socket, EndPointListener listener
  239. )
  240. {
  241. HttpConnection conn = null;
  242. try {
  243. conn = new HttpConnection (socket, listener);
  244. }
  245. catch (Exception) {
  246. // TODO: Logging.
  247. socket.Close ();
  248. return;
  249. }
  250. lock (listener._connectionsSync)
  251. listener._connections.Add (conn, conn);
  252. conn.BeginReadRequest ();
  253. }
  254. private static bool removeSpecial (
  255. List<HttpListenerPrefix> prefixes, HttpListenerPrefix prefix
  256. )
  257. {
  258. var path = prefix.Path;
  259. var cnt = prefixes.Count;
  260. for (var i = 0; i < cnt; i++) {
  261. if (prefixes[i].Path == path) {
  262. prefixes.RemoveAt (i);
  263. return true;
  264. }
  265. }
  266. return false;
  267. }
  268. private static HttpListener searchHttpListenerFromSpecial (
  269. string path, List<HttpListenerPrefix> prefixes
  270. )
  271. {
  272. if (prefixes == null)
  273. return null;
  274. HttpListener ret = null;
  275. var bestLen = -1;
  276. foreach (var pref in prefixes) {
  277. var prefPath = pref.Path;
  278. var len = prefPath.Length;
  279. if (len < bestLen)
  280. continue;
  281. if (path.StartsWith (prefPath, StringComparison.Ordinal)) {
  282. bestLen = len;
  283. ret = pref.Listener;
  284. }
  285. }
  286. return ret;
  287. }
  288. #endregion
  289. #region Internal Methods
  290. internal static bool CertificateExists (int port, string folderPath)
  291. {
  292. if (folderPath == null || folderPath.Length == 0)
  293. folderPath = _defaultCertFolderPath;
  294. var cer = Path.Combine (folderPath, String.Format ("{0}.cer", port));
  295. var key = Path.Combine (folderPath, String.Format ("{0}.key", port));
  296. return File.Exists (cer) && File.Exists (key);
  297. }
  298. internal void RemoveConnection (HttpConnection connection)
  299. {
  300. lock (_connectionsSync)
  301. _connections.Remove (connection);
  302. }
  303. internal bool TrySearchHttpListener (Uri uri, out HttpListener listener)
  304. {
  305. listener = null;
  306. if (uri == null)
  307. return false;
  308. var host = uri.Host;
  309. var dns = Uri.CheckHostName (host) == UriHostNameType.Dns;
  310. var port = uri.Port.ToString ();
  311. var path = HttpUtility.UrlDecode (uri.AbsolutePath);
  312. if (path[path.Length - 1] != '/')
  313. path += "/";
  314. if (host != null && host.Length > 0) {
  315. var prefs = _prefixes;
  316. var bestLen = -1;
  317. foreach (var pref in prefs) {
  318. if (dns) {
  319. var prefHost = pref.Host;
  320. var prefDns = Uri.CheckHostName (prefHost) == UriHostNameType.Dns;
  321. if (prefDns) {
  322. if (prefHost != host)
  323. continue;
  324. }
  325. }
  326. if (pref.Port != port)
  327. continue;
  328. var prefPath = pref.Path;
  329. var len = prefPath.Length;
  330. if (len < bestLen)
  331. continue;
  332. if (path.StartsWith (prefPath, StringComparison.Ordinal)) {
  333. bestLen = len;
  334. listener = pref.Listener;
  335. }
  336. }
  337. if (bestLen != -1)
  338. return true;
  339. }
  340. listener = searchHttpListenerFromSpecial (path, _unhandled);
  341. if (listener != null)
  342. return true;
  343. listener = searchHttpListenerFromSpecial (path, _all);
  344. return listener != null;
  345. }
  346. #endregion
  347. #region Public Methods
  348. public void AddPrefix (HttpListenerPrefix prefix)
  349. {
  350. List<HttpListenerPrefix> current, future;
  351. if (prefix.Host == "*") {
  352. do {
  353. current = _unhandled;
  354. future = current != null
  355. ? new List<HttpListenerPrefix> (current)
  356. : new List<HttpListenerPrefix> ();
  357. addSpecial (future, prefix);
  358. }
  359. while (
  360. Interlocked.CompareExchange (ref _unhandled, future, current) != current
  361. );
  362. return;
  363. }
  364. if (prefix.Host == "+") {
  365. do {
  366. current = _all;
  367. future = current != null
  368. ? new List<HttpListenerPrefix> (current)
  369. : new List<HttpListenerPrefix> ();
  370. addSpecial (future, prefix);
  371. }
  372. while (
  373. Interlocked.CompareExchange (ref _all, future, current) != current
  374. );
  375. return;
  376. }
  377. do {
  378. current = _prefixes;
  379. var idx = current.IndexOf (prefix);
  380. if (idx > -1) {
  381. if (current[idx].Listener != prefix.Listener) {
  382. var msg = String.Format (
  383. "There is another listener for {0}.", prefix
  384. );
  385. throw new HttpListenerException (87, msg);
  386. }
  387. return;
  388. }
  389. future = new List<HttpListenerPrefix> (current);
  390. future.Add (prefix);
  391. }
  392. while (
  393. Interlocked.CompareExchange (ref _prefixes, future, current) != current
  394. );
  395. }
  396. public void Close ()
  397. {
  398. _socket.Close ();
  399. clearConnections ();
  400. EndPointManager.RemoveEndPoint (_endpoint);
  401. }
  402. public void RemovePrefix (HttpListenerPrefix prefix)
  403. {
  404. List<HttpListenerPrefix> current, future;
  405. if (prefix.Host == "*") {
  406. do {
  407. current = _unhandled;
  408. if (current == null)
  409. break;
  410. future = new List<HttpListenerPrefix> (current);
  411. if (!removeSpecial (future, prefix))
  412. break;
  413. }
  414. while (
  415. Interlocked.CompareExchange (ref _unhandled, future, current) != current
  416. );
  417. leaveIfNoPrefix ();
  418. return;
  419. }
  420. if (prefix.Host == "+") {
  421. do {
  422. current = _all;
  423. if (current == null)
  424. break;
  425. future = new List<HttpListenerPrefix> (current);
  426. if (!removeSpecial (future, prefix))
  427. break;
  428. }
  429. while (
  430. Interlocked.CompareExchange (ref _all, future, current) != current
  431. );
  432. leaveIfNoPrefix ();
  433. return;
  434. }
  435. do {
  436. current = _prefixes;
  437. if (!current.Contains (prefix))
  438. break;
  439. future = new List<HttpListenerPrefix> (current);
  440. future.Remove (prefix);
  441. }
  442. while (
  443. Interlocked.CompareExchange (ref _prefixes, future, current) != current
  444. );
  445. leaveIfNoPrefix ();
  446. }
  447. #endregion
  448. }
  449. }