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

1.1       parser      1: /** @file
                      2:        Parser: @b math parser class.
                      3: 
1.24.2.2  paf         4:        Copyright(c) 2001-2003 ArtLebedev Group(http://www.artlebedev.com)
1.20      paf         5:        Author: Alexandr Petrosian <paf@design.ru>(http://paf.design.ru)
1.24.2.12.2.1  (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.24.2.12.2.1  (paf       11:): static const char* IDENT_MATH_C="$Date: 2003/04/04 09:41:54 $";
1.24.2.4  paf        12: 
                     13: #include "pa_vmethod_frame.h"
1.1       parser     14: #include "pa_common.h"
                     15: #include "pa_vint.h"
1.2       parser     16: #include "pa_vmath.h"
1.1       parser     17: #include "pa_request.h"
1.19      paf        18: #include "pa_md5.h"
1.24.2.12.2.1  (paf       19:): #include "pa_threads.h"
1.1       parser     20: 
1.5       parser     21: #ifdef WIN32
1.24.2.12.2.1  (paf       22:): #    define _WIN32_WINNT 0x400
1.5       parser     23: #      include <windows.h>
1.24.2.12.2.1  (paf       24:): #    include <wincrypt.h>
1.5       parser     25: #endif
                     26: 
1.24.2.12  paf        27: #ifdef HAVE_CRYPT
                     28: #      ifdef HAVE_CRYPT_H
                     29: #              include <crypt.h>
                     30: #      endif
                     31: #else
1.24.2.12.2.3  (paf       32::       extern char *crypt(const char* , const char* );
1.20      paf        33: #endif
                     34: 
1.1       parser     35: // defines
                     36: 
1.20      paf        37: #define MAX_SALT 8
1.1       parser     38: 
                     39: // class
                     40: 
1.24.2.8  paf        41: class MMath: public Methoded {
1.1       parser     42: public:
1.24.2.6  paf        43:        MMath();
1.5       parser     44: 
1.1       parser     45: public: // Methoded
1.15      paf        46:        bool used_directly() { return false; }
1.1       parser     47: };
                     48: 
1.24.2.6  paf        49: // global variables
                     50: 
1.24.2.10  paf        51: DECLARE_CLASS_VAR(math, 0 /*fictive*/, new MMath);
1.24.2.6  paf        52: 
1.24.2.12.2.1  (paf       53:): #ifdef WIN32
                     54:): class Random_provider {
                     55:):      HCRYPTPROV fhProv;
                     56:):      
                     57:):      void acquire() {
                     58:):              SYNCHRONIZED;
                     59:): 
                     60:):              if(fhProv)
                     61:):                      return;
                     62:): 
                     63:):              if(!CryptAcquireContext(&fhProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
                     64:):                      throw Exception(0,
                     65:):                              0,
                     66:):                              "CryptAcquireContext failed");
                     67:):      }
                     68:):      void release() {
                     69:):              if(fhProv)
                     70:):                      CryptReleaseContext(fhProv, 0);
                     71:):      }
                     72:):      
                     73:): public:
                     74:):      Random_provider(): fhProv(0) {}
                     75:):      ~Random_provider() { release(); }
                     76:):      void generate(void *buffer, size_t size) {
                     77:):              acquire();
                     78:): 
                     79:):              if(!CryptGenRandom(fhProv, size, (BYTE*)buffer))
                     80:):                      throw Exception(0,
                     81:):                              0,
                     82:):                              "CryptGenRandom failed");
                     83:):      }
                     84:): }
                     85:):      random_provider;
                     86:): 
                     87:): #else
                     88:): 
                     89:): /// from gen_uuid.c
                     90:): static int get_random_fd(void)
                     91:): {
                     92:):         struct timeval  tv;
                     93:):         static int      fd = -2;
                     94:):         int             i;
                     95:): 
                     96:):         if (fd == -2) {
                     97:):                 gettimeofday(&tv, 0);
                     98:):                 fd = open("/dev/urandom", O_RDONLY);
                     99:):                 if (fd == -1)
                    100:):                         fd = open("/dev/random", O_RDONLY | O_NONBLOCK);
                    101:):                 srand((getpid() << 16) ^ getuid() ^ tv.tv_sec ^ tv.tv_usec);
                    102:):         }
                    103:):         /* Crank the random number generator a few times */
                    104:):         gettimeofday(&tv, 0);
                    105:):         for (i = (tv.tv_sec ^ tv.tv_usec) & 0x1F; i > 0; i--)
                    106:):                 rand();
                    107:):         return fd;
                    108:): }
                    109:): 
                    110:): 
                    111:): /*
                    112:):  * Generate a series of random bytes.  Use /dev/urandom if possible,
                    113:):  * and if not, use srandom/random.
                    114:):  */
                    115:): static void get_random_bytes(void *buf, int nbytes)
                    116:): {
                    117:):         int i, fd = get_random_fd();
                    118:):         int lose_counter = 0;
                    119:):         char *cp = (char *) buf;
                    120:): 
                    121:):         if (fd >= 0) {
                    122:):                 while (nbytes > 0) {
                    123:):                         i = read(fd, cp, nbytes);
                    124:):                         if (i <= 0) {
                    125:):                                 if (lose_counter++ > 16)
                    126:):                                         break;
                    127:):                                 continue;
                    128:):                         }
                    129:):                         nbytes -= i;
                    130:):                         cp += i;
                    131:):                         lose_counter = 0;
                    132:):                 }
                    133:):         }
                    134:): 
                    135:):         /* XXX put something better here if no /dev/random! */
                    136:):         for (i = 0; i < nbytes; i++)
                    137:):                 *cp++ = rand() & 0xFF;
                    138:):         return;
                    139:): }
                    140:): 
                    141:): 
                    142:): #endif
                    143:): 
                    144:): 
                    145:): // helpers
                    146:): 
                    147:): static void random(void *buffer, size_t size) {
                    148:): #ifdef WIN32
                    149:):      random_provider.generate(buffer, size);
                    150:): #else
                    151:):      get_random_bytes(buffer, size);
                    152:): #endif
                    153:): }
                    154:): 
1.1       parser    155: // methods
1.20      paf       156: static inline int _random(uint top) {
1.24.2.12.2.1  (paf      157:):      uint raw;
                    158:):      random(&raw, sizeof(raw));
                    159:):      return int(double(raw) / 0x100000000 * top );
1.20      paf       160: }
1.24.2.12.2.1  (paf      161:): #define MAX_UINT 0xFFFFFFFFu
1.24.2.12.2.9  (paf      162:: static void _random(Request& r, MethodParams& params) {
                    163::       Value& range=params.as_junction(0, "range must be expression");
1.24.2.12.2.6  (paf      164::       double top=r.process_to_value(range).as_double();
1.24.2.12.2.1  (paf      165:):      if(top<=0 || top>MAX_UINT)
1.16      paf       166:                throw Exception("parser.runtime",
1.24.2.12.2.6  (paf      167::                       0,
1.24.2.12.2.1  (paf      168:):                      "top(%g) must be [1..%u]", top, MAX_UINT);
1.1       parser    169:        
1.24.2.12.2.6  (paf      170::       r.write_no_lang(*new VInt(_random(uint(top))));
1.1       parser    171: }
                    172: 
                    173: 
1.20      paf       174: typedef double(*math1_func_ptr)(double);
1.3       parser    175: static double frac(double param) { return param-trunc(param); }
                    176: static double degrees(double param) { return param /PI *180; }
                    177: static double radians(double param) { return param /180 *PI; }
1.1       parser    178: 
1.24.2.12.2.9  (paf      179:: static void math1(Request& r, MethodParams& params, math1_func_ptr func) {
                    180::       Value& param=params.as_junction(0, "parameter must be expression");
1.1       parser    181: 
1.24.2.12.2.6  (paf      182::       double result=func(r.process_to_value(param).as_double());
                    183::       r.write_no_lang(*new VDouble(result));
1.1       parser    184: }
                    185: 
                    186: #define MATH1(name) \
1.24.2.12.2.9  (paf      187::       static void _##name(Request& r, MethodParams& params) {\
1.24.2.12.2.6  (paf      188::               math1(r, params, &name);\
1.1       parser    189:        }
                    190: #define MATH1P(name_parser, name_c) \
1.24.2.12.2.9  (paf      191::       static void _##name_parser(Request& r, MethodParams& params) {\
1.24.2.12.2.6  (paf      192::               math1(r, params, &name_c);\
1.1       parser    193:        }
                    194: MATH1(round);  MATH1(floor);   MATH1P(ceiling, ceil);
1.3       parser    195: MATH1(trunc);  MATH1(frac);
1.1       parser    196: MATH1P(abs, fabs);     MATH1(sign);
                    197: MATH1(exp);    MATH1(log);     
                    198: MATH1(sin);    MATH1(asin);    
                    199: MATH1(cos);    MATH1(acos);    
                    200: MATH1(tan);    MATH1(atan);
1.3       parser    201: MATH1(degrees);        MATH1(radians);
1.1       parser    202: MATH1(sqrt);
                    203: 
                    204: 
                    205: typedef double (*math2_func_ptr)(double, double);
1.24.2.12.2.9  (paf      206:: static void math2(Request& r, MethodParams& params, math2_func_ptr func) {
                    207::       Value& a=params.as_junction(0, "parameter must be expression");
                    208::       Value& b=params.as_junction(1, "parameter must be expression");
1.1       parser    209: 
1.24.2.6  paf       210:        double result=func(
1.24.2.12.2.6  (paf      211::               r.process_to_value(a).as_double(),
                    212::               r.process_to_value(b).as_double());
                    213::       r.write_no_lang(*new VDouble(result));
1.1       parser    214: }
                    215: 
                    216: #define MATH2(name) \
1.24.2.12.2.9  (paf      217::       static void _##name(Request& r, MethodParams& params) {\
1.24.2.12.2.6  (paf      218::               math2(r, params, &name);\
1.1       parser    219:        }
                    220: MATH2(pow);
                    221: 
1.20      paf       222: inline bool is_salt_body_char(int c) {
                    223:        return isalnum(c) || c == '.' || c=='/';
                    224: }
1.24.2.2  paf       225: static size_t calc_prefix_size(const char* salt) {
1.20      paf       226:        if(size_t salt_size=strlen(salt)) {
                    227:                if(!is_salt_body_char(salt[0])) { // $...  {...
1.24.2.2  paf       228:                        const char* cur=salt+1; // skip
1.20      paf       229:                        while(is_salt_body_char(*cur++)) // ...$  ...}
                    230:                                ;
                    231:                        return cur-salt;
                    232:                } else
                    233:                        return 0;
                    234:        } else
                    235:                return 0;
                    236: }
1.24.2.12.2.9  (paf      237:: static void _crypt(Request& r, MethodParams& params) {
                    238::       const char* password=params.as_string(0, "password must be string").cstr();
                    239::       const char* maybe_bodyless_salt=params.as_string(1, "salt must be string").cstr();
1.20      paf       240: 
                    241:        size_t prefix_size=calc_prefix_size(maybe_bodyless_salt);
1.24.2.2  paf       242:        const char* normal_salt;
1.20      paf       243:        char normalize_buf[MAX_STRING];
                    244:        if(prefix_size==strlen(maybe_bodyless_salt)) { // bodyless?
                    245:                strncpy(normalize_buf, maybe_bodyless_salt, MAX_STRING-MAX_SALT-1);
                    246:                char *cur=normalize_buf+strlen(normalize_buf);
                    247:                // sould add up MAX_SALT random chars
                    248:                static unsigned char itoa64[] =         /* 0 ... 63 => ASCII - 64 */
                    249:                "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
                    250:                for(int i=0; i<MAX_SALT; i++)
                    251:                        *cur++=itoa64[_random(64)];
                    252:                *cur=0;
                    253:                normal_salt=normalize_buf;
                    254:        } else
                    255:                normal_salt=maybe_bodyless_salt;
1.19      paf       256: 
                    257:     /* FreeBSD style MD5 string 
                    258:      */
1.20      paf       259:     if(strncmp(normal_salt, PA_MD5PW_ID, PA_MD5PW_IDLEN) == 0) {
1.19      paf       260:                const size_t sample_size=120;
1.24.2.12.2.7  (paf      261::               char *sample_buf=new(PointerFreeGC) char[sample_size];
1.24.2.12.2.1  (paf      262:):              PA_MD5Encode((const unsigned char *)password,
1.20      paf       263:                                (const unsigned char *)normal_salt, sample_buf, sample_size);
1.24.2.6  paf       264:                String sample(sample_buf);
                    265:                r.write_pass_lang(sample);
1.20      paf       266:     } else {
                    267: #ifdef HAVE_CRYPT
1.24.2.6  paf       268:                const char* static_sample_buf=crypt(password, normal_salt);
                    269:                if(!static_sample_buf  // nothing generated
                    270:                        || !static_sample_buf[0] // generated nothing
                    271:                        || strncmp(static_sample_buf, normal_salt, prefix_size)!=0) // salt prefix not preserved
1.20      paf       272:                        throw Exception("parser.runtime",
1.24.2.12.2.8  (paf      273::                               0,
                    274::                               "crypt on this platform does not support '%.*s' salt prefix", prefix_size, normal_salt);
1.20      paf       275:                
1.24.2.12.2.8  (paf      276::               r.write_pass_lang(String(pa_strdup(static_sample_buf)));
1.20      paf       277: #else
1.19      paf       278:                throw Exception("parser.runtime",
1.24.2.12.2.6  (paf      279::                       0,
1.19      paf       280:                        "salt must start with '" PA_MD5PW_ID "'");
1.20      paf       281: #endif
                    282:        }
1.19      paf       283: }
                    284: 
1.24.2.12.2.1  (paf      285:): static const char* hex_string(unsigned char* bytes, size_t size, bool upcase) {
                    286:):      char *bytes_hex=new(PointerFreeGC) char [size*2/*byte->hh*/+1/*for zero-teminator*/];
                    287:):      unsigned char *src=bytes;
                    288:):      unsigned char *end=bytes+size;
                    289:):      char *dest=bytes_hex;
                    290:):      const char *format=upcase?"%02X":"%02x";
                    291:):      while(src<end)
                    292:):              dest+=snprintf(dest, 3, format, *src++);
                    293:): 
                    294:):      return bytes_hex;
                    295:): }
                    296:): 
                    297:): static void _md5(Request& r, MethodParams& params) {
                    298:):      const char *string=params.as_string(0, "parameter must be string").cstr();
                    299:): 
                    300:): 
                    301:):      PA_MD5_CTX context;
                    302:):      unsigned char digest[16];
                    303:):      PA_MD5Init(&context);
                    304:):      PA_MD5Update(&context, (const unsigned char*)string, strlen(string));
                    305:):      PA_MD5Final(digest, &context);
                    306:): 
                    307:):      r.write_pass_lang(*new String(hex_string(digest, sizeof(digest), false)));
                    308:): }
                    309:): 
                    310:): /// to hell with extra bytes on 64bit platforms
                    311:): struct uuid {
                    312:):         unsigned int   time_low;
                    313:):         unsigned short   time_mid;
                    314:):         unsigned short   time_hi_and_version;
                    315:):         unsigned short   clock_seq;
                    316:):         unsigned char    node[6];
                    317:): };
                    318:): static void _uuid(Request& r, MethodParams& /*params*/) {
                    319:):      // random
                    320:):      struct uuid uuid;
                    321:):      random(&uuid, sizeof(uuid));
                    322:): 
                    323:):      // http://www.opengroup.org/onlinepubs/9629399/apdxa.htm#tagtcjh_35
                    324:):      // ~
                    325:):      // version = DCE Security version, with embedded POSIX UIDs.  
                    326:):      // variant = DCE
                    327:):      //
                    328:):      // DCE=Distributed Computing Environment
                    329:):      // http://www.opengroup.org/dce/
                    330:):      //
                    331:):      // they say this influences comparison&such,
                    332:):      // but could not figure out how, hence structure layout specified strictly
                    333:):      // anyhow, uuidgen on Win32 yield those values
                    334:):      // 
                    335:):      // xxxxxxxx-xxxx-4xxx-{8,9,A,B}xxx-xxxxxxxxxxxx
                    336:):      uuid.clock_seq = (uuid.clock_seq & 0x3FFF) | 0x8000;
                    337:):         uuid.time_hi_and_version = (uuid.time_hi_and_version & 0x0FFF) | 0x4000;
                    338:):  
                    339:):      // format 
                    340:):      const int uuid_cstr_bufsize=32+1/*for zero-teminator*/;
                    341:):      char *uuid_cstr=new(PointerFreeGC) char[uuid_cstr_bufsize];
                    342:):         snprintf(uuid_cstr, uuid_cstr_bufsize,
                    343:):                 "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
                    344:):                 uuid.time_low, uuid.time_mid, uuid.time_hi_and_version,
                    345:):                 uuid.clock_seq >> 8, uuid.clock_seq & 0xFF,
                    346:):                 uuid.node[0], uuid.node[1], uuid.node[2],
                    347:):                 uuid.node[3], uuid.node[4], uuid.node[5]);
                    348:): 
                    349:):      r.write_pass_lang(*new String(uuid_cstr));
                    350:): }
                    351:): 
                    352:): static void _uid64(Request& r, MethodParams& /*params*/) {
                    353:):      unsigned char id[64/8];
                    354:):      random(&id, sizeof(id));
                    355:): 
                    356:):      r.write_pass_lang(*new String(hex_string(id, sizeof(id), true)));
                    357:): }
                    358:): 
1.1       parser    359: // constructor
                    360: 
1.24.2.6  paf       361: MMath::MMath(): Methoded("math") {
1.1       parser    362:        // ^FUNC(expr)  
1.24.2.12.2.1  (paf      363:): #define ADDX(name, X) \
                    364:):      add_native_method(#name, Method::CT_STATIC, _##name, X, X)
                    365:): #define ADD0(name) ADDX(name, 0)
                    366:): #define ADD1(name) ADDX(name, 1)
                    367:): #define ADD2(name) ADDX(name, 2)
1.1       parser    368: 
                    369:        ADD1(round);    ADD1(floor);    ADD1(ceiling);
1.3       parser    370:        ADD1(trunc);    ADD1(frac);
1.1       parser    371:        ADD1(abs);      ADD1(sign);
                    372:        ADD1(exp);      ADD1(log);      
                    373:        ADD1(sin);      ADD1(asin);     
                    374:        ADD1(cos);      ADD1(acos);     
                    375:        ADD1(tan);      ADD1(atan);
1.3       parser    376:        ADD1(degrees);  ADD1(radians);
1.1       parser    377:        ADD1(sqrt);
1.3       parser    378:        ADD1(random);
1.1       parser    379: 
                    380:        // ^pow(x;y)
                    381:        ADD2(pow);
                    382: 
1.19      paf       383:        // ^crypt[password;salt]
                    384:        ADD2(crypt);
1.5       parser    385: 
1.24.2.12.2.1  (paf      386:):      // ^md5[string]
                    387:):      ADD1(md5);
                    388:): 
                    389:):      // ^uuid[]
                    390:):      ADD0(uuid);
                    391:): 
                    392:):      // ^uid64[]
                    393:):      ADD0(uid64);
1.1       parser    394: }

E-mail: