uspoof_impl.h 14 KB

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