UrlDecodeQueryFeature.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. // Unencode and re-parse querystring.
  50. var unencodedKey = HttpUtility.UrlDecode(key);
  51. if (string.Equals(unencodedKey, key, StringComparison.Ordinal))
  52. {
  53. // Don't do anything if it's not encoded.
  54. _store = value;
  55. return;
  56. }
  57. var pairs = new Dictionary<string, StringValues>();
  58. var queryString = unencodedKey.SpanSplit('&');
  59. foreach (var pair in queryString)
  60. {
  61. var i = pair.IndexOf('=');
  62. if (i == -1)
  63. {
  64. // encoded is an equals.
  65. // We use TryAdd so duplicate keys get ignored
  66. pairs.TryAdd(pair.ToString(), StringValues.Empty);
  67. continue;
  68. }
  69. var k = pair[..i].ToString();
  70. var v = pair[(i + 1)..].ToString();
  71. if (!pairs.TryAdd(k, new StringValues(v)))
  72. {
  73. pairs[k] = StringValues.Concat(pairs[k], v);
  74. }
  75. }
  76. _store = new QueryCollection(pairs);
  77. }
  78. }
  79. }
  80. }