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