blob: 03fc8df89a13380816d962766f77601578c63b82 (
plain) (
blame)
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
|
#include "config.h"
#include <assert.h>
#include <pthread.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <siphash.h>
#include "hash.h"
#include "logerr.h"
#include "random.h"
static volatile bool
INITIALIZED = false;
static uint8_t
HASH_KEY[SIPHASHBS_KEY_LENGTH];
static pthread_mutex_t
SEED_MUTEX = PTHREAD_MUTEX_INITIALIZER;
static int
unsafe_init(void) {
int rc = -1;
if (urandom_bytes(SIPHASHBS_KEY_LENGTH, &HASH_KEY)) {
logerr("urandom_bytes()");
goto out;
}
rc = 0;
out:
return rc;
}
static int
safe_init(void) {
int rc = -1;
bool lock_acquired = false;
if (INITIALIZED == true) {
rc = 0;
goto out;
}
const int ret1 = pthread_mutex_lock(&SEED_MUTEX);
if (ret1) {
logerr("pthread_mutex_lock(): %s", strerror(ret1));
goto out;
}
lock_acquired = true;
if (INITIALIZED == true) {
rc = 0;
goto out;
}
if (unsafe_init()) {
logerr("unsafe_init()");
goto out;
}
INITIALIZED = true;
rc = 0;
out:
if (lock_acquired) {
const int ret2 = pthread_mutex_unlock(&SEED_MUTEX);
if (ret2) {
logerr("pthread_mutex_unlock(): %s", strerror(ret2));
rc = -1;
}
}
return rc;
}
static void
ensure_initialized(void) {
assert((safe_init() == 0) && "Failed to initialized the hash seed");
}
int
hash_init(void) {
return safe_init();
}
void
hash(
const size_t inlen,
const void *const restrict in,
uint8_t out[HASH_OUTPUT_LENGTH]
) {
ensure_initialized();
siphashbs(HASH_KEY, inlen, in, out);
}
|