HttpListenerResponse.Managed.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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 { return _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 { return _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()
  65. {
  66. Close(true);
  67. }
  68. public void Close()
  69. {
  70. if (Disposed)
  71. return;
  72. Close(false);
  73. }
  74. public void Abort()
  75. {
  76. if (Disposed)
  77. return;
  78. Close(true);
  79. }
  80. private void Close(bool force)
  81. {
  82. Disposed = true;
  83. _httpContext.Connection.Close(force);
  84. }
  85. public void Close(byte[] responseEntity, bool willBlock)
  86. {
  87. CheckDisposed();
  88. if (responseEntity == null)
  89. {
  90. throw new ArgumentNullException(nameof(responseEntity));
  91. }
  92. if (!SentHeaders && _boundaryType != BoundaryType.Chunked)
  93. {
  94. ContentLength64 = responseEntity.Length;
  95. }
  96. if (willBlock)
  97. {
  98. try
  99. {
  100. OutputStream.Write(responseEntity, 0, responseEntity.Length);
  101. }
  102. finally
  103. {
  104. Close(false);
  105. }
  106. }
  107. else
  108. {
  109. OutputStream.BeginWrite(responseEntity, 0, responseEntity.Length, iar =>
  110. {
  111. var thisRef = (HttpListenerResponse)iar.AsyncState;
  112. try
  113. {
  114. thisRef.OutputStream.EndWrite(iar);
  115. }
  116. finally
  117. {
  118. thisRef.Close(false);
  119. }
  120. }, this);
  121. }
  122. }
  123. public void CopyFrom(HttpListenerResponse templateResponse)
  124. {
  125. _webHeaders.Clear();
  126. //_webHeaders.Add(templateResponse._webHeaders);
  127. _contentLength = templateResponse._contentLength;
  128. _statusCode = templateResponse._statusCode;
  129. _statusDescription = templateResponse._statusDescription;
  130. _keepAlive = templateResponse._keepAlive;
  131. _version = templateResponse._version;
  132. }
  133. internal void SendHeaders(bool closing, MemoryStream ms, bool isWebSocketHandshake = false)
  134. {
  135. if (!isWebSocketHandshake)
  136. {
  137. if (_webHeaders["Server"] == null)
  138. {
  139. _webHeaders.Set("Server", "Microsoft-NetCore/2.0");
  140. }
  141. if (_webHeaders["Date"] == null)
  142. {
  143. _webHeaders.Set("Date", DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture));
  144. }
  145. if (_boundaryType == BoundaryType.None)
  146. {
  147. if (HttpListenerRequest.ProtocolVersion <= HttpVersion.Version10)
  148. {
  149. _keepAlive = false;
  150. }
  151. else
  152. {
  153. _boundaryType = BoundaryType.Chunked;
  154. }
  155. if (CanSendResponseBody(_httpContext.Response.StatusCode))
  156. {
  157. _contentLength = -1;
  158. }
  159. else
  160. {
  161. _boundaryType = BoundaryType.ContentLength;
  162. _contentLength = 0;
  163. }
  164. }
  165. if (_boundaryType != BoundaryType.Chunked)
  166. {
  167. if (_boundaryType != BoundaryType.ContentLength && closing)
  168. {
  169. _contentLength = CanSendResponseBody(_httpContext.Response.StatusCode) ? -1 : 0;
  170. }
  171. if (_boundaryType == BoundaryType.ContentLength)
  172. {
  173. _webHeaders.Set("Content-Length", _contentLength.ToString("D", CultureInfo.InvariantCulture));
  174. }
  175. }
  176. /* Apache forces closing the connection for these status codes:
  177. * HttpStatusCode.BadRequest 400
  178. * HttpStatusCode.RequestTimeout 408
  179. * HttpStatusCode.LengthRequired 411
  180. * HttpStatusCode.RequestEntityTooLarge 413
  181. * HttpStatusCode.RequestUriTooLong 414
  182. * HttpStatusCode.InternalServerError 500
  183. * HttpStatusCode.ServiceUnavailable 503
  184. */
  185. bool conn_close = (_statusCode == (int)HttpStatusCode.BadRequest || _statusCode == (int)HttpStatusCode.RequestTimeout
  186. || _statusCode == (int)HttpStatusCode.LengthRequired || _statusCode == (int)HttpStatusCode.RequestEntityTooLarge
  187. || _statusCode == (int)HttpStatusCode.RequestUriTooLong || _statusCode == (int)HttpStatusCode.InternalServerError
  188. || _statusCode == (int)HttpStatusCode.ServiceUnavailable);
  189. if (!conn_close)
  190. {
  191. conn_close = !_httpContext.Request.KeepAlive;
  192. }
  193. // They sent both KeepAlive: true and Connection: close
  194. if (!_keepAlive || conn_close)
  195. {
  196. _webHeaders.Set("Connection", "Close");
  197. conn_close = true;
  198. }
  199. if (SendChunked)
  200. {
  201. _webHeaders.Set("Transfer-Encoding", "Chunked");
  202. }
  203. int reuses = _httpContext.Connection.Reuses;
  204. if (reuses >= 100)
  205. {
  206. _forceCloseChunked = true;
  207. if (!conn_close)
  208. {
  209. _webHeaders.Set("Connection", "Close");
  210. conn_close = true;
  211. }
  212. }
  213. if (HttpListenerRequest.ProtocolVersion <= HttpVersion.Version10)
  214. {
  215. if (_keepAlive)
  216. {
  217. Headers["Keep-Alive"] = "true";
  218. }
  219. if (!conn_close)
  220. {
  221. _webHeaders.Set("Connection", "Keep-Alive");
  222. }
  223. }
  224. ComputeCookies();
  225. }
  226. Encoding encoding = _textEncoding.GetDefaultEncoding();
  227. StreamWriter writer = new StreamWriter(ms, encoding, 256);
  228. writer.Write("HTTP/1.1 {0} ", _statusCode); // "1.1" matches Windows implementation, which ignores the response version
  229. writer.Flush();
  230. byte[] statusDescriptionBytes = WebHeaderEncoding.GetBytes(StatusDescription);
  231. ms.Write(statusDescriptionBytes, 0, statusDescriptionBytes.Length);
  232. writer.Write("\r\n");
  233. writer.Write(FormatHeaders(_webHeaders));
  234. writer.Flush();
  235. int preamble = encoding.GetPreamble().Length;
  236. EnsureResponseStream();
  237. /* Assumes that the ms was at position 0 */
  238. ms.Position = preamble;
  239. SentHeaders = !isWebSocketHandshake;
  240. }
  241. private static bool HeaderCanHaveEmptyValue(string name) =>
  242. !string.Equals(name, "Location", StringComparison.OrdinalIgnoreCase);
  243. private static string FormatHeaders(WebHeaderCollection headers)
  244. {
  245. var sb = new StringBuilder();
  246. for (int i = 0; i < headers.Count; i++)
  247. {
  248. string key = headers.GetKey(i);
  249. string[] values = headers.GetValues(i);
  250. int startingLength = sb.Length;
  251. sb.Append(key).Append(": ");
  252. bool anyValues = false;
  253. for (int j = 0; j < values.Length; j++)
  254. {
  255. string value = values[j];
  256. if (!string.IsNullOrWhiteSpace(value))
  257. {
  258. if (anyValues)
  259. {
  260. sb.Append(", ");
  261. }
  262. sb.Append(value);
  263. anyValues = true;
  264. }
  265. }
  266. if (anyValues || HeaderCanHaveEmptyValue(key))
  267. {
  268. // Complete the header
  269. sb.Append("\r\n");
  270. }
  271. else
  272. {
  273. // Empty header; remove it.
  274. sb.Length = startingLength;
  275. }
  276. }
  277. return sb.Append("\r\n").ToString();
  278. }
  279. private bool Disposed { get; set; }
  280. internal bool SentHeaders { get; set; }
  281. public Task TransmitFile(string path, long offset, long count, FileShareMode fileShareMode, CancellationToken cancellationToken)
  282. {
  283. return ((HttpResponseStream)OutputStream).TransmitFile(path, offset, count, fileShareMode, cancellationToken);
  284. }
  285. }
  286. }