HttpListenerResponse.Managed.cs 11 KB

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