cosmetics
[tomato.git] / release / src / router / openvpn / list.c
blob7e57782a8f29251acdf4056c6d8764bf41a6c370
1 /*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
8 * Copyright (C) 2002-2009 OpenVPN Technologies, Inc. <sales@openvpn.net>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2
12 * as published by the Free Software Foundation.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program (see the file COPYING included with this
21 * distribution); if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include "syshead.h"
27 #if P2MP_SERVER
29 #include "list.h"
30 #include "misc.h"
32 #include "memdbg.h"
34 struct hash *
35 hash_init (const int n_buckets,
36 const uint32_t iv,
37 uint32_t (*hash_function)(const void *key, uint32_t iv),
38 bool (*compare_function)(const void *key1, const void *key2))
40 struct hash *h;
41 int i;
43 ASSERT (n_buckets > 0);
44 ALLOC_OBJ_CLEAR (h, struct hash);
45 h->n_buckets = (int) adjust_power_of_2 (n_buckets);
46 h->mask = h->n_buckets - 1;
47 h->hash_function = hash_function;
48 h->compare_function = compare_function;
49 h->iv = iv;
50 ALLOC_ARRAY (h->buckets, struct hash_bucket, h->n_buckets);
51 for (i = 0; i < h->n_buckets; ++i)
53 struct hash_bucket *b = &h->buckets[i];
54 b->list = NULL;
55 mutex_init (&b->mutex);
57 return h;
60 void
61 hash_free (struct hash *hash)
63 int i;
64 for (i = 0; i < hash->n_buckets; ++i)
66 struct hash_bucket *b = &hash->buckets[i];
67 struct hash_element *he = b->list;
69 mutex_destroy (&b->mutex);
70 while (he)
72 struct hash_element *next = he->next;
73 free (he);
74 he = next;
77 free (hash->buckets);
78 free (hash);
81 struct hash_element *
82 hash_lookup_fast (struct hash *hash,
83 struct hash_bucket *bucket,
84 const void *key,
85 uint32_t hv)
87 struct hash_element *he;
88 struct hash_element *prev = NULL;
90 he = bucket->list;
92 while (he)
94 if (hv == he->hash_value && (*hash->compare_function)(key, he->key))
96 /* move to head of list */
97 if (prev)
99 prev->next = he->next;
100 he->next = bucket->list;
101 bucket->list = he;
103 return he;
105 prev = he;
106 he = he->next;
109 return NULL;
112 bool
113 hash_remove_fast (struct hash *hash,
114 struct hash_bucket *bucket,
115 const void *key,
116 uint32_t hv)
118 struct hash_element *he;
119 struct hash_element *prev = NULL;
121 he = bucket->list;
123 while (he)
125 if (hv == he->hash_value && (*hash->compare_function)(key, he->key))
127 if (prev)
128 prev->next = he->next;
129 else
130 bucket->list = he->next;
131 free (he);
132 --hash->n_elements;
133 return true;
135 prev = he;
136 he = he->next;
138 return false;
141 bool
142 hash_add (struct hash *hash, const void *key, void *value, bool replace)
144 uint32_t hv;
145 struct hash_bucket *bucket;
146 struct hash_element *he;
147 bool ret = false;
149 hv = hash_value (hash, key);
150 bucket = &hash->buckets[hv & hash->mask];
151 mutex_lock (&bucket->mutex);
153 if ((he = hash_lookup_fast (hash, bucket, key, hv))) /* already exists? */
155 if (replace)
157 he->value = value;
158 ret = true;
161 else
163 hash_add_fast (hash, bucket, key, hv, value);
164 ret = true;
167 mutex_unlock (&bucket->mutex);
169 return ret;
172 void
173 hash_remove_by_value (struct hash *hash, void *value, bool autolock)
175 struct hash_iterator hi;
176 struct hash_element *he;
178 hash_iterator_init (hash, &hi, autolock);
179 while ((he = hash_iterator_next (&hi)))
181 if (he->value == value)
182 hash_iterator_delete_element (&hi);
184 hash_iterator_free (&hi);
187 static void
188 hash_remove_marked (struct hash *hash, struct hash_bucket *bucket)
190 struct hash_element *prev = NULL;
191 struct hash_element *he = bucket->list;
193 while (he)
195 if (!he->key) /* marked? */
197 struct hash_element *newhe;
198 if (prev)
199 newhe = prev->next = he->next;
200 else
201 newhe = bucket->list = he->next;
202 free (he);
203 --hash->n_elements;
204 he = newhe;
206 else
208 prev = he;
209 he = he->next;
214 uint32_t
215 void_ptr_hash_function (const void *key, uint32_t iv)
217 return hash_func ((const void *)&key, sizeof (key), iv);
220 bool
221 void_ptr_compare_function (const void *key1, const void *key2)
223 return key1 == key2;
226 void
227 hash_iterator_init_range (struct hash *hash,
228 struct hash_iterator *hi,
229 bool autolock,
230 int start_bucket,
231 int end_bucket)
233 if (end_bucket > hash->n_buckets)
234 end_bucket = hash->n_buckets;
236 ASSERT (start_bucket >= 0 && start_bucket <= end_bucket);
238 hi->hash = hash;
239 hi->elem = NULL;
240 hi->bucket = NULL;
241 hi->autolock = autolock;
242 hi->last = NULL;
243 hi->bucket_marked = false;
244 hi->bucket_index_start = start_bucket;
245 hi->bucket_index_end = end_bucket;
246 hi->bucket_index = hi->bucket_index_start - 1;
249 void
250 hash_iterator_init (struct hash *hash,
251 struct hash_iterator *hi,
252 bool autolock)
254 hash_iterator_init_range (hash, hi, autolock, 0, hash->n_buckets);
257 static inline void
258 hash_iterator_lock (struct hash_iterator *hi, struct hash_bucket *b)
260 if (hi->autolock)
262 mutex_lock (&b->mutex);
264 hi->bucket = b;
265 hi->last = NULL;
266 hi->bucket_marked = false;
269 static inline void
270 hash_iterator_unlock (struct hash_iterator *hi)
272 if (hi->bucket)
274 if (hi->bucket_marked)
276 hash_remove_marked (hi->hash, hi->bucket);
277 hi->bucket_marked = false;
279 if (hi->autolock)
281 mutex_unlock (&hi->bucket->mutex);
283 hi->bucket = NULL;
284 hi->last = NULL;
288 static inline void
289 hash_iterator_advance (struct hash_iterator *hi)
291 hi->last = hi->elem;
292 hi->elem = hi->elem->next;
295 void
296 hash_iterator_free (struct hash_iterator *hi)
298 hash_iterator_unlock (hi);
301 struct hash_element *
302 hash_iterator_next (struct hash_iterator *hi)
304 struct hash_element *ret = NULL;
305 if (hi->elem)
307 ret = hi->elem;
308 hash_iterator_advance (hi);
310 else
312 while (++hi->bucket_index < hi->bucket_index_end)
314 struct hash_bucket *b;
315 hash_iterator_unlock (hi);
316 b = &hi->hash->buckets[hi->bucket_index];
317 if (b->list)
319 hash_iterator_lock (hi, b);
320 hi->elem = b->list;
321 if (hi->elem)
323 ret = hi->elem;
324 hash_iterator_advance (hi);
325 break;
330 return ret;
333 void
334 hash_iterator_delete_element (struct hash_iterator *hi)
336 ASSERT (hi->last);
337 hi->last->key = NULL;
338 hi->bucket_marked = true;
342 #ifdef LIST_TEST
345 * Test the hash code by implementing a simple
346 * word frequency algorithm.
349 struct word
351 const char *word;
352 int n;
355 static uint32_t
356 word_hash_function (const void *key, uint32_t iv)
358 const char *str = (const char *) key;
359 const int len = strlen (str);
360 return hash_func ((const uint8_t *)str, len, iv);
363 static bool
364 word_compare_function (const void *key1, const void *key2)
366 return strcmp ((const char *)key1, (const char *)key2) == 0;
369 static void
370 print_nhash (struct hash *hash)
372 struct hash_iterator hi;
373 struct hash_element *he;
374 int count = 0;
376 hash_iterator_init (hash, &hi, true);
378 while ((he = hash_iterator_next (&hi)))
380 printf ("%d ", (int) he->value);
381 ++count;
383 printf ("\n");
385 hash_iterator_free (&hi);
386 ASSERT (count == hash_n_elements (hash));
389 static void
390 rmhash (struct hash *hash, const char *word)
392 hash_remove (hash, word);
395 void
396 list_test (void)
398 openvpn_thread_init ();
401 struct gc_arena gc = gc_new ();
402 struct hash *hash = hash_init (10000, get_random (), word_hash_function, word_compare_function);
403 struct hash *nhash = hash_init (256, get_random (), word_hash_function, word_compare_function);
405 printf ("hash_init n_buckets=%d mask=0x%08x\n", hash->n_buckets, hash->mask);
407 /* parse words from stdin */
408 while (true)
410 char buf[256];
411 char wordbuf[256];
412 int wbi;
413 int bi;
414 char c;
416 if (!fgets(buf, sizeof(buf), stdin))
417 break;
419 bi = wbi = 0;
422 c = buf[bi++];
423 if (isalnum (c) || c == '_')
425 ASSERT (wbi < (int) sizeof (wordbuf));
426 wordbuf[wbi++] = c;
428 else
430 if (wbi)
432 struct word *w;
433 ASSERT (wbi < (int) sizeof (wordbuf));
434 wordbuf[wbi++] = '\0';
436 /* word is parsed from stdin */
438 /* does it already exist in table? */
439 w = (struct word *) hash_lookup (hash, wordbuf);
441 if (w)
443 /* yes, increment count */
444 ++w->n;
446 else
448 /* no, make a new object */
449 ALLOC_OBJ_GC (w, struct word, &gc);
450 w->word = string_alloc (wordbuf, &gc);
451 w->n = 1;
452 ASSERT (hash_add (hash, w->word, w, false));
453 ASSERT (hash_add (nhash, w->word, (void*) ((random() & 0x0F) + 1), false));
456 wbi = 0;
458 } while (c);
461 #if 1
462 /* remove some words from the table */
464 rmhash (hash, "true");
465 rmhash (hash, "false");
467 #endif
469 /* output contents of hash table */
471 int base;
472 int inc = 0;
473 int count = 0;
475 for (base = 0; base < hash_n_buckets (hash); base += inc) {
476 struct hash_iterator hi;
477 struct hash_element *he;
478 inc = (get_random () % 3) + 1;
479 hash_iterator_init_range (hash, &hi, true, base, base + inc);
481 while ((he = hash_iterator_next (&hi)))
483 struct word *w = (struct word *) he->value;
484 printf ("%6d '%s'\n", w->n, w->word);
485 ++count;
488 hash_iterator_free (&hi);
490 ASSERT (count == hash_n_elements (hash));
493 #if 1
494 /* test hash_remove_by_value function */
496 int i;
497 for (i = 1; i <= 16; ++i)
499 printf ("[%d] ***********************************\n", i);
500 print_nhash (nhash);
501 hash_remove_by_value (nhash, (void *) i, true);
503 printf ("FINAL **************************\n");
504 print_nhash (nhash);
506 #endif
508 hash_free (hash);
509 hash_free (nhash);
510 gc_free (&gc);
513 openvpn_thread_cleanup ();
516 #endif
519 --------------------------------------------------------------------
520 hash() -- hash a variable-length key into a 32-bit value
521 k : the key (the unaligned variable-length array of bytes)
522 len : the length of the key, counting by bytes
523 level : can be any 4-byte value
524 Returns a 32-bit value. Every bit of the key affects every bit of
525 the return value. Every 1-bit and 2-bit delta achieves avalanche.
526 About 36+6len instructions.
528 The best hash table sizes are powers of 2. There is no need to do
529 mod a prime (mod is sooo slow!). If you need less than 32 bits,
530 use a bitmask. For example, if you need only 10 bits, do
531 h = (h & hashmask(10));
532 In which case, the hash table should have hashsize(10) elements.
534 If you are hashing n strings (uint8_t **)k, do it like this:
535 for (i=0, h=0; i<n; ++i) h = hash( k[i], len[i], h);
537 By Bob Jenkins, 1996. bob_jenkins@burtleburtle.net. You may use this
538 code any way you wish, private, educational, or commercial. It's free.
540 See http://burlteburtle.net/bob/hash/evahash.html
541 Use for hash table lookup, or anything where one collision in 2^32 is
542 acceptable. Do NOT use for cryptographic purposes.
544 --------------------------------------------------------------------
546 mix -- mix 3 32-bit values reversibly.
547 For every delta with one or two bit set, and the deltas of all three
548 high bits or all three low bits, whether the original value of a,b,c
549 is almost all zero or is uniformly distributed,
550 * If mix() is run forward or backward, at least 32 bits in a,b,c
551 have at least 1/4 probability of changing.
552 * If mix() is run forward, every bit of c will change between 1/3 and
553 2/3 of the time. (Well, 22/100 and 78/100 for some 2-bit deltas.)
554 mix() was built out of 36 single-cycle latency instructions in a
555 structure that could supported 2x parallelism, like so:
556 a -= b;
557 a -= c; x = (c>>13);
558 b -= c; a ^= x;
559 b -= a; x = (a<<8);
560 c -= a; b ^= x;
561 c -= b; x = (b>>13);
563 Unfortunately, superscalar Pentiums and Sparcs can't take advantage
564 of that parallelism. They've also turned some of those single-cycle
565 latency instructions into multi-cycle latency instructions. Still,
566 this is the fastest good hash I could find. There were about 2^^68
567 to choose from. I only looked at a billion or so.
569 James Yonan Notes:
571 * This function is faster than it looks, and appears to be
572 appropriate for our usage in OpenVPN which is primarily
573 for hash-table based address lookup (IPv4, IPv6, and Ethernet MAC).
574 NOTE: This function is never used for cryptographic purposes, only
575 to produce evenly-distributed indexes into hash tables.
577 * Benchmark results: 11.39 machine cycles per byte on a P2 266Mhz,
578 and 12.1 machine cycles per byte on a
579 2.2 Ghz P4 when hashing a 6 byte string.
580 --------------------------------------------------------------------
583 #define mix(a,b,c) \
585 a -= b; a -= c; a ^= (c>>13); \
586 b -= c; b -= a; b ^= (a<<8); \
587 c -= a; c -= b; c ^= (b>>13); \
588 a -= b; a -= c; a ^= (c>>12); \
589 b -= c; b -= a; b ^= (a<<16); \
590 c -= a; c -= b; c ^= (b>>5); \
591 a -= b; a -= c; a ^= (c>>3); \
592 b -= c; b -= a; b ^= (a<<10); \
593 c -= a; c -= b; c ^= (b>>15); \
596 uint32_t
597 hash_func (const uint8_t *k, uint32_t length, uint32_t initval)
599 uint32_t a, b, c, len;
601 /* Set up the internal state */
602 len = length;
603 a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */
604 c = initval; /* the previous hash value */
606 /*---------------------------------------- handle most of the key */
607 while (len >= 12)
609 a += (k[0] + ((uint32_t) k[1] << 8)
610 + ((uint32_t) k[2] << 16)
611 + ((uint32_t) k[3] << 24));
612 b += (k[4] + ((uint32_t) k[5] << 8)
613 + ((uint32_t) k[6] << 16)
614 + ((uint32_t) k[7] << 24));
615 c += (k[8] + ((uint32_t) k[9] << 8)
616 + ((uint32_t) k[10] << 16)
617 + ((uint32_t) k[11] << 24));
618 mix (a, b, c);
619 k += 12;
620 len -= 12;
623 /*------------------------------------- handle the last 11 bytes */
624 c += length;
625 switch (len) /* all the case statements fall through */
627 case 11:
628 c += ((uint32_t) k[10] << 24);
629 case 10:
630 c += ((uint32_t) k[9] << 16);
631 case 9:
632 c += ((uint32_t) k[8] << 8);
633 /* the first byte of c is reserved for the length */
634 case 8:
635 b += ((uint32_t) k[7] << 24);
636 case 7:
637 b += ((uint32_t) k[6] << 16);
638 case 6:
639 b += ((uint32_t) k[5] << 8);
640 case 5:
641 b += k[4];
642 case 4:
643 a += ((uint32_t) k[3] << 24);
644 case 3:
645 a += ((uint32_t) k[2] << 16);
646 case 2:
647 a += ((uint32_t) k[1] << 8);
648 case 1:
649 a += k[0];
650 /* case 0: nothing left to add */
652 mix (a, b, c);
653 /*-------------------------------------- report the result */
654 return c;
657 #else
658 static void dummy(void) {}
659 #endif /* P2MP_SERVER */