HttpListenerResponse.Managed.cs 11 KB

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