1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
|
/*
mxUID -- An UID datatype
Copyright (c) 1998-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
Copyright (c) 2000-2011, eGenix.com Software GmbH; mailto:info@egenix.com
See the documentation for further copyright information or contact
the author (mailto:mal@lemburg.com).
*/
/* Debug defines: */
/*#define MAL_MEM_DEBUG*/
/*#define MAL_DEBUG*/
/*#define MAL_REF_DEBUG*/
/* Logging file used by debugging facility */
#ifndef MAL_DEBUG_OUTPUTFILE
# define MAL_DEBUG_OUTPUTFILE "mxUID.log"
#endif
/* We want all our symbols to be exported */
#define MX_BUILDING_MXUID
/* Mark the module as Py_ssize_t clean. */
#define PY_SSIZE_T_CLEAN 1
/* Setup mxstdlib memory management */
#if 1
# define MAL_USE_PYMALLOC
#else
# define MAL_USE_C_MALLOC
#endif
#include "mx.h"
#include "mxUID.h"
#include <ctype.h>
#include <time.h>
/* Version number: Major.Minor.Patchlevel */
#define MXUID_VERSION "3.2.1"
/* Additional includes needed for mxUID_GetCurrentTime() API */
# if defined(HAVE_SYS_TIME_H) && defined(TIME_WITH_SYS_TIME)
# include <sys/time.h>
# include <time.h>
# else
# include <time.h>
# endif
# ifdef HAVE_UNISTD_H
# include <unistd.h>
# endif
/* Define this to have the module use a free list for UIDs */
#define MXUID_FREELIST
/* Define this to enable the speedup in mxUID_SchemeUsesRelativePaths()
that uses hard-coded values for the uses_relative part of the
scheme dict entries in mxUID_SchemeDict below. Saves a
dictionary lookup for every join. */
#define HARDCODE_SCHEMES_USES_RELATIVE
/* --- module doc-string -------------------------------------------------- */
static char *Module_docstring =
MXUID_MODULE" -- An UID datatype.\n\n"
"Version "MXUID_VERSION"\n\n"
"Copyright (c) 1998-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com\n"
"Copyright (c) 2000-2011, eGenix.com Software GmbH; mailto:info@egenix.com\n\n"
" All Rights Reserved\n\n"
"See the documentation for further information on copyrights,\n"
"or contact the author."
;
/* --- module globals ----------------------------------------------------- */
static PyObject *mxUID_Error; /* Error Exception object */
static unsigned int mxUID_IDCounter; /* ID Counter (20 bit) */
static unsigned int mxUID_HostID; /* Host ID (16 bit) */
static unsigned int mxUID_ProcessID; /* Process ID (16 bit) */
/* Flag telling us whether the module was initialized or not. */
static int mxUID_Initialized = 0;
/* --- forward declarations ----------------------------------------------- */
/* --- internal macros ---------------------------------------------------- */
/* --- module helpers ----------------------------------------------------- */
/* Create an exception object, insert it into the module dictionary
under the given name and return the object pointer; this is NULL in
case an error occurred. base can be given to indicate the base
object to be used by the exception object. It should be NULL
otherwise */
static
PyObject *insexc(PyObject *moddict,
char *name,
PyObject *base)
{
PyObject *v;
char fullname[256];
char *modname;
char *dot;
v = PyDict_GetItemString(moddict, "__name__");
if (v == NULL)
modname = NULL;
else
modname = PyString_AsString(v);
if (modname == NULL) {
PyErr_Clear();
modname = MXUID_MODULE;
}
/* The symbols from this extension are imported into
mx.<packagename>. We trim the name to not confuse the user with
an overly long package path. */
strcpy(fullname, modname);
dot = strchr(fullname, '.');
if (dot)
dot = strchr(dot+1, '.');
if (dot)
strcpy(dot+1, name);
else
sprintf(fullname, "%s.%s", modname, name);
v = PyErr_NewException(fullname, base, NULL);
if (v == NULL)
return NULL;
if (PyDict_SetItemString(moddict,name,v))
return NULL;
return v;
}
#if 0
/* Helper for adding integer constants. Check for errors with
PyErr_Occurred() */
static
void insint(PyObject *dict,
char *name,
int value)
{
PyObject *v = PyInt_FromLong((long)value);
PyDict_SetItemString(dict, name, v);
Py_XDECREF(v);
}
#endif
#ifdef Py_NEWSTYLENUMBER
static
PyObject *notimplemented1(PyObject *v)
{
Py_Error(PyExc_TypeError,
"operation not implemented");
onError:
return NULL;
}
static
PyObject *notimplemented2(PyObject *v, PyObject *w)
{
Py_Error(PyExc_TypeError,
"operation not implemented");
onError:
return NULL;
}
static
PyObject *notimplemented3(PyObject *u, PyObject *v, PyObject *w)
{
Py_Error(PyExc_TypeError,
"operation not implemented");
onError:
return NULL;
}
#endif
/* --- internal functions --- */
static
unsigned int mxUID_CRC32(char *str,
Py_ssize_t len)
{
Py_ssize_t i,j;
register unsigned char *s = (unsigned char *)str;
register int x;
register int y;
x = 0;
y = 0;
for (i = 0, j = len + 1; i < len; i++,j--) {
register unsigned char c = s[i];
x += c;
x &= 0xFFFF;
y += (j & 0xFFFF) * c;
y &= 0xFFFF;
}
return (unsigned int)(x + (y<<16));
}
static
unsigned short mxUID_CRC16(char *str,
Py_ssize_t len)
{
Py_ssize_t i,j;
register unsigned char *s = (unsigned char *)str;
register int x;
register int y;
x = 0;
y = 0;
for (i = 0, j = len + 1; i < len; i++,j--) {
register unsigned char c = s[i];
x += c;
x &= 0xFF;
y += (j & 0xFFFF) * c;
y &= 0xFF;
}
return (unsigned short)(x + (y<<8));
}
/* Folds a string in with length in_len into a string out having
length out_len. The output string is zero terminated; its buffer
must have size out_len + 1.
XXX This functions doesn't really do what it's supposed to... better
not rely on it's output !
*/
static
void mxUID_Fold(char *in_str,
Py_ssize_t in_len,
char *out_str,
Py_ssize_t out_len)
{
Py_ssize_t chunksize;
register unsigned char *in = (unsigned char *)in_str;
register unsigned char *out = (unsigned char *)out_str;
/* First pass */
chunksize = min(in_len, out_len);
memcpy(out, in, chunksize);
if (chunksize < out_len)
memset(out + chunksize, 0, out_len - chunksize);
in += chunksize;
in_len -= chunksize;
/* Next passes */
while (in_len > 0) {
register Py_ssize_t i;
chunksize = min(in_len, out_len);
for (i = 0; i < chunksize; i++)
out[i] ^= in[i];
in += chunksize;
in_len -= chunksize;
}
/* Zero terminate */
out[out_len] = '\0';
}
/* Fold a long integer to 16 bits of data */
static
unsigned short mxUID_FoldInteger(long value)
{
unsigned short result = 0;
Py_ssize_t i;
for (i = 0; i < sizeof(value) / 2; i++) {
result ^= value & 0xFFFF;
value >>= 16;
}
return result;
}
/* Apply a one-time pad to a data string. The data string should only
use lowercase HEX characters (all other characters are passed
through unchanged). */
static
int mxUID_OneTimePad(unsigned char *data,
unsigned char *out,
Py_ssize_t data_len,
unsigned char *otp,
Py_ssize_t otp_len)
{
register Py_ssize_t i, j;
static char charbase[] = "0123456789abcdef";
if (otp_len <= 0 || otp == NULL) {
memcpy(out, data, data_len);
return 0;
}
for (i = 0, j = 0; i < data_len; i++) {
register unsigned char c = data[i];
register unsigned char x = otp[j];
if (c >= '0' && c <= '9')
c = c - '0';
else if (c >= 'a' && c <= 'f')
c = c - 'a' + 10;
#if 0
else if (c >= 'A' && c <= 'F')
c = c - 'A' + 10;
#endif
else {
out[i] = c;
goto next;
}
out[i] = charbase[(c ^ x ^ (x >> 4)) & 0x0F];
next:
DPRINTF("i=%i, j=%i, data[i]='%c', ot[j]='%c', c=%i, x=%i -> out[i]='%c'\n",
i, j, data[i], otp[j], c, x, out[i]);
if (++j >= otp_len)
j = 0;
}
return 0;
}
/* Verify an unencrypted UID string uid with length uid_len using the
embedded CRC-16 value. If the UID string was generated using a code
string, this must be given too. Otherwise, NULL may be used. */
static
int mxUID_Verify(char *uid,
Py_ssize_t uid_len,
char *code)
{
int crc16;
int value = -1;
if (uid_len < 32)
return 0;
crc16 = (int)mxUID_CRC16(uid, uid_len - 4);
if (sscanf((char *)(uid + uid_len - 4), "%x", &value) <= 0)
return 0;
DPRINTF("crc=%i, value=%i\n", crc16, value);
if (crc16 != value)
return 0;
if (code) {
Py_ssize_t code_len = strlen(code);
if (uid_len != 32 + code_len)
return 0;
if (code_len == 0)
return 1;
return (memcmp(code, uid + 28, strlen(code)) == 0);
}
else if (uid_len != 32)
return 0;
return 1;
}
/* Returns the current time in Unix ticks.
The function tries to use the gettimeofday() API in BSD systems and
falls back to time() for all others.
-1.0 is returned in case of an error.
(Taken from mxDateTime.c.)
*/
static
double mxUID_GetCurrentTime(void)
{
#ifdef HAVE_GETTIMEOFDAY
struct timeval tv;
# ifdef GETTIMEOFDAY_NO_TZ
if (!gettimeofday(&tv))
# else
if (!gettimeofday(&tv, 0))
# endif
return ((double)tv.tv_sec + (double)tv.tv_usec * 1e-6);
else
return -1.0;
#else
time_t ticks;
time(&ticks);
return (double) ticks;
#endif
}
/* --- C API --------------------------------------------------------------- */
/* Build a new UID string for object with address id.
code is optionally included in UID if given. It may be NULL.
timestamp should be a double indicating Unix ticks, or -1 to have
the API use the current time.
The output buffer uid must have room for at least 512
bytes. uid_len is set to the uid data length. It must be preset to
the buffer's size.
Returns the Python string object on success, NULL on error.
*/
static
PyObject *mxUID_New(void *obj,
char *code,
double timestamp)
{
unsigned int t_hi, t_lo, id;
Py_ssize_t len;
int crc16;
char uid[256];
/* Build UID */
if (code) {
Py_Assert(strlen(code) < 100,
PyExc_ValueError,
"len(code) must be <100");
}
else
code = "";
/* For the object id simply take the address and fold into 16
bits */
id = mxUID_FoldInteger((long)obj);
/* Build timestamp */
if (timestamp == -1)
timestamp = mxUID_GetCurrentTime();
if (timestamp >= 0) {
timestamp *= 97.5;
t_hi = (unsigned int)(timestamp / 4294967296.0);
t_lo = (unsigned int)(timestamp - t_hi * 4294967296.0);
Py_Assert(t_hi <= 0xFF,
PyExc_ValueError,
"timestamp value too large");
}
else
Py_Error(PyExc_ValueError,
"timestamp must be positive");
/* Format the UID string. Also see mxUID_Verify() and mangle()
demangle() in UID.py. */
len = sprintf(uid,
"%06x" /* 24-bit counter */
"%02x%08x" /* 40-bit timestamp */
"%04x" /* 16-bit pid */
"%04x" /* 16-bit hostid */
"%04x" /* id(v) */
"%.100s" /* optional code */
,
mxUID_IDCounter & 0xFFFFFF,
t_hi,t_lo,
mxUID_ProcessID,
mxUID_HostID,
id,
code);
Py_Assert(len < sizeof(uid) - 5,
PyExc_SystemError,
"internal error in mxUID_UID: buffer overflow");
/* Increment counter; overflow is intended */
mxUID_IDCounter += 1000003;
/* Add 16 bit CRC value in HEX */
crc16 = (int)mxUID_CRC16(uid, len);
len += sprintf(&uid[len], "%04x", crc16);
return PyString_FromStringAndSize(uid, len);
onError:
return NULL;
}
/* Extracts the ticks timestamp from an unencrypted UID string uid */
static
double mxUID_ExtractTimestamp(unsigned char *uid)
{
int i;
double ticks = 0.0,
base = 1.0;
for (i = 15; i >= 6; i--) {
char c = uid[i];
int value;
if (c >= '0' && c <= '9')
value = c - '0';
else if (c >= 'a' && c <= 'f')
value = c - 'a' + 10;
else if (c >= 'A' && c <= 'F')
value = c - 'A' + 10;
else
/* Hmm, a buggy character: ignore... */
value = 0;
/*printf("i=%i s[i]=%c value=%i, ticks=%f, base=%f\n",
i,c,value,ticks,base);*/
if (value)
ticks += base * value;
base *= 16.0;
}
return ticks / 97.5;
}
/* --- Python API ---------------------------------------------------------- */
Py_C_Function_WithKeywords(
mxUID_UID,
"UID(object=None, code='', timestamp=None)\n\n"
"Create a new UID string for object. code is optionally\n"
"included in the UID. timestamp must be a ticks float and\n"
"defaults to the current time."
)
{
PyObject *object = Py_None;
char *code = NULL;
double timestamp = -1;
Py_KeywordsGet3Args("|Osd", object, code, timestamp);
/* Build UID string */
return mxUID_New(object, code, timestamp);
onError:
return NULL;
}
Py_C_Function_WithKeywords(
mxUID_setids,
"setids(hostid, pid, counter)\n\n"
"Sets the IDs to be used by the module. The function\n"
"can take keyword arguments in case only some values\n"
"need to be changed. All others are then left untouched."
)
{
unsigned int hostid=mxUID_HostID;
unsigned int pid=mxUID_ProcessID;
unsigned int counter=mxUID_IDCounter;
Py_KeywordsGet3Args("|iii", hostid, pid, counter);
mxUID_IDCounter = counter;
/* Map to 16 bits */
mxUID_HostID = mxUID_FoldInteger(hostid);
mxUID_ProcessID = mxUID_FoldInteger(pid);
Py_ReturnNone();
onError:
return NULL;
}
Py_C_Function( mxUID_getids,
"getids()\n\n"
"Returns a tuple (hostid16, pid16, counter) of the currently\n"
"active values used for UID generation."
)
{
Py_NoArgsCheck();
Py_Return3Args("(iii)",
mxUID_HostID, mxUID_ProcessID, mxUID_IDCounter);
onError:
return NULL;
}
Py_C_Function( mxUID_timestamp,
"timestamp(uid)\n\n"
"Returns the timestamp encoded in the UID."
)
{
unsigned char *s;
Py_ssize_t len;
Py_Get2Args("s#", s, len);
Py_Assert(len > 10 && len < 256,
PyExc_ValueError,
"need a UID string");
return PyFloat_FromDouble(mxUID_ExtractTimestamp(s));
onError:
return NULL;
}
Py_C_Function( mxUID_verify,
"verify(uid[, code])\n\n"
"Verifies the given UID string and returns 0/1 depending\n"
"on whether the UID matches the mxUID layout. code must be\n"
"given in case it was used to create the UID."
)
{
char *s;
Py_ssize_t len;
char *code = NULL;
Py_Get3Args("s#|s",
s, len, code);
Py_Assert(len > 10 && len < 256,
PyExc_ValueError,
"need a UID string");
return PyInt_FromLong(mxUID_Verify(s, len, code));
onError:
return NULL;
}
Py_C_Function( mxUID_fold,
"fold(string[,size=8])\n\n"
"Returns a new string with size bytes, which is deduced\n"
"from string by XOR folding it."
)
{
char *s;
Py_ssize_t size = 8;
Py_ssize_t len;
PyObject *v = NULL;
Py_Get3Args("s#|"Py_SSIZE_T_PARSERMARKER,
s, len, size);
v = PyString_FromStringAndSize(NULL,size);
if (!v)
goto onError;
mxUID_Fold(s, len, PyString_AS_STRING(v), size);
return v;
onError:
Py_XDECREF(v);
return NULL;
}
Py_C_Function( mxUID_otp,
"otp(data, pad)\n\n"
"Returns a one-time padded version of data using\n"
"pad as basis. This function is idempotent."
)
{
unsigned char *data;
Py_ssize_t data_len;
unsigned char *otp;
Py_ssize_t otp_len;
PyObject *v = NULL;
Py_Get4Args("s#s#",
data, data_len, otp, otp_len);
v = PyString_FromStringAndSize(NULL, data_len);
if (!v)
goto onError;
mxUID_OneTimePad(data, (unsigned char *)PyString_AS_STRING(v),
data_len, otp, otp_len);
return v;
onError:
Py_XDECREF(v);
return NULL;
}
Py_C_Function( mxUID_crc,
"crc(string[,bits=32])\n\n"
"Returns a CRC integer calculated from string having the\n"
"given number of bits (16 or 32)."
)
{
int bits = 32;
Py_ssize_t len;
long crc;
char *s;
Py_Get3Args("s#|i",
s, len, bits);
if (bits == 32)
crc = (long)mxUID_CRC32(s,len);
else if (bits == 16)
crc = (long)mxUID_CRC16(s,len);
else
Py_Error(PyExc_ValueError,
"only 16 or 32 bit CRCs are supported");
return PyInt_FromLong((long)crc);
onError:
return NULL;
}
/* --- module init --------------------------------------------------------- */
/* Python Method Table */
static
PyMethodDef Module_methods[] =
{
Py_MethodWithKeywordsListEntry("UID",mxUID_UID),
Py_MethodListEntry("timestamp",mxUID_timestamp),
Py_MethodListEntry("verify",mxUID_verify),
Py_MethodListEntry("crc",mxUID_crc),
Py_MethodListEntry("fold",mxUID_fold),
Py_MethodListEntry("otp",mxUID_otp),
Py_MethodWithKeywordsListEntry("setids",mxUID_setids),
Py_MethodListEntryNoArgs("getids",mxUID_getids),
{NULL,NULL} /* end of list */
};
/* C API table */
static
mxUIDModule_APIObject mxUIDModuleAPI =
{
mxUID_New,
mxUID_ExtractTimestamp,
};
/* Cleanup function */
static
void mxUIDModule_Cleanup(void)
{
/* Reset mxUID_Initialized flag */
mxUID_Initialized = 0;
}
/* create PyMethodObjects and register them in the module's dict */
MX_EXPORT(void)
initmxUID(void)
{
PyObject *module, *moddict, *api;
if (mxUID_Initialized)
Py_Error(PyExc_SystemError,
"can't initialize "MXUID_MODULE" more than once");
/* Create module */
module = Py_InitModule4(MXUID_MODULE, /* Module name */
Module_methods, /* Method list */
Module_docstring, /* Module doc-string */
(PyObject *)NULL, /* always pass this as *self */
PYTHON_API_VERSION); /* API Version */
if (module == NULL)
goto onError;
/* Add some constants to the module's dict */
moddict = PyModule_GetDict(module);
PyDict_SetItemString(moddict,
"__version__",
PyString_FromString(MXUID_VERSION));
if (!(mxUID_Error = insexc(moddict,"Error",PyExc_StandardError)))
goto onError;
/* Register cleanup function */
if (Py_AtExit(mxUIDModule_Cleanup)) {
/* XXX what to do if we can't register that function ??? */
DPRINTF("* Failed to register mxUID cleanup function\n");
}
/* Export C API */
api = PyCObject_FromVoidPtr((void *)&mxUIDModuleAPI, NULL);
if (api == NULL)
goto onError;
PyDict_SetItemString(moddict,MXUID_MODULE"API",api);
Py_DECREF(api);
/* We are now initialized */
mxUID_Initialized = 1;
onError:
/* Check for errors and report them */
if (PyErr_Occurred())
Py_ReportModuleInitError(MXUID_MODULE);
return;
}
|