Annotation of parser3/src/classes/math.C, revision 1.33
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.33 ! paf 11: static const char* IDENT_MATH_C="$Date: 2003/05/26 09:32:29 $";
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));
1.32 paf 151: return int(double(raw) / 0xFFFFFFFFu * 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.30 paf 285: static const char* hex_string(Pool& pool, unsigned char* bytes, size_t size, bool upcase) {
286: char *bytes_hex=(char *)pool.malloc(size*2/*byte->hh*/+1/*for zero-teminator*/);
287: unsigned char *src=bytes;
288: unsigned char *end=bytes+size;
289: char *dest=bytes_hex;
1.31 paf 290:
291: static const char *hex=upcase?"0123456789ABCDEF":"0123456789abcdef";
292:
1.30 paf 293: const char *format=upcase?"%02X":"%02x";
1.31 paf 294: for(; src<end; src++) {
295: *dest++=hex[*src/0x10];
296: *dest++=hex[*src%0x10];
297: }
298: *dest=0;
1.30 paf 299:
300: return bytes_hex;
301: }
302:
1.26 paf 303: static void _md5(Request& r, const String& method_name, MethodParams *params) {
304: Pool& pool=r.pool();
305: const char *string=params->as_string(0, "parameter must be string").cstr();
1.27 paf 306:
307:
308: PA_MD5_CTX context;
309: unsigned char digest[16];
310: PA_MD5Init(&context);
311: PA_MD5Update(&context, (const unsigned char*)string, strlen(string));
312: PA_MD5Final(digest, &context);
313:
1.30 paf 314: r.write_pass_lang(*new(pool) String(pool,
315: hex_string(pool, digest, sizeof(digest), false)));
1.26 paf 316: }
317:
1.28 paf 318: /// to hell with extra bytes on 64bit platforms
319: struct uuid {
320: unsigned int time_low;
321: unsigned short time_mid;
322: unsigned short time_hi_and_version;
323: unsigned short clock_seq;
324: unsigned char node[6];
325: };
1.29 paf 326: static void _uuid(Request& r, const String& method_name, MethodParams *params) {
1.28 paf 327: Pool& pool=r.pool();
328:
329: // random
330: struct uuid uuid;
331: random(&uuid, sizeof(uuid));
332:
333: // http://www.opengroup.org/onlinepubs/9629399/apdxa.htm#tagtcjh_35
334: // ~
335: // version = DCE Security version, with embedded POSIX UIDs.
336: // variant = DCE
337: //
338: // DCE=Distributed Computing Environment
339: // http://www.opengroup.org/dce/
340: //
341: // they say this influences comparison&such,
342: // but could not figure out how, hence structure layout specified strictly
343: // anyhow, uuidgen on Win32 yield those values
344: //
345: // xxxxxxxx-xxxx-4xxx-{8,9,A,B}xxx-xxxxxxxxxxxx
346: uuid.clock_seq = (uuid.clock_seq & 0x3FFF) | 0x8000;
347: uuid.time_hi_and_version = (uuid.time_hi_and_version & 0x0FFF) | 0x4000;
348:
349: // format
1.33 ! paf 350: const int uuid_cstr_bufsize=36+1/*for zero-teminator*/+1/*buggy snprintfs*/;
1.29 paf 351: char *uuid_cstr=(char *)pool.malloc(uuid_cstr_bufsize);
352: snprintf(uuid_cstr, uuid_cstr_bufsize,
1.28 paf 353: "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
354: uuid.time_low, uuid.time_mid, uuid.time_hi_and_version,
355: uuid.clock_seq >> 8, uuid.clock_seq & 0xFF,
356: uuid.node[0], uuid.node[1], uuid.node[2],
357: uuid.node[3], uuid.node[4], uuid.node[5]);
358:
1.29 paf 359: r.write_pass_lang(*new(pool) String(pool, uuid_cstr));
1.28 paf 360: }
361:
1.30 paf 362: static void _uid64(Request& r, const String& method_name, MethodParams *params) {
363: Pool& pool=r.pool();
364:
365: unsigned char id[64/8];
366: random(&id, sizeof(id));
367:
368: r.write_pass_lang(*new(pool) String(pool,
369: hex_string(pool, id, sizeof(id), true)));
370: }
371:
1.1 parser 372: // constructor
373:
1.18 paf 374: MMath::MMath(Pool& apool) : Methoded(apool, "math") {
1.1 parser 375: // ^FUNC(expr)
1.28 paf 376: #define ADDX(name, X) \
377: add_native_method(#name, Method::CT_STATIC, _##name, X, X)
378: #define ADD0(name) ADDX(name, 0)
379: #define ADD1(name) ADDX(name, 1)
380: #define ADD2(name) ADDX(name, 2)
1.1 parser 381:
382: ADD1(round); ADD1(floor); ADD1(ceiling);
1.3 parser 383: ADD1(trunc); ADD1(frac);
1.1 parser 384: ADD1(abs); ADD1(sign);
385: ADD1(exp); ADD1(log);
386: ADD1(sin); ADD1(asin);
387: ADD1(cos); ADD1(acos);
388: ADD1(tan); ADD1(atan);
1.3 parser 389: ADD1(degrees); ADD1(radians);
1.1 parser 390: ADD1(sqrt);
1.3 parser 391: ADD1(random);
1.1 parser 392:
393: // ^pow(x;y)
394: ADD2(pow);
395:
1.19 paf 396: // ^crypt[password;salt]
397: ADD2(crypt);
1.26 paf 398:
399: // ^md5[string]
400: ADD1(md5);
1.5 parser 401:
1.29 paf 402: // ^uuid[]
403: ADD0(uuid);
404:
1.30 paf 405: // ^uid64[]
406: ADD0(uid64);
1.1 parser 407: }
408:
1.2 parser 409: // global variables
410:
411: Methoded *math_base_class;
412: Hash *math_consts;
413:
1.1 parser 414: // creator
415:
416: Methoded *MMath_create(Pool& pool) {
1.2 parser 417: math_consts=new(pool) Hash(pool);
418: math_consts->put(
419: *new(pool) String(pool, "PI"),
1.3 parser 420: new(pool) VDouble(pool, PI));
1.2 parser 421:
422: return math_base_class=new(pool) MMath(pool);
1.1 parser 423: }
E-mail: