X-Git-Url: https://git.saurik.com/redis.git/blobdiff_plain/9ea54feef0f2e62f7618da9b0ce3acce9f474db6..7eb850ef0e437323e2d84157ddc2e6e82af57bbc:/src/util.c diff --git a/src/util.c b/src/util.c index f7437e1c..e3224f50 100644 --- a/src/util.c +++ b/src/util.c @@ -5,6 +5,9 @@ #include #include #include +#include +#include +#include #include "util.h" @@ -317,7 +320,7 @@ int d2string(char *buf, size_t len, double value) { * integer printing function that is much faster. */ double min = -4503599627370495; /* (2^52)-1 */ double max = 4503599627370496; /* -(2^52) */ - if (val > min && val < max && value == ((double)((long long)value))) + if (value > min && value < max && value == ((double)((long long)value))) len = ll2string(buf,len,(long long)value); else #endif @@ -327,6 +330,52 @@ int d2string(char *buf, size_t len, double value) { return len; } +/* Generate the Redis "Run ID", a SHA1-sized random number that identifies a + * given execution of Redis, so that if you are talking with an instance + * having run_id == A, and you reconnect and it has run_id == B, you can be + * sure that it is either a different instance or it was restarted. */ +void getRandomHexChars(char *p, unsigned int len) { + FILE *fp = fopen("/dev/urandom","r"); + char *charset = "0123456789abcdef"; + unsigned int j; + + if (fp == NULL || fread(p,len,1,fp) == 0) { + /* If we can't read from /dev/urandom, do some reasonable effort + * in order to create some entropy, since this function is used to + * generate run_id and cluster instance IDs */ + char *x = p; + unsigned int l = len; + struct timeval tv; + pid_t pid = getpid(); + + /* Use time and PID to fill the initial array. */ + gettimeofday(&tv,NULL); + if (l >= sizeof(tv.tv_usec)) { + memcpy(x,&tv.tv_usec,sizeof(tv.tv_usec)); + l -= sizeof(tv.tv_usec); + x += sizeof(tv.tv_usec); + } + if (l >= sizeof(tv.tv_sec)) { + memcpy(x,&tv.tv_sec,sizeof(tv.tv_sec)); + l -= sizeof(tv.tv_sec); + x += sizeof(tv.tv_sec); + } + if (l >= sizeof(pid)) { + memcpy(x,&pid,sizeof(pid)); + l -= sizeof(pid); + x += sizeof(pid); + } + /* Finally xor it with rand() output, that was already seeded with + * time() at startup. */ + for (j = 0; j < len; j++) + p[j] ^= rand(); + } + /* Turn it into hex digits taking just 4 bits out of 8 for every byte. */ + for (j = 0; j < len; j++) + p[j] = charset[p[j] & 0x0F]; + fclose(fp); +} + #ifdef UTIL_TEST_MAIN #include