001/* 002 * Copyright (C) 2008 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.escape; 016 017import static com.google.common.base.Preconditions.checkNotNull; 018 019import com.google.common.annotations.GwtCompatible; 020import org.checkerframework.checker.nullness.qual.Nullable; 021 022/** 023 * An {@link Escaper} that converts literal text into a format safe for inclusion in a particular 024 * context (such as an XML document). Typically (but not always), the inverse process of 025 * "unescaping" the text is performed automatically by the relevant parser. 026 * 027 * <p>For example, an XML escaper would convert the literal string {@code "Foo<Bar>"} into {@code 028 * "Foo<Bar>"} to prevent {@code "<Bar>"} from being confused with an XML tag. When the 029 * resulting XML document is parsed, the parser API will return this text as the original literal 030 * string {@code "Foo<Bar>"}. 031 * 032 * <p><b>Note:</b> This class is similar to {@link CharEscaper} but with one very important 033 * difference. A CharEscaper can only process Java <a 034 * href="http://en.wikipedia.org/wiki/UTF-16">UTF16</a> characters in isolation and may not cope 035 * when it encounters surrogate pairs. This class facilitates the correct escaping of all Unicode 036 * characters. 037 * 038 * <p>As there are important reasons, including potential security issues, to handle Unicode 039 * correctly if you are considering implementing a new escaper you should favor using UnicodeEscaper 040 * wherever possible. 041 * 042 * <p>A {@code UnicodeEscaper} instance is required to be stateless, and safe when used concurrently 043 * by multiple threads. 044 * 045 * <p>Popular escapers are defined as constants in classes like {@link 046 * com.google.common.html.HtmlEscapers} and {@link com.google.common.xml.XmlEscapers}. To create 047 * your own escapers extend this class and implement the {@link #escape(int)} method. 048 * 049 * @author David Beaumont 050 * @since 15.0 051 */ 052@GwtCompatible 053public abstract class UnicodeEscaper extends Escaper { 054 /** The amount of padding (chars) to use when growing the escape buffer. */ 055 private static final int DEST_PAD = 32; 056 057 /** Constructor for use by subclasses. */ 058 protected UnicodeEscaper() {} 059 060 /** 061 * Returns the escaped form of the given Unicode code point, or {@code null} if this code point 062 * does not need to be escaped. When called as part of an escaping operation, the given code point 063 * is guaranteed to be in the range {@code 0 <= cp <= Character#MAX_CODE_POINT}. 064 * 065 * <p>If an empty array is returned, this effectively strips the input character from the 066 * resulting text. 067 * 068 * <p>If the character does not need to be escaped, this method should return {@code null}, rather 069 * than an array containing the character representation of the code point. This enables the 070 * escaping algorithm to perform more efficiently. 071 * 072 * <p>If the implementation of this method cannot correctly handle a particular code point then it 073 * should either throw an appropriate runtime exception or return a suitable replacement 074 * character. It must never silently discard invalid input as this may constitute a security risk. 075 * 076 * @param cp the Unicode code point to escape if necessary 077 * @return the replacement characters, or {@code null} if no escaping was needed 078 */ 079 protected abstract char @Nullable [] escape(int cp); 080 081 /** 082 * Returns the escaped form of a given literal string. 083 * 084 * <p>If you are escaping input in arbitrary successive chunks, then it is not generally safe to 085 * use this method. If an input string ends with an unmatched high surrogate character, then this 086 * method will throw {@link IllegalArgumentException}. You should ensure your input is valid <a 087 * href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> before calling this method. 088 * 089 * <p><b>Note:</b> When implementing an escaper it is a good idea to override this method for 090 * efficiency by inlining the implementation of {@link #nextEscapeIndex(CharSequence, int, int)} 091 * directly. Doing this for {@link com.google.common.net.PercentEscaper} more than doubled the 092 * performance for unescaped strings (as measured by {@code CharEscapersBenchmark}). 093 * 094 * @param string the literal string to be escaped 095 * @return the escaped form of {@code string} 096 * @throws NullPointerException if {@code string} is null 097 * @throws IllegalArgumentException if invalid surrogate characters are encountered 098 */ 099 @Override 100 public String escape(String string) { 101 checkNotNull(string); 102 int end = string.length(); 103 int index = nextEscapeIndex(string, 0, end); 104 return index == end ? string : escapeSlow(string, index); 105 } 106 107 /** 108 * Scans a sub-sequence of characters from a given {@link CharSequence}, returning the index of 109 * the next character that requires escaping. 110 * 111 * <p><b>Note:</b> When implementing an escaper, it is a good idea to override this method for 112 * efficiency. The base class implementation determines successive Unicode code points and invokes 113 * {@link #escape(int)} for each of them. If the semantics of your escaper are such that code 114 * points in the supplementary range are either all escaped or all unescaped, this method can be 115 * implemented more efficiently using {@link CharSequence#charAt(int)}. 116 * 117 * <p>Note however that if your escaper does not escape characters in the supplementary range, you 118 * should either continue to validate the correctness of any surrogate characters encountered or 119 * provide a clear warning to users that your escaper does not validate its input. 120 * 121 * <p>See {@link com.google.common.net.PercentEscaper} for an example. 122 * 123 * @param csq a sequence of characters 124 * @param start the index of the first character to be scanned 125 * @param end the index immediately after the last character to be scanned 126 * @throws IllegalArgumentException if the scanned sub-sequence of {@code csq} contains invalid 127 * surrogate pairs 128 */ 129 protected int nextEscapeIndex(CharSequence csq, int start, int end) { 130 int index = start; 131 while (index < end) { 132 int cp = codePointAt(csq, index, end); 133 if (cp < 0 || escape(cp) != null) { 134 break; 135 } 136 index += Character.isSupplementaryCodePoint(cp) ? 2 : 1; 137 } 138 return index; 139 } 140 141 /** 142 * Returns the escaped form of a given literal string, starting at the given index. This method is 143 * called by the {@link #escape(String)} method when it discovers that escaping is required. It is 144 * protected to allow subclasses to override the fastpath escaping function to inline their 145 * escaping test. See {@link CharEscaperBuilder} for an example usage. 146 * 147 * <p>This method is not reentrant and may only be invoked by the top level {@link 148 * #escape(String)} method. 149 * 150 * @param s the literal string to be escaped 151 * @param index the index to start escaping from 152 * @return the escaped form of {@code string} 153 * @throws NullPointerException if {@code string} is null 154 * @throws IllegalArgumentException if invalid surrogate characters are encountered 155 */ 156 protected final String escapeSlow(String s, int index) { 157 int end = s.length(); 158 159 // Get a destination buffer and setup some loop variables. 160 char[] dest = Platform.charBufferFromThreadLocal(); 161 int destIndex = 0; 162 int unescapedChunkStart = 0; 163 164 while (index < end) { 165 int cp = codePointAt(s, index, end); 166 if (cp < 0) { 167 throw new IllegalArgumentException("Trailing high surrogate at end of input"); 168 } 169 // It is possible for this to return null because nextEscapeIndex() may 170 // (for performance reasons) yield some false positives but it must never 171 // give false negatives. 172 char[] escaped = escape(cp); 173 int nextIndex = index + (Character.isSupplementaryCodePoint(cp) ? 2 : 1); 174 if (escaped != null) { 175 int charsSkipped = index - unescapedChunkStart; 176 177 // This is the size needed to add the replacement, not the full 178 // size needed by the string. We only regrow when we absolutely must. 179 int sizeNeeded = destIndex + charsSkipped + escaped.length; 180 if (dest.length < sizeNeeded) { 181 int destLength = sizeNeeded + (end - index) + DEST_PAD; 182 dest = growBuffer(dest, destIndex, destLength); 183 } 184 // If we have skipped any characters, we need to copy them now. 185 if (charsSkipped > 0) { 186 s.getChars(unescapedChunkStart, index, dest, destIndex); 187 destIndex += charsSkipped; 188 } 189 if (escaped.length > 0) { 190 System.arraycopy(escaped, 0, dest, destIndex, escaped.length); 191 destIndex += escaped.length; 192 } 193 // If we dealt with an escaped character, reset the unescaped range. 194 unescapedChunkStart = nextIndex; 195 } 196 index = nextEscapeIndex(s, nextIndex, end); 197 } 198 199 // Process trailing unescaped characters - no need to account for escaped 200 // length or padding the allocation. 201 int charsSkipped = end - unescapedChunkStart; 202 if (charsSkipped > 0) { 203 int endIndex = destIndex + charsSkipped; 204 if (dest.length < endIndex) { 205 dest = growBuffer(dest, destIndex, endIndex); 206 } 207 s.getChars(unescapedChunkStart, end, dest, destIndex); 208 destIndex = endIndex; 209 } 210 return new String(dest, 0, destIndex); 211 } 212 213 /** 214 * Returns the Unicode code point of the character at the given index. 215 * 216 * <p>Unlike {@link Character#codePointAt(CharSequence, int)} or {@link String#codePointAt(int)} 217 * this method will never fail silently when encountering an invalid surrogate pair. 218 * 219 * <p>The behaviour of this method is as follows: 220 * 221 * <ol> 222 * <li>If {@code index >= end}, {@link IndexOutOfBoundsException} is thrown. 223 * <li><b>If the character at the specified index is not a surrogate, it is returned.</b> 224 * <li>If the first character was a high surrogate value, then an attempt is made to read the 225 * next character. 226 * <ol> 227 * <li><b>If the end of the sequence was reached, the negated value of the trailing high 228 * surrogate is returned.</b> 229 * <li><b>If the next character was a valid low surrogate, the code point value of the 230 * high/low surrogate pair is returned.</b> 231 * <li>If the next character was not a low surrogate value, then {@link 232 * IllegalArgumentException} is thrown. 233 * </ol> 234 * <li>If the first character was a low surrogate value, {@link IllegalArgumentException} is 235 * thrown. 236 * </ol> 237 * 238 * @param seq the sequence of characters from which to decode the code point 239 * @param index the index of the first character to decode 240 * @param end the index beyond the last valid character to decode 241 * @return the Unicode code point for the given index or the negated value of the trailing high 242 * surrogate character at the end of the sequence 243 */ 244 protected static int codePointAt(CharSequence seq, int index, int end) { 245 checkNotNull(seq); 246 if (index < end) { 247 char c1 = seq.charAt(index++); 248 if (c1 < Character.MIN_HIGH_SURROGATE || c1 > Character.MAX_LOW_SURROGATE) { 249 // Fast path (first test is probably all we need to do) 250 return c1; 251 } else if (c1 <= Character.MAX_HIGH_SURROGATE) { 252 // If the high surrogate was the last character, return its inverse 253 if (index == end) { 254 return -c1; 255 } 256 // Otherwise look for the low surrogate following it 257 char c2 = seq.charAt(index); 258 if (Character.isLowSurrogate(c2)) { 259 return Character.toCodePoint(c1, c2); 260 } 261 throw new IllegalArgumentException( 262 "Expected low surrogate but got char '" 263 + c2 264 + "' with value " 265 + (int) c2 266 + " at index " 267 + index 268 + " in '" 269 + seq 270 + "'"); 271 } else { 272 throw new IllegalArgumentException( 273 "Unexpected low surrogate character '" 274 + c1 275 + "' with value " 276 + (int) c1 277 + " at index " 278 + (index - 1) 279 + " in '" 280 + seq 281 + "'"); 282 } 283 } 284 throw new IndexOutOfBoundsException("Index exceeds specified range"); 285 } 286 287 /** 288 * Helper method to grow the character buffer as needed, this only happens once in a while so it's 289 * ok if it's in a method call. If the index passed in is 0 then no copying will be done. 290 */ 291 private static char[] growBuffer(char[] dest, int index, int size) { 292 if (size < 0) { // overflow - should be OutOfMemoryError but GWT/j2cl don't support it 293 throw new AssertionError("Cannot increase internal buffer any further"); 294 } 295 char[] copy = new char[size]; 296 if (index > 0) { 297 System.arraycopy(dest, 0, copy, 0, index); 298 } 299 return copy; 300 } 301}