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

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.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.67      moko       22: extern "C" char *crypt(const char* , const char* );
1.20      paf        23: #endif
                     24: 
1.72    ! moko       25: volatile const char * IDENT_MATH_C="$Id: math.C,v 1.71 2013/08/22 14:35:30 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.1       parser     34: public:
1.34      paf        35:        MMath();
1.5       parser     36: 
1.1       parser     37: public: // Methoded
1.15      paf        38:        bool used_directly() { return false; }
1.1       parser     39: };
                     40: 
1.34      paf        41: // global variables
                     42: 
                     43: DECLARE_CLASS_VAR(math, 0 /*fictive*/, new MMath);
                     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.34      paf        49:        if(top<=0 || top>MAX_UINT)
1.45      misha      50:                throw Exception(PARSER_RUNTIME,
1.34      paf        51:                        0,
                     52:                        "top(%g) must be [1..%u]", top, MAX_UINT);
1.1       parser     53:        
1.34      paf        54:        r.write_no_lang(*new VInt(_random(uint(top))));
1.1       parser     55: }
                     56: 
                     57: 
1.20      paf        58: typedef double(*math1_func_ptr)(double);
1.3       parser     59: static double frac(double param) { return param-trunc(param); }
                     60: static double degrees(double param) { return param /PI *180; }
                     61: static double radians(double param) { return param /180 *PI; }
1.1       parser     62: 
1.34      paf        63: static void math1(Request& r, MethodParams& params, math1_func_ptr func) {
1.41      paf        64:        double param=params.as_double(0, "parameter must be expression", r);
                     65:        double result=func(param);
1.34      paf        66:        r.write_no_lang(*new VDouble(result));
1.1       parser     67: }
                     68: 
                     69: #define MATH1(name) \
1.34      paf        70:        static void _##name(Request& r, MethodParams& params) {\
                     71:                math1(r, params, &name);\
1.1       parser     72:        }
                     73: #define MATH1P(name_parser, name_c) \
1.34      paf        74:        static void _##name_parser(Request& r, MethodParams& params) {\
                     75:                math1(r, params, &name_c);\
1.1       parser     76:        }
                     77: MATH1(round);  MATH1(floor);   MATH1P(ceiling, ceil);
1.3       parser     78: MATH1(trunc);  MATH1(frac);
1.1       parser     79: MATH1P(abs, fabs);     MATH1(sign);
1.46      misha      80: MATH1(exp);    
1.48      misha      81: MATH1(log);    MATH1(log10);
1.1       parser     82: MATH1(sin);    MATH1(asin);    
                     83: MATH1(cos);    MATH1(acos);    
                     84: MATH1(tan);    MATH1(atan);
1.3       parser     85: MATH1(degrees);        MATH1(radians);
1.1       parser     86: MATH1(sqrt);
                     87: 
                     88: 
                     89: typedef double (*math2_func_ptr)(double, double);
1.34      paf        90: static void math2(Request& r, MethodParams& params, math2_func_ptr func) {
1.41      paf        91:        double a=params.as_double(0, "parameter must be expression", r);
                     92:        double b=params.as_double(1, "parameter must be expression", r);
                     93:        double result=func(a, b);
1.34      paf        94:        r.write_no_lang(*new VDouble(result));
1.1       parser     95: }
                     96: 
                     97: #define MATH2(name) \
1.34      paf        98:        static void _##name(Request& r, MethodParams& params) {\
                     99:                math2(r, params, &name);\
1.1       parser    100:        }
                    101: MATH2(pow);
                    102: 
1.20      paf       103: inline bool is_salt_body_char(int c) {
                    104:        return isalnum(c) || c == '.' || c=='/';
                    105: }
1.34      paf       106: static size_t calc_prefix_size(const char* salt) {
1.37      paf       107:        if(strlen(salt)) {
1.39      paf       108:                if(!is_salt_body_char((unsigned char)salt[0])) { // $...  {...
1.34      paf       109:                        const char* cur=salt+1; // skip
1.39      paf       110:                        while(is_salt_body_char((unsigned char)*cur++)) // ...$  ...}
1.20      paf       111:                                ;
                    112:                        return cur-salt;
                    113:                } else
                    114:                        return 0;
                    115:        } else
                    116:                return 0;
                    117: }
1.34      paf       118: static void _crypt(Request& r, MethodParams& params) {
                    119:        const char* password=params.as_string(0, "password must be string").cstr();
                    120:        const char* maybe_bodyless_salt=params.as_string(1, "salt must be string").cstr();
1.20      paf       121: 
                    122:        size_t prefix_size=calc_prefix_size(maybe_bodyless_salt);
1.34      paf       123:        const char* normal_salt;
1.20      paf       124:        char normalize_buf[MAX_STRING];
                    125:        if(prefix_size==strlen(maybe_bodyless_salt)) { // bodyless?
                    126:                strncpy(normalize_buf, maybe_bodyless_salt, MAX_STRING-MAX_SALT-1);
                    127:                char *cur=normalize_buf+strlen(normalize_buf);
                    128:                // sould add up MAX_SALT random chars
                    129:                static unsigned char itoa64[] =         /* 0 ... 63 => ASCII - 64 */
                    130:                "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
                    131:                for(int i=0; i<MAX_SALT; i++)
                    132:                        *cur++=itoa64[_random(64)];
                    133:                *cur=0;
                    134:                normal_salt=normalize_buf;
                    135:        } else
                    136:                normal_salt=maybe_bodyless_salt;
1.19      paf       137: 
1.54      misha     138:        /* FreeBSD style MD5 string 
                    139:        */
                    140:        if(strncmp(normal_salt, PA_MD5PW_ID, PA_MD5PW_IDLEN) == 0) {
1.19      paf       141:                const size_t sample_size=120;
1.34      paf       142:                char *sample_buf=new(PointerFreeGC) char[sample_size];
                    143:                pa_MD5Encode((const unsigned char *)password,
                    144:                                (const unsigned char *)normal_salt, sample_buf, sample_size);
                    145:                String sample(sample_buf);
                    146:                r.write_pass_lang(sample);
1.54      misha     147:        } else {
1.20      paf       148: #ifdef HAVE_CRYPT
1.34      paf       149:                const char* static_sample_buf=crypt(password, normal_salt);
                    150:                if(!static_sample_buf  // nothing generated
                    151:                        || !static_sample_buf[0] // generated nothing
                    152:                        || strncmp(static_sample_buf, normal_salt, prefix_size)!=0) // salt prefix not preserved
1.45      misha     153:                        throw Exception(PARSER_RUNTIME,
1.34      paf       154:                                0,
                    155:                                "crypt on this platform does not support '%.*s' salt prefix", prefix_size, normal_salt);
1.20      paf       156:                
1.34      paf       157:                r.write_pass_lang(String(pa_strdup(static_sample_buf)));
1.20      paf       158: #else
1.45      misha     159:                throw Exception(PARSER_RUNTIME,
1.34      paf       160:                        0,
1.19      paf       161:                        "salt must start with '" PA_MD5PW_ID "'");
1.20      paf       162: #endif
                    163:        }
1.19      paf       164: }
                    165: 
1.34      paf       166: static void _md5(Request& r, MethodParams& params) {
1.72    ! moko      167:        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       168: 
                    169:        PA_MD5_CTX context;
                    170:        unsigned char digest[16];
1.34      paf       171:        pa_MD5Init(&context);
                    172:        pa_MD5Update(&context, (const unsigned char*)string, strlen(string));
                    173:        pa_MD5Final(digest, &context);
1.27      paf       174: 
1.34      paf       175:        r.write_pass_lang(*new String(hex_string(digest, sizeof(digest), false)));
1.26      paf       176: }
                    177: 
1.49      misha     178: 
                    179: //SHA-1:
                    180: 
1.50      misha     181: struct SHA1Context {
1.54      misha     182:        unsigned Message_Digest[5], Length_Low, Length_High;
                    183:        unsigned int Message_Block[64];
                    184:        int Message_Block_Index, Computed, Corrupted;
1.50      misha     185: };
1.49      misha     186: 
                    187: #define SHA1CircularShift(bits,word) ((((word) << (bits)) & 0xFFFFFFFF)|((word) >> (32-(bits))))
                    188: void SHA1ProcessMessageBlock(SHA1Context *);
                    189: void SHA1PadMessage(SHA1Context *);
1.50      misha     190: void SHA1Reset(SHA1Context *context) {
1.54      misha     191:        context->Length_Low = context->Length_High = context->Message_Block_Index = 0;
                    192:        context->Message_Digest[0]      = 0x67452301;
                    193:        context->Message_Digest[1]      = 0xEFCDAB89;
                    194:        context->Message_Digest[2]      = 0x98BADCFE;
                    195:        context->Message_Digest[3]      = 0x10325476;
                    196:        context->Message_Digest[4]      = 0xC3D2E1F0;
                    197:        context->Computed = context->Corrupted  = 0;
1.50      misha     198: }
1.49      misha     199: 
1.50      misha     200: int SHA1Result(SHA1Context *context) {
1.54      misha     201:        if (context->Corrupted)
                    202:                return 0;
                    203:        if (!context->Computed) {
                    204:                SHA1PadMessage(context);
                    205:                context->Computed = 1;
                    206:        }
                    207:        return 1;
                    208: }
                    209: 
                    210: void SHA1Input(SHA1Context *context, const unsigned char *message_array, unsigned length) {
                    211:        if (!length)
                    212:                return;
                    213:        if (context->Computed || context->Corrupted) {
                    214:                context->Corrupted = 1;
                    215:                return;
                    216:        }
                    217: 
                    218:        while(length-- && !context->Corrupted) {
                    219:                context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF);
                    220:                context->Length_Low += 8;
                    221:                context->Length_Low &= 0xFFFFFFFF;
                    222:                if (!context->Length_Low && !(context->Length_High=((1+context->Length_High)&0xFFFFFFFF)))
                    223:                        context->Corrupted = 1; // too long message
                    224:                if (context->Message_Block_Index == 64)
                    225:                        SHA1ProcessMessageBlock(context);
                    226:                message_array++;
1.49      misha     227:        }
1.50      misha     228: }
1.49      misha     229: 
1.50      misha     230: void SHA1ProcessMessageBlock(SHA1Context *context) {
1.54      misha     231:        const unsigned K[] = {0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 };
                    232:        int t;
                    233:        unsigned    temp, W[80], buf[5];
                    234:        unsigned &A=buf[0], &B=buf[1], &C=buf[2], &D=buf[3], &E=buf[4];
1.50      misha     235: 
1.54      misha     236:        for(t = 0; t < 16; t++)
                    237:                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     238: 
1.54      misha     239:        for(t = 16; t < 80; t++)
                    240:                W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
1.49      misha     241: 
1.54      misha     242:        memcpy (buf, context->Message_Digest, sizeof(buf));
                    243:        for(t = 0; t < 20; t++) {
                    244:                temp =  (SHA1CircularShift(5,A) + ((B & C) | ((~B) & D)) + E + W[t] + K[0]) & 0xFFFFFFFF;
                    245:                E = D; D = C;
                    246:                C = SHA1CircularShift(30,B);
                    247:                B = A; A = temp;
1.49      misha     248:        }
                    249: 
1.54      misha     250:        for(t = 20; t < 40; t++) {
                    251:                temp = (SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]) & 0xFFFFFFFF;
                    252:                E = D; D = C;
                    253:                C = SHA1CircularShift(30,B);
                    254:                B = A; A = temp;
1.49      misha     255:        }
                    256: 
1.54      misha     257:        for(t = 40; t < 60; t++) {
                    258:                temp = (SHA1CircularShift(5,A) + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]) & 0xFFFFFFFF;
                    259:                E = D; D = C;
                    260:                C = SHA1CircularShift(30,B);
                    261:                B = A; A = temp;
1.49      misha     262:        }
                    263: 
1.54      misha     264:        for(t = 60; t < 80; t++) {
                    265:                temp = (SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3]) & 0xFFFFFFFF;
                    266:                E = D; D = C;
                    267:                C = SHA1CircularShift(30,B);
                    268:                B = A; A = temp;
1.49      misha     269:        }
                    270: 
1.54      misha     271:        for (t = 0; t < 5; t++)
                    272:                context->Message_Digest[t] = (context->Message_Digest[t] + buf[t]) & 0xFFFFFFFF;
1.50      misha     273: 
1.54      misha     274:        context->Message_Block_Index = 0;
1.50      misha     275: }
1.49      misha     276: 
1.50      misha     277: void SHA1PadMessage(SHA1Context *context) {
1.54      misha     278:        context->Message_Block[context->Message_Block_Index++] = 0x80;
1.50      misha     279:        if (context->Message_Block_Index > 56) {
                    280:                //was 55, one shift
1.54      misha     281:                while(context->Message_Block_Index < 64)
                    282:                        context->Message_Block[context->Message_Block_Index++] = 0;
                    283:                SHA1ProcessMessageBlock(context);
                    284:                while(context->Message_Block_Index < 56)
                    285:                        context->Message_Block[context->Message_Block_Index++] = 0;
1.50      misha     286:        } else
1.54      misha     287:                while(context->Message_Block_Index < 56)
                    288:                        context->Message_Block[context->Message_Block_Index++] = 0;
                    289:        context->Message_Block[56] = (context->Length_High >> 24) & 0xFF;
                    290:        context->Message_Block[57] = (context->Length_High >> 16) & 0xFF;
                    291:        context->Message_Block[58] = (context->Length_High >> 8) & 0xFF;
                    292:        context->Message_Block[59] = (context->Length_High) & 0xFF;
                    293:        context->Message_Block[60] = (context->Length_Low >> 24) & 0xFF;
                    294:        context->Message_Block[61] = (context->Length_Low >> 16) & 0xFF;
                    295:        context->Message_Block[62] = (context->Length_Low >> 8) & 0xFF;
                    296:        context->Message_Block[63] = (context->Length_Low) & 0xFF;
                    297:        SHA1ProcessMessageBlock(context);
1.50      misha     298: }
1.49      misha     299: 
1.62      moko      300: #ifdef PA_BIG_ENDIAN
                    301: #define SWAP(n) (n)
                    302: #else
                    303: #define SWAP(n) (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
                    304: #endif
                    305: 
1.64      moko      306: void SHA1ReadDigest(void *buf, SHA1Context *c)
1.62      moko      307: {
1.64      moko      308:        if(!SHA1Result(c))
1.62      moko      309:                throw Exception (PARSER_RUNTIME, 0, "Can not compute SHA1");
                    310: 
1.64      moko      311:        ((uint32_t *)buf)[0] = SWAP(c->Message_Digest[0]);
                    312:        ((uint32_t *)buf)[1] = SWAP(c->Message_Digest[1]);
                    313:        ((uint32_t *)buf)[2] = SWAP(c->Message_Digest[2]);
                    314:        ((uint32_t *)buf)[3] = SWAP(c->Message_Digest[3]);
                    315:        ((uint32_t *)buf)[4] = SWAP(c->Message_Digest[4]);
1.62      moko      316: }
                    317: 
1.54      misha     318: static void _sha1(Request& r, MethodParams& params) {
1.72    ! moko      319:        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     320: 
1.54      misha     321:        SHA1Context c;
1.64      moko      322:        unsigned char digest[20];
1.54      misha     323:        SHA1Reset (&c);
                    324:        SHA1Input (&c, (const unsigned char*)string, strlen(string));
1.64      moko      325:        SHA1ReadDigest(digest, &c);
1.54      misha     326: 
1.62      moko      327:        r.write_pass_lang(*new String(hex_string(digest, sizeof(digest), false)));
                    328: }
                    329: 
1.64      moko      330: void memxor(char *dest, const char *src, size_t n){
                    331:        for (;n>0;n--) *dest++ ^= *src++;
                    332: }
                    333: 
1.62      moko      334: #define IPAD 0x36
                    335: #define OPAD 0x5c
                    336: 
1.65      moko      337: #define HMAC(key,init,update,final,blocklen,digestlen){                                \
1.64      moko      338:        unsigned char tempdigest[digestlen], keydigest[digestlen];              \
                    339:        size_t keylen=strlen(key);                                              \
1.65      moko      340:        /* Reduce the key's size, so that it becomes <= blocklen bytes. */      \
                    341:        if (keylen > blocklen){                                                 \
1.64      moko      342:                init(&c);                                                       \
                    343:                update(&c,(const unsigned char*)hmac, keylen);                  \
                    344:                final(keydigest, &c);                                           \
                    345:                key = (char *)keydigest;                                        \
                    346:                keylen = digestlen;                                             \
                    347:        }                                                                       \
                    348:        /* Compute TEMP from KEY and STRING. */                                 \
1.65      moko      349:        char block[blocklen];                                                   \
                    350:        memset (block, IPAD, blocklen);                                         \
1.64      moko      351:        memxor (block, key, keylen);                                            \
                    352:        init(&c);                                                               \
1.65      moko      353:        update(&c, (const unsigned char*)block, blocklen);                      \
1.69      moko      354:        update(&c, (const unsigned char*)data.str, data.length);                \
1.64      moko      355:        final(tempdigest, &c);                                                  \
                    356:        /* Compute result from KEY and TEMP. */                                 \
1.65      moko      357:        memset (block, OPAD, blocklen);                                         \
1.64      moko      358:        memxor (block, key, keylen);                                            \
                    359:        init(&c);                                                               \
1.65      moko      360:        update(&c, (const unsigned char*)block, blocklen);                      \
1.64      moko      361:        update(&c, (const unsigned char*)tempdigest, digestlen);                \
1.62      moko      362: }
1.55      misha     363: 
1.62      moko      364: static void _digest(Request& r, MethodParams& params) {
1.63      moko      365:        const String &smethod = params.as_string(0, PARAMETER_MUST_BE_STRING);
1.69      moko      366: 
                    367:        Value& vdata=params.as_no_junction(1, "parameter must be string or file");
                    368: 
                    369:        String::C data;
                    370:        if(const String* sdata=vdata.get_string()){
1.72    ! moko      371:                String::Body body=sdata->cstr_to_string_body_untaint(String::L_AS_IS, r.connection(false), &r.charsets); // explode content, honor tainting changes
1.69      moko      372:                data=String::C(body.cstr(), body.length());
                    373:        } else {
                    374:                VFile *file=vdata.as_vfile(String::L_AS_IS);
                    375:                data=String::C(file->value_ptr(),file->value_size());
                    376:        }
1.62      moko      377: 
1.65      moko      378:        enum Method { M_MD5, M_SHA1, M_SHA256, M_SHA512 } method;
1.62      moko      379: 
1.63      moko      380:        if (smethod == "md5") method = M_MD5;
                    381:        else if (smethod == "sha1" ) method = M_SHA1;
1.65      moko      382:        else if (smethod == "sha256" ) method = M_SHA256;
                    383:        else if (smethod == "sha512" ) method = M_SHA512;
1.63      moko      384:        else throw Exception(PARSER_RUNTIME, &smethod, "must be 'md5' or 'sha1'");
1.62      moko      385: 
                    386:        const char *hmac=0;
1.63      moko      387:        enum Format { F_HEX, F_BASE64 } format = F_HEX;
1.62      moko      388: 
                    389:        if(params.count() == 3)
                    390:                if(HashStringValue* options=params.as_hash(2)) {
                    391:                        int valid_options=0;
                    392:                        if(Value* value=options->get("hmac")) {
                    393:                                hmac=value->as_string().cstr();
                    394:                                valid_options++;
                    395:                        }
1.63      moko      396:                        if(Value* value=options->get("format")) {
                    397:                                const String& sformat=value->as_string();
                    398:                                if (sformat == "hex") format = F_HEX;
                    399:                                else if (sformat == "base64" ) format = F_BASE64;
                    400:                                else throw Exception(PARSER_RUNTIME, &sformat, "must be 'hex' or 'base64'");
1.62      moko      401:                                valid_options++;
                    402:                        }
                    403:                        if(valid_options!=options->count())
                    404:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    405:                }
                    406: 
                    407:        String::C digest;
                    408: 
1.63      moko      409:        if(method == M_MD5){
1.64      moko      410:                PA_MD5_CTX c;
                    411:                if(hmac){
1.65      moko      412:                        HMAC(hmac, pa_MD5Init, pa_MD5Update, pa_MD5Final, 64, 16);
1.64      moko      413:                } else {
                    414:                        pa_MD5Init(&c);
1.69      moko      415:                        pa_MD5Update(&c, (const unsigned char*)data.str, data.length);
1.64      moko      416:                }
1.62      moko      417:                char *str=(char *)pa_malloc(16);
1.64      moko      418:                pa_MD5Final((unsigned char *)str, &c);
1.62      moko      419:                digest = String::C(str, 16);
                    420:        }
                    421: 
1.63      moko      422:        if(method == M_SHA1){
1.62      moko      423:                SHA1Context c;
                    424:                if(hmac){
1.65      moko      425:                        HMAC(hmac, SHA1Reset, SHA1Input, SHA1ReadDigest, 64, 20);
1.62      moko      426:                } else {
1.64      moko      427:                        SHA1Reset(&c);
1.69      moko      428:                        SHA1Input(&c, (const unsigned char*)data.str, data.length);
1.62      moko      429:                }
                    430:                char *str=(char *)pa_malloc(20);
1.64      moko      431:                SHA1ReadDigest(str, &c);
1.62      moko      432:                digest = String::C(str, 20);
                    433:        }
1.49      misha     434: 
1.65      moko      435:        if(method == M_SHA256){
                    436:                SHA256_CTX c;
                    437:                if(hmac){
                    438:                        HMAC(hmac, pa_SHA256_Init, pa_SHA256_Update, pa_SHA256_Final, 64, SHA256_DIGEST_LENGTH);
                    439:                } else {
                    440:                        pa_SHA256_Init(&c);
1.69      moko      441:                        pa_SHA256_Update(&c, (const unsigned char*)data.str, data.length);
1.65      moko      442:                }
                    443:                char *str=(char *)pa_malloc(SHA256_DIGEST_LENGTH);
                    444:                pa_SHA256_Final((unsigned char *)str, &c);
                    445:                digest = String::C(str, SHA256_DIGEST_LENGTH);
                    446:        }
                    447: 
                    448:        if(method == M_SHA512){
                    449:                SHA512_CTX c;
                    450:                if(hmac){
                    451:                        HMAC(hmac, pa_SHA512_Init, pa_SHA512_Update, pa_SHA512_Final, 128, SHA512_DIGEST_LENGTH);
                    452:                } else {
                    453:                        pa_SHA512_Init(&c);
1.69      moko      454:                        pa_SHA512_Update(&c, (const unsigned char*)data.str, data.length);
1.65      moko      455:                }
                    456:                char *str=(char *)pa_malloc(SHA512_DIGEST_LENGTH);
                    457:                pa_SHA512_Final((unsigned char *)str, &c);
                    458:                digest = String::C(str, SHA512_DIGEST_LENGTH);
                    459:        }
                    460: 
1.63      moko      461:        if(format == F_HEX){
1.62      moko      462:                r.write_pass_lang(*new String(hex_string((unsigned char *)digest.str, digest.length, false)));
                    463:        }
1.63      moko      464:        if(format == F_BASE64){
1.62      moko      465:                r.write_pass_lang(*new String(pa_base64_encode(digest.str, digest.length)));
                    466:        }
1.54      misha     467: }
1.49      misha     468: 
1.55      misha     469: static void _uuid(Request& r, MethodParams& /*params*/) {
                    470:        uuid uuid=get_uuid();
1.49      misha     471: 
1.55      misha     472:        const size_t bufsize=36+1/*zero-teminator*/+1/*for faulty snprintfs*/;
                    473:        char* cstr=new(PointerFreeGC) char[bufsize];
1.28      paf       474: 
1.55      misha     475:        snprintf(cstr, bufsize,
                    476:                        "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
                    477:                        uuid.time_low, uuid.time_mid, uuid.time_hi_and_version,
                    478:                        uuid.clock_seq >> 8, uuid.clock_seq & 0xFF,
                    479:                        uuid.node[0], uuid.node[1], uuid.node[2],
                    480:                        uuid.node[3], uuid.node[4], uuid.node[5]);
1.28      paf       481: 
1.55      misha     482:        r.write_pass_lang(*new String(cstr));
1.28      paf       483: }
                    484: 
1.34      paf       485: static void _uid64(Request& r, MethodParams& /*params*/) {
1.30      paf       486: 
                    487:        unsigned char id[64/8];
                    488:        random(&id, sizeof(id));
                    489: 
1.34      paf       490:        r.write_pass_lang(*new String(hex_string(id, sizeof(id), true)));
1.30      paf       491: }
                    492: 
1.43      misha     493: static void _crc32(Request& r, MethodParams& params) {
1.51      misha     494:        const char *string=params.as_string(0, PARAMETER_MUST_BE_STRING).cstr();
1.43      misha     495:        r.write_no_lang(*new VInt(pa_crc32(string, strlen(string))));
                    496: }
                    497: 
1.61      moko      498: static void toBase(unsigned int value, unsigned int base, char*& ptr){
1.57      misha     499:        static const char* hex="0123456789ABCDEF";
                    500:        int rest = value % base;
1.58      misha     501:        if(value >= base)
1.57      misha     502:                toBase( (value-rest)/base, base, ptr);
                    503:        *ptr++=(char)hex[rest];
                    504: }
                    505: 
                    506: static void _convert(Request& r, MethodParams& params) {
1.60      moko      507:        const char *str=params.as_string(0, PARAMETER_MUST_BE_STRING).cstr();
                    508: 
1.57      misha     509:        int base_from=params.as_int(1, "base from must be integer", r);
                    510:        if(base_from < 2 || base_from > 16)
                    511:                throw Exception(PARSER_RUNTIME, 0, "base from must be an integer from 2 to 16");
                    512: 
1.60      moko      513:        int base_to=params.as_int(2, "base to must be integer", r);
                    514:        if(base_to < 2 || base_to > 16)
                    515:                throw Exception(PARSER_RUNTIME, 0, "base to must be an integer from 2 to 16");
                    516: 
1.61      moko      517:        while(isspace(*str))
1.60      moko      518:                str++;
                    519: 
                    520:        if(!*str)
                    521:                return;
                    522: 
                    523:        bool negative=false;
                    524:        if(str[0]=='-') {
                    525:                negative=true;
                    526:                str++;
                    527:        } else if(str[0]=='+') {
                    528:                str++;
                    529:        }
                    530: 
1.61      moko      531:        unsigned int value=pa_atoui(str, base_from);
1.57      misha     532: 
1.61      moko      533:        char result_cstr[sizeof(unsigned int)*8+1/*minus for negative number*/+1/*terminator*/];
1.60      moko      534:        char* ptr=result_cstr;
                    535:        if(negative)
                    536:                *ptr++='-';
1.57      misha     537: 
                    538:        toBase(value, base_to, ptr);
                    539:        *ptr=0;
                    540:        r.write_pass_lang(*new String(pa_strdup(result_cstr)));
                    541: }
                    542: 
1.1       parser    543: // constructor
                    544: 
1.34      paf       545: MMath::MMath(): Methoded("math") {
1.1       parser    546:        // ^FUNC(expr)  
1.28      paf       547: #define ADDX(name, X) \
                    548:        add_native_method(#name, Method::CT_STATIC, _##name, X, X)
                    549: #define ADD0(name) ADDX(name, 0)
                    550: #define ADD1(name) ADDX(name, 1)
                    551: #define ADD2(name) ADDX(name, 2)
1.1       parser    552: 
                    553:        ADD1(round);    ADD1(floor);    ADD1(ceiling);
1.3       parser    554:        ADD1(trunc);    ADD1(frac);
1.1       parser    555:        ADD1(abs);      ADD1(sign);
1.46      misha     556:        ADD1(exp);
1.48      misha     557:        ADD1(log);      ADD1(log10);
1.1       parser    558:        ADD1(sin);      ADD1(asin);     
                    559:        ADD1(cos);      ADD1(acos);     
                    560:        ADD1(tan);      ADD1(atan);
1.3       parser    561:        ADD1(degrees);  ADD1(radians);
1.1       parser    562:        ADD1(sqrt);
1.3       parser    563:        ADD1(random);
1.1       parser    564: 
1.49      misha     565:        // ^math:pow(x;y)
1.1       parser    566:        ADD2(pow);
                    567: 
1.49      misha     568:        // ^math:crypt[password;salt]
1.19      paf       569:        ADD2(crypt);
1.26      paf       570: 
1.49      misha     571:        // ^math:md5[string]
1.26      paf       572:        ADD1(md5);
1.5       parser    573: 
1.49      misha     574:        // ^math:sha1[string]
                    575:        ADD1(sha1);
                    576:        
1.71      moko      577:        // ^math:digest[method;string|file;options]
1.62      moko      578:        add_native_method("digest", Method::CT_STATIC, _digest, 2, 3);
                    579:        
1.49      misha     580:        // ^math:crc32[string]
1.43      misha     581:        ADD1(crc32);
                    582: 
1.49      misha     583:        // ^math:uuid[]
1.29      paf       584:        ADD0(uuid);
                    585: 
1.49      misha     586:        // ^math:uid64[]
1.30      paf       587:        ADD0(uid64);
1.57      misha     588: 
                    589:        // ^math:convert[number](base-from;base-to)
                    590:        add_native_method("convert", Method::CT_STATIC, _convert, 3, 3);
1.1       parser    591: }

E-mail: