2
0

BaseHandler.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. /// <summary>
  99. /// Gets the MIME type to include in the response headers
  100. /// </summary>
  101. public abstract Task<string> GetContentType();
  102. /// <summary>
  103. /// Gets the status code to include in the response headers
  104. /// </summary>
  105. protected int StatusCode { get; set; }
  106. /// <summary>
  107. /// Gets the cache duration to include in the response headers
  108. /// </summary>
  109. public virtual TimeSpan CacheDuration
  110. {
  111. get
  112. {
  113. return TimeSpan.FromTicks(0);
  114. }
  115. }
  116. public virtual bool ShouldCompressResponse(string contentType)
  117. {
  118. return true;
  119. }
  120. private bool ClientSupportsCompression
  121. {
  122. get
  123. {
  124. string enc = HttpListenerContext.Request.Headers["Accept-Encoding"] ?? string.Empty;
  125. return enc.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1 || enc.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1;
  126. }
  127. }
  128. private string CompressionMethod
  129. {
  130. get
  131. {
  132. string enc = HttpListenerContext.Request.Headers["Accept-Encoding"] ?? string.Empty;
  133. if (enc.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1)
  134. {
  135. return "deflate";
  136. }
  137. if (enc.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
  138. {
  139. return "gzip";
  140. }
  141. return null;
  142. }
  143. }
  144. public virtual async Task ProcessRequest(HttpListenerContext ctx)
  145. {
  146. HttpListenerContext = ctx;
  147. string url = ctx.Request.Url.ToString();
  148. Logger.LogInfo("Http Server received request at: " + url);
  149. Logger.LogInfo("Http Headers: " + string.Join(",", ctx.Request.Headers.AllKeys.Select(k => k + "=" + ctx.Request.Headers[k])));
  150. ctx.Response.AddHeader("Access-Control-Allow-Origin", "*");
  151. ctx.Response.KeepAlive = true;
  152. try
  153. {
  154. if (SupportsByteRangeRequests && IsRangeRequest)
  155. {
  156. ctx.Response.Headers["Accept-Ranges"] = "bytes";
  157. }
  158. // Set the initial status code
  159. // When serving a range request, we need to return status code 206 to indicate a partial response body
  160. StatusCode = SupportsByteRangeRequests && IsRangeRequest ? 206 : 200;
  161. ctx.Response.ContentType = await GetContentType().ConfigureAwait(false);
  162. TimeSpan cacheDuration = CacheDuration;
  163. DateTime? lastDateModified = await GetLastDateModified().ConfigureAwait(false);
  164. if (ctx.Request.Headers.AllKeys.Contains("If-Modified-Since"))
  165. {
  166. DateTime ifModifiedSince;
  167. if (DateTime.TryParse(ctx.Request.Headers["If-Modified-Since"], out ifModifiedSince))
  168. {
  169. // If the cache hasn't expired yet just return a 304
  170. if (IsCacheValid(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified))
  171. {
  172. StatusCode = 304;
  173. }
  174. }
  175. }
  176. await PrepareResponse().ConfigureAwait(false);
  177. Logger.LogInfo("Responding with status code {0} for url {1}", StatusCode, url);
  178. if (IsResponseValid)
  179. {
  180. bool compressResponse = ShouldCompressResponse(ctx.Response.ContentType) && ClientSupportsCompression;
  181. await ProcessUncachedRequest(ctx, compressResponse, cacheDuration, lastDateModified).ConfigureAwait(false);
  182. }
  183. else
  184. {
  185. ctx.Response.StatusCode = StatusCode;
  186. ctx.Response.SendChunked = false;
  187. }
  188. }
  189. catch (Exception ex)
  190. {
  191. // It might be too late if some response data has already been transmitted, but try to set this
  192. ctx.Response.StatusCode = 500;
  193. Logger.LogException(ex);
  194. }
  195. finally
  196. {
  197. DisposeResponseStream();
  198. }
  199. }
  200. private async Task ProcessUncachedRequest(HttpListenerContext ctx, bool compressResponse, TimeSpan cacheDuration, DateTime? lastDateModified)
  201. {
  202. long? totalContentLength = TotalContentLength;
  203. // By default, use chunked encoding if we don't know the content length
  204. bool useChunkedEncoding = UseChunkedEncoding == null ? (totalContentLength == null) : UseChunkedEncoding.Value;
  205. // Don't force this to true. HttpListener will default it to true if supported by the client.
  206. if (!useChunkedEncoding)
  207. {
  208. ctx.Response.SendChunked = false;
  209. }
  210. // Set the content length, if we know it
  211. if (totalContentLength.HasValue)
  212. {
  213. ctx.Response.ContentLength64 = totalContentLength.Value;
  214. }
  215. // Add the compression header
  216. if (compressResponse)
  217. {
  218. ctx.Response.AddHeader("Content-Encoding", CompressionMethod);
  219. }
  220. // Add caching headers
  221. if (cacheDuration.Ticks > 0)
  222. {
  223. CacheResponse(ctx.Response, cacheDuration, lastDateModified);
  224. }
  225. // Set the status code
  226. ctx.Response.StatusCode = StatusCode;
  227. if (IsResponseValid)
  228. {
  229. // Finally, write the response data
  230. Stream outputStream = ctx.Response.OutputStream;
  231. if (compressResponse)
  232. {
  233. if (CompressionMethod.Equals("deflate", StringComparison.OrdinalIgnoreCase))
  234. {
  235. CompressedStream = new DeflateStream(outputStream, CompressionLevel.Fastest, false);
  236. }
  237. else
  238. {
  239. CompressedStream = new GZipStream(outputStream, CompressionLevel.Fastest, false);
  240. }
  241. outputStream = CompressedStream;
  242. }
  243. await WriteResponseToOutputStream(outputStream).ConfigureAwait(false);
  244. }
  245. else
  246. {
  247. ctx.Response.SendChunked = false;
  248. }
  249. }
  250. private void CacheResponse(HttpListenerResponse response, TimeSpan duration, DateTime? dateModified)
  251. {
  252. DateTime now = DateTime.UtcNow;
  253. DateTime lastModified = dateModified ?? now;
  254. response.Headers[HttpResponseHeader.CacheControl] = "public, max-age=" + Convert.ToInt32(duration.TotalSeconds);
  255. response.Headers[HttpResponseHeader.Expires] = now.Add(duration).ToString("r");
  256. response.Headers[HttpResponseHeader.LastModified] = lastModified.ToString("r");
  257. }
  258. /// <summary>
  259. /// Gives subclasses a chance to do any prep work, and also to validate data and set an error status code, if needed
  260. /// </summary>
  261. protected virtual Task PrepareResponse()
  262. {
  263. return Task.FromResult<object>(null);
  264. }
  265. protected abstract Task WriteResponseToOutputStream(Stream stream);
  266. protected virtual void DisposeResponseStream()
  267. {
  268. if (CompressedStream != null)
  269. {
  270. CompressedStream.Dispose();
  271. }
  272. HttpListenerContext.Response.OutputStream.Dispose();
  273. }
  274. private bool IsCacheValid(DateTime ifModifiedSince, TimeSpan cacheDuration, DateTime? dateModified)
  275. {
  276. if (dateModified.HasValue)
  277. {
  278. DateTime lastModified = NormalizeDateForComparison(dateModified.Value);
  279. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  280. return lastModified <= ifModifiedSince;
  281. }
  282. DateTime cacheExpirationDate = ifModifiedSince.Add(cacheDuration);
  283. if (DateTime.UtcNow < cacheExpirationDate)
  284. {
  285. return true;
  286. }
  287. return false;
  288. }
  289. /// <summary>
  290. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  291. /// </summary>
  292. private DateTime NormalizeDateForComparison(DateTime date)
  293. {
  294. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  295. }
  296. protected virtual long? GetTotalContentLength()
  297. {
  298. return null;
  299. }
  300. protected virtual Task<DateTime?> GetLastDateModified()
  301. {
  302. DateTime? value = null;
  303. return Task.FromResult(value);
  304. }
  305. private bool IsResponseValid
  306. {
  307. get
  308. {
  309. return StatusCode == 200 || StatusCode == 206;
  310. }
  311. }
  312. private Hashtable _formValues;
  313. /// <summary>
  314. /// Gets a value from form POST data
  315. /// </summary>
  316. protected async Task<string> GetFormValue(string name)
  317. {
  318. if (_formValues == null)
  319. {
  320. _formValues = await GetFormValues(HttpListenerContext.Request).ConfigureAwait(false);
  321. }
  322. if (_formValues.ContainsKey(name))
  323. {
  324. return _formValues[name].ToString();
  325. }
  326. return null;
  327. }
  328. /// <summary>
  329. /// Extracts form POST data from a request
  330. /// </summary>
  331. private async Task<Hashtable> GetFormValues(HttpListenerRequest request)
  332. {
  333. var formVars = new Hashtable();
  334. if (request.HasEntityBody)
  335. {
  336. if (request.ContentType.IndexOf("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) != -1)
  337. {
  338. using (Stream requestBody = request.InputStream)
  339. {
  340. using (var reader = new StreamReader(requestBody, request.ContentEncoding))
  341. {
  342. string s = await reader.ReadToEndAsync().ConfigureAwait(false);
  343. string[] pairs = s.Split('&');
  344. for (int x = 0; x < pairs.Length; x++)
  345. {
  346. string pair = pairs[x];
  347. int index = pair.IndexOf('=');
  348. if (index != -1)
  349. {
  350. string name = pair.Substring(0, index);
  351. string value = pair.Substring(index + 1);
  352. formVars.Add(name, value);
  353. }
  354. }
  355. }
  356. }
  357. }
  358. }
  359. return formVars;
  360. }
  361. }
  362. }