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

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

E-mail: