HttpListenerResponse.cs 16 KB

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