Skip to content

Commit

Permalink
Merge pull request #3479 from ar45/uuid-v7
Browse files Browse the repository at this point in the history
Add support for UUID version 7 generation.
  • Loading branch information
liviuchircu authored Oct 18, 2024
2 parents e9f9e8e + 66ace29 commit c49a974
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
4 changes: 4 additions & 0 deletions modules/uuid/doc/uuid_admin.xml
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ xlog("generated uuid: $uuid\n");
generated by hashing a namespace identifier and name
via SHA-1.</para>
</listitem>
<listitem>
<para><emphasis>7</emphasis> - version 7 UUID
generated by timestamp and randomness.</para>
</listitem>
</itemizedlist>
</para>
</listitem>
Expand Down
34 changes: 34 additions & 0 deletions modules/uuid/uuid.c
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#include "../../mod_fix.h"
#include "../../dprint.h"

#include <unistd.h>
#include <uuid/uuid.h>

#define UUID_STR_BUFSIZE 37
Expand All @@ -37,6 +38,7 @@ enum uuid_gen_vers {
UUID_VERS_3 = 3,
UUID_VERS_4 = 4,
UUID_VERS_5 = 5,
UUID_VERS_7 = 7,
};

static uuid_t uuid;
Expand Down Expand Up @@ -86,6 +88,34 @@ struct module_exports exports= {
0
};

static int gen_uuidv7(uuid_t value) {
// random bytes
if (getentropy(value, 16) != 0) {
return -1;
}

// current timestamp in ms
struct timeval tv;
if (gettimeofday(&tv, NULL) != 0)
return -1;

uint64_t timestamp = (uint64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;

// timestamp
value[0] = (timestamp >> 40) & 0xFF;
value[1] = (timestamp >> 32) & 0xFF;
value[2] = (timestamp >> 24) & 0xFF;
value[3] = (timestamp >> 16) & 0xFF;
value[4] = (timestamp >> 8) & 0xFF;
value[5] = timestamp & 0xFF;

// version and variant
value[6] = (value[6] & 0x0F) | 0x70;
value[8] = (value[8] & 0x3F) | 0x80;

return RET_OK;
}

static int gen_uuid(enum uuid_gen_vers vers, str *ns, str *n, pv_value_t *res)
{
int rc = RET_OK;
Expand Down Expand Up @@ -133,6 +163,9 @@ static int gen_uuid(enum uuid_gen_vers vers, str *ns, str *n, pv_value_t *res)
case UUID_VERS_4:
uuid_generate_random(uuid);
break;
case UUID_VERS_7:
rc = gen_uuidv7(uuid);
break;
default:
LM_BUG("Bad UUID generation algorithm selected\n");
return RET_ERR;
Expand Down Expand Up @@ -193,6 +226,7 @@ static int w_uuid(struct sip_msg *msg, pv_spec_t *out_var, int *vers_param, str
case UUID_VERS_3:
#endif
case UUID_VERS_4:
case UUID_VERS_7:
#ifdef UUID_TYPE_DCE_SHA1
case UUID_VERS_5:
#endif
Expand Down

0 comments on commit c49a974

Please sign in to comment.