Annotation of parser3/src/classes/math.C, revision 1.49
1.1 parser 1: /** @file
2: Parser: @b math parser class.
3:
1.40 paf 4: Copyright(c) 2001-2005 ArtLebedev Group(http://www.artlebedev.com)
1.20 paf 5: Author: Alexandr Petrosian <paf@design.ru>(http://paf.design.ru)
1.28 paf 6:
7: portions from gen_uuid.c,
8: Copyright (C) 1996, 1997, 1998, 1999 Theodore Ts'o.
1.22 paf 9: */
1.1 parser 10:
1.49 ! misha 11: static const char * const IDENT_MATH_C="$Date: 2007/04/24 08:40:12 $";
1.1 parser 12:
1.34 paf 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.28 paf 19: #include "pa_threads.h"
1.1 parser 20:
1.5 parser 21: #ifdef WIN32
1.28 paf 22: # define _WIN32_WINNT 0x400
1.5 parser 23: # include <windows.h>
1.28 paf 24: # include <wincrypt.h>
1.5 parser 25: #endif
26:
1.34 paf 27: #ifdef HAVE_CRYPT
28: # ifdef HAVE_CRYPT_H
29: # include <crypt.h>
30: # endif
31: #else
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.34 paf 41: class MMath: public Methoded {
1.1 parser 42: public:
1.34 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.34 paf 49: // global variables
50:
51: DECLARE_CLASS_VAR(math, 0 /*fictive*/, new MMath);
52:
1.28 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.34 paf 155:
1.1 parser 156: // methods
1.34 paf 157:
158: #define MAX_UINT 0xFFFFFFFFu
159:
1.20 paf 160: static inline int _random(uint top) {
1.28 paf 161: uint raw;
162: random(&raw, sizeof(raw));
1.34 paf 163: return int(double(raw) / MAX_UINT * top );
1.20 paf 164: }
1.1 parser 165:
1.34 paf 166: static void _random(Request& r, MethodParams& params) {
1.41 paf 167: double top=params.as_double(0, "range must be expression", r);
1.34 paf 168: if(top<=0 || top>MAX_UINT)
1.45 misha 169: throw Exception(PARSER_RUNTIME,
1.34 paf 170: 0,
171: "top(%g) must be [1..%u]", top, MAX_UINT);
1.1 parser 172:
1.34 paf 173: r.write_no_lang(*new VInt(_random(uint(top))));
1.1 parser 174: }
175:
176:
1.20 paf 177: typedef double(*math1_func_ptr)(double);
1.3 parser 178: static double frac(double param) { return param-trunc(param); }
179: static double degrees(double param) { return param /PI *180; }
180: static double radians(double param) { return param /180 *PI; }
1.1 parser 181:
1.34 paf 182: static void math1(Request& r, MethodParams& params, math1_func_ptr func) {
1.41 paf 183: double param=params.as_double(0, "parameter must be expression", r);
184: double result=func(param);
1.34 paf 185: r.write_no_lang(*new VDouble(result));
1.1 parser 186: }
187:
188: #define MATH1(name) \
1.34 paf 189: static void _##name(Request& r, MethodParams& params) {\
190: math1(r, params, &name);\
1.1 parser 191: }
192: #define MATH1P(name_parser, name_c) \
1.34 paf 193: static void _##name_parser(Request& r, MethodParams& params) {\
194: math1(r, params, &name_c);\
1.1 parser 195: }
196: MATH1(round); MATH1(floor); MATH1P(ceiling, ceil);
1.3 parser 197: MATH1(trunc); MATH1(frac);
1.1 parser 198: MATH1P(abs, fabs); MATH1(sign);
1.46 misha 199: MATH1(exp);
1.48 misha 200: MATH1(log); MATH1(log10);
1.1 parser 201: MATH1(sin); MATH1(asin);
202: MATH1(cos); MATH1(acos);
203: MATH1(tan); MATH1(atan);
1.3 parser 204: MATH1(degrees); MATH1(radians);
1.1 parser 205: MATH1(sqrt);
206:
207:
208: typedef double (*math2_func_ptr)(double, double);
1.34 paf 209: static void math2(Request& r, MethodParams& params, math2_func_ptr func) {
1.41 paf 210: double a=params.as_double(0, "parameter must be expression", r);
211: double b=params.as_double(1, "parameter must be expression", r);
212: double result=func(a, b);
1.34 paf 213: r.write_no_lang(*new VDouble(result));
1.1 parser 214: }
215:
216: #define MATH2(name) \
1.34 paf 217: static void _##name(Request& r, MethodParams& params) {\
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.34 paf 225: static size_t calc_prefix_size(const char* salt) {
1.37 paf 226: if(strlen(salt)) {
1.39 paf 227: if(!is_salt_body_char((unsigned char)salt[0])) { // $... {...
1.34 paf 228: const char* cur=salt+1; // skip
1.39 paf 229: while(is_salt_body_char((unsigned char)*cur++)) // ...$ ...}
1.20 paf 230: ;
231: return cur-salt;
232: } else
233: return 0;
234: } else
235: return 0;
236: }
1.34 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.34 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.34 paf 261: char *sample_buf=new(PointerFreeGC) char[sample_size];
262: pa_MD5Encode((const unsigned char *)password,
263: (const unsigned char *)normal_salt, sample_buf, sample_size);
264: String sample(sample_buf);
265: r.write_pass_lang(sample);
1.20 paf 266: } else {
267: #ifdef HAVE_CRYPT
1.34 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.45 misha 272: throw Exception(PARSER_RUNTIME,
1.34 paf 273: 0,
274: "crypt on this platform does not support '%.*s' salt prefix", prefix_size, normal_salt);
1.20 paf 275:
1.34 paf 276: r.write_pass_lang(String(pa_strdup(static_sample_buf)));
1.20 paf 277: #else
1.45 misha 278: throw Exception(PARSER_RUNTIME,
1.34 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.34 paf 285: static void _md5(Request& r, MethodParams& params) {
286: const char *string=params.as_string(0, "parameter must be string").cstr();
1.27 paf 287:
288: PA_MD5_CTX context;
289: unsigned char digest[16];
1.34 paf 290: pa_MD5Init(&context);
291: pa_MD5Update(&context, (const unsigned char*)string, strlen(string));
292: pa_MD5Final(digest, &context);
1.27 paf 293:
1.34 paf 294: r.write_pass_lang(*new String(hex_string(digest, sizeof(digest), false)));
1.26 paf 295: }
296:
1.49 ! misha 297:
! 298: //SHA-1:
! 299:
! 300: struct SHA1Context
! 301: {
! 302: unsigned Message_Digest[5], Length_Low, Length_High;
! 303: unsigned char Message_Block[64];
! 304: int Message_Block_Index, Computed, Corrupted;
! 305: };
! 306:
! 307: #define SHA1CircularShift(bits,word) ((((word) << (bits)) & 0xFFFFFFFF)|((word) >> (32-(bits))))
! 308: void SHA1ProcessMessageBlock(SHA1Context *);
! 309: void SHA1PadMessage(SHA1Context *);
! 310: void SHA1Reset(SHA1Context *context)
! 311: {
! 312: context->Length_Low = context->Length_High = context->Message_Block_Index = 0;
! 313: context->Message_Digest[0] = 0x67452301;
! 314: context->Message_Digest[1] = 0xEFCDAB89;
! 315: context->Message_Digest[2] = 0x98BADCFE;
! 316: context->Message_Digest[3] = 0x10325476;
! 317: context->Message_Digest[4] = 0xC3D2E1F0;
! 318: context->Computed = context->Corrupted = 0;
! 319: }
! 320:
! 321: int SHA1Result(SHA1Context *context)
! 322: {
! 323: if (context->Corrupted)
! 324: return 0;
! 325: if (!context->Computed)
! 326: {
! 327: SHA1PadMessage(context);
! 328: context->Computed = 1;
! 329: }
! 330: return 1;
! 331: }
! 332:
! 333: void SHA1Input (SHA1Context *context, const unsigned char *message_array, unsigned length)
! 334: {
! 335: if (!length)
! 336: return;
! 337: if (context->Computed || context->Corrupted)
! 338: {
! 339: context->Corrupted = 1;
! 340: return;
! 341: }
! 342:
! 343: while(length-- && !context->Corrupted)
! 344: {
! 345: context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF);
! 346: context->Length_Low += 8;
! 347: context->Length_Low &= 0xFFFFFFFF;
! 348: if (!context->Length_Low && !(context->Length_High=((1+context->Length_High)&0xFFFFFFFF)))
! 349: context->Corrupted = 1; // too long message
! 350: if (context->Message_Block_Index == 64)
! 351: SHA1ProcessMessageBlock(context);
! 352: message_array++;
! 353: }
! 354: }
! 355:
! 356: void SHA1ProcessMessageBlock(SHA1Context *context)
! 357: {
! 358: const unsigned K[] = {0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 };
! 359: int t;
! 360: unsigned temp, W[80], buf[5];
! 361: unsigned &A=buf[0], &B=buf[1], &C=buf[2], &D=buf[3], &E=buf[4];
! 362: for(t = 0; t < 16; t++)
! 363: W[t] = (((unsigned) context->Message_Block[t * 4]) << 24) | (((unsigned) context->Message_Block[t * 4 + 1]) << 16) | (((unsigned) context->Message_Block[t * 4 + 2]) << 8) | ((unsigned) context->Message_Block[t * 4 + 3]);
! 364: for(t = 16; t < 80; t++)
! 365: W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
! 366:
! 367: memcpy (buf, context->Message_Digest, sizeof(buf));
! 368: for(t = 0; t < 20; t++)
! 369: {
! 370: temp = (SHA1CircularShift(5,A) + ((B & C) | ((~B) & D)) + E + W[t] + K[0]) & 0xFFFFFFFF;
! 371: E = D; D = C;
! 372: C = SHA1CircularShift(30,B);
! 373: B = A; A = temp;
! 374: }
! 375:
! 376: for(t = 20; t < 40; t++)
! 377: {
! 378: temp = (SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]) & 0xFFFFFFFF;
! 379: E = D; D = C;
! 380: C = SHA1CircularShift(30,B);
! 381: B = A; A = temp;
! 382: }
! 383:
! 384: for(t = 40; t < 60; t++)
! 385: {
! 386: temp = (SHA1CircularShift(5,A) + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]) & 0xFFFFFFFF;
! 387: E = D; D = C;
! 388: C = SHA1CircularShift(30,B);
! 389: B = A; A = temp;
! 390: }
! 391:
! 392: for(t = 60; t < 80; t++)
! 393: {
! 394: temp = (SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3]) & 0xFFFFFFFF;
! 395: E = D; D = C;
! 396: C = SHA1CircularShift(30,B);
! 397: B = A; A = temp;
! 398: }
! 399:
! 400: for (t = 0; t < 5; t++)
! 401: context->Message_Digest[t] = (context->Message_Digest[t] + buf[t]) & 0xFFFFFFFF;
! 402: context->Message_Block_Index = 0;
! 403: }
! 404:
! 405: void SHA1PadMessage(SHA1Context *context)
! 406: {
! 407: context->Message_Block[context->Message_Block_Index++] = 0x80;
! 408: if (context->Message_Block_Index > 56) //was 55, one shift
! 409: {
! 410: while(context->Message_Block_Index < 64)
! 411: context->Message_Block[context->Message_Block_Index++] = 0;
! 412: SHA1ProcessMessageBlock(context);
! 413: while(context->Message_Block_Index < 56)
! 414: context->Message_Block[context->Message_Block_Index++] = 0;
! 415: }
! 416: else
! 417: while(context->Message_Block_Index < 56)
! 418: context->Message_Block[context->Message_Block_Index++] = 0;
! 419: context->Message_Block[56] = (context->Length_High >> 24) & 0xFF;
! 420: context->Message_Block[57] = (context->Length_High >> 16) & 0xFF;
! 421: context->Message_Block[58] = (context->Length_High >> 8) & 0xFF;
! 422: context->Message_Block[59] = (context->Length_High) & 0xFF;
! 423: context->Message_Block[60] = (context->Length_Low >> 24) & 0xFF;
! 424: context->Message_Block[61] = (context->Length_Low >> 16) & 0xFF;
! 425: context->Message_Block[62] = (context->Length_Low >> 8) & 0xFF;
! 426: context->Message_Block[63] = (context->Length_Low) & 0xFF;
! 427: SHA1ProcessMessageBlock(context);
! 428: }
! 429:
! 430:
! 431: static void _sha1(Request& r, MethodParams& params)
! 432: {
! 433: const char *string = params.as_string(0, "parameter must be string").cstr();
! 434:
! 435: SHA1Context c;
! 436: SHA1Reset (&c);
! 437: SHA1Input (&c, (const unsigned char*)string, strlen(string));
! 438: if (!SHA1Result (&c))
! 439: throw Exception ("parser.runtime", 0, "Cannot compute SHA1");
! 440:
! 441: char digest[128];
! 442: sprintf(digest, "%08x%08x%08x%08x%08x", c.Message_Digest[0], c.Message_Digest[1], c.Message_Digest[2], c.Message_Digest[3], c.Message_Digest[4]);
! 443:
! 444: char *ret = new(PointerFreeGC) char[strlen(digest)+1];
! 445: strcpy(ret, digest);
! 446: r.write_pass_lang(*new String(ret, 0, false));
! 447: }
! 448:
! 449:
1.28 paf 450: /// to hell with extra bytes on 64bit platforms
451: struct uuid {
452: unsigned int time_low;
453: unsigned short time_mid;
454: unsigned short time_hi_and_version;
455: unsigned short clock_seq;
456: unsigned char node[6];
457: };
1.34 paf 458: static void _uuid(Request& r, MethodParams& /*params*/) {
1.28 paf 459:
460: // random
461: struct uuid uuid;
462: random(&uuid, sizeof(uuid));
463:
464: // http://www.opengroup.org/onlinepubs/9629399/apdxa.htm#tagtcjh_35
465: // ~
466: // version = DCE Security version, with embedded POSIX UIDs.
467: // variant = DCE
468: //
469: // DCE=Distributed Computing Environment
470: // http://www.opengroup.org/dce/
471: //
472: // they say this influences comparison&such,
473: // but could not figure out how, hence structure layout specified strictly
474: // anyhow, uuidgen on Win32 yield those values
475: //
476: // xxxxxxxx-xxxx-4xxx-{8,9,A,B}xxx-xxxxxxxxxxxx
477: uuid.clock_seq = (uuid.clock_seq & 0x3FFF) | 0x8000;
478: uuid.time_hi_and_version = (uuid.time_hi_and_version & 0x0FFF) | 0x4000;
479:
480: // format
1.34 paf 481: const int uuid_cstr_bufsize=36+1/*for zero-teminator*/+1/*for faulty snprintfs*/;
482: char *uuid_cstr=new(PointerFreeGC) char[uuid_cstr_bufsize];
1.29 paf 483: snprintf(uuid_cstr, uuid_cstr_bufsize,
1.28 paf 484: "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
485: uuid.time_low, uuid.time_mid, uuid.time_hi_and_version,
486: uuid.clock_seq >> 8, uuid.clock_seq & 0xFF,
487: uuid.node[0], uuid.node[1], uuid.node[2],
488: uuid.node[3], uuid.node[4], uuid.node[5]);
489:
1.34 paf 490: r.write_pass_lang(*new String(uuid_cstr));
1.28 paf 491: }
492:
1.34 paf 493: static void _uid64(Request& r, MethodParams& /*params*/) {
1.30 paf 494:
495: unsigned char id[64/8];
496: random(&id, sizeof(id));
497:
1.34 paf 498: r.write_pass_lang(*new String(hex_string(id, sizeof(id), true)));
1.30 paf 499: }
500:
1.43 misha 501: static void _crc32(Request& r, MethodParams& params) {
502: const char *string=params.as_string(0, "parameter must be string").cstr();
503: r.write_no_lang(*new VInt(pa_crc32(string, strlen(string))));
504: }
505:
1.49 ! misha 506: static void _long2ip(Request& r, MethodParams& params) {
! 507: unsigned long l=(unsigned long)trunc(params.as_double(0, "parameter must be expression", r));
! 508: static const int ip_cstr_bufsize=15+1+1;
! 509: char* ip_cstr=new(PointerFreeGC) char[ip_cstr_bufsize];
! 510:
! 511: snprintf(ip_cstr, ip_cstr_bufsize, "%d.%d.%d.%d",
! 512: (l>>24) & 0xFF,
! 513: (l>>16) & 0xFF,
! 514: (l>>8) & 0xFF,
! 515: l & 0xFF);
! 516:
! 517: r.write_no_lang(*new String(ip_cstr));
! 518: }
! 519:
1.1 parser 520: // constructor
521:
1.34 paf 522: MMath::MMath(): Methoded("math") {
1.1 parser 523: // ^FUNC(expr)
1.28 paf 524: #define ADDX(name, X) \
525: add_native_method(#name, Method::CT_STATIC, _##name, X, X)
526: #define ADD0(name) ADDX(name, 0)
527: #define ADD1(name) ADDX(name, 1)
528: #define ADD2(name) ADDX(name, 2)
1.1 parser 529:
530: ADD1(round); ADD1(floor); ADD1(ceiling);
1.3 parser 531: ADD1(trunc); ADD1(frac);
1.1 parser 532: ADD1(abs); ADD1(sign);
1.46 misha 533: ADD1(exp);
1.48 misha 534: ADD1(log); ADD1(log10);
1.1 parser 535: ADD1(sin); ADD1(asin);
536: ADD1(cos); ADD1(acos);
537: ADD1(tan); ADD1(atan);
1.3 parser 538: ADD1(degrees); ADD1(radians);
1.1 parser 539: ADD1(sqrt);
1.3 parser 540: ADD1(random);
1.1 parser 541:
1.49 ! misha 542: // ^math:pow(x;y)
1.1 parser 543: ADD2(pow);
544:
1.49 ! misha 545: // ^math:crypt[password;salt]
1.19 paf 546: ADD2(crypt);
1.26 paf 547:
1.49 ! misha 548: // ^math:md5[string]
1.26 paf 549: ADD1(md5);
1.5 parser 550:
1.49 ! misha 551: // ^math:sha1[string]
! 552: ADD1(sha1);
! 553:
! 554: // ^math:crc32[string]
1.43 misha 555: ADD1(crc32);
556:
1.49 ! misha 557: ADD1(long2ip);
! 558:
! 559: // ^math:uuid[]
1.29 paf 560: ADD0(uuid);
561:
1.49 ! misha 562: // ^math:uid64[]
1.30 paf 563: ADD0(uid64);
1.1 parser 564: }
E-mail: