HttpListenerResponse.Managed.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Model.Text;
  10. using SocketHttpListener.Primitives;
  11. using System.Threading;
  12. using MediaBrowser.Model.IO;
  13. namespace SocketHttpListener.Net
  14. {
  15. public sealed partial class HttpListenerResponse : IDisposable
  16. {
  17. private long _contentLength;
  18. private Version _version = HttpVersion.Version11;
  19. private int _statusCode = 200;
  20. internal object _headersLock = new object();
  21. private bool _forceCloseChunked;
  22. private ITextEncoding _textEncoding;
  23. internal HttpListenerResponse(HttpListenerContext context, ITextEncoding textEncoding)
  24. {
  25. _httpContext = context;
  26. _textEncoding = textEncoding;
  27. }
  28. internal bool ForceCloseChunked => _forceCloseChunked;
  29. private void EnsureResponseStream()
  30. {
  31. if (_responseStream == null)
  32. {
  33. _responseStream = _httpContext.Connection.GetResponseStream();
  34. }
  35. }
  36. public Version ProtocolVersion
  37. {
  38. get => _version;
  39. set
  40. {
  41. CheckDisposed();
  42. if (value == null)
  43. {
  44. throw new ArgumentNullException(nameof(value));
  45. }
  46. if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1))
  47. {
  48. throw new ArgumentException("Wrong version");
  49. }
  50. _version = new Version(value.Major, value.Minor); // match Windows behavior, trimming to just Major.Minor
  51. }
  52. }
  53. public int StatusCode
  54. {
  55. get => _statusCode;
  56. set
  57. {
  58. CheckDisposed();
  59. if (value < 100 || value > 999)
  60. throw new ProtocolViolationException("Invalid status");
  61. _statusCode = value;
  62. }
  63. }
  64. private void Dispose() => Close(true);
  65. public void Close()
  66. {
  67. if (Disposed)
  68. return;
  69. Close(false);
  70. }
  71. public void Abort()
  72. {
  73. if (Disposed)
  74. return;
  75. Close(true);
  76. }
  77. private void Close(bool force)
  78. {
  79. Disposed = true;
  80. _httpContext.Connection.Close(force);
  81. }
  82. public void Close(byte[] responseEntity, bool willBlock)
  83. {
  84. CheckDisposed();
  85. if (responseEntity == null)
  86. {
  87. throw new ArgumentNullException(nameof(responseEntity));
  88. }
  89. if (!SentHeaders && _boundaryType != BoundaryType.Chunked)
  90. {
  91. ContentLength64 = responseEntity.Length;
  92. }
  93. if (willBlock)
  94. {
  95. try
  96. {
  97. OutputStream.Write(responseEntity, 0, responseEntity.Length);
  98. }
  99. finally
  100. {
  101. Close(false);
  102. }
  103. }
  104. else
  105. {
  106. OutputStream.BeginWrite(responseEntity, 0, responseEntity.Length, iar =>
  107. {
  108. var thisRef = (HttpListenerResponse)iar.AsyncState;
  109. try
  110. {
  111. thisRef.OutputStream.EndWrite(iar);
  112. }
  113. finally
  114. {
  115. thisRef.Close(false);
  116. }
  117. }, this);
  118. }
  119. }
  120. public void CopyFrom(HttpListenerResponse templateResponse)
  121. {
  122. _webHeaders.Clear();
  123. //_webHeaders.Add(templateResponse._webHeaders);
  124. _contentLength = templateResponse._contentLength;
  125. _statusCode = templateResponse._statusCode;
  126. _statusDescription = templateResponse._statusDescription;
  127. _keepAlive = templateResponse._keepAlive;
  128. _version = templateResponse._version;
  129. }
  130. internal void SendHeaders(bool closing, MemoryStream ms, bool isWebSocketHandshake = false)
  131. {
  132. if (!isWebSocketHandshake)
  133. {
  134. if (_webHeaders["Server"] == null)
  135. {
  136. _webHeaders.Set("Server", "Microsoft-NetCore/2.0");
  137. }
  138. if (_webHeaders["Date"] == null)
  139. {
  140. _webHeaders.Set("Date", DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture));
  141. }
  142. if (_boundaryType == BoundaryType.None)
  143. {
  144. if (HttpListenerRequest.ProtocolVersion <= HttpVersion.Version10)
  145. {
  146. _keepAlive = false;
  147. }
  148. else
  149. {
  150. _boundaryType = BoundaryType.Chunked;
  151. }
  152. if (CanSendResponseBody(_httpContext.Response.StatusCode))
  153. {
  154. _contentLength = -1;
  155. }
  156. else
  157. {
  158. _boundaryType = BoundaryType.ContentLength;
  159. _contentLength = 0;
  160. }
  161. }
  162. if (_boundaryType != BoundaryType.Chunked)
  163. {
  164. if (_boundaryType != BoundaryType.ContentLength && closing)
  165. {
  166. _contentLength = CanSendResponseBody(_httpContext.Response.StatusCode) ? -1 : 0;
  167. }
  168. if (_boundaryType == BoundaryType.ContentLength)
  169. {
  170. _webHeaders.Set("Content-Length", _contentLength.ToString("D", CultureInfo.InvariantCulture));
  171. }
  172. }
  173. /* Apache forces closing the connection for these status codes:
  174. * HttpStatusCode.BadRequest 400
  175. * HttpStatusCode.RequestTimeout 408
  176. * HttpStatusCode.LengthRequired 411
  177. * HttpStatusCode.RequestEntityTooLarge 413
  178. * HttpStatusCode.RequestUriTooLong 414
  179. * HttpStatusCode.InternalServerError 500
  180. * HttpStatusCode.ServiceUnavailable 503
  181. */
  182. bool conn_close = (_statusCode == (int)HttpStatusCode.BadRequest || _statusCode == (int)HttpStatusCode.RequestTimeout
  183. || _statusCode == (int)HttpStatusCode.LengthRequired || _statusCode == (int)HttpStatusCode.RequestEntityTooLarge
  184. || _statusCode == (int)HttpStatusCode.RequestUriTooLong || _statusCode == (int)HttpStatusCode.InternalServerError
  185. || _statusCode == (int)HttpStatusCode.ServiceUnavailable);
  186. if (!conn_close)
  187. {
  188. conn_close = !_httpContext.Request.KeepAlive;
  189. }
  190. // They sent both KeepAlive: true and Connection: close
  191. if (!_keepAlive || conn_close)
  192. {
  193. _webHeaders.Set("Connection", "Close");
  194. conn_close = true;
  195. }
  196. if (SendChunked)
  197. {
  198. _webHeaders.Set("Transfer-Encoding", "Chunked");
  199. }
  200. int reuses = _httpContext.Connection.Reuses;
  201. if (reuses >= 100)
  202. {
  203. _forceCloseChunked = true;
  204. if (!conn_close)
  205. {
  206. _webHeaders.Set("Connection", "Close");
  207. conn_close = true;
  208. }
  209. }
  210. if (HttpListenerRequest.ProtocolVersion <= HttpVersion.Version10)
  211. {
  212. if (_keepAlive)
  213. {
  214. Headers["Keep-Alive"] = "true";
  215. }
  216. if (!conn_close)
  217. {
  218. _webHeaders.Set("Connection", "Keep-Alive");
  219. }
  220. }
  221. ComputeCookies();
  222. }
  223. Encoding encoding = _textEncoding.GetDefaultEncoding();
  224. StreamWriter writer = new StreamWriter(ms, encoding, 256);
  225. writer.Write("HTTP/1.1 {0} ", _statusCode); // "1.1" matches Windows implementation, which ignores the response version
  226. writer.Flush();
  227. byte[] statusDescriptionBytes = WebHeaderEncoding.GetBytes(StatusDescription);
  228. ms.Write(statusDescriptionBytes, 0, statusDescriptionBytes.Length);
  229. writer.Write("\r\n");
  230. writer.Write(FormatHeaders(_webHeaders));
  231. writer.Flush();
  232. int preamble = encoding.GetPreamble().Length;
  233. EnsureResponseStream();
  234. /* Assumes that the ms was at position 0 */
  235. ms.Position = preamble;
  236. SentHeaders = !isWebSocketHandshake;
  237. }
  238. private static bool HeaderCanHaveEmptyValue(string name) =>
  239. !string.Equals(name, "Location", StringComparison.OrdinalIgnoreCase);
  240. private static string FormatHeaders(WebHeaderCollection headers)
  241. {
  242. var sb = new StringBuilder();
  243. for (int i = 0; i < headers.Count; i++)
  244. {
  245. string key = headers.GetKey(i);
  246. string[] values = headers.GetValues(i);
  247. int startingLength = sb.Length;
  248. sb.Append(key).Append(": ");
  249. bool anyValues = false;
  250. for (int j = 0; j < values.Length; j++)
  251. {
  252. string value = values[j];
  253. if (!string.IsNullOrWhiteSpace(value))
  254. {
  255. if (anyValues)
  256. {
  257. sb.Append(", ");
  258. }
  259. sb.Append(value);
  260. anyValues = true;
  261. }
  262. }
  263. if (anyValues || HeaderCanHaveEmptyValue(key))
  264. {
  265. // Complete the header
  266. sb.Append("\r\n");
  267. }
  268. else
  269. {
  270. // Empty header; remove it.
  271. sb.Length = startingLength;
  272. }
  273. }
  274. return sb.Append("\r\n").ToString();
  275. }
  276. private bool Disposed { get; set; }
  277. internal bool SentHeaders { get; set; }
  278. public Task TransmitFile(string path, long offset, long count, FileShareMode fileShareMode, CancellationToken cancellationToken)
  279. {
  280. return ((HttpResponseStream)OutputStream).TransmitFile(path, offset, count, fileShareMode, cancellationToken);
  281. }
  282. }
  283. }