HttpListenerResponse.cs 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  1. #region License
  2. /*
  3. * HttpListenerResponse.cs
  4. *
  5. * This code is derived from HttpListenerResponse.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-2021 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. * - Nicholas Devenish
  42. */
  43. #endregion
  44. using System;
  45. using System.Collections.Generic;
  46. using System.Globalization;
  47. using System.IO;
  48. using System.Text;
  49. namespace WebSocketSharp.Net
  50. {
  51. /// <summary>
  52. /// Represents an HTTP response to an HTTP request received by
  53. /// a <see cref="HttpListener"/> instance.
  54. /// </summary>
  55. /// <remarks>
  56. /// This class cannot be inherited.
  57. /// </remarks>
  58. public sealed class HttpListenerResponse : IDisposable
  59. {
  60. #region Private Fields
  61. private bool _closeConnection;
  62. private Encoding _contentEncoding;
  63. private long _contentLength;
  64. private string _contentType;
  65. private HttpListenerContext _context;
  66. private CookieCollection _cookies;
  67. private bool _disposed;
  68. private WebHeaderCollection _headers;
  69. private bool _headersSent;
  70. private bool _keepAlive;
  71. private ResponseStream _outputStream;
  72. private Uri _redirectLocation;
  73. private bool _sendChunked;
  74. private int _statusCode;
  75. private string _statusDescription;
  76. private Version _version;
  77. #endregion
  78. #region Internal Constructors
  79. internal HttpListenerResponse (HttpListenerContext context)
  80. {
  81. _context = context;
  82. _keepAlive = true;
  83. _statusCode = 200;
  84. _statusDescription = "OK";
  85. _version = HttpVersion.Version11;
  86. }
  87. #endregion
  88. #region Internal Properties
  89. internal bool CloseConnection {
  90. get {
  91. return _closeConnection;
  92. }
  93. set {
  94. _closeConnection = value;
  95. }
  96. }
  97. internal WebHeaderCollection FullHeaders {
  98. get {
  99. var headers = new WebHeaderCollection (HttpHeaderType.Response, true);
  100. if (_headers != null)
  101. headers.Add (_headers);
  102. if (_contentType != null) {
  103. headers.InternalSet (
  104. "Content-Type",
  105. createContentTypeHeaderText (_contentType, _contentEncoding),
  106. true
  107. );
  108. }
  109. if (headers["Server"] == null)
  110. headers.InternalSet ("Server", "websocket-sharp/1.0", true);
  111. if (headers["Date"] == null) {
  112. headers.InternalSet (
  113. "Date",
  114. DateTime.UtcNow.ToString ("r", CultureInfo.InvariantCulture),
  115. true
  116. );
  117. }
  118. if (_sendChunked) {
  119. headers.InternalSet ("Transfer-Encoding", "chunked", true);
  120. }
  121. else {
  122. headers.InternalSet (
  123. "Content-Length",
  124. _contentLength.ToString (CultureInfo.InvariantCulture),
  125. true
  126. );
  127. }
  128. /*
  129. * Apache forces closing the connection for these status codes:
  130. * - 400 Bad Request
  131. * - 408 Request Timeout
  132. * - 411 Length Required
  133. * - 413 Request Entity Too Large
  134. * - 414 Request-Uri Too Long
  135. * - 500 Internal Server Error
  136. * - 503 Service Unavailable
  137. */
  138. var closeConn = !_context.Request.KeepAlive
  139. || !_keepAlive
  140. || _statusCode == 400
  141. || _statusCode == 408
  142. || _statusCode == 411
  143. || _statusCode == 413
  144. || _statusCode == 414
  145. || _statusCode == 500
  146. || _statusCode == 503;
  147. var reuses = _context.Connection.Reuses;
  148. if (closeConn || reuses >= 100) {
  149. headers.InternalSet ("Connection", "close", true);
  150. }
  151. else {
  152. headers.InternalSet (
  153. "Keep-Alive",
  154. String.Format ("timeout=15,max={0}", 100 - reuses),
  155. true
  156. );
  157. if (_context.Request.ProtocolVersion < HttpVersion.Version11)
  158. headers.InternalSet ("Connection", "keep-alive", true);
  159. }
  160. if (_redirectLocation != null)
  161. headers.InternalSet ("Location", _redirectLocation.AbsoluteUri, true);
  162. if (_cookies != null) {
  163. foreach (var cookie in _cookies) {
  164. headers.InternalSet (
  165. "Set-Cookie",
  166. cookie.ToResponseString (),
  167. true
  168. );
  169. }
  170. }
  171. return headers;
  172. }
  173. }
  174. internal bool HeadersSent {
  175. get {
  176. return _headersSent;
  177. }
  178. set {
  179. _headersSent = value;
  180. }
  181. }
  182. internal string StatusLine {
  183. get {
  184. return String.Format (
  185. "HTTP/{0} {1} {2}\r\n",
  186. _version,
  187. _statusCode,
  188. _statusDescription
  189. );
  190. }
  191. }
  192. #endregion
  193. #region Public Properties
  194. /// <summary>
  195. /// Gets or sets the encoding for the entity body data included in
  196. /// the response.
  197. /// </summary>
  198. /// <value>
  199. /// <para>
  200. /// A <see cref="Encoding"/> that represents the encoding for
  201. /// the entity body data.
  202. /// </para>
  203. /// <para>
  204. /// <see langword="null"/> if no encoding is specified.
  205. /// </para>
  206. /// <para>
  207. /// The default value is <see langword="null"/>.
  208. /// </para>
  209. /// </value>
  210. /// <exception cref="InvalidOperationException">
  211. /// The response is already being sent.
  212. /// </exception>
  213. /// <exception cref="ObjectDisposedException">
  214. /// This instance is closed.
  215. /// </exception>
  216. public Encoding ContentEncoding {
  217. get {
  218. return _contentEncoding;
  219. }
  220. set {
  221. if (_disposed) {
  222. var name = GetType ().ToString ();
  223. throw new ObjectDisposedException (name);
  224. }
  225. if (_headersSent) {
  226. var msg = "The response is already being sent.";
  227. throw new InvalidOperationException (msg);
  228. }
  229. _contentEncoding = value;
  230. }
  231. }
  232. /// <summary>
  233. /// Gets or sets the number of bytes in the entity body data included in
  234. /// the response.
  235. /// </summary>
  236. /// <value>
  237. /// <para>
  238. /// A <see cref="long"/> that represents the number of bytes in
  239. /// the entity body data.
  240. /// </para>
  241. /// <para>
  242. /// It is used for the value of the Content-Length header.
  243. /// </para>
  244. /// <para>
  245. /// The default value is zero.
  246. /// </para>
  247. /// </value>
  248. /// <exception cref="ArgumentOutOfRangeException">
  249. /// The value specified for a set operation is less than zero.
  250. /// </exception>
  251. /// <exception cref="InvalidOperationException">
  252. /// The response is already being sent.
  253. /// </exception>
  254. /// <exception cref="ObjectDisposedException">
  255. /// This instance is closed.
  256. /// </exception>
  257. public long ContentLength64 {
  258. get {
  259. return _contentLength;
  260. }
  261. set {
  262. if (_disposed) {
  263. var name = GetType ().ToString ();
  264. throw new ObjectDisposedException (name);
  265. }
  266. if (_headersSent) {
  267. var msg = "The response is already being sent.";
  268. throw new InvalidOperationException (msg);
  269. }
  270. if (value < 0) {
  271. var msg = "Less than zero.";
  272. throw new ArgumentOutOfRangeException (msg, "value");
  273. }
  274. _contentLength = value;
  275. }
  276. }
  277. /// <summary>
  278. /// Gets or sets the media type of the entity body included in
  279. /// the response.
  280. /// </summary>
  281. /// <value>
  282. /// <para>
  283. /// A <see cref="string"/> that represents the media type of
  284. /// the entity body.
  285. /// </para>
  286. /// <para>
  287. /// It is used for the value of the Content-Type header.
  288. /// </para>
  289. /// <para>
  290. /// <see langword="null"/> if no media type is specified.
  291. /// </para>
  292. /// <para>
  293. /// The default value is <see langword="null"/>.
  294. /// </para>
  295. /// </value>
  296. /// <exception cref="ArgumentException">
  297. /// <para>
  298. /// The value specified for a set operation is an empty string.
  299. /// </para>
  300. /// <para>
  301. /// -or-
  302. /// </para>
  303. /// <para>
  304. /// The value specified for a set operation contains
  305. /// an invalid character.
  306. /// </para>
  307. /// </exception>
  308. /// <exception cref="InvalidOperationException">
  309. /// The response is already being sent.
  310. /// </exception>
  311. /// <exception cref="ObjectDisposedException">
  312. /// This instance is closed.
  313. /// </exception>
  314. public string ContentType {
  315. get {
  316. return _contentType;
  317. }
  318. set {
  319. if (_disposed) {
  320. var name = GetType ().ToString ();
  321. throw new ObjectDisposedException (name);
  322. }
  323. if (_headersSent) {
  324. var msg = "The response is already being sent.";
  325. throw new InvalidOperationException (msg);
  326. }
  327. if (value == null) {
  328. _contentType = null;
  329. return;
  330. }
  331. if (value.Length == 0) {
  332. var msg = "An empty string.";
  333. throw new ArgumentException (msg, "value");
  334. }
  335. if (!isValidForContentType (value)) {
  336. var msg = "It contains an invalid character.";
  337. throw new ArgumentException (msg, "value");
  338. }
  339. _contentType = value;
  340. }
  341. }
  342. /// <summary>
  343. /// Gets or sets the collection of cookies sent with the response.
  344. /// </summary>
  345. /// <value>
  346. /// A <see cref="CookieCollection"/> that contains the cookies sent with
  347. /// the response.
  348. /// </value>
  349. public CookieCollection Cookies {
  350. get {
  351. if (_cookies == null)
  352. _cookies = new CookieCollection ();
  353. return _cookies;
  354. }
  355. set {
  356. _cookies = value;
  357. }
  358. }
  359. /// <summary>
  360. /// Gets or sets the collection of the HTTP headers sent to the client.
  361. /// </summary>
  362. /// <value>
  363. /// A <see cref="WebHeaderCollection"/> that contains the headers sent to
  364. /// the client.
  365. /// </value>
  366. /// <exception cref="InvalidOperationException">
  367. /// The value specified for a set operation is not valid for a response.
  368. /// </exception>
  369. public WebHeaderCollection Headers {
  370. get {
  371. if (_headers == null)
  372. _headers = new WebHeaderCollection (HttpHeaderType.Response, false);
  373. return _headers;
  374. }
  375. set {
  376. if (value == null) {
  377. _headers = null;
  378. return;
  379. }
  380. if (value.State != HttpHeaderType.Response) {
  381. var msg = "The value is not valid for a response.";
  382. throw new InvalidOperationException (msg);
  383. }
  384. _headers = value;
  385. }
  386. }
  387. /// <summary>
  388. /// Gets or sets a value indicating whether the server requests
  389. /// a persistent connection.
  390. /// </summary>
  391. /// <value>
  392. /// <para>
  393. /// <c>true</c> if the server requests a persistent connection;
  394. /// otherwise, <c>false</c>.
  395. /// </para>
  396. /// <para>
  397. /// The default value is <c>true</c>.
  398. /// </para>
  399. /// </value>
  400. /// <exception cref="InvalidOperationException">
  401. /// The response is already being sent.
  402. /// </exception>
  403. /// <exception cref="ObjectDisposedException">
  404. /// This instance is closed.
  405. /// </exception>
  406. public bool KeepAlive {
  407. get {
  408. return _keepAlive;
  409. }
  410. set {
  411. if (_disposed) {
  412. var name = GetType ().ToString ();
  413. throw new ObjectDisposedException (name);
  414. }
  415. if (_headersSent) {
  416. var msg = "The response is already being sent.";
  417. throw new InvalidOperationException (msg);
  418. }
  419. _keepAlive = value;
  420. }
  421. }
  422. /// <summary>
  423. /// Gets a stream instance to which the entity body data can be written.
  424. /// </summary>
  425. /// <value>
  426. /// A <see cref="Stream"/> instance to which the entity body data can be
  427. /// written.
  428. /// </value>
  429. /// <exception cref="ObjectDisposedException">
  430. /// This instance is closed.
  431. /// </exception>
  432. public Stream OutputStream {
  433. get {
  434. if (_disposed) {
  435. var name = GetType ().ToString ();
  436. throw new ObjectDisposedException (name);
  437. }
  438. if (_outputStream == null)
  439. _outputStream = _context.Connection.GetResponseStream ();
  440. return _outputStream;
  441. }
  442. }
  443. /// <summary>
  444. /// Gets the HTTP version used for the response.
  445. /// </summary>
  446. /// <value>
  447. /// <para>
  448. /// A <see cref="Version"/> that represents the HTTP version used for
  449. /// the response.
  450. /// </para>
  451. /// <para>
  452. /// Always returns same as 1.1.
  453. /// </para>
  454. /// </value>
  455. public Version ProtocolVersion {
  456. get {
  457. return _version;
  458. }
  459. }
  460. /// <summary>
  461. /// Gets or sets the URL to which the client is redirected to locate
  462. /// a requested resource.
  463. /// </summary>
  464. /// <value>
  465. /// <para>
  466. /// A <see cref="string"/> that represents the absolute URL for
  467. /// the redirect location.
  468. /// </para>
  469. /// <para>
  470. /// It is used for the value of the Location header.
  471. /// </para>
  472. /// <para>
  473. /// <see langword="null"/> if no redirect location is specified.
  474. /// </para>
  475. /// <para>
  476. /// The default value is <see langword="null"/>.
  477. /// </para>
  478. /// </value>
  479. /// <exception cref="ArgumentException">
  480. /// <para>
  481. /// The value specified for a set operation is an empty string.
  482. /// </para>
  483. /// <para>
  484. /// -or-
  485. /// </para>
  486. /// <para>
  487. /// The value specified for a set operation is not an absolute URL.
  488. /// </para>
  489. /// </exception>
  490. /// <exception cref="InvalidOperationException">
  491. /// The response is already being sent.
  492. /// </exception>
  493. /// <exception cref="ObjectDisposedException">
  494. /// This instance is closed.
  495. /// </exception>
  496. public string RedirectLocation {
  497. get {
  498. return _redirectLocation != null
  499. ? _redirectLocation.OriginalString
  500. : null;
  501. }
  502. set {
  503. if (_disposed) {
  504. var name = GetType ().ToString ();
  505. throw new ObjectDisposedException (name);
  506. }
  507. if (_headersSent) {
  508. var msg = "The response is already being sent.";
  509. throw new InvalidOperationException (msg);
  510. }
  511. if (value == null) {
  512. _redirectLocation = null;
  513. return;
  514. }
  515. if (value.Length == 0) {
  516. var msg = "An empty string.";
  517. throw new ArgumentException (msg, "value");
  518. }
  519. Uri uri;
  520. if (!Uri.TryCreate (value, UriKind.Absolute, out uri)) {
  521. var msg = "Not an absolute URL.";
  522. throw new ArgumentException (msg, "value");
  523. }
  524. _redirectLocation = uri;
  525. }
  526. }
  527. /// <summary>
  528. /// Gets or sets a value indicating whether the response uses the chunked
  529. /// transfer encoding.
  530. /// </summary>
  531. /// <value>
  532. /// <para>
  533. /// <c>true</c> if the response uses the chunked transfer encoding;
  534. /// otherwise, <c>false</c>.
  535. /// </para>
  536. /// <para>
  537. /// The default value is <c>false</c>.
  538. /// </para>
  539. /// </value>
  540. /// <exception cref="InvalidOperationException">
  541. /// The response is already being sent.
  542. /// </exception>
  543. /// <exception cref="ObjectDisposedException">
  544. /// This instance is closed.
  545. /// </exception>
  546. public bool SendChunked {
  547. get {
  548. return _sendChunked;
  549. }
  550. set {
  551. if (_disposed) {
  552. var name = GetType ().ToString ();
  553. throw new ObjectDisposedException (name);
  554. }
  555. if (_headersSent) {
  556. var msg = "The response is already being sent.";
  557. throw new InvalidOperationException (msg);
  558. }
  559. _sendChunked = value;
  560. }
  561. }
  562. /// <summary>
  563. /// Gets or sets the HTTP status code returned to the client.
  564. /// </summary>
  565. /// <value>
  566. /// <para>
  567. /// An <see cref="int"/> that represents the HTTP status code for
  568. /// the response to the request.
  569. /// </para>
  570. /// <para>
  571. /// The default value is 200. It indicates that the request has
  572. /// succeeded.
  573. /// </para>
  574. /// </value>
  575. /// <exception cref="InvalidOperationException">
  576. /// The response is already being sent.
  577. /// </exception>
  578. /// <exception cref="ObjectDisposedException">
  579. /// This instance is closed.
  580. /// </exception>
  581. /// <exception cref="System.Net.ProtocolViolationException">
  582. /// <para>
  583. /// The value specified for a set operation is invalid.
  584. /// </para>
  585. /// <para>
  586. /// Valid values are between 100 and 999 inclusive.
  587. /// </para>
  588. /// </exception>
  589. public int StatusCode {
  590. get {
  591. return _statusCode;
  592. }
  593. set {
  594. if (_disposed) {
  595. var name = GetType ().ToString ();
  596. throw new ObjectDisposedException (name);
  597. }
  598. if (_headersSent) {
  599. var msg = "The response is already being sent.";
  600. throw new InvalidOperationException (msg);
  601. }
  602. if (value < 100 || value > 999) {
  603. var msg = "A value is not between 100 and 999 inclusive.";
  604. throw new System.Net.ProtocolViolationException (msg);
  605. }
  606. _statusCode = value;
  607. _statusDescription = value.GetStatusDescription ();
  608. }
  609. }
  610. /// <summary>
  611. /// Gets or sets the description of the HTTP status code returned to
  612. /// the client.
  613. /// </summary>
  614. /// <value>
  615. /// <para>
  616. /// A <see cref="string"/> that represents the description of
  617. /// the HTTP status code for the response to the request.
  618. /// </para>
  619. /// <para>
  620. /// The default value is
  621. /// the <see href="http://tools.ietf.org/html/rfc2616#section-10">
  622. /// RFC 2616</see> description for the <see cref="StatusCode"/>
  623. /// property value.
  624. /// </para>
  625. /// <para>
  626. /// An empty string if an RFC 2616 description does not exist.
  627. /// </para>
  628. /// </value>
  629. /// <exception cref="ArgumentNullException">
  630. /// The value specified for a set operation is <see langword="null"/>.
  631. /// </exception>
  632. /// <exception cref="ArgumentException">
  633. /// The value specified for a set operation contains an invalid character.
  634. /// </exception>
  635. /// <exception cref="InvalidOperationException">
  636. /// The response is already being sent.
  637. /// </exception>
  638. /// <exception cref="ObjectDisposedException">
  639. /// This instance is closed.
  640. /// </exception>
  641. public string StatusDescription {
  642. get {
  643. return _statusDescription;
  644. }
  645. set {
  646. if (_disposed) {
  647. var name = GetType ().ToString ();
  648. throw new ObjectDisposedException (name);
  649. }
  650. if (_headersSent) {
  651. var msg = "The response is already being sent.";
  652. throw new InvalidOperationException (msg);
  653. }
  654. if (value == null)
  655. throw new ArgumentNullException ("value");
  656. if (value.Length == 0) {
  657. _statusDescription = _statusCode.GetStatusDescription ();
  658. return;
  659. }
  660. if (!isValidForStatusDescription (value)) {
  661. var msg = "It contains an invalid character.";
  662. throw new ArgumentException (msg, "value");
  663. }
  664. _statusDescription = value;
  665. }
  666. }
  667. #endregion
  668. #region Private Methods
  669. private bool canSetCookie (Cookie cookie)
  670. {
  671. var found = findCookie (cookie).ToList ();
  672. if (found.Count == 0)
  673. return true;
  674. var ver = cookie.Version;
  675. foreach (var c in found) {
  676. if (c.Version == ver)
  677. return true;
  678. }
  679. return false;
  680. }
  681. private void close (bool force)
  682. {
  683. _disposed = true;
  684. _context.Connection.Close (force);
  685. }
  686. private void close (byte[] responseEntity, int bufferLength, bool willBlock)
  687. {
  688. var stream = OutputStream;
  689. if (willBlock) {
  690. stream.WriteBytes (responseEntity, bufferLength);
  691. close (false);
  692. return;
  693. }
  694. stream.WriteBytesAsync (
  695. responseEntity,
  696. bufferLength,
  697. () => close (false),
  698. null
  699. );
  700. }
  701. private static string createContentTypeHeaderText (
  702. string value, Encoding encoding
  703. )
  704. {
  705. if (value.IndexOf ("charset=", StringComparison.Ordinal) > -1)
  706. return value;
  707. if (encoding == null)
  708. return value;
  709. return String.Format ("{0}; charset={1}", value, encoding.WebName);
  710. }
  711. private IEnumerable<Cookie> findCookie (Cookie cookie)
  712. {
  713. if (_cookies == null || _cookies.Count == 0)
  714. yield break;
  715. foreach (var c in _cookies) {
  716. if (c.EqualsWithoutValueAndVersion (cookie))
  717. yield return c;
  718. }
  719. }
  720. private static bool isValidForContentType (string value)
  721. {
  722. foreach (var c in value) {
  723. if (c < 0x20)
  724. return false;
  725. if (c > 0x7e)
  726. return false;
  727. if ("()<>@:\\[]?{}".IndexOf (c) > -1)
  728. return false;
  729. }
  730. return true;
  731. }
  732. private static bool isValidForStatusDescription (string value)
  733. {
  734. foreach (var c in value) {
  735. if (c < 0x20)
  736. return false;
  737. if (c > 0x7e)
  738. return false;
  739. }
  740. return true;
  741. }
  742. #endregion
  743. #region Public Methods
  744. /// <summary>
  745. /// Closes the connection to the client without sending a response.
  746. /// </summary>
  747. public void Abort ()
  748. {
  749. if (_disposed)
  750. return;
  751. close (true);
  752. }
  753. /// <summary>
  754. /// Appends the specified cookie to the cookies sent with the response.
  755. /// </summary>
  756. /// <param name="cookie">
  757. /// A <see cref="Cookie"/> to append.
  758. /// </param>
  759. /// <exception cref="ArgumentNullException">
  760. /// <paramref name="cookie"/> is <see langword="null"/>.
  761. /// </exception>
  762. public void AppendCookie (Cookie cookie)
  763. {
  764. Cookies.Add (cookie);
  765. }
  766. /// <summary>
  767. /// Appends an HTTP header with the specified name and value to
  768. /// the headers for the response.
  769. /// </summary>
  770. /// <param name="name">
  771. /// A <see cref="string"/> that specifies the name of the header to
  772. /// append.
  773. /// </param>
  774. /// <param name="value">
  775. /// A <see cref="string"/> that specifies the value of the header to
  776. /// append.
  777. /// </param>
  778. /// <exception cref="ArgumentNullException">
  779. /// <paramref name="name"/> is <see langword="null"/>.
  780. /// </exception>
  781. /// <exception cref="ArgumentException">
  782. /// <para>
  783. /// <paramref name="name"/> is an empty string.
  784. /// </para>
  785. /// <para>
  786. /// -or-
  787. /// </para>
  788. /// <para>
  789. /// <paramref name="name"/> is a string of spaces.
  790. /// </para>
  791. /// <para>
  792. /// -or-
  793. /// </para>
  794. /// <para>
  795. /// <paramref name="name"/> contains an invalid character.
  796. /// </para>
  797. /// <para>
  798. /// -or-
  799. /// </para>
  800. /// <para>
  801. /// <paramref name="value"/> contains an invalid character.
  802. /// </para>
  803. /// <para>
  804. /// -or-
  805. /// </para>
  806. /// <para>
  807. /// <paramref name="name"/> is a restricted header name.
  808. /// </para>
  809. /// </exception>
  810. /// <exception cref="ArgumentOutOfRangeException">
  811. /// The length of <paramref name="value"/> is greater than 65,535
  812. /// characters.
  813. /// </exception>
  814. /// <exception cref="InvalidOperationException">
  815. /// The current headers do not allow the header.
  816. /// </exception>
  817. public void AppendHeader (string name, string value)
  818. {
  819. Headers.Add (name, value);
  820. }
  821. /// <summary>
  822. /// Sends the response to the client and releases the resources used by
  823. /// this instance.
  824. /// </summary>
  825. public void Close ()
  826. {
  827. if (_disposed)
  828. return;
  829. close (false);
  830. }
  831. /// <summary>
  832. /// Sends the response with the specified entity body data to the client
  833. /// and releases the resources used by this instance.
  834. /// </summary>
  835. /// <param name="responseEntity">
  836. /// An array of <see cref="byte"/> that contains the entity body data.
  837. /// </param>
  838. /// <param name="willBlock">
  839. /// A <see cref="bool"/>: <c>true</c> if this method blocks execution while
  840. /// flushing the stream to the client; otherwise, <c>false</c>.
  841. /// </param>
  842. /// <exception cref="ArgumentNullException">
  843. /// <paramref name="responseEntity"/> is <see langword="null"/>.
  844. /// </exception>
  845. /// <exception cref="ObjectDisposedException">
  846. /// This instance is closed.
  847. /// </exception>
  848. public void Close (byte[] responseEntity, bool willBlock)
  849. {
  850. if (_disposed) {
  851. var name = GetType ().ToString ();
  852. throw new ObjectDisposedException (name);
  853. }
  854. if (responseEntity == null)
  855. throw new ArgumentNullException ("responseEntity");
  856. var len = responseEntity.LongLength;
  857. if (len > Int32.MaxValue) {
  858. close (responseEntity, 1024, willBlock);
  859. return;
  860. }
  861. var stream = OutputStream;
  862. if (willBlock) {
  863. stream.Write (responseEntity, 0, (int) len);
  864. close (false);
  865. return;
  866. }
  867. stream.BeginWrite (
  868. responseEntity,
  869. 0,
  870. (int) len,
  871. ar => {
  872. stream.EndWrite (ar);
  873. close (false);
  874. },
  875. null
  876. );
  877. }
  878. /// <summary>
  879. /// Copies some properties from the specified response instance to
  880. /// this instance.
  881. /// </summary>
  882. /// <param name="templateResponse">
  883. /// A <see cref="HttpListenerResponse"/> to copy.
  884. /// </param>
  885. /// <exception cref="ArgumentNullException">
  886. /// <paramref name="templateResponse"/> is <see langword="null"/>.
  887. /// </exception>
  888. public void CopyFrom (HttpListenerResponse templateResponse)
  889. {
  890. if (templateResponse == null)
  891. throw new ArgumentNullException ("templateResponse");
  892. var headers = templateResponse._headers;
  893. if (headers != null) {
  894. if (_headers != null)
  895. _headers.Clear ();
  896. Headers.Add (headers);
  897. }
  898. else {
  899. _headers = null;
  900. }
  901. _contentLength = templateResponse._contentLength;
  902. _statusCode = templateResponse._statusCode;
  903. _statusDescription = templateResponse._statusDescription;
  904. _keepAlive = templateResponse._keepAlive;
  905. _version = templateResponse._version;
  906. }
  907. /// <summary>
  908. /// Configures the response to redirect the client's request to
  909. /// the specified URL.
  910. /// </summary>
  911. /// <remarks>
  912. /// This method sets the <see cref="RedirectLocation"/> property to
  913. /// <paramref name="url"/>, the <see cref="StatusCode"/> property to
  914. /// 302, and the <see cref="StatusDescription"/> property to "Found".
  915. /// </remarks>
  916. /// <param name="url">
  917. /// A <see cref="string"/> that specifies the absolute URL to which
  918. /// the client is redirected to locate a requested resource.
  919. /// </param>
  920. /// <exception cref="ArgumentNullException">
  921. /// <paramref name="url"/> is <see langword="null"/>.
  922. /// </exception>
  923. /// <exception cref="ArgumentException">
  924. /// <para>
  925. /// <paramref name="url"/> is an empty string.
  926. /// </para>
  927. /// <para>
  928. /// -or-
  929. /// </para>
  930. /// <para>
  931. /// <paramref name="url"/> is not an absolute URL.
  932. /// </para>
  933. /// </exception>
  934. /// <exception cref="InvalidOperationException">
  935. /// The response is already being sent.
  936. /// </exception>
  937. /// <exception cref="ObjectDisposedException">
  938. /// This instance is closed.
  939. /// </exception>
  940. public void Redirect (string url)
  941. {
  942. if (_disposed) {
  943. var name = GetType ().ToString ();
  944. throw new ObjectDisposedException (name);
  945. }
  946. if (_headersSent) {
  947. var msg = "The response is already being sent.";
  948. throw new InvalidOperationException (msg);
  949. }
  950. if (url == null)
  951. throw new ArgumentNullException ("url");
  952. if (url.Length == 0) {
  953. var msg = "An empty string.";
  954. throw new ArgumentException (msg, "url");
  955. }
  956. Uri uri;
  957. if (!Uri.TryCreate (url, UriKind.Absolute, out uri)) {
  958. var msg = "Not an absolute URL.";
  959. throw new ArgumentException (msg, "url");
  960. }
  961. _redirectLocation = uri;
  962. _statusCode = 302;
  963. _statusDescription = "Found";
  964. }
  965. /// <summary>
  966. /// Adds or updates a cookie in the cookies sent with the response.
  967. /// </summary>
  968. /// <param name="cookie">
  969. /// A <see cref="Cookie"/> to set.
  970. /// </param>
  971. /// <exception cref="ArgumentNullException">
  972. /// <paramref name="cookie"/> is <see langword="null"/>.
  973. /// </exception>
  974. /// <exception cref="ArgumentException">
  975. /// <paramref name="cookie"/> already exists in the cookies but
  976. /// it cannot be updated.
  977. /// </exception>
  978. public void SetCookie (Cookie cookie)
  979. {
  980. if (cookie == null)
  981. throw new ArgumentNullException ("cookie");
  982. if (!canSetCookie (cookie)) {
  983. var msg = "It cannot be updated.";
  984. throw new ArgumentException (msg, "cookie");
  985. }
  986. Cookies.Add (cookie);
  987. }
  988. /// <summary>
  989. /// Adds or updates an HTTP header with the specified name and value in
  990. /// the headers for the response.
  991. /// </summary>
  992. /// <param name="name">
  993. /// A <see cref="string"/> that specifies the name of the header to set.
  994. /// </param>
  995. /// <param name="value">
  996. /// A <see cref="string"/> that specifies the value of the header to set.
  997. /// </param>
  998. /// <exception cref="ArgumentNullException">
  999. /// <paramref name="name"/> is <see langword="null"/>.
  1000. /// </exception>
  1001. /// <exception cref="ArgumentException">
  1002. /// <para>
  1003. /// <paramref name="name"/> is an empty string.
  1004. /// </para>
  1005. /// <para>
  1006. /// -or-
  1007. /// </para>
  1008. /// <para>
  1009. /// <paramref name="name"/> is a string of spaces.
  1010. /// </para>
  1011. /// <para>
  1012. /// -or-
  1013. /// </para>
  1014. /// <para>
  1015. /// <paramref name="name"/> contains an invalid character.
  1016. /// </para>
  1017. /// <para>
  1018. /// -or-
  1019. /// </para>
  1020. /// <para>
  1021. /// <paramref name="value"/> contains an invalid character.
  1022. /// </para>
  1023. /// <para>
  1024. /// -or-
  1025. /// </para>
  1026. /// <para>
  1027. /// <paramref name="name"/> is a restricted header name.
  1028. /// </para>
  1029. /// </exception>
  1030. /// <exception cref="ArgumentOutOfRangeException">
  1031. /// The length of <paramref name="value"/> is greater than 65,535
  1032. /// characters.
  1033. /// </exception>
  1034. /// <exception cref="InvalidOperationException">
  1035. /// The current headers do not allow the header.
  1036. /// </exception>
  1037. public void SetHeader (string name, string value)
  1038. {
  1039. Headers.Set (name, value);
  1040. }
  1041. #endregion
  1042. #region Explicit Interface Implementations
  1043. /// <summary>
  1044. /// Releases all resources used by this instance.
  1045. /// </summary>
  1046. void IDisposable.Dispose ()
  1047. {
  1048. if (_disposed)
  1049. return;
  1050. close (true);
  1051. }
  1052. #endregion
  1053. }
  1054. }