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

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

E-mail: