1 // © 2016 and later: Unicode, Inc. and others. 2 // License & terms of use: http://www.unicode.org/copyright.html#License 3 /* 4 *************************************************************************** 5 * Copyright (C) 2008-2016 International Business Machines Corporation 6 * and others. All Rights Reserved. 7 *************************************************************************** 8 * 9 * Unicode Spoof Detection 10 */ 11 12 package com.ibm.icu.text; 13 14 import java.io.IOException; 15 import java.io.LineNumberReader; 16 import java.io.Reader; 17 import java.nio.ByteBuffer; 18 import java.text.ParseException; 19 import java.util.ArrayList; 20 import java.util.Arrays; 21 import java.util.BitSet; 22 import java.util.Collections; 23 import java.util.Comparator; 24 import java.util.HashSet; 25 import java.util.Hashtable; 26 import java.util.LinkedHashSet; 27 import java.util.Locale; 28 import java.util.MissingResourceException; 29 import java.util.Set; 30 import java.util.Vector; 31 import java.util.regex.Matcher; 32 import java.util.regex.Pattern; 33 34 import com.ibm.icu.impl.ICUBinary; 35 import com.ibm.icu.impl.ICUBinary.Authenticate; 36 import com.ibm.icu.impl.Utility; 37 import com.ibm.icu.lang.UCharacter; 38 import com.ibm.icu.lang.UCharacterCategory; 39 import com.ibm.icu.lang.UProperty; 40 import com.ibm.icu.lang.UScript; 41 import com.ibm.icu.util.ULocale; 42 43 /** 44 * <p> 45 * This class, based on <a href="http://unicode.org/reports/tr36">Unicode Technical Report #36</a> and 46 * <a href="http://unicode.org/reports/tr39">Unicode Technical Standard #39</a>, has two main functions: 47 * 48 * <ol> 49 * <li>Checking whether two strings are visually <em>confusable</em> with each other, such as "desparejado" and 50 * "ԁеѕрагејаԁо".</li> 51 * <li>Checking whether an individual string is likely to be an attempt at confusing the reader (<em>spoof 52 * detection</em>), such as "pаypаl" spelled with Cyrillic 'а' characters.</li> 53 * </ol> 54 * 55 * <p> 56 * Although originally designed as a method for flagging suspicious identifier strings such as URLs, 57 * <code>SpoofChecker</code> has a number of other practical use cases, such as preventing attempts to evade bad-word 58 * content filters. 59 * 60 * <h2>Confusables</h2> 61 * 62 * <p> 63 * The following example shows how to use <code>SpoofChecker</code> to check for confusability between two strings: 64 * 65 * <pre> 66 * <code> 67 * SpoofChecker sc = new SpoofChecker.Builder().setChecks(SpoofChecker.CONFUSABLE).build(); 68 * int result = sc.areConfusable("desparejado", "ԁеѕрагејаԁо"); 69 * System.out.println(result != 0); // true 70 * </code> 71 * </pre> 72 * 73 * <p> 74 * <code>SpoofChecker</code> uses a builder paradigm: options are specified within the context of a lightweight 75 * {@link SpoofChecker.Builder} object, and upon calling {@link SpoofChecker.Builder#build}, expensive data loading 76 * operations are performed, and an immutable <code>SpoofChecker</code> is returned. 77 * 78 * <p> 79 * The first line of the example creates a <code>SpoofChecker</code> object with confusable-checking enabled; the second 80 * line performs the confusability test. For best performance, the instance should be created once (e.g., upon 81 * application startup), and the more efficient {@link SpoofChecker#areConfusable} method can be used at runtime. 82 * 83 * <p> 84 * UTS 39 defines two strings to be <em>confusable</em> if they map to the same skeleton. A <em>skeleton</em> is a 85 * sequence of families of confusable characters, where each family has a single exemplar character. 86 * {@link SpoofChecker#getSkeleton} computes the skeleton for a particular string, so the following snippet is 87 * equivalent to the example above: 88 * 89 * <pre> 90 * <code> 91 * SpoofChecker sc = new SpoofChecker.Builder().setChecks(SpoofChecker.CONFUSABLE).build(); 92 * boolean result = sc.getSkeleton("desparejado").equals(sc.getSkeleton("ԁеѕрагејаԁо")); 93 * System.out.println(result); // true 94 * </code> 95 * </pre> 96 * 97 * <p> 98 * If you need to check if a string is confusable with any string in a dictionary of many strings, rather than calling 99 * {@link SpoofChecker#areConfusable} many times in a loop, {@link SpoofChecker#getSkeleton} can be used instead, as 100 * shown below: 101 * 102 * <pre> 103 * // Setup: 104 * String[] DICTIONARY = new String[]{ "lorem", "ipsum" }; // example 105 * SpoofChecker sc = new SpoofChecker.Builder().setChecks(SpoofChecker.CONFUSABLE).build(); 106 * HashSet<String> skeletons = new HashSet<String>(); 107 * for (String word : DICTIONARY) { 108 * skeletons.add(sc.getSkeleton(word)); 109 * } 110 * 111 * // Live Check: 112 * boolean result = skeletons.contains(sc.getSkeleton("1orern")); 113 * System.out.println(result); // true 114 * </pre> 115 * 116 * <p> 117 * <b>Note:</b> Since the Unicode confusables mapping table is frequently updated, confusable skeletons are <em>not</em> 118 * guaranteed to be the same between ICU releases. We therefore recommend that you always compute confusable skeletons 119 * at runtime and do not rely on creating a permanent, or difficult to update, database of skeletons. 120 * 121 * <h2>Spoof Detection</h2> 122 * 123 * <p> 124 * The following snippet shows a minimal example of using <code>SpoofChecker</code> to perform spoof detection on a 125 * string: 126 * 127 * <pre> 128 * SpoofChecker sc = new SpoofChecker.Builder() 129 * .setAllowedChars(SpoofChecker.RECOMMENDED.cloneAsThawed().addAll(SpoofChecker.INCLUSION)) 130 * .setRestrictionLevel(SpoofChecker.RestrictionLevel.MODERATELY_RESTRICTIVE) 131 * .setChecks(SpoofChecker.ALL_CHECKS &~ SpoofChecker.CONFUSABLE) 132 * .build(); 133 * boolean result = sc.failsChecks("pаypаl"); // with Cyrillic 'а' characters 134 * System.out.println(result); // true 135 * </pre> 136 * 137 * <p> 138 * As in the case for confusability checking, it is good practice to create one <code>SpoofChecker</code> instance at 139 * startup, and call the cheaper {@link SpoofChecker#failsChecks} online. In the second line, we specify the set of 140 * allowed characters to be those with type RECOMMENDED or INCLUSION, according to the recommendation in UTS 39. In the 141 * third line, the CONFUSABLE checks are disabled. It is good practice to disable them if you won't be using the 142 * instance to perform confusability checking. 143 * 144 * <p> 145 * To get more details on why a string failed the checks, use a {@link SpoofChecker.CheckResult}: 146 * 147 * <pre> 148 * <code> 149 * SpoofChecker sc = new SpoofChecker.Builder() 150 * .setAllowedChars(SpoofChecker.RECOMMENDED.cloneAsThawed().addAll(SpoofChecker.INCLUSION)) 151 * .setRestrictionLevel(SpoofChecker.RestrictionLevel.MODERATELY_RESTRICTIVE) 152 * .setChecks(SpoofChecker.ALL_CHECKS &~ SpoofChecker.CONFUSABLE) 153 * .build(); 154 * SpoofChecker.CheckResult checkResult = new SpoofChecker.CheckResult(); 155 * boolean result = sc.failsChecks("pаypаl", checkResult); 156 * System.out.println(checkResult.checks); // 16 157 * </code> 158 * </pre> 159 * 160 * <p> 161 * The return value is a bitmask of the checks that failed. In this case, there was one check that failed: 162 * {@link SpoofChecker#RESTRICTION_LEVEL}, corresponding to the fifth bit (16). The possible checks are: 163 * 164 * <ul> 165 * <li><code>RESTRICTION_LEVEL</code>: flags strings that violate the 166 * <a href="http://unicode.org/reports/tr39/#Restriction_Level_Detection">Restriction Level</a> test as specified in UTS 167 * 39; in most cases, this means flagging strings that contain characters from multiple different scripts.</li> 168 * <li><code>INVISIBLE</code>: flags strings that contain invisible characters, such as zero-width spaces, or character 169 * sequences that are likely not to display, such as multiple occurrences of the same non-spacing mark.</li> 170 * <li><code>CHAR_LIMIT</code>: flags strings that contain characters outside of a specified set of acceptable 171 * characters. See {@link SpoofChecker.Builder#setAllowedChars} and {@link SpoofChecker.Builder#setAllowedLocales}.</li> 172 * <li><code>MIXED_NUMBERS</code>: flags strings that contain digits from multiple different numbering systems.</li> 173 * </ul> 174 * 175 * <p> 176 * These checks can be enabled independently of each other. For example, if you were interested in checking for only the 177 * INVISIBLE and MIXED_NUMBERS conditions, you could do: 178 * 179 * <pre> 180 * <code> 181 * SpoofChecker sc = new SpoofChecker.Builder() 182 * .setChecks(SpoofChecker.INVISIBLE | SpoofChecker.MIXED_NUMBERS) 183 * .build(); 184 * boolean result = sc.failsChecks("৪8"); 185 * System.out.println(result); // true 186 * </code> 187 * </pre> 188 * 189 * <p> 190 * <b>Note:</b> The Restriction Level is the most powerful of the checks. The full logic is documented in 191 * <a href="http://unicode.org/reports/tr39/#Restriction_Level_Detection">UTS 39</a>, but the basic idea is that strings 192 * are restricted to contain characters from only a single script, <em>except</em> that most scripts are allowed to have 193 * Latin characters interspersed. Although the default restriction level is <code>HIGHLY_RESTRICTIVE</code>, it is 194 * recommended that users set their restriction level to <code>MODERATELY_RESTRICTIVE</code>, which allows Latin mixed 195 * with all other scripts except Cyrillic, Greek, and Cherokee, with which it is often confusable. For more details on 196 * the levels, see UTS 39 or {@link SpoofChecker.RestrictionLevel}. The Restriction Level test is aware of the set of 197 * allowed characters set in {@link SpoofChecker.Builder#setAllowedChars}. Note that characters which have script code 198 * COMMON or INHERITED, such as numbers and punctuation, are ignored when computing whether a string has multiple 199 * scripts. 200 * 201 * <h2>Additional Information</h2> 202 * 203 * <p> 204 * A <code>SpoofChecker</code> instance may be used repeatedly to perform checks on any number of identifiers. 205 * 206 * <p> 207 * <b>Thread Safety:</b> The methods on <code>SpoofChecker</code> objects are thread safe. The test functions for 208 * checking a single identifier, or for testing whether two identifiers are potentially confusable, may called 209 * concurrently from multiple threads using the same <code>SpoofChecker</code> instance. 210 * 211 * @stable ICU 4.6 212 */ 213 public class SpoofChecker { 214 215 /** 216 * Constants from UTS 39 for use in setRestrictionLevel. 217 * 218 * @stable ICU 53 219 */ 220 public enum RestrictionLevel { 221 /** 222 * All characters in the string are in the identifier profile and all characters in the string are in the ASCII 223 * range. 224 * 225 * @stable ICU 53 226 */ 227 ASCII, 228 /** 229 * The string classifies as ASCII-Only, or all characters in the string are in the identifier profile and the 230 * string is single-script, according to the definition in UTS 39 section 5.1. 231 * 232 * @stable ICU 53 233 */ 234 SINGLE_SCRIPT_RESTRICTIVE, 235 /** 236 * The string classifies as Single Script, or all characters in the string are in the identifier profile and the 237 * string is covered by any of the following sets of scripts, according to the definition in UTS 39 section 5.1: 238 * <ul> 239 * <li>Latin + Han + Bopomofo (or equivalently: Latn + Hanb)</li> 240 * <li>Latin + Han + Hiragana + Katakana (or equivalently: Latn + Jpan)</li> 241 * <li>Latin + Han + Hangul (or equivalently: Latn +Kore)</li> 242 * </ul> 243 * 244 * @stable ICU 53 245 */ 246 HIGHLY_RESTRICTIVE, 247 /** 248 * The string classifies as Highly Restrictive, or all characters in the string are in the identifier profile 249 * and the string is covered by Latin and any one other Recommended or Aspirational script, except Cyrillic, 250 * Greek, and Cherokee. 251 * 252 * @stable ICU 53 253 */ 254 MODERATELY_RESTRICTIVE, 255 /** 256 * All characters in the string are in the identifier profile. Allow arbitrary mixtures of scripts, such as 257 * Ωmega, Teχ, HλLF-LIFE, Toys-Я-Us. 258 * 259 * @stable ICU 53 260 */ 261 MINIMALLY_RESTRICTIVE, 262 /** 263 * Any valid identifiers, including characters outside of the Identifier Profile, such as I♥NY.org 264 * 265 * @stable ICU 53 266 */ 267 UNRESTRICTIVE, 268 } 269 270 /** 271 * Security Profile constant from UTS 39 for use in {@link SpoofChecker.Builder#setAllowedChars}. 272 * 273 * @stable ICU 58 274 */ 275 public static final UnicodeSet INCLUSION = new UnicodeSet( 276 "['\\-.\\:\\u00B7\\u0375\\u058A\\u05F3\\u05F4\\u06FD\\u06FE\\u0F0B\\u200C" 277 + "\\u200D\\u2010\\u2019\\u2027\\u30A0\\u30FB]" 278 ).freeze(); 279 // Note: data from IdentifierStatus.txt & IdentifierType.txt 280 // There is tooling to generate this constant in the unicodetools project: 281 // org.unicode.text.tools.RecommendedSetGenerator 282 // It will print the Java and C++ code to the console for easy copy-paste into this file. 283 284 /** 285 * Security Profile constant from UTS 39 for use in {@link SpoofChecker.Builder#setAllowedChars}. 286 * 287 * @stable ICU 58 288 */ 289 public static final UnicodeSet RECOMMENDED = new UnicodeSet( 290 "[0-9A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u0131\\u0134-\\u013E" 291 + "\\u0141-\\u0148\\u014A-\\u017E\\u018F\\u01A0\\u01A1\\u01AF\\u01B0\\u01CD-" 292 + "\\u01DC\\u01DE-\\u01E3\\u01E6-\\u01F0\\u01F4\\u01F5\\u01F8-\\u021B\\u021E" 293 + "\\u021F\\u0226-\\u0233\\u0259\\u02BB\\u02BC\\u02EC\\u0300-\\u0304\\u0306-" 294 + "\\u030C\\u030F-\\u0311\\u0313\\u0314\\u031B\\u0323-\\u0328\\u032D\\u032E" 295 + "\\u0330\\u0331\\u0335\\u0338\\u0339\\u0342\\u0345\\u037B-\\u037D\\u0386" 296 + "\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03CE\\u03FC-\\u045F\\u048A-" 297 + "\\u04FF\\u0510-\\u0529\\u052E\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0586" 298 + "\\u05B4\\u05D0-\\u05EA\\u05EF-\\u05F2\\u0620-\\u063F\\u0641-\\u0655\\u0660-" 299 + "\\u0669\\u0670-\\u0672\\u0674\\u0679-\\u068D\\u068F-\\u06A0\\u06A2-\\u06D3" 300 + "\\u06D5\\u06E5\\u06E6\\u06EE-\\u06FC\\u06FF\\u0750-\\u07B1\\u08A0-\\u08AC" 301 + "\\u08B2\\u08B6-\\u08C7\\u0901-\\u094D\\u094F\\u0950\\u0956\\u0957\\u0960-" 302 + "\\u0963\\u0966-\\u096F\\u0971-\\u0977\\u0979-\\u097F\\u0981-\\u0983\\u0985-" 303 + "\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9" 304 + "\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09E0-\\u09E3\\u09E6-" 305 + "\\u09F1\\u09FE\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28" 306 + "\\u0A2A-\\u0A30\\u0A32\\u0A35\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47" 307 + "\\u0A48\\u0A4B-\\u0A4D\\u0A5C\\u0A66-\\u0A74\\u0A81-\\u0A83\\u0A85-\\u0A8D" 308 + "\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9" 309 + "\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0-\\u0AE3\\u0AE6-" 310 + "\\u0AEF\\u0AFA-\\u0AFF\\u0B01-\\u0B03\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-" 311 + "\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3C-\\u0B43\\u0B47" 312 + "\\u0B48\\u0B4B-\\u0B4D\\u0B55-\\u0B57\\u0B5F-\\u0B61\\u0B66-\\u0B6F\\u0B71" 313 + "\\u0B82\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A" 314 + "\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BBE-" 315 + "\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD0\\u0BD7\\u0BE6-\\u0BEF\\u0C01-" 316 + "\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D-" 317 + "\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C60\\u0C61\\u0C66-" 318 + "\\u0C6F\\u0C80\\u0C82\\u0C83\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8" 319 + "\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBC-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD" 320 + "\\u0CD5\\u0CD6\\u0CE0-\\u0CE3\\u0CE6-\\u0CEF\\u0CF1\\u0CF2\\u0D00\\u0D02" 321 + "\\u0D03\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D-\\u0D43\\u0D46-" 322 + "\\u0D48\\u0D4A-\\u0D4E\\u0D54-\\u0D57\\u0D60\\u0D61\\u0D66-\\u0D6F\\u0D7A-" 323 + "\\u0D7F\\u0D82\\u0D83\\u0D85-\\u0D8E\\u0D91-\\u0D96\\u0D9A-\\u0DA5\\u0DA7-" 324 + "\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0DCA\\u0DCF-\\u0DD4\\u0DD6" 325 + "\\u0DD8-\\u0DDE\\u0DF2\\u0E01-\\u0E32\\u0E34-\\u0E3A\\u0E40-\\u0E4E\\u0E50-" 326 + "\\u0E59\\u0E81\\u0E82\\u0E84\\u0E86-\\u0E8A\\u0E8C-\\u0EA3\\u0EA5\\u0EA7-" 327 + "\\u0EB2\\u0EB4-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9" 328 + "\\u0EDE\\u0EDF\\u0F00\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F3E-\\u0F42\\u0F44-" 329 + "\\u0F47\\u0F49-\\u0F4C\\u0F4E-\\u0F51\\u0F53-\\u0F56\\u0F58-\\u0F5B\\u0F5D-" 330 + "\\u0F68\\u0F6A-\\u0F6C\\u0F71\\u0F72\\u0F74\\u0F7A-\\u0F80\\u0F82-\\u0F84" 331 + "\\u0F86-\\u0F92\\u0F94-\\u0F97\\u0F99-\\u0F9C\\u0F9E-\\u0FA1\\u0FA3-\\u0FA6" 332 + "\\u0FA8-\\u0FAB\\u0FAD-\\u0FB8\\u0FBA-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-" 333 + "\\u109D\\u10C7\\u10CD\\u10D0-\\u10F0\\u10F7-\\u10FA\\u10FD-\\u10FF\\u1200-" 334 + "\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288" 335 + "\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-" 336 + "\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-" 337 + "\\u135F\\u1380-\\u138F\\u1780-\\u17A2\\u17A5-\\u17A7\\u17A9-\\u17B3\\u17B6-" 338 + "\\u17CA\\u17D2\\u17D7\\u17DC\\u17E0-\\u17E9\\u1C90-\\u1CBA\\u1CBD-\\u1CBF" 339 + "\\u1E00-\\u1E99\\u1E9E\\u1EA0-\\u1EF9\\u1F00-\\u1F15\\u1F18-\\u1F1D\\u1F20-" 340 + "\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F70" 341 + "\\u1F72\\u1F74\\u1F76\\u1F78\\u1F7A\\u1F7C\\u1F80-\\u1FB4\\u1FB6-\\u1FBA" 342 + "\\u1FBC\\u1FC2-\\u1FC4\\u1FC6-\\u1FC8\\u1FCA\\u1FCC\\u1FD0-\\u1FD2\\u1FD6-" 343 + "\\u1FDA\\u1FE0-\\u1FE2\\u1FE4-\\u1FEA\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FF8" 344 + "\\u1FFA\\u1FFC\\u2D27\\u2D2D\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE" 345 + "\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6" 346 + "\\u2DD8-\\u2DDE\\u3005-\\u3007\\u3041-\\u3096\\u3099\\u309A\\u309D\\u309E" 347 + "\\u30A1-\\u30FA\\u30FC-\\u30FE\\u3105-\\u312D\\u312F\\u31A0-\\u31BF\\u3400-" 348 + "\\u4DBF\\u4E00-\\u9FFC\\uA67F\\uA717-\\uA71F\\uA788\\uA78D\\uA792\\uA793" 349 + "\\uA7AA\\uA7AE\\uA7B8\\uA7B9\\uA7C2-\\uA7CA\\uA9E7-\\uA9FE\\uAA60-\\uAA76" 350 + "\\uAA7A-\\uAA7F\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26" 351 + "\\uAB28-\\uAB2E\\uAB66\\uAB67\\uAC00-\\uD7A3\\uFA0E\\uFA0F\\uFA11\\uFA13" 352 + "\\uFA14\\uFA1F\\uFA21\\uFA23\\uFA24\\uFA27-\\uFA29\\U00011301\\U00011303" 353 + "\\U0001133B\\U0001133C\\U00016FF0\\U00016FF1\\U0001B150-\\U0001B152" 354 + "\\U0001B164-\\U0001B167\\U00020000-\\U0002A6DD\\U0002A700-\\U0002B734" 355 + "\\U0002B740-\\U0002B81D\\U0002B820-\\U0002CEA1\\U0002CEB0-\\U0002EBE0" 356 + "\\U00030000-\\U0003134A]" 357 ).freeze(); 358 // Note: data from IdentifierStatus.txt & IdentifierType.txt 359 // There is tooling to generate this constant in the unicodetools project: 360 // org.unicode.text.tools.RecommendedSetGenerator 361 // It will print the Java and C++ code to the console for easy copy-paste into this file. 362 363 /** 364 * Constants for the kinds of checks that USpoofChecker can perform. These values are used both to select the set of 365 * checks that will be performed, and to report results from the check function. 366 * 367 */ 368 369 /** 370 * When performing the two-string {@link SpoofChecker#areConfusable} test, this flag in the return value indicates 371 * that the two strings are visually confusable and that they are from the same script, according to UTS 39 section 372 * 4. 373 * 374 * @stable ICU 4.6 375 */ 376 public static final int SINGLE_SCRIPT_CONFUSABLE = 1; 377 378 /** 379 * When performing the two-string {@link SpoofChecker#areConfusable} test, this flag in the return value indicates 380 * that the two strings are visually confusable and that they are <b>not</b> from the same script, according to UTS 381 * 39 section 4. 382 * 383 * @stable ICU 4.6 384 */ 385 public static final int MIXED_SCRIPT_CONFUSABLE = 2; 386 387 /** 388 * When performing the two-string {@link SpoofChecker#areConfusable} test, this flag in the return value indicates 389 * that the two strings are visually confusable and that they are not from the same script but both of them are 390 * single-script strings, according to UTS 39 section 4. 391 * 392 * @stable ICU 4.6 393 */ 394 public static final int WHOLE_SCRIPT_CONFUSABLE = 4; 395 396 /** 397 * Enable this flag in {@link SpoofChecker.Builder#setChecks} to turn on all types of confusables. You may set the 398 * checks to some subset of SINGLE_SCRIPT_CONFUSABLE, MIXED_SCRIPT_CONFUSABLE, or WHOLE_SCRIPT_CONFUSABLE to make 399 * {@link SpoofChecker#areConfusable} return only those types of confusables. 400 * 401 * @stable ICU 58 402 */ 403 public static final int CONFUSABLE = SINGLE_SCRIPT_CONFUSABLE | MIXED_SCRIPT_CONFUSABLE | WHOLE_SCRIPT_CONFUSABLE; 404 405 /** 406 * This flag is deprecated and no longer affects the behavior of SpoofChecker. 407 * 408 * @deprecated ICU 58 Any case confusable mappings were removed from UTS 39; the corresponding ICU API was 409 * deprecated. 410 */ 411 @Deprecated 412 public static final int ANY_CASE = 8; 413 414 /** 415 * Check that an identifier satisfies the requirements for the restriction level specified in 416 * {@link SpoofChecker.Builder#setRestrictionLevel}. The default restriction level is 417 * {@link RestrictionLevel#HIGHLY_RESTRICTIVE}. 418 * 419 * @stable ICU 58 420 */ 421 public static final int RESTRICTION_LEVEL = 16; 422 423 /** 424 * Check that an identifier contains only characters from a single script (plus chars from the common and inherited 425 * scripts.) Applies to checks of a single identifier check only. 426 * 427 * @deprecated ICU 51 Use RESTRICTION_LEVEL 428 */ 429 @Deprecated 430 public static final int SINGLE_SCRIPT = RESTRICTION_LEVEL; 431 432 /** 433 * Check an identifier for the presence of invisible characters, such as zero-width spaces, or character sequences 434 * that are likely not to display, such as multiple occurrences of the same non-spacing mark. This check does not 435 * test the input string as a whole for conformance to any particular syntax for identifiers. 436 * 437 * @stable ICU 4.6 438 */ 439 public static final int INVISIBLE = 32; 440 441 /** 442 * Check that an identifier contains only characters from a specified set of acceptable characters. See 443 * {@link Builder#setAllowedChars} and {@link Builder#setAllowedLocales}. Note that a string that fails this check 444 * will also fail the {@link #RESTRICTION_LEVEL} check. 445 * 446 * @stable ICU 4.6 447 */ 448 public static final int CHAR_LIMIT = 64; 449 450 /** 451 * Check that an identifier does not mix numbers from different numbering systems. For more information, see UTS 39 452 * section 5.3. 453 * 454 * @stable ICU 58 455 */ 456 public static final int MIXED_NUMBERS = 128; 457 458 /** 459 * Check that an identifier does not have a combining character following a character in which that 460 * combining character would be hidden; for example 'i' followed by a U+0307 combining dot. 461 * <p> 462 * More specifically, the following characters are forbidden from preceding a U+0307: 463 * <ul> 464 * <li>Those with the Soft_Dotted Unicode property (which includes 'i' and 'j')</li> 465 * <li>Latin lowercase letter 'l'</li> 466 * <li>Dotless 'i' and 'j' ('ı' and 'ȷ', U+0131 and U+0237)</li> 467 * <li>Any character whose confusable prototype ends with such a character 468 * (Soft_Dotted, 'l', 'ı', or 'ȷ')</li> 469 * </ul> 470 * In addition, combining characters are allowed between the above characters and U+0307 except those 471 * with combining class 0 or combining class "Above" (230, same class as U+0307). 472 * <p> 473 * This list and the number of combing characters considered by this check may grow over time. 474 * 475 * @stable ICU 62 476 */ 477 public static final int HIDDEN_OVERLAY = 256; 478 479 // Update CheckResult.toString() when a new check is added. 480 481 /** 482 * Enable all spoof checks. 483 * 484 * @stable ICU 4.6 485 */ 486 public static final int ALL_CHECKS = 0xFFFFFFFF; 487 488 // Used for checking for ASCII-Only restriction level 489 static final UnicodeSet ASCII = new UnicodeSet(0, 0x7F).freeze(); 490 491 /** 492 * private constructor: a SpoofChecker has to be built by the builder 493 */ SpoofChecker()494 private SpoofChecker() { 495 } 496 497 /** 498 * SpoofChecker Builder. To create a SpoofChecker, first instantiate a SpoofChecker.Builder, set the desired 499 * checking options on the builder, then call the build() function to create a SpoofChecker instance. 500 * 501 * @stable ICU 4.6 502 */ 503 public static class Builder { 504 int fChecks; // Bit vector of checks to perform. 505 SpoofData fSpoofData; 506 final UnicodeSet fAllowedCharsSet = new UnicodeSet(0, 0x10ffff); // The UnicodeSet of allowed characters. 507 // for this Spoof Checker. Defaults to all chars. 508 final Set<ULocale> fAllowedLocales = new LinkedHashSet<>(); // The list of allowed locales. 509 private RestrictionLevel fRestrictionLevel; 510 511 /** 512 * Constructor: Create a default Unicode Spoof Checker Builder, configured to perform all checks except for 513 * LOCALE_LIMIT and CHAR_LIMIT. Note that additional checks may be added in the future, resulting in the changes 514 * to the default checking behavior. 515 * 516 * @stable ICU 4.6 517 */ Builder()518 public Builder() { 519 fChecks = ALL_CHECKS; 520 fSpoofData = null; 521 fRestrictionLevel = RestrictionLevel.HIGHLY_RESTRICTIVE; 522 } 523 524 /** 525 * Constructor: Create a Spoof Checker Builder, and set the configuration from an existing SpoofChecker. 526 * 527 * @param src 528 * The existing checker. 529 * @stable ICU 4.6 530 */ Builder(SpoofChecker src)531 public Builder(SpoofChecker src) { 532 fChecks = src.fChecks; 533 fSpoofData = src.fSpoofData; // For the data, we will either use the source data 534 // as-is, or drop the builder's reference to it 535 // and generate new data, depending on what our 536 // caller does with the builder. 537 fAllowedCharsSet.set(src.fAllowedCharsSet); 538 fAllowedLocales.addAll(src.fAllowedLocales); 539 fRestrictionLevel = src.fRestrictionLevel; 540 } 541 542 /** 543 * Create a SpoofChecker with current configuration. 544 * 545 * @return SpoofChecker 546 * @stable ICU 4.6 547 */ build()548 public SpoofChecker build() { 549 // TODO: Make this data loading be lazy (see #12696). 550 if (fSpoofData == null) { 551 // read binary file 552 fSpoofData = SpoofData.getDefault(); 553 } 554 555 // Copy all state from the builder to the new SpoofChecker. 556 // Make sure that everything is either cloned or copied, so 557 // that subsequent re-use of the builder won't modify the built 558 // SpoofChecker. 559 // 560 // One exception to this: the SpoofData is just assigned. 561 // If the builder subsequently needs to modify fSpoofData 562 // it will create a new SpoofData object first. 563 564 SpoofChecker result = new SpoofChecker(); 565 result.fChecks = this.fChecks; 566 result.fSpoofData = this.fSpoofData; 567 result.fAllowedCharsSet = (UnicodeSet) (this.fAllowedCharsSet.clone()); 568 result.fAllowedCharsSet.freeze(); 569 result.fAllowedLocales = new HashSet<>(this.fAllowedLocales); 570 result.fRestrictionLevel = this.fRestrictionLevel; 571 return result; 572 } 573 574 /** 575 * Specify the source form of the spoof data Spoof Checker. The inputs correspond to the Unicode data file 576 * confusables.txt as described in Unicode UAX 39. The syntax of the source data is as described in UAX 39 for 577 * these files, and the content of these files is acceptable input. 578 * 579 * @param confusables 580 * the Reader of confusable characters definitions, as found in file confusables.txt from 581 * unicode.org. 582 * @throws ParseException 583 * To report syntax errors in the input. 584 * 585 * @stable ICU 58 586 */ setData(Reader confusables)587 public Builder setData(Reader confusables) throws ParseException, IOException { 588 589 // Compile the binary data from the source (text) format. 590 // Drop the builder's reference to any pre-existing data, which may 591 // be in use in an already-built checker. 592 593 fSpoofData = new SpoofData(); 594 ConfusabledataBuilder.buildConfusableData(confusables, fSpoofData); 595 return this; 596 } 597 598 /** 599 * Deprecated as of ICU 58; use {@link SpoofChecker.Builder#setData(Reader confusables)} instead. 600 * 601 * @param confusables 602 * the Reader of confusable characters definitions, as found in file confusables.txt from 603 * unicode.org. 604 * @param confusablesWholeScript 605 * No longer supported. 606 * @throws ParseException 607 * To report syntax errors in the input. 608 * 609 * @deprecated ICU 58 610 */ 611 @Deprecated setData(Reader confusables, Reader confusablesWholeScript)612 public Builder setData(Reader confusables, Reader confusablesWholeScript) throws ParseException, IOException { 613 setData(confusables); 614 return this; 615 } 616 617 /** 618 * Specify the bitmask of checks that will be performed by {@link SpoofChecker#failsChecks}. Calling this method 619 * overwrites any checks that may have already been enabled. By default, all checks are enabled. 620 * 621 * To enable specific checks and disable all others, the "whitelisted" checks should be ORed together. For 622 * example, to fail strings containing characters outside of the set specified by {@link #setAllowedChars} and 623 * also strings that contain digits from mixed numbering systems: 624 * 625 * <pre> 626 * {@code 627 * builder.setChecks(SpoofChecker.CHAR_LIMIT | SpoofChecker.MIXED_NUMBERS); 628 * } 629 * </pre> 630 * 631 * To disable specific checks and enable all others, the "blacklisted" checks should be ANDed away from 632 * ALL_CHECKS. For example, if you are not planning to use the {@link SpoofChecker#areConfusable} functionality, 633 * it is good practice to disable the CONFUSABLE check: 634 * 635 * <pre> 636 * {@code 637 * builder.setChecks(SpoofChecker.ALL_CHECKS & ~SpoofChecker.CONFUSABLE); 638 * } 639 * </pre> 640 * 641 * Note that methods such as {@link #setAllowedChars}, {@link #setAllowedLocales}, and 642 * {@link #setRestrictionLevel} will enable certain checks when called. Those methods will OR the check they 643 * enable onto the existing bitmask specified by this method. For more details, see the documentation of those 644 * methods. 645 * 646 * @param checks 647 * The set of checks that this spoof checker will perform. The value is an 'or' of the desired 648 * checks. 649 * @return self 650 * @stable ICU 4.6 651 */ setChecks(int checks)652 public Builder setChecks(int checks) { 653 // Verify that the requested checks are all ones (bits) that 654 // are acceptable, known values. 655 if (0 != (checks & ~SpoofChecker.ALL_CHECKS)) { 656 throw new IllegalArgumentException("Bad Spoof Checks value."); 657 } 658 this.fChecks = (checks & SpoofChecker.ALL_CHECKS); 659 return this; 660 } 661 662 /** 663 * Limit characters that are acceptable in identifiers being checked to those normally used with the languages 664 * associated with the specified locales. Any previously specified list of locales is replaced by the new 665 * settings. 666 * 667 * A set of languages is determined from the locale(s), and from those a set of acceptable Unicode scripts is 668 * determined. Characters from this set of scripts, along with characters from the "common" and "inherited" 669 * Unicode Script categories will be permitted. 670 * 671 * Supplying an empty string removes all restrictions; characters from any script will be allowed. 672 * 673 * The {@link #CHAR_LIMIT} test is automatically enabled for this SpoofChecker when calling this function with a 674 * non-empty list of locales. 675 * 676 * The Unicode Set of characters that will be allowed is accessible via the {@link #getAllowedChars} function. 677 * setAllowedLocales() will <i>replace</i> any previously applied set of allowed characters. 678 * 679 * Adjustments, such as additions or deletions of certain classes of characters, can be made to the result of 680 * {@link #setAllowedChars} by fetching the resulting set with {@link #getAllowedChars}, manipulating it with 681 * the Unicode Set API, then resetting the spoof detectors limits with {@link #setAllowedChars}. 682 * 683 * @param locales 684 * A Set of ULocales, from which the language and associated script are extracted. If the locales Set 685 * is null, no restrictions will be placed on the allowed characters. 686 * 687 * @return self 688 * @stable ICU 4.6 689 */ setAllowedLocales(Set<ULocale> locales)690 public Builder setAllowedLocales(Set<ULocale> locales) { 691 fAllowedCharsSet.clear(); 692 693 for (ULocale locale : locales) { 694 // Add the script chars for this locale to the accumulating set 695 // of allowed chars. 696 addScriptChars(locale, fAllowedCharsSet); 697 } 698 699 // If our caller provided an empty list of locales, we disable the 700 // allowed characters checking 701 fAllowedLocales.clear(); 702 if (locales.size() == 0) { 703 fAllowedCharsSet.add(0, 0x10ffff); 704 fChecks &= ~CHAR_LIMIT; 705 return this; 706 } 707 708 // Add all common and inherited characters to the set of allowed 709 // chars. 710 UnicodeSet tempSet = new UnicodeSet(); 711 tempSet.applyIntPropertyValue(UProperty.SCRIPT, UScript.COMMON); 712 fAllowedCharsSet.addAll(tempSet); 713 tempSet.applyIntPropertyValue(UProperty.SCRIPT, UScript.INHERITED); 714 fAllowedCharsSet.addAll(tempSet); 715 716 // Store the updated spoof checker state. 717 fAllowedLocales.clear(); 718 fAllowedLocales.addAll(locales); 719 fChecks |= CHAR_LIMIT; 720 return this; 721 } 722 723 /** 724 * Limit characters that are acceptable in identifiers being checked to those normally used with the languages 725 * associated with the specified locales. Any previously specified list of locales is replaced by the new 726 * settings. 727 * 728 * @param locales 729 * A Set of Locales, from which the language and associated script are extracted. If the locales Set 730 * is null, no restrictions will be placed on the allowed characters. 731 * 732 * @return self 733 * @stable ICU 54 734 */ setAllowedJavaLocales(Set<Locale> locales)735 public Builder setAllowedJavaLocales(Set<Locale> locales) { 736 HashSet<ULocale> ulocales = new HashSet<>(locales.size()); 737 for (Locale locale : locales) { 738 ulocales.add(ULocale.forLocale(locale)); 739 } 740 return setAllowedLocales(ulocales); 741 } 742 743 // Add (union) to the UnicodeSet all of the characters for the scripts 744 // used for the specified locale. Part of the implementation of 745 // setAllowedLocales. addScriptChars(ULocale locale, UnicodeSet allowedChars)746 private void addScriptChars(ULocale locale, UnicodeSet allowedChars) { 747 int scripts[] = UScript.getCode(locale); 748 if (scripts != null) { 749 UnicodeSet tmpSet = new UnicodeSet(); 750 for (int i = 0; i < scripts.length; i++) { 751 tmpSet.applyIntPropertyValue(UProperty.SCRIPT, scripts[i]); 752 allowedChars.addAll(tmpSet); 753 } 754 } 755 // else it's an unknown script. 756 // Maybe they asked for the script of "zxx", which refers to no linguistic content. 757 // Maybe they asked for the script of a newer locale that we don't know in the older version of ICU. 758 } 759 760 /** 761 * Limit the acceptable characters to those specified by a Unicode Set. Any previously specified character limit 762 * is is replaced by the new settings. This includes limits on characters that were set with the 763 * setAllowedLocales() function. Note that the RESTRICTED set is useful. 764 * 765 * The {@link #CHAR_LIMIT} test is automatically enabled for this SpoofChecker by this function. 766 * 767 * @param chars 768 * A Unicode Set containing the list of characters that are permitted. The incoming set is cloned by 769 * this function, so there are no restrictions on modifying or deleting the UnicodeSet after calling 770 * this function. Note that this clears the allowedLocales set. 771 * @return self 772 * @stable ICU 4.6 773 */ setAllowedChars(UnicodeSet chars)774 public Builder setAllowedChars(UnicodeSet chars) { 775 fAllowedCharsSet.set(chars); 776 fAllowedLocales.clear(); 777 fChecks |= CHAR_LIMIT; 778 return this; 779 } 780 781 /** 782 * Set the loosest restriction level allowed for strings. The default if this is not called is 783 * {@link RestrictionLevel#HIGHLY_RESTRICTIVE}. Calling this method enables the {@link #RESTRICTION_LEVEL} and 784 * {@link #MIXED_NUMBERS} checks, corresponding to Sections 5.1 and 5.2 of UTS 39. To customize which checks are 785 * to be performed by {@link SpoofChecker#failsChecks}, see {@link #setChecks}. 786 * 787 * @param restrictionLevel 788 * The loosest restriction level allowed. 789 * @return self 790 * @provisional This API might change or be removed in a future release. 791 * @stable ICU 58 792 */ setRestrictionLevel(RestrictionLevel restrictionLevel)793 public Builder setRestrictionLevel(RestrictionLevel restrictionLevel) { 794 fRestrictionLevel = restrictionLevel; 795 fChecks |= RESTRICTION_LEVEL | MIXED_NUMBERS; 796 return this; 797 } 798 799 /* 800 * ***************************************************************************** 801 * Internal classes for compililing confusable data into its binary (runtime) form. 802 * ***************************************************************************** 803 */ 804 // --------------------------------------------------------------------- 805 // 806 // buildConfusableData Compile the source confusable data, as defined by 807 // the Unicode data file confusables.txt, into the binary 808 // structures used by the confusable detector. 809 // 810 // The binary structures are described in uspoof_impl.h 811 // 812 // 1. parse the data, making a hash table mapping from a codepoint to a String. 813 // 814 // 2. Sort all of the strings encountered by length, since they will need to 815 // be stored in that order in the final string table. 816 // TODO: Sorting these strings by length is no longer needed since the removal of 817 // the string lengths table. This logic can be removed to save processing time 818 // when building confusables data. 819 // 820 // 3. Build a list of keys (UChar32s) from the mapping table. Sort the 821 // list because that will be the ordering of our runtime table. 822 // 823 // 4. Generate the run time string table. This is generated before the key & value 824 // table because we need the string indexes when building those tables. 825 // 826 // 5. Build the run-time key and value table. These are parallel tables, and 827 // are built at the same time 828 829 // class ConfusabledataBuilder 830 // An instance of this class exists while the confusable data is being built from source. 831 // It encapsulates the intermediate data structures that are used for building. 832 // It exports one static function, to do a confusable data build. 833 private static class ConfusabledataBuilder { 834 835 private Hashtable<Integer, SPUString> fTable; 836 private UnicodeSet fKeySet; // A set of all keys (UChar32s) that go into the 837 // four mapping tables. 838 839 // The compiled data is first assembled into the following four collections, 840 // then output to the builder's SpoofData object. 841 private StringBuffer fStringTable; 842 private ArrayList<Integer> fKeyVec; 843 private ArrayList<Integer> fValueVec; 844 private SPUStringPool stringPool; 845 private Pattern fParseLine; 846 private Pattern fParseHexNum; 847 private int fLineNum; 848 ConfusabledataBuilder()849 ConfusabledataBuilder() { 850 fTable = new Hashtable<>(); 851 fKeySet = new UnicodeSet(); 852 fKeyVec = new ArrayList<>(); 853 fValueVec = new ArrayList<>(); 854 stringPool = new SPUStringPool(); 855 } 856 build(Reader confusables, SpoofData dest)857 void build(Reader confusables, SpoofData dest) throws ParseException, java.io.IOException { 858 StringBuffer fInput = new StringBuffer(); 859 860 // Convert the user input data from UTF-8 to char (UTF-16) 861 LineNumberReader lnr = new LineNumberReader(confusables); 862 do { 863 String line = lnr.readLine(); 864 if (line == null) { 865 break; 866 } 867 fInput.append(line); 868 fInput.append('\n'); 869 } while (true); 870 871 // Regular Expression to parse a line from Confusables.txt. The expression will match 872 // any line. What was matched is determined by examining which capture groups have a match. 873 // Capture Group 1: the source char 874 // Capture Group 2: the replacement chars 875 // Capture Group 3-6 the table type, SL, SA, ML, or MA (deprecated) 876 // Capture Group 7: A blank or comment only line. 877 // Capture Group 8: A syntactically invalid line. Anything that didn't match before. 878 // Example Line from the confusables.txt source file: 879 // "1D702 ; 006E 0329 ; SL # MATHEMATICAL ITALIC SMALL ETA ... " 880 fParseLine = Pattern.compile("(?m)^[ \\t]*([0-9A-Fa-f]+)[ \\t]+;" + // Match the source char 881 "[ \\t]*([0-9A-Fa-f]+" + // Match the replacement char(s) 882 "(?:[ \\t]+[0-9A-Fa-f]+)*)[ \\t]*;" + // (continued) 883 "\\s*(?:(SL)|(SA)|(ML)|(MA))" + // Match the table type 884 "[ \\t]*(?:#.*?)?$" + // Match any trailing #comment 885 "|^([ \\t]*(?:#.*?)?)$" + // OR match empty lines or lines with only a #comment 886 "|^(.*?)$"); // OR match any line, which catches illegal lines. 887 888 // Regular expression for parsing a hex number out of a space-separated list of them. 889 // Capture group 1 gets the number, with spaces removed. 890 fParseHexNum = Pattern.compile("\\s*([0-9A-F]+)"); 891 892 // Zap any Byte Order Mark at the start of input. Changing it to a space 893 // is benign given the syntax of the input. 894 if (fInput.charAt(0) == 0xfeff) { 895 fInput.setCharAt(0, (char) 0x20); 896 } 897 898 // Parse the input, one line per iteration of this loop. 899 Matcher matcher = fParseLine.matcher(fInput); 900 while (matcher.find()) { 901 fLineNum++; 902 if (matcher.start(7) >= 0) { 903 // this was a blank or comment line. 904 continue; 905 } 906 if (matcher.start(8) >= 0) { 907 // input file syntax error. 908 // status = U_PARSE_ERROR; 909 throw new ParseException( 910 "Confusables, line " + fLineNum + ": Unrecognized Line: " + matcher.group(8), 911 matcher.start(8)); 912 } 913 914 // We have a good input line. Extract the key character and mapping 915 // string, and 916 // put them into the appropriate mapping table. 917 int keyChar = Integer.parseInt(matcher.group(1), 16); 918 if (keyChar > 0x10ffff) { 919 throw new ParseException( 920 "Confusables, line " + fLineNum + ": Bad code point: " + matcher.group(1), 921 matcher.start(1)); 922 } 923 Matcher m = fParseHexNum.matcher(matcher.group(2)); 924 925 StringBuilder mapString = new StringBuilder(); 926 while (m.find()) { 927 int c = Integer.parseInt(m.group(1), 16); 928 if (c > 0x10ffff) { 929 throw new ParseException( 930 "Confusables, line " + fLineNum + ": Bad code point: " + Integer.toString(c, 16), 931 matcher.start(2)); 932 } 933 mapString.appendCodePoint(c); 934 } 935 assert (mapString.length() >= 1); 936 937 // Put the map (value) string into the string pool 938 // This a little like a Java intern() - any duplicates will be 939 // eliminated. 940 SPUString smapString = stringPool.addString(mapString.toString()); 941 942 // Add the char . string mapping to the table. 943 // For Unicode 8, the SL, SA and ML tables have been discontinued. 944 // All input data from confusables.txt is tagged MA. 945 fTable.put(keyChar, smapString); 946 947 fKeySet.add(keyChar); 948 } 949 950 // Input data is now all parsed and collected. 951 // Now create the run-time binary form of the data. 952 // 953 // This is done in two steps. First the data is assembled into vectors and strings, 954 // for ease of construction, then the contents of these collections are copied 955 // into the actual SpoofData object. 956 957 // Build up the string array, and record the index of each string therein 958 // in the (build time only) string pool. 959 // Strings of length one are not entered into the strings array. 960 // (Strings in the table are sorted by length) 961 962 stringPool.sort(); 963 fStringTable = new StringBuffer(); 964 int poolSize = stringPool.size(); 965 int i; 966 for (i = 0; i < poolSize; i++) { 967 SPUString s = stringPool.getByIndex(i); 968 int strLen = s.fStr.length(); 969 int strIndex = fStringTable.length(); 970 if (strLen == 1) { 971 // strings of length one do not get an entry in the string table. 972 // Keep the single string character itself here, which is the same 973 // convention that is used in the final run-time string table index. 974 s.fCharOrStrTableIndex = s.fStr.charAt(0); 975 } else { 976 s.fCharOrStrTableIndex = strIndex; 977 fStringTable.append(s.fStr); 978 } 979 } 980 981 // Construct the compile-time Key and Value table. 982 // 983 // The keys in the Key table follow the format described in uspoof.h for the 984 // Cfu confusables data structure. 985 // 986 // Starting in ICU 58, each code point has exactly one entry in the data 987 // structure. 988 989 for (String keyCharStr : fKeySet) { 990 int keyChar = keyCharStr.codePointAt(0); 991 SPUString targetMapping = fTable.get(keyChar); 992 assert targetMapping != null; 993 994 // Throw a sane exception if trying to consume a long string. Otherwise, 995 // codePointAndLengthToKey will throw an assertion error. 996 if (targetMapping.fStr.length() > 256) { 997 throw new IllegalArgumentException("Confusable prototypes cannot be longer than 256 entries."); 998 } 999 1000 int key = ConfusableDataUtils.codePointAndLengthToKey(keyChar, targetMapping.fStr.length()); 1001 int value = targetMapping.fCharOrStrTableIndex; 1002 1003 fKeyVec.add(key); 1004 fValueVec.add(value); 1005 } 1006 1007 // Put the assembled data into the destination SpoofData object. 1008 1009 // The Key Table 1010 // While copying the keys to the output array, 1011 // also sanity check that the keys are sorted. 1012 int numKeys = fKeyVec.size(); 1013 dest.fCFUKeys = new int[numKeys]; 1014 int previousCodePoint = 0; 1015 for (i = 0; i < numKeys; i++) { 1016 int key = fKeyVec.get(i); 1017 int codePoint = ConfusableDataUtils.keyToCodePoint(key); 1018 // strictly greater because there can be only one entry per code point 1019 assert codePoint > previousCodePoint; 1020 dest.fCFUKeys[i] = key; 1021 previousCodePoint = codePoint; 1022 } 1023 1024 // The Value Table, parallels the key table 1025 int numValues = fValueVec.size(); 1026 assert (numKeys == numValues); 1027 dest.fCFUValues = new short[numValues]; 1028 i = 0; 1029 for (int value : fValueVec) { 1030 assert (value < 0xffff); 1031 dest.fCFUValues[i++] = (short) value; 1032 } 1033 1034 // The Strings Table. 1035 dest.fCFUStrings = fStringTable.toString(); 1036 } 1037 1038 public static void buildConfusableData(Reader confusables, SpoofData dest) 1039 throws java.io.IOException, ParseException { 1040 ConfusabledataBuilder builder = new ConfusabledataBuilder(); 1041 builder.build(confusables, dest); 1042 } 1043 1044 /* 1045 * ***************************************************************************** 1046 * Internal classes for compiling confusable data into its binary (runtime) form. 1047 * ***************************************************************************** 1048 */ 1049 // SPUString 1050 // Holds a string that is the result of one of the mappings defined 1051 // by the confusable mapping data (confusables.txt from Unicode.org) 1052 // Instances of SPUString exist during the compilation process only. 1053 1054 private static class SPUString { 1055 String fStr; // The actual string. 1056 int fCharOrStrTableIndex; // Index into the final runtime data for this string. 1057 // (or, for length 1, the single string char itself, 1058 // there being no string table entry for it.) 1059 1060 SPUString(String s) { 1061 fStr = s; 1062 fCharOrStrTableIndex = 0; 1063 } 1064 } 1065 1066 // Comparison function for ordering strings in the string pool. 1067 // Compare by length first, then, within a group of the same length, 1068 // by code point order. 1069 1070 private static class SPUStringComparator implements Comparator<SPUString> { 1071 @Override 1072 public int compare(SPUString sL, SPUString sR) { 1073 int lenL = sL.fStr.length(); 1074 int lenR = sR.fStr.length(); 1075 if (lenL < lenR) { 1076 return -1; 1077 } else if (lenL > lenR) { 1078 return 1; 1079 } else { 1080 return sL.fStr.compareTo(sR.fStr); 1081 } 1082 } 1083 1084 final static SPUStringComparator INSTANCE = new SPUStringComparator(); 1085 } 1086 1087 // String Pool A utility class for holding the strings that are the result of 1088 // the spoof mappings. These strings will utimately end up in the 1089 // run-time String Table. 1090 // This is sort of like a sorted set of strings, except that ICU's anemic 1091 // built-in collections don't support those, so it is implemented with a 1092 // combination of a uhash and a Vector. 1093 private static class SPUStringPool { 1094 public SPUStringPool() { 1095 fVec = new Vector<>(); 1096 fHash = new Hashtable<>(); 1097 } 1098 1099 public int size() { 1100 return fVec.size(); 1101 } 1102 1103 // Get the n-th string in the collection. 1104 public SPUString getByIndex(int index) { 1105 SPUString retString = fVec.elementAt(index); 1106 return retString; 1107 } 1108 1109 // Add a string. Return the string from the table. 1110 // If the input parameter string is already in the table, delete the 1111 // input parameter and return the existing string. 1112 public SPUString addString(String src) { 1113 SPUString hashedString = fHash.get(src); 1114 if (hashedString == null) { 1115 hashedString = new SPUString(src); 1116 fHash.put(src, hashedString); 1117 fVec.addElement(hashedString); 1118 } 1119 return hashedString; 1120 } 1121 1122 // Sort the contents; affects the ordering of getByIndex(). 1123 public void sort() { 1124 Collections.sort(fVec, SPUStringComparator.INSTANCE); 1125 } 1126 1127 private Vector<SPUString> fVec; // Elements are SPUString * 1128 private Hashtable<String, SPUString> fHash; // Key: Value: 1129 } 1130 1131 } 1132 } 1133 1134 /** 1135 * Get the Restriction Level that is being tested. 1136 * 1137 * @return The restriction level 1138 * @internal 1139 * @deprecated This API is ICU internal only. 1140 */ 1141 @Deprecated 1142 public RestrictionLevel getRestrictionLevel() { 1143 return fRestrictionLevel; 1144 } 1145 1146 /** 1147 * Get the set of checks that this Spoof Checker has been configured to perform. 1148 * 1149 * @return The set of checks that this spoof checker will perform. 1150 * @stable ICU 4.6 1151 */ 1152 public int getChecks() { 1153 return fChecks; 1154 } 1155 1156 /** 1157 * Get a read-only set of locales for the scripts that are acceptable in strings to be checked. If no limitations on 1158 * scripts have been specified, an empty set will be returned. 1159 * 1160 * setAllowedChars() will reset the list of allowed locales to be empty. 1161 * 1162 * The returned set may not be identical to the originally specified set that is supplied to setAllowedLocales(); 1163 * the information other than languages from the originally specified locales may be omitted. 1164 * 1165 * @return A set of locales corresponding to the acceptable scripts. 1166 * 1167 * @stable ICU 4.6 1168 */ 1169 public Set<ULocale> getAllowedLocales() { 1170 return Collections.unmodifiableSet(fAllowedLocales); 1171 } 1172 1173 /** 1174 * Get a set of {@link java.util.Locale} instances for the scripts that are acceptable in strings to be checked. If 1175 * no limitations on scripts have been specified, an empty set will be returned. 1176 * 1177 * @return A set of locales corresponding to the acceptable scripts. 1178 * @stable ICU 54 1179 */ 1180 public Set<Locale> getAllowedJavaLocales() { 1181 HashSet<Locale> locales = new HashSet<>(fAllowedLocales.size()); 1182 for (ULocale uloc : fAllowedLocales) { 1183 locales.add(uloc.toLocale()); 1184 } 1185 return locales; 1186 } 1187 1188 /** 1189 * Get a UnicodeSet for the characters permitted in an identifier. This corresponds to the limits imposed by the Set 1190 * Allowed Characters functions. Limitations imposed by other checks will not be reflected in the set returned by 1191 * this function. 1192 * 1193 * The returned set will be frozen, meaning that it cannot be modified by the caller. 1194 * 1195 * @return A UnicodeSet containing the characters that are permitted by the CHAR_LIMIT test. 1196 * @stable ICU 4.6 1197 */ 1198 public UnicodeSet getAllowedChars() { 1199 return fAllowedCharsSet; 1200 } 1201 1202 /** 1203 * A struct-like class to hold the results of a Spoof Check operation. Tells which check(s) have failed. 1204 * 1205 * @stable ICU 4.6 1206 */ 1207 public static class CheckResult { 1208 /** 1209 * Indicates which of the spoof check(s) have failed. The value is a bitwise OR of the constants for the tests 1210 * in question: RESTRICTION_LEVEL, CHAR_LIMIT, and so on. 1211 * 1212 * @stable ICU 4.6 1213 * @see Builder#setChecks 1214 */ 1215 public int checks; 1216 1217 /** 1218 * The index of the first string position that failed a check. 1219 * 1220 * @deprecated ICU 51. No longer supported. Always set to zero. 1221 */ 1222 @Deprecated 1223 public int position; 1224 1225 /** 1226 * The numerics found in the string, if MIXED_NUMBERS was set; otherwise null. The set will contain the zero 1227 * digit from each decimal number system found in the input string. 1228 * 1229 * @stable ICU 58 1230 */ 1231 public UnicodeSet numerics; 1232 1233 /** 1234 * The restriction level that the text meets, if RESTRICTION_LEVEL is set; otherwise null. 1235 * 1236 * @stable ICU 58 1237 */ 1238 public RestrictionLevel restrictionLevel; 1239 1240 /** 1241 * Default constructor 1242 * 1243 * @stable ICU 4.6 1244 */ 1245 public CheckResult() { 1246 checks = 0; 1247 position = 0; 1248 } 1249 1250 /** 1251 * {@inheritDoc} 1252 * 1253 * @stable ICU 4.6 1254 */ 1255 @Override 1256 public String toString() { 1257 StringBuilder sb = new StringBuilder(); 1258 sb.append("checks:"); 1259 if (checks == 0) { 1260 sb.append(" none"); 1261 } else if (checks == ALL_CHECKS) { 1262 sb.append(" all"); 1263 } else { 1264 if ((checks & SINGLE_SCRIPT_CONFUSABLE) != 0) { 1265 sb.append(" SINGLE_SCRIPT_CONFUSABLE"); 1266 } 1267 if ((checks & MIXED_SCRIPT_CONFUSABLE) != 0) { 1268 sb.append(" MIXED_SCRIPT_CONFUSABLE"); 1269 } 1270 if ((checks & WHOLE_SCRIPT_CONFUSABLE) != 0) { 1271 sb.append(" WHOLE_SCRIPT_CONFUSABLE"); 1272 } 1273 if ((checks & ANY_CASE) != 0) { 1274 sb.append(" ANY_CASE"); 1275 } 1276 if ((checks & RESTRICTION_LEVEL) != 0) { 1277 sb.append(" RESTRICTION_LEVEL"); 1278 } 1279 if ((checks & INVISIBLE) != 0) { 1280 sb.append(" INVISIBLE"); 1281 } 1282 if ((checks & CHAR_LIMIT) != 0) { 1283 sb.append(" CHAR_LIMIT"); 1284 } 1285 if ((checks & MIXED_NUMBERS) != 0) { 1286 sb.append(" MIXED_NUMBERS"); 1287 } 1288 } 1289 sb.append(", numerics: ").append(numerics.toPattern(false)); 1290 sb.append(", position: ").append(position); 1291 sb.append(", restrictionLevel: ").append(restrictionLevel); 1292 return sb.toString(); 1293 } 1294 } 1295 1296 /** 1297 * Check the specified string for possible security issues. The text to be checked will typically be an identifier 1298 * of some sort. The set of checks to be performed was specified when building the SpoofChecker. 1299 * 1300 * @param text 1301 * A String to be checked for possible security issues. 1302 * @param checkResult 1303 * Output parameter, indicates which specific tests failed. May be null if the information is not wanted. 1304 * @return True there any issue is found with the input string. 1305 * @stable ICU 4.8 1306 */ 1307 public boolean failsChecks(String text, CheckResult checkResult) { 1308 int length = text.length(); 1309 1310 int result = 0; 1311 if (checkResult != null) { 1312 checkResult.position = 0; 1313 checkResult.numerics = null; 1314 checkResult.restrictionLevel = null; 1315 } 1316 1317 if (0 != (this.fChecks & RESTRICTION_LEVEL)) { 1318 RestrictionLevel textRestrictionLevel = getRestrictionLevel(text); 1319 if (textRestrictionLevel.compareTo(fRestrictionLevel) > 0) { 1320 result |= RESTRICTION_LEVEL; 1321 } 1322 if (checkResult != null) { 1323 checkResult.restrictionLevel = textRestrictionLevel; 1324 } 1325 } 1326 1327 if (0 != (this.fChecks & MIXED_NUMBERS)) { 1328 UnicodeSet numerics = new UnicodeSet(); 1329 getNumerics(text, numerics); 1330 if (numerics.size() > 1) { 1331 result |= MIXED_NUMBERS; 1332 } 1333 if (checkResult != null) { 1334 checkResult.numerics = numerics; 1335 } 1336 } 1337 1338 if (0 != (this.fChecks & HIDDEN_OVERLAY)) { 1339 int index = findHiddenOverlay(text); 1340 if (index != -1) { 1341 result |= HIDDEN_OVERLAY; 1342 } 1343 } 1344 1345 if (0 != (this.fChecks & CHAR_LIMIT)) { 1346 int i; 1347 int c; 1348 for (i = 0; i < length;) { 1349 // U16_NEXT(text, i, length, c); 1350 c = Character.codePointAt(text, i); 1351 i = Character.offsetByCodePoints(text, i, 1); 1352 if (!this.fAllowedCharsSet.contains(c)) { 1353 result |= CHAR_LIMIT; 1354 break; 1355 } 1356 } 1357 } 1358 1359 if (0 != (this.fChecks & INVISIBLE)) { 1360 // This check needs to be done on NFD input 1361 String nfdText = nfdNormalizer.normalize(text); 1362 1363 // scan for more than one occurrence of the same non-spacing mark 1364 // in a sequence of non-spacing marks. 1365 int i; 1366 int c; 1367 int firstNonspacingMark = 0; 1368 boolean haveMultipleMarks = false; 1369 UnicodeSet marksSeenSoFar = new UnicodeSet(); // Set of combining marks in a 1370 // single combining sequence. 1371 for (i = 0; i < length;) { 1372 c = Character.codePointAt(nfdText, i); 1373 i = Character.offsetByCodePoints(nfdText, i, 1); 1374 if (Character.getType(c) != UCharacterCategory.NON_SPACING_MARK) { 1375 firstNonspacingMark = 0; 1376 if (haveMultipleMarks) { 1377 marksSeenSoFar.clear(); 1378 haveMultipleMarks = false; 1379 } 1380 continue; 1381 } 1382 if (firstNonspacingMark == 0) { 1383 firstNonspacingMark = c; 1384 continue; 1385 } 1386 if (!haveMultipleMarks) { 1387 marksSeenSoFar.add(firstNonspacingMark); 1388 haveMultipleMarks = true; 1389 } 1390 if (marksSeenSoFar.contains(c)) { 1391 // report the error, and stop scanning. 1392 // No need to find more than the first failure. 1393 result |= INVISIBLE; 1394 break; 1395 } 1396 marksSeenSoFar.add(c); 1397 } 1398 } 1399 if (checkResult != null) { 1400 checkResult.checks = result; 1401 } 1402 return (0 != result); 1403 } 1404 1405 /** 1406 * Check the specified string for possible security issues. The text to be checked will typically be an identifier 1407 * of some sort. The set of checks to be performed was specified when building the SpoofChecker. 1408 * 1409 * @param text 1410 * A String to be checked for possible security issues. 1411 * @return True there any issue is found with the input string. 1412 * @stable ICU 4.8 1413 */ failsChecks(String text)1414 public boolean failsChecks(String text) { 1415 return failsChecks(text, null); 1416 } 1417 1418 /** 1419 * Check the whether two specified strings are visually confusable. The types of confusability to be tested - single 1420 * script, mixed script, or whole script - are determined by the check options set for the SpoofChecker. 1421 * 1422 * The tests to be performed are controlled by the flags SINGLE_SCRIPT_CONFUSABLE MIXED_SCRIPT_CONFUSABLE 1423 * WHOLE_SCRIPT_CONFUSABLE At least one of these tests must be selected. 1424 * 1425 * ANY_CASE is a modifier for the tests. Select it if the identifiers may be of mixed case. If identifiers are case 1426 * folded for comparison and display to the user, do not select the ANY_CASE option. 1427 * 1428 * 1429 * @param s1 1430 * The first of the two strings to be compared for confusability. 1431 * @param s2 1432 * The second of the two strings to be compared for confusability. 1433 * @return Non-zero if s1 and s1 are confusable. If not 0, the value will indicate the type(s) of confusability 1434 * found, as defined by spoof check test constants. 1435 * @stable ICU 4.6 1436 */ areConfusable(String s1, String s2)1437 public int areConfusable(String s1, String s2) { 1438 // 1439 // See section 4 of UAX 39 for the algorithm for checking whether two strings are confusable, 1440 // and for definitions of the types (single, whole, mixed-script) of confusables. 1441 1442 // We only care about a few of the check flags. Ignore the others. 1443 // If no tests relevant to this function have been specified, signal an error. 1444 // TODO: is this really the right thing to do? It's probably an error on 1445 // the caller's part, but logically we would just return 0 (no error). 1446 if ((this.fChecks & CONFUSABLE) == 0) { 1447 throw new IllegalArgumentException("No confusable checks are enabled."); 1448 } 1449 1450 // Compute the skeletons and check for confusability. 1451 String s1Skeleton = getSkeleton(s1); 1452 String s2Skeleton = getSkeleton(s2); 1453 if (!s1Skeleton.equals(s2Skeleton)) { 1454 return 0; 1455 } 1456 1457 // If we get here, the strings are confusable. Now we just need to set the flags for the appropriate classes 1458 // of confusables according to UTS 39 section 4. 1459 // Start by computing the resolved script sets of s1 and s2. 1460 ScriptSet s1RSS = new ScriptSet(); 1461 getResolvedScriptSet(s1, s1RSS); 1462 ScriptSet s2RSS = new ScriptSet(); 1463 getResolvedScriptSet(s2, s2RSS); 1464 1465 // Turn on all applicable flags 1466 int result = 0; 1467 if (s1RSS.intersects(s2RSS)) { 1468 result |= SINGLE_SCRIPT_CONFUSABLE; 1469 } else { 1470 result |= MIXED_SCRIPT_CONFUSABLE; 1471 if (!s1RSS.isEmpty() && !s2RSS.isEmpty()) { 1472 result |= WHOLE_SCRIPT_CONFUSABLE; 1473 } 1474 } 1475 1476 // Turn off flags that the user doesn't want 1477 result &= fChecks; 1478 1479 return result; 1480 } 1481 1482 /** 1483 * Get the "skeleton" for an identifier string. Skeletons are a transformation of the input string; Two strings are 1484 * confusable if their skeletons are identical. See Unicode UAX 39 for additional information. 1485 * 1486 * Using skeletons directly makes it possible to quickly check whether an identifier is confusable with any of some 1487 * large set of existing identifiers, by creating an efficiently searchable collection of the skeletons. 1488 * 1489 * Skeletons are computed using the algorithm and data described in Unicode UAX 39. 1490 * 1491 * @param str 1492 * The input string whose skeleton will be generated. 1493 * @return The output skeleton string. 1494 * 1495 * @stable ICU 58 1496 */ getSkeleton(CharSequence str)1497 public String getSkeleton(CharSequence str) { 1498 // Apply the skeleton mapping to the NFD normalized input string 1499 // Accumulate the skeleton, possibly unnormalized, in a String. 1500 String nfdId = nfdNormalizer.normalize(str); 1501 int normalizedLen = nfdId.length(); 1502 StringBuilder skelSB = new StringBuilder(); 1503 for (int inputIndex = 0; inputIndex < normalizedLen;) { 1504 int c = Character.codePointAt(nfdId, inputIndex); 1505 inputIndex += Character.charCount(c); 1506 this.fSpoofData.confusableLookup(c, skelSB); 1507 } 1508 String skelStr = skelSB.toString(); 1509 skelStr = nfdNormalizer.normalize(skelStr); 1510 return skelStr; 1511 } 1512 1513 /** 1514 * Calls {@link SpoofChecker#getSkeleton(CharSequence id)}. Starting with ICU 55, the "type" parameter has been 1515 * ignored, and starting with ICU 58, this function has been deprecated. 1516 * 1517 * @param type 1518 * No longer supported. Prior to ICU 55, was used to specify the mapping table SL, SA, ML, or MA. 1519 * @param id 1520 * The input identifier whose skeleton will be generated. 1521 * @return The output skeleton string. 1522 * 1523 * @deprecated ICU 58 1524 */ 1525 @Deprecated getSkeleton(int type, String id)1526 public String getSkeleton(int type, String id) { 1527 return getSkeleton(id); 1528 } 1529 1530 /** 1531 * Equality function. Return true if the two SpoofChecker objects incorporate the same confusable data and have 1532 * enabled the same set of checks. 1533 * 1534 * @param other 1535 * the SpoofChecker being compared with. 1536 * @return true if the two SpoofCheckers are equal. 1537 * @stable ICU 4.6 1538 */ 1539 @Override equals(Object other)1540 public boolean equals(Object other) { 1541 if (!(other instanceof SpoofChecker)) { 1542 return false; 1543 } 1544 SpoofChecker otherSC = (SpoofChecker) other; 1545 if (fSpoofData != otherSC.fSpoofData && fSpoofData != null && !fSpoofData.equals(otherSC.fSpoofData)) { 1546 return false; 1547 } 1548 if (fChecks != otherSC.fChecks) { 1549 return false; 1550 } 1551 if (fAllowedLocales != otherSC.fAllowedLocales && fAllowedLocales != null 1552 && !fAllowedLocales.equals(otherSC.fAllowedLocales)) { 1553 return false; 1554 } 1555 if (fAllowedCharsSet != otherSC.fAllowedCharsSet && fAllowedCharsSet != null 1556 && !fAllowedCharsSet.equals(otherSC.fAllowedCharsSet)) { 1557 return false; 1558 } 1559 if (fRestrictionLevel != otherSC.fRestrictionLevel) { 1560 return false; 1561 } 1562 return true; 1563 } 1564 1565 /** 1566 * Overrides {@link Object#hashCode()}. 1567 * @stable ICU 4.6 1568 */ 1569 @Override hashCode()1570 public int hashCode() { 1571 return fChecks 1572 ^ fSpoofData.hashCode() 1573 ^ fAllowedLocales.hashCode() 1574 ^ fAllowedCharsSet.hashCode() 1575 ^ fRestrictionLevel.ordinal(); 1576 } 1577 1578 /** 1579 * Computes the augmented script set for a code point, according to UTS 39 section 5.1. 1580 */ getAugmentedScriptSet(int codePoint, ScriptSet result)1581 private static void getAugmentedScriptSet(int codePoint, ScriptSet result) { 1582 result.clear(); 1583 UScript.getScriptExtensions(codePoint, result); 1584 1585 // Section 5.1 step 1 1586 if (result.get(UScript.HAN)) { 1587 result.set(UScript.HAN_WITH_BOPOMOFO); 1588 result.set(UScript.JAPANESE); 1589 result.set(UScript.KOREAN); 1590 } 1591 if (result.get(UScript.HIRAGANA)) { 1592 result.set(UScript.JAPANESE); 1593 } 1594 if (result.get(UScript.KATAKANA)) { 1595 result.set(UScript.JAPANESE); 1596 } 1597 if (result.get(UScript.HANGUL)) { 1598 result.set(UScript.KOREAN); 1599 } 1600 if (result.get(UScript.BOPOMOFO)) { 1601 result.set(UScript.HAN_WITH_BOPOMOFO); 1602 } 1603 1604 // Section 5.1 step 2 1605 if (result.get(UScript.COMMON) || result.get(UScript.INHERITED)) { 1606 result.setAll(); 1607 } 1608 } 1609 1610 /** 1611 * Computes the resolved script set for a string, according to UTS 39 section 5.1. 1612 */ getResolvedScriptSet(CharSequence input, ScriptSet result)1613 private void getResolvedScriptSet(CharSequence input, ScriptSet result) { 1614 getResolvedScriptSetWithout(input, UScript.CODE_LIMIT, result); 1615 } 1616 1617 /** 1618 * Computes the resolved script set for a string, omitting characters having the specified script. If 1619 * UScript.CODE_LIMIT is passed as the second argument, all characters are included. 1620 */ getResolvedScriptSetWithout(CharSequence input, int script, ScriptSet result)1621 private void getResolvedScriptSetWithout(CharSequence input, int script, ScriptSet result) { 1622 result.setAll(); 1623 1624 ScriptSet temp = new ScriptSet(); 1625 for (int utf16Offset = 0; utf16Offset < input.length();) { 1626 int codePoint = Character.codePointAt(input, utf16Offset); 1627 utf16Offset += Character.charCount(codePoint); 1628 1629 // Compute the augmented script set for the character 1630 getAugmentedScriptSet(codePoint, temp); 1631 1632 // Intersect the augmented script set with the resolved script set, but only if the character doesn't 1633 // have the script specified in the function call 1634 if (script == UScript.CODE_LIMIT || !temp.get(script)) { 1635 result.and(temp); 1636 } 1637 } 1638 } 1639 1640 /** 1641 * Computes the set of numerics for a string, according to UTS 39 section 5.3. 1642 */ getNumerics(String input, UnicodeSet result)1643 private void getNumerics(String input, UnicodeSet result) { 1644 result.clear(); 1645 1646 for (int utf16Offset = 0; utf16Offset < input.length();) { 1647 int codePoint = Character.codePointAt(input, utf16Offset); 1648 utf16Offset += Character.charCount(codePoint); 1649 1650 // Store a representative character for each kind of decimal digit 1651 if (UCharacter.getType(codePoint) == UCharacterCategory.DECIMAL_DIGIT_NUMBER) { 1652 // Store the zero character as a representative for comparison. 1653 // Unicode guarantees it is codePoint - value 1654 result.add(codePoint - UCharacter.getNumericValue(codePoint)); 1655 } 1656 } 1657 } 1658 1659 /** 1660 * Computes the restriction level of a string, according to UTS 39 section 5.2. 1661 */ getRestrictionLevel(String input)1662 private RestrictionLevel getRestrictionLevel(String input) { 1663 // Section 5.2 step 1: 1664 if (!fAllowedCharsSet.containsAll(input)) { 1665 return RestrictionLevel.UNRESTRICTIVE; 1666 } 1667 1668 // Section 5.2 step 2: 1669 if (ASCII.containsAll(input)) { 1670 return RestrictionLevel.ASCII; 1671 } 1672 1673 // Section 5.2 steps 3: 1674 ScriptSet resolvedScriptSet = new ScriptSet(); 1675 getResolvedScriptSet(input, resolvedScriptSet); 1676 1677 // Section 5.2 step 4: 1678 if (!resolvedScriptSet.isEmpty()) { 1679 return RestrictionLevel.SINGLE_SCRIPT_RESTRICTIVE; 1680 } 1681 1682 // Section 5.2 step 5: 1683 ScriptSet resolvedNoLatn = new ScriptSet(); 1684 getResolvedScriptSetWithout(input, UScript.LATIN, resolvedNoLatn); 1685 1686 // Section 5.2 step 6: 1687 if (resolvedNoLatn.get(UScript.HAN_WITH_BOPOMOFO) || resolvedNoLatn.get(UScript.JAPANESE) 1688 || resolvedNoLatn.get(UScript.KOREAN)) { 1689 return RestrictionLevel.HIGHLY_RESTRICTIVE; 1690 } 1691 1692 // Section 5.2 step 7: 1693 if (!resolvedNoLatn.isEmpty() && !resolvedNoLatn.get(UScript.CYRILLIC) && !resolvedNoLatn.get(UScript.GREEK) 1694 && !resolvedNoLatn.get(UScript.CHEROKEE)) { 1695 return RestrictionLevel.MODERATELY_RESTRICTIVE; 1696 } 1697 1698 // Section 5.2 step 8: 1699 return RestrictionLevel.MINIMALLY_RESTRICTIVE; 1700 } 1701 findHiddenOverlay(String input)1702 int findHiddenOverlay(String input) { 1703 boolean sawLeadCharacter = false; 1704 StringBuilder sb = new StringBuilder(); 1705 for (int i=0; i<input.length();) { 1706 int cp = input.codePointAt(i); 1707 if (sawLeadCharacter && cp == 0x0307) { 1708 return i; 1709 } 1710 int combiningClass = UCharacter.getCombiningClass(cp); 1711 // Skip over characters except for those with combining class 0 (non-combining characters) or with 1712 // combining class 230 (same class as U+0307) 1713 assert UCharacter.getCombiningClass(0x0307) == 230; 1714 if (combiningClass == 0 || combiningClass == 230) { 1715 sawLeadCharacter = isIllegalCombiningDotLeadCharacter(cp, sb); 1716 } 1717 i += UCharacter.charCount(cp); 1718 } 1719 return -1; 1720 } 1721 isIllegalCombiningDotLeadCharacterNoLookup(int cp)1722 boolean isIllegalCombiningDotLeadCharacterNoLookup(int cp) { 1723 return cp == 'i' || cp == 'j' || cp == 'ı' || cp == 'ȷ' || cp == 'l' || 1724 UCharacter.hasBinaryProperty(cp, UProperty.SOFT_DOTTED); 1725 } 1726 isIllegalCombiningDotLeadCharacter(int cp, StringBuilder sb)1727 boolean isIllegalCombiningDotLeadCharacter(int cp, StringBuilder sb) { 1728 if (isIllegalCombiningDotLeadCharacterNoLookup(cp)) { 1729 return true; 1730 } 1731 sb.setLength(0); 1732 fSpoofData.confusableLookup(cp, sb); 1733 int finalCp = UCharacter.codePointBefore(sb, sb.length()); 1734 if (finalCp != cp && isIllegalCombiningDotLeadCharacterNoLookup(finalCp)) { 1735 return true; 1736 } 1737 return false; 1738 } 1739 1740 // Data Members 1741 private int fChecks; // Bit vector of checks to perform. 1742 private SpoofData fSpoofData; 1743 private Set<ULocale> fAllowedLocales; // The Set of allowed locales. 1744 private UnicodeSet fAllowedCharsSet; // The UnicodeSet of allowed characters. 1745 private RestrictionLevel fRestrictionLevel; 1746 1747 private static Normalizer2 nfdNormalizer = Normalizer2.getNFDInstance(); 1748 1749 // Confusable Mappings Data Structures, version 2.0 1750 // 1751 // This description and the corresponding implementation are to be kept 1752 // in-sync with the copy in icu4c uspoof_impl.h. 1753 // 1754 // For the confusable data, we are essentially implementing a map, 1755 // key: a code point 1756 // value: a string. Most commonly one char in length, but can be more. 1757 // 1758 // The keys are stored as a sorted array of 32 bit ints. 1759 // bits 0-23 a code point value 1760 // bits 24-31 length of value string, in UChars (between 1 and 256 UChars). 1761 // The key table is sorted in ascending code point order. (not on the 1762 // 32 bit int value, the flag bits do not participate in the sorting.) 1763 // 1764 // Lookup is done by means of a binary search in the key table. 1765 // 1766 // The corresponding values are kept in a parallel array of 16 bit ints. 1767 // If the value string is of length 1, it is literally in the value array. 1768 // For longer strings, the value array contains an index into the strings 1769 // table. 1770 // 1771 // String Table: 1772 // The strings table contains all of the value strings (those of length two or greater) 1773 // concatentated together into one long char (UTF-16) array. 1774 // 1775 // There is no nul character or other mark between adjacent strings. 1776 // 1777 //---------------------------------------------------------------------------- 1778 // 1779 // Changes from format version 1 to format version 2: 1780 // 1) Removal of the whole-script confusable data tables. 1781 // 2) Removal of the SL/SA/ML/MA and multi-table flags in the key bitmask. 1782 // 3) Expansion of string length value in the key bitmask from 2 bits to 8 bits. 1783 // 4) Removal of the string lengths table since 8 bits is sufficient for the 1784 // lengths of all entries in confusables.txt. 1785 // 1786 private static final class ConfusableDataUtils { 1787 public static final int FORMAT_VERSION = 2; // version for ICU 58 1788 keyToCodePoint(int key)1789 public static final int keyToCodePoint(int key) { 1790 return key & 0x00ffffff; 1791 } 1792 keyToLength(int key)1793 public static final int keyToLength(int key) { 1794 return ((key & 0xff000000) >> 24) + 1; 1795 } 1796 codePointAndLengthToKey(int codePoint, int length)1797 public static final int codePointAndLengthToKey(int codePoint, int length) { 1798 assert (codePoint & 0x00ffffff) == codePoint; 1799 assert length <= 256; 1800 return codePoint | ((length - 1) << 24); 1801 } 1802 } 1803 1804 // ------------------------------------------------------------------------------------- 1805 // 1806 // SpoofData 1807 // 1808 // This class corresponds to the ICU SpoofCheck data. 1809 // 1810 // The data can originate with the Binary ICU data that is generated in ICU4C, 1811 // or it can originate from source rules that are compiled in ICU4J. 1812 // 1813 // This class does not include the set of checks to be performed, but only 1814 // data that is serialized into the ICU binary data. 1815 // 1816 // Because Java cannot easily wrap binary data like ICU4C, the binary data is 1817 // copied into Java structures that are convenient for use by the run time code. 1818 // 1819 // --------------------------------------------------------------------------------------- 1820 private static class SpoofData { 1821 1822 // The Confusable data, Java data structures for. 1823 int[] fCFUKeys; 1824 short[] fCFUValues; 1825 String fCFUStrings; 1826 1827 private static final int DATA_FORMAT = 0x43667520; // "Cfu " 1828 1829 private static final class IsAcceptable implements Authenticate { 1830 @Override isDataVersionAcceptable(byte version[])1831 public boolean isDataVersionAcceptable(byte version[]) { 1832 return version[0] == ConfusableDataUtils.FORMAT_VERSION || version[1] != 0 || version[2] != 0 1833 || version[3] != 0; 1834 } 1835 } 1836 1837 private static final IsAcceptable IS_ACCEPTABLE = new IsAcceptable(); 1838 1839 private static final class DefaultData { 1840 private static SpoofData INSTANCE = null; 1841 private static IOException EXCEPTION = null; 1842 1843 static { 1844 // Note: Although this is static, the Java runtime can delay execution of this block until 1845 // the data is actually requested via SpoofData.getDefault(). 1846 try { 1847 INSTANCE = new SpoofData(ICUBinary.getRequiredData("confusables.cfu")); 1848 } catch (IOException e) { 1849 EXCEPTION = e; 1850 } 1851 } 1852 } 1853 1854 /** 1855 * @return instance for Unicode standard data 1856 */ getDefault()1857 public static SpoofData getDefault() { 1858 if (DefaultData.EXCEPTION != null) { 1859 throw new MissingResourceException( 1860 "Could not load default confusables data: " + DefaultData.EXCEPTION.getMessage(), 1861 "SpoofChecker", ""); 1862 } 1863 return DefaultData.INSTANCE; 1864 } 1865 1866 // SpoofChecker Data constructor for use from data builder. 1867 // Initializes a new, empty data area that will be populated later. SpoofData()1868 private SpoofData() { 1869 } 1870 1871 // Constructor for use when creating from prebuilt default data. 1872 // A ByteBuffer is what the ICU internal data loading functions provide. SpoofData(ByteBuffer bytes)1873 private SpoofData(ByteBuffer bytes) throws java.io.IOException { 1874 ICUBinary.readHeader(bytes, DATA_FORMAT, IS_ACCEPTABLE); 1875 bytes.mark(); 1876 readData(bytes); 1877 } 1878 1879 @Override equals(Object other)1880 public boolean equals(Object other) { 1881 if (!(other instanceof SpoofData)) { 1882 return false; 1883 } 1884 SpoofData otherData = (SpoofData) other; 1885 if (!Arrays.equals(fCFUKeys, otherData.fCFUKeys)) 1886 return false; 1887 if (!Arrays.equals(fCFUValues, otherData.fCFUValues)) 1888 return false; 1889 if (!Utility.sameObjects(fCFUStrings, otherData.fCFUStrings) && fCFUStrings != null 1890 && !fCFUStrings.equals(otherData.fCFUStrings)) 1891 return false; 1892 return true; 1893 } 1894 1895 @Override hashCode()1896 public int hashCode() { 1897 return Arrays.hashCode(fCFUKeys) 1898 ^ Arrays.hashCode(fCFUValues) 1899 ^ fCFUStrings.hashCode(); 1900 } 1901 1902 // Set the SpoofChecker data from pre-built binary data in a byte buffer. 1903 // The binary data format is as described for ICU4C spoof data. 1904 // readData(ByteBuffer bytes)1905 private void readData(ByteBuffer bytes) throws java.io.IOException { 1906 int magic = bytes.getInt(); 1907 if (magic != 0x3845fdef) { 1908 throw new IllegalArgumentException("Bad Spoof Check Data."); 1909 } 1910 @SuppressWarnings("unused") 1911 int dataFormatVersion = bytes.getInt(); 1912 @SuppressWarnings("unused") 1913 int dataLength = bytes.getInt(); 1914 1915 int CFUKeysOffset = bytes.getInt(); 1916 int CFUKeysSize = bytes.getInt(); 1917 1918 int CFUValuesOffset = bytes.getInt(); 1919 int CFUValuesSize = bytes.getInt(); 1920 1921 int CFUStringTableOffset = bytes.getInt(); 1922 int CFUStringTableSize = bytes.getInt(); 1923 1924 // We have now read the file header, and obtained the position for each 1925 // of the data items. Now read each in turn, first seeking the 1926 // input stream to the position of the data item. 1927 1928 bytes.reset(); 1929 ICUBinary.skipBytes(bytes, CFUKeysOffset); 1930 fCFUKeys = ICUBinary.getInts(bytes, CFUKeysSize, 0); 1931 1932 bytes.reset(); 1933 ICUBinary.skipBytes(bytes, CFUValuesOffset); 1934 fCFUValues = ICUBinary.getShorts(bytes, CFUValuesSize, 0); 1935 1936 bytes.reset(); 1937 ICUBinary.skipBytes(bytes, CFUStringTableOffset); 1938 fCFUStrings = ICUBinary.getString(bytes, CFUStringTableSize, 0); 1939 } 1940 1941 /** 1942 * Append the confusable skeleton transform for a single code point to a StringBuilder. The string to be 1943 * appended will between 1 and 18 characters as of Unicode 9. 1944 * 1945 * This is the heart of the confusable skeleton generation implementation. 1946 */ confusableLookup(int inChar, StringBuilder dest)1947 public void confusableLookup(int inChar, StringBuilder dest) { 1948 // Perform a binary search. 1949 // [lo, hi), i.e lo is inclusive, hi is exclusive. 1950 // The result after the loop will be in lo. 1951 int lo = 0; 1952 int hi = length(); 1953 do { 1954 int mid = (lo + hi) / 2; 1955 if (codePointAt(mid) > inChar) { 1956 hi = mid; 1957 } else if (codePointAt(mid) < inChar) { 1958 lo = mid; 1959 } else { 1960 // Found result. Break early. 1961 lo = mid; 1962 break; 1963 } 1964 } while (hi - lo > 1); 1965 1966 // Did we find an entry? If not, the char maps to itself. 1967 if (codePointAt(lo) != inChar) { 1968 dest.appendCodePoint(inChar); 1969 return; 1970 } 1971 1972 // Add the element to the string builder and return. 1973 appendValueTo(lo, dest); 1974 return; 1975 } 1976 1977 /** 1978 * Return the number of confusable entries in this SpoofData. 1979 * 1980 * @return The number of entries. 1981 */ length()1982 public int length() { 1983 return fCFUKeys.length; 1984 } 1985 1986 /** 1987 * Return the code point (key) at the specified index. 1988 * 1989 * @param index 1990 * The index within the SpoofData. 1991 * @return The code point. 1992 */ codePointAt(int index)1993 public int codePointAt(int index) { 1994 return ConfusableDataUtils.keyToCodePoint(fCFUKeys[index]); 1995 } 1996 1997 /** 1998 * Append the confusable skeleton at the specified index to the StringBuilder dest. 1999 * 2000 * @param index 2001 * The index within the SpoofData. 2002 * @param dest 2003 * The StringBuilder to which to append the skeleton. 2004 */ appendValueTo(int index, StringBuilder dest)2005 public void appendValueTo(int index, StringBuilder dest) { 2006 int stringLength = ConfusableDataUtils.keyToLength(fCFUKeys[index]); 2007 2008 // Value is either a char (for strings of length 1) or 2009 // an index into the string table (for longer strings) 2010 short value = fCFUValues[index]; 2011 if (stringLength == 1) { 2012 dest.append((char) value); 2013 } else { 2014 dest.append(fCFUStrings, value, value + stringLength); 2015 } 2016 } 2017 } 2018 2019 // ------------------------------------------------------------------------------- 2020 // 2021 // ScriptSet - Script code bit sets. 2022 // Extends Java BitSet with input/output support and a few helper methods. 2023 // Note: The I/O is not currently being used, so it has been commented out. If 2024 // it is needed again, the code can be restored. 2025 // 2026 // ------------------------------------------------------------------------------- 2027 static class ScriptSet extends BitSet { 2028 2029 // Eclipse default value to quell warnings: 2030 private static final long serialVersionUID = 1L; 2031 2032 // // The serialized version of this class can hold INT_CAPACITY * 32 scripts. 2033 // private static final int INT_CAPACITY = 6; 2034 // private static final long serialVersionUID = INT_CAPACITY; 2035 // static { 2036 // assert ScriptSet.INT_CAPACITY * Integer.SIZE <= UScript.CODE_LIMIT; 2037 // } 2038 // 2039 // public ScriptSet() { 2040 // } 2041 // 2042 // public ScriptSet(ByteBuffer bytes) throws java.io.IOException { 2043 // for (int i = 0; i < INT_CAPACITY; i++) { 2044 // int bits = bytes.getInt(); 2045 // for (int j = 0; j < Integer.SIZE; j++) { 2046 // if ((bits & (1 << j)) != 0) { 2047 // set(i * Integer.SIZE + j); 2048 // } 2049 // } 2050 // } 2051 // } 2052 // 2053 // public void output(DataOutputStream os) throws java.io.IOException { 2054 // for (int i = 0; i < INT_CAPACITY; i++) { 2055 // int bits = 0; 2056 // for (int j = 0; j < Integer.SIZE; j++) { 2057 // if (get(i * Integer.SIZE + j)) { 2058 // bits |= (1 << j); 2059 // } 2060 // } 2061 // os.writeInt(bits); 2062 // } 2063 // } 2064 and(int script)2065 public void and(int script) { 2066 this.clear(0, script); 2067 this.clear(script + 1, UScript.CODE_LIMIT); 2068 } 2069 setAll()2070 public void setAll() { 2071 this.set(0, UScript.CODE_LIMIT); 2072 } 2073 isFull()2074 public boolean isFull() { 2075 return cardinality() == UScript.CODE_LIMIT; 2076 } 2077 appendStringTo(StringBuilder sb)2078 public void appendStringTo(StringBuilder sb) { 2079 sb.append("{ "); 2080 if (isEmpty()) { 2081 sb.append("- "); 2082 } else if (isFull()) { 2083 sb.append("* "); 2084 } else { 2085 for (int script = 0; script < UScript.CODE_LIMIT; script++) { 2086 if (get(script)) { 2087 sb.append(UScript.getShortName(script)); 2088 sb.append(" "); 2089 } 2090 } 2091 } 2092 sb.append("}"); 2093 } 2094 2095 @Override toString()2096 public String toString() { 2097 StringBuilder sb = new StringBuilder(); 2098 sb.append("<ScriptSet "); 2099 appendStringTo(sb); 2100 sb.append(">"); 2101 return sb.toString(); 2102 } 2103 } 2104 } 2105