|
| 1 | +// Copyright 2020 New Relic, Inc. All rights reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Text; |
| 6 | +using System.Text.RegularExpressions; |
| 7 | + |
| 8 | +namespace NewRelic.Agent.Core.BrowserMonitoring |
| 9 | +{ |
| 10 | + internal static class BrowserScriptInjectionIndexHelper |
| 11 | + { |
| 12 | + |
| 13 | + private static readonly Regex XUaCompatibleFilter = new Regex(@"(<\s*meta[^>]+http-equiv[\s]*=[\s]*['""]x-ua-compatible['""][^>]*>)", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase); |
| 14 | + private static readonly Regex CharsetFilter = new Regex(@"(<\s*meta[^>]+charset\s*=[^>]*>)", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase); |
| 15 | + |
| 16 | + /// <summary> |
| 17 | + /// Returns the index into the (UTF-8 encoded) buffer where the RUM script should be injected, or -1 if no suitable location is found |
| 18 | + /// </summary> |
| 19 | + /// <param name="content"></param> |
| 20 | + /// <returns></returns> |
| 21 | + /// <remarks> |
| 22 | + /// Specification for Javascript insertion: https://newrelic.atlassian.net/wiki/spaces/eng/pages/50299103/BAM+Agent+Auto-Instrumentation |
| 23 | + /// </remarks> |
| 24 | + public static int TryFindInjectionIndex(byte[] content) |
| 25 | + { |
| 26 | + var contentAsString = Encoding.UTF8.GetString(content); |
| 27 | + |
| 28 | + var openingHeadTagIndex = FindFirstOpeningHeadTag(contentAsString); |
| 29 | + |
| 30 | + // No <HEAD> tag. Attempt to insert before <BODY> tag (not a great fallback option). |
| 31 | + if (openingHeadTagIndex == -1) |
| 32 | + { |
| 33 | + return FindIndexBeforeBodyTag(content, contentAsString); |
| 34 | + } |
| 35 | + |
| 36 | + // Since we have a head tag (top of 'page'), search for <X_UA_COMPATIBLE> and for <CHARSET> tags in Head section |
| 37 | + var xUaCompatibleFilterMatch = XUaCompatibleFilter.Match(contentAsString, openingHeadTagIndex); |
| 38 | + var charsetFilterMatch = CharsetFilter.Match(contentAsString, openingHeadTagIndex); |
| 39 | + |
| 40 | + // Try to find </HEAD> tag. (It's okay if we don't find it!) |
| 41 | + var closingHeadTagIndex = contentAsString.IndexOf("</head>", StringComparison.InvariantCultureIgnoreCase); |
| 42 | + |
| 43 | + // Find which of the two tags occurs latest (if at all) and ensure that at least |
| 44 | + // one of the matches occurs prior to the closing head tag |
| 45 | + if ((xUaCompatibleFilterMatch.Success || charsetFilterMatch.Success) && |
| 46 | + (xUaCompatibleFilterMatch.Index < closingHeadTagIndex || charsetFilterMatch.Index < closingHeadTagIndex)) |
| 47 | + { |
| 48 | + var match = charsetFilterMatch; |
| 49 | + if (xUaCompatibleFilterMatch.Index > charsetFilterMatch.Index) |
| 50 | + { |
| 51 | + match = xUaCompatibleFilterMatch; |
| 52 | + } |
| 53 | + |
| 54 | + // find the index just after the end of the regex match in the UTF-8 buffer |
| 55 | + var contentSubString = contentAsString.Substring(match.Index, match.Length); |
| 56 | + var utf8HeadMatchIndex = IndexOfByteArray(content, contentSubString, out var substringBytesLength); |
| 57 | + |
| 58 | + return utf8HeadMatchIndex + substringBytesLength; |
| 59 | + } |
| 60 | + |
| 61 | + // found opening head tag but no meta tags, insert immediately after the opening head tag |
| 62 | + // Find first '>' after the opening head tag, which will be end of head opening tag. |
| 63 | + var indexOfEndHeadOpeningTag = contentAsString.IndexOf('>', openingHeadTagIndex); |
| 64 | + |
| 65 | + // The <HEAD> tag may be malformed or simply be another type of tag, if so do not use it |
| 66 | + if (!(indexOfEndHeadOpeningTag > openingHeadTagIndex)) |
| 67 | + return -1; |
| 68 | + |
| 69 | + // Get the whole open HEAD tag string |
| 70 | + var headOpeningTag = contentAsString.Substring(openingHeadTagIndex, (indexOfEndHeadOpeningTag - openingHeadTagIndex) + 1); |
| 71 | + var utf8HeadOpeningTagIndex = IndexOfByteArray(content, headOpeningTag, out var headOpeningTagBytesLength); |
| 72 | + return utf8HeadOpeningTagIndex + headOpeningTagBytesLength; |
| 73 | + } |
| 74 | + |
| 75 | + private static int FindIndexBeforeBodyTag(byte[] content, string contentAsString) |
| 76 | + { |
| 77 | + const string bodyOpenTag = "<body"; |
| 78 | + |
| 79 | + var indexOfBodyTag = contentAsString.IndexOf(bodyOpenTag, StringComparison.InvariantCultureIgnoreCase); |
| 80 | + if (indexOfBodyTag < 0) |
| 81 | + return -1; |
| 82 | + |
| 83 | + // find the body tag start index in the UTF-8 buffer |
| 84 | + var bodyFromContent = contentAsString.Substring(indexOfBodyTag, bodyOpenTag.Length); |
| 85 | + var utf8BodyTagIndex = IndexOfByteArray(content, bodyFromContent, out _); |
| 86 | + return utf8BodyTagIndex; |
| 87 | + } |
| 88 | + |
| 89 | + private static int FindFirstOpeningHeadTag(string content) |
| 90 | + { |
| 91 | + int indexOpeningHead = -1; |
| 92 | + |
| 93 | + var indexTemp = content.IndexOf("<head", StringComparison.InvariantCultureIgnoreCase); |
| 94 | + if (indexTemp < 0) |
| 95 | + return -1; |
| 96 | + |
| 97 | + if (content[indexTemp + 5] == '>' || content[indexTemp + 5] == ' ') |
| 98 | + { |
| 99 | + indexOpeningHead = indexTemp; |
| 100 | + } |
| 101 | + |
| 102 | + return indexOpeningHead; |
| 103 | + } |
| 104 | + |
| 105 | + /// <summary> |
| 106 | + /// Returns an index into a byte array to find a string in the byte array. |
| 107 | + /// Exact match using the encoding provided or UTF-8 by default. |
| 108 | + /// </summary> |
| 109 | + /// <param name="buffer"></param> |
| 110 | + /// <param name="stringToFind"></param> |
| 111 | + /// <param name="stringToFindBytesLength"></param> |
| 112 | + /// <param name="encoding"></param> |
| 113 | + /// <returns></returns> |
| 114 | + private static int IndexOfByteArray(byte[] buffer, string stringToFind, out int stringToFindBytesLength, Encoding encoding = null) |
| 115 | + { |
| 116 | + stringToFindBytesLength = 0; |
| 117 | + encoding ??= Encoding.UTF8; |
| 118 | + |
| 119 | + if (buffer.Length == 0 || string.IsNullOrEmpty(stringToFind)) |
| 120 | + return -1; |
| 121 | + |
| 122 | + var stringToFindBytes = encoding.GetBytes(stringToFind); |
| 123 | + stringToFindBytesLength = stringToFindBytes.Length; |
| 124 | + |
| 125 | + return buffer.AsSpan().IndexOf(stringToFindBytes); |
| 126 | + } |
| 127 | + } |
| 128 | +} |
0 commit comments