HttpListenerResponse.Managed.cs 11 KB

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