jellyfin/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs

87 lines
2.7 KiB
C#
Raw Normal View History

2021-05-05 23:52:39 +02:00
using System.Collections.Generic;
using System.Linq;
using System.Web;
2021-05-08 13:52:25 +02:00
using MediaBrowser.Common.Extensions;
2021-05-05 23:52:39 +02:00
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Primitives;
namespace Jellyfin.Server.Middleware
{
/// <summary>
/// Defines the <see cref="UrlDecodeQueryFeature"/>.
/// </summary>
public class UrlDecodeQueryFeature : IQueryFeature
{
private IQueryCollection? _store;
/// <summary>
/// Initializes a new instance of the <see cref="UrlDecodeQueryFeature"/> class.
/// </summary>
/// <param name="feature">The <see cref="IQueryFeature"/> instance.</param>
public UrlDecodeQueryFeature(IQueryFeature feature)
{
Query = feature.Query;
}
/// <summary>
/// Gets or sets a value indicating the url decoded <see cref="IQueryCollection"/>.
/// </summary>
public IQueryCollection Query
{
get
{
return _store ?? QueryCollection.Empty;
}
set
{
2021-05-06 00:14:05 +02:00
// Only interested in where the querystring is encoded which shows up as one key with nothing in the value.
2021-05-05 23:52:39 +02:00
if (value.Count != 1)
{
_store = value;
return;
}
2021-05-06 00:14:05 +02:00
// Encoded querystrings have no value, so don't process anything if a value is present.
2021-05-05 23:52:39 +02:00
var kvp = value.First();
if (!string.IsNullOrEmpty(kvp.Value))
{
_store = value;
return;
}
// Unencode and re-parse querystring.
var unencodedKey = HttpUtility.UrlDecode(kvp.Key);
if (string.Equals(unencodedKey, kvp.Key, System.StringComparison.Ordinal))
{
2021-05-06 00:14:05 +02:00
// Don't do anything if it's not encoded.
2021-05-05 23:52:39 +02:00
_store = value;
return;
}
var pairs = new Dictionary<string, StringValues>();
2021-05-08 13:52:25 +02:00
var queryString = unencodedKey.SpanSplit('&');
2021-05-05 23:52:39 +02:00
foreach (var pair in queryString)
{
2021-05-08 17:00:41 +02:00
var section = pair.ToString();
var i = section.IndexOf('=', System.StringComparison.Ordinal);
2021-05-08 13:52:25 +02:00
2021-05-08 17:00:41 +02:00
if (i == -1)
2021-05-07 15:02:42 +02:00
{
2021-05-08 13:52:25 +02:00
// encoded is an equals.
2021-05-08 17:00:41 +02:00
pairs.Add(section, new StringValues(string.Empty));
2021-05-08 13:52:25 +02:00
continue;
2021-05-07 15:02:42 +02:00
}
2021-05-08 13:52:25 +02:00
2021-05-08 17:00:41 +02:00
pairs.Add(section[0..i], new StringValues(section[(i + 1)..]));
2021-05-05 23:52:39 +02:00
}
_store = new QueryCollection(pairs);
}
}
}
}