HttpListenerResponse.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. using System;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Net;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Model.IO;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Text;
  11. using SocketHttpListener.Primitives;
  12. namespace SocketHttpListener.Net
  13. {
  14. public sealed class HttpListenerResponse : IDisposable
  15. {
  16. bool disposed;
  17. Encoding content_encoding;
  18. long content_length;
  19. bool cl_set;
  20. string content_type;
  21. CookieCollection cookies;
  22. WebHeaderCollection headers = new WebHeaderCollection();
  23. bool keep_alive = true;
  24. Stream output_stream;
  25. Version version = HttpVersion.Version11;
  26. string location;
  27. int status_code = 200;
  28. string status_description = "OK";
  29. bool chunked;
  30. HttpListenerContext context;
  31. internal bool HeadersSent;
  32. internal object headers_lock = new object();
  33. private readonly ILogger _logger;
  34. private readonly ITextEncoding _textEncoding;
  35. private readonly IFileSystem _fileSystem;
  36. internal HttpListenerResponse(HttpListenerContext context, ILogger logger, ITextEncoding textEncoding, IFileSystem fileSystem)
  37. {
  38. this.context = context;
  39. _logger = logger;
  40. _textEncoding = textEncoding;
  41. _fileSystem = fileSystem;
  42. }
  43. internal bool CloseConnection
  44. {
  45. get
  46. {
  47. return headers["Connection"] == "close";
  48. }
  49. }
  50. public bool ForceCloseChunked
  51. {
  52. get { return false; }
  53. }
  54. public Encoding ContentEncoding
  55. {
  56. get
  57. {
  58. if (content_encoding == null)
  59. content_encoding = _textEncoding.GetDefaultEncoding();
  60. return content_encoding;
  61. }
  62. set
  63. {
  64. if (disposed)
  65. throw new ObjectDisposedException(GetType().ToString());
  66. content_encoding = value;
  67. }
  68. }
  69. public long ContentLength64
  70. {
  71. get { return content_length; }
  72. set
  73. {
  74. if (disposed)
  75. throw new ObjectDisposedException(GetType().ToString());
  76. if (HeadersSent)
  77. throw new InvalidOperationException("Cannot be changed after headers are sent.");
  78. if (value < 0)
  79. throw new ArgumentOutOfRangeException("Must be >= 0", "value");
  80. cl_set = true;
  81. content_length = value;
  82. }
  83. }
  84. public string ContentType
  85. {
  86. get { return content_type; }
  87. set
  88. {
  89. // TODO: is null ok?
  90. if (disposed)
  91. throw new ObjectDisposedException(GetType().ToString());
  92. content_type = value;
  93. }
  94. }
  95. // RFC 2109, 2965 + the netscape specification at http://wp.netscape.com/newsref/std/cookie_spec.html
  96. public CookieCollection Cookies
  97. {
  98. get
  99. {
  100. if (cookies == null)
  101. cookies = new CookieCollection();
  102. return cookies;
  103. }
  104. set { cookies = value; } // null allowed?
  105. }
  106. public WebHeaderCollection Headers
  107. {
  108. get { return headers; }
  109. set
  110. {
  111. /**
  112. * "If you attempt to set a Content-Length, Keep-Alive, Transfer-Encoding, or
  113. * WWW-Authenticate header using the Headers property, an exception will be
  114. * thrown. Use the KeepAlive or ContentLength64 properties to set these headers.
  115. * You cannot set the Transfer-Encoding or WWW-Authenticate headers manually."
  116. */
  117. // TODO: check if this is marked readonly after headers are sent.
  118. headers = value;
  119. }
  120. }
  121. public bool KeepAlive
  122. {
  123. get { return keep_alive; }
  124. set
  125. {
  126. if (disposed)
  127. throw new ObjectDisposedException(GetType().ToString());
  128. keep_alive = value;
  129. }
  130. }
  131. public Stream OutputStream
  132. {
  133. get
  134. {
  135. if (output_stream == null)
  136. output_stream = context.Connection.GetResponseStream();
  137. return output_stream;
  138. }
  139. }
  140. public Version ProtocolVersion
  141. {
  142. get { return version; }
  143. set
  144. {
  145. if (disposed)
  146. throw new ObjectDisposedException(GetType().ToString());
  147. if (value == null)
  148. throw new ArgumentNullException("value");
  149. if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1))
  150. throw new ArgumentException("Must be 1.0 or 1.1", "value");
  151. if (disposed)
  152. throw new ObjectDisposedException(GetType().ToString());
  153. version = value;
  154. }
  155. }
  156. public string RedirectLocation
  157. {
  158. get { return location; }
  159. set
  160. {
  161. if (disposed)
  162. throw new ObjectDisposedException(GetType().ToString());
  163. location = value;
  164. }
  165. }
  166. public bool SendChunked
  167. {
  168. get { return chunked; }
  169. set
  170. {
  171. if (disposed)
  172. throw new ObjectDisposedException(GetType().ToString());
  173. chunked = value;
  174. }
  175. }
  176. public int StatusCode
  177. {
  178. get { return status_code; }
  179. set
  180. {
  181. if (disposed)
  182. throw new ObjectDisposedException(GetType().ToString());
  183. if (value < 100 || value > 999)
  184. throw new ProtocolViolationException("StatusCode must be between 100 and 999.");
  185. status_code = value;
  186. status_description = GetStatusDescription(value);
  187. }
  188. }
  189. internal static string GetStatusDescription(int code)
  190. {
  191. switch (code)
  192. {
  193. case 100: return "Continue";
  194. case 101: return "Switching Protocols";
  195. case 102: return "Processing";
  196. case 200: return "OK";
  197. case 201: return "Created";
  198. case 202: return "Accepted";
  199. case 203: return "Non-Authoritative Information";
  200. case 204: return "No Content";
  201. case 205: return "Reset Content";
  202. case 206: return "Partial Content";
  203. case 207: return "Multi-Status";
  204. case 300: return "Multiple Choices";
  205. case 301: return "Moved Permanently";
  206. case 302: return "Found";
  207. case 303: return "See Other";
  208. case 304: return "Not Modified";
  209. case 305: return "Use Proxy";
  210. case 307: return "Temporary Redirect";
  211. case 400: return "Bad Request";
  212. case 401: return "Unauthorized";
  213. case 402: return "Payment Required";
  214. case 403: return "Forbidden";
  215. case 404: return "Not Found";
  216. case 405: return "Method Not Allowed";
  217. case 406: return "Not Acceptable";
  218. case 407: return "Proxy Authentication Required";
  219. case 408: return "Request Timeout";
  220. case 409: return "Conflict";
  221. case 410: return "Gone";
  222. case 411: return "Length Required";
  223. case 412: return "Precondition Failed";
  224. case 413: return "Request Entity Too Large";
  225. case 414: return "Request-Uri Too Long";
  226. case 415: return "Unsupported Media Type";
  227. case 416: return "Requested Range Not Satisfiable";
  228. case 417: return "Expectation Failed";
  229. case 422: return "Unprocessable Entity";
  230. case 423: return "Locked";
  231. case 424: return "Failed Dependency";
  232. case 500: return "Internal Server Error";
  233. case 501: return "Not Implemented";
  234. case 502: return "Bad Gateway";
  235. case 503: return "Service Unavailable";
  236. case 504: return "Gateway Timeout";
  237. case 505: return "Http Version Not Supported";
  238. case 507: return "Insufficient Storage";
  239. }
  240. return "";
  241. }
  242. public string StatusDescription
  243. {
  244. get { return status_description; }
  245. set
  246. {
  247. status_description = value;
  248. }
  249. }
  250. void IDisposable.Dispose()
  251. {
  252. Close(true); //TODO: Abort or Close?
  253. }
  254. public void Abort()
  255. {
  256. if (disposed)
  257. return;
  258. Close(true);
  259. }
  260. public void AddHeader(string name, string value)
  261. {
  262. if (name == null)
  263. throw new ArgumentNullException("name");
  264. if (name == "")
  265. throw new ArgumentException("'name' cannot be empty", "name");
  266. //TODO: check for forbidden headers and invalid characters
  267. if (value.Length > 65535)
  268. throw new ArgumentOutOfRangeException("value");
  269. headers.Set(name, value);
  270. }
  271. public void AppendCookie(Cookie cookie)
  272. {
  273. if (cookie == null)
  274. throw new ArgumentNullException("cookie");
  275. Cookies.Add(cookie);
  276. }
  277. public void AppendHeader(string name, string value)
  278. {
  279. if (name == null)
  280. throw new ArgumentNullException("name");
  281. if (name == "")
  282. throw new ArgumentException("'name' cannot be empty", "name");
  283. if (value.Length > 65535)
  284. throw new ArgumentOutOfRangeException("value");
  285. headers.Add(name, value);
  286. }
  287. private void Close(bool force)
  288. {
  289. if (force)
  290. {
  291. _logger.Debug("HttpListenerResponse force closing HttpConnection");
  292. }
  293. disposed = true;
  294. context.Connection.Close(force);
  295. }
  296. public void Close(byte[] responseEntity, bool willBlock)
  297. {
  298. //CheckDisposed();
  299. if (responseEntity == null)
  300. {
  301. throw new ArgumentNullException(nameof(responseEntity));
  302. }
  303. //if (_boundaryType != BoundaryType.Chunked)
  304. {
  305. ContentLength64 = responseEntity.Length;
  306. }
  307. if (willBlock)
  308. {
  309. try
  310. {
  311. OutputStream.Write(responseEntity, 0, responseEntity.Length);
  312. }
  313. finally
  314. {
  315. Close(false);
  316. }
  317. }
  318. else
  319. {
  320. OutputStream.BeginWrite(responseEntity, 0, responseEntity.Length, iar =>
  321. {
  322. var thisRef = (HttpListenerResponse)iar.AsyncState;
  323. try
  324. {
  325. thisRef.OutputStream.EndWrite(iar);
  326. }
  327. finally
  328. {
  329. thisRef.Close(false);
  330. }
  331. }, this);
  332. }
  333. }
  334. public void Close()
  335. {
  336. if (disposed)
  337. return;
  338. Close(false);
  339. }
  340. public void Redirect(string url)
  341. {
  342. StatusCode = 302; // Found
  343. location = url;
  344. }
  345. bool FindCookie(Cookie cookie)
  346. {
  347. string name = cookie.Name;
  348. string domain = cookie.Domain;
  349. string path = cookie.Path;
  350. foreach (Cookie c in cookies)
  351. {
  352. if (name != c.Name)
  353. continue;
  354. if (domain != c.Domain)
  355. continue;
  356. if (path == c.Path)
  357. return true;
  358. }
  359. return false;
  360. }
  361. public void DetermineIfChunked()
  362. {
  363. if (chunked)
  364. {
  365. return;
  366. }
  367. Version v = context.Request.ProtocolVersion;
  368. if (!cl_set && !chunked && v >= HttpVersion.Version11)
  369. chunked = true;
  370. if (!chunked && string.Equals(headers["Transfer-Encoding"], "chunked"))
  371. {
  372. chunked = true;
  373. }
  374. }
  375. internal void SendHeaders(bool closing, MemoryStream ms)
  376. {
  377. Encoding encoding = content_encoding;
  378. if (encoding == null)
  379. encoding = _textEncoding.GetDefaultEncoding();
  380. if (content_type != null)
  381. {
  382. if (content_encoding != null && content_type.IndexOf("charset=", StringComparison.OrdinalIgnoreCase) == -1)
  383. {
  384. string enc_name = content_encoding.WebName;
  385. headers.SetInternal("Content-Type", content_type + "; charset=" + enc_name);
  386. }
  387. else
  388. {
  389. headers.SetInternal("Content-Type", content_type);
  390. }
  391. }
  392. if (headers["Server"] == null)
  393. headers.SetInternal("Server", "Mono-HTTPAPI/1.0");
  394. CultureInfo inv = CultureInfo.InvariantCulture;
  395. if (headers["Date"] == null)
  396. headers.SetInternal("Date", DateTime.UtcNow.ToString("r", inv));
  397. if (!chunked)
  398. {
  399. if (!cl_set && closing)
  400. {
  401. cl_set = true;
  402. content_length = 0;
  403. }
  404. if (cl_set)
  405. headers.SetInternal("Content-Length", content_length.ToString(inv));
  406. }
  407. Version v = context.Request.ProtocolVersion;
  408. if (!cl_set && !chunked && v >= HttpVersion.Version11)
  409. chunked = true;
  410. /* Apache forces closing the connection for these status codes:
  411. * HttpStatusCode.BadRequest 400
  412. * HttpStatusCode.RequestTimeout 408
  413. * HttpStatusCode.LengthRequired 411
  414. * HttpStatusCode.RequestEntityTooLarge 413
  415. * HttpStatusCode.RequestUriTooLong 414
  416. * HttpStatusCode.InternalServerError 500
  417. * HttpStatusCode.ServiceUnavailable 503
  418. */
  419. bool conn_close = status_code == 400 || status_code == 408 || status_code == 411 ||
  420. status_code == 413 || status_code == 414 ||
  421. status_code == 500 ||
  422. status_code == 503;
  423. if (conn_close == false)
  424. conn_close = !context.Request.KeepAlive;
  425. // They sent both KeepAlive: true and Connection: close!?
  426. if (!keep_alive || conn_close)
  427. {
  428. headers.SetInternal("Connection", "close");
  429. conn_close = true;
  430. }
  431. if (chunked)
  432. headers.SetInternal("Transfer-Encoding", "chunked");
  433. //int reuses = context.Connection.Reuses;
  434. //if (reuses >= 100)
  435. //{
  436. // _logger.Debug("HttpListenerResponse - keep alive has exceeded 100 uses and will be closed.");
  437. // force_close_chunked = true;
  438. // if (!conn_close)
  439. // {
  440. // headers.SetInternal("Connection", "close");
  441. // conn_close = true;
  442. // }
  443. //}
  444. if (!conn_close)
  445. {
  446. if (context.Request.ProtocolVersion <= HttpVersion.Version10)
  447. headers.SetInternal("Connection", "keep-alive");
  448. }
  449. if (location != null)
  450. headers.SetInternal("Location", location);
  451. if (cookies != null)
  452. {
  453. foreach (Cookie cookie in cookies)
  454. headers.SetInternal("Set-Cookie", cookie.ToString());
  455. }
  456. headers.SetInternal("Status", status_code.ToString(CultureInfo.InvariantCulture));
  457. using (StreamWriter writer = new StreamWriter(ms, encoding, 256, true))
  458. {
  459. writer.Write("HTTP/{0} {1} {2}\r\n", version, status_code, status_description);
  460. string headers_str = headers.ToStringMultiValue();
  461. writer.Write(headers_str);
  462. writer.Flush();
  463. }
  464. int preamble = encoding.GetPreamble().Length;
  465. if (output_stream == null)
  466. output_stream = context.Connection.GetResponseStream();
  467. /* Assumes that the ms was at position 0 */
  468. ms.Position = preamble;
  469. HeadersSent = true;
  470. }
  471. public void SetCookie(Cookie cookie)
  472. {
  473. if (cookie == null)
  474. throw new ArgumentNullException("cookie");
  475. if (cookies != null)
  476. {
  477. if (FindCookie(cookie))
  478. throw new ArgumentException("The cookie already exists.");
  479. }
  480. else
  481. {
  482. cookies = new CookieCollection();
  483. }
  484. cookies.Add(cookie);
  485. }
  486. public Task TransmitFile(string path, long offset, long count, FileShareMode fileShareMode, CancellationToken cancellationToken)
  487. {
  488. return ((HttpResponseStream)OutputStream).TransmitFile(path, offset, count, fileShareMode, cancellationToken);
  489. }
  490. }
  491. }