Home | History | Annotate | Download | only in gencfu
      1 /*
      2 **********************************************************************
      3 *   Copyright (C) 2009, International Business Machines
      4 *   Corporation and others.  All Rights Reserved.
      5 **********************************************************************
      6 *
      7 * File gencfu.c
      8 */
      9 
     10 //--------------------------------------------------------------------
     11 //
     12 //   Tool for generating Unicode Confusable data files (.cfu files).
     13 //   .cfu files contain the compiled of the confusable data
     14 //   derived from the Unicode Consortium data described in
     15 //   Unicode UAX 39.
     16 //
     17 //   Usage:  gencfu [options] -r confusables-file.txt -w whole-script-confusables.txt  -o output-file.cfu
     18 //
     19 //       options:   -v         verbose
     20 //                  -? or -h   help
     21 //
     22 //   The input rule filew is are plain text files containing confusable character
     23 //    definitions in the input format defined by Unicode UAX39 for the files
     24 //    confusables.txt and confusablesWholeScript.txt.  This source (.txt) format
     25 //    is also accepted direaccepted by ICU spoof detedtors.  The
     26 //    files must be encoded in utf-8 format, with or without a BOM.
     27 //
     28 //--------------------------------------------------------------------
     29 
     30 #include "unicode/utypes.h"
     31 #include "unicode/unistr.h"
     32 #include "unicode/uclean.h"
     33 #include "unicode/udata.h"
     34 #include "unicode/putil.h"
     35 
     36 #include "uoptions.h"
     37 #include "unewdata.h"
     38 #include "ucmndata.h"
     39 #include "uspoof_impl.h"
     40 #include "cmemory.h"
     41 
     42 #include <stdio.h>
     43 #include <stdlib.h>
     44 #include <string.h>
     45 
     46 U_NAMESPACE_USE
     47 
     48 static char *progName;
     49 static UOption options[]={
     50     UOPTION_HELP_H,             /* 0 */
     51     UOPTION_HELP_QUESTION_MARK, /* 1 */
     52     UOPTION_VERBOSE,            /* 2 */
     53     { "rules", NULL, NULL, NULL, 'r', UOPT_REQUIRES_ARG, 0 },   /* 3 */
     54     { "wsrules", NULL, NULL, NULL, 'w', UOPT_REQUIRES_ARG, 0},  /* 4 */
     55     { "out",   NULL, NULL, NULL, 'o', UOPT_REQUIRES_ARG, 0 },   /* 5 */
     56     UOPTION_ICUDATADIR,         /* 6 */
     57     UOPTION_DESTDIR,            /* 7 */
     58     UOPTION_COPYRIGHT,          /* 8 */
     59 };
     60 
     61 void usageAndDie(int retCode) {
     62         printf("Usage: %s [-v] [-options] -r confusablesRules.txt -w wholeScriptConfusables.txt -o output-file\n", progName);
     63         printf("\tRead in Unicode confusable character definitions and write out the binary data\n"
     64             "options:\n"
     65             "\t-h or -? or --help  this usage text\n"
     66             "\t-V or --version     show a version message\n"
     67             "\t-c or --copyright   include a copyright notice\n"
     68             "\t-v or --verbose     turn on verbose output\n"
     69             "\t-i or --icudatadir  directory for locating any needed intermediate data files,\n"
     70             "\t                    followed by path, defaults to %s\n"
     71             "\t-d or --destdir     destination directory, followed by the path\n",
     72             u_getDataDirectory());
     73         exit (retCode);
     74 }
     75 
     76 
     77 #if UCONFIG_NO_REGULAR_EXPRESSIONS
     78 
     79 /* dummy UDataInfo cf. udata.h */
     80 static UDataInfo dummyDataInfo = {
     81     sizeof(UDataInfo),
     82     0,
     83 
     84     U_IS_BIG_ENDIAN,
     85     U_CHARSET_FAMILY,
     86     U_SIZEOF_UCHAR,
     87     0,
     88 
     89     { 0, 0, 0, 0 },                 /* dummy dataFormat */
     90     { 0, 0, 0, 0 },                 /* dummy formatVersion */
     91     { 0, 0, 0, 0 }                  /* dummy dataVersion */
     92 };
     93 
     94 #else
     95 
     96 //
     97 //  Set up the ICU data header, defined in ucmndata.h
     98 //
     99 DataHeader dh ={
    100     {sizeof(DataHeader),           // Struct MappedData
    101         0xda,
    102         0x27},
    103 
    104     {                               // struct UDataInfo
    105         sizeof(UDataInfo),          //     size
    106         0,                          //     reserved
    107         U_IS_BIG_ENDIAN,
    108         U_CHARSET_FAMILY,
    109         U_SIZEOF_UCHAR,
    110         0,                          //     reserved
    111 
    112     { 0x43, 0x66, 0x75, 0x20 },     //     dataFormat="Cfu "
    113     { 0xff, 0, 0, 0 },              //     formatVersion.  Filled in later with values
    114                                     //      from the  builder.  The  values declared
    115                                     //      here should never appear in any real data.
    116         { 5, 1, 0, 0 }              //   dataVersion (Unicode version)
    117     }};
    118 
    119 #endif
    120 
    121 // Forward declaration for function for reading source files.
    122 static const char *readFile(const char *fileName, int32_t *len);
    123 
    124 //----------------------------------------------------------------------------
    125 //
    126 //  main      for gencfu
    127 //
    128 //----------------------------------------------------------------------------
    129 int  main(int argc, char **argv) {
    130     UErrorCode  status = U_ZERO_ERROR;
    131     const char *confFileName;
    132     const char *confWSFileName;
    133     const char *outFileName;
    134     const char *outDir = NULL;
    135     const char *copyright = NULL;
    136 
    137     //
    138     // Pick up and check the command line arguments,
    139     //    using the standard ICU tool utils option handling.
    140     //
    141     U_MAIN_INIT_ARGS(argc, argv);
    142     progName = argv[0];
    143     argc=u_parseArgs(argc, argv, sizeof(options)/sizeof(options[0]), options);
    144     if(argc<0) {
    145         // Unrecognized option
    146         fprintf(stderr, "error in command line argument \"%s\"\n", argv[-argc]);
    147         usageAndDie(U_ILLEGAL_ARGUMENT_ERROR);
    148     }
    149 
    150     if(options[0].doesOccur || options[1].doesOccur) {
    151         //  -? or -h for help.
    152         usageAndDie(0);
    153     }
    154 
    155     if (!(options[3].doesOccur && options[4].doesOccur && options[5].doesOccur)) {
    156         fprintf(stderr, "confusables file, whole script confusables file and output file must all be specified.\n");
    157         usageAndDie(U_ILLEGAL_ARGUMENT_ERROR);
    158     }
    159     confFileName   = options[3].value;
    160     confWSFileName = options[4].value;
    161     outFileName    = options[5].value;
    162 
    163     if (options[6].doesOccur) {
    164         u_setDataDirectory(options[6].value);
    165     }
    166 
    167     /* Initialize ICU */
    168     u_init(&status);
    169     if (U_FAILURE(status)) {
    170         fprintf(stderr, "%s: can not initialize ICU.  status = %s\n",
    171             argv[0], u_errorName(status));
    172         exit(1);
    173     }
    174     status = U_ZERO_ERROR;
    175 
    176     /* Combine the directory with the file name */
    177     if(options[7].doesOccur) {
    178         outDir = options[7].value;
    179     }
    180     if (options[8].doesOccur) {
    181         copyright = U_COPYRIGHT_STRING;
    182     }
    183 
    184 #if UCONFIG_NO_REGULAR_EXPRESSIONS
    185     // spoof detection data file parsing is dependent on regular expressions.
    186     // TODO: have the tool return an error status.  Requires fixing the ICU data build
    187     //       so that it doesn't abort entirely on that error.
    188 
    189     UNewDataMemory *pData;
    190     char msg[1024];
    191 
    192     /* write message with just the name */
    193     sprintf(msg, "gencfu writes dummy %s because of UCONFIG_NO_REGULAR_EXPRESSIONS, see uconfig.h", outFileName);
    194     fprintf(stderr, "%s\n", msg);
    195 
    196     /* write the dummy data file */
    197     pData = udata_create(outDir, NULL, outFileName, &dummyDataInfo, NULL, &status);
    198     udata_writeBlock(pData, msg, strlen(msg));
    199     udata_finish(pData, &status);
    200     return (int)status;
    201 
    202 #else
    203 
    204     //  Read in the confusables source file
    205 
    206     int32_t      confusablesLen = 0;
    207     const char  *confusables = readFile(confFileName, &confusablesLen);
    208     if (confusables == NULL) {
    209         printf("gencfu: error reading file  \"%s\"\n", confFileName);
    210         exit(-1);
    211     }
    212 
    213     int32_t     wsConfusablesLen = 0;
    214     const char *wsConfsables =  readFile(confWSFileName, &wsConfusablesLen);
    215     if (wsConfsables == NULL) {
    216         printf("gencfu: error reading file  \"%s\"\n", confFileName);
    217         exit(-1);
    218     }
    219 
    220     //
    221     //  Create the Spoof Detector from the source confusables files.
    222     //     This will compile the data.
    223     //
    224     UParseError parseError;
    225     parseError.line = 0;
    226     parseError.offset = 0;
    227     int32_t errType;
    228     USpoofChecker *sc = uspoof_openFromSource(confusables, confusablesLen,
    229                                               wsConfsables, wsConfusablesLen,
    230                                               &errType, &parseError, &status);
    231     if (U_FAILURE(status)) {
    232         const char *errFile =
    233             (errType == USPOOF_WHOLE_SCRIPT_CONFUSABLE)? confWSFileName : confFileName;
    234         fprintf(stderr, "gencfu: uspoof_openFromSource error \"%s\"  at file %s, line %d, column %d\n",
    235                 u_errorName(status), errFile, (int)parseError.line, (int)parseError.offset);
    236         exit(status);
    237     };
    238 
    239 
    240     //
    241     //  Get the compiled rule data from the USpoofChecker.
    242     //
    243     uint32_t        outDataSize;
    244     uint8_t        *outData;
    245     outDataSize = uspoof_serialize(sc, NULL, 0, &status);
    246     if (status != U_BUFFER_OVERFLOW_ERROR) {
    247         fprintf(stderr, "gencfu: uspoof_serialize() returned %s\n", u_errorName(status));
    248         exit(status);
    249     }
    250     status = U_ZERO_ERROR;
    251     outData = new uint8_t[outDataSize];
    252     uspoof_serialize(sc, outData, outDataSize, &status);
    253 
    254     // Copy the data format version numbers from the spoof data header into the UDataMemory header.
    255 
    256     uprv_memcpy(dh.info.formatVersion,
    257                 reinterpret_cast<SpoofDataHeader *>(outData)->fFormatVersion,
    258                 sizeof(dh.info.formatVersion));
    259 
    260     //
    261     //  Create the output file
    262     //
    263     size_t bytesWritten;
    264     UNewDataMemory *pData;
    265     pData = udata_create(outDir, NULL, outFileName, &(dh.info), copyright, &status);
    266     if(U_FAILURE(status)) {
    267         fprintf(stderr, "gencfu: Could not open output file \"%s\", \"%s\"\n",
    268                          outFileName, u_errorName(status));
    269         exit(status);
    270     }
    271 
    272 
    273     //  Write the data itself.
    274     udata_writeBlock(pData, outData, outDataSize);
    275     // finish up
    276     bytesWritten = udata_finish(pData, &status);
    277     if(U_FAILURE(status)) {
    278         fprintf(stderr, "gencfu: Error %d writing the output file\n", status);
    279         exit(status);
    280     }
    281 
    282     if (bytesWritten != outDataSize) {
    283         fprintf(stderr, "gencfu: Error writing to output file \"%s\"\n", outFileName);
    284         exit(-1);
    285     }
    286 
    287     uspoof_close(sc);
    288     delete outData;
    289     delete confusables;
    290     delete wsConfsables;
    291     u_cleanup();
    292     printf("gencfu: tool completed successfully.\n");
    293     return 0;
    294 #endif   // UCONFIG_NO_REGULAR_EXPRESSIONS
    295 }
    296 
    297 
    298  //
    299  //  Read in a confusables source file
    300  //
    301  static const char *readFile(const char *fileName, int32_t *len) {
    302     char       *result;
    303     long        fileSize;
    304     FILE        *file;
    305 
    306     file = fopen(fileName, "rb");
    307     if( file == 0 ) {
    308         return NULL;
    309     }
    310     fseek(file, 0, SEEK_END);
    311     fileSize = ftell(file);
    312     fseek(file, 0, SEEK_SET);
    313     result = new char[fileSize+10];
    314     if (result==NULL) {
    315         return result;
    316     }
    317 
    318     long t = fread(result, 1, fileSize, file);
    319     if (t != fileSize)  {
    320         delete result;
    321         return NULL;
    322     }
    323     result[fileSize]=0;
    324     *len = static_cast<int32_t>(fileSize);
    325     fclose(file);
    326     return result;
    327  }
    328