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