diff --git a/Source/HtmlRenderer/Core/Handlers/StylesheetLoadHandler.cs b/Source/HtmlRenderer/Core/Handlers/StylesheetLoadHandler.cs index 0b15c62d8..e79f740e5 100644 --- a/Source/HtmlRenderer/Core/Handlers/StylesheetLoadHandler.cs +++ b/Source/HtmlRenderer/Core/Handlers/StylesheetLoadHandler.cs @@ -12,8 +12,10 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; +using System.Text; using System.Threading.Tasks; using TheArtOfDev.HtmlRenderer.Core.Entities; using TheArtOfDev.HtmlRenderer.Core.Network; @@ -142,37 +144,121 @@ private static string CorrectRelativeUrls(string stylesheet, Uri baseUri) while (idx >= 0 && idx < stylesheet.Length) { idx = stylesheet.IndexOf("url(", idx, StringComparison.OrdinalIgnoreCase); - if (idx >= 0) + if (idx < 0) + break; + + if (TryReadUrl(stylesheet, idx + 4, out var urlStr, out var endIdx) && + Uri.TryCreate(urlStr, UriKind.Relative, out var url)) + { + // Written back quoted, unquoted it couldn't hold the ' ( ) an absolute URI may contain + var replacement = "\"" + new Uri(baseUri, url).AbsoluteUri + "\""; + stylesheet = stylesheet.Remove(idx + 4, endIdx - idx - 4).Insert(idx + 4, replacement); + idx += 4 + replacement.Length + 1; + } + else { - int endIdx = stylesheet.IndexOf(')', idx); - if (endIdx > idx + 4) - { - var offset1 = 4 + (stylesheet[idx + 4] == '\'' ? 1 : 0); - var offset2 = (stylesheet[endIdx - 1] == '\'' ? 1 : 0); - var urlStr = stylesheet.Substring(idx + offset1, endIdx - idx - offset1 - offset2); - Uri url; - if (Uri.TryCreate(urlStr, UriKind.Relative, out url)) - { - url = new Uri(baseUri, url); - stylesheet = stylesheet.Remove(idx + 4, endIdx - idx - 4); - stylesheet = stylesheet.Insert(idx + 4, url.AbsoluteUri); - idx += url.AbsoluteUri.Length + 4; - } - else - { - idx = endIdx + 1; - } - } - else - { - idx += 4; - } + idx += 4; } } return stylesheet; } + /// + /// Read the URL of a url() without its quotes and with its escapes resolved. + /// + /// the stylesheet to read from + /// the index right after "url(" + /// the URL + /// the index of the closing ')' + /// false if it isn't a well-formed url() + private static bool TryReadUrl(string stylesheet, int start, out string url, out int endIdx) + { + // CSS 2.1 4.3.4: optional whitespace and a pair of matching ' or " quotes around the URL + url = null; + endIdx = -1; + + int i = SkipWhitespace(stylesheet, start); + char quote = i < stylesheet.Length && (stylesheet[i] == '"' || stylesheet[i] == '\'') ? stylesheet[i++] : '\0'; + + var sb = new StringBuilder(); + while (true) + { + if (i >= stylesheet.Length) + return false; + + char c = stylesheet[i]; + if (quote != '\0' ? c == quote : c == ')' || IsWhitespace(c)) + break; + if (quote != '\0' ? c == '\n' || c == '\r' || c == '\f' : c == '"' || c == '\'' || c == '(') + return false; + + if (c == '\\') + { + i = Unescape(stylesheet, i + 1, sb); + } + else + { + sb.Append(c); + i++; + } + } + + if (quote != '\0') + i++; + + i = SkipWhitespace(stylesheet, i); + if (i >= stylesheet.Length || stylesheet[i] != ')' || sb.Length == 0) + return false; + + url = sb.ToString(); + endIdx = i; + return true; + } + + /// + /// Append what the escape after a backslash stands for (CSS 2.1 4.1.3). + /// + /// the stylesheet to read from + /// the index right after the backslash + /// the builder to append to + /// the index after the escape + private static int Unescape(string stylesheet, int i, StringBuilder sb) + { + if (i >= stylesheet.Length) + return i; + + int hexEnd = i; + while (hexEnd < stylesheet.Length && hexEnd - i < 6 && Uri.IsHexDigit(stylesheet[hexEnd])) + hexEnd++; + + if (hexEnd == i) + { + // A backslash before a newline in a string continues the line + if (stylesheet[i] == '\r' && i + 1 < stylesheet.Length && stylesheet[i + 1] == '\n') + return i + 2; + if (stylesheet[i] != '\n' && stylesheet[i] != '\r' && stylesheet[i] != '\f') + sb.Append(stylesheet[i]); + return i + 1; + } + + int codePoint = int.Parse(stylesheet.Substring(i, hexEnd - i), NumberStyles.HexNumber, CultureInfo.InvariantCulture); + sb.Append(codePoint == 0 || codePoint > 0x10FFFF || (codePoint >= 0xD800 && codePoint <= 0xDFFF) ? "�" : char.ConvertFromUtf32(codePoint)); + + if (hexEnd + 1 < stylesheet.Length && stylesheet[hexEnd] == '\r' && stylesheet[hexEnd + 1] == '\n') + return hexEnd + 2; + return hexEnd < stylesheet.Length && IsWhitespace(stylesheet[hexEnd]) ? hexEnd + 1 : hexEnd; + } + + private static int SkipWhitespace(string stylesheet, int i) + { + while (i < stylesheet.Length && IsWhitespace(stylesheet[i])) + i++; + return i; + } + + private static bool IsWhitespace(char c) => c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f'; + #endregion } } diff --git a/Source/Test/HtmlRenderer.Test/Css/FontFaceTests.cs b/Source/Test/HtmlRenderer.Test/Css/FontFaceTests.cs index 9f247c098..42b8e60d5 100644 --- a/Source/Test/HtmlRenderer.Test/Css/FontFaceTests.cs +++ b/Source/Test/HtmlRenderer.Test/Css/FontFaceTests.cs @@ -1,5 +1,9 @@ +using System.Text; using HtmlRenderer.Test.CssEngineSupport; +using HtmlRenderer.Test.TestSupport; +using TheArtOfDev.HtmlRenderer.Core; using TheArtOfDev.HtmlRenderer.Core.CssEngine; +using TheArtOfDev.HtmlRenderer.Core.Network; namespace HtmlRenderer.Test.Css; @@ -97,4 +101,47 @@ public void UnicodeRangeTokenStartAndEnd(string source, string start, string end Assert.AreEqual(end, rangeToken.End); Assert.AreEqual(TokenType.EndOfFile, lexer.Get().Type); } + + [TestMethod] + [DataRow("url(f.ttf)", "f.ttf")] + [DataRow("url('f.ttf')", "f.ttf")] + [DataRow("url(\"f.ttf\")", "f.ttf")] + [DataRow("url( \"f.ttf\" )", "f.ttf")] + [DataRow(@"url(""f\"")g.ttf"")", "f%22)g.ttf")] + [DataRow(@"url('f\'g.ttf')", "f'g.ttf")] + [DataRow(@"url(f\(g\).ttf)", "f(g).ttf")] + [DataRow(@"url(""f\67 .ttf"")", "fg.ttf")] + public void FontFaceInALinkedStyleSheet_ResolvesAgainstTheStyleSheetUrl(string src, string expected) + { + CollectionAssert.Contains(FontFaceRequests(src), "https://example.com/doc/css/" + expected); + } + + private static List FontFaceRequests(string src) + { + var loader = new StyleSheetLoader("@font-face { font-family: F; src: " + src + " }"); + var container = new HtmlContainerInt(new MockAdapter { NetworkLoader = loader }) { AvoidAsyncImagesLoading = true }; + + container.SetHtml("a").GetAwaiter().GetResult(); + + return loader.Requests; + } + + private sealed class StyleSheetLoader(string styleSheet) : RNetworkLoader + { + public List Requests { get; } = []; + + public override RUri? BaseUri => new("https://example.com/doc/index.html"); + + public override Task GetPrimaryContents() => Task.FromResult(string.Empty); + + public override Task GetResourceStream(RUri uri) + { + Requests.Add(uri.AbsoluteUri); + if (uri.AbsoluteUri != "https://example.com/doc/css/fonts.css") + return Task.FromResult(null); + + var headers = new Dictionary { ["Content-Type"] = ["text/css"] }; + return Task.FromResult(new RNetworkResponse(new MemoryStream(Encoding.UTF8.GetBytes(styleSheet)), headers)); + } + } }