1 // © 2016 and later: Unicode, Inc. and others. 2 // License & terms of use: http://www.unicode.org/copyright.html 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, 622 * OR together only the bit constants for the desired checks. 623 * For example, to fail strings containing characters outside of 624 * the set specified by {@link #setAllowedChars} and 625 * also strings that contain digits from mixed numbering systems: 626 * 627 * <pre> 628 * {@code 629 * builder.setChecks(SpoofChecker.CHAR_LIMIT | SpoofChecker.MIXED_NUMBERS); 630 * } 631 * </pre> 632 * 633 * To disable specific checks and enable all others, 634 * start with ALL_CHECKS and "AND away" the not-desired checks. 635 * For example, if you are not planning to use the {@link SpoofChecker#areConfusable} functionality, 636 * it is good practice to disable the CONFUSABLE check: 637 * 638 * <pre> 639 * {@code 640 * builder.setChecks(SpoofChecker.ALL_CHECKS & ~SpoofChecker.CONFUSABLE); 641 * } 642 * </pre> 643 * 644 * Note that methods such as {@link #setAllowedChars}, {@link #setAllowedLocales}, and 645 * {@link #setRestrictionLevel} will enable certain checks when called. Those methods will OR the check they 646 * enable onto the existing bitmask specified by this method. For more details, see the documentation of those 647 * methods. 648 * 649 * @param checks 650 * The set of checks that this spoof checker will perform. The value is an 'or' of the desired 651 * checks. 652 * @return self 653 * @stable ICU 4.6 654 */ setChecks(int checks)655 public Builder setChecks(int checks) { 656 // Verify that the requested checks are all ones (bits) that 657 // are acceptable, known values. 658 if (0 != (checks & ~SpoofChecker.ALL_CHECKS)) { 659 throw new IllegalArgumentException("Bad Spoof Checks value."); 660 } 661 this.fChecks = (checks & SpoofChecker.ALL_CHECKS); 662 return this; 663 } 664 665 /** 666 * Limit characters that are acceptable in identifiers being checked to those normally used with the languages 667 * associated with the specified locales. Any previously specified list of locales is replaced by the new 668 * settings. 669 * 670 * A set of languages is determined from the locale(s), and from those a set of acceptable Unicode scripts is 671 * determined. Characters from this set of scripts, along with characters from the "common" and "inherited" 672 * Unicode Script categories will be permitted. 673 * 674 * Supplying an empty string removes all restrictions; characters from any script will be allowed. 675 * 676 * The {@link #CHAR_LIMIT} test is automatically enabled for this SpoofChecker when calling this function with a 677 * non-empty list of locales. 678 * 679 * The Unicode Set of characters that will be allowed is accessible via the {@link #getAllowedChars} function. 680 * setAllowedLocales() will <i>replace</i> any previously applied set of allowed characters. 681 * 682 * Adjustments, such as additions or deletions of certain classes of characters, can be made to the result of 683 * {@link #setAllowedChars} by fetching the resulting set with {@link #getAllowedChars}, manipulating it with 684 * the Unicode Set API, then resetting the spoof detectors limits with {@link #setAllowedChars}. 685 * 686 * @param locales 687 * A Set of ULocales, from which the language and associated script are extracted. If the locales Set 688 * is null, no restrictions will be placed on the allowed characters. 689 * 690 * @return self 691 * @stable ICU 4.6 692 */ setAllowedLocales(Set<ULocale> locales)693 public Builder setAllowedLocales(Set<ULocale> locales) { 694 fAllowedCharsSet.clear(); 695 696 for (ULocale locale : locales) { 697 // Add the script chars for this locale to the accumulating set 698 // of allowed chars. 699 addScriptChars(locale, fAllowedCharsSet); 700 } 701 702 // If our caller provided an empty list of locales, we disable the 703 // allowed characters checking 704 fAllowedLocales.clear(); 705 if (locales.size() == 0) { 706 fAllowedCharsSet.add(0, 0x10ffff); 707 fChecks &= ~CHAR_LIMIT; 708 return this; 709 } 710 711 // Add all common and inherited characters to the set of allowed 712 // chars. 713 UnicodeSet tempSet = new UnicodeSet(); 714 tempSet.applyIntPropertyValue(UProperty.SCRIPT, UScript.COMMON); 715 fAllowedCharsSet.addAll(tempSet); 716 tempSet.applyIntPropertyValue(UProperty.SCRIPT, UScript.INHERITED); 717 fAllowedCharsSet.addAll(tempSet); 718 719 // Store the updated spoof checker state. 720 fAllowedLocales.clear(); 721 fAllowedLocales.addAll(locales); 722 fChecks |= CHAR_LIMIT; 723 return this; 724 } 725 726 /** 727 * Limit characters that are acceptable in identifiers being checked to those normally used with the languages 728 * associated with the specified locales. Any previously specified list of locales is replaced by the new 729 * settings. 730 * 731 * @param locales 732 * A Set of Locales, from which the language and associated script are extracted. If the locales Set 733 * is null, no restrictions will be placed on the allowed characters. 734 * 735 * @return self 736 * @stable ICU 54 737 */ setAllowedJavaLocales(Set<Locale> locales)738 public Builder setAllowedJavaLocales(Set<Locale> locales) { 739 HashSet<ULocale> ulocales = new HashSet<>(locales.size()); 740 for (Locale locale : locales) { 741 ulocales.add(ULocale.forLocale(locale)); 742 } 743 return setAllowedLocales(ulocales); 744 } 745 746 // Add (union) to the UnicodeSet all of the characters for the scripts 747 // used for the specified locale. Part of the implementation of 748 // setAllowedLocales. addScriptChars(ULocale locale, UnicodeSet allowedChars)749 private void addScriptChars(ULocale locale, UnicodeSet allowedChars) { 750 int scripts[] = UScript.getCode(locale); 751 if (scripts != null) { 752 UnicodeSet tmpSet = new UnicodeSet(); 753 for (int i = 0; i < scripts.length; i++) { 754 tmpSet.applyIntPropertyValue(UProperty.SCRIPT, scripts[i]); 755 allowedChars.addAll(tmpSet); 756 } 757 } 758 // else it's an unknown script. 759 // Maybe they asked for the script of "zxx", which refers to no linguistic content. 760 // Maybe they asked for the script of a newer locale that we don't know in the older version of ICU. 761 } 762 763 /** 764 * Limit the acceptable characters to those specified by a Unicode Set. Any previously specified character limit 765 * is is replaced by the new settings. This includes limits on characters that were set with the 766 * setAllowedLocales() function. Note that the RESTRICTED set is useful. 767 * 768 * The {@link #CHAR_LIMIT} test is automatically enabled for this SpoofChecker by this function. 769 * 770 * @param chars 771 * A Unicode Set containing the list of characters that are permitted. The incoming set is cloned by 772 * this function, so there are no restrictions on modifying or deleting the UnicodeSet after calling 773 * this function. Note that this clears the allowedLocales set. 774 * @return self 775 * @stable ICU 4.6 776 */ setAllowedChars(UnicodeSet chars)777 public Builder setAllowedChars(UnicodeSet chars) { 778 fAllowedCharsSet.set(chars); 779 fAllowedLocales.clear(); 780 fChecks |= CHAR_LIMIT; 781 return this; 782 } 783 784 /** 785 * Set the loosest restriction level allowed for strings. The default if this is not called is 786 * {@link RestrictionLevel#HIGHLY_RESTRICTIVE}. Calling this method enables the {@link #RESTRICTION_LEVEL} and 787 * {@link #MIXED_NUMBERS} checks, corresponding to Sections 5.1 and 5.2 of UTS 39. To customize which checks are 788 * to be performed by {@link SpoofChecker#failsChecks}, see {@link #setChecks}. 789 * 790 * @param restrictionLevel 791 * The loosest restriction level allowed. 792 * @return self 793 * @stable ICU 58 794 */ setRestrictionLevel(RestrictionLevel restrictionLevel)795 public Builder setRestrictionLevel(RestrictionLevel restrictionLevel) { 796 fRestrictionLevel = restrictionLevel; 797 fChecks |= RESTRICTION_LEVEL | MIXED_NUMBERS; 798 return this; 799 } 800 801 /* 802 * ***************************************************************************** 803 * Internal classes for compiling confusable data into its binary (runtime) form. 804 * ***************************************************************************** 805 */ 806 // --------------------------------------------------------------------- 807 // 808 // buildConfusableData Compile the source confusable data, as defined by 809 // the Unicode data file confusables.txt, into the binary 810 // structures used by the confusable detector. 811 // 812 // The binary structures are described in uspoof_impl.h 813 // 814 // 1. parse the data, making a hash table mapping from a codepoint to a String. 815 // 816 // 2. Sort all of the strings encountered by length, since they will need to 817 // be stored in that order in the final string table. 818 // TODO: Sorting these strings by length is no longer needed since the removal of 819 // the string lengths table. This logic can be removed to save processing time 820 // when building confusables data. 821 // 822 // 3. Build a list of keys (UChar32s) from the mapping table. Sort the 823 // list because that will be the ordering of our runtime table. 824 // 825 // 4. Generate the run time string table. This is generated before the key & value 826 // table because we need the string indexes when building those tables. 827 // 828 // 5. Build the run-time key and value table. These are parallel tables, and 829 // are built at the same time 830 831 // class ConfusabledataBuilder 832 // An instance of this class exists while the confusable data is being built from source. 833 // It encapsulates the intermediate data structures that are used for building. 834 // It exports one static function, to do a confusable data build. 835 private static class ConfusabledataBuilder { 836 837 private Hashtable<Integer, SPUString> fTable; 838 private UnicodeSet fKeySet; // A set of all keys (UChar32s) that go into the 839 // four mapping tables. 840 841 // The compiled data is first assembled into the following four collections, 842 // then output to the builder's SpoofData object. 843 private StringBuffer fStringTable; 844 private ArrayList<Integer> fKeyVec; 845 private ArrayList<Integer> fValueVec; 846 private SPUStringPool stringPool; 847 private Pattern fParseLine; 848 private Pattern fParseHexNum; 849 private int fLineNum; 850 ConfusabledataBuilder()851 ConfusabledataBuilder() { 852 fTable = new Hashtable<>(); 853 fKeySet = new UnicodeSet(); 854 fKeyVec = new ArrayList<>(); 855 fValueVec = new ArrayList<>(); 856 stringPool = new SPUStringPool(); 857 } 858 build(Reader confusables, SpoofData dest)859 void build(Reader confusables, SpoofData dest) throws ParseException, java.io.IOException { 860 StringBuffer fInput = new StringBuffer(); 861 862 // Convert the user input data from UTF-8 to char (UTF-16) 863 LineNumberReader lnr = new LineNumberReader(confusables); 864 do { 865 String line = lnr.readLine(); 866 if (line == null) { 867 break; 868 } 869 fInput.append(line); 870 fInput.append('\n'); 871 } while (true); 872 873 // Regular Expression to parse a line from Confusables.txt. The expression will match 874 // any line. What was matched is determined by examining which capture groups have a match. 875 // Capture Group 1: the source char 876 // Capture Group 2: the replacement chars 877 // Capture Group 3-6 the table type, SL, SA, ML, or MA (deprecated) 878 // Capture Group 7: A blank or comment only line. 879 // Capture Group 8: A syntactically invalid line. Anything that didn't match before. 880 // Example Line from the confusables.txt source file: 881 // "1D702 ; 006E 0329 ; SL # MATHEMATICAL ITALIC SMALL ETA ... " 882 fParseLine = Pattern.compile("(?m)^[ \\t]*([0-9A-Fa-f]+)[ \\t]+;" + // Match the source char 883 "[ \\t]*([0-9A-Fa-f]+" + // Match the replacement char(s) 884 "(?:[ \\t]+[0-9A-Fa-f]+)*)[ \\t]*;" + // (continued) 885 "\\s*(?:(SL)|(SA)|(ML)|(MA))" + // Match the table type 886 "[ \\t]*(?:#.*?)?$" + // Match any trailing #comment 887 "|^([ \\t]*(?:#.*?)?)$" + // OR match empty lines or lines with only a #comment 888 "|^(.*?)$"); // OR match any line, which catches illegal lines. 889 890 // Regular expression for parsing a hex number out of a space-separated list of them. 891 // Capture group 1 gets the number, with spaces removed. 892 fParseHexNum = Pattern.compile("\\s*([0-9A-F]+)"); 893 894 // Zap any Byte Order Mark at the start of input. Changing it to a space 895 // is benign given the syntax of the input. 896 if (fInput.charAt(0) == 0xfeff) { 897 fInput.setCharAt(0, (char) 0x20); 898 } 899 900 // Parse the input, one line per iteration of this loop. 901 Matcher matcher = fParseLine.matcher(fInput); 902 while (matcher.find()) { 903 fLineNum++; 904 if (matcher.start(7) >= 0) { 905 // this was a blank or comment line. 906 continue; 907 } 908 if (matcher.start(8) >= 0) { 909 // input file syntax error. 910 // status = U_PARSE_ERROR; 911 throw new ParseException( 912 "Confusables, line " + fLineNum + ": Unrecognized Line: " + matcher.group(8), 913 matcher.start(8)); 914 } 915 916 // We have a good input line. Extract the key character and mapping 917 // string, and 918 // put them into the appropriate mapping table. 919 int keyChar = Integer.parseInt(matcher.group(1), 16); 920 if (keyChar > 0x10ffff) { 921 throw new ParseException( 922 "Confusables, line " + fLineNum + ": Bad code point: " + matcher.group(1), 923 matcher.start(1)); 924 } 925 Matcher m = fParseHexNum.matcher(matcher.group(2)); 926 927 StringBuilder mapString = new StringBuilder(); 928 while (m.find()) { 929 int c = Integer.parseInt(m.group(1), 16); 930 if (c > 0x10ffff) { 931 throw new ParseException( 932 "Confusables, line " + fLineNum + ": Bad code point: " + Integer.toString(c, 16), 933 matcher.start(2)); 934 } 935 mapString.appendCodePoint(c); 936 } 937 assert (mapString.length() >= 1); 938 939 // Put the map (value) string into the string pool 940 // This a little like a Java intern() - any duplicates will be 941 // eliminated. 942 SPUString smapString = stringPool.addString(mapString.toString()); 943 944 // Add the char . string mapping to the table. 945 // For Unicode 8, the SL, SA and ML tables have been discontinued. 946 // All input data from confusables.txt is tagged MA. 947 fTable.put(keyChar, smapString); 948 949 fKeySet.add(keyChar); 950 } 951 952 // Input data is now all parsed and collected. 953 // Now create the run-time binary form of the data. 954 // 955 // This is done in two steps. First the data is assembled into vectors and strings, 956 // for ease of construction, then the contents of these collections are copied 957 // into the actual SpoofData object. 958 959 // Build up the string array, and record the index of each string therein 960 // in the (build time only) string pool. 961 // Strings of length one are not entered into the strings array. 962 // (Strings in the table are sorted by length) 963 964 stringPool.sort(); 965 fStringTable = new StringBuffer(); 966 int poolSize = stringPool.size(); 967 int i; 968 for (i = 0; i < poolSize; i++) { 969 SPUString s = stringPool.getByIndex(i); 970 int strLen = s.fStr.length(); 971 int strIndex = fStringTable.length(); 972 if (strLen == 1) { 973 // strings of length one do not get an entry in the string table. 974 // Keep the single string character itself here, which is the same 975 // convention that is used in the final run-time string table index. 976 s.fCharOrStrTableIndex = s.fStr.charAt(0); 977 } else { 978 s.fCharOrStrTableIndex = strIndex; 979 fStringTable.append(s.fStr); 980 } 981 } 982 983 // Construct the compile-time Key and Value table. 984 // 985 // The keys in the Key table follow the format described in uspoof.h for the 986 // Cfu confusables data structure. 987 // 988 // Starting in ICU 58, each code point has exactly one entry in the data 989 // structure. 990 991 for (String keyCharStr : fKeySet) { 992 int keyChar = keyCharStr.codePointAt(0); 993 SPUString targetMapping = fTable.get(keyChar); 994 assert targetMapping != null; 995 996 // Throw a sane exception if trying to consume a long string. Otherwise, 997 // codePointAndLengthToKey will throw an assertion error. 998 if (targetMapping.fStr.length() > 256) { 999 throw new IllegalArgumentException("Confusable prototypes cannot be longer than 256 entries."); 1000 } 1001 1002 int key = ConfusableDataUtils.codePointAndLengthToKey(keyChar, targetMapping.fStr.length()); 1003 int value = targetMapping.fCharOrStrTableIndex; 1004 1005 fKeyVec.add(key); 1006 fValueVec.add(value); 1007 } 1008 1009 // Put the assembled data into the destination SpoofData object. 1010 1011 // The Key Table 1012 // While copying the keys to the output array, 1013 // also sanity check that the keys are sorted. 1014 int numKeys = fKeyVec.size(); 1015 dest.fCFUKeys = new int[numKeys]; 1016 int previousCodePoint = 0; 1017 for (i = 0; i < numKeys; i++) { 1018 int key = fKeyVec.get(i); 1019 int codePoint = ConfusableDataUtils.keyToCodePoint(key); 1020 // strictly greater because there can be only one entry per code point 1021 assert codePoint > previousCodePoint; 1022 dest.fCFUKeys[i] = key; 1023 previousCodePoint = codePoint; 1024 } 1025 1026 // The Value Table, parallels the key table 1027 int numValues = fValueVec.size(); 1028 assert (numKeys == numValues); 1029 dest.fCFUValues = new short[numValues]; 1030 i = 0; 1031 for (int value : fValueVec) { 1032 assert (value < 0xffff); 1033 dest.fCFUValues[i++] = (short) value; 1034 } 1035 1036 // The Strings Table. 1037 dest.fCFUStrings = fStringTable.toString(); 1038 } 1039 1040 public static void buildConfusableData(Reader confusables, SpoofData dest) 1041 throws java.io.IOException, ParseException { 1042 ConfusabledataBuilder builder = new ConfusabledataBuilder(); 1043 builder.build(confusables, dest); 1044 } 1045 1046 /* 1047 * ***************************************************************************** 1048 * Internal classes for compiling confusable data into its binary (runtime) form. 1049 * ***************************************************************************** 1050 */ 1051 // SPUString 1052 // Holds a string that is the result of one of the mappings defined 1053 // by the confusable mapping data (confusables.txt from Unicode.org) 1054 // Instances of SPUString exist during the compilation process only. 1055 1056 private static class SPUString { 1057 String fStr; // The actual string. 1058 int fCharOrStrTableIndex; // Index into the final runtime data for this string. 1059 // (or, for length 1, the single string char itself, 1060 // there being no string table entry for it.) 1061 1062 SPUString(String s) { 1063 fStr = s; 1064 fCharOrStrTableIndex = 0; 1065 } 1066 } 1067 1068 // Comparison function for ordering strings in the string pool. 1069 // Compare by length first, then, within a group of the same length, 1070 // by code point order. 1071 1072 private static class SPUStringComparator implements Comparator<SPUString> { 1073 @Override 1074 public int compare(SPUString sL, SPUString sR) { 1075 int lenL = sL.fStr.length(); 1076 int lenR = sR.fStr.length(); 1077 if (lenL < lenR) { 1078 return -1; 1079 } else if (lenL > lenR) { 1080 return 1; 1081 } else { 1082 return sL.fStr.compareTo(sR.fStr); 1083 } 1084 } 1085 1086 final static SPUStringComparator INSTANCE = new SPUStringComparator(); 1087 } 1088 1089 // String Pool A utility class for holding the strings that are the result of 1090 // the spoof mappings. These strings will utimately end up in the 1091 // run-time String Table. 1092 // This is sort of like a sorted set of strings, except that ICU's anemic 1093 // built-in collections don't support those, so it is implemented with a 1094 // combination of a uhash and a Vector. 1095 private static class SPUStringPool { 1096 public SPUStringPool() { 1097 fVec = new Vector<>(); 1098 fHash = new Hashtable<>(); 1099 } 1100 1101 public int size() { 1102 return fVec.size(); 1103 } 1104 1105 // Get the n-th string in the collection. 1106 public SPUString getByIndex(int index) { 1107 SPUString retString = fVec.elementAt(index); 1108 return retString; 1109 } 1110 1111 // Add a string. Return the string from the table. 1112 // If the input parameter string is already in the table, delete the 1113 // input parameter and return the existing string. 1114 public SPUString addString(String src) { 1115 SPUString hashedString = fHash.get(src); 1116 if (hashedString == null) { 1117 hashedString = new SPUString(src); 1118 fHash.put(src, hashedString); 1119 fVec.addElement(hashedString); 1120 } 1121 return hashedString; 1122 } 1123 1124 // Sort the contents; affects the ordering of getByIndex(). 1125 public void sort() { 1126 Collections.sort(fVec, SPUStringComparator.INSTANCE); 1127 } 1128 1129 private Vector<SPUString> fVec; // Elements are SPUString * 1130 private Hashtable<String, SPUString> fHash; // Key: Value: 1131 } 1132 1133 } 1134 } 1135 1136 /** 1137 * Get the Restriction Level that is being tested. 1138 * 1139 * @return The restriction level 1140 * @internal 1141 * @deprecated This API is ICU internal only. 1142 */ 1143 @Deprecated 1144 public RestrictionLevel getRestrictionLevel() { 1145 return fRestrictionLevel; 1146 } 1147 1148 /** 1149 * Get the set of checks that this Spoof Checker has been configured to perform. 1150 * 1151 * @return The set of checks that this spoof checker will perform. 1152 * @stable ICU 4.6 1153 */ 1154 public int getChecks() { 1155 return fChecks; 1156 } 1157 1158 /** 1159 * Get a read-only set of locales for the scripts that are acceptable in strings to be checked. If no limitations on 1160 * scripts have been specified, an empty set will be returned. 1161 * 1162 * setAllowedChars() will reset the list of allowed locales to be empty. 1163 * 1164 * The returned set may not be identical to the originally specified set that is supplied to setAllowedLocales(); 1165 * the information other than languages from the originally specified locales may be omitted. 1166 * 1167 * @return A set of locales corresponding to the acceptable scripts. 1168 * 1169 * @stable ICU 4.6 1170 */ 1171 public Set<ULocale> getAllowedLocales() { 1172 return Collections.unmodifiableSet(fAllowedLocales); 1173 } 1174 1175 /** 1176 * Get a set of {@link java.util.Locale} instances for the scripts that are acceptable in strings to be checked. If 1177 * no limitations on scripts have been specified, an empty set will be returned. 1178 * 1179 * @return A set of locales corresponding to the acceptable scripts. 1180 * @stable ICU 54 1181 */ 1182 public Set<Locale> getAllowedJavaLocales() { 1183 HashSet<Locale> locales = new HashSet<>(fAllowedLocales.size()); 1184 for (ULocale uloc : fAllowedLocales) { 1185 locales.add(uloc.toLocale()); 1186 } 1187 return locales; 1188 } 1189 1190 /** 1191 * Get a UnicodeSet for the characters permitted in an identifier. This corresponds to the limits imposed by the Set 1192 * Allowed Characters functions. Limitations imposed by other checks will not be reflected in the set returned by 1193 * this function. 1194 * 1195 * The returned set will be frozen, meaning that it cannot be modified by the caller. 1196 * 1197 * @return A UnicodeSet containing the characters that are permitted by the CHAR_LIMIT test. 1198 * @stable ICU 4.6 1199 */ 1200 public UnicodeSet getAllowedChars() { 1201 return fAllowedCharsSet; 1202 } 1203 1204 /** 1205 * A struct-like class to hold the results of a Spoof Check operation. Tells which check(s) have failed. 1206 * 1207 * @stable ICU 4.6 1208 */ 1209 public static class CheckResult { 1210 /** 1211 * Indicates which of the spoof check(s) have failed. The value is a bitwise OR of the constants for the tests 1212 * in question: RESTRICTION_LEVEL, CHAR_LIMIT, and so on. 1213 * 1214 * @stable ICU 4.6 1215 * @see Builder#setChecks 1216 */ 1217 public int checks; 1218 1219 /** 1220 * The index of the first string position that failed a check. 1221 * 1222 * @deprecated ICU 51. No longer supported. Always set to zero. 1223 */ 1224 @Deprecated 1225 public int position; 1226 1227 /** 1228 * The numerics found in the string, if MIXED_NUMBERS was set; otherwise null. The set will contain the zero 1229 * digit from each decimal number system found in the input string. 1230 * 1231 * @stable ICU 58 1232 */ 1233 public UnicodeSet numerics; 1234 1235 /** 1236 * The restriction level that the text meets, if RESTRICTION_LEVEL is set; otherwise null. 1237 * 1238 * @stable ICU 58 1239 */ 1240 public RestrictionLevel restrictionLevel; 1241 1242 /** 1243 * Default constructor 1244 * 1245 * @stable ICU 4.6 1246 */ 1247 public CheckResult() { 1248 checks = 0; 1249 position = 0; 1250 } 1251 1252 /** 1253 * {@inheritDoc} 1254 * 1255 * @stable ICU 4.6 1256 */ 1257 @Override 1258 public String toString() { 1259 StringBuilder sb = new StringBuilder(); 1260 sb.append("checks:"); 1261 if (checks == 0) { 1262 sb.append(" none"); 1263 } else if (checks == ALL_CHECKS) { 1264 sb.append(" all"); 1265 } else { 1266 if ((checks & SINGLE_SCRIPT_CONFUSABLE) != 0) { 1267 sb.append(" SINGLE_SCRIPT_CONFUSABLE"); 1268 } 1269 if ((checks & MIXED_SCRIPT_CONFUSABLE) != 0) { 1270 sb.append(" MIXED_SCRIPT_CONFUSABLE"); 1271 } 1272 if ((checks & WHOLE_SCRIPT_CONFUSABLE) != 0) { 1273 sb.append(" WHOLE_SCRIPT_CONFUSABLE"); 1274 } 1275 if ((checks & ANY_CASE) != 0) { 1276 sb.append(" ANY_CASE"); 1277 } 1278 if ((checks & RESTRICTION_LEVEL) != 0) { 1279 sb.append(" RESTRICTION_LEVEL"); 1280 } 1281 if ((checks & INVISIBLE) != 0) { 1282 sb.append(" INVISIBLE"); 1283 } 1284 if ((checks & CHAR_LIMIT) != 0) { 1285 sb.append(" CHAR_LIMIT"); 1286 } 1287 if ((checks & MIXED_NUMBERS) != 0) { 1288 sb.append(" MIXED_NUMBERS"); 1289 } 1290 } 1291 sb.append(", numerics: ").append(numerics.toPattern(false)); 1292 sb.append(", position: ").append(position); 1293 sb.append(", restrictionLevel: ").append(restrictionLevel); 1294 return sb.toString(); 1295 } 1296 } 1297 1298 /** 1299 * Check the specified string for possible security issues. The text to be checked will typically be an identifier 1300 * of some sort. The set of checks to be performed was specified when building the SpoofChecker. 1301 * 1302 * @param text 1303 * A String to be checked for possible security issues. 1304 * @param checkResult 1305 * Output parameter, indicates which specific tests failed. May be null if the information is not wanted. 1306 * @return True there any issue is found with the input string. 1307 * @stable ICU 4.8 1308 */ 1309 public boolean failsChecks(String text, CheckResult checkResult) { 1310 int length = text.length(); 1311 1312 int result = 0; 1313 if (checkResult != null) { 1314 checkResult.position = 0; 1315 checkResult.numerics = null; 1316 checkResult.restrictionLevel = null; 1317 } 1318 1319 if (0 != (this.fChecks & RESTRICTION_LEVEL)) { 1320 RestrictionLevel textRestrictionLevel = getRestrictionLevel(text); 1321 if (textRestrictionLevel.compareTo(fRestrictionLevel) > 0) { 1322 result |= RESTRICTION_LEVEL; 1323 } 1324 if (checkResult != null) { 1325 checkResult.restrictionLevel = textRestrictionLevel; 1326 } 1327 } 1328 1329 if (0 != (this.fChecks & MIXED_NUMBERS)) { 1330 UnicodeSet numerics = new UnicodeSet(); 1331 getNumerics(text, numerics); 1332 if (numerics.size() > 1) { 1333 result |= MIXED_NUMBERS; 1334 } 1335 if (checkResult != null) { 1336 checkResult.numerics = numerics; 1337 } 1338 } 1339 1340 if (0 != (this.fChecks & HIDDEN_OVERLAY)) { 1341 int index = findHiddenOverlay(text); 1342 if (index != -1) { 1343 result |= HIDDEN_OVERLAY; 1344 } 1345 } 1346 1347 if (0 != (this.fChecks & CHAR_LIMIT)) { 1348 int i; 1349 int c; 1350 for (i = 0; i < length;) { 1351 // U16_NEXT(text, i, length, c); 1352 c = Character.codePointAt(text, i); 1353 i = Character.offsetByCodePoints(text, i, 1); 1354 if (!this.fAllowedCharsSet.contains(c)) { 1355 result |= CHAR_LIMIT; 1356 break; 1357 } 1358 } 1359 } 1360 1361 if (0 != (this.fChecks & INVISIBLE)) { 1362 // This check needs to be done on NFD input 1363 String nfdText = nfdNormalizer.normalize(text); 1364 1365 // scan for more than one occurrence of the same non-spacing mark 1366 // in a sequence of non-spacing marks. 1367 int i; 1368 int c; 1369 int firstNonspacingMark = 0; 1370 boolean haveMultipleMarks = false; 1371 UnicodeSet marksSeenSoFar = new UnicodeSet(); // Set of combining marks in a 1372 // single combining sequence. 1373 for (i = 0; i < length;) { 1374 c = Character.codePointAt(nfdText, i); 1375 i = Character.offsetByCodePoints(nfdText, i, 1); 1376 if (Character.getType(c) != UCharacterCategory.NON_SPACING_MARK) { 1377 firstNonspacingMark = 0; 1378 if (haveMultipleMarks) { 1379 marksSeenSoFar.clear(); 1380 haveMultipleMarks = false; 1381 } 1382 continue; 1383 } 1384 if (firstNonspacingMark == 0) { 1385 firstNonspacingMark = c; 1386 continue; 1387 } 1388 if (!haveMultipleMarks) { 1389 marksSeenSoFar.add(firstNonspacingMark); 1390 haveMultipleMarks = true; 1391 } 1392 if (marksSeenSoFar.contains(c)) { 1393 // report the error, and stop scanning. 1394 // No need to find more than the first failure. 1395 result |= INVISIBLE; 1396 break; 1397 } 1398 marksSeenSoFar.add(c); 1399 } 1400 } 1401 if (checkResult != null) { 1402 checkResult.checks = result; 1403 } 1404 return (0 != result); 1405 } 1406 1407 /** 1408 * Check the specified string for possible security issues. The text to be checked will typically be an identifier 1409 * of some sort. The set of checks to be performed was specified when building the SpoofChecker. 1410 * 1411 * @param text 1412 * A String to be checked for possible security issues. 1413 * @return True there any issue is found with the input string. 1414 * @stable ICU 4.8 1415 */ failsChecks(String text)1416 public boolean failsChecks(String text) { 1417 return failsChecks(text, null); 1418 } 1419 1420 /** 1421 * Check the whether two specified strings are visually confusable. The types of confusability to be tested - single 1422 * script, mixed script, or whole script - are determined by the check options set for the SpoofChecker. 1423 * 1424 * The tests to be performed are controlled by the flags SINGLE_SCRIPT_CONFUSABLE MIXED_SCRIPT_CONFUSABLE 1425 * WHOLE_SCRIPT_CONFUSABLE At least one of these tests must be selected. 1426 * 1427 * ANY_CASE is a modifier for the tests. Select it if the identifiers may be of mixed case. If identifiers are case 1428 * folded for comparison and display to the user, do not select the ANY_CASE option. 1429 * 1430 * 1431 * @param s1 1432 * The first of the two strings to be compared for confusability. 1433 * @param s2 1434 * The second of the two strings to be compared for confusability. 1435 * @return Non-zero if s1 and s1 are confusable. If not 0, the value will indicate the type(s) of confusability 1436 * found, as defined by spoof check test constants. 1437 * @stable ICU 4.6 1438 */ areConfusable(String s1, String s2)1439 public int areConfusable(String s1, String s2) { 1440 // 1441 // See section 4 of UAX 39 for the algorithm for checking whether two strings are confusable, 1442 // and for definitions of the types (single, whole, mixed-script) of confusables. 1443 1444 // We only care about a few of the check flags. Ignore the others. 1445 // If no tests relevant to this function have been specified, signal an error. 1446 // TODO: is this really the right thing to do? It's probably an error on 1447 // the caller's part, but logically we would just return 0 (no error). 1448 if ((this.fChecks & CONFUSABLE) == 0) { 1449 throw new IllegalArgumentException("No confusable checks are enabled."); 1450 } 1451 1452 // Compute the skeletons and check for confusability. 1453 String s1Skeleton = getSkeleton(s1); 1454 String s2Skeleton = getSkeleton(s2); 1455 if (!s1Skeleton.equals(s2Skeleton)) { 1456 return 0; 1457 } 1458 1459 // If we get here, the strings are confusable. Now we just need to set the flags for the appropriate classes 1460 // of confusables according to UTS 39 section 4. 1461 // Start by computing the resolved script sets of s1 and s2. 1462 ScriptSet s1RSS = new ScriptSet(); 1463 getResolvedScriptSet(s1, s1RSS); 1464 ScriptSet s2RSS = new ScriptSet(); 1465 getResolvedScriptSet(s2, s2RSS); 1466 1467 // Turn on all applicable flags 1468 int result = 0; 1469 if (s1RSS.intersects(s2RSS)) { 1470 result |= SINGLE_SCRIPT_CONFUSABLE; 1471 } else { 1472 result |= MIXED_SCRIPT_CONFUSABLE; 1473 if (!s1RSS.isEmpty() && !s2RSS.isEmpty()) { 1474 result |= WHOLE_SCRIPT_CONFUSABLE; 1475 } 1476 } 1477 1478 // Turn off flags that the user doesn't want 1479 result &= fChecks; 1480 1481 return result; 1482 } 1483 1484 /** 1485 * Get the "skeleton" for an identifier string. Skeletons are a transformation of the input string; Two strings are 1486 * confusable if their skeletons are identical. See Unicode UAX 39 for additional information. 1487 * 1488 * Using skeletons directly makes it possible to quickly check whether an identifier is confusable with any of some 1489 * large set of existing identifiers, by creating an efficiently searchable collection of the skeletons. 1490 * 1491 * Skeletons are computed using the algorithm and data described in Unicode UAX 39. 1492 * 1493 * @param str 1494 * The input string whose skeleton will be generated. 1495 * @return The output skeleton string. 1496 * 1497 * @stable ICU 58 1498 */ getSkeleton(CharSequence str)1499 public String getSkeleton(CharSequence str) { 1500 // Apply the skeleton mapping to the NFD normalized input string 1501 // Accumulate the skeleton, possibly unnormalized, in a String. 1502 String nfdId = nfdNormalizer.normalize(str); 1503 int normalizedLen = nfdId.length(); 1504 StringBuilder skelSB = new StringBuilder(); 1505 for (int inputIndex = 0; inputIndex < normalizedLen;) { 1506 int c = Character.codePointAt(nfdId, inputIndex); 1507 inputIndex += Character.charCount(c); 1508 this.fSpoofData.confusableLookup(c, skelSB); 1509 } 1510 String skelStr = skelSB.toString(); 1511 skelStr = nfdNormalizer.normalize(skelStr); 1512 return skelStr; 1513 } 1514 1515 /** 1516 * Calls {@link SpoofChecker#getSkeleton(CharSequence id)}. Starting with ICU 55, the "type" parameter has been 1517 * ignored, and starting with ICU 58, this function has been deprecated. 1518 * 1519 * @param type 1520 * No longer supported. Prior to ICU 55, was used to specify the mapping table SL, SA, ML, or MA. 1521 * @param id 1522 * The input identifier whose skeleton will be generated. 1523 * @return The output skeleton string. 1524 * 1525 * @deprecated ICU 58 1526 */ 1527 @Deprecated getSkeleton(int type, String id)1528 public String getSkeleton(int type, String id) { 1529 return getSkeleton(id); 1530 } 1531 1532 /** 1533 * Equality function. Return true if the two SpoofChecker objects incorporate the same confusable data and have 1534 * enabled the same set of checks. 1535 * 1536 * @param other 1537 * the SpoofChecker being compared with. 1538 * @return true if the two SpoofCheckers are equal. 1539 * @stable ICU 4.6 1540 */ 1541 @Override equals(Object other)1542 public boolean equals(Object other) { 1543 if (!(other instanceof SpoofChecker)) { 1544 return false; 1545 } 1546 SpoofChecker otherSC = (SpoofChecker) other; 1547 if (fSpoofData != otherSC.fSpoofData && fSpoofData != null && !fSpoofData.equals(otherSC.fSpoofData)) { 1548 return false; 1549 } 1550 if (fChecks != otherSC.fChecks) { 1551 return false; 1552 } 1553 if (fAllowedLocales != otherSC.fAllowedLocales && fAllowedLocales != null 1554 && !fAllowedLocales.equals(otherSC.fAllowedLocales)) { 1555 return false; 1556 } 1557 if (fAllowedCharsSet != otherSC.fAllowedCharsSet && fAllowedCharsSet != null 1558 && !fAllowedCharsSet.equals(otherSC.fAllowedCharsSet)) { 1559 return false; 1560 } 1561 if (fRestrictionLevel != otherSC.fRestrictionLevel) { 1562 return false; 1563 } 1564 return true; 1565 } 1566 1567 /** 1568 * Overrides {@link Object#hashCode()}. 1569 * @stable ICU 4.6 1570 */ 1571 @Override hashCode()1572 public int hashCode() { 1573 return fChecks 1574 ^ fSpoofData.hashCode() 1575 ^ fAllowedLocales.hashCode() 1576 ^ fAllowedCharsSet.hashCode() 1577 ^ fRestrictionLevel.ordinal(); 1578 } 1579 1580 /** 1581 * Computes the augmented script set for a code point, according to UTS 39 section 5.1. 1582 */ getAugmentedScriptSet(int codePoint, ScriptSet result)1583 private static void getAugmentedScriptSet(int codePoint, ScriptSet result) { 1584 result.clear(); 1585 UScript.getScriptExtensions(codePoint, result); 1586 1587 // Section 5.1 step 1 1588 if (result.get(UScript.HAN)) { 1589 result.set(UScript.HAN_WITH_BOPOMOFO); 1590 result.set(UScript.JAPANESE); 1591 result.set(UScript.KOREAN); 1592 } 1593 if (result.get(UScript.HIRAGANA)) { 1594 result.set(UScript.JAPANESE); 1595 } 1596 if (result.get(UScript.KATAKANA)) { 1597 result.set(UScript.JAPANESE); 1598 } 1599 if (result.get(UScript.HANGUL)) { 1600 result.set(UScript.KOREAN); 1601 } 1602 if (result.get(UScript.BOPOMOFO)) { 1603 result.set(UScript.HAN_WITH_BOPOMOFO); 1604 } 1605 1606 // Section 5.1 step 2 1607 if (result.get(UScript.COMMON) || result.get(UScript.INHERITED)) { 1608 result.setAll(); 1609 } 1610 } 1611 1612 /** 1613 * Computes the resolved script set for a string, according to UTS 39 section 5.1. 1614 */ getResolvedScriptSet(CharSequence input, ScriptSet result)1615 private void getResolvedScriptSet(CharSequence input, ScriptSet result) { 1616 getResolvedScriptSetWithout(input, UScript.CODE_LIMIT, result); 1617 } 1618 1619 /** 1620 * Computes the resolved script set for a string, omitting characters having the specified script. If 1621 * UScript.CODE_LIMIT is passed as the second argument, all characters are included. 1622 */ getResolvedScriptSetWithout(CharSequence input, int script, ScriptSet result)1623 private void getResolvedScriptSetWithout(CharSequence input, int script, ScriptSet result) { 1624 result.setAll(); 1625 1626 ScriptSet temp = new ScriptSet(); 1627 for (int utf16Offset = 0; utf16Offset < input.length();) { 1628 int codePoint = Character.codePointAt(input, utf16Offset); 1629 utf16Offset += Character.charCount(codePoint); 1630 1631 // Compute the augmented script set for the character 1632 getAugmentedScriptSet(codePoint, temp); 1633 1634 // Intersect the augmented script set with the resolved script set, but only if the character doesn't 1635 // have the script specified in the function call 1636 if (script == UScript.CODE_LIMIT || !temp.get(script)) { 1637 result.and(temp); 1638 } 1639 } 1640 } 1641 1642 /** 1643 * Computes the set of numerics for a string, according to UTS 39 section 5.3. 1644 */ getNumerics(String input, UnicodeSet result)1645 private void getNumerics(String input, UnicodeSet result) { 1646 result.clear(); 1647 1648 for (int utf16Offset = 0; utf16Offset < input.length();) { 1649 int codePoint = Character.codePointAt(input, utf16Offset); 1650 utf16Offset += Character.charCount(codePoint); 1651 1652 // Store a representative character for each kind of decimal digit 1653 if (UCharacter.getType(codePoint) == UCharacterCategory.DECIMAL_DIGIT_NUMBER) { 1654 // Store the zero character as a representative for comparison. 1655 // Unicode guarantees it is codePoint - value 1656 result.add(codePoint - UCharacter.getNumericValue(codePoint)); 1657 } 1658 } 1659 } 1660 1661 /** 1662 * Computes the restriction level of a string, according to UTS 39 section 5.2. 1663 */ getRestrictionLevel(String input)1664 private RestrictionLevel getRestrictionLevel(String input) { 1665 // Section 5.2 step 1: 1666 if (!fAllowedCharsSet.containsAll(input)) { 1667 return RestrictionLevel.UNRESTRICTIVE; 1668 } 1669 1670 // Section 5.2 step 2: 1671 if (ASCII.containsAll(input)) { 1672 return RestrictionLevel.ASCII; 1673 } 1674 1675 // Section 5.2 steps 3: 1676 ScriptSet resolvedScriptSet = new ScriptSet(); 1677 getResolvedScriptSet(input, resolvedScriptSet); 1678 1679 // Section 5.2 step 4: 1680 if (!resolvedScriptSet.isEmpty()) { 1681 return RestrictionLevel.SINGLE_SCRIPT_RESTRICTIVE; 1682 } 1683 1684 // Section 5.2 step 5: 1685 ScriptSet resolvedNoLatn = new ScriptSet(); 1686 getResolvedScriptSetWithout(input, UScript.LATIN, resolvedNoLatn); 1687 1688 // Section 5.2 step 6: 1689 if (resolvedNoLatn.get(UScript.HAN_WITH_BOPOMOFO) || resolvedNoLatn.get(UScript.JAPANESE) 1690 || resolvedNoLatn.get(UScript.KOREAN)) { 1691 return RestrictionLevel.HIGHLY_RESTRICTIVE; 1692 } 1693 1694 // Section 5.2 step 7: 1695 if (!resolvedNoLatn.isEmpty() && !resolvedNoLatn.get(UScript.CYRILLIC) && !resolvedNoLatn.get(UScript.GREEK) 1696 && !resolvedNoLatn.get(UScript.CHEROKEE)) { 1697 return RestrictionLevel.MODERATELY_RESTRICTIVE; 1698 } 1699 1700 // Section 5.2 step 8: 1701 return RestrictionLevel.MINIMALLY_RESTRICTIVE; 1702 } 1703 findHiddenOverlay(String input)1704 int findHiddenOverlay(String input) { 1705 boolean sawLeadCharacter = false; 1706 StringBuilder sb = new StringBuilder(); 1707 for (int i=0; i<input.length();) { 1708 int cp = input.codePointAt(i); 1709 if (sawLeadCharacter && cp == 0x0307) { 1710 return i; 1711 } 1712 int combiningClass = UCharacter.getCombiningClass(cp); 1713 // Skip over characters except for those with combining class 0 (non-combining characters) or with 1714 // combining class 230 (same class as U+0307) 1715 assert UCharacter.getCombiningClass(0x0307) == 230; 1716 if (combiningClass == 0 || combiningClass == 230) { 1717 sawLeadCharacter = isIllegalCombiningDotLeadCharacter(cp, sb); 1718 } 1719 i += UCharacter.charCount(cp); 1720 } 1721 return -1; 1722 } 1723 isIllegalCombiningDotLeadCharacterNoLookup(int cp)1724 boolean isIllegalCombiningDotLeadCharacterNoLookup(int cp) { 1725 return cp == 'i' || cp == 'j' || cp == 'ı' || cp == 'ȷ' || cp == 'l' || 1726 UCharacter.hasBinaryProperty(cp, UProperty.SOFT_DOTTED); 1727 } 1728 isIllegalCombiningDotLeadCharacter(int cp, StringBuilder sb)1729 boolean isIllegalCombiningDotLeadCharacter(int cp, StringBuilder sb) { 1730 if (isIllegalCombiningDotLeadCharacterNoLookup(cp)) { 1731 return true; 1732 } 1733 sb.setLength(0); 1734 fSpoofData.confusableLookup(cp, sb); 1735 int finalCp = UCharacter.codePointBefore(sb, sb.length()); 1736 if (finalCp != cp && isIllegalCombiningDotLeadCharacterNoLookup(finalCp)) { 1737 return true; 1738 } 1739 return false; 1740 } 1741 1742 // Data Members 1743 private int fChecks; // Bit vector of checks to perform. 1744 private SpoofData fSpoofData; 1745 private Set<ULocale> fAllowedLocales; // The Set of allowed locales. 1746 private UnicodeSet fAllowedCharsSet; // The UnicodeSet of allowed characters. 1747 private RestrictionLevel fRestrictionLevel; 1748 1749 private static Normalizer2 nfdNormalizer = Normalizer2.getNFDInstance(); 1750 1751 // Confusable Mappings Data Structures, version 2.0 1752 // 1753 // This description and the corresponding implementation are to be kept 1754 // in-sync with the copy in icu4c uspoof_impl.h. 1755 // 1756 // For the confusable data, we are essentially implementing a map, 1757 // key: a code point 1758 // value: a string. Most commonly one char in length, but can be more. 1759 // 1760 // The keys are stored as a sorted array of 32 bit ints. 1761 // bits 0-23 a code point value 1762 // bits 24-31 length of value string, in UChars (between 1 and 256 UChars). 1763 // The key table is sorted in ascending code point order. (not on the 1764 // 32 bit int value, the flag bits do not participate in the sorting.) 1765 // 1766 // Lookup is done by means of a binary search in the key table. 1767 // 1768 // The corresponding values are kept in a parallel array of 16 bit ints. 1769 // If the value string is of length 1, it is literally in the value array. 1770 // For longer strings, the value array contains an index into the strings 1771 // table. 1772 // 1773 // String Table: 1774 // The strings table contains all of the value strings (those of length two or greater) 1775 // concatenated together into one long char (UTF-16) array. 1776 // 1777 // There is no nul character or other mark between adjacent strings. 1778 // 1779 //---------------------------------------------------------------------------- 1780 // 1781 // Changes from format version 1 to format version 2: 1782 // 1) Removal of the whole-script confusable data tables. 1783 // 2) Removal of the SL/SA/ML/MA and multi-table flags in the key bitmask. 1784 // 3) Expansion of string length value in the key bitmask from 2 bits to 8 bits. 1785 // 4) Removal of the string lengths table since 8 bits is sufficient for the 1786 // lengths of all entries in confusables.txt. 1787 // 1788 private static final class ConfusableDataUtils { 1789 public static final int FORMAT_VERSION = 2; // version for ICU 58 1790 keyToCodePoint(int key)1791 public static final int keyToCodePoint(int key) { 1792 return key & 0x00ffffff; 1793 } 1794 keyToLength(int key)1795 public static final int keyToLength(int key) { 1796 return ((key & 0xff000000) >> 24) + 1; 1797 } 1798 codePointAndLengthToKey(int codePoint, int length)1799 public static final int codePointAndLengthToKey(int codePoint, int length) { 1800 assert (codePoint & 0x00ffffff) == codePoint; 1801 assert length <= 256; 1802 return codePoint | ((length - 1) << 24); 1803 } 1804 } 1805 1806 // ------------------------------------------------------------------------------------- 1807 // 1808 // SpoofData 1809 // 1810 // This class corresponds to the ICU SpoofCheck data. 1811 // 1812 // The data can originate with the Binary ICU data that is generated in ICU4C, 1813 // or it can originate from source rules that are compiled in ICU4J. 1814 // 1815 // This class does not include the set of checks to be performed, but only 1816 // data that is serialized into the ICU binary data. 1817 // 1818 // Because Java cannot easily wrap binary data like ICU4C, the binary data is 1819 // copied into Java structures that are convenient for use by the run time code. 1820 // 1821 // --------------------------------------------------------------------------------------- 1822 private static class SpoofData { 1823 1824 // The Confusable data, Java data structures for. 1825 int[] fCFUKeys; 1826 short[] fCFUValues; 1827 String fCFUStrings; 1828 1829 private static final int DATA_FORMAT = 0x43667520; // "Cfu " 1830 1831 private static final class IsAcceptable implements Authenticate { 1832 @Override isDataVersionAcceptable(byte version[])1833 public boolean isDataVersionAcceptable(byte version[]) { 1834 return version[0] == ConfusableDataUtils.FORMAT_VERSION || version[1] != 0 || version[2] != 0 1835 || version[3] != 0; 1836 } 1837 } 1838 1839 private static final IsAcceptable IS_ACCEPTABLE = new IsAcceptable(); 1840 1841 private static final class DefaultData { 1842 private static SpoofData INSTANCE = null; 1843 private static IOException EXCEPTION = null; 1844 1845 static { 1846 // Note: Although this is static, the Java runtime can delay execution of this block until 1847 // the data is actually requested via SpoofData.getDefault(). 1848 try { 1849 INSTANCE = new SpoofData(ICUBinary.getRequiredData("confusables.cfu")); 1850 } catch (IOException e) { 1851 EXCEPTION = e; 1852 } 1853 } 1854 } 1855 1856 /** 1857 * @return instance for Unicode standard data 1858 */ getDefault()1859 public static SpoofData getDefault() { 1860 if (DefaultData.EXCEPTION != null) { 1861 throw new MissingResourceException( 1862 "Could not load default confusables data: " + DefaultData.EXCEPTION.getMessage(), 1863 "SpoofChecker", ""); 1864 } 1865 return DefaultData.INSTANCE; 1866 } 1867 1868 // SpoofChecker Data constructor for use from data builder. 1869 // Initializes a new, empty data area that will be populated later. SpoofData()1870 private SpoofData() { 1871 } 1872 1873 // Constructor for use when creating from prebuilt default data. 1874 // A ByteBuffer is what the ICU internal data loading functions provide. SpoofData(ByteBuffer bytes)1875 private SpoofData(ByteBuffer bytes) throws java.io.IOException { 1876 ICUBinary.readHeader(bytes, DATA_FORMAT, IS_ACCEPTABLE); 1877 bytes.mark(); 1878 readData(bytes); 1879 } 1880 1881 @Override equals(Object other)1882 public boolean equals(Object other) { 1883 if (!(other instanceof SpoofData)) { 1884 return false; 1885 } 1886 SpoofData otherData = (SpoofData) other; 1887 if (!Arrays.equals(fCFUKeys, otherData.fCFUKeys)) 1888 return false; 1889 if (!Arrays.equals(fCFUValues, otherData.fCFUValues)) 1890 return false; 1891 if (!Utility.sameObjects(fCFUStrings, otherData.fCFUStrings) && fCFUStrings != null 1892 && !fCFUStrings.equals(otherData.fCFUStrings)) 1893 return false; 1894 return true; 1895 } 1896 1897 @Override hashCode()1898 public int hashCode() { 1899 return Arrays.hashCode(fCFUKeys) 1900 ^ Arrays.hashCode(fCFUValues) 1901 ^ fCFUStrings.hashCode(); 1902 } 1903 1904 // Set the SpoofChecker data from pre-built binary data in a byte buffer. 1905 // The binary data format is as described for ICU4C spoof data. 1906 // readData(ByteBuffer bytes)1907 private void readData(ByteBuffer bytes) throws java.io.IOException { 1908 int magic = bytes.getInt(); 1909 if (magic != 0x3845fdef) { 1910 throw new IllegalArgumentException("Bad Spoof Check Data."); 1911 } 1912 @SuppressWarnings("unused") 1913 int dataFormatVersion = bytes.getInt(); 1914 @SuppressWarnings("unused") 1915 int dataLength = bytes.getInt(); 1916 1917 int CFUKeysOffset = bytes.getInt(); 1918 int CFUKeysSize = bytes.getInt(); 1919 1920 int CFUValuesOffset = bytes.getInt(); 1921 int CFUValuesSize = bytes.getInt(); 1922 1923 int CFUStringTableOffset = bytes.getInt(); 1924 int CFUStringTableSize = bytes.getInt(); 1925 1926 // We have now read the file header, and obtained the position for each 1927 // of the data items. Now read each in turn, first seeking the 1928 // input stream to the position of the data item. 1929 1930 bytes.reset(); 1931 ICUBinary.skipBytes(bytes, CFUKeysOffset); 1932 fCFUKeys = ICUBinary.getInts(bytes, CFUKeysSize, 0); 1933 1934 bytes.reset(); 1935 ICUBinary.skipBytes(bytes, CFUValuesOffset); 1936 fCFUValues = ICUBinary.getShorts(bytes, CFUValuesSize, 0); 1937 1938 bytes.reset(); 1939 ICUBinary.skipBytes(bytes, CFUStringTableOffset); 1940 fCFUStrings = ICUBinary.getString(bytes, CFUStringTableSize, 0); 1941 } 1942 1943 /** 1944 * Append the confusable skeleton transform for a single code point to a StringBuilder. The string to be 1945 * appended will between 1 and 18 characters as of Unicode 9. 1946 * 1947 * This is the heart of the confusable skeleton generation implementation. 1948 */ confusableLookup(int inChar, StringBuilder dest)1949 public void confusableLookup(int inChar, StringBuilder dest) { 1950 // Perform a binary search. 1951 // [lo, hi), i.e lo is inclusive, hi is exclusive. 1952 // The result after the loop will be in lo. 1953 int lo = 0; 1954 int hi = length(); 1955 do { 1956 int mid = (lo + hi) / 2; 1957 if (codePointAt(mid) > inChar) { 1958 hi = mid; 1959 } else if (codePointAt(mid) < inChar) { 1960 lo = mid; 1961 } else { 1962 // Found result. Break early. 1963 lo = mid; 1964 break; 1965 } 1966 } while (hi - lo > 1); 1967 1968 // Did we find an entry? If not, the char maps to itself. 1969 if (codePointAt(lo) != inChar) { 1970 dest.appendCodePoint(inChar); 1971 return; 1972 } 1973 1974 // Add the element to the string builder and return. 1975 appendValueTo(lo, dest); 1976 return; 1977 } 1978 1979 /** 1980 * Return the number of confusable entries in this SpoofData. 1981 * 1982 * @return The number of entries. 1983 */ length()1984 public int length() { 1985 return fCFUKeys.length; 1986 } 1987 1988 /** 1989 * Return the code point (key) at the specified index. 1990 * 1991 * @param index 1992 * The index within the SpoofData. 1993 * @return The code point. 1994 */ codePointAt(int index)1995 public int codePointAt(int index) { 1996 return ConfusableDataUtils.keyToCodePoint(fCFUKeys[index]); 1997 } 1998 1999 /** 2000 * Append the confusable skeleton at the specified index to the StringBuilder dest. 2001 * 2002 * @param index 2003 * The index within the SpoofData. 2004 * @param dest 2005 * The StringBuilder to which to append the skeleton. 2006 */ appendValueTo(int index, StringBuilder dest)2007 public void appendValueTo(int index, StringBuilder dest) { 2008 int stringLength = ConfusableDataUtils.keyToLength(fCFUKeys[index]); 2009 2010 // Value is either a char (for strings of length 1) or 2011 // an index into the string table (for longer strings) 2012 short value = fCFUValues[index]; 2013 if (stringLength == 1) { 2014 dest.append((char) value); 2015 } else { 2016 dest.append(fCFUStrings, value, value + stringLength); 2017 } 2018 } 2019 } 2020 2021 // ------------------------------------------------------------------------------- 2022 // 2023 // ScriptSet - Script code bit sets. 2024 // Extends Java BitSet with input/output support and a few helper methods. 2025 // Note: The I/O is not currently being used, so it has been commented out. If 2026 // it is needed again, the code can be restored. 2027 // 2028 // ------------------------------------------------------------------------------- 2029 static class ScriptSet extends BitSet { 2030 2031 // Eclipse default value to quell warnings: 2032 private static final long serialVersionUID = 1L; 2033 2034 // // The serialized version of this class can hold INT_CAPACITY * 32 scripts. 2035 // private static final int INT_CAPACITY = 6; 2036 // private static final long serialVersionUID = INT_CAPACITY; 2037 // static { 2038 // assert ScriptSet.INT_CAPACITY * Integer.SIZE <= UScript.CODE_LIMIT; 2039 // } 2040 // 2041 // public ScriptSet() { 2042 // } 2043 // 2044 // public ScriptSet(ByteBuffer bytes) throws java.io.IOException { 2045 // for (int i = 0; i < INT_CAPACITY; i++) { 2046 // int bits = bytes.getInt(); 2047 // for (int j = 0; j < Integer.SIZE; j++) { 2048 // if ((bits & (1 << j)) != 0) { 2049 // set(i * Integer.SIZE + j); 2050 // } 2051 // } 2052 // } 2053 // } 2054 // 2055 // public void output(DataOutputStream os) throws java.io.IOException { 2056 // for (int i = 0; i < INT_CAPACITY; i++) { 2057 // int bits = 0; 2058 // for (int j = 0; j < Integer.SIZE; j++) { 2059 // if (get(i * Integer.SIZE + j)) { 2060 // bits |= (1 << j); 2061 // } 2062 // } 2063 // os.writeInt(bits); 2064 // } 2065 // } 2066 and(int script)2067 public void and(int script) { 2068 this.clear(0, script); 2069 this.clear(script + 1, UScript.CODE_LIMIT); 2070 } 2071 setAll()2072 public void setAll() { 2073 this.set(0, UScript.CODE_LIMIT); 2074 } 2075 isFull()2076 public boolean isFull() { 2077 return cardinality() == UScript.CODE_LIMIT; 2078 } 2079 appendStringTo(StringBuilder sb)2080 public void appendStringTo(StringBuilder sb) { 2081 sb.append("{ "); 2082 if (isEmpty()) { 2083 sb.append("- "); 2084 } else if (isFull()) { 2085 sb.append("* "); 2086 } else { 2087 for (int script = 0; script < UScript.CODE_LIMIT; script++) { 2088 if (get(script)) { 2089 sb.append(UScript.getShortName(script)); 2090 sb.append(" "); 2091 } 2092 } 2093 } 2094 sb.append("}"); 2095 } 2096 2097 @Override toString()2098 public String toString() { 2099 StringBuilder sb = new StringBuilder(); 2100 sb.append("<ScriptSet "); 2101 appendStringTo(sb); 2102 sb.append(">"); 2103 return sb.toString(); 2104 } 2105 } 2106 } 2107