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

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

E-mail: