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