BaseHandler.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. using MediaBrowser.Common.Logging;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Collections.Specialized;
  6. using System.IO;
  7. using System.IO.Compression;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Threading.Tasks;
  11. namespace MediaBrowser.Common.Net.Handlers
  12. {
  13. public abstract class BaseHandler
  14. {
  15. public abstract bool HandlesRequest(HttpListenerRequest request);
  16. private Stream CompressedStream { get; set; }
  17. public virtual bool? UseChunkedEncoding
  18. {
  19. get
  20. {
  21. return null;
  22. }
  23. }
  24. private bool _totalContentLengthDiscovered;
  25. private long? _totalContentLength;
  26. public long? TotalContentLength
  27. {
  28. get
  29. {
  30. if (!_totalContentLengthDiscovered)
  31. {
  32. _totalContentLength = GetTotalContentLength();
  33. _totalContentLengthDiscovered = true;
  34. }
  35. return _totalContentLength;
  36. }
  37. }
  38. protected virtual bool SupportsByteRangeRequests
  39. {
  40. get
  41. {
  42. return false;
  43. }
  44. }
  45. /// <summary>
  46. /// The original HttpListenerContext
  47. /// </summary>
  48. protected HttpListenerContext HttpListenerContext { get; set; }
  49. /// <summary>
  50. /// The original QueryString
  51. /// </summary>
  52. protected NameValueCollection QueryString
  53. {
  54. get
  55. {
  56. return HttpListenerContext.Request.QueryString;
  57. }
  58. }
  59. private List<KeyValuePair<long, long?>> _requestedRanges;
  60. protected IEnumerable<KeyValuePair<long, long?>> RequestedRanges
  61. {
  62. get
  63. {
  64. if (_requestedRanges == null)
  65. {
  66. _requestedRanges = new List<KeyValuePair<long, long?>>();
  67. if (IsRangeRequest)
  68. {
  69. // Example: bytes=0-,32-63
  70. string[] ranges = HttpListenerContext.Request.Headers["Range"].Split('=')[1].Split(',');
  71. foreach (string range in ranges)
  72. {
  73. string[] vals = range.Split('-');
  74. long start = 0;
  75. long? end = null;
  76. if (!string.IsNullOrEmpty(vals[0]))
  77. {
  78. start = long.Parse(vals[0]);
  79. }
  80. if (!string.IsNullOrEmpty(vals[1]))
  81. {
  82. end = long.Parse(vals[1]);
  83. }
  84. _requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
  85. }
  86. }
  87. }
  88. return _requestedRanges;
  89. }
  90. }
  91. protected bool IsRangeRequest
  92. {
  93. get
  94. {
  95. return HttpListenerContext.Request.Headers.AllKeys.Contains("Range");
  96. }
  97. }
  98. private bool ClientSupportsCompression
  99. {
  100. get
  101. {
  102. string enc = HttpListenerContext.Request.Headers["Accept-Encoding"] ?? string.Empty;
  103. return enc.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1 || enc.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1;
  104. }
  105. }
  106. private string CompressionMethod
  107. {
  108. get
  109. {
  110. string enc = HttpListenerContext.Request.Headers["Accept-Encoding"] ?? string.Empty;
  111. if (enc.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1)
  112. {
  113. return "deflate";
  114. }
  115. if (enc.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
  116. {
  117. return "gzip";
  118. }
  119. return null;
  120. }
  121. }
  122. public virtual async Task ProcessRequest(HttpListenerContext ctx)
  123. {
  124. HttpListenerContext = ctx;
  125. string url = ctx.Request.Url.ToString();
  126. Logger.LogInfo("Http Server received request at: " + url);
  127. Logger.LogInfo("Http Headers: " + string.Join(",", ctx.Request.Headers.AllKeys.Select(k => k + "=" + ctx.Request.Headers[k])));
  128. ctx.Response.AddHeader("Access-Control-Allow-Origin", "*");
  129. ctx.Response.KeepAlive = true;
  130. try
  131. {
  132. if (SupportsByteRangeRequests && IsRangeRequest)
  133. {
  134. ctx.Response.Headers["Accept-Ranges"] = "bytes";
  135. }
  136. ResponseInfo responseInfo = await GetResponseInfo().ConfigureAwait(false);
  137. if (responseInfo.IsResponseValid)
  138. {
  139. // Set the initial status code
  140. // When serving a range request, we need to return status code 206 to indicate a partial response body
  141. responseInfo.StatusCode = SupportsByteRangeRequests && IsRangeRequest ? 206 : 200;
  142. }
  143. ctx.Response.ContentType = responseInfo.ContentType;
  144. if (!string.IsNullOrEmpty(responseInfo.Etag))
  145. {
  146. ctx.Response.Headers["ETag"] = responseInfo.Etag;
  147. }
  148. if (ctx.Request.Headers.AllKeys.Contains("If-Modified-Since"))
  149. {
  150. DateTime ifModifiedSince;
  151. if (DateTime.TryParse(ctx.Request.Headers["If-Modified-Since"], out ifModifiedSince))
  152. {
  153. // If the cache hasn't expired yet just return a 304
  154. if (IsCacheValid(ifModifiedSince.ToUniversalTime(), responseInfo.CacheDuration, responseInfo.DateLastModified))
  155. {
  156. // ETag must also match (if supplied)
  157. if ((responseInfo.Etag ?? string.Empty).Equals(ctx.Request.Headers["If-None-Match"] ?? string.Empty))
  158. {
  159. responseInfo.StatusCode = 304;
  160. }
  161. }
  162. }
  163. }
  164. Logger.LogInfo("Responding with status code {0} for url {1}", responseInfo.StatusCode, url);
  165. if (responseInfo.IsResponseValid)
  166. {
  167. await ProcessUncachedRequest(ctx, responseInfo).ConfigureAwait(false);
  168. }
  169. else
  170. {
  171. ctx.Response.StatusCode = responseInfo.StatusCode;
  172. ctx.Response.SendChunked = false;
  173. }
  174. }
  175. catch (Exception ex)
  176. {
  177. // It might be too late if some response data has already been transmitted, but try to set this
  178. ctx.Response.StatusCode = 500;
  179. Logger.LogException(ex);
  180. }
  181. finally
  182. {
  183. DisposeResponseStream();
  184. }
  185. }
  186. private async Task ProcessUncachedRequest(HttpListenerContext ctx, ResponseInfo responseInfo)
  187. {
  188. long? totalContentLength = TotalContentLength;
  189. // By default, use chunked encoding if we don't know the content length
  190. bool useChunkedEncoding = UseChunkedEncoding == null ? (totalContentLength == null) : UseChunkedEncoding.Value;
  191. // Don't force this to true. HttpListener will default it to true if supported by the client.
  192. if (!useChunkedEncoding)
  193. {
  194. ctx.Response.SendChunked = false;
  195. }
  196. // Set the content length, if we know it
  197. if (totalContentLength.HasValue)
  198. {
  199. ctx.Response.ContentLength64 = totalContentLength.Value;
  200. }
  201. var compressResponse = responseInfo.CompressResponse && ClientSupportsCompression;
  202. // Add the compression header
  203. if (compressResponse)
  204. {
  205. ctx.Response.AddHeader("Content-Encoding", CompressionMethod);
  206. }
  207. if (responseInfo.DateLastModified.HasValue)
  208. {
  209. ctx.Response.Headers[HttpResponseHeader.LastModified] = responseInfo.DateLastModified.Value.ToString("r");
  210. }
  211. // Add caching headers
  212. if (responseInfo.CacheDuration.Ticks > 0)
  213. {
  214. CacheResponse(ctx.Response, responseInfo.CacheDuration);
  215. }
  216. // Set the status code
  217. ctx.Response.StatusCode = responseInfo.StatusCode;
  218. if (responseInfo.IsResponseValid)
  219. {
  220. // Finally, write the response data
  221. Stream outputStream = ctx.Response.OutputStream;
  222. if (compressResponse)
  223. {
  224. if (CompressionMethod.Equals("deflate", StringComparison.OrdinalIgnoreCase))
  225. {
  226. CompressedStream = new DeflateStream(outputStream, CompressionLevel.Fastest, false);
  227. }
  228. else
  229. {
  230. CompressedStream = new GZipStream(outputStream, CompressionLevel.Fastest, false);
  231. }
  232. outputStream = CompressedStream;
  233. }
  234. await WriteResponseToOutputStream(outputStream).ConfigureAwait(false);
  235. }
  236. else
  237. {
  238. ctx.Response.SendChunked = false;
  239. }
  240. }
  241. private void CacheResponse(HttpListenerResponse response, TimeSpan duration)
  242. {
  243. response.Headers[HttpResponseHeader.CacheControl] = "public, max-age=" + Convert.ToInt32(duration.TotalSeconds);
  244. response.Headers[HttpResponseHeader.Expires] = DateTime.UtcNow.Add(duration).ToString("r");
  245. }
  246. protected abstract Task WriteResponseToOutputStream(Stream stream);
  247. protected virtual void DisposeResponseStream()
  248. {
  249. if (CompressedStream != null)
  250. {
  251. CompressedStream.Dispose();
  252. }
  253. HttpListenerContext.Response.OutputStream.Dispose();
  254. }
  255. private bool IsCacheValid(DateTime ifModifiedSince, TimeSpan cacheDuration, DateTime? dateModified)
  256. {
  257. if (dateModified.HasValue)
  258. {
  259. DateTime lastModified = NormalizeDateForComparison(dateModified.Value);
  260. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  261. return lastModified <= ifModifiedSince;
  262. }
  263. DateTime cacheExpirationDate = ifModifiedSince.Add(cacheDuration);
  264. if (DateTime.UtcNow < cacheExpirationDate)
  265. {
  266. return true;
  267. }
  268. return false;
  269. }
  270. /// <summary>
  271. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  272. /// </summary>
  273. private DateTime NormalizeDateForComparison(DateTime date)
  274. {
  275. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  276. }
  277. protected virtual long? GetTotalContentLength()
  278. {
  279. return null;
  280. }
  281. protected abstract Task<ResponseInfo> GetResponseInfo();
  282. private Hashtable _formValues;
  283. /// <summary>
  284. /// Gets a value from form POST data
  285. /// </summary>
  286. protected async Task<string> GetFormValue(string name)
  287. {
  288. if (_formValues == null)
  289. {
  290. _formValues = await GetFormValues(HttpListenerContext.Request).ConfigureAwait(false);
  291. }
  292. if (_formValues.ContainsKey(name))
  293. {
  294. return _formValues[name].ToString();
  295. }
  296. return null;
  297. }
  298. /// <summary>
  299. /// Extracts form POST data from a request
  300. /// </summary>
  301. private async Task<Hashtable> GetFormValues(HttpListenerRequest request)
  302. {
  303. var formVars = new Hashtable();
  304. if (request.HasEntityBody)
  305. {
  306. if (request.ContentType.IndexOf("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) != -1)
  307. {
  308. using (Stream requestBody = request.InputStream)
  309. {
  310. using (var reader = new StreamReader(requestBody, request.ContentEncoding))
  311. {
  312. string s = await reader.ReadToEndAsync().ConfigureAwait(false);
  313. string[] pairs = s.Split('&');
  314. for (int x = 0; x < pairs.Length; x++)
  315. {
  316. string pair = pairs[x];
  317. int index = pair.IndexOf('=');
  318. if (index != -1)
  319. {
  320. string name = pair.Substring(0, index);
  321. string value = pair.Substring(index + 1);
  322. formVars.Add(name, value);
  323. }
  324. }
  325. }
  326. }
  327. }
  328. }
  329. return formVars;
  330. }
  331. }
  332. public class ResponseInfo
  333. {
  334. public string ContentType { get; set; }
  335. public string Etag { get; set; }
  336. public DateTime? DateLastModified { get; set; }
  337. public TimeSpan CacheDuration { get; set; }
  338. public bool CompressResponse { get; set; }
  339. public int StatusCode { get; set; }
  340. public ResponseInfo()
  341. {
  342. CacheDuration = TimeSpan.FromTicks(0);
  343. CompressResponse = true;
  344. StatusCode = 200;
  345. }
  346. public bool IsResponseValid
  347. {
  348. get
  349. {
  350. return StatusCode == 200 || StatusCode == 206;
  351. }
  352. }
  353. }
  354. }