Beispiel #1
0
char *TadsServerManager::gen_rand_id(void *obj)
{
    /* set up a hashing buffer */
    sha256_ctx s;
    sha256_begin(&s);

    /* add the current date/time to the hash */
    os_time_t timer = os_time(0);
    struct tm *tblock = os_localtime(&timer);
    sha256_hash((unsigned char *)tblock, sizeof(*tblock), &s);

    /* add the system timer to the hash */
    long systime = os_get_sys_clock_ms();
    sha256_hash((unsigned char *)&systime, sizeof(systime), &s);

    /* add the object address to the hash */
    sha256_hash((unsigned char *)obj, sizeof(obj), &s);

    /* add the current stack location to the hash */
    sha256_hash((unsigned char *)&obj, sizeof(void *), &s);

    /* add some random bytes from the operating system */
    unsigned char rbuf[128];
    os_gen_rand_bytes(rbuf, sizeof(rbuf));
    sha256_hash(rbuf, sizeof(rbuf), &s);

    /* compute the hash */
    unsigned char hval[32];
    sha256_end(hval, &s);

    /* convert it to hex, but just keep the low nybbles, for 32 digits */
    char *ret = lib_alloc_str(32);
    int i;
    for (i = 0 ; i < 32 ; ++i)
        ret[i] = nybble2hex(hval[i]);

    /* null-terminate the string */
    ret[i] = '\0';

    /* return the allocated string */
    return ret;
}
Beispiel #2
0
/*
 *   Allocate space for a string of known length, and save a copy of the
 *   string.  The length does not include a null terminator, and in fact
 *   the string does not need to be null-terminated.  The copy returned,
 *   however, is null-terminated.  
 */
char *lib_copy_str(const char *str, size_t len)
{
    /* if the source string is null, just return null as the result */
    if (str == 0)
        return 0;

    /* allocate space */
    char *buf = lib_alloc_str(len);

    /* if that succeeded, make a copy */
    if (buf != 0)
    {
        /* copy the string */
        memcpy(buf, str, len);

        /* null-terminate it */
        buf[len] = '\0';
    }

    /* return the buffer */
    return buf;
}