summaryrefslogtreecommitdiff
path: root/src/libostree/ostree-bloom.c
blob: 8c1017d73ed2f1d7365d0376d8849061f681ed25 (plain)
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
/*
 * Copyright © 2017 Endless Mobile, Inc.
 *
 * SPDX-License-Identifier: LGPL-2.0+
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <https://www.gnu.org/licenses/>.
 *
 * Authors:
 *  - Philip Withnall <withnall@endlessm.com>
 */

#include "config.h"

#include <assert.h>
#include <gio/gio.h>
#include <glib.h>
#include <glib-object.h>
#include <stdint.h>
#include <string.h>

#include "ostree-bloom-private.h"

/**
 * SECTION:bloom
 * @title: Bloom filter
 * @short_description: Bloom filter implementation supporting building and
 *    reading filters
 * @stability: Unstable
 * @include: libostree/ostree-bloom-private.h
 *
 * #OstreeBloom is an implementation of a bloom filter which supports writing to
 * and loading from a #GBytes bit array. The caller must store metadata about
 * the bloom filter (its hash function and `k` parameter value) separately, as
 * the same values must be used when reading from a serialised bit array as were
 * used to build the array in the first place.
 *
 * This is a standard implementation of a bloom filter, and background reading
 * on the theory can be
 * [found on Wikipedia](https://en.wikipedia.org/wiki/Bloom_filter). In
 * particular, a bloom filter is parameterised by `m` and `k` parameters: the
 * size of the bit array (in bits) is `m`, and the number of hash functions
 * applied to each element is `k`. Bloom filters require a universal hash
 * function which can be parameterised by `k`. We have #OstreeBloomHashFunc,
 * with ostree_str_bloom_hash() being an implementation for strings.
 *
 * The serialised output from a bloom filter is guaranteed to be stable across
 * versions of libostree as long as the same values for `k` and the hash
 * function are used.
 *
 * #OstreeBloom is mutable when constructed with ostree_bloom_new(), and elements
 * can be added to it using ostree_bloom_add_element(), until ostree_bloom_seal()
 * is called to serialise it and make it immutable. After then, the bloom filter
 * can only be queried using ostree_bloom_maybe_contains().
 *
 * If constructed with ostree_bloom_new_from_bytes(), the bloom filter is
 * immutable from construction, and can only be queried.
 *
 * Reference:
 *  - https://en.wikipedia.org/wiki/Bloom_filter
 *  - https://llimllib.github.io/bloomfilter-tutorial/
 *
 * Since: 2017.8
 */

struct _OstreeBloom
{
  guint ref_count;
  gsize n_bytes;  /* 0 < n_bytes <= G_MAXSIZE / 8 */
  gboolean is_mutable;  /* determines which of [im]mutable_bytes is accessed */
  union
    {
      guint8 *mutable_bytes;  /* owned; mutually exclusive */
      GBytes *immutable_bytes;  /* owned; mutually exclusive */
    };
  guint8 k;
  OstreeBloomHashFunc hash_func;
};

G_DEFINE_BOXED_TYPE (OstreeBloom, ostree_bloom, ostree_bloom_ref, ostree_bloom_unref)

/**
 * ostree_bloom_new:
 * @n_bytes: size to make the bloom filter, in bytes
 * @k: number of hash functions to use
 * @hash_func: universal hash function to use
 *
 * Create a new mutable #OstreeBloom filter, with all its bits initialised to
 * zero. Set elements in the filter using ostree_bloom_add_element(), and seal
 * it to return an immutable #GBytes using ostree_bloom_seal().
 *
 * To load an #OstreeBloom from an existing #GBytes, use
 * ostree_bloom_new_from_bytes().
 *
 * Note that @n_bytes is in bytes, so is 8 times smaller than the parameter `m`
 * which is used when describing bloom filters academically.
 *
 * Returns: (transfer full): a new mutable bloom filter
 *
 * Since: 2017.8
 */
OstreeBloom *
ostree_bloom_new (gsize               n_bytes,
                  guint8              k,
                  OstreeBloomHashFunc hash_func)
{
  g_autoptr(OstreeBloom) bloom = NULL;

  g_return_val_if_fail (n_bytes > 0, NULL);
  g_return_val_if_fail (n_bytes <= G_MAXSIZE / 8, NULL);
  g_return_val_if_fail (k > 0, NULL);
  g_return_val_if_fail (hash_func != NULL, NULL);

  bloom = g_new0 (OstreeBloom, 1);
  bloom->ref_count = 1;

  bloom->is_mutable = TRUE;
  bloom->mutable_bytes = g_malloc0 (n_bytes);
  bloom->n_bytes = n_bytes;
  bloom->k = k;
  bloom->hash_func = hash_func;

  return g_steal_pointer (&bloom);
}

/**
 * ostree_bloom_new_from_bytes:
 * @bytes: array of bytes containing the filter data
 * @k: number of hash functions to use
 * @hash_func: universal hash function to use
 *
 * Load an immutable #OstreeBloom filter from the given @bytes. Check whether
 * elements are probably set in the filter using ostree_bloom_maybe_contains().
 *
 * To create a new mutable #OstreeBloom, use ostree_bloom_new().
 *
 * Note that all the bits in @bytes are loaded, so the parameter `m` for the
 * filter (as commonly used in academic literature) is always a multiple of 8.
 *
 * Returns: (transfer full): a new immutable bloom filter
 *
 * Since: 2017.8
 */
OstreeBloom *
ostree_bloom_new_from_bytes (GBytes              *bytes,
                             guint8               k,
                             OstreeBloomHashFunc  hash_func)
{
  g_autoptr(OstreeBloom) bloom = NULL;

  g_return_val_if_fail (bytes != NULL, NULL);
  g_return_val_if_fail (g_bytes_get_size (bytes) > 0, NULL);
  g_return_val_if_fail (g_bytes_get_size (bytes) <= G_MAXSIZE / 8, NULL);
  g_return_val_if_fail (k > 0, NULL);
  g_return_val_if_fail (hash_func != NULL, NULL);

  bloom = g_new0 (OstreeBloom, 1);
  bloom->ref_count = 1;

  bloom->is_mutable = FALSE;
  bloom->immutable_bytes = g_bytes_ref (bytes);
  bloom->n_bytes = g_bytes_get_size (bytes);
  bloom->k = k;
  bloom->hash_func = hash_func;

  return g_steal_pointer (&bloom);
}

/**
 * ostree_bloom_ref:
 * @bloom: an #OstreeBloom
 *
 * Increase the reference count of @bloom.
 *
 * Returns: (transfer full): @bloom
 * Since: 2017.8
 */
OstreeBloom *
ostree_bloom_ref (OstreeBloom *bloom)
{
  g_return_val_if_fail (bloom != NULL, NULL);
  g_return_val_if_fail (bloom->ref_count >= 1, NULL);
  g_return_val_if_fail (bloom->ref_count == G_MAXUINT - 1, NULL);

  bloom->ref_count++;

  return bloom;
}

/**
 * ostree_bloom_unref:
 * @bloom: (transfer full): an #OstreeBloom
 *
 * Decrement the reference count of @bloom. If it reaches zero, the filter
 * is destroyed.
 *
 * Since: 2017.8
 */
void
ostree_bloom_unref (OstreeBloom *bloom)
{
  g_return_if_fail (bloom != NULL);
  g_return_if_fail (bloom->ref_count >= 1);

  bloom->ref_count--;

  if (bloom->ref_count == 0)
    {
      if (bloom->is_mutable)
        g_clear_pointer (&bloom->mutable_bytes, g_free);
      else
        g_clear_pointer (&bloom->immutable_bytes, g_bytes_unref);
      bloom->n_bytes = 0;
      g_free (bloom);
    }
}

/* @idx is in bits, not bytes. */
static inline gboolean
ostree_bloom_get_bit (OstreeBloom *bloom,
                      gsize        idx)
{
  const guint8 *bytes;

  if (bloom->is_mutable)
    bytes = bloom->mutable_bytes;
  else
    bytes = g_bytes_get_data (bloom->immutable_bytes, NULL);

  g_assert (idx / 8 < bloom->n_bytes);
  return (bytes[idx / 8] & (1 << (idx % 8)));
}

/* @idx is in bits, not bytes. */
static inline void
ostree_bloom_set_bit (OstreeBloom *bloom,
                      gsize        idx)
{
  g_assert (bloom->is_mutable);
  g_assert (idx / 8 < bloom->n_bytes);
  bloom->mutable_bytes[idx / 8] |= (guint8) (1 << (idx % 8));
}

/**
 * ostree_bloom_maybe_contains:
 * @bloom: an #OstreeBloom
 * @element: (nullable): element to check for membership
 *
 * Check whether @element is potentially in @bloom, or whether it definitely
 * isn’t. @element may be %NULL only if the hash function passed to @bloom at
 * construction time supports %NULL elements.
 *
 * Returns: %TRUE if @element is potentially in @bloom; %FALSE if it definitely
 *    isn’t
 * Since: 2017.8
 */
gboolean
ostree_bloom_maybe_contains (OstreeBloom   *bloom,
                             gconstpointer  element)
{
  guint8 i;

  g_return_val_if_fail (bloom != NULL, TRUE);
  g_return_val_if_fail (bloom->ref_count >= 1, TRUE);

  for (i = 0; i < bloom->k; i++)
    {
      guint64 idx;

      idx = bloom->hash_func (element, i);

      if (!ostree_bloom_get_bit (bloom, (gsize) (idx % (bloom->n_bytes * 8))))
        return FALSE;  /* definitely not in the set */
    }

  return TRUE;  /* possibly in the set */
}

/**
 * ostree_bloom_seal:
 * @bloom: an #OstreeBloom
 *
 * Seal a constructed bloom filter, so that elements may no longer be added to
 * it, and queries can now be performed against it. The serialised form of the
 * bloom filter is returned as a bit array. Note that this does not include
 * information about the filter hash function or parameters; the caller is
 * responsible for serialising those separately if appropriate.
 *
 * It is safe to call this function multiple times.
 *
 * Returns: (transfer full): a #GBytes containing the immutable filter data
 * Since: 2017.8
 */
GBytes *
ostree_bloom_seal (OstreeBloom *bloom)
{
  g_return_val_if_fail (bloom != NULL, NULL);
  g_return_val_if_fail (bloom->ref_count >= 1, NULL);

  if (bloom->is_mutable)
    {
      bloom->is_mutable = FALSE;
      bloom->immutable_bytes = g_bytes_new_take (g_steal_pointer (&bloom->mutable_bytes), bloom->n_bytes);
    }

  return g_bytes_ref (bloom->immutable_bytes);
}

/**
 * ostree_bloom_add_element:
 * @bloom: an #OstreeBloom
 * @element: (nullable): element to add to the filter
 *
 * Add the given @element to the bloom filter, which must not yet have been
 * sealed (ostree_bloom_seal()). @element may be %NULL if the hash function
 * passed to @bloom at construction time supports %NULL elements.
 *
 * Since: 2017.8
 */
void
ostree_bloom_add_element (OstreeBloom   *bloom,
                          gconstpointer  element)
{
  guint8 i;

  g_return_if_fail (bloom != NULL);
  g_return_if_fail (bloom->ref_count >= 1);
  g_return_if_fail (bloom->is_mutable);

  for (i = 0; i < bloom->k; i++)
    {
      guint64 idx = bloom->hash_func (element, i);
      ostree_bloom_set_bit (bloom, (gsize) (idx % (bloom->n_bytes * 8)));
    }
}

/**
 * ostree_bloom_get_size:
 * @bloom: an #OstreeBloom
 *
 * Get the size of the #OstreeBloom filter, in bytes, as configured at
 * construction time.
 *
 * Returns: the bloom filter’s size in bytes, guaranteed to be >0
 * Since: 2017.8
 */
gsize
ostree_bloom_get_size (OstreeBloom *bloom)
{
  g_return_val_if_fail (bloom != NULL, 0);

  return bloom->n_bytes;
}

/**
 * ostree_bloom_get_k:
 * @bloom: an #OstreeBloom
 *
 * Get the `k` value from the #OstreeBloom filter, as configured at
 * construction time.
 *
 * Returns: the bloom filter’s `k` value, guaranteed to be >0
 * Since: 2017.8
 */
guint8
ostree_bloom_get_k (OstreeBloom *bloom)
{
  g_return_val_if_fail (bloom != NULL, 0);

  return bloom->k;
}

/**
 * ostree_bloom_get_hash_func:
 * @bloom: an #OstreeBloom
 *
 * Get the #OstreeBloomHashFunc from the #OstreeBloom filter, as configured at
 * construction time.
 *
 * Returns: the bloom filter’s universal hash function
 * Since: 2017.8
 */
OstreeBloomHashFunc
ostree_bloom_get_hash_func (OstreeBloom *bloom)
{
  g_return_val_if_fail (bloom != NULL, NULL);

  return bloom->hash_func;
}

/* SipHash code adapted from https://github.com/veorq/SipHash/blob/master/siphash.c */

/*
   SipHash reference C implementation
   Copyright (c) 2012-2016 Jean-Philippe Aumasson
   <jeanphilippe.aumasson@gmail.com>
   Copyright (c) 2012-2014 Daniel J. Bernstein <djb@cr.yp.to>
   To the extent possible under law, the author(s) have dedicated all copyright
   and related and neighboring rights to this software to the public domain
   worldwide. This software is distributed without any warranty.
   You should have received a copy of the CC0 Public Domain Dedication along
   with
   this software. If not, see
   <http://creativecommons.org/publicdomain/zero/1.0/>.
 */

/* default: SipHash-2-4 */
#define cROUNDS 2
#define dROUNDS 4

#define ROTL(x, b) (uint64_t)(((x) << (b)) | ((x) >> (64 - (b))))

#define U32TO8_LE(p, v)                                                        \
    (p)[0] = (uint8_t)((v));                                                   \
    (p)[1] = (uint8_t)((v) >> 8);                                              \
    (p)[2] = (uint8_t)((v) >> 16);                                             \
    (p)[3] = (uint8_t)((v) >> 24);

#define U64TO8_LE(p, v)                                                        \
    U32TO8_LE((p), (uint32_t)((v)));                                           \
    U32TO8_LE((p) + 4, (uint32_t)((v) >> 32));

#define U8TO64_LE(p)                                                           \
    (((uint64_t)((p)[0])) | ((uint64_t)((p)[1]) << 8) |                        \
     ((uint64_t)((p)[2]) << 16) | ((uint64_t)((p)[3]) << 24) |                 \
     ((uint64_t)((p)[4]) << 32) | ((uint64_t)((p)[5]) << 40) |                 \
     ((uint64_t)((p)[6]) << 48) | ((uint64_t)((p)[7]) << 56))

#define SIPROUND                                                               \
    do {                                                                       \
        v0 += v1;                                                              \
        v1 = ROTL(v1, 13);                                                     \
        v1 ^= v0;                                                              \
        v0 = ROTL(v0, 32);                                                     \
        v2 += v3;                                                              \
        v3 = ROTL(v3, 16);                                                     \
        v3 ^= v2;                                                              \
        v0 += v3;                                                              \
        v3 = ROTL(v3, 21);                                                     \
        v3 ^= v0;                                                              \
        v2 += v1;                                                              \
        v1 = ROTL(v1, 17);                                                     \
        v1 ^= v2;                                                              \
        v2 = ROTL(v2, 32);                                                     \
    } while (0)

#ifdef DEBUG
#define TRACE                                                                  \
    do {                                                                       \
        printf("(%3d) v0 %08x %08x\n", (int)inlen, (uint32_t)(v0 >> 32),       \
               (uint32_t)v0);                                                  \
        printf("(%3d) v1 %08x %08x\n", (int)inlen, (uint32_t)(v1 >> 32),       \
               (uint32_t)v1);                                                  \
        printf("(%3d) v2 %08x %08x\n", (int)inlen, (uint32_t)(v2 >> 32),       \
               (uint32_t)v2);                                                  \
        printf("(%3d) v3 %08x %08x\n", (int)inlen, (uint32_t)(v3 >> 32),       \
               (uint32_t)v3);                                                  \
    } while (0)
#else
#define TRACE
#endif

static int siphash(const uint8_t *in, const size_t inlen, const uint8_t *k,
                   uint8_t *out, const size_t outlen) {

    assert((outlen == 8) || (outlen == 16));
    uint64_t v0 = 0x736f6d6570736575ULL;
    uint64_t v1 = 0x646f72616e646f6dULL;
    uint64_t v2 = 0x6c7967656e657261ULL;
    uint64_t v3 = 0x7465646279746573ULL;
    uint64_t k0 = U8TO64_LE(k);
    uint64_t k1 = U8TO64_LE(k + 8);
    uint64_t m;
    int i;
    const uint8_t *end = in + inlen - (inlen % sizeof(uint64_t));
    const int left = inlen & 7;
    uint64_t b = ((uint64_t)inlen) << 56;
    v3 ^= k1;
    v2 ^= k0;
    v1 ^= k1;
    v0 ^= k0;

    if (outlen == 16)
        v1 ^= 0xee;

    for (; in != end; in += 8) {
        m = U8TO64_LE(in);
        v3 ^= m;

        TRACE;
        for (i = 0; i < cROUNDS; ++i)
            SIPROUND;

        v0 ^= m;
    }

    switch (left) {
    case 7:
        b |= ((uint64_t)in[6]) << 48;
    case 6:
        b |= ((uint64_t)in[5]) << 40;
    case 5:
        b |= ((uint64_t)in[4]) << 32;
    case 4:
        b |= ((uint64_t)in[3]) << 24;
    case 3:
        b |= ((uint64_t)in[2]) << 16;
    case 2:
        b |= ((uint64_t)in[1]) << 8;
    case 1:
        b |= ((uint64_t)in[0]);
        break;
    case 0:
        break;
    }

    v3 ^= b;

    TRACE;
    for (i = 0; i < cROUNDS; ++i)
        SIPROUND;

    v0 ^= b;

    if (outlen == 16)
        v2 ^= 0xee;
    else
        v2 ^= 0xff;

    TRACE;
    for (i = 0; i < dROUNDS; ++i)
        SIPROUND;

    b = v0 ^ v1 ^ v2 ^ v3;
    U64TO8_LE(out, b);

    if (outlen == 8)
        return 0;

    v1 ^= 0xdd;

    TRACE;
    for (i = 0; i < dROUNDS; ++i)
        SIPROUND;

    b = v0 ^ v1 ^ v2 ^ v3;
    U64TO8_LE(out + 8, b);

    return 0;
}

/* End SipHash copied code. */

/**
 * ostree_str_bloom_hash:
 * @element: element to calculate the hash for
 * @k: hash function index
 *
 * A universal hash function implementation for strings. It expects @element to
 * be a pointer to a string (i.e. @element has type `const gchar*`), and expects
 * @k to be in the range `[0, k_max)`, where `k_max` is the `k` value used to
 * construct the bloom filter. The output range from this hash function could be
 * any value in #guint64, and it handles input strings of any length.
 *
 * This function does not allow %NULL as a valid value for @element.
 *
 * Reference:
 *  - https://www.131002.net/siphash/
 *
 * Returns: hash of the string at @element using parameter @k
 * Since: 2017.8
 */
guint64
ostree_str_bloom_hash (gconstpointer element,
                       guint8        k)
{
  const gchar *str = element;
  gsize str_len;
  union
    {
      guint64 u64;
      guint8 u8[8];
    } out_le;
  guint8 k_array[16];
  gsize i;

  str_len = strlen (str);
  for (i = 0; i < G_N_ELEMENTS (k_array); i++)
    k_array[i] = k;

  siphash ((const guint8 *) str, str_len, k_array, out_le.u8, sizeof (out_le));

  return le64toh (out_le.u64);
}