Skip to content

Commit 846bbdd

Browse files
committed
Resolve double-quoted URLs in style sheets against the sheet
1 parent ee38a62 commit 846bbdd

2 files changed

Lines changed: 157 additions & 24 deletions

File tree

‎Source/HtmlRenderer/Core/Handlers/StylesheetLoadHandler.cs‎

Lines changed: 110 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,10 @@
1212

1313
using System;
1414
using System.Collections.Generic;
15+
using System.Globalization;
1516
using System.IO;
1617
using System.Linq;
18+
using System.Text;
1719
using System.Threading.Tasks;
1820
using TheArtOfDev.HtmlRenderer.Core.Entities;
1921
using TheArtOfDev.HtmlRenderer.Core.Network;
@@ -142,37 +144,121 @@ private static string CorrectRelativeUrls(string stylesheet, Uri baseUri)
142144
while (idx >= 0 && idx < stylesheet.Length)
143145
{
144146
idx = stylesheet.IndexOf("url(", idx, StringComparison.OrdinalIgnoreCase);
145-
if (idx >= 0)
147+
if (idx < 0)
148+
break;
149+
150+
if (TryReadUrl(stylesheet, idx + 4, out var urlStr, out var endIdx) &&
151+
Uri.TryCreate(urlStr, UriKind.Relative, out var url))
152+
{
153+
// Written back quoted, unquoted it couldn't hold the ' ( ) an absolute URI may contain
154+
var replacement = "\"" + new Uri(baseUri, url).AbsoluteUri + "\"";
155+
stylesheet = stylesheet.Remove(idx + 4, endIdx - idx - 4).Insert(idx + 4, replacement);
156+
idx += 4 + replacement.Length + 1;
157+
}
158+
else
146159
{
147-
int endIdx = stylesheet.IndexOf(')', idx);
148-
if (endIdx > idx + 4)
149-
{
150-
var offset1 = 4 + (stylesheet[idx + 4] == '\'' ? 1 : 0);
151-
var offset2 = (stylesheet[endIdx - 1] == '\'' ? 1 : 0);
152-
var urlStr = stylesheet.Substring(idx + offset1, endIdx - idx - offset1 - offset2);
153-
Uri url;
154-
if (Uri.TryCreate(urlStr, UriKind.Relative, out url))
155-
{
156-
url = new Uri(baseUri, url);
157-
stylesheet = stylesheet.Remove(idx + 4, endIdx - idx - 4);
158-
stylesheet = stylesheet.Insert(idx + 4, url.AbsoluteUri);
159-
idx += url.AbsoluteUri.Length + 4;
160-
}
161-
else
162-
{
163-
idx = endIdx + 1;
164-
}
165-
}
166-
else
167-
{
168-
idx += 4;
169-
}
160+
idx += 4;
170161
}
171162
}
172163

173164
return stylesheet;
174165
}
175166

167+
/// <summary>
168+
/// Read the URL of a url() without its quotes and with its escapes resolved.
169+
/// </summary>
170+
/// <param name="stylesheet">the stylesheet to read from</param>
171+
/// <param name="start">the index right after "url("</param>
172+
/// <param name="url">the URL</param>
173+
/// <param name="endIdx">the index of the closing ')'</param>
174+
/// <returns>false if it isn't a well-formed url()</returns>
175+
private static bool TryReadUrl(string stylesheet, int start, out string url, out int endIdx)
176+
{
177+
// CSS 2.1 4.3.4: optional whitespace and a pair of matching ' or " quotes around the URL
178+
url = null;
179+
endIdx = -1;
180+
181+
int i = SkipWhitespace(stylesheet, start);
182+
char quote = i < stylesheet.Length && (stylesheet[i] == '"' || stylesheet[i] == '\'') ? stylesheet[i++] : '\0';
183+
184+
var sb = new StringBuilder();
185+
while (true)
186+
{
187+
if (i >= stylesheet.Length)
188+
return false;
189+
190+
char c = stylesheet[i];
191+
if (quote != '\0' ? c == quote : c == ')' || IsWhitespace(c))
192+
break;
193+
if (quote != '\0' ? c == '\n' || c == '\r' || c == '\f' : c == '"' || c == '\'' || c == '(')
194+
return false;
195+
196+
if (c == '\\')
197+
{
198+
i = Unescape(stylesheet, i + 1, sb);
199+
}
200+
else
201+
{
202+
sb.Append(c);
203+
i++;
204+
}
205+
}
206+
207+
if (quote != '\0')
208+
i++;
209+
210+
i = SkipWhitespace(stylesheet, i);
211+
if (i >= stylesheet.Length || stylesheet[i] != ')' || sb.Length == 0)
212+
return false;
213+
214+
url = sb.ToString();
215+
endIdx = i;
216+
return true;
217+
}
218+
219+
/// <summary>
220+
/// Append what the escape after a backslash stands for (CSS 2.1 4.1.3).
221+
/// </summary>
222+
/// <param name="stylesheet">the stylesheet to read from</param>
223+
/// <param name="i">the index right after the backslash</param>
224+
/// <param name="sb">the builder to append to</param>
225+
/// <returns>the index after the escape</returns>
226+
private static int Unescape(string stylesheet, int i, StringBuilder sb)
227+
{
228+
if (i >= stylesheet.Length)
229+
return i;
230+
231+
int hexEnd = i;
232+
while (hexEnd < stylesheet.Length && hexEnd - i < 6 && Uri.IsHexDigit(stylesheet[hexEnd]))
233+
hexEnd++;
234+
235+
if (hexEnd == i)
236+
{
237+
// A backslash before a newline in a string continues the line
238+
if (stylesheet[i] == '\r' && i + 1 < stylesheet.Length && stylesheet[i + 1] == '\n')
239+
return i + 2;
240+
if (stylesheet[i] != '\n' && stylesheet[i] != '\r' && stylesheet[i] != '\f')
241+
sb.Append(stylesheet[i]);
242+
return i + 1;
243+
}
244+
245+
int codePoint = int.Parse(stylesheet.Substring(i, hexEnd - i), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
246+
sb.Append(codePoint == 0 || codePoint > 0x10FFFF || (codePoint >= 0xD800 && codePoint <= 0xDFFF) ? "�" : char.ConvertFromUtf32(codePoint));
247+
248+
if (hexEnd + 1 < stylesheet.Length && stylesheet[hexEnd] == '\r' && stylesheet[hexEnd + 1] == '\n')
249+
return hexEnd + 2;
250+
return hexEnd < stylesheet.Length && IsWhitespace(stylesheet[hexEnd]) ? hexEnd + 1 : hexEnd;
251+
}
252+
253+
private static int SkipWhitespace(string stylesheet, int i)
254+
{
255+
while (i < stylesheet.Length && IsWhitespace(stylesheet[i]))
256+
i++;
257+
return i;
258+
}
259+
260+
private static bool IsWhitespace(char c) => c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
261+
176262
#endregion
177263
}
178264
}

‎Source/Test/HtmlRenderer.Test/Css/FontFaceTests.cs‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1+
using System.Text;
12
using HtmlRenderer.Test.CssEngineSupport;
3+
using HtmlRenderer.Test.TestSupport;
4+
using TheArtOfDev.HtmlRenderer.Core;
25
using TheArtOfDev.HtmlRenderer.Core.CssEngine;
6+
using TheArtOfDev.HtmlRenderer.Core.Network;
37

48
namespace HtmlRenderer.Test.Css;
59

@@ -97,4 +101,47 @@ public void UnicodeRangeTokenStartAndEnd(string source, string start, string end
97101
Assert.AreEqual(end, rangeToken.End);
98102
Assert.AreEqual(TokenType.EndOfFile, lexer.Get().Type);
99103
}
104+
105+
[TestMethod]
106+
[DataRow("url(f.ttf)", "f.ttf")]
107+
[DataRow("url('f.ttf')", "f.ttf")]
108+
[DataRow("url(\"f.ttf\")", "f.ttf")]
109+
[DataRow("url( \"f.ttf\" )", "f.ttf")]
110+
[DataRow(@"url(""f\"")g.ttf"")", "f%22)g.ttf")]
111+
[DataRow(@"url('f\'g.ttf')", "f'g.ttf")]
112+
[DataRow(@"url(f\(g\).ttf)", "f(g).ttf")]
113+
[DataRow(@"url(""f\67 .ttf"")", "fg.ttf")]
114+
public void FontFaceInALinkedStyleSheet_ResolvesAgainstTheStyleSheetUrl(string src, string expected)
115+
{
116+
CollectionAssert.Contains(FontFaceRequests(src), "https://example.com/doc/css/" + expected);
117+
}
118+
119+
private static List<string> FontFaceRequests(string src)
120+
{
121+
var loader = new StyleSheetLoader("@font-face { font-family: F; src: " + src + " }");
122+
var container = new HtmlContainerInt(new MockAdapter { NetworkLoader = loader }) { AvoidAsyncImagesLoading = true };
123+
124+
container.SetHtml("<html><head><link rel=stylesheet href=css/fonts.css></head><body>a</body></html>").GetAwaiter().GetResult();
125+
126+
return loader.Requests;
127+
}
128+
129+
private sealed class StyleSheetLoader(string styleSheet) : RNetworkLoader
130+
{
131+
public List<string> Requests { get; } = [];
132+
133+
public override RUri? BaseUri => new("https://example.com/doc/index.html");
134+
135+
public override Task<string> GetPrimaryContents() => Task.FromResult(string.Empty);
136+
137+
public override Task<RNetworkResponse?> GetResourceStream(RUri uri)
138+
{
139+
Requests.Add(uri.AbsoluteUri);
140+
if (uri.AbsoluteUri != "https://example.com/doc/css/fonts.css")
141+
return Task.FromResult<RNetworkResponse?>(null);
142+
143+
var headers = new Dictionary<string, string[]> { ["Content-Type"] = ["text/css"] };
144+
return Task.FromResult<RNetworkResponse?>(new RNetworkResponse(new MemoryStream(Encoding.UTF8.GetBytes(styleSheet)), headers));
145+
}
146+
}
100147
}

0 commit comments

Comments
 (0)