BIO_PAIR_DEBUG did nothing; remove it.
[openssl.git] / crypto / lhash / lhash.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57
58 /*-
59  * Code for dynamic hash table routines
60  * Author - Eric Young v 2.0
61  *
62  * 2.2 eay - added #include "crypto.h" so the memory leak checking code is
63  *           present. eay 18-Jun-98
64  *
65  * 2.1 eay - Added an 'error in last operation' flag. eay 6-May-98
66  *
67  * 2.0 eay - Fixed a bug that occurred when using lh_delete
68  *           from inside lh_doall().  As entries were deleted,
69  *           the 'table' was 'contract()ed', making some entries
70  *           jump from the end of the table to the start, there by
71  *           skipping the lh_doall() processing. eay - 4/12/95
72  *
73  * 1.9 eay - Fixed a memory leak in lh_free, the LHASH_NODEs
74  *           were not being free()ed. 21/11/95
75  *
76  * 1.8 eay - Put the stats routines into a separate file, lh_stats.c
77  *           19/09/95
78  *
79  * 1.7 eay - Removed the fputs() for realloc failures - the code
80  *           should silently tolerate them.  I have also fixed things
81  *           lint complained about 04/05/95
82  *
83  * 1.6 eay - Fixed an invalid pointers in contract/expand 27/07/92
84  *
85  * 1.5 eay - Fixed a misuse of realloc in expand 02/03/1992
86  *
87  * 1.4 eay - Fixed lh_doall so the function can call lh_delete 28/05/91
88  *
89  * 1.3 eay - Fixed a few lint problems 19/3/1991
90  *
91  * 1.2 eay - Fixed lh_doall problem 13/3/1991
92  *
93  * 1.1 eay - Added lh_doall
94  *
95  * 1.0 eay - First version
96  */
97 #include <stdio.h>
98 #include <string.h>
99 #include <stdlib.h>
100 #include <openssl/crypto.h>
101 #include <openssl/lhash.h>
102
103 #undef MIN_NODES
104 #define MIN_NODES       16
105 #define UP_LOAD         (2*LH_LOAD_MULT) /* load times 256 (default 2) */
106 #define DOWN_LOAD       (LH_LOAD_MULT) /* load times 256 (default 1) */
107
108 static void expand(_LHASH *lh);
109 static void contract(_LHASH *lh);
110 static LHASH_NODE **getrn(_LHASH *lh, const void *data, unsigned long *rhash);
111
112 _LHASH *lh_new(LHASH_HASH_FN_TYPE h, LHASH_COMP_FN_TYPE c)
113 {
114     _LHASH *ret;
115
116     if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL)
117         goto err0;
118     if ((ret->b = OPENSSL_zalloc(sizeof(*ret->b) * MIN_NODES)) == NULL)
119         goto err1;
120     ret->comp = ((c == NULL) ? (LHASH_COMP_FN_TYPE)strcmp : c);
121     ret->hash = ((h == NULL) ? (LHASH_HASH_FN_TYPE)lh_strhash : h);
122     ret->num_nodes = MIN_NODES / 2;
123     ret->num_alloc_nodes = MIN_NODES;
124     ret->pmax = MIN_NODES / 2;
125     ret->up_load = UP_LOAD;
126     ret->down_load = DOWN_LOAD;
127     return (ret);
128
129  err1:
130     OPENSSL_free(ret);
131  err0:
132     return (NULL);
133 }
134
135 void lh_free(_LHASH *lh)
136 {
137     unsigned int i;
138     LHASH_NODE *n, *nn;
139
140     if (lh == NULL)
141         return;
142
143     for (i = 0; i < lh->num_nodes; i++) {
144         n = lh->b[i];
145         while (n != NULL) {
146             nn = n->next;
147             OPENSSL_free(n);
148             n = nn;
149         }
150     }
151     OPENSSL_free(lh->b);
152     OPENSSL_free(lh);
153 }
154
155 void *lh_insert(_LHASH *lh, void *data)
156 {
157     unsigned long hash;
158     LHASH_NODE *nn, **rn;
159     void *ret;
160
161     lh->error = 0;
162     if (lh->up_load <= (lh->num_items * LH_LOAD_MULT / lh->num_nodes))
163         expand(lh);
164
165     rn = getrn(lh, data, &hash);
166
167     if (*rn == NULL) {
168         if ((nn = OPENSSL_malloc(sizeof(*nn))) == NULL) {
169             lh->error++;
170             return (NULL);
171         }
172         nn->data = data;
173         nn->next = NULL;
174         nn->hash = hash;
175         *rn = nn;
176         ret = NULL;
177         lh->num_insert++;
178         lh->num_items++;
179     } else {                    /* replace same key */
180
181         ret = (*rn)->data;
182         (*rn)->data = data;
183         lh->num_replace++;
184     }
185     return (ret);
186 }
187
188 void *lh_delete(_LHASH *lh, const void *data)
189 {
190     unsigned long hash;
191     LHASH_NODE *nn, **rn;
192     void *ret;
193
194     lh->error = 0;
195     rn = getrn(lh, data, &hash);
196
197     if (*rn == NULL) {
198         lh->num_no_delete++;
199         return (NULL);
200     } else {
201         nn = *rn;
202         *rn = nn->next;
203         ret = nn->data;
204         OPENSSL_free(nn);
205         lh->num_delete++;
206     }
207
208     lh->num_items--;
209     if ((lh->num_nodes > MIN_NODES) &&
210         (lh->down_load >= (lh->num_items * LH_LOAD_MULT / lh->num_nodes)))
211         contract(lh);
212
213     return (ret);
214 }
215
216 void *lh_retrieve(_LHASH *lh, const void *data)
217 {
218     unsigned long hash;
219     LHASH_NODE **rn;
220     void *ret;
221
222     lh->error = 0;
223     rn = getrn(lh, data, &hash);
224
225     if (*rn == NULL) {
226         lh->num_retrieve_miss++;
227         return (NULL);
228     } else {
229         ret = (*rn)->data;
230         lh->num_retrieve++;
231     }
232     return (ret);
233 }
234
235 static void doall_util_fn(_LHASH *lh, int use_arg, LHASH_DOALL_FN_TYPE func,
236                           LHASH_DOALL_ARG_FN_TYPE func_arg, void *arg)
237 {
238     int i;
239     LHASH_NODE *a, *n;
240
241     if (lh == NULL)
242         return;
243
244     /*
245      * reverse the order so we search from 'top to bottom' We were having
246      * memory leaks otherwise
247      */
248     for (i = lh->num_nodes - 1; i >= 0; i--) {
249         a = lh->b[i];
250         while (a != NULL) {
251             /*
252              * 28/05/91 - eay - n added so items can be deleted via lh_doall
253              */
254             /*
255              * 22/05/08 - ben - eh? since a is not passed, this should not be
256              * needed
257              */
258             n = a->next;
259             if (use_arg)
260                 func_arg(a->data, arg);
261             else
262                 func(a->data);
263             a = n;
264         }
265     }
266 }
267
268 void lh_doall(_LHASH *lh, LHASH_DOALL_FN_TYPE func)
269 {
270     doall_util_fn(lh, 0, func, (LHASH_DOALL_ARG_FN_TYPE)0, NULL);
271 }
272
273 void lh_doall_arg(_LHASH *lh, LHASH_DOALL_ARG_FN_TYPE func, void *arg)
274 {
275     doall_util_fn(lh, 1, (LHASH_DOALL_FN_TYPE)0, func, arg);
276 }
277
278 static void expand(_LHASH *lh)
279 {
280     LHASH_NODE **n, **n1, **n2, *np;
281     unsigned int p, i, j;
282     unsigned long hash, nni;
283
284     lh->num_nodes++;
285     lh->num_expands++;
286     p = (int)lh->p++;
287     n1 = &(lh->b[p]);
288     n2 = &(lh->b[p + (int)lh->pmax]);
289     *n2 = NULL;                 /* 27/07/92 - eay - undefined pointer bug */
290     nni = lh->num_alloc_nodes;
291
292     for (np = *n1; np != NULL;) {
293         hash = np->hash;
294         if ((hash % nni) != p) { /* move it */
295             *n1 = (*n1)->next;
296             np->next = *n2;
297             *n2 = np;
298         } else
299             n1 = &((*n1)->next);
300         np = *n1;
301     }
302
303     if ((lh->p) >= lh->pmax) {
304         j = (int)lh->num_alloc_nodes * 2;
305         n = OPENSSL_realloc(lh->b, (int)(sizeof(LHASH_NODE *) * j));
306         if (n == NULL) {
307             /* fputs("realloc error in lhash",stderr); */
308             lh->error++;
309             lh->p = 0;
310             return;
311         }
312         for (i = (int)lh->num_alloc_nodes; i < j; i++) /* 26/02/92 eay */
313             n[i] = NULL;        /* 02/03/92 eay */
314         lh->pmax = lh->num_alloc_nodes;
315         lh->num_alloc_nodes = j;
316         lh->num_expand_reallocs++;
317         lh->p = 0;
318         lh->b = n;
319     }
320 }
321
322 static void contract(_LHASH *lh)
323 {
324     LHASH_NODE **n, *n1, *np;
325
326     np = lh->b[lh->p + lh->pmax - 1];
327     lh->b[lh->p + lh->pmax - 1] = NULL; /* 24/07-92 - eay - weird but :-( */
328     if (lh->p == 0) {
329         n = OPENSSL_realloc(lh->b,
330                             (unsigned int)(sizeof(LHASH_NODE *) * lh->pmax));
331         if (n == NULL) {
332             /* fputs("realloc error in lhash",stderr); */
333             lh->error++;
334             return;
335         }
336         lh->num_contract_reallocs++;
337         lh->num_alloc_nodes /= 2;
338         lh->pmax /= 2;
339         lh->p = lh->pmax - 1;
340         lh->b = n;
341     } else
342         lh->p--;
343
344     lh->num_nodes--;
345     lh->num_contracts++;
346
347     n1 = lh->b[(int)lh->p];
348     if (n1 == NULL)
349         lh->b[(int)lh->p] = np;
350     else {
351         while (n1->next != NULL)
352             n1 = n1->next;
353         n1->next = np;
354     }
355 }
356
357 static LHASH_NODE **getrn(_LHASH *lh, const void *data, unsigned long *rhash)
358 {
359     LHASH_NODE **ret, *n1;
360     unsigned long hash, nn;
361     LHASH_COMP_FN_TYPE cf;
362
363     hash = (*(lh->hash)) (data);
364     lh->num_hash_calls++;
365     *rhash = hash;
366
367     nn = hash % lh->pmax;
368     if (nn < lh->p)
369         nn = hash % lh->num_alloc_nodes;
370
371     cf = lh->comp;
372     ret = &(lh->b[(int)nn]);
373     for (n1 = *ret; n1 != NULL; n1 = n1->next) {
374         lh->num_hash_comps++;
375         if (n1->hash != hash) {
376             ret = &(n1->next);
377             continue;
378         }
379         lh->num_comp_calls++;
380         if (cf(n1->data, data) == 0)
381             break;
382         ret = &(n1->next);
383     }
384     return (ret);
385 }
386
387 /*
388  * The following hash seems to work very well on normal text strings no
389  * collisions on /usr/dict/words and it distributes on %2^n quite well, not
390  * as good as MD5, but still good.
391  */
392 unsigned long lh_strhash(const char *c)
393 {
394     unsigned long ret = 0;
395     long n;
396     unsigned long v;
397     int r;
398
399     if ((c == NULL) || (*c == '\0'))
400         return (ret);
401 /*-
402     unsigned char b[16];
403     MD5(c,strlen(c),b);
404     return(b[0]|(b[1]<<8)|(b[2]<<16)|(b[3]<<24));
405 */
406
407     n = 0x100;
408     while (*c) {
409         v = n | (*c);
410         n += 0x100;
411         r = (int)((v >> 2) ^ v) & 0x0f;
412         ret = (ret << r) | (ret >> (32 - r));
413         ret &= 0xFFFFFFFFL;
414         ret ^= v * v;
415         c++;
416     }
417     return ((ret >> 16) ^ ret);
418 }
419
420 unsigned long lh_num_items(const _LHASH *lh)
421 {
422     return lh ? lh->num_items : 0;
423 }
424
425 unsigned long lh_get_down_load(const _LHASH *lh)
426 {
427     return lh->down_load;
428 }
429
430 void lh_set_down_load(_LHASH *lh, unsigned long down_load)
431 {
432     lh->down_load = down_load;
433 }
434
435 int lh_error(_LHASH *lh)
436 {
437     return lh->error;
438 }