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

1.1       parser      1: /** @file
                      2:        Parser: @b math parser class.
                      3: 
1.85      moko        4:        Copyright (c) 2001-2017 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.69      moko       15: #include "pa_vfile.h"
1.1       parser     16: #include "pa_request.h"
1.19      paf        17: #include "pa_md5.h"
1.65      moko       18: #include "pa_sha2.h"
1.55      misha      19: #include "pa_random.h"
1.1       parser     20: 
1.34      paf        21: #ifdef HAVE_CRYPT
1.76      moko       22: extern "C" char *crypt(const char* , const char* );
1.20      paf        23: #endif
                     24: 
1.87    ! moko       25: volatile const char * IDENT_MATH_C="$Id: math.C,v 1.86 2017/12/07 00:23:16 moko Exp $";
1.59      moko       26: 
1.1       parser     27: // defines
                     28: 
1.20      paf        29: #define MAX_SALT 8
1.1       parser     30: 
                     31: // class
                     32: 
1.34      paf        33: class MMath: public Methoded {
1.81      moko       34: public: // Methoded
                     35:        bool used_directly() { return false; }
                     36: 
1.1       parser     37: public:
1.34      paf        38:        MMath();
1.1       parser     39: };
                     40: 
1.34      paf        41: // global variables
                     42: 
1.81      moko       43: DECLARE_CLASS_VAR(math, new MMath);
1.34      paf        44: 
1.1       parser     45: // methods
1.34      paf        46: 
                     47: static void _random(Request& r, MethodParams& params) {
1.41      paf        48:        double top=params.as_double(0, "range must be expression", r);
1.84      moko       49:        if(top<1 || top>INT32_MAX)
                     50:                throw Exception(PARSER_RUNTIME, 0, "top(%.15g) must be [1..%u]", top, INT32_MAX);
1.83      moko       51:        r.write(*new VInt(_random(uint(top))));
1.1       parser     52: }
                     53: 
                     54: 
1.20      paf        55: typedef double(*math1_func_ptr)(double);
1.3       parser     56: static double frac(double param) { return param-trunc(param); }
                     57: static double degrees(double param) { return param /PI *180; }
                     58: static double radians(double param) { return param /180 *PI; }
1.1       parser     59: 
1.34      paf        60: static void math1(Request& r, MethodParams& params, math1_func_ptr func) {
1.41      paf        61:        double param=params.as_double(0, "parameter must be expression", r);
                     62:        double result=func(param);
1.83      moko       63:        r.write(*new VDouble(result));
1.1       parser     64: }
                     65: 
                     66: #define MATH1(name) \
1.34      paf        67:        static void _##name(Request& r, MethodParams& params) {\
                     68:                math1(r, params, &name);\
1.1       parser     69:        }
1.74      moko       70: 
1.1       parser     71: #define MATH1P(name_parser, name_c) \
1.34      paf        72:        static void _##name_parser(Request& r, MethodParams& params) {\
                     73:                math1(r, params, &name_c);\
1.1       parser     74:        }
1.74      moko       75: 
                     76: MATH1(round)
                     77: MATH1(floor)
                     78: MATH1P(ceiling, ceil)
                     79: MATH1(trunc)
                     80: MATH1(frac)
                     81: MATH1P(abs, fabs)
                     82: MATH1(sign)
                     83: MATH1(exp)
                     84: MATH1(log)
                     85: MATH1(log10)
                     86: MATH1(sin)
                     87: MATH1(asin)
                     88: MATH1(cos)
                     89: MATH1(acos)
                     90: MATH1(tan)
                     91: MATH1(atan)
                     92: MATH1(degrees)
                     93: MATH1(radians)
                     94: MATH1(sqrt)
1.1       parser     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.83      moko      102:        r.write(*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:        }
1.74      moko      109: 
                    110: MATH2(pow)
1.1       parser    111: 
1.77      moko      112: inline bool is_salt_body_char(unsigned char c) {
1.73      moko      113:        return pa_isalnum(c) || c == '.' || c=='/';
1.20      paf       114: }
1.77      moko      115: 
1.34      paf       116: static size_t calc_prefix_size(const char* salt) {
1.37      paf       117:        if(strlen(salt)) {
1.39      paf       118:                if(!is_salt_body_char((unsigned char)salt[0])) { // $...  {...
1.34      paf       119:                        const char* cur=salt+1; // skip
1.39      paf       120:                        while(is_salt_body_char((unsigned char)*cur++)) // ...$  ...}
1.20      paf       121:                                ;
                    122:                        return cur-salt;
                    123:                } else
                    124:                        return 0;
                    125:        } else
                    126:                return 0;
                    127: }
1.34      paf       128: static void _crypt(Request& r, MethodParams& params) {
                    129:        const char* password=params.as_string(0, "password must be string").cstr();
                    130:        const char* maybe_bodyless_salt=params.as_string(1, "salt must be string").cstr();
1.20      paf       131: 
                    132:        size_t prefix_size=calc_prefix_size(maybe_bodyless_salt);
1.34      paf       133:        const char* normal_salt;
1.20      paf       134:        char normalize_buf[MAX_STRING];
                    135:        if(prefix_size==strlen(maybe_bodyless_salt)) { // bodyless?
                    136:                strncpy(normalize_buf, maybe_bodyless_salt, MAX_STRING-MAX_SALT-1);
                    137:                char *cur=normalize_buf+strlen(normalize_buf);
                    138:                // sould add up MAX_SALT random chars
                    139:                static unsigned char itoa64[] =         /* 0 ... 63 => ASCII - 64 */
                    140:                "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
                    141:                for(int i=0; i<MAX_SALT; i++)
                    142:                        *cur++=itoa64[_random(64)];
                    143:                *cur=0;
                    144:                normal_salt=normalize_buf;
                    145:        } else
                    146:                normal_salt=maybe_bodyless_salt;
1.19      paf       147: 
1.54      misha     148:        /* FreeBSD style MD5 string 
                    149:        */
                    150:        if(strncmp(normal_salt, PA_MD5PW_ID, PA_MD5PW_IDLEN) == 0) {
1.19      paf       151:                const size_t sample_size=120;
1.34      paf       152:                char *sample_buf=new(PointerFreeGC) char[sample_size];
                    153:                pa_MD5Encode((const unsigned char *)password,
                    154:                                (const unsigned char *)normal_salt, sample_buf, sample_size);
                    155:                String sample(sample_buf);
1.83      moko      156:                r.write(sample);
1.54      misha     157:        } else {
1.20      paf       158: #ifdef HAVE_CRYPT
1.34      paf       159:                const char* static_sample_buf=crypt(password, normal_salt);
                    160:                if(!static_sample_buf  // nothing generated
                    161:                        || !static_sample_buf[0] // generated nothing
                    162:                        || strncmp(static_sample_buf, normal_salt, prefix_size)!=0) // salt prefix not preserved
1.45      misha     163:                        throw Exception(PARSER_RUNTIME,
1.34      paf       164:                                0,
                    165:                                "crypt on this platform does not support '%.*s' salt prefix", prefix_size, normal_salt);
1.20      paf       166:                
1.83      moko      167:                r.write(String(pa_strdup(static_sample_buf)));
1.20      paf       168: #else
1.45      misha     169:                throw Exception(PARSER_RUNTIME,
1.34      paf       170:                        0,
1.19      paf       171:                        "salt must start with '" PA_MD5PW_ID "'");
1.20      paf       172: #endif
                    173:        }
1.19      paf       174: }
                    175: 
1.34      paf       176: static void _md5(Request& r, MethodParams& params) {
1.72      moko      177:        const char *string=params.as_string(0, PARAMETER_MUST_BE_STRING).cstr_to_string_body_untaint(String::L_AS_IS, r.connection(false), &r.charsets).cstr();
1.27      paf       178: 
                    179:        PA_MD5_CTX context;
                    180:        unsigned char digest[16];
1.34      paf       181:        pa_MD5Init(&context);
                    182:        pa_MD5Update(&context, (const unsigned char*)string, strlen(string));
                    183:        pa_MD5Final(digest, &context);
1.27      paf       184: 
1.83      moko      185:        r.write(*new String(hex_string(digest, sizeof(digest), false)));
1.26      paf       186: }
                    187: 
1.49      misha     188: 
                    189: //SHA-1:
                    190: 
1.50      misha     191: struct SHA1Context {
1.54      misha     192:        unsigned Message_Digest[5], Length_Low, Length_High;
                    193:        unsigned int Message_Block[64];
                    194:        int Message_Block_Index, Computed, Corrupted;
1.50      misha     195: };
1.49      misha     196: 
                    197: #define SHA1CircularShift(bits,word) ((((word) << (bits)) & 0xFFFFFFFF)|((word) >> (32-(bits))))
                    198: void SHA1ProcessMessageBlock(SHA1Context *);
                    199: void SHA1PadMessage(SHA1Context *);
1.50      misha     200: void SHA1Reset(SHA1Context *context) {
1.54      misha     201:        context->Length_Low = context->Length_High = context->Message_Block_Index = 0;
                    202:        context->Message_Digest[0]      = 0x67452301;
                    203:        context->Message_Digest[1]      = 0xEFCDAB89;
                    204:        context->Message_Digest[2]      = 0x98BADCFE;
                    205:        context->Message_Digest[3]      = 0x10325476;
                    206:        context->Message_Digest[4]      = 0xC3D2E1F0;
                    207:        context->Computed = context->Corrupted  = 0;
1.50      misha     208: }
1.49      misha     209: 
1.50      misha     210: int SHA1Result(SHA1Context *context) {
1.54      misha     211:        if (context->Corrupted)
                    212:                return 0;
                    213:        if (!context->Computed) {
                    214:                SHA1PadMessage(context);
                    215:                context->Computed = 1;
                    216:        }
                    217:        return 1;
                    218: }
                    219: 
                    220: void SHA1Input(SHA1Context *context, const unsigned char *message_array, unsigned length) {
                    221:        if (!length)
                    222:                return;
                    223:        if (context->Computed || context->Corrupted) {
                    224:                context->Corrupted = 1;
                    225:                return;
                    226:        }
                    227: 
                    228:        while(length-- && !context->Corrupted) {
                    229:                context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF);
                    230:                context->Length_Low += 8;
                    231:                context->Length_Low &= 0xFFFFFFFF;
                    232:                if (!context->Length_Low && !(context->Length_High=((1+context->Length_High)&0xFFFFFFFF)))
                    233:                        context->Corrupted = 1; // too long message
                    234:                if (context->Message_Block_Index == 64)
                    235:                        SHA1ProcessMessageBlock(context);
                    236:                message_array++;
1.49      misha     237:        }
1.50      misha     238: }
1.49      misha     239: 
1.50      misha     240: void SHA1ProcessMessageBlock(SHA1Context *context) {
1.54      misha     241:        const unsigned K[] = {0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 };
                    242:        int t;
                    243:        unsigned    temp, W[80], buf[5];
                    244:        unsigned &A=buf[0], &B=buf[1], &C=buf[2], &D=buf[3], &E=buf[4];
1.50      misha     245: 
1.54      misha     246:        for(t = 0; t < 16; t++)
                    247:                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     248: 
1.54      misha     249:        for(t = 16; t < 80; t++)
                    250:                W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
1.49      misha     251: 
1.54      misha     252:        memcpy (buf, context->Message_Digest, sizeof(buf));
                    253:        for(t = 0; t < 20; t++) {
                    254:                temp =  (SHA1CircularShift(5,A) + ((B & C) | ((~B) & D)) + E + W[t] + K[0]) & 0xFFFFFFFF;
                    255:                E = D; D = C;
                    256:                C = SHA1CircularShift(30,B);
                    257:                B = A; A = temp;
1.49      misha     258:        }
                    259: 
1.54      misha     260:        for(t = 20; t < 40; t++) {
                    261:                temp = (SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]) & 0xFFFFFFFF;
                    262:                E = D; D = C;
                    263:                C = SHA1CircularShift(30,B);
                    264:                B = A; A = temp;
1.49      misha     265:        }
                    266: 
1.54      misha     267:        for(t = 40; t < 60; t++) {
                    268:                temp = (SHA1CircularShift(5,A) + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]) & 0xFFFFFFFF;
                    269:                E = D; D = C;
                    270:                C = SHA1CircularShift(30,B);
                    271:                B = A; A = temp;
1.49      misha     272:        }
                    273: 
1.54      misha     274:        for(t = 60; t < 80; t++) {
                    275:                temp = (SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3]) & 0xFFFFFFFF;
                    276:                E = D; D = C;
                    277:                C = SHA1CircularShift(30,B);
                    278:                B = A; A = temp;
1.49      misha     279:        }
                    280: 
1.54      misha     281:        for (t = 0; t < 5; t++)
                    282:                context->Message_Digest[t] = (context->Message_Digest[t] + buf[t]) & 0xFFFFFFFF;
1.50      misha     283: 
1.54      misha     284:        context->Message_Block_Index = 0;
1.50      misha     285: }
1.49      misha     286: 
1.50      misha     287: void SHA1PadMessage(SHA1Context *context) {
1.54      misha     288:        context->Message_Block[context->Message_Block_Index++] = 0x80;
1.50      misha     289:        if (context->Message_Block_Index > 56) {
                    290:                //was 55, one shift
1.54      misha     291:                while(context->Message_Block_Index < 64)
                    292:                        context->Message_Block[context->Message_Block_Index++] = 0;
                    293:                SHA1ProcessMessageBlock(context);
                    294:                while(context->Message_Block_Index < 56)
                    295:                        context->Message_Block[context->Message_Block_Index++] = 0;
1.50      misha     296:        } else
1.54      misha     297:                while(context->Message_Block_Index < 56)
                    298:                        context->Message_Block[context->Message_Block_Index++] = 0;
                    299:        context->Message_Block[56] = (context->Length_High >> 24) & 0xFF;
                    300:        context->Message_Block[57] = (context->Length_High >> 16) & 0xFF;
                    301:        context->Message_Block[58] = (context->Length_High >> 8) & 0xFF;
                    302:        context->Message_Block[59] = (context->Length_High) & 0xFF;
                    303:        context->Message_Block[60] = (context->Length_Low >> 24) & 0xFF;
                    304:        context->Message_Block[61] = (context->Length_Low >> 16) & 0xFF;
                    305:        context->Message_Block[62] = (context->Length_Low >> 8) & 0xFF;
                    306:        context->Message_Block[63] = (context->Length_Low) & 0xFF;
                    307:        SHA1ProcessMessageBlock(context);
1.50      misha     308: }
1.49      misha     309: 
1.62      moko      310: #ifdef PA_BIG_ENDIAN
                    311: #define SWAP(n) (n)
                    312: #else
                    313: #define SWAP(n) (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
                    314: #endif
                    315: 
1.64      moko      316: void SHA1ReadDigest(void *buf, SHA1Context *c)
1.62      moko      317: {
1.64      moko      318:        if(!SHA1Result(c))
1.62      moko      319:                throw Exception (PARSER_RUNTIME, 0, "Can not compute SHA1");
                    320: 
1.64      moko      321:        ((uint32_t *)buf)[0] = SWAP(c->Message_Digest[0]);
                    322:        ((uint32_t *)buf)[1] = SWAP(c->Message_Digest[1]);
                    323:        ((uint32_t *)buf)[2] = SWAP(c->Message_Digest[2]);
                    324:        ((uint32_t *)buf)[3] = SWAP(c->Message_Digest[3]);
                    325:        ((uint32_t *)buf)[4] = SWAP(c->Message_Digest[4]);
1.62      moko      326: }
                    327: 
1.54      misha     328: static void _sha1(Request& r, MethodParams& params) {
1.72      moko      329:        const char *string = params.as_string(0, PARAMETER_MUST_BE_STRING).cstr_to_string_body_untaint(String::L_AS_IS, r.connection(false), &r.charsets).cstr();
1.49      misha     330: 
1.54      misha     331:        SHA1Context c;
1.64      moko      332:        unsigned char digest[20];
1.54      misha     333:        SHA1Reset (&c);
                    334:        SHA1Input (&c, (const unsigned char*)string, strlen(string));
1.64      moko      335:        SHA1ReadDigest(digest, &c);
1.54      misha     336: 
1.83      moko      337:        r.write(*new String(hex_string(digest, sizeof(digest), false)));
1.62      moko      338: }
                    339: 
1.87    ! moko      340: String::C getData(Value& vdata, Request& r){
        !           341:        if(const String* sdata=vdata.get_string()){
        !           342:                String::Body body=sdata->cstr_to_string_body_untaint(String::L_AS_IS, r.connection(false), &r.charsets); // explode content, honor tainting changes
        !           343:                return String::C(body.cstr(), body.length());
        !           344:        } else {
        !           345:                VFile *file=vdata.as_vfile(String::L_AS_IS);
        !           346:                return String::C(file->value_ptr(),file->value_size());
        !           347:        }
        !           348: }
        !           349: 
1.64      moko      350: void memxor(char *dest, const char *src, size_t n){
                    351:        for (;n>0;n--) *dest++ ^= *src++;
                    352: }
                    353: 
1.62      moko      354: #define IPAD 0x36
                    355: #define OPAD 0x5c
                    356: 
1.65      moko      357: #define HMAC(key,init,update,final,blocklen,digestlen){                                \
1.64      moko      358:        unsigned char tempdigest[digestlen], keydigest[digestlen];              \
                    359:        size_t keylen=strlen(key);                                              \
1.65      moko      360:        /* Reduce the key's size, so that it becomes <= blocklen bytes. */      \
                    361:        if (keylen > blocklen){                                                 \
1.64      moko      362:                init(&c);                                                       \
                    363:                update(&c,(const unsigned char*)hmac, keylen);                  \
                    364:                final(keydigest, &c);                                           \
                    365:                key = (char *)keydigest;                                        \
                    366:                keylen = digestlen;                                             \
                    367:        }                                                                       \
                    368:        /* Compute TEMP from KEY and STRING. */                                 \
1.65      moko      369:        char block[blocklen];                                                   \
                    370:        memset (block, IPAD, blocklen);                                         \
1.64      moko      371:        memxor (block, key, keylen);                                            \
                    372:        init(&c);                                                               \
1.65      moko      373:        update(&c, (const unsigned char*)block, blocklen);                      \
1.69      moko      374:        update(&c, (const unsigned char*)data.str, data.length);                \
1.64      moko      375:        final(tempdigest, &c);                                                  \
                    376:        /* Compute result from KEY and TEMP. */                                 \
1.65      moko      377:        memset (block, OPAD, blocklen);                                         \
1.64      moko      378:        memxor (block, key, keylen);                                            \
                    379:        init(&c);                                                               \
1.65      moko      380:        update(&c, (const unsigned char*)block, blocklen);                      \
1.64      moko      381:        update(&c, (const unsigned char*)tempdigest, digestlen);                \
1.62      moko      382: }
1.55      misha     383: 
1.62      moko      384: static void _digest(Request& r, MethodParams& params) {
1.63      moko      385:        const String &smethod = params.as_string(0, PARAMETER_MUST_BE_STRING);
1.69      moko      386: 
1.87    ! moko      387:        String::C data=getData(params.as_no_junction(1, "parameter must be string or file"), r);
1.62      moko      388: 
1.65      moko      389:        enum Method { M_MD5, M_SHA1, M_SHA256, M_SHA512 } method;
1.62      moko      390: 
1.63      moko      391:        if (smethod == "md5") method = M_MD5;
                    392:        else if (smethod == "sha1" ) method = M_SHA1;
1.65      moko      393:        else if (smethod == "sha256" ) method = M_SHA256;
                    394:        else if (smethod == "sha512" ) method = M_SHA512;
1.86      moko      395:        else throw Exception(PARSER_RUNTIME, &smethod, "must be 'md5' or 'sha1' or 'sha256' or 'sha512'");
1.62      moko      396: 
                    397:        const char *hmac=0;
1.63      moko      398:        enum Format { F_HEX, F_BASE64 } format = F_HEX;
1.62      moko      399: 
                    400:        if(params.count() == 3)
                    401:                if(HashStringValue* options=params.as_hash(2)) {
                    402:                        int valid_options=0;
                    403:                        if(Value* value=options->get("hmac")) {
                    404:                                hmac=value->as_string().cstr();
                    405:                                valid_options++;
                    406:                        }
1.63      moko      407:                        if(Value* value=options->get("format")) {
                    408:                                const String& sformat=value->as_string();
                    409:                                if (sformat == "hex") format = F_HEX;
                    410:                                else if (sformat == "base64" ) format = F_BASE64;
                    411:                                else throw Exception(PARSER_RUNTIME, &sformat, "must be 'hex' or 'base64'");
1.62      moko      412:                                valid_options++;
                    413:                        }
                    414:                        if(valid_options!=options->count())
                    415:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    416:                }
                    417: 
                    418:        String::C digest;
                    419: 
1.63      moko      420:        if(method == M_MD5){
1.64      moko      421:                PA_MD5_CTX c;
                    422:                if(hmac){
1.65      moko      423:                        HMAC(hmac, pa_MD5Init, pa_MD5Update, pa_MD5Final, 64, 16);
1.64      moko      424:                } else {
                    425:                        pa_MD5Init(&c);
1.69      moko      426:                        pa_MD5Update(&c, (const unsigned char*)data.str, data.length);
1.64      moko      427:                }
1.62      moko      428:                char *str=(char *)pa_malloc(16);
1.64      moko      429:                pa_MD5Final((unsigned char *)str, &c);
1.62      moko      430:                digest = String::C(str, 16);
                    431:        }
                    432: 
1.63      moko      433:        if(method == M_SHA1){
1.62      moko      434:                SHA1Context c;
                    435:                if(hmac){
1.65      moko      436:                        HMAC(hmac, SHA1Reset, SHA1Input, SHA1ReadDigest, 64, 20);
1.62      moko      437:                } else {
1.64      moko      438:                        SHA1Reset(&c);
1.69      moko      439:                        SHA1Input(&c, (const unsigned char*)data.str, data.length);
1.62      moko      440:                }
                    441:                char *str=(char *)pa_malloc(20);
1.64      moko      442:                SHA1ReadDigest(str, &c);
1.62      moko      443:                digest = String::C(str, 20);
                    444:        }
1.49      misha     445: 
1.65      moko      446:        if(method == M_SHA256){
                    447:                SHA256_CTX c;
                    448:                if(hmac){
                    449:                        HMAC(hmac, pa_SHA256_Init, pa_SHA256_Update, pa_SHA256_Final, 64, SHA256_DIGEST_LENGTH);
                    450:                } else {
                    451:                        pa_SHA256_Init(&c);
1.69      moko      452:                        pa_SHA256_Update(&c, (const unsigned char*)data.str, data.length);
1.65      moko      453:                }
                    454:                char *str=(char *)pa_malloc(SHA256_DIGEST_LENGTH);
                    455:                pa_SHA256_Final((unsigned char *)str, &c);
                    456:                digest = String::C(str, SHA256_DIGEST_LENGTH);
                    457:        }
                    458: 
                    459:        if(method == M_SHA512){
                    460:                SHA512_CTX c;
                    461:                if(hmac){
                    462:                        HMAC(hmac, pa_SHA512_Init, pa_SHA512_Update, pa_SHA512_Final, 128, SHA512_DIGEST_LENGTH);
                    463:                } else {
                    464:                        pa_SHA512_Init(&c);
1.69      moko      465:                        pa_SHA512_Update(&c, (const unsigned char*)data.str, data.length);
1.65      moko      466:                }
                    467:                char *str=(char *)pa_malloc(SHA512_DIGEST_LENGTH);
                    468:                pa_SHA512_Final((unsigned char *)str, &c);
                    469:                digest = String::C(str, SHA512_DIGEST_LENGTH);
                    470:        }
                    471: 
1.63      moko      472:        if(format == F_HEX){
1.83      moko      473:                r.write(*new String(hex_string((unsigned char *)digest.str, digest.length, false)));
1.62      moko      474:        }
1.63      moko      475:        if(format == F_BASE64){
1.83      moko      476:                r.write(*new String(pa_base64_encode(digest.str, digest.length)));
1.62      moko      477:        }
1.54      misha     478: }
1.49      misha     479: 
1.55      misha     480: static void _uuid(Request& r, MethodParams& /*params*/) {
1.83      moko      481:        r.write(*new String(get_uuid_cstr()));
1.28      paf       482: }
                    483: 
1.34      paf       484: static void _uid64(Request& r, MethodParams& /*params*/) {
1.30      paf       485:        unsigned char id[64/8];
                    486:        random(&id, sizeof(id));
                    487: 
1.83      moko      488:        r.write(*new String(hex_string(id, sizeof(id), true)));
1.30      paf       489: }
                    490: 
1.43      misha     491: static void _crc32(Request& r, MethodParams& params) {
1.51      misha     492:        const char *string=params.as_string(0, PARAMETER_MUST_BE_STRING).cstr();
1.83      moko      493:        r.write(*new VInt(pa_crc32(string, strlen(string))));
1.43      misha     494: }
                    495: 
1.87    ! moko      496: static const char* abc_hex="0123456789ABCDEF";
        !           497: 
        !           498: static unsigned char hex_lookup[256]={
        !           499:         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        !           500:         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        !           501:         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        !           502:         0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0,
        !           503:         0,10,11,12,13,14,15, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        !           504:         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        !           505:         0,10,11,12,13,14,15, 0, 0, 0, 0, 0, 0, 0, 0, 0
        !           506: };
        !           507: 
        !           508: static unsigned char abc_lookup[256]={};
        !           509: static unsigned char abc_256_lookup[256]={};
        !           510: 
        !           511: inline unsigned char *init_abc_256(){
        !           512:        if(!abc_256_lookup[255]) for(int i=0; i<256; i++) abc_256_lookup[i] = (unsigned char)i;
        !           513:        return abc_256_lookup;
1.57      misha     514: }
                    515: 
                    516: static void _convert(Request& r, MethodParams& params) {
1.87    ! moko      517:        String::C data=getData(params.as_no_junction(0, "parameter must be string or file"), r);
1.60      moko      518: 
1.87    ! moko      519:        bool abc_mode = true;
        !           520:        unsigned char *lookup;
        !           521:        const char *abc_from;
        !           522:        int base_from;
        !           523: 
        !           524:        if(params[1].is_string()){
        !           525:                abc_from = params[1].get_string()->cstr();
        !           526:                base_from = strlen(abc_from);
        !           527:                if(base_from < 2)
        !           528:                        throw Exception(PARSER_RUNTIME, 0, "alphabet 'from' must contain at least 2 characters");
        !           529:                lookup = abc_lookup;
        !           530:                memset(abc_lookup,0,sizeof(abc_lookup));
        !           531:                for(int i=0; i<base_from; i++) abc_lookup[(unsigned char)abc_from[i]] = (unsigned char)i;
        !           532:        } else {
        !           533:                base_from=params.as_int(1, "base 'from' must be integer or string", r);
        !           534:                if(base_from < 2 || base_from > 16 && base_from != 256)
        !           535:                        throw Exception(PARSER_RUNTIME, 0, "base 'from' must be an integer from 2 to 16 or 256");
        !           536:                if (base_from == 256){
        !           537:                        abc_from = "";
        !           538:                        lookup = init_abc_256();
        !           539:                } else {
        !           540:                        abc_mode = false;
        !           541:                        abc_from = abc_hex;
        !           542:                        lookup = hex_lookup;
        !           543:                }
        !           544:        }
1.57      misha     545: 
1.87    ! moko      546:        const char *abc_to;
        !           547:        int base_to;
1.60      moko      548: 
1.87    ! moko      549:        if(params[2].is_string()){
        !           550:                abc_to=params[2].get_string()->cstr();
        !           551:                base_to=strlen(abc_to);
        !           552:                if(base_to < 2)
        !           553:                        throw Exception(PARSER_RUNTIME, 0, "alphabet 'to' must contain at least 2 characters");
        !           554:        } else {
        !           555:                base_to=params.as_int(2, "base 'to' must be integer or string", r);
        !           556:                if(base_to < 2 || base_to > 16 && base_to != 256)
        !           557:                        throw Exception(PARSER_RUNTIME, 0, "base 'to' must be an integer from 2 to 16 or 256");
        !           558:                if (base_to == 256){
        !           559:                        abc_to = (char *)init_abc_256();
        !           560:                } else {
        !           561:                        abc_to = abc_hex;
        !           562:                }
        !           563:        }
        !           564: 
        !           565:        VFile* result_file = 0;
1.60      moko      566: 
1.87    ! moko      567:        if(params.count() == 4)
        !           568:                if(HashStringValue* options=params.as_hash(3)) {
        !           569:                        int valid_options=0;
        !           570:                        if(Value* value=options->get("format")) {
        !           571:                                const String& sformat=value->as_string();
        !           572:                                if (sformat == "file" ) result_file = new VFile;
        !           573:                                else if (sformat != "string") throw Exception(PARSER_RUNTIME, &sformat, "must be 'string' or 'file'");
        !           574:                                valid_options++;
        !           575:                        }
        !           576:                        if(valid_options!=options->count())
        !           577:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
        !           578:                }
1.60      moko      579: 
                    580:        bool negative=false;
1.87    ! moko      581:        bool sign=false;
        !           582: 
        !           583:        // converting digits to their numeric values
        !           584: 
        !           585:        unsigned char *src=(unsigned char *)pa_strdup(data.str, data.length);
        !           586:        const unsigned char *src_end = src + data.length;
        !           587: 
        !           588:        unsigned char *c;
        !           589: 
        !           590:        if(abc_mode){
        !           591: 
        !           592:                for(c=src;c<src_end;c++){
        !           593:                        unsigned char digit=lookup[*c];
        !           594:                        if(!digit && *c != abc_from[0])
        !           595:                                throw Exception("number.format", 0, "'%c' is invalid digit", *c);
        !           596:                        *c=digit;
        !           597:                }
        !           598: 
        !           599:        } else {
        !           600:                // numbers mode, allow whitespace and sign
        !           601: 
        !           602:                while(isspace(*src))
        !           603:                        src++;
        !           604: 
        !           605:                if(src[0]=='-') {
        !           606:                        negative=true;
        !           607:                        sign=true;
        !           608:                        src++;
        !           609:                } else if(src[0]=='+') {
        !           610:                        sign=true;
        !           611:                        src++;
        !           612:                }
        !           613: 
        !           614:                for(c=src;c<src_end;c++) {
        !           615:                        unsigned char digit=lookup[*c];
        !           616:                        if(!digit && *c != abc_from[0] || digit>=base_from) {
        !           617:                                for(unsigned char *s=c;s<src_end;s++)
        !           618:                                        if(!isspace(*s))
        !           619:                                                throw Exception("number.format", 0, "'%c' is invalid digit", *s);
        !           620:                                src_end=c;
        !           621:                                break;
        !           622:                        }
        !           623:                        *c=digit;
        !           624:                }
        !           625: 
1.60      moko      626:        }
                    627: 
1.87    ! moko      628:        if(src==src_end){
        !           629:                if(sign)
        !           630:                        throw Exception("number.format", 0,  "'%c' is invalid number", negative ? '-' : '+');
        !           631:                if(result_file)
        !           632:                        r.write(*result_file);
        !           633:                return;
        !           634:        }
        !           635: 
        !           636:        // core
        !           637: 
        !           638:        Array<char> remainders(round(data.length * log2(base_from) / log2(base_to)) + 1);
1.57      misha     639: 
1.87    ! moko      640:        do {
        !           641:                int carry = 0;
        !           642:                unsigned char *dst = src;
        !           643:                for (c=src; c<src_end; c++) {
        !           644:                        carry = carry * base_from + *c;
        !           645:                        if (carry >= base_to) {
        !           646:                                *(dst++) = carry / base_to;
        !           647:                                carry %= base_to;
        !           648:                        } else if (dst > src) {
        !           649:                                *(dst++) = 0;
        !           650:                        }
        !           651:                }
        !           652:                src_end = dst;
        !           653:                remainders += abc_to[carry];
        !           654:        } while (src_end > src);
        !           655: 
        !           656:        // result processing
        !           657: 
        !           658:        size_t result_length = negative + remainders.count();
        !           659:        char *result_str = (char *)pa_malloc_atomic(result_length+1);
1.60      moko      660:        if(negative)
1.87    ! moko      661:                result_str[0] = '-';
        !           662:        for(int i=0; i<remainders.count(); i++)
        !           663:                result_str[result_length - 1 - i] = remainders[i];
        !           664:        result_str[result_length]='\0';
        !           665: 
        !           666:        if(result_file){
        !           667:                result_file->set(true/*tainted*/, 0 /*binary*/, result_str, result_length, 0, 0, &r);
        !           668:                r.write(*result_file);
        !           669:        } else {
        !           670:                r.write(*new String(result_str)); // no length as there can be '\0' inside
        !           671:        }
1.57      misha     672: }
                    673: 
1.1       parser    674: // constructor
                    675: 
1.34      paf       676: MMath::MMath(): Methoded("math") {
1.1       parser    677:        // ^FUNC(expr)  
1.28      paf       678: #define ADDX(name, X) \
                    679:        add_native_method(#name, Method::CT_STATIC, _##name, X, X)
                    680: #define ADD0(name) ADDX(name, 0)
                    681: #define ADD1(name) ADDX(name, 1)
                    682: #define ADD2(name) ADDX(name, 2)
1.1       parser    683: 
                    684:        ADD1(round);    ADD1(floor);    ADD1(ceiling);
1.3       parser    685:        ADD1(trunc);    ADD1(frac);
1.1       parser    686:        ADD1(abs);      ADD1(sign);
1.46      misha     687:        ADD1(exp);
1.48      misha     688:        ADD1(log);      ADD1(log10);
1.87    ! moko      689:        ADD1(sin);      ADD1(asin);
        !           690:        ADD1(cos);      ADD1(acos);
1.1       parser    691:        ADD1(tan);      ADD1(atan);
1.3       parser    692:        ADD1(degrees);  ADD1(radians);
1.1       parser    693:        ADD1(sqrt);
1.3       parser    694:        ADD1(random);
1.1       parser    695: 
1.49      misha     696:        // ^math:pow(x;y)
1.1       parser    697:        ADD2(pow);
                    698: 
1.49      misha     699:        // ^math:crypt[password;salt]
1.19      paf       700:        ADD2(crypt);
1.26      paf       701: 
1.49      misha     702:        // ^math:md5[string]
1.26      paf       703:        ADD1(md5);
1.5       parser    704: 
1.49      misha     705:        // ^math:sha1[string]
                    706:        ADD1(sha1);
                    707:        
1.71      moko      708:        // ^math:digest[method;string|file;options]
1.62      moko      709:        add_native_method("digest", Method::CT_STATIC, _digest, 2, 3);
                    710:        
1.49      misha     711:        // ^math:crc32[string]
1.43      misha     712:        ADD1(crc32);
                    713: 
1.49      misha     714:        // ^math:uuid[]
1.29      paf       715:        ADD0(uuid);
                    716: 
1.49      misha     717:        // ^math:uid64[]
1.30      paf       718:        ADD0(uid64);
1.57      misha     719: 
1.87    ! moko      720:        // ^math:convert[number|file](base-from)|[abc_from](base-to)|[abc_to][options]
        !           721:        add_native_method("convert", Method::CT_STATIC, _convert, 3, 4);
1.1       parser    722: }

E-mail: