-
Notifications
You must be signed in to change notification settings - Fork 0
/
UrlSanitizer.cs
87 lines (76 loc) · 2.8 KB
/
UrlSanitizer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
namespace Microsoft.Data.Services.Toolkit
{
using System;
using System.Linq;
using System.Reflection;
using System.Text;
/// <summary>
/// Sanitizes url characters.
/// </summary>
public class UrlSanitizer
{
private static readonly MethodInfo GetSyntaxMethod = typeof(UriParser).GetMethod("GetSyntax", BindingFlags.Static | BindingFlags.NonPublic);
private static readonly FieldInfo FlagsField = typeof(UriParser).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
private readonly UrlSettingsAttribute urlSettings;
/// <summary>
/// Initializes a new instance of the UrlSanitizer class.
/// </summary>
/// <param name="urlSettings">The url settings for the sanitization process.</param>
public UrlSanitizer(UrlSettingsAttribute urlSettings)
{
this.urlSettings = urlSettings;
}
/// <summary>
/// Enables OAuth support.
/// </summary>
public static void EnableOAuthSupport()
{
foreach (var scheme in new[] { "http", "https" })
{
var parser = (UriParser)GetSyntaxMethod.Invoke(null, new object[] { scheme });
if (parser == null)
continue;
var flagsValue = (int)FlagsField.GetValue(parser);
if ((flagsValue & 0x1000000) != 0)
FlagsField.SetValue(parser, flagsValue & ~0x1000000);
}
}
/// <summary>
/// Executes the Sanitization process.
/// </summary>
/// <param name="uri">The Uri to be sanitized.</param>
/// <returns>The sanitized <see cref="Uri"/>.</returns>
public Uri Sanitize(string uri)
{
var replaceUri = new StringBuilder();
var inQuote = false;
var escapedCharacters = this.urlSettings.GetEscapedCharacters();
foreach (var t in uri)
{
switch (t)
{
case '\'':
replaceUri.Append(t);
inQuote = !inQuote;
break;
case '#':
case '\\':
case '/':
case '?':
case '&':
if (inQuote && escapedCharacters.Contains(t))
{
replaceUri.AppendFormat("%{0:X}", (int)t);
}
else
replaceUri.Append(t);
break;
default:
replaceUri.Append(t);
break;
}
}
return new Uri(replaceUri.ToString());
}
}
}