Path: blob/master/thirdparty/icu4c/i18n/uspoof_impl.h
9912 views
// © 2016 and later: Unicode, Inc. and others.1// License & terms of use: http://www.unicode.org/copyright.html2/*3***************************************************************************4* Copyright (C) 2008-2013, International Business Machines Corporation5* and others. All Rights Reserved.6***************************************************************************7*8* uspoof_impl.h9*10* Implementation header for spoof detection11*12*/1314#ifndef USPOOFIM_H15#define USPOOFIM_H1617#include "uassert.h"18#include "unicode/utypes.h"19#include "unicode/uspoof.h"20#include "unicode/uscript.h"21#include "unicode/udata.h"22#include "udataswp.h"23#include "utrie2.h"2425#if !UCONFIG_NO_NORMALIZATION2627#ifdef __cplusplus2829#include "capi_helper.h"30#include "umutex.h"3132U_NAMESPACE_BEGIN3334// The maximum length (in UTF-16 UChars) of the skeleton replacement string resulting from35// a single input code point. This is function of the unicode.org data.36#define USPOOF_MAX_SKELETON_EXPANSION 203738// The default stack buffer size for copies or conversions or normalizations39// of input strings being checked. (Used in multiple places.)40#define USPOOF_STACK_BUFFER_SIZE 1004142// Magic number for sanity checking spoof data.43#define USPOOF_MAGIC 0x3845fdef4445// Magic number for sanity checking spoof checkers.46#define USPOOF_CHECK_MAGIC 0x2734ecde4748class ScriptSet;49class SpoofData;50struct SpoofDataHeader;51class ConfusableDataUtils;5253/**54* Class SpoofImpl corresponds directly to the plain C API opaque type55* USpoofChecker. One can be cast to the other.56*/57class SpoofImpl : public UObject,58public IcuCApiHelper<USpoofChecker, SpoofImpl, USPOOF_MAGIC> {59public:60SpoofImpl(SpoofData *data, UErrorCode& status);61SpoofImpl(UErrorCode& status);62SpoofImpl();63void construct(UErrorCode& status);64virtual ~SpoofImpl();6566/** Copy constructor, used by the user level uspoof_clone() function.67*/68SpoofImpl(const SpoofImpl &src, UErrorCode &status);6970USpoofChecker *asUSpoofChecker();71static SpoofImpl *validateThis(USpoofChecker *sc, UErrorCode &status);72static const SpoofImpl *validateThis(const USpoofChecker *sc, UErrorCode &status);7374/** Set and Get AllowedLocales, implementations of the corresponding API */75void setAllowedLocales(const char *localesList, UErrorCode &status);76const char * getAllowedLocales(UErrorCode &status);7778// Add (union) to the UnicodeSet all of the characters for the scripts used for79// the specified locale. Part of the implementation of setAllowedLocales.80void addScriptChars(const char *locale, UnicodeSet *allowedChars, UErrorCode &status);8182// Functions implementing the features of UTS 39 section 5.83static void getAugmentedScriptSet(UChar32 codePoint, ScriptSet& result, UErrorCode& status);84void getResolvedScriptSet(const UnicodeString& input, ScriptSet& result, UErrorCode& status) const;85void getResolvedScriptSetWithout(const UnicodeString& input, UScriptCode script, ScriptSet& result, UErrorCode& status) const;86void getNumerics(const UnicodeString& input, UnicodeSet& result, UErrorCode& status) const;87URestrictionLevel getRestrictionLevel(const UnicodeString& input, UErrorCode& status) const;8889int32_t findHiddenOverlay(const UnicodeString& input, UErrorCode& status) const;90bool isIllegalCombiningDotLeadCharacter(UChar32 cp) const;9192/** parse a hex number. Untility used by the builders. */93static UChar32 ScanHex(const char16_t *s, int32_t start, int32_t limit, UErrorCode &status);9495static UClassID U_EXPORT2 getStaticClassID();96virtual UClassID getDynamicClassID() const override;9798//99// Data Members100//101102int32_t fChecks; // Bit vector of checks to perform.103104SpoofData *fSpoofData;105106const UnicodeSet *fAllowedCharsSet; // The UnicodeSet of allowed characters.107// for this Spoof Checker. Defaults to all chars.108109const char *fAllowedLocales; // The list of allowed locales.110URestrictionLevel fRestrictionLevel; // The maximum restriction level for an acceptable identifier.111};112113/**114* Class CheckResult corresponds directly to the plain C API opaque type115* USpoofCheckResult. One can be cast to the other.116*/117class CheckResult : public UObject,118public IcuCApiHelper<USpoofCheckResult, CheckResult, USPOOF_CHECK_MAGIC> {119public:120CheckResult();121virtual ~CheckResult();122123USpoofCheckResult *asUSpoofCheckResult();124static CheckResult *validateThis(USpoofCheckResult *ptr, UErrorCode &status);125static const CheckResult *validateThis(const USpoofCheckResult *ptr, UErrorCode &status);126127void clear();128129// Used to convert this CheckResult to the older int32_t return value API130int32_t toCombinedBitmask(int32_t expectedChecks);131132// Data Members133int32_t fChecks; // Bit vector of checks that were failed.134UnicodeSet fNumerics; // Set of numerics found in the string.135URestrictionLevel fRestrictionLevel; // The restriction level of the string.136};137138139//140// Confusable Mappings Data Structures, version 2.0141//142// For the confusable data, we are essentially implementing a map,143// key: a code point144// value: a string. Most commonly one char in length, but can be more.145//146// The keys are stored as a sorted array of 32 bit ints.147// bits 0-23 a code point value148// bits 24-31 length of value string, in UChars (between 1 and 256 UChars).149// The key table is sorted in ascending code point order. (not on the150// 32 bit int value, the flag bits do not participate in the sorting.)151//152// Lookup is done by means of a binary search in the key table.153//154// The corresponding values are kept in a parallel array of 16 bit ints.155// If the value string is of length 1, it is literally in the value array.156// For longer strings, the value array contains an index into the strings table.157//158// String Table:159// The strings table contains all of the value strings (those of length two or greater)160// concatenated together into one long char16_t (UTF-16) array.161//162// There is no nul character or other mark between adjacent strings.163//164//----------------------------------------------------------------------------165//166// Changes from format version 1 to format version 2:167// 1) Removal of the whole-script confusable data tables.168// 2) Removal of the SL/SA/ML/MA and multi-table flags in the key bitmask.169// 3) Expansion of string length value in the key bitmask from 2 bits to 8 bits.170// 4) Removal of the string lengths table since 8 bits is sufficient for the171// lengths of all entries in confusables.txt.172173174175// Internal functions for manipulating confusable data table keys176#define USPOOF_CONFUSABLE_DATA_FORMAT_VERSION 2 // version for ICU 58177class ConfusableDataUtils {178public:179inline static UChar32 keyToCodePoint(int32_t key) {180return key & 0x00ffffff;181}182inline static int32_t keyToLength(int32_t key) {183return ((key & 0xff000000) >> 24) + 1;184}185inline static int32_t codePointAndLengthToKey(UChar32 codePoint, int32_t length) {186U_ASSERT((codePoint & 0x00ffffff) == codePoint);187U_ASSERT(length <= 256);188return codePoint | ((length - 1) << 24);189}190};191192193//-------------------------------------------------------------------------------------194//195// SpoofData196//197// A small class that wraps the raw (usually memory mapped) spoof data.198// Serves two primary functions:199// 1. Convenience. Contains real pointers to the data, to avoid dealing with200// the offsets in the raw data.201// 2. Reference counting. When a spoof checker is cloned, the raw data is shared202// and must be retained until all checkers using the data are closed.203// Nothing in this struct includes state that is specific to any particular204// USpoofDetector object.205//206//---------------------------------------------------------------------------------------207class SpoofData: public UMemory {208public:209static SpoofData* getDefault(UErrorCode &status); // Get standard ICU spoof data.210static void releaseDefault(); // Cleanup reference to default spoof data.211212SpoofData(UErrorCode &status); // Create new spoof data wrapper.213// Only used when building new data from rules.214215// Constructor for use when creating from prebuilt default data.216// A UDataMemory is what the ICU internal data loading functions provide.217// The udm is adopted by the SpoofData.218SpoofData(UDataMemory *udm, UErrorCode &status);219220// Constructor for use when creating from serialized data.221//222SpoofData(const void *serializedData, int32_t length, UErrorCode &status);223224// Check raw Spoof Data Version compatibility.225// Return true it looks good.226UBool validateDataVersion(UErrorCode &status) const;227228~SpoofData(); // Destructor not normally used.229// Use removeReference() instead.230// Reference Counting functions.231// Clone of a user-level spoof detector increments the ref count on the data.232// Close of a user-level spoof detector decrements the ref count.233// If the data is owned by us, it will be deleted when count goes to zero.234SpoofData *addReference();235void removeReference();236237// Reset all fields to an initial state.238// Called from the top of all constructors.239void reset();240241// Copy this instance's raw data buffer to the specified address.242int32_t serialize(void *buf, int32_t capacity, UErrorCode &status) const;243244// Get the total number of bytes of data backed by this SpoofData.245// Not to be confused with length, which returns the number of confusable entries.246int32_t size() const;247248// Get the confusable skeleton transform for a single code point.249// The result is a string with a length between 1 and 18 as of Unicode 9.250// This is the main public endpoint for this class.251// @return The length in UTF-16 code units of the substitution string.252int32_t confusableLookup(UChar32 inChar, UnicodeString &dest) const;253254// Get the number of confusable entries in this SpoofData.255int32_t length() const;256257// Get the code point (key) at the specified index.258UChar32 codePointAt(int32_t index) const;259260// Get the confusable skeleton (value) at the specified index.261// Append it to the specified UnicodeString&.262// @return The length in UTF-16 code units of the skeleton string.263int32_t appendValueTo(int32_t index, UnicodeString& dest) const;264265private:266// Reserve space in the raw data. For use by builder when putting together a267// new set of data. Init the new storage to zero, to prevent inconsistent268// results if it is not all otherwise set by the requester.269// Return:270// pointer to the new space that was added by this function.271void *reserveSpace(int32_t numBytes, UErrorCode &status);272273// initialize the pointers from this object to the raw data.274void initPtrs(UErrorCode &status);275276SpoofDataHeader *fRawData; // Ptr to the raw memory-mapped data277UBool fDataOwned; // True if the raw data is owned, and needs278// to be deleted when refcount goes to zero.279UDataMemory *fUDM; // If not nullptr, our data came from a280// UDataMemory, which we must close when281// we are done.282283uint32_t fMemLimit; // Limit of available raw data space284u_atomic_int32_t fRefCount;285286// Confusable data287int32_t *fCFUKeys;288uint16_t *fCFUValues;289char16_t *fCFUStrings;290291friend class ConfusabledataBuilder;292};293294//---------------------------------------------------------------------------------------295//296// Raw Binary Data Formats, as loaded from the ICU data file,297// or as built by the builder.298//299//---------------------------------------------------------------------------------------300struct SpoofDataHeader {301int32_t fMagic; // (0x3845fdef)302uint8_t fFormatVersion[4]; // Data Format. Same as the value in struct UDataInfo303// if there is one associated with this data.304int32_t fLength; // Total length in bytes of this spoof data,305// including all sections, not just the header.306307// The following four sections refer to data representing the confusable data308// from the Unicode.org data from "confusables.txt"309310int32_t fCFUKeys; // byte offset to Keys table (from SpoofDataHeader *)311int32_t fCFUKeysSize; // number of entries in keys table (32 bits each)312313// TODO: change name to fCFUValues, for consistency.314int32_t fCFUStringIndex; // byte offset to String Indexes table315int32_t fCFUStringIndexSize; // number of entries in String Indexes table (16 bits each)316// (number of entries must be same as in Keys table317318int32_t fCFUStringTable; // byte offset of String table319int32_t fCFUStringTableLen; // length of string table (in 16 bit UChars)320321// The following sections are for data from xidmodifications.txt322323int32_t unused[15]; // Padding, Room for Expansion324};325326327328U_NAMESPACE_END329#endif /* __cplusplus */330331/**332* Endianness swap function for binary spoof data.333* @internal334*/335U_CAPI int32_t U_EXPORT2336uspoof_swap(const UDataSwapper *ds, const void *inData, int32_t length, void *outData,337UErrorCode *status);338339340#endif341342#endif /* USPOOFIM_H */343344345346