Home | History | Annotate | Download | only in i18n
      1 /*
      2 ***************************************************************************
      3 * Copyright (C) 2008-2011, International Business Machines Corporation
      4 * and others. All Rights Reserved.
      5 ***************************************************************************
      6 *
      7 *  uspoof_impl.h
      8 *
      9 *    Implemenation header for spoof detection
     10 *
     11 */
     12 
     13 #ifndef USPOOFIM_H
     14 #define USPOOFIM_H
     15 
     16 #include "unicode/utypes.h"
     17 #include "unicode/uspoof.h"
     18 #include "utrie2.h"
     19 #include "unicode/uscript.h"
     20 #include "unicode/udata.h"
     21 
     22 
     23 #if !UCONFIG_NO_NORMALIZATION
     24 
     25 #ifdef __cplusplus
     26 
     27 U_NAMESPACE_BEGIN
     28 
     29 // The maximium length (in UTF-16 UChars) of the skeleton replacement string resulting from
     30 //   a single input code point.  This is function of the unicode.org data.
     31 #define USPOOF_MAX_SKELETON_EXPANSION 20
     32 
     33 // The default stack buffer size for copies or conversions or normalizations
     34 // of input strings being checked.  (Used in multiple places.)
     35 #define USPOOF_STACK_BUFFER_SIZE 100
     36 
     37 // Magic number for sanity checking spoof data.
     38 #define USPOOF_MAGIC 0x3845fdef
     39 
     40 class SpoofData;
     41 struct SpoofDataHeader;
     42 struct SpoofStringLengthsElement;
     43 class ScriptSet;
     44 
     45 /**
     46   *  Class SpoofImpl corresponds directly to the plain C API opaque type
     47   *  USpoofChecker.  One can be cast to the other.
     48   */
     49 class SpoofImpl : public UObject  {
     50 public:
     51 	SpoofImpl(SpoofData *data, UErrorCode &status);
     52 	SpoofImpl();
     53 	virtual ~SpoofImpl();
     54 
     55     /** Copy constructor, used by the user level uspoof_clone() function.
     56      */
     57     SpoofImpl(const SpoofImpl &src, UErrorCode &status);
     58 
     59     static SpoofImpl *validateThis(USpoofChecker *sc, UErrorCode &status);
     60     static const SpoofImpl *validateThis(const USpoofChecker *sc, UErrorCode &status);
     61 
     62     /** Get the confusable skeleton transform for a single code point.
     63      *  The result is a string with a length between 1 and 18.
     64      *  @param    tableMask  bit flag specifying which confusable table to use.
     65      *                       One of USPOOF_SL_TABLE_FLAG, USPOOF_MA_TABLE_FLAG, etc.
     66      *  @return   The length in UTF-16 code units of the substition string.
     67      */
     68     int32_t confusableLookup(UChar32 inChar, int32_t tableMask, UChar *destBuf) const;
     69 
     70     /** Set and Get AllowedLocales, implementations of the corresponding API */
     71     void setAllowedLocales(const char *localesList, UErrorCode &status);
     72     const char * getAllowedLocales(UErrorCode &status);
     73 
     74     // Add (union) to the UnicodeSet all of the characters for the scripts used for
     75     // the specified locale.  Part of the implementation of setAllowedLocales.
     76     void addScriptChars(const char *locale, UnicodeSet *allowedChars, UErrorCode &status);
     77 
     78 
     79     /** parse a hex number.  Untility used by the builders.   */
     80     static UChar32 ScanHex(const UChar *s, int32_t start, int32_t limit, UErrorCode &status);
     81 
     82     // Implementation for Whole Script tests.
     83     // Return the test bit flag to be ORed into the eventual user return value
     84     //    if a Spoof opportunity is detected.
     85     void wholeScriptCheck(
     86         const UChar *text, int32_t length, ScriptSet *result, UErrorCode &status) const;
     87 
     88     /** Scan a string to determine how many scripts it includes.
     89      * Ignore characters with script=Common and scirpt=Inherited.
     90      * @param    text     The UChar text to be scanned
     91      * @param    length   The length of the input text, -1 for nul termintated.
     92      * @param    pos      An out parameter, set to the first input postion at which
     93      *                    a second script was encountered, ignoring Common and Inherited.
     94      * @param    status   For errors.
     95      * @return            the number of (non-common,inherited) scripts encountered,
     96      *                    clipped to a max of two.
     97      */
     98     int32_t scriptScan(const UChar *text, int32_t length, int32_t &pos, UErrorCode &status) const;
     99 
    100     static UClassID U_EXPORT2 getStaticClassID(void);
    101     virtual UClassID getDynamicClassID(void) const;
    102 
    103     //
    104     // Data Members
    105     //
    106 
    107     int32_t           fMagic;             // Internal sanity check.
    108     int32_t           fChecks;            // Bit vector of checks to perform.
    109 
    110     SpoofData        *fSpoofData;
    111 
    112     const UnicodeSet *fAllowedCharsSet;   // The UnicodeSet of allowed characters.
    113                                           //   for this Spoof Checker.  Defaults to all chars.
    114 
    115     const char       *fAllowedLocales;    // The list of allowed locales.
    116 };
    117 
    118 
    119 
    120 //
    121 //  Confusable Mappings Data Structures
    122 //
    123 //    For the confusable data, we are essentially implementing a map,
    124 //       key:    a code point
    125 //       value:  a string.  Most commonly one char in length, but can be more.
    126 //
    127 //    The keys are stored as a sorted array of 32 bit ints.
    128 //             bits 0-23    a code point value
    129 //             bits 24-31   flags
    130 //                24:  1 if entry applies to SL table
    131 //                25:  1 if entry applies to SA table
    132 //                26:  1 if entry applies to ML table
    133 //                27:  1 if entry applies to MA table
    134 //                28:  1 if there are multiple entries for this code point.
    135 //                29-30:  length of value string, in UChars.
    136 //                         values are (1, 2, 3, other)
    137 //        The key table is sorted in ascending code point order.  (not on the
    138 //        32 bit int value, the flag bits do not participate in the sorting.)
    139 //
    140 //        Lookup is done by means of a binary search in the key table.
    141 //
    142 //    The corresponding values are kept in a parallel array of 16 bit ints.
    143 //        If the value string is of length 1, it is literally in the value array.
    144 //        For longer strings, the value array contains an index into the strings table.
    145 //
    146 //    String Table:
    147 //       The strings table contains all of the value strings (those of length two or greater)
    148 //       concatentated together into one long UChar (UTF-16) array.
    149 //
    150 //       The array is arranged by length of the strings - all strings of the same length
    151 //       are stored together.  The sections are ordered by length of the strings -
    152 //       all two char strings first, followed by all of the three Char strings, etc.
    153 //
    154 //       There is no nul character or other mark between adjacent strings.
    155 //
    156 //    String Lengths table
    157 //       The length of strings from 1 to 3 is flagged in the key table.
    158 //       For strings of length 4 or longer, the string length table provides a
    159 //       mapping between an index into the string table and the corresponding length.
    160 //       Strings of these lengths are rare, so lookup time is not an issue.
    161 //       Each entry consists of
    162 //            uint16_t      index of the _last_ string with this length
    163 //            uint16_t      the length
    164 //
    165 
    166 // Flag bits in the Key entries
    167 #define USPOOF_SL_TABLE_FLAG (1<<24)
    168 #define USPOOF_SA_TABLE_FLAG (1<<25)
    169 #define USPOOF_ML_TABLE_FLAG (1<<26)
    170 #define USPOOF_MA_TABLE_FLAG (1<<27)
    171 #define USPOOF_KEY_MULTIPLE_VALUES (1<<28)
    172 #define USPOOF_KEY_LENGTH_SHIFT 29
    173 #define USPOOF_KEY_LENGTH_FIELD(x) (((x)>>29) & 3)
    174 
    175 
    176 struct SpoofStringLengthsElement {
    177     uint16_t      fLastString;         // index in string table of last string with this length
    178     uint16_t      fStrLength;           // Length of strings
    179 };
    180 
    181 
    182 //-------------------------------------------------------------------------------
    183 //
    184 //  ScriptSet - Wrapper class for the Script code bit sets that are part of the
    185 //              whole script confusable data.
    186 //
    187 //              This class is used both at data build and at run time.
    188 //              The constructor is only used at build time.
    189 //              At run time, just point at the prebuilt data and go.
    190 //
    191 //-------------------------------------------------------------------------------
    192 class ScriptSet: public UMemory {
    193   public:
    194     ScriptSet();
    195     ~ScriptSet();
    196 
    197     UBool operator == (const ScriptSet &other);
    198     ScriptSet & operator = (const ScriptSet &other);
    199 
    200     void Union(const ScriptSet &other);
    201     void Union(UScriptCode script);
    202     void intersect(const ScriptSet &other);
    203     void intersect(UScriptCode script);
    204     void setAll();
    205     void resetAll();
    206     int32_t countMembers();
    207 
    208   private:
    209     uint32_t  bits[6];
    210 };
    211 
    212 
    213 
    214 
    215 //-------------------------------------------------------------------------------
    216 //
    217 //  NFDBuffer   A little class to handle the NFD normalization that is
    218 //               needed on incoming identifiers to be checked.
    219 //               Takes care of buffer handling and normalization
    220 //
    221 //               Instances of this class are intended to be stack-allocated.
    222 //
    223 //               TODO:  how to map position offsets back to user values?
    224 //
    225 //--------------------------------------------------------------------------------
    226 class NFDBuffer: public UMemory {
    227 public:
    228     NFDBuffer(const UChar *text, int32_t length, UErrorCode &status);
    229     ~NFDBuffer();
    230     const UChar *getBuffer();
    231     int32_t getLength();
    232 
    233   private:
    234     const UChar *fOriginalText;
    235     UChar       *fNormalizedText;
    236     int32_t      fNormalizedTextLength;
    237     UChar        fSmallBuf[USPOOF_STACK_BUFFER_SIZE];
    238 };
    239 
    240 
    241 
    242 
    243 
    244 //-------------------------------------------------------------------------------------
    245 //
    246 //  SpoofData
    247 //
    248 //    A small class that wraps the raw (usually memory mapped) spoof data.
    249 //    Serves two primary functions:
    250 //      1.  Convenience.  Contains real pointers to the data, to avoid dealing with
    251 //          the offsets in the raw data.
    252 //      2.  Reference counting.  When a spoof checker is cloned, the raw data is shared
    253 //          and must be retained until all checkers using the data are closed.
    254 //    Nothing in this struct includes state that is specific to any particular
    255 //    USpoofDetector object.
    256 //
    257 //---------------------------------------------------------------------------------------
    258 class SpoofData: public UMemory {
    259   public:
    260     static SpoofData *getDefault(UErrorCode &status);   // Load standard ICU spoof data.
    261     SpoofData(UErrorCode &status);   // Create new spoof data wrapper.
    262                                      // Only used when building new data from rules.
    263 
    264     // Constructor for use when creating from prebuilt default data.
    265     //   A UDataMemory is what the ICU internal data loading functions provide.
    266     //   The udm is adopted by the SpoofData.
    267     SpoofData(UDataMemory *udm, UErrorCode &status);
    268 
    269     // Constructor for use when creating from serialized data.
    270     //
    271     SpoofData(const void *serializedData, int32_t length, UErrorCode &status);
    272 
    273     //  Check raw Spoof Data Version compatibility.
    274     //  Return TRUE it looks good.
    275     static UBool validateDataVersion(const SpoofDataHeader *rawData, UErrorCode &status);
    276     ~SpoofData();                    // Destructor not normally used.
    277                                      // Use removeReference() instead.
    278     // Reference Counting functions.
    279     //    Clone of a user-level spoof detector increments the ref count on the data.
    280     //    Close of a user-level spoof detector decrements the ref count.
    281     //    If the data is owned by us, it will be deleted when count goes to zero.
    282     SpoofData *addReference();
    283     void removeReference();
    284 
    285     // Reserve space in the raw data.  For use by builder when putting together a
    286     //   new set of data.  Init the new storage to zero, to prevent inconsistent
    287     //   results if it is not all otherwise set by the requester.
    288     //  Return:
    289     //    pointer to the new space that was added by this function.
    290     void *reserveSpace(int32_t numBytes, UErrorCode &status);
    291 
    292     // initialize the pointers from this object to the raw data.
    293     void initPtrs(UErrorCode &status);
    294 
    295     // Reset all fields to an initial state.
    296     // Called from the top of all constructors.
    297     void reset();
    298 
    299     SpoofDataHeader             *fRawData;          // Ptr to the raw memory-mapped data
    300     UBool                       fDataOwned;         // True if the raw data is owned, and needs
    301                                                     //  to be deleted when refcount goes to zero.
    302     UDataMemory                 *fUDM;              // If not NULL, our data came from a
    303                                                     //   UDataMemory, which we must close when
    304                                                     //   we are done.
    305 
    306     uint32_t                    fMemLimit;          // Limit of available raw data space
    307     int32_t                     fRefCount;
    308 
    309     // Confusable data
    310     int32_t                     *fCFUKeys;
    311     uint16_t                    *fCFUValues;
    312     SpoofStringLengthsElement   *fCFUStringLengths;
    313     UChar                       *fCFUStrings;
    314 
    315     // Whole Script Confusable Data
    316     UTrie2                      *fAnyCaseTrie;
    317     UTrie2                      *fLowerCaseTrie;
    318     ScriptSet                   *fScriptSets;
    319     };
    320 
    321 
    322 //---------------------------------------------------------------------------------------
    323 //
    324 //  Raw Binary Data Formats, as loaded from the ICU data file,
    325 //    or as built by the builder.
    326 //
    327 //---------------------------------------------------------------------------------------
    328 struct SpoofDataHeader {
    329     int32_t       fMagic;                // (0x3845fdef)
    330     uint8_t       fFormatVersion[4];     // Data Format. Same as the value in struct UDataInfo
    331                                          //   if there is one associated with this data.
    332     int32_t       fLength;               // Total lenght in bytes of this spoof data,
    333                                          //   including all sections, not just the header.
    334 
    335     // The following four sections refer to data representing the confusable data
    336     //   from the Unicode.org data from "confusables.txt"
    337 
    338     int32_t       fCFUKeys;               // byte offset to Keys table (from SpoofDataHeader *)
    339     int32_t       fCFUKeysSize;           // number of entries in keys table  (32 bits each)
    340 
    341     // TODO: change name to fCFUValues, for consistency.
    342     int32_t       fCFUStringIndex;        // byte offset to String Indexes table
    343     int32_t       fCFUStringIndexSize;    // number of entries in String Indexes table (16 bits each)
    344                                           //     (number of entries must be same as in Keys table
    345 
    346     int32_t       fCFUStringTable;        // byte offset of String table
    347     int32_t       fCFUStringTableLen;     // length of string table (in 16 bit UChars)
    348 
    349     int32_t       fCFUStringLengths;      // byte offset to String Lengths table
    350     int32_t       fCFUStringLengthsSize;  // number of entries in lengths table. (2 x 16 bits each)
    351 
    352 
    353     // The following sections are for data from confusablesWholeScript.txt
    354 
    355     int32_t       fAnyCaseTrie;           // byte offset to the serialized Any Case Trie
    356     int32_t       fAnyCaseTrieLength;     // Length (bytes) of the serialized Any Case Trie
    357 
    358     int32_t       fLowerCaseTrie;         // byte offset to the serialized Lower Case Trie
    359     int32_t       fLowerCaseTrieLength;   // Length (bytes) of the serialized Lower Case Trie
    360 
    361     int32_t       fScriptSets;            // byte offset to array of ScriptSets
    362     int32_t       fScriptSetsLength;      // Number of ScriptSets (24 bytes each)
    363 
    364 
    365     // The following sections are for data from xidmodifications.txt
    366 
    367 
    368     int32_t       unused[15];              // Padding, Room for Expansion
    369 
    370  };
    371 
    372 
    373 
    374 
    375 //
    376 //  Structure for the Whole Script Confusable Data
    377 //    See Unicode UAX-39, Unicode Security Mechanisms, for a description of the
    378 //    Whole Script confusable data
    379 //
    380 //  The data provides mappings from code points to a set of scripts
    381 //    that contain characters that might be confused with the code point.
    382 //  There are two mappings, one for lower case only, and one for characters
    383 //    of any case.
    384 //
    385 //  The actual data consists of a utrie2 to map from a code point to an offset,
    386 //  and an array of UScriptSets (essentially bit maps) that is indexed
    387 //  by the offsets obtained from the Trie.
    388 //
    389 //
    390 
    391 
    392 U_NAMESPACE_END
    393 #endif /* __cplusplus */
    394 
    395 /**
    396   * Endianness swap function for binary spoof data.
    397   * @internal
    398   */
    399 U_CAPI int32_t U_EXPORT2
    400 uspoof_swap(const UDataSwapper *ds, const void *inData, int32_t length, void *outData,
    401             UErrorCode *status);
    402 
    403 
    404 #endif
    405 
    406 #endif  /* USPOOFIM_H */
    407 
    408