Annotation of parser3/src/classes/math.C, revision 1.61

1.1       parser      1: /** @file
                      2:        Parser: @b math parser class.
                      3: 
1.59      moko        4:        Copyright (c) 2001-2012 Art. Lebedev Studio (http://www.artlebedev.com)
1.20      paf         5:        Author: Alexandr Petrosian <paf@design.ru>(http://paf.design.ru)
1.28      paf         6: 
                      7:        portions from gen_uuid.c,
                      8:        Copyright (C) 1996, 1997, 1998, 1999 Theodore Ts'o.
1.22      paf         9: */
1.1       parser     10: 
1.34      paf        11: #include "pa_vmethod_frame.h"
1.1       parser     12: #include "pa_common.h"
                     13: #include "pa_vint.h"
1.2       parser     14: #include "pa_vmath.h"
1.1       parser     15: #include "pa_request.h"
1.19      paf        16: #include "pa_md5.h"
1.55      misha      17: #include "pa_random.h"
1.1       parser     18: 
1.5       parser     19: #ifdef WIN32
1.28      paf        20: #      define _WIN32_WINNT 0x400
1.5       parser     21: #      include <windows.h>
1.28      paf        22: #      include <wincrypt.h>
1.5       parser     23: #endif
                     24: 
1.34      paf        25: #ifdef HAVE_CRYPT
                     26: #      ifdef HAVE_CRYPT_H
                     27: #              include <crypt.h>
                     28: #      endif
                     29: #else
                     30:        extern char *crypt(const char* , const char* );
1.20      paf        31: #endif
                     32: 
1.61    ! moko       33: volatile const char * IDENT_MATH_C="$Id: math.C,v 1.60 2012-05-23 20:51:40 moko Exp $";
1.59      moko       34: 
1.1       parser     35: // defines
                     36: 
1.20      paf        37: #define MAX_SALT 8
1.1       parser     38: 
                     39: // class
                     40: 
1.34      paf        41: class MMath: public Methoded {
1.1       parser     42: public:
1.34      paf        43:        MMath();
1.5       parser     44: 
1.1       parser     45: public: // Methoded
1.15      paf        46:        bool used_directly() { return false; }
1.1       parser     47: };
                     48: 
1.34      paf        49: // global variables
                     50: 
                     51: DECLARE_CLASS_VAR(math, 0 /*fictive*/, new MMath);
                     52: 
1.1       parser     53: // methods
1.34      paf        54: 
                     55: static void _random(Request& r, MethodParams& params) {
1.41      paf        56:        double top=params.as_double(0, "range must be expression", r);
1.34      paf        57:        if(top<=0 || top>MAX_UINT)
1.45      misha      58:                throw Exception(PARSER_RUNTIME,
1.34      paf        59:                        0,
                     60:                        "top(%g) must be [1..%u]", top, MAX_UINT);
1.1       parser     61:        
1.34      paf        62:        r.write_no_lang(*new VInt(_random(uint(top))));
1.1       parser     63: }
                     64: 
                     65: 
1.20      paf        66: typedef double(*math1_func_ptr)(double);
1.3       parser     67: static double frac(double param) { return param-trunc(param); }
                     68: static double degrees(double param) { return param /PI *180; }
                     69: static double radians(double param) { return param /180 *PI; }
1.1       parser     70: 
1.34      paf        71: static void math1(Request& r, MethodParams& params, math1_func_ptr func) {
1.41      paf        72:        double param=params.as_double(0, "parameter must be expression", r);
                     73:        double result=func(param);
1.34      paf        74:        r.write_no_lang(*new VDouble(result));
1.1       parser     75: }
                     76: 
                     77: #define MATH1(name) \
1.34      paf        78:        static void _##name(Request& r, MethodParams& params) {\
                     79:                math1(r, params, &name);\
1.1       parser     80:        }
                     81: #define MATH1P(name_parser, name_c) \
1.34      paf        82:        static void _##name_parser(Request& r, MethodParams& params) {\
                     83:                math1(r, params, &name_c);\
1.1       parser     84:        }
                     85: MATH1(round);  MATH1(floor);   MATH1P(ceiling, ceil);
1.3       parser     86: MATH1(trunc);  MATH1(frac);
1.1       parser     87: MATH1P(abs, fabs);     MATH1(sign);
1.46      misha      88: MATH1(exp);    
1.48      misha      89: MATH1(log);    MATH1(log10);
1.1       parser     90: MATH1(sin);    MATH1(asin);    
                     91: MATH1(cos);    MATH1(acos);    
                     92: MATH1(tan);    MATH1(atan);
1.3       parser     93: MATH1(degrees);        MATH1(radians);
1.1       parser     94: MATH1(sqrt);
                     95: 
                     96: 
                     97: typedef double (*math2_func_ptr)(double, double);
1.34      paf        98: static void math2(Request& r, MethodParams& params, math2_func_ptr func) {
1.41      paf        99:        double a=params.as_double(0, "parameter must be expression", r);
                    100:        double b=params.as_double(1, "parameter must be expression", r);
                    101:        double result=func(a, b);
1.34      paf       102:        r.write_no_lang(*new VDouble(result));
1.1       parser    103: }
                    104: 
                    105: #define MATH2(name) \
1.34      paf       106:        static void _##name(Request& r, MethodParams& params) {\
                    107:                math2(r, params, &name);\
1.1       parser    108:        }
                    109: MATH2(pow);
                    110: 
1.20      paf       111: inline bool is_salt_body_char(int c) {
                    112:        return isalnum(c) || c == '.' || c=='/';
                    113: }
1.34      paf       114: static size_t calc_prefix_size(const char* salt) {
1.37      paf       115:        if(strlen(salt)) {
1.39      paf       116:                if(!is_salt_body_char((unsigned char)salt[0])) { // $...  {...
1.34      paf       117:                        const char* cur=salt+1; // skip
1.39      paf       118:                        while(is_salt_body_char((unsigned char)*cur++)) // ...$  ...}
1.20      paf       119:                                ;
                    120:                        return cur-salt;
                    121:                } else
                    122:                        return 0;
                    123:        } else
                    124:                return 0;
                    125: }
1.34      paf       126: static void _crypt(Request& r, MethodParams& params) {
                    127:        const char* password=params.as_string(0, "password must be string").cstr();
                    128:        const char* maybe_bodyless_salt=params.as_string(1, "salt must be string").cstr();
1.20      paf       129: 
                    130:        size_t prefix_size=calc_prefix_size(maybe_bodyless_salt);
1.34      paf       131:        const char* normal_salt;
1.20      paf       132:        char normalize_buf[MAX_STRING];
                    133:        if(prefix_size==strlen(maybe_bodyless_salt)) { // bodyless?
                    134:                strncpy(normalize_buf, maybe_bodyless_salt, MAX_STRING-MAX_SALT-1);
                    135:                char *cur=normalize_buf+strlen(normalize_buf);
                    136:                // sould add up MAX_SALT random chars
                    137:                static unsigned char itoa64[] =         /* 0 ... 63 => ASCII - 64 */
                    138:                "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
                    139:                for(int i=0; i<MAX_SALT; i++)
                    140:                        *cur++=itoa64[_random(64)];
                    141:                *cur=0;
                    142:                normal_salt=normalize_buf;
                    143:        } else
                    144:                normal_salt=maybe_bodyless_salt;
1.19      paf       145: 
1.54      misha     146:        /* FreeBSD style MD5 string 
                    147:        */
                    148:        if(strncmp(normal_salt, PA_MD5PW_ID, PA_MD5PW_IDLEN) == 0) {
1.19      paf       149:                const size_t sample_size=120;
1.34      paf       150:                char *sample_buf=new(PointerFreeGC) char[sample_size];
                    151:                pa_MD5Encode((const unsigned char *)password,
                    152:                                (const unsigned char *)normal_salt, sample_buf, sample_size);
                    153:                String sample(sample_buf);
                    154:                r.write_pass_lang(sample);
1.54      misha     155:        } else {
1.20      paf       156: #ifdef HAVE_CRYPT
1.34      paf       157:                const char* static_sample_buf=crypt(password, normal_salt);
                    158:                if(!static_sample_buf  // nothing generated
                    159:                        || !static_sample_buf[0] // generated nothing
                    160:                        || strncmp(static_sample_buf, normal_salt, prefix_size)!=0) // salt prefix not preserved
1.45      misha     161:                        throw Exception(PARSER_RUNTIME,
1.34      paf       162:                                0,
                    163:                                "crypt on this platform does not support '%.*s' salt prefix", prefix_size, normal_salt);
1.20      paf       164:                
1.34      paf       165:                r.write_pass_lang(String(pa_strdup(static_sample_buf)));
1.20      paf       166: #else
1.45      misha     167:                throw Exception(PARSER_RUNTIME,
1.34      paf       168:                        0,
1.19      paf       169:                        "salt must start with '" PA_MD5PW_ID "'");
1.20      paf       170: #endif
                    171:        }
1.19      paf       172: }
                    173: 
1.34      paf       174: static void _md5(Request& r, MethodParams& params) {
1.51      misha     175:        const char *string=params.as_string(0, PARAMETER_MUST_BE_STRING).cstr();
1.27      paf       176: 
                    177:        PA_MD5_CTX context;
                    178:        unsigned char digest[16];
1.34      paf       179:        pa_MD5Init(&context);
                    180:        pa_MD5Update(&context, (const unsigned char*)string, strlen(string));
                    181:        pa_MD5Final(digest, &context);
1.27      paf       182: 
1.34      paf       183:        r.write_pass_lang(*new String(hex_string(digest, sizeof(digest), false)));
1.26      paf       184: }
                    185: 
1.49      misha     186: 
                    187: //SHA-1:
                    188: 
1.50      misha     189: struct SHA1Context {
1.54      misha     190:        unsigned Message_Digest[5], Length_Low, Length_High;
                    191:        unsigned int Message_Block[64];
                    192:        int Message_Block_Index, Computed, Corrupted;
1.50      misha     193: };
1.49      misha     194: 
                    195: #define SHA1CircularShift(bits,word) ((((word) << (bits)) & 0xFFFFFFFF)|((word) >> (32-(bits))))
                    196: void SHA1ProcessMessageBlock(SHA1Context *);
                    197: void SHA1PadMessage(SHA1Context *);
1.50      misha     198: void SHA1Reset(SHA1Context *context) {
1.54      misha     199:        context->Length_Low = context->Length_High = context->Message_Block_Index = 0;
                    200:        context->Message_Digest[0]      = 0x67452301;
                    201:        context->Message_Digest[1]      = 0xEFCDAB89;
                    202:        context->Message_Digest[2]      = 0x98BADCFE;
                    203:        context->Message_Digest[3]      = 0x10325476;
                    204:        context->Message_Digest[4]      = 0xC3D2E1F0;
                    205:        context->Computed = context->Corrupted  = 0;
1.50      misha     206: }
1.49      misha     207: 
1.50      misha     208: int SHA1Result(SHA1Context *context) {
1.54      misha     209:        if (context->Corrupted)
                    210:                return 0;
                    211:        if (!context->Computed) {
                    212:                SHA1PadMessage(context);
                    213:                context->Computed = 1;
                    214:        }
                    215:        return 1;
                    216: }
                    217: 
                    218: void SHA1Input(SHA1Context *context, const unsigned char *message_array, unsigned length) {
                    219:        if (!length)
                    220:                return;
                    221:        if (context->Computed || context->Corrupted) {
                    222:                context->Corrupted = 1;
                    223:                return;
                    224:        }
                    225: 
                    226:        while(length-- && !context->Corrupted) {
                    227:                context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF);
                    228:                context->Length_Low += 8;
                    229:                context->Length_Low &= 0xFFFFFFFF;
                    230:                if (!context->Length_Low && !(context->Length_High=((1+context->Length_High)&0xFFFFFFFF)))
                    231:                        context->Corrupted = 1; // too long message
                    232:                if (context->Message_Block_Index == 64)
                    233:                        SHA1ProcessMessageBlock(context);
                    234:                message_array++;
1.49      misha     235:        }
1.50      misha     236: }
1.49      misha     237: 
1.50      misha     238: void SHA1ProcessMessageBlock(SHA1Context *context) {
1.54      misha     239:        const unsigned K[] = {0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 };
                    240:        int t;
                    241:        unsigned    temp, W[80], buf[5];
                    242:        unsigned &A=buf[0], &B=buf[1], &C=buf[2], &D=buf[3], &E=buf[4];
1.50      misha     243: 
1.54      misha     244:        for(t = 0; t < 16; t++)
                    245:                W[t] = (((unsigned) context->Message_Block[t * 4]) << 24) | (((unsigned) context->Message_Block[t * 4 + 1]) << 16) | (((unsigned) context->Message_Block[t * 4 + 2]) << 8) | ((unsigned) context->Message_Block[t * 4 + 3]);
1.50      misha     246: 
1.54      misha     247:        for(t = 16; t < 80; t++)
                    248:                W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
1.49      misha     249: 
1.54      misha     250:        memcpy (buf, context->Message_Digest, sizeof(buf));
                    251:        for(t = 0; t < 20; t++) {
                    252:                temp =  (SHA1CircularShift(5,A) + ((B & C) | ((~B) & D)) + E + W[t] + K[0]) & 0xFFFFFFFF;
                    253:                E = D; D = C;
                    254:                C = SHA1CircularShift(30,B);
                    255:                B = A; A = temp;
1.49      misha     256:        }
                    257: 
1.54      misha     258:        for(t = 20; t < 40; t++) {
                    259:                temp = (SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]) & 0xFFFFFFFF;
                    260:                E = D; D = C;
                    261:                C = SHA1CircularShift(30,B);
                    262:                B = A; A = temp;
1.49      misha     263:        }
                    264: 
1.54      misha     265:        for(t = 40; t < 60; t++) {
                    266:                temp = (SHA1CircularShift(5,A) + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]) & 0xFFFFFFFF;
                    267:                E = D; D = C;
                    268:                C = SHA1CircularShift(30,B);
                    269:                B = A; A = temp;
1.49      misha     270:        }
                    271: 
1.54      misha     272:        for(t = 60; t < 80; t++) {
                    273:                temp = (SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3]) & 0xFFFFFFFF;
                    274:                E = D; D = C;
                    275:                C = SHA1CircularShift(30,B);
                    276:                B = A; A = temp;
1.49      misha     277:        }
                    278: 
1.54      misha     279:        for (t = 0; t < 5; t++)
                    280:                context->Message_Digest[t] = (context->Message_Digest[t] + buf[t]) & 0xFFFFFFFF;
1.50      misha     281: 
1.54      misha     282:        context->Message_Block_Index = 0;
1.50      misha     283: }
1.49      misha     284: 
1.50      misha     285: void SHA1PadMessage(SHA1Context *context) {
1.54      misha     286:        context->Message_Block[context->Message_Block_Index++] = 0x80;
1.50      misha     287:        if (context->Message_Block_Index > 56) {
                    288:                //was 55, one shift
1.54      misha     289:                while(context->Message_Block_Index < 64)
                    290:                        context->Message_Block[context->Message_Block_Index++] = 0;
                    291:                SHA1ProcessMessageBlock(context);
                    292:                while(context->Message_Block_Index < 56)
                    293:                        context->Message_Block[context->Message_Block_Index++] = 0;
1.50      misha     294:        } else
1.54      misha     295:                while(context->Message_Block_Index < 56)
                    296:                        context->Message_Block[context->Message_Block_Index++] = 0;
                    297:        context->Message_Block[56] = (context->Length_High >> 24) & 0xFF;
                    298:        context->Message_Block[57] = (context->Length_High >> 16) & 0xFF;
                    299:        context->Message_Block[58] = (context->Length_High >> 8) & 0xFF;
                    300:        context->Message_Block[59] = (context->Length_High) & 0xFF;
                    301:        context->Message_Block[60] = (context->Length_Low >> 24) & 0xFF;
                    302:        context->Message_Block[61] = (context->Length_Low >> 16) & 0xFF;
                    303:        context->Message_Block[62] = (context->Length_Low >> 8) & 0xFF;
                    304:        context->Message_Block[63] = (context->Length_Low) & 0xFF;
                    305:        SHA1ProcessMessageBlock(context);
1.50      misha     306: }
1.49      misha     307: 
1.54      misha     308: static void _sha1(Request& r, MethodParams& params) {
                    309:        const char *string = params.as_string(0, PARAMETER_MUST_BE_STRING).cstr();
1.49      misha     310: 
1.54      misha     311:        SHA1Context c;
                    312:        SHA1Reset (&c);
                    313:        SHA1Input (&c, (const unsigned char*)string, strlen(string));
                    314:        if(!SHA1Result(&c))
                    315:                throw Exception (PARSER_RUNTIME, 0, "Can not compute SHA1");
                    316: 
1.56      misha     317:        const size_t bufsize=40+1/*zero-teminator*/+1/*for faulty snprintfs*/;
1.55      misha     318:        char* cstr=new(PointerFreeGC) char[bufsize];
                    319: 
                    320:        snprintf(cstr, bufsize,
1.54      misha     321:                        "%08x%08x%08x%08x%08x",
                    322:                        c.Message_Digest[0],
                    323:                        c.Message_Digest[1],
                    324:                        c.Message_Digest[2],
                    325:                        c.Message_Digest[3],
                    326:                        c.Message_Digest[4]);
1.49      misha     327: 
1.55      misha     328:        r.write_pass_lang(*new String(cstr));
1.54      misha     329: }
1.49      misha     330: 
1.55      misha     331: static void _uuid(Request& r, MethodParams& /*params*/) {
                    332:        uuid uuid=get_uuid();
1.49      misha     333: 
1.55      misha     334:        const size_t bufsize=36+1/*zero-teminator*/+1/*for faulty snprintfs*/;
                    335:        char* cstr=new(PointerFreeGC) char[bufsize];
1.28      paf       336: 
1.55      misha     337:        snprintf(cstr, bufsize,
                    338:                        "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
                    339:                        uuid.time_low, uuid.time_mid, uuid.time_hi_and_version,
                    340:                        uuid.clock_seq >> 8, uuid.clock_seq & 0xFF,
                    341:                        uuid.node[0], uuid.node[1], uuid.node[2],
                    342:                        uuid.node[3], uuid.node[4], uuid.node[5]);
1.28      paf       343: 
1.55      misha     344:        r.write_pass_lang(*new String(cstr));
1.28      paf       345: }
                    346: 
1.34      paf       347: static void _uid64(Request& r, MethodParams& /*params*/) {
1.30      paf       348: 
                    349:        unsigned char id[64/8];
                    350:        random(&id, sizeof(id));
                    351: 
1.34      paf       352:        r.write_pass_lang(*new String(hex_string(id, sizeof(id), true)));
1.30      paf       353: }
                    354: 
1.43      misha     355: static void _crc32(Request& r, MethodParams& params) {
1.51      misha     356:        const char *string=params.as_string(0, PARAMETER_MUST_BE_STRING).cstr();
1.43      misha     357:        r.write_no_lang(*new VInt(pa_crc32(string, strlen(string))));
                    358: }
                    359: 
1.61    ! moko      360: static void toBase(unsigned int value, unsigned int base, char*& ptr){
1.57      misha     361:        static const char* hex="0123456789ABCDEF";
                    362:        int rest = value % base;
1.58      misha     363:        if(value >= base)
1.57      misha     364:                toBase( (value-rest)/base, base, ptr);
                    365:        *ptr++=(char)hex[rest];
                    366: }
                    367: 
                    368: static void _convert(Request& r, MethodParams& params) {
1.60      moko      369:        const char *str=params.as_string(0, PARAMETER_MUST_BE_STRING).cstr();
                    370: 
1.57      misha     371:        int base_from=params.as_int(1, "base from must be integer", r);
                    372:        if(base_from < 2 || base_from > 16)
                    373:                throw Exception(PARSER_RUNTIME, 0, "base from must be an integer from 2 to 16");
                    374: 
1.60      moko      375:        int base_to=params.as_int(2, "base to must be integer", r);
                    376:        if(base_to < 2 || base_to > 16)
                    377:                throw Exception(PARSER_RUNTIME, 0, "base to must be an integer from 2 to 16");
                    378: 
1.61    ! moko      379:        while(isspace(*str))
1.60      moko      380:                str++;
                    381: 
                    382:        if(!*str)
                    383:                return;
                    384: 
                    385:        bool negative=false;
                    386:        if(str[0]=='-') {
                    387:                negative=true;
                    388:                str++;
                    389:        } else if(str[0]=='+') {
                    390:                str++;
                    391:        }
                    392: 
1.61    ! moko      393:        unsigned int value=pa_atoui(str, base_from);
1.57      misha     394: 
1.61    ! moko      395:        char result_cstr[sizeof(unsigned int)*8+1/*minus for negative number*/+1/*terminator*/];
1.60      moko      396:        char* ptr=result_cstr;
                    397:        if(negative)
                    398:                *ptr++='-';
1.57      misha     399: 
                    400:        toBase(value, base_to, ptr);
                    401:        *ptr=0;
                    402:        r.write_pass_lang(*new String(pa_strdup(result_cstr)));
                    403: }
                    404: 
1.1       parser    405: // constructor
                    406: 
1.34      paf       407: MMath::MMath(): Methoded("math") {
1.1       parser    408:        // ^FUNC(expr)  
1.28      paf       409: #define ADDX(name, X) \
                    410:        add_native_method(#name, Method::CT_STATIC, _##name, X, X)
                    411: #define ADD0(name) ADDX(name, 0)
                    412: #define ADD1(name) ADDX(name, 1)
                    413: #define ADD2(name) ADDX(name, 2)
1.1       parser    414: 
                    415:        ADD1(round);    ADD1(floor);    ADD1(ceiling);
1.3       parser    416:        ADD1(trunc);    ADD1(frac);
1.1       parser    417:        ADD1(abs);      ADD1(sign);
1.46      misha     418:        ADD1(exp);
1.48      misha     419:        ADD1(log);      ADD1(log10);
1.1       parser    420:        ADD1(sin);      ADD1(asin);     
                    421:        ADD1(cos);      ADD1(acos);     
                    422:        ADD1(tan);      ADD1(atan);
1.3       parser    423:        ADD1(degrees);  ADD1(radians);
1.1       parser    424:        ADD1(sqrt);
1.3       parser    425:        ADD1(random);
1.1       parser    426: 
1.49      misha     427:        // ^math:pow(x;y)
1.1       parser    428:        ADD2(pow);
                    429: 
1.49      misha     430:        // ^math:crypt[password;salt]
1.19      paf       431:        ADD2(crypt);
1.26      paf       432: 
1.49      misha     433:        // ^math:md5[string]
1.26      paf       434:        ADD1(md5);
1.5       parser    435: 
1.49      misha     436:        // ^math:sha1[string]
                    437:        ADD1(sha1);
                    438:        
                    439:        // ^math:crc32[string]
1.43      misha     440:        ADD1(crc32);
                    441: 
1.49      misha     442:        // ^math:uuid[]
1.29      paf       443:        ADD0(uuid);
                    444: 
1.49      misha     445:        // ^math:uid64[]
1.30      paf       446:        ADD0(uid64);
1.57      misha     447: 
                    448:        // ^math:convert[number](base-from;base-to)
                    449:        add_native_method("convert", Method::CT_STATIC, _convert, 3, 3);
1.1       parser    450: }

E-mail: