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
|
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* A bloom filter.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "sslbloom.h"
#include "prnetdb.h"
#include "secport.h"
static inline unsigned int
sslBloom_Size(unsigned int bits)
{
return (bits >= 3) ? (1 << (bits - 3)) : 1;
}
SECStatus
sslBloom_Init(sslBloomFilter *filter, unsigned int k, unsigned int bits)
{
PORT_Assert(filter);
PORT_Assert(bits > 0);
PORT_Assert(bits <= sizeof(PRUint32) * 8);
PORT_Assert(k > 0);
filter->filter = PORT_ZNewArray(PRUint8, sslBloom_Size(bits));
if (!filter->filter) {
return SECFailure; /* Error code already set. */
}
filter->k = k;
filter->bits = bits;
return SECSuccess;
}
void
sslBloom_Zero(sslBloomFilter *filter)
{
PORT_Memset(filter->filter, 0, sslBloom_Size(filter->bits));
}
void
sslBloom_Fill(sslBloomFilter *filter)
{
PORT_Memset(filter->filter, 0xff, sslBloom_Size(filter->bits));
}
static PRBool
sslBloom_AddOrCheck(sslBloomFilter *filter, const PRUint8 *hashes, PRBool add)
{
unsigned int iteration;
unsigned int bitIndex;
PRUint32 tmp = 0;
PRUint8 mask;
unsigned int bytes = (filter->bits + 7) / 8;
unsigned int shift = (bytes * 8) - filter->bits;
PRBool found = PR_TRUE;
PORT_Assert(bytes <= sizeof(unsigned int));
for (iteration = 0; iteration < filter->k; ++iteration) {
PORT_Memcpy(((PRUint8 *)&tmp) + (sizeof(tmp) - bytes),
hashes, bytes);
hashes += bytes;
bitIndex = PR_ntohl(tmp) >> shift;
mask = 1 << (bitIndex % 8);
found = found && filter->filter[bitIndex / 8] & mask;
if (add) {
filter->filter[bitIndex / 8] |= mask;
}
}
return found;
}
PRBool
sslBloom_Add(sslBloomFilter *filter, const PRUint8 *hashes)
{
return sslBloom_AddOrCheck(filter, hashes, PR_TRUE);
}
PRBool
sslBloom_Check(sslBloomFilter *filter, const PRUint8 *hashes)
{
return sslBloom_AddOrCheck(filter, hashes, PR_FALSE);
}
void
sslBloom_Destroy(sslBloomFilter *filter)
{
PORT_Free(filter->filter);
PORT_Memset(filter, 0, sizeof(*filter));
}
|