HttpListenerResponse.Managed.cs 11 KB

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