uspoof_impl.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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-2013, International Business Machines Corporation
  6. * and others. All Rights Reserved.
  7. ***************************************************************************
  8. *
  9. * uspoof_impl.h
  10. *
  11. * Implemenation header for spoof detection
  12. *
  13. */
  14. #ifndef USPOOFIM_H
  15. #define USPOOFIM_H
  16. #include "uassert.h"
  17. #include "unicode/utypes.h"
  18. #include "unicode/uspoof.h"
  19. #include "unicode/uscript.h"
  20. #include "unicode/udata.h"
  21. #include "udataswp.h"
  22. #include "utrie2.h"
  23. #if !UCONFIG_NO_NORMALIZATION
  24. #ifdef __cplusplus
  25. #include "capi_helper.h"
  26. U_NAMESPACE_BEGIN
  27. // The maximium length (in UTF-16 UChars) of the skeleton replacement string resulting from
  28. // a single input code point. This is function of the unicode.org data.
  29. #define USPOOF_MAX_SKELETON_EXPANSION 20
  30. // The default stack buffer size for copies or conversions or normalizations
  31. // of input strings being checked. (Used in multiple places.)
  32. #define USPOOF_STACK_BUFFER_SIZE 100
  33. // Magic number for sanity checking spoof data.
  34. #define USPOOF_MAGIC 0x3845fdef
  35. // Magic number for sanity checking spoof checkers.
  36. #define USPOOF_CHECK_MAGIC 0x2734ecde
  37. class ScriptSet;
  38. class SpoofData;
  39. struct SpoofDataHeader;
  40. class ConfusableDataUtils;
  41. /**
  42. * Class SpoofImpl corresponds directly to the plain C API opaque type
  43. * USpoofChecker. One can be cast to the other.
  44. */
  45. class SpoofImpl : public UObject,
  46. public IcuCApiHelper<USpoofChecker, SpoofImpl, USPOOF_MAGIC> {
  47. public:
  48. SpoofImpl(SpoofData *data, UErrorCode& status);
  49. SpoofImpl(UErrorCode& status);
  50. SpoofImpl();
  51. void construct(UErrorCode& status);
  52. virtual ~SpoofImpl();
  53. /** Copy constructor, used by the user level uspoof_clone() function.
  54. */
  55. SpoofImpl(const SpoofImpl &src, UErrorCode &status);
  56. USpoofChecker *asUSpoofChecker();
  57. static SpoofImpl *validateThis(USpoofChecker *sc, UErrorCode &status);
  58. static const SpoofImpl *validateThis(const USpoofChecker *sc, UErrorCode &status);
  59. /** Set and Get AllowedLocales, implementations of the corresponding API */
  60. void setAllowedLocales(const char *localesList, UErrorCode &status);
  61. const char * getAllowedLocales(UErrorCode &status);
  62. // Add (union) to the UnicodeSet all of the characters for the scripts used for
  63. // the specified locale. Part of the implementation of setAllowedLocales.
  64. void addScriptChars(const char *locale, UnicodeSet *allowedChars, UErrorCode &status);
  65. // Functions implementing the features of UTS 39 section 5.
  66. static void getAugmentedScriptSet(UChar32 codePoint, ScriptSet& result, UErrorCode& status);
  67. void getResolvedScriptSet(const UnicodeString& input, ScriptSet& result, UErrorCode& status) const;
  68. void getResolvedScriptSetWithout(const UnicodeString& input, UScriptCode script, ScriptSet& result, UErrorCode& status) const;
  69. void getNumerics(const UnicodeString& input, UnicodeSet& result, UErrorCode& status) const;
  70. URestrictionLevel getRestrictionLevel(const UnicodeString& input, UErrorCode& status) const;
  71. int32_t findHiddenOverlay(const UnicodeString& input, UErrorCode& status) const;
  72. bool isIllegalCombiningDotLeadCharacter(UChar32 cp) const;
  73. /** parse a hex number. Untility used by the builders. */
  74. static UChar32 ScanHex(const UChar *s, int32_t start, int32_t limit, UErrorCode &status);
  75. static UClassID U_EXPORT2 getStaticClassID(void);
  76. virtual UClassID getDynamicClassID(void) const;
  77. //
  78. // Data Members
  79. //
  80. int32_t fChecks; // Bit vector of checks to perform.
  81. SpoofData *fSpoofData;
  82. const UnicodeSet *fAllowedCharsSet; // The UnicodeSet of allowed characters.
  83. // for this Spoof Checker. Defaults to all chars.
  84. const char *fAllowedLocales; // The list of allowed locales.
  85. URestrictionLevel fRestrictionLevel; // The maximum restriction level for an acceptable identifier.
  86. };
  87. /**
  88. * Class CheckResult corresponds directly to the plain C API opaque type
  89. * USpoofCheckResult. One can be cast to the other.
  90. */
  91. class CheckResult : public UObject,
  92. public IcuCApiHelper<USpoofCheckResult, CheckResult, USPOOF_CHECK_MAGIC> {
  93. public:
  94. CheckResult();
  95. virtual ~CheckResult();
  96. USpoofCheckResult *asUSpoofCheckResult();
  97. static CheckResult *validateThis(USpoofCheckResult *ptr, UErrorCode &status);
  98. static const CheckResult *validateThis(const USpoofCheckResult *ptr, UErrorCode &status);
  99. void clear();
  100. // Used to convert this CheckResult to the older int32_t return value API
  101. int32_t toCombinedBitmask(int32_t expectedChecks);
  102. // Data Members
  103. int32_t fChecks; // Bit vector of checks that were failed.
  104. UnicodeSet fNumerics; // Set of numerics found in the string.
  105. URestrictionLevel fRestrictionLevel; // The restriction level of the string.
  106. };
  107. //
  108. // Confusable Mappings Data Structures, version 2.0
  109. //
  110. // For the confusable data, we are essentially implementing a map,
  111. // key: a code point
  112. // value: a string. Most commonly one char in length, but can be more.
  113. //
  114. // The keys are stored as a sorted array of 32 bit ints.
  115. // bits 0-23 a code point value
  116. // bits 24-31 length of value string, in UChars (between 1 and 256 UChars).
  117. // The key table is sorted in ascending code point order. (not on the
  118. // 32 bit int value, the flag bits do not participate in the sorting.)
  119. //
  120. // Lookup is done by means of a binary search in the key table.
  121. //
  122. // The corresponding values are kept in a parallel array of 16 bit ints.
  123. // If the value string is of length 1, it is literally in the value array.
  124. // For longer strings, the value array contains an index into the strings table.
  125. //
  126. // String Table:
  127. // The strings table contains all of the value strings (those of length two or greater)
  128. // concatentated together into one long UChar (UTF-16) array.
  129. //
  130. // There is no nul character or other mark between adjacent strings.
  131. //
  132. //----------------------------------------------------------------------------
  133. //
  134. // Changes from format version 1 to format version 2:
  135. // 1) Removal of the whole-script confusable data tables.
  136. // 2) Removal of the SL/SA/ML/MA and multi-table flags in the key bitmask.
  137. // 3) Expansion of string length value in the key bitmask from 2 bits to 8 bits.
  138. // 4) Removal of the string lengths table since 8 bits is sufficient for the
  139. // lengths of all entries in confusables.txt.
  140. // Internal functions for manipulating confusable data table keys
  141. #define USPOOF_CONFUSABLE_DATA_FORMAT_VERSION 2 // version for ICU 58
  142. class ConfusableDataUtils {
  143. public:
  144. inline static UChar32 keyToCodePoint(int32_t key) {
  145. return key & 0x00ffffff;
  146. }
  147. inline static int32_t keyToLength(int32_t key) {
  148. return ((key & 0xff000000) >> 24) + 1;
  149. }
  150. inline static int32_t codePointAndLengthToKey(UChar32 codePoint, int32_t length) {
  151. U_ASSERT((codePoint & 0x00ffffff) == codePoint);
  152. U_ASSERT(length <= 256);
  153. return codePoint | ((length - 1) << 24);
  154. }
  155. };
  156. //-------------------------------------------------------------------------------------
  157. //
  158. // SpoofData
  159. //
  160. // A small class that wraps the raw (usually memory mapped) spoof data.
  161. // Serves two primary functions:
  162. // 1. Convenience. Contains real pointers to the data, to avoid dealing with
  163. // the offsets in the raw data.
  164. // 2. Reference counting. When a spoof checker is cloned, the raw data is shared
  165. // and must be retained until all checkers using the data are closed.
  166. // Nothing in this struct includes state that is specific to any particular
  167. // USpoofDetector object.
  168. //
  169. //---------------------------------------------------------------------------------------
  170. class SpoofData: public UMemory {
  171. public:
  172. static SpoofData* getDefault(UErrorCode &status); // Get standard ICU spoof data.
  173. static void releaseDefault(); // Cleanup reference to default spoof data.
  174. SpoofData(UErrorCode &status); // Create new spoof data wrapper.
  175. // Only used when building new data from rules.
  176. // Constructor for use when creating from prebuilt default data.
  177. // A UDataMemory is what the ICU internal data loading functions provide.
  178. // The udm is adopted by the SpoofData.
  179. SpoofData(UDataMemory *udm, UErrorCode &status);
  180. // Constructor for use when creating from serialized data.
  181. //
  182. SpoofData(const void *serializedData, int32_t length, UErrorCode &status);
  183. // Check raw Spoof Data Version compatibility.
  184. // Return TRUE it looks good.
  185. UBool validateDataVersion(UErrorCode &status) const;
  186. ~SpoofData(); // Destructor not normally used.
  187. // Use removeReference() instead.
  188. // Reference Counting functions.
  189. // Clone of a user-level spoof detector increments the ref count on the data.
  190. // Close of a user-level spoof detector decrements the ref count.
  191. // If the data is owned by us, it will be deleted when count goes to zero.
  192. SpoofData *addReference();
  193. void removeReference();
  194. // Reset all fields to an initial state.
  195. // Called from the top of all constructors.
  196. void reset();
  197. // Copy this instance's raw data buffer to the specified address.
  198. int32_t serialize(void *buf, int32_t capacity, UErrorCode &status) const;
  199. // Get the total number of bytes of data backed by this SpoofData.
  200. // Not to be confused with length, which returns the number of confusable entries.
  201. int32_t size() const;
  202. // Get the confusable skeleton transform for a single code point.
  203. // The result is a string with a length between 1 and 18 as of Unicode 9.
  204. // This is the main public endpoint for this class.
  205. // @return The length in UTF-16 code units of the substition string.
  206. int32_t confusableLookup(UChar32 inChar, UnicodeString &dest) const;
  207. // Get the number of confusable entries in this SpoofData.
  208. int32_t length() const;
  209. // Get the code point (key) at the specified index.
  210. UChar32 codePointAt(int32_t index) const;
  211. // Get the confusable skeleton (value) at the specified index.
  212. // Append it to the specified UnicodeString&.
  213. // @return The length in UTF-16 code units of the skeleton string.
  214. int32_t appendValueTo(int32_t index, UnicodeString& dest) const;
  215. private:
  216. // Reserve space in the raw data. For use by builder when putting together a
  217. // new set of data. Init the new storage to zero, to prevent inconsistent
  218. // results if it is not all otherwise set by the requester.
  219. // Return:
  220. // pointer to the new space that was added by this function.
  221. void *reserveSpace(int32_t numBytes, UErrorCode &status);
  222. // initialize the pointers from this object to the raw data.
  223. void initPtrs(UErrorCode &status);
  224. SpoofDataHeader *fRawData; // Ptr to the raw memory-mapped data
  225. UBool fDataOwned; // True if the raw data is owned, and needs
  226. // to be deleted when refcount goes to zero.
  227. UDataMemory *fUDM; // If not NULL, our data came from a
  228. // UDataMemory, which we must close when
  229. // we are done.
  230. uint32_t fMemLimit; // Limit of available raw data space
  231. u_atomic_int32_t fRefCount;
  232. // Confusable data
  233. int32_t *fCFUKeys;
  234. uint16_t *fCFUValues;
  235. UChar *fCFUStrings;
  236. friend class ConfusabledataBuilder;
  237. };
  238. //---------------------------------------------------------------------------------------
  239. //
  240. // Raw Binary Data Formats, as loaded from the ICU data file,
  241. // or as built by the builder.
  242. //
  243. //---------------------------------------------------------------------------------------
  244. struct SpoofDataHeader {
  245. int32_t fMagic; // (0x3845fdef)
  246. uint8_t fFormatVersion[4]; // Data Format. Same as the value in struct UDataInfo
  247. // if there is one associated with this data.
  248. int32_t fLength; // Total lenght in bytes of this spoof data,
  249. // including all sections, not just the header.
  250. // The following four sections refer to data representing the confusable data
  251. // from the Unicode.org data from "confusables.txt"
  252. int32_t fCFUKeys; // byte offset to Keys table (from SpoofDataHeader *)
  253. int32_t fCFUKeysSize; // number of entries in keys table (32 bits each)
  254. // TODO: change name to fCFUValues, for consistency.
  255. int32_t fCFUStringIndex; // byte offset to String Indexes table
  256. int32_t fCFUStringIndexSize; // number of entries in String Indexes table (16 bits each)
  257. // (number of entries must be same as in Keys table
  258. int32_t fCFUStringTable; // byte offset of String table
  259. int32_t fCFUStringTableLen; // length of string table (in 16 bit UChars)
  260. // The following sections are for data from xidmodifications.txt
  261. int32_t unused[15]; // Padding, Room for Expansion
  262. };
  263. U_NAMESPACE_END
  264. #endif /* __cplusplus */
  265. /**
  266. * Endianness swap function for binary spoof data.
  267. * @internal
  268. */
  269. U_CAPI int32_t U_EXPORT2
  270. uspoof_swap(const UDataSwapper *ds, const void *inData, int32_t length, void *outData,
  271. UErrorCode *status);
  272. #endif
  273. #endif /* USPOOFIM_H */