UrlDecodeQueryFeature.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using Jellyfin.Extensions;
  6. using Microsoft.AspNetCore.Http;
  7. using Microsoft.AspNetCore.Http.Features;
  8. using Microsoft.Extensions.Primitives;
  9. namespace Jellyfin.Server.Middleware
  10. {
  11. /// <summary>
  12. /// Defines the <see cref="UrlDecodeQueryFeature"/>.
  13. /// </summary>
  14. public class UrlDecodeQueryFeature : IQueryFeature
  15. {
  16. private IQueryCollection? _store;
  17. /// <summary>
  18. /// Initializes a new instance of the <see cref="UrlDecodeQueryFeature"/> class.
  19. /// </summary>
  20. /// <param name="feature">The <see cref="IQueryFeature"/> instance.</param>
  21. public UrlDecodeQueryFeature(IQueryFeature feature)
  22. {
  23. Query = feature.Query;
  24. }
  25. /// <summary>
  26. /// Gets or sets a value indicating the url decoded <see cref="IQueryCollection"/>.
  27. /// </summary>
  28. public IQueryCollection Query
  29. {
  30. get
  31. {
  32. return _store ?? QueryCollection.Empty;
  33. }
  34. set
  35. {
  36. // Only interested in where the querystring is encoded which shows up as one key with nothing in the value.
  37. if (value.Count != 1)
  38. {
  39. _store = value;
  40. return;
  41. }
  42. // Encoded querystrings have no value, so don't process anything if a value is present.
  43. var (key, stringValues) = value.First();
  44. if (!string.IsNullOrEmpty(stringValues))
  45. {
  46. _store = value;
  47. return;
  48. }
  49. if (!key.Contains('='))
  50. {
  51. _store = value;
  52. return;
  53. }
  54. var pairs = new Dictionary<string, StringValues>();
  55. foreach (var pair in key.SpanSplit('&'))
  56. {
  57. var i = pair.IndexOf('=');
  58. if (i == -1)
  59. {
  60. // encoded is an equals.
  61. // We use TryAdd so duplicate keys get ignored
  62. pairs.TryAdd(pair.ToString(), StringValues.Empty);
  63. continue;
  64. }
  65. var k = pair[..i].ToString();
  66. var v = pair[(i + 1)..].ToString();
  67. if (!pairs.TryAdd(k, new StringValues(v)))
  68. {
  69. pairs[k] = StringValues.Concat(pairs[k], v);
  70. }
  71. }
  72. _store = new QueryCollection(pairs);
  73. }
  74. }
  75. }
  76. }