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

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

E-mail: