HttpServer.cs 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  1. #region License
  2. /*
  3. * HttpServer.cs
  4. *
  5. * The MIT License
  6. *
  7. * Copyright (c) 2012-2023 sta.blockhead
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. */
  27. #endregion
  28. #region Contributors
  29. /*
  30. * Contributors:
  31. * - Juan Manuel Lallana <juan.manuel.lallana@gmail.com>
  32. * - Liryna <liryna.stark@gmail.com>
  33. * - Rohan Singh <rohan-singh@hotmail.com>
  34. */
  35. #endregion
  36. using System;
  37. using System.Collections.Generic;
  38. using System.Diagnostics;
  39. using System.IO;
  40. using System.Net.Sockets;
  41. using System.Security.Cryptography.X509Certificates;
  42. using System.Security.Principal;
  43. using System.Text;
  44. using System.Threading;
  45. using WebSocketSharp.Net;
  46. using WebSocketSharp.Net.WebSockets;
  47. namespace WebSocketSharp.Server
  48. {
  49. /// <summary>
  50. /// Provides a simple HTTP server.
  51. /// </summary>
  52. /// <remarks>
  53. /// <para>
  54. /// The server supports HTTP/1.1 version request and response.
  55. /// </para>
  56. /// <para>
  57. /// Also the server allows to accept WebSocket handshake requests.
  58. /// </para>
  59. /// <para>
  60. /// This class can provide multiple WebSocket services.
  61. /// </para>
  62. /// </remarks>
  63. public class HttpServer
  64. {
  65. #region Private Fields
  66. private System.Net.IPAddress _address;
  67. private string _docRootPath;
  68. private string _hostname;
  69. private HttpListener _listener;
  70. private Logger _log;
  71. private int _port;
  72. private Thread _receiveThread;
  73. private bool _secure;
  74. private WebSocketServiceManager _services;
  75. private volatile ServerState _state;
  76. private object _sync;
  77. #endregion
  78. #region Public Constructors
  79. /// <summary>
  80. /// Initializes a new instance of the <see cref="HttpServer"/> class.
  81. /// </summary>
  82. /// <remarks>
  83. /// The new instance listens for incoming requests on
  84. /// <see cref="System.Net.IPAddress.Any"/> and port 80.
  85. /// </remarks>
  86. public HttpServer ()
  87. {
  88. init ("*", System.Net.IPAddress.Any, 80, false);
  89. }
  90. /// <summary>
  91. /// Initializes a new instance of the <see cref="HttpServer"/> class with
  92. /// the specified port.
  93. /// </summary>
  94. /// <remarks>
  95. /// <para>
  96. /// The new instance listens for incoming requests on
  97. /// <see cref="System.Net.IPAddress.Any"/> and <paramref name="port"/>.
  98. /// </para>
  99. /// <para>
  100. /// It provides secure connections if <paramref name="port"/> is 443.
  101. /// </para>
  102. /// </remarks>
  103. /// <param name="port">
  104. /// An <see cref="int"/> that specifies the number of the port on which
  105. /// to listen.
  106. /// </param>
  107. /// <exception cref="ArgumentOutOfRangeException">
  108. /// <paramref name="port"/> is less than 1 or greater than 65535.
  109. /// </exception>
  110. public HttpServer (int port)
  111. : this (port, port == 443)
  112. {
  113. }
  114. /// <summary>
  115. /// Initializes a new instance of the <see cref="HttpServer"/> class with
  116. /// the specified URL.
  117. /// </summary>
  118. /// <remarks>
  119. /// <para>
  120. /// The new instance listens for incoming requests on the IP address and
  121. /// port of <paramref name="url"/>.
  122. /// </para>
  123. /// <para>
  124. /// Either port 80 or 443 is used if <paramref name="url"/> includes
  125. /// no port. Port 443 is used if the scheme of <paramref name="url"/>
  126. /// is https; otherwise, port 80 is used.
  127. /// </para>
  128. /// <para>
  129. /// The new instance provides secure connections if the scheme of
  130. /// <paramref name="url"/> is https.
  131. /// </para>
  132. /// </remarks>
  133. /// <param name="url">
  134. /// A <see cref="string"/> that specifies the HTTP URL of the server.
  135. /// </param>
  136. /// <exception cref="ArgumentNullException">
  137. /// <paramref name="url"/> is <see langword="null"/>.
  138. /// </exception>
  139. /// <exception cref="ArgumentException">
  140. /// <para>
  141. /// <paramref name="url"/> is an empty string.
  142. /// </para>
  143. /// <para>
  144. /// -or-
  145. /// </para>
  146. /// <para>
  147. /// <paramref name="url"/> is invalid.
  148. /// </para>
  149. /// </exception>
  150. public HttpServer (string url)
  151. {
  152. if (url == null)
  153. throw new ArgumentNullException ("url");
  154. if (url.Length == 0)
  155. throw new ArgumentException ("An empty string.", "url");
  156. Uri uri;
  157. string msg;
  158. if (!tryCreateUri (url, out uri, out msg))
  159. throw new ArgumentException (msg, "url");
  160. var host = uri.GetDnsSafeHost (true);
  161. var addr = host.ToIPAddress ();
  162. if (addr == null) {
  163. msg = "The host part could not be converted to an IP address.";
  164. throw new ArgumentException (msg, "url");
  165. }
  166. if (!addr.IsLocal ()) {
  167. msg = "The IP address of the host is not a local IP address.";
  168. throw new ArgumentException (msg, "url");
  169. }
  170. init (host, addr, uri.Port, uri.Scheme == "https");
  171. }
  172. /// <summary>
  173. /// Initializes a new instance of the <see cref="HttpServer"/> class with
  174. /// the specified port and boolean if secure or not.
  175. /// </summary>
  176. /// <remarks>
  177. /// The new instance listens for incoming requests on
  178. /// <see cref="System.Net.IPAddress.Any"/> and <paramref name="port"/>.
  179. /// </remarks>
  180. /// <param name="port">
  181. /// An <see cref="int"/> that specifies the number of the port on which
  182. /// to listen.
  183. /// </param>
  184. /// <param name="secure">
  185. /// A <see cref="bool"/>: <c>true</c> if the new instance provides
  186. /// secure connections; otherwise, <c>false</c>.
  187. /// </param>
  188. /// <exception cref="ArgumentOutOfRangeException">
  189. /// <paramref name="port"/> is less than 1 or greater than 65535.
  190. /// </exception>
  191. public HttpServer (int port, bool secure)
  192. {
  193. if (!port.IsPortNumber ()) {
  194. var msg = "Less than 1 or greater than 65535.";
  195. throw new ArgumentOutOfRangeException ("port", msg);
  196. }
  197. init ("*", System.Net.IPAddress.Any, port, secure);
  198. }
  199. /// <summary>
  200. /// Initializes a new instance of the <see cref="HttpServer"/> class with
  201. /// the specified IP address and port.
  202. /// </summary>
  203. /// <remarks>
  204. /// <para>
  205. /// The new instance listens for incoming requests on
  206. /// <paramref name="address"/> and <paramref name="port"/>.
  207. /// </para>
  208. /// <para>
  209. /// It provides secure connections if <paramref name="port"/> is 443.
  210. /// </para>
  211. /// </remarks>
  212. /// <param name="address">
  213. /// A <see cref="System.Net.IPAddress"/> that specifies the local IP
  214. /// address on which to listen.
  215. /// </param>
  216. /// <param name="port">
  217. /// An <see cref="int"/> that specifies the number of the port on which
  218. /// to listen.
  219. /// </param>
  220. /// <exception cref="ArgumentNullException">
  221. /// <paramref name="address"/> is <see langword="null"/>.
  222. /// </exception>
  223. /// <exception cref="ArgumentException">
  224. /// <paramref name="address"/> is not a local IP address.
  225. /// </exception>
  226. /// <exception cref="ArgumentOutOfRangeException">
  227. /// <paramref name="port"/> is less than 1 or greater than 65535.
  228. /// </exception>
  229. public HttpServer (System.Net.IPAddress address, int port)
  230. : this (address, port, port == 443)
  231. {
  232. }
  233. /// <summary>
  234. /// Initializes a new instance of the <see cref="HttpServer"/> class with
  235. /// the specified IP address, port, and boolean if secure or not.
  236. /// </summary>
  237. /// <remarks>
  238. /// The new instance listens for incoming requests on
  239. /// <paramref name="address"/> and <paramref name="port"/>.
  240. /// </remarks>
  241. /// <param name="address">
  242. /// A <see cref="System.Net.IPAddress"/> that specifies the local IP
  243. /// address on which to listen.
  244. /// </param>
  245. /// <param name="port">
  246. /// An <see cref="int"/> that specifies the number of the port on which
  247. /// to listen.
  248. /// </param>
  249. /// <param name="secure">
  250. /// A <see cref="bool"/>: <c>true</c> if the new instance provides
  251. /// secure connections; otherwise, <c>false</c>.
  252. /// </param>
  253. /// <exception cref="ArgumentNullException">
  254. /// <paramref name="address"/> is <see langword="null"/>.
  255. /// </exception>
  256. /// <exception cref="ArgumentException">
  257. /// <paramref name="address"/> is not a local IP address.
  258. /// </exception>
  259. /// <exception cref="ArgumentOutOfRangeException">
  260. /// <paramref name="port"/> is less than 1 or greater than 65535.
  261. /// </exception>
  262. public HttpServer (System.Net.IPAddress address, int port, bool secure)
  263. {
  264. if (address == null)
  265. throw new ArgumentNullException ("address");
  266. if (!address.IsLocal ()) {
  267. var msg = "Not a local IP address.";
  268. throw new ArgumentException (msg, "address");
  269. }
  270. if (!port.IsPortNumber ()) {
  271. var msg = "Less than 1 or greater than 65535.";
  272. throw new ArgumentOutOfRangeException ("port", msg);
  273. }
  274. init (address.ToString (true), address, port, secure);
  275. }
  276. #endregion
  277. #region Public Properties
  278. /// <summary>
  279. /// Gets the IP address of the server.
  280. /// </summary>
  281. /// <value>
  282. /// A <see cref="System.Net.IPAddress"/> that represents the local IP
  283. /// address on which to listen for incoming requests.
  284. /// </value>
  285. public System.Net.IPAddress Address {
  286. get {
  287. return _address;
  288. }
  289. }
  290. /// <summary>
  291. /// Gets or sets the scheme used to authenticate the clients.
  292. /// </summary>
  293. /// <remarks>
  294. /// The set operation works if the current state of the server is
  295. /// Ready or Stop.
  296. /// </remarks>
  297. /// <value>
  298. /// <para>
  299. /// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/>
  300. /// enum values.
  301. /// </para>
  302. /// <para>
  303. /// It represents the scheme used to authenticate the clients.
  304. /// </para>
  305. /// <para>
  306. /// The default value is
  307. /// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>.
  308. /// </para>
  309. /// </value>
  310. public AuthenticationSchemes AuthenticationSchemes {
  311. get {
  312. return _listener.AuthenticationSchemes;
  313. }
  314. set {
  315. lock (_sync) {
  316. if (!canSet ())
  317. return;
  318. _listener.AuthenticationSchemes = value;
  319. }
  320. }
  321. }
  322. /// <summary>
  323. /// Gets or sets the path to the document folder of the server.
  324. /// </summary>
  325. /// <remarks>
  326. /// The set operation works if the current state of the server is
  327. /// Ready or Stop.
  328. /// </remarks>
  329. /// <value>
  330. /// <para>
  331. /// A <see cref="string"/> that represents a path to the folder
  332. /// from which to find the requested file.
  333. /// </para>
  334. /// <para>
  335. /// '/' or '\' is trimmed from the end of the value if present.
  336. /// </para>
  337. /// <para>
  338. /// The default value is "./Public".
  339. /// </para>
  340. /// </value>
  341. /// <exception cref="ArgumentNullException">
  342. /// The value specified for a set operation is <see langword="null"/>.
  343. /// </exception>
  344. /// <exception cref="ArgumentException">
  345. /// <para>
  346. /// The value specified for a set operation is an empty string.
  347. /// </para>
  348. /// <para>
  349. /// -or-
  350. /// </para>
  351. /// <para>
  352. /// The value specified for a set operation is an absolute root.
  353. /// </para>
  354. /// <para>
  355. /// -or-
  356. /// </para>
  357. /// <para>
  358. /// The value specified for a set operation is an invalid path string.
  359. /// </para>
  360. /// </exception>
  361. public string DocumentRootPath {
  362. get {
  363. return _docRootPath;
  364. }
  365. set {
  366. if (value == null)
  367. throw new ArgumentNullException ("value");
  368. if (value.Length == 0)
  369. throw new ArgumentException ("An empty string.", "value");
  370. value = value.TrimSlashOrBackslashFromEnd ();
  371. if (value == "/")
  372. throw new ArgumentException ("An absolute root.", "value");
  373. if (value == "\\")
  374. throw new ArgumentException ("An absolute root.", "value");
  375. if (value.Length == 2 && value[1] == ':')
  376. throw new ArgumentException ("An absolute root.", "value");
  377. string full = null;
  378. try {
  379. full = Path.GetFullPath (value);
  380. }
  381. catch (Exception ex) {
  382. throw new ArgumentException ("An invalid path string.", "value", ex);
  383. }
  384. if (full == "/")
  385. throw new ArgumentException ("An absolute root.", "value");
  386. full = full.TrimSlashOrBackslashFromEnd ();
  387. if (full.Length == 2 && full[1] == ':')
  388. throw new ArgumentException ("An absolute root.", "value");
  389. lock (_sync) {
  390. if (!canSet ())
  391. return;
  392. _docRootPath = value;
  393. }
  394. }
  395. }
  396. /// <summary>
  397. /// Gets a value indicating whether the server has started.
  398. /// </summary>
  399. /// <value>
  400. /// <c>true</c> if the server has started; otherwise, <c>false</c>.
  401. /// </value>
  402. public bool IsListening {
  403. get {
  404. return _state == ServerState.Start;
  405. }
  406. }
  407. /// <summary>
  408. /// Gets a value indicating whether the server provides secure connections.
  409. /// </summary>
  410. /// <value>
  411. /// <c>true</c> if the server provides secure connections; otherwise,
  412. /// <c>false</c>.
  413. /// </value>
  414. public bool IsSecure {
  415. get {
  416. return _secure;
  417. }
  418. }
  419. /// <summary>
  420. /// Gets or sets a value indicating whether the server cleans up
  421. /// the inactive sessions periodically.
  422. /// </summary>
  423. /// <remarks>
  424. /// The set operation works if the current state of the server is
  425. /// Ready or Stop.
  426. /// </remarks>
  427. /// <value>
  428. /// <para>
  429. /// <c>true</c> if the server cleans up the inactive sessions
  430. /// every 60 seconds; otherwise, <c>false</c>.
  431. /// </para>
  432. /// <para>
  433. /// The default value is <c>true</c>.
  434. /// </para>
  435. /// </value>
  436. public bool KeepClean {
  437. get {
  438. return _services.KeepClean;
  439. }
  440. set {
  441. _services.KeepClean = value;
  442. }
  443. }
  444. /// <summary>
  445. /// Gets the logging function for the server.
  446. /// </summary>
  447. /// <remarks>
  448. /// The default logging level is <see cref="LogLevel.Error"/>.
  449. /// </remarks>
  450. /// <value>
  451. /// A <see cref="Logger"/> that provides the logging function.
  452. /// </value>
  453. public Logger Log {
  454. get {
  455. return _log;
  456. }
  457. }
  458. /// <summary>
  459. /// Gets the port of the server.
  460. /// </summary>
  461. /// <value>
  462. /// An <see cref="int"/> that represents the number of the port on which
  463. /// to listen for incoming requests.
  464. /// </value>
  465. public int Port {
  466. get {
  467. return _port;
  468. }
  469. }
  470. /// <summary>
  471. /// Gets or sets the name of the realm associated with the server.
  472. /// </summary>
  473. /// <remarks>
  474. /// The set operation works if the current state of the server is
  475. /// Ready or Stop.
  476. /// </remarks>
  477. /// <value>
  478. /// <para>
  479. /// A <see cref="string"/> that represents the name of the realm.
  480. /// </para>
  481. /// <para>
  482. /// "SECRET AREA" is used as the name of the realm if the value is
  483. /// <see langword="null"/> or an empty string.
  484. /// </para>
  485. /// <para>
  486. /// The default value is <see langword="null"/>.
  487. /// </para>
  488. /// </value>
  489. public string Realm {
  490. get {
  491. return _listener.Realm;
  492. }
  493. set {
  494. lock (_sync) {
  495. if (!canSet ())
  496. return;
  497. _listener.Realm = value;
  498. }
  499. }
  500. }
  501. /// <summary>
  502. /// Gets or sets a value indicating whether the server is allowed to
  503. /// be bound to an address that is already in use.
  504. /// </summary>
  505. /// <remarks>
  506. /// <para>
  507. /// You should set this property to <c>true</c> if you would like to
  508. /// resolve to wait for socket in TIME_WAIT state.
  509. /// </para>
  510. /// <para>
  511. /// The set operation works if the current state of the server is
  512. /// Ready or Stop.
  513. /// </para>
  514. /// </remarks>
  515. /// <value>
  516. /// <para>
  517. /// <c>true</c> if the server is allowed to be bound to an address
  518. /// that is already in use; otherwise, <c>false</c>.
  519. /// </para>
  520. /// <para>
  521. /// The default value is <c>false</c>.
  522. /// </para>
  523. /// </value>
  524. public bool ReuseAddress {
  525. get {
  526. return _listener.ReuseAddress;
  527. }
  528. set {
  529. lock (_sync) {
  530. if (!canSet ())
  531. return;
  532. _listener.ReuseAddress = value;
  533. }
  534. }
  535. }
  536. /// <summary>
  537. /// Gets the configuration for secure connection.
  538. /// </summary>
  539. /// <remarks>
  540. /// The configuration is used when the server attempts to start,
  541. /// so it must be configured before the start method is called.
  542. /// </remarks>
  543. /// <value>
  544. /// A <see cref="ServerSslConfiguration"/> that represents the
  545. /// configuration used to provide secure connections.
  546. /// </value>
  547. /// <exception cref="InvalidOperationException">
  548. /// The server does not provide secure connections.
  549. /// </exception>
  550. public ServerSslConfiguration SslConfiguration {
  551. get {
  552. if (!_secure) {
  553. var msg = "The server does not provide secure connections.";
  554. throw new InvalidOperationException (msg);
  555. }
  556. return _listener.SslConfiguration;
  557. }
  558. }
  559. /// <summary>
  560. /// Gets or sets the delegate used to find the credentials for an identity.
  561. /// </summary>
  562. /// <remarks>
  563. /// The set operation works if the current state of the server is
  564. /// Ready or Stop.
  565. /// </remarks>
  566. /// <value>
  567. /// <para>
  568. /// A <see cref="T:System.Func{IIdentity, NetworkCredential}"/>
  569. /// delegate.
  570. /// </para>
  571. /// <para>
  572. /// The delegate invokes the method called when the server finds
  573. /// the credentials used to authenticate a client.
  574. /// </para>
  575. /// <para>
  576. /// The method must return <see langword="null"/> if the credentials
  577. /// are not found.
  578. /// </para>
  579. /// <para>
  580. /// <see langword="null"/> if not necessary.
  581. /// </para>
  582. /// <para>
  583. /// The default value is <see langword="null"/>.
  584. /// </para>
  585. /// </value>
  586. public Func<IIdentity, NetworkCredential> UserCredentialsFinder {
  587. get {
  588. return _listener.UserCredentialsFinder;
  589. }
  590. set {
  591. lock (_sync) {
  592. if (!canSet ())
  593. return;
  594. _listener.UserCredentialsFinder = value;
  595. }
  596. }
  597. }
  598. /// <summary>
  599. /// Gets or sets the time to wait for the response to the WebSocket
  600. /// Ping or Close.
  601. /// </summary>
  602. /// <remarks>
  603. /// The set operation works if the current state of the server is
  604. /// Ready or Stop.
  605. /// </remarks>
  606. /// <value>
  607. /// <para>
  608. /// A <see cref="TimeSpan"/> that represents the time to wait for
  609. /// the response.
  610. /// </para>
  611. /// <para>
  612. /// The default value is the same as 1 second.
  613. /// </para>
  614. /// </value>
  615. /// <exception cref="ArgumentOutOfRangeException">
  616. /// The value specified for a set operation is zero or less.
  617. /// </exception>
  618. public TimeSpan WaitTime {
  619. get {
  620. return _services.WaitTime;
  621. }
  622. set {
  623. _services.WaitTime = value;
  624. }
  625. }
  626. /// <summary>
  627. /// Gets the management function for the WebSocket services provided by
  628. /// the server.
  629. /// </summary>
  630. /// <value>
  631. /// A <see cref="WebSocketServiceManager"/> that manages the WebSocket
  632. /// services provided by the server.
  633. /// </value>
  634. public WebSocketServiceManager WebSocketServices {
  635. get {
  636. return _services;
  637. }
  638. }
  639. #endregion
  640. #region Public Events
  641. /// <summary>
  642. /// Occurs when the server receives an HTTP CONNECT request.
  643. /// </summary>
  644. public event EventHandler<HttpRequestEventArgs> OnConnect;
  645. /// <summary>
  646. /// Occurs when the server receives an HTTP DELETE request.
  647. /// </summary>
  648. public event EventHandler<HttpRequestEventArgs> OnDelete;
  649. /// <summary>
  650. /// Occurs when the server receives an HTTP GET request.
  651. /// </summary>
  652. public event EventHandler<HttpRequestEventArgs> OnGet;
  653. /// <summary>
  654. /// Occurs when the server receives an HTTP HEAD request.
  655. /// </summary>
  656. public event EventHandler<HttpRequestEventArgs> OnHead;
  657. /// <summary>
  658. /// Occurs when the server receives an HTTP OPTIONS request.
  659. /// </summary>
  660. public event EventHandler<HttpRequestEventArgs> OnOptions;
  661. /// <summary>
  662. /// Occurs when the server receives an HTTP POST request.
  663. /// </summary>
  664. public event EventHandler<HttpRequestEventArgs> OnPost;
  665. /// <summary>
  666. /// Occurs when the server receives an HTTP PUT request.
  667. /// </summary>
  668. public event EventHandler<HttpRequestEventArgs> OnPut;
  669. /// <summary>
  670. /// Occurs when the server receives an HTTP TRACE request.
  671. /// </summary>
  672. public event EventHandler<HttpRequestEventArgs> OnTrace;
  673. #endregion
  674. #region Private Methods
  675. private void abort ()
  676. {
  677. lock (_sync) {
  678. if (_state != ServerState.Start)
  679. return;
  680. _state = ServerState.ShuttingDown;
  681. }
  682. try {
  683. _services.Stop (1006, String.Empty);
  684. }
  685. catch (Exception ex) {
  686. _log.Fatal (ex.Message);
  687. _log.Debug (ex.ToString ());
  688. }
  689. try {
  690. _listener.Abort ();
  691. }
  692. catch (Exception ex) {
  693. _log.Fatal (ex.Message);
  694. _log.Debug (ex.ToString ());
  695. }
  696. _state = ServerState.Stop;
  697. }
  698. private bool canSet ()
  699. {
  700. return _state == ServerState.Ready || _state == ServerState.Stop;
  701. }
  702. private bool checkCertificate (out string message)
  703. {
  704. message = null;
  705. var byUser = _listener.SslConfiguration.ServerCertificate != null;
  706. var path = _listener.CertificateFolderPath;
  707. var withPort = EndPointListener.CertificateExists (_port, path);
  708. var either = byUser || withPort;
  709. if (!either) {
  710. message = "There is no server certificate for secure connection.";
  711. return false;
  712. }
  713. var both = byUser && withPort;
  714. if (both) {
  715. var msg = "The server certificate associated with the port is used.";
  716. _log.Warn (msg);
  717. }
  718. return true;
  719. }
  720. private static HttpListener createListener (
  721. string hostname, int port, bool secure
  722. )
  723. {
  724. var lsnr = new HttpListener ();
  725. var schm = secure ? "https" : "http";
  726. var pref = String.Format ("{0}://{1}:{2}/", schm, hostname, port);
  727. lsnr.Prefixes.Add (pref);
  728. return lsnr;
  729. }
  730. private void init (
  731. string hostname, System.Net.IPAddress address, int port, bool secure
  732. )
  733. {
  734. _hostname = hostname;
  735. _address = address;
  736. _port = port;
  737. _secure = secure;
  738. _docRootPath = "./Public";
  739. _listener = createListener (_hostname, _port, _secure);
  740. _log = _listener.Log;
  741. _services = new WebSocketServiceManager (_log);
  742. _sync = new object ();
  743. }
  744. private void processRequest (HttpListenerContext context)
  745. {
  746. var method = context.Request.HttpMethod;
  747. var evt = method == "GET"
  748. ? OnGet
  749. : method == "HEAD"
  750. ? OnHead
  751. : method == "POST"
  752. ? OnPost
  753. : method == "PUT"
  754. ? OnPut
  755. : method == "DELETE"
  756. ? OnDelete
  757. : method == "CONNECT"
  758. ? OnConnect
  759. : method == "OPTIONS"
  760. ? OnOptions
  761. : method == "TRACE"
  762. ? OnTrace
  763. : null;
  764. if (evt == null) {
  765. context.ErrorStatusCode = 501;
  766. context.SendError ();
  767. return;
  768. }
  769. var e = new HttpRequestEventArgs (context, _docRootPath);
  770. evt (this, e);
  771. context.Response.Close ();
  772. }
  773. private void processRequest (HttpListenerWebSocketContext context)
  774. {
  775. var uri = context.RequestUri;
  776. if (uri == null) {
  777. context.Close (HttpStatusCode.BadRequest);
  778. return;
  779. }
  780. var path = uri.AbsolutePath;
  781. if (path.IndexOfAny (new[] { '%', '+' }) > -1)
  782. path = HttpUtility.UrlDecode (path, Encoding.UTF8);
  783. WebSocketServiceHost host;
  784. if (!_services.InternalTryGetServiceHost (path, out host)) {
  785. context.Close (HttpStatusCode.NotImplemented);
  786. return;
  787. }
  788. host.StartSession (context);
  789. }
  790. private void receiveRequest ()
  791. {
  792. while (true) {
  793. HttpListenerContext ctx = null;
  794. try {
  795. ctx = _listener.GetContext ();
  796. ThreadPool.QueueUserWorkItem (
  797. state => {
  798. try {
  799. if (ctx.Request.IsUpgradeRequest ("websocket")) {
  800. processRequest (ctx.GetWebSocketContext (null));
  801. return;
  802. }
  803. processRequest (ctx);
  804. }
  805. catch (Exception ex) {
  806. _log.Error (ex.Message);
  807. _log.Debug (ex.ToString ());
  808. ctx.Connection.Close (true);
  809. }
  810. }
  811. );
  812. }
  813. catch (HttpListenerException ex) {
  814. if (_state == ServerState.ShuttingDown)
  815. return;
  816. _log.Fatal (ex.Message);
  817. _log.Debug (ex.ToString ());
  818. break;
  819. }
  820. catch (InvalidOperationException ex) {
  821. if (_state == ServerState.ShuttingDown)
  822. return;
  823. _log.Fatal (ex.Message);
  824. _log.Debug (ex.ToString ());
  825. break;
  826. }
  827. catch (Exception ex) {
  828. _log.Fatal (ex.Message);
  829. _log.Debug (ex.ToString ());
  830. if (ctx != null)
  831. ctx.Connection.Close (true);
  832. if (_state == ServerState.ShuttingDown)
  833. return;
  834. break;
  835. }
  836. }
  837. abort ();
  838. }
  839. private void start ()
  840. {
  841. lock (_sync) {
  842. if (_state == ServerState.Start || _state == ServerState.ShuttingDown)
  843. return;
  844. if (_secure) {
  845. string msg;
  846. if (!checkCertificate (out msg))
  847. throw new InvalidOperationException (msg);
  848. }
  849. _services.Start ();
  850. try {
  851. startReceiving ();
  852. }
  853. catch {
  854. _services.Stop (1011, String.Empty);
  855. throw;
  856. }
  857. _state = ServerState.Start;
  858. }
  859. }
  860. private void startReceiving ()
  861. {
  862. try {
  863. _listener.Start ();
  864. }
  865. catch (Exception ex) {
  866. var msg = "The underlying listener has failed to start.";
  867. throw new InvalidOperationException (msg, ex);
  868. }
  869. var receiver = new ThreadStart (receiveRequest);
  870. _receiveThread = new Thread (receiver);
  871. _receiveThread.IsBackground = true;
  872. _receiveThread.Start ();
  873. }
  874. private void stop (ushort code, string reason)
  875. {
  876. lock (_sync) {
  877. if (_state != ServerState.Start)
  878. return;
  879. _state = ServerState.ShuttingDown;
  880. }
  881. try {
  882. _services.Stop (code, reason);
  883. }
  884. catch (Exception ex) {
  885. _log.Fatal (ex.Message);
  886. _log.Debug (ex.ToString ());
  887. }
  888. try {
  889. var timeout = 5000;
  890. stopReceiving (timeout);
  891. }
  892. catch (Exception ex) {
  893. _log.Fatal (ex.Message);
  894. _log.Debug (ex.ToString ());
  895. }
  896. _state = ServerState.Stop;
  897. }
  898. private void stopReceiving (int millisecondsTimeout)
  899. {
  900. _listener.Stop ();
  901. _receiveThread.Join (millisecondsTimeout);
  902. }
  903. private static bool tryCreateUri (
  904. string uriString, out Uri result, out string message
  905. )
  906. {
  907. result = null;
  908. message = null;
  909. var uri = uriString.ToUri ();
  910. if (uri == null) {
  911. message = "An invalid URI string.";
  912. return false;
  913. }
  914. if (!uri.IsAbsoluteUri) {
  915. message = "A relative URI.";
  916. return false;
  917. }
  918. var schm = uri.Scheme;
  919. var http = schm == "http" || schm == "https";
  920. if (!http) {
  921. message = "The scheme part is not 'http' or 'https'.";
  922. return false;
  923. }
  924. if (uri.PathAndQuery != "/") {
  925. message = "It includes either or both path and query components.";
  926. return false;
  927. }
  928. if (uri.Fragment.Length > 0) {
  929. message = "It includes the fragment component.";
  930. return false;
  931. }
  932. if (uri.Port == 0) {
  933. message = "The port part is zero.";
  934. return false;
  935. }
  936. result = uri;
  937. return true;
  938. }
  939. #endregion
  940. #region Public Methods
  941. /// <summary>
  942. /// Adds a WebSocket service with the specified behavior and path.
  943. /// </summary>
  944. /// <param name="path">
  945. /// <para>
  946. /// A <see cref="string"/> that specifies an absolute path to
  947. /// the service to add.
  948. /// </para>
  949. /// <para>
  950. /// / is trimmed from the end of the string if present.
  951. /// </para>
  952. /// </param>
  953. /// <typeparam name="TBehavior">
  954. /// <para>
  955. /// The type of the behavior for the service.
  956. /// </para>
  957. /// <para>
  958. /// It must inherit the <see cref="WebSocketBehavior"/> class.
  959. /// </para>
  960. /// <para>
  961. /// Also it must have a public parameterless constructor.
  962. /// </para>
  963. /// </typeparam>
  964. /// <exception cref="ArgumentNullException">
  965. /// <paramref name="path"/> is <see langword="null"/>.
  966. /// </exception>
  967. /// <exception cref="ArgumentException">
  968. /// <para>
  969. /// <paramref name="path"/> is an empty string.
  970. /// </para>
  971. /// <para>
  972. /// -or-
  973. /// </para>
  974. /// <para>
  975. /// <paramref name="path"/> is not an absolute path.
  976. /// </para>
  977. /// <para>
  978. /// -or-
  979. /// </para>
  980. /// <para>
  981. /// <paramref name="path"/> includes either or both
  982. /// query and fragment components.
  983. /// </para>
  984. /// <para>
  985. /// -or-
  986. /// </para>
  987. /// <para>
  988. /// <paramref name="path"/> is already in use.
  989. /// </para>
  990. /// </exception>
  991. public void AddWebSocketService<TBehavior> (string path)
  992. where TBehavior : WebSocketBehavior, new ()
  993. {
  994. _services.AddService<TBehavior> (path, null);
  995. }
  996. /// <summary>
  997. /// Adds a WebSocket service with the specified behavior, path,
  998. /// and initializer.
  999. /// </summary>
  1000. /// <param name="path">
  1001. /// <para>
  1002. /// A <see cref="string"/> that specifies an absolute path to
  1003. /// the service to add.
  1004. /// </para>
  1005. /// <para>
  1006. /// / is trimmed from the end of the string if present.
  1007. /// </para>
  1008. /// </param>
  1009. /// <param name="initializer">
  1010. /// <para>
  1011. /// An <see cref="T:System.Action{TBehavior}"/> delegate.
  1012. /// </para>
  1013. /// <para>
  1014. /// The delegate invokes the method called when the service
  1015. /// initializes a new session instance.
  1016. /// </para>
  1017. /// <para>
  1018. /// <see langword="null"/> if not necessary.
  1019. /// </para>
  1020. /// </param>
  1021. /// <typeparam name="TBehavior">
  1022. /// <para>
  1023. /// The type of the behavior for the service.
  1024. /// </para>
  1025. /// <para>
  1026. /// It must inherit the <see cref="WebSocketBehavior"/> class.
  1027. /// </para>
  1028. /// <para>
  1029. /// Also it must have a public parameterless constructor.
  1030. /// </para>
  1031. /// </typeparam>
  1032. /// <exception cref="ArgumentNullException">
  1033. /// <paramref name="path"/> is <see langword="null"/>.
  1034. /// </exception>
  1035. /// <exception cref="ArgumentException">
  1036. /// <para>
  1037. /// <paramref name="path"/> is an empty string.
  1038. /// </para>
  1039. /// <para>
  1040. /// -or-
  1041. /// </para>
  1042. /// <para>
  1043. /// <paramref name="path"/> is not an absolute path.
  1044. /// </para>
  1045. /// <para>
  1046. /// -or-
  1047. /// </para>
  1048. /// <para>
  1049. /// <paramref name="path"/> includes either or both
  1050. /// query and fragment components.
  1051. /// </para>
  1052. /// <para>
  1053. /// -or-
  1054. /// </para>
  1055. /// <para>
  1056. /// <paramref name="path"/> is already in use.
  1057. /// </para>
  1058. /// </exception>
  1059. public void AddWebSocketService<TBehavior> (
  1060. string path, Action<TBehavior> initializer
  1061. )
  1062. where TBehavior : WebSocketBehavior, new ()
  1063. {
  1064. _services.AddService<TBehavior> (path, initializer);
  1065. }
  1066. /// <summary>
  1067. /// Removes a WebSocket service with the specified path.
  1068. /// </summary>
  1069. /// <remarks>
  1070. /// The service is stopped with close status 1001 (going away)
  1071. /// if the current state of the service is Start.
  1072. /// </remarks>
  1073. /// <returns>
  1074. /// <c>true</c> if the service is successfully found and removed;
  1075. /// otherwise, <c>false</c>.
  1076. /// </returns>
  1077. /// <param name="path">
  1078. /// <para>
  1079. /// A <see cref="string"/> that specifies an absolute path to
  1080. /// the service to remove.
  1081. /// </para>
  1082. /// <para>
  1083. /// / is trimmed from the end of the string if present.
  1084. /// </para>
  1085. /// </param>
  1086. /// <exception cref="ArgumentNullException">
  1087. /// <paramref name="path"/> is <see langword="null"/>.
  1088. /// </exception>
  1089. /// <exception cref="ArgumentException">
  1090. /// <para>
  1091. /// <paramref name="path"/> is an empty string.
  1092. /// </para>
  1093. /// <para>
  1094. /// -or-
  1095. /// </para>
  1096. /// <para>
  1097. /// <paramref name="path"/> is not an absolute path.
  1098. /// </para>
  1099. /// <para>
  1100. /// -or-
  1101. /// </para>
  1102. /// <para>
  1103. /// <paramref name="path"/> includes either or both
  1104. /// query and fragment components.
  1105. /// </para>
  1106. /// </exception>
  1107. public bool RemoveWebSocketService (string path)
  1108. {
  1109. return _services.RemoveService (path);
  1110. }
  1111. /// <summary>
  1112. /// Starts receiving incoming requests.
  1113. /// </summary>
  1114. /// <remarks>
  1115. /// This method works if the current state of the server is Ready or Stop.
  1116. /// </remarks>
  1117. /// <exception cref="InvalidOperationException">
  1118. /// <para>
  1119. /// There is no server certificate for secure connection.
  1120. /// </para>
  1121. /// <para>
  1122. /// -or-
  1123. /// </para>
  1124. /// <para>
  1125. /// The underlying <see cref="HttpListener"/> has failed to start.
  1126. /// </para>
  1127. /// </exception>
  1128. public void Start ()
  1129. {
  1130. if (_state == ServerState.Start || _state == ServerState.ShuttingDown)
  1131. return;
  1132. start ();
  1133. }
  1134. /// <summary>
  1135. /// Stops receiving incoming requests.
  1136. /// </summary>
  1137. /// <remarks>
  1138. /// This method works if the current state of the server is Start.
  1139. /// </remarks>
  1140. public void Stop ()
  1141. {
  1142. if (_state != ServerState.Start)
  1143. return;
  1144. stop (1001, String.Empty);
  1145. }
  1146. #endregion
  1147. }
  1148. }