final touches on dkim test harness
[citadel.git] / libcitadel / lib / hash.c
1 /*
2  * Copyright (c) 1987-2011 by the citadel.org team
3  *
4  * This program is open source software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  */
18
19 #include <stdint.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <limits.h>
23 //dbg
24 #include <stdio.h>
25 #include "libcitadel.h"
26 #include "lookup3.h"
27
28 typedef struct Payload Payload;
29
30 /**
31  * @defgroup HashList Hashlist Key Value list implementation; 
32  * Hashlist is a simple implementation of key value pairs. It doesn't implement collision handling.
33  * the Hashingalgorythm is pluggeable on creation. 
34  * items are added with a functionpointer destructs them; that way complex structures can be added.
35  * if no pointer is given, simply free is used. Use @ref reference_free_handler if you don't want us to free you rmemory.
36  */
37
38 /**
39  * @defgroup HashListData Datastructures used for the internals of HashList
40  * @ingroup HashList
41  */
42
43 /**
44  * @defgroup HashListDebug Hashlist debugging functions
45  * @ingroup HashList
46  */
47
48 /**
49  * @defgroup HashListPrivate Hashlist internal functions
50  * @ingroup HashList
51  */
52
53 /**
54  * @defgroup HashListSort Hashlist sorting functions
55  * @ingroup HashList
56  */
57
58 /**
59  * @defgroup HashListAccess Hashlist functions to access / put / delete items in(to) the list
60  * @ingroup HashList
61  */
62
63 /**
64  * @defgroup HashListAlgorithm functions to condense Key to an integer.
65  * @ingroup HashList
66  */
67
68 /**
69  * @defgroup HashListMset MSet is sort of a derived hashlist, its special for treating Messagesets as Citadel uses them to store access rangesx
70  * @ingroup HashList
71  */
72
73 /**
74  * @ingroup HashListData
75  * @brief Hash Payload storage Structure; filled in linear.
76  */
77 struct Payload {
78         void *Data; /**< the Data belonging to this storage */
79         DeleteHashDataFunc Destructor; /**< if we want to destroy Data, do it with this function. */
80 };
81
82
83 /**
84  * @ingroup HashListData
85  * @brief Hash key element; sorted by key
86  */
87 struct HashKey {
88         long Key;         /**< Numeric Hashkey comperator for hash sorting */
89         long Position;    /**< Pointer to a Payload struct in the Payload Aray */
90         char *HashKey;    /**< the Plaintext Hashkey */
91         long HKLen;       /**< length of the Plaintext Hashkey */
92         Payload *PL;      /**< pointer to our payload for sorting */
93 };
94
95 /**
96  * @ingroup HashListData
97  * @brief Hash structure; holds arrays of Hashkey and Payload. 
98  */
99 struct HashList {
100         Payload **Members;     /**< Our Payload members. This fills up linear */
101         HashKey **LookupTable; /**< Hash Lookup table. Elements point to members, and are sorted by their hashvalue */
102         char **MyKeys;         /**< this keeps the members for a call of GetHashKeys */
103         HashFunc Algorithm;    /**< should we use an alternating algorithm to calc the hash values? */
104         long nMembersUsed;     /**< how many pointers inside of the array are used? */
105         long nLookupTableItems; /**< how many items of the lookup table are used? */
106         long MemberSize;       /**< how big is Members and LookupTable? */
107         long tainted;          /**< if 0, we're hashed, else s.b. else sorted us in his own way. */
108         long uniq;             /**< are the keys going to be uniq? */
109 };
110
111 /**
112  * @ingroup HashListData
113  * @brief Anonymous Hash Iterator Object. used for traversing the whole array from outside 
114  */
115 struct HashPos {
116         long Position;        /**< Position inside of the hash */
117         int StepWidth;        /**< small? big? forward? backward? */
118 };
119
120
121 /**
122  * @ingroup HashListDebug
123  * @brief Iterate over the hash and call PrintEntry. 
124  * @param Hash your Hashlist structure
125  * @param Trans is called so you could for example print 'A:' if the next entries are like that.
126  *        Must be aware to receive NULL in both pointers.
127  * @param PrintEntry print entry one by one
128  * @return the number of items printed
129  */
130 int PrintHash(HashList *Hash, TransitionFunc Trans, PrintHashDataFunc PrintEntry)
131 {
132         int i;
133         void *Previous;
134         void *Next;
135         const char* KeyStr;
136
137         if (Hash == NULL)
138                 return 0;
139
140         for (i=0; i < Hash->nLookupTableItems; i++) {
141                 if (i==0) {
142                         Previous = NULL;
143                 }
144                 else {
145                         if (Hash->LookupTable[i - 1] == NULL)
146                                 Previous = NULL;
147                         else
148                                 Previous = Hash->Members[Hash->LookupTable[i-1]->Position]->Data;
149                 }
150                 if (Hash->LookupTable[i] == NULL) {
151                         KeyStr = "";
152                         Next = NULL;
153                 }
154                 else {
155                         Next = Hash->Members[Hash->LookupTable[i]->Position]->Data;
156                         KeyStr = Hash->LookupTable[i]->HashKey;
157                 }
158
159                 Trans(Previous, Next, i % 2);
160                 PrintEntry(KeyStr, Next, i % 2);
161         }
162         return i;
163 }
164
165 const char *dbg_PrintStrBufPayload(const char *Key, void *Item, int Odd)
166 {
167         return ChrPtr((StrBuf*)Item);
168 }
169
170 /**
171  * @ingroup HashListDebug
172  * @brief verify the contents of a hash list; here for debugging purposes.
173  * @param Hash your Hashlist structure
174  * @param First Functionpointer to allow you to print your payload
175  * @param Second Functionpointer to allow you to print your payload
176  * @return 0
177  */
178 int dbg_PrintHash(HashList *Hash, PrintHashContent First, PrintHashContent Second)
179 {
180 #ifdef DEBUG
181         const char *foo;
182         const char *bar;
183         const char *bla = "";
184         long key;
185 #endif
186         long i;
187
188         if (Hash == NULL)
189                 return 0;
190
191         if (Hash->MyKeys != NULL)
192                 free (Hash->MyKeys);
193
194         Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
195 #ifdef DEBUG
196         printf("----------------------------------\n");
197 #endif
198         for (i=0; i < Hash->nLookupTableItems; i++) {
199                 
200                 if (Hash->LookupTable[i] == NULL)
201                 {
202 #ifdef DEBUG
203                         foo = "";
204                         bar = "";
205                         key = 0;
206 #endif
207                 }
208                 else 
209                 {
210 #ifdef DEBUG
211                         key = Hash->LookupTable[i]->Key;
212                         foo = Hash->LookupTable[i]->HashKey;
213 #endif
214                         if (First != NULL)
215 #ifdef DEBUG
216                                 bar =
217 #endif
218                                         First(Hash->Members[Hash->LookupTable[i]->Position]->Data);
219 #ifdef DEBUG
220                         else 
221                                 bar = "";
222 #endif
223
224                         if (Second != NULL)
225 #ifdef DEBUG
226                                 bla = 
227 #endif 
228                                         Second(Hash->Members[Hash->LookupTable[i]->Position]->Data);
229 #ifdef DEBUG
230
231                         else
232                                 bla = "";
233 #endif
234
235                 }
236 #ifdef DEBUG
237                 if ((Hash->Algorithm == lFlathash) || (Hash->Algorithm == Flathash)) {
238                         printf (" ---- Hashkey[%ld][%ld]: %ld '%s' Value: '%s' ; %s\n", i, key, *(long*) foo, foo, bar, bla);
239                 }
240                 else {
241                         printf (" ---- Hashkey[%ld][%ld]: '%s' Value: '%s' ; %s\n", i, key, foo, bar, bla);
242                 }
243 #endif
244         }
245 #ifdef DEBUG
246         printf("----------------------------------\n");
247 #endif
248         return 0;
249 }
250
251
252 int TestValidateHash(HashList *TestHash)
253 {
254         long i;
255
256         if (TestHash->nMembersUsed != TestHash->nLookupTableItems)
257                 return 1;
258
259         if (TestHash->nMembersUsed > TestHash->MemberSize)
260                 return 2;
261
262         for (i=0; i < TestHash->nMembersUsed; i++)
263         {
264
265                 if (TestHash->LookupTable[i]->Position > TestHash->nMembersUsed)
266                         return 3;
267                 
268                 if (TestHash->Members[TestHash->LookupTable[i]->Position] == NULL)
269                         return 4;
270                 if (TestHash->Members[TestHash->LookupTable[i]->Position]->Data == NULL)
271                         return 5;
272         }
273         return 0;
274 }
275
276 /**
277  * @ingroup HashListAccess
278  * @brief instanciate a new hashlist
279  * @return the newly allocated list. 
280  */
281 HashList *NewHash(int Uniq, HashFunc F)
282 {
283         HashList *NewList;
284         NewList = malloc (sizeof(HashList));
285         if (NewList == NULL)
286                 return NULL;
287         memset(NewList, 0, sizeof(HashList));
288
289         NewList->Members = malloc(sizeof(Payload*) * 100);
290         if (NewList->Members == NULL)
291         {
292                 free(NewList);
293                 return NULL;
294         }
295         memset(NewList->Members, 0, sizeof(Payload*) * 100);
296
297         NewList->LookupTable = malloc(sizeof(HashKey*) * 100);
298         if (NewList->LookupTable == NULL)
299         {
300                 free(NewList->Members);
301                 free(NewList);
302                 return NULL;
303         }
304         memset(NewList->LookupTable, 0, sizeof(HashKey*) * 100);
305
306         NewList->MemberSize = 100;
307         NewList->tainted = 0;
308         NewList->uniq = Uniq;
309         NewList->Algorithm = F;
310
311         return NewList;
312 }
313
314 int GetCount(HashList *Hash)
315 {
316         if(Hash==NULL) return 0;
317         return Hash->nLookupTableItems;
318 }
319
320
321 /**
322  * @ingroup HashListPrivate
323  * @brief private destructor for one hash element.
324  * Crashing? go one frame up and do 'print *FreeMe->LookupTable[i]'
325  * @param Data an element to free using the user provided destructor, or just plain free
326  */
327 static void DeleteHashPayload (Payload *Data)
328 {
329         /** do we have a destructor for our payload? */
330         if (Data->Destructor)
331                 Data->Destructor(Data->Data);
332         else
333                 free(Data->Data);
334 }
335
336 /**
337  * @ingroup HashListPrivate
338  * @brief Destructor for nested hashes
339  */
340 void HDeleteHash(void *vHash)
341 {
342         HashList *FreeMe = (HashList*)vHash;
343         DeleteHash(&FreeMe);
344 }
345
346 /**
347  * @ingroup HashListAccess
348  * @brief flush the members of a hashlist 
349  * Crashing? do 'print *FreeMe->LookupTable[i]'
350  * @param Hash Hash to destroy. Is NULL'ed so you are shure its done.
351  */
352 void DeleteHashContent(HashList **Hash)
353 {
354         int i;
355         HashList *FreeMe;
356
357         FreeMe = *Hash;
358         if (FreeMe == NULL)
359                 return;
360         /* even if there are sparse members already deleted... */
361         for (i=0; i < FreeMe->nMembersUsed; i++)
362         {
363                 /** get rid of our payload */
364                 if (FreeMe->Members[i] != NULL)
365                 {
366                         DeleteHashPayload(FreeMe->Members[i]);
367                         free(FreeMe->Members[i]);
368                 }
369                 /** delete our hashing data */
370                 if (FreeMe->LookupTable[i] != NULL)
371                 {
372                         free(FreeMe->LookupTable[i]->HashKey);
373                         free(FreeMe->LookupTable[i]);
374                 }
375         }
376         FreeMe->nMembersUsed = 0;
377         FreeMe->tainted = 0;
378         FreeMe->nLookupTableItems = 0;
379         memset(FreeMe->Members, 0, sizeof(Payload*) * FreeMe->MemberSize);
380         memset(FreeMe->LookupTable, 0, sizeof(HashKey*) * FreeMe->MemberSize);
381
382         /** did s.b. want an array of our keys? free them. */
383         if (FreeMe->MyKeys != NULL)
384                 free(FreeMe->MyKeys);
385 }
386
387 /**
388  * @ingroup HashListAccess
389  * @brief destroy a hashlist and all of its members
390  * Crashing? do 'print *FreeMe->LookupTable[i]'
391  * @param Hash Hash to destroy. Is NULL'ed so you are shure its done.
392  */
393 void DeleteHash(HashList **Hash)
394 {
395         HashList *FreeMe;
396
397         FreeMe = *Hash;
398         if (FreeMe == NULL)
399                 return;
400         DeleteHashContent(Hash);
401         /** now, free our arrays... */
402         free(FreeMe->LookupTable);
403         free(FreeMe->Members);
404
405         /** buye bye cruel world. */    
406         free (FreeMe);
407         *Hash = NULL;
408 }
409
410 /**
411  * @ingroup HashListPrivate
412  * @brief Private function to increase the hash size.
413  * @param Hash the Hasharray to increase
414  */
415 static int IncreaseHashSize(HashList *Hash)
416 {
417         /* Ok, Our space is used up. Double the available space. */
418         Payload **NewPayloadArea;
419         HashKey **NewTable;
420         
421         if (Hash == NULL)
422                 return 0;
423
424         /** If we grew to much, this might be the place to rehash and shrink again.
425         if ((Hash->NMembersUsed > Hash->nLookupTableItems) && 
426             ((Hash->NMembersUsed - Hash->nLookupTableItems) > 
427              (Hash->nLookupTableItems / 10)))
428         {
429
430
431         }
432         */
433
434         NewPayloadArea = (Payload**) malloc(sizeof(Payload*) * Hash->MemberSize * 2);
435         if (NewPayloadArea == NULL)
436                 return 0;
437         NewTable = malloc(sizeof(HashKey*) * Hash->MemberSize * 2);
438         if (NewTable == NULL)
439         {
440                 free(NewPayloadArea);
441                 return 0;
442         }
443
444         /** double our payload area */
445         memset(&NewPayloadArea[Hash->MemberSize], 0, sizeof(Payload*) * Hash->MemberSize);
446         memcpy(NewPayloadArea, Hash->Members, sizeof(Payload*) * Hash->MemberSize);
447         free(Hash->Members);
448         Hash->Members = NewPayloadArea;
449         
450         /** double our hashtable area */
451         memset(&NewTable[Hash->MemberSize], 0, sizeof(HashKey*) * Hash->MemberSize);
452         memcpy(NewTable, Hash->LookupTable, sizeof(HashKey*) * Hash->MemberSize);
453         free(Hash->LookupTable);
454         Hash->LookupTable = NewTable;
455         
456         Hash->MemberSize *= 2;
457         return 1;
458 }
459
460
461 /**
462  * @ingroup HashListPrivate
463  * @brief private function to add a new item to / replace an existing in -  the hashlist
464  * if the hash list is full, its re-alloced with double size.
465  * @param Hash our hashlist to manipulate
466  * @param HashPos where should we insert / replace?
467  * @param HashKeyStr the Hash-String
468  * @param HKLen length of HashKeyStr
469  * @param Data your Payload to add
470  * @param Destructor Functionpointer to free Data. if NULL, default free() is used.
471  */
472 static int InsertHashItem(HashList *Hash, 
473                           long HashPos, 
474                           long HashBinKey, 
475                           const char *HashKeyStr, 
476                           long HKLen, 
477                           void *Data,
478                           DeleteHashDataFunc Destructor)
479 {
480         Payload *NewPayloadItem;
481         HashKey *NewHashKey;
482         char *HashKeyOrgVal;
483
484         if (Hash == NULL)
485                 return 0;
486
487         if ((Hash->nMembersUsed >= Hash->MemberSize) &&
488             (!IncreaseHashSize (Hash)))
489             return 0;
490
491         NewPayloadItem = (Payload*) malloc (sizeof(Payload));
492         if (NewPayloadItem == NULL)
493                 return 0;
494         NewHashKey = (HashKey*) malloc (sizeof(HashKey));
495         if (NewHashKey == NULL)
496         {
497                 free(NewPayloadItem);
498                 return 0;
499         }
500         HashKeyOrgVal = (char *) malloc (HKLen + 1);
501         if (HashKeyOrgVal == NULL)
502         {
503                 free(NewHashKey);
504                 free(NewPayloadItem);
505                 return 0;
506         }
507
508
509         /** Arrange the payload */
510         NewPayloadItem->Data = Data;
511         NewPayloadItem->Destructor = Destructor;
512         /** Arrange the hashkey */
513         NewHashKey->HKLen = HKLen;
514         NewHashKey->HashKey = HashKeyOrgVal;
515         memcpy (NewHashKey->HashKey, HashKeyStr, HKLen + 1);
516         NewHashKey->Key = HashBinKey;
517         NewHashKey->PL = NewPayloadItem;
518         /** our payload is queued at the end... */
519         NewHashKey->Position = Hash->nMembersUsed;
520         /** but if we should be sorted into a specific place... */
521         if ((Hash->nLookupTableItems != 0) && 
522             (HashPos != Hash->nLookupTableItems) ) {
523                 long ItemsAfter;
524
525                 ItemsAfter = Hash->nLookupTableItems - HashPos;
526                 /** make space were we can fill us in */
527                 if (ItemsAfter > 0)
528                 {
529                         memmove(&Hash->LookupTable[HashPos + 1],
530                                 &Hash->LookupTable[HashPos],
531                                 ItemsAfter * sizeof(HashKey*));
532                 } 
533         }
534         
535         Hash->Members[Hash->nMembersUsed] = NewPayloadItem;
536         Hash->LookupTable[HashPos] = NewHashKey;
537         Hash->nMembersUsed++;
538         Hash->nLookupTableItems++;
539         return 1;
540 }
541
542 /**
543  * @ingroup HashListSort
544  * @brief if the user has tainted the hash, but wants to insert / search items by their key
545  *  we need to search linear through the array. You have been warned that this will take more time!
546  * @param Hash Our Hash to manipulate
547  * @param HashBinKey the Hash-Number to lookup. 
548  * @return the position (most closely) matching HashBinKey (-> Caller needs to compare! )
549  */
550 static long FindInTaintedHash(HashList *Hash, long HashBinKey)
551 {
552         long SearchPos;
553
554         if (Hash == NULL)
555                 return 0;
556
557         for (SearchPos = 0; SearchPos < Hash->nLookupTableItems; SearchPos ++) {
558                 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
559                         return SearchPos;
560                 }
561         }
562         return SearchPos;
563 }
564
565 /**
566  * @ingroup HashListPrivate
567  * @brief Private function to lookup the Item / the closest position to put it in
568  * @param Hash Our Hash to manipulate
569  * @param HashBinKey the Hash-Number to lookup. 
570  * @return the position (most closely) matching HashBinKey (-> Caller needs to compare! )
571  */
572 static long FindInHash(HashList *Hash, long HashBinKey)
573 {
574         long SearchPos;
575         long StepWidth;
576
577         if (Hash == NULL)
578                 return 0;
579
580         if (Hash->tainted)
581                 return FindInTaintedHash(Hash, HashBinKey);
582
583         SearchPos = Hash->nLookupTableItems / 2;
584         StepWidth = SearchPos / 2;
585         while ((SearchPos > 0) && 
586                (SearchPos < Hash->nLookupTableItems)) 
587         {
588                 /** Did we find it? */
589                 if (Hash->LookupTable[SearchPos]->Key == HashBinKey){
590                         return SearchPos;
591                 }
592                 /** are we Aproximating in big steps? */
593                 if (StepWidth > 1){
594                         if (Hash->LookupTable[SearchPos]->Key > HashBinKey)
595                                 SearchPos -= StepWidth;
596                         else
597                                 SearchPos += StepWidth;
598                         StepWidth /= 2;                 
599                 }
600                 else { /** We are right next to our target, within 4 positions */
601                         if (Hash->LookupTable[SearchPos]->Key > HashBinKey) {
602                                 if ((SearchPos > 0) && 
603                                     (Hash->LookupTable[SearchPos - 1]->Key < HashBinKey))
604                                         return SearchPos;
605                                 SearchPos --;
606                         }
607                         else {
608                                 if ((SearchPos + 1 < Hash->nLookupTableItems) && 
609                                     (Hash->LookupTable[SearchPos + 1]->Key > HashBinKey))
610                                         return SearchPos;
611                                 SearchPos ++;
612                         }
613                         StepWidth--;
614                 }
615         }
616         return SearchPos;
617 }
618
619
620 /**
621  * @ingroup HashListAlgorithm
622  * @brief another hashing algorithm; treat it as just a pointer to int.
623  * @param str Our pointer to the int value
624  * @param len the length of the data pointed to; needs to be sizeof int, else we won't use it!
625  * @return the calculated hash value
626  */
627 long Flathash(const char *str, long len)
628 {
629         if (len != sizeof (int))
630         {
631 #ifdef DEBUG
632                 int *crash = NULL;
633                 *crash = 1;
634 #endif
635                 return 0;
636         }
637         else return *(int*)str;
638 }
639
640 /**
641  * @ingroup HashListAlgorithm
642  * @brief another hashing algorithm; treat it as just a pointer to long.
643  * @param str Our pointer to the long value
644  * @param len the length of the data pointed to; needs to be sizeof long, else we won't use it!
645  * @return the calculated hash value
646  */
647 long lFlathash(const char *str, long len)
648 {
649         if (len != sizeof (long))
650         {
651 #ifdef DEBUG
652                 int *crash = NULL;
653                 *crash = 1;
654 #endif
655                 return 0;
656         }
657         else return *(long*)str;
658 }
659
660 /**
661  * @ingroup HashListAlgorithm
662  * @brief another hashing algorithm; accepts exactly 4 characters, convert it to a hash key.
663  * @param str Our pointer to the long value
664  * @param len the length of the data pointed to; needs to be sizeof long, else we won't use it!
665  * @return the calculated hash value
666  */
667 long FourHash(const char *key, long length) 
668 {
669         int i;
670         int ret = 0;
671         const unsigned char *ptr = (const unsigned char*)key;
672
673         for (i = 0; i < 4; i++, ptr ++) 
674                 ret = (ret << 8) | 
675                         ( ((*ptr >= 'a') &&
676                            (*ptr <= 'z'))? 
677                           *ptr - 'a' + 'A': 
678                           *ptr);
679
680         return ret;
681 }
682
683 /**
684  * @ingroup HashListPrivate
685  * @brief private abstract wrapper around the hashing algorithm
686  * @param HKey the hash string
687  * @param HKLen length of HKey
688  * @return the calculated hash value
689  */
690 inline static long CalcHashKey (HashList *Hash, const char *HKey, long HKLen)
691 {
692         if (Hash == NULL)
693                 return 0;
694
695         if (Hash->Algorithm == NULL)
696                 return hashlittle(HKey, HKLen, 9283457);
697         else
698                 return Hash->Algorithm(HKey, HKLen);
699 }
700
701
702 /**
703  * @ingroup HashListAccess
704  * @brief Add a new / Replace an existing item in the Hash
705  * @param Hash the list to manipulate
706  * @param HKey the hash-string to store Data under
707  * @param HKLen Length of HKey
708  * @param Data the payload you want to associate with HKey
709  * @param DeleteIt if not free() should be used to delete Data set to NULL, else DeleteIt is used.
710  */
711 void Put(HashList *Hash, const char *HKey, long HKLen, void *Data, DeleteHashDataFunc DeleteIt)
712 {
713         long HashBinKey;
714         long HashAt;
715
716         if (Hash == NULL)
717                 return;
718
719         /** first, find out were we could fit in... */
720         HashBinKey = CalcHashKey(Hash, HKey, HKLen);
721         HashAt = FindInHash(Hash, HashBinKey);
722
723         if ((HashAt >= Hash->MemberSize) &&
724             (!IncreaseHashSize (Hash)))
725                 return;
726
727         /** oh, we're brand new... */
728         if (Hash->LookupTable[HashAt] == NULL) {
729                 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
730         }/** Insert Before? */
731         else if (Hash->LookupTable[HashAt]->Key > HashBinKey) {
732                 InsertHashItem(Hash, HashAt, HashBinKey, HKey, HKLen, Data, DeleteIt);
733         }/** Insert After? */
734         else if (Hash->LookupTable[HashAt]->Key < HashBinKey) {
735                 InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
736         }
737         else { /** Ok, we have a colision. replace it. */
738                 if (Hash->uniq) {
739                         long PayloadPos;
740                         
741                         PayloadPos = Hash->LookupTable[HashAt]->Position;
742                         DeleteHashPayload(Hash->Members[PayloadPos]);
743                         Hash->Members[PayloadPos]->Data = Data;
744                         Hash->Members[PayloadPos]->Destructor = DeleteIt;
745                 }
746                 else {
747                         InsertHashItem(Hash, HashAt + 1, HashBinKey, HKey, HKLen, Data, DeleteIt);
748                 }
749         }
750 }
751
752 /**
753  * @ingroup HashListAccess
754  * @brief Lookup the Data associated with HKey
755  * @param Hash the Hashlist to search in
756  * @param HKey the hashkey to look up
757  * @param HKLen length of HKey
758  * @param Data returns the Data associated with HKey
759  * @return 0 if not found, 1 if.
760  */
761 int GetHash(HashList *Hash, const char *HKey, long HKLen, void **Data)
762 {
763         long HashBinKey;
764         long HashAt;
765
766         if (Hash == NULL)
767                 return 0;
768
769         if (HKLen <= 0) {
770                 *Data = NULL;
771                 return  0;
772         }
773         /** first, find out were we could be... */
774         HashBinKey = CalcHashKey(Hash, HKey, HKLen);
775         HashAt = FindInHash(Hash, HashBinKey);
776         if ((HashAt < 0) || /**< Not found at the lower edge? */
777             (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
778             (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
779                 *Data = NULL;
780                 return 0;
781         }
782         else { /** GOTCHA! */
783                 long MemberPosition;
784
785                 MemberPosition = Hash->LookupTable[HashAt]->Position;
786                 *Data = Hash->Members[MemberPosition]->Data;
787                 return 1;
788         }
789 }
790
791 /* TODO? */
792 int GetKey(HashList *Hash, char *HKey, long HKLen, void **Payload)
793 {
794         return 0;
795 }
796
797 /**
798  * @ingroup HashListAccess
799  * @brief get the Keys present in this hash, similar to array_keys() in PHP
800  *  Attention: List remains to Hash! don't modify or free it!
801  * @param Hash Your Hashlist to extract the keys from
802  * @param List returns the list of hashkeys stored in Hash
803  */
804 int GetHashKeys(HashList *Hash, char ***List)
805 {
806         long i;
807
808         *List = NULL;
809         if (Hash == NULL)
810                 return 0;
811         if (Hash->MyKeys != NULL)
812                 free (Hash->MyKeys);
813
814         Hash->MyKeys = (char**) malloc(sizeof(char*) * Hash->nLookupTableItems);
815         if (Hash->MyKeys == NULL)
816                 return 0;
817
818         for (i=0; i < Hash->nLookupTableItems; i++)
819         {
820                 Hash->MyKeys[i] = Hash->LookupTable[i]->HashKey;
821         }
822         *List = (char**)Hash->MyKeys;
823         return Hash->nLookupTableItems;
824 }
825
826 /**
827  * @ingroup HashListAccess
828  * @brief creates a hash-linear iterator object
829  * @param Hash the list we reference
830  * @param StepWidth in which step width should we iterate?
831  *  If negative, the last position matching the 
832  *  step-raster is provided.
833  * @return the hash iterator
834  */
835 HashPos *GetNewHashPos(const HashList *Hash, int StepWidth)
836 {
837         HashPos *Ret;
838         
839         Ret = (HashPos*)malloc(sizeof(HashPos));
840         if (Ret == NULL)
841                 return NULL;
842
843         if (StepWidth != 0)
844                 Ret->StepWidth = StepWidth;
845         else
846                 Ret->StepWidth = 1;
847         if (Ret->StepWidth <  0) {
848                 Ret->Position = Hash->nLookupTableItems - 1;
849         }
850         else {
851                 Ret->Position = 0;
852         }
853         return Ret;
854 }
855
856 /**
857  * @ingroup HashListAccess
858  * @brief resets a hash-linear iterator object
859  * @param Hash the list we reference
860  * @param StepWidth in which step width should we iterate?
861  * @param it the iterator object to manipulate
862  *  If negative, the last position matching the 
863  *  step-raster is provided.
864  * @return the hash iterator
865  */
866 void RewindHashPos(const HashList *Hash, HashPos *it, int StepWidth)
867 {
868         if (StepWidth != 0)
869                 it->StepWidth = StepWidth;
870         else
871                 it->StepWidth = 1;
872         if (it->StepWidth <  0) {
873                 it->Position = Hash->nLookupTableItems - 1;
874         }
875         else {
876                 it->Position = 0;
877         }
878 }
879
880 /**
881  * @ingroup HashListAccess
882  * @brief Set iterator object to point to key. If not found, don't change iterator
883  * @param Hash the list we reference
884  * @param HKey key to search for
885  * @param HKLen length of key
886  * @param At HashPos to update
887  * @return 0 if not found
888  */
889 int GetHashPosFromKey(HashList *Hash, const char *HKey, long HKLen, HashPos *At)
890 {
891         long HashBinKey;
892         long HashAt;
893
894         if (Hash == NULL)
895                 return 0;
896
897         if (HKLen <= 0) {
898                 return  0;
899         }
900         /** first, find out were we could be... */
901         HashBinKey = CalcHashKey(Hash, HKey, HKLen);
902         HashAt = FindInHash(Hash, HashBinKey);
903         if ((HashAt < 0) || /**< Not found at the lower edge? */
904             (HashAt >= Hash->nLookupTableItems) || /**< Not found at the upper edge? */
905             (Hash->LookupTable[HashAt]->Key != HashBinKey)) { /**< somewhere inbetween but no match? */
906                 return 0;
907         }
908         /** GOTCHA! */
909         At->Position = HashAt;
910         return 1;
911 }
912
913 /**
914  * @ingroup HashListAccess
915  * @brief Delete from the Hash the entry at Position
916  * @param Hash the list we reference
917  * @param At the position within the Hash
918  * @return 0 if not found
919  */
920 int DeleteEntryFromHash(HashList *Hash, HashPos *At)
921 {
922         Payload *FreeMe;
923         if (Hash == NULL)
924                 return 0;
925
926         /* if lockable, lock here */
927         if ((Hash == NULL) || 
928             (At->Position >= Hash->nLookupTableItems) || 
929             (At->Position < 0) ||
930             (At->Position > Hash->nLookupTableItems))
931         {
932                 /* unlock... */
933                 return 0;
934         }
935
936         FreeMe = Hash->Members[Hash->LookupTable[At->Position]->Position];
937         Hash->Members[Hash->LookupTable[At->Position]->Position] = NULL;
938
939
940         /** delete our hashing data */
941         if (Hash->LookupTable[At->Position] != NULL)
942         {
943                 free(Hash->LookupTable[At->Position]->HashKey);
944                 free(Hash->LookupTable[At->Position]);
945                 if (At->Position < Hash->nLookupTableItems)
946                 {
947                         memmove(&Hash->LookupTable[At->Position],
948                                 &Hash->LookupTable[At->Position + 1],
949                                 (Hash->nLookupTableItems - At->Position - 1) * 
950                                 sizeof(HashKey*));
951
952                         Hash->LookupTable[Hash->nLookupTableItems - 1] = NULL;
953                 }
954                 else 
955                         Hash->LookupTable[At->Position] = NULL;
956                 Hash->nLookupTableItems--;
957         }
958         /* unlock... */
959
960
961         /** get rid of our payload */
962         if (FreeMe != NULL)
963         {
964                 DeleteHashPayload(FreeMe);
965                 free(FreeMe);
966         }
967         return 1;
968 }
969
970 /**
971  * @ingroup HashListAccess
972  * @brief retrieve the counter from the itteratoor
973  * @param Hash which 
974  * @param At the Iterator to analyze
975  * @return the n'th hashposition we point at
976  */
977 int GetHashPosCounter(HashList *Hash, HashPos *At)
978 {
979         if ((Hash == NULL) || 
980             (At->Position >= Hash->nLookupTableItems) || 
981             (At->Position < 0) ||
982             (At->Position > Hash->nLookupTableItems))
983                 return 0;
984         return At->Position;
985 }
986
987 /**
988  * @ingroup HashListAccess
989  * @brief frees a linear hash iterator
990  */
991 void DeleteHashPos(HashPos **DelMe)
992 {
993         if (*DelMe != NULL)
994         {
995                 free(*DelMe);
996                 *DelMe = NULL;
997         }
998 }
999
1000
1001 /**
1002  * @ingroup HashListAccess
1003  * @brief Get the data located where HashPos Iterator points at, and Move HashPos one forward
1004  * @param Hash your Hashlist to follow
1005  * @param At the position to retrieve the Item from and move forward afterwards
1006  * @param HKLen returns Length of Hashkey Returned
1007  * @param HashKey returns the Hashkey corrosponding to HashPos
1008  * @param Data returns the Data found at HashPos
1009  * @return whether the item was found or not.
1010  */
1011 int GetNextHashPos(const HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
1012 {
1013         long PayloadPos;
1014
1015         if ((Hash == NULL) || 
1016             (At->Position >= Hash->nLookupTableItems) || 
1017             (At->Position < 0) ||
1018             (At->Position > Hash->nLookupTableItems))
1019                 return 0;
1020         *HKLen = Hash->LookupTable[At->Position]->HKLen;
1021         *HashKey = Hash->LookupTable[At->Position]->HashKey;
1022         PayloadPos = Hash->LookupTable[At->Position]->Position;
1023         *Data = Hash->Members[PayloadPos]->Data;
1024
1025         /* Position is NULL-Based, while Stepwidth is not... */
1026         if ((At->Position % abs(At->StepWidth)) == 0)
1027                 At->Position += At->StepWidth;
1028         else 
1029                 At->Position += ((At->Position) % abs(At->StepWidth)) * 
1030                         (At->StepWidth / abs(At->StepWidth));
1031         return 1;
1032 }
1033
1034 /**
1035  * @ingroup HashListAccess
1036  * @brief Get the data located where HashPos Iterator points at
1037  * @param Hash your Hashlist to follow
1038  * @param At the position retrieve the data from
1039  * @param HKLen returns Length of Hashkey Returned
1040  * @param HashKey returns the Hashkey corrosponding to HashPos
1041  * @param Data returns the Data found at HashPos
1042  * @return whether the item was found or not.
1043  */
1044 int GetHashPos(HashList *Hash, HashPos *At, long *HKLen, const char **HashKey, void **Data)
1045 {
1046         long PayloadPos;
1047
1048         if ((Hash == NULL) || 
1049             (At->Position >= Hash->nLookupTableItems) || 
1050             (At->Position < 0) ||
1051             (At->Position > Hash->nLookupTableItems))
1052                 return 0;
1053         *HKLen = Hash->LookupTable[At->Position]->HKLen;
1054         *HashKey = Hash->LookupTable[At->Position]->HashKey;
1055         PayloadPos = Hash->LookupTable[At->Position]->Position;
1056         *Data = Hash->Members[PayloadPos]->Data;
1057
1058         return 1;
1059 }
1060
1061 /**
1062  * @ingroup HashListAccess
1063  * @brief Move HashPos one forward
1064  * @param Hash your Hashlist to follow
1065  * @param At the position to move forward
1066  * @return whether there is a next item or not.
1067  */
1068 int NextHashPos(HashList *Hash, HashPos *At)
1069 {
1070         if ((Hash == NULL) || 
1071             (At->Position >= Hash->nLookupTableItems) || 
1072             (At->Position < 0) ||
1073             (At->Position > Hash->nLookupTableItems))
1074                 return 0;
1075
1076         /* Position is NULL-Based, while Stepwidth is not... */
1077         if ((At->Position % abs(At->StepWidth)) == 0)
1078                 At->Position += At->StepWidth;
1079         else 
1080                 At->Position += ((At->Position) % abs(At->StepWidth)) * 
1081                         (At->StepWidth / abs(At->StepWidth));
1082         return !((At->Position >= Hash->nLookupTableItems) || 
1083                  (At->Position < 0) ||
1084                  (At->Position > Hash->nLookupTableItems));
1085 }
1086
1087 /**
1088  * @ingroup HashListAccess
1089  * @brief Get the data located where At points to
1090  * note: you should prefer iterator operations instead of using me.
1091  * @param Hash your Hashlist peek from
1092  * @param At get the item in the position At.
1093  * @param HKLen returns Length of Hashkey Returned
1094  * @param HashKey returns the Hashkey corrosponding to HashPos
1095  * @param Data returns the Data found at HashPos
1096  * @return whether the item was found or not.
1097  */
1098 int GetHashAt(HashList *Hash,long At, long *HKLen, const char **HashKey, void **Data)
1099 {
1100         long PayloadPos;
1101
1102         if ((Hash == NULL) || 
1103             (At < 0) || 
1104             (At >= Hash->nLookupTableItems))
1105                 return 0;
1106         *HKLen = Hash->LookupTable[At]->HKLen;
1107         *HashKey = Hash->LookupTable[At]->HashKey;
1108         PayloadPos = Hash->LookupTable[At]->Position;
1109         *Data = Hash->Members[PayloadPos]->Data;
1110         return 1;
1111 }
1112
1113 /**
1114  * @ingroup HashListSort
1115  * @brief Get the data located where At points to
1116  * note: you should prefer iterator operations instead of using me.
1117  * @param Hash your Hashlist peek from
1118  * @param HKLen returns Length of Hashkey Returned
1119  * @param HashKey returns the Hashkey corrosponding to HashPos
1120  * @param Data returns the Data found at HashPos
1121  * @return whether the item was found or not.
1122  */
1123 /*
1124 long GetHashIDAt(HashList *Hash,long At)
1125 {
1126         if ((Hash == NULL) || 
1127             (At < 0) || 
1128             (At > Hash->nLookupTableItems))
1129                 return 0;
1130
1131         return Hash->LookupTable[At]->Key;
1132 }
1133 */
1134
1135
1136 /**
1137  * @ingroup HashListSort
1138  * @brief sorting function for sorting the Hash alphabeticaly by their strings
1139  * @param Key1 first item
1140  * @param Key2 second item
1141  */
1142 static int SortByKeys(const void *Key1, const void* Key2)
1143 {
1144         HashKey *HKey1, *HKey2;
1145         HKey1 = *(HashKey**) Key1;
1146         HKey2 = *(HashKey**) Key2;
1147
1148         return strcasecmp(HKey1->HashKey, HKey2->HashKey);
1149 }
1150
1151 /**
1152  * @ingroup HashListSort
1153  * @brief sorting function for sorting the Hash alphabeticaly reverse by their strings
1154  * @param Key1 first item
1155  * @param Key2 second item
1156  */
1157 static int SortByKeysRev(const void *Key1, const void* Key2)
1158 {
1159         HashKey *HKey1, *HKey2;
1160         HKey1 = *(HashKey**) Key1;
1161         HKey2 = *(HashKey**) Key2;
1162
1163         return strcasecmp(HKey2->HashKey, HKey1->HashKey);
1164 }
1165
1166 /**
1167  * @ingroup HashListSort
1168  * @brief sorting function to regain hash-sequence and revert tainted status
1169  * @param Key1 first item
1170  * @param Key2 second item
1171  */
1172 static int SortByHashKeys(const void *Key1, const void* Key2)
1173 {
1174         HashKey *HKey1, *HKey2;
1175         HKey1 = *(HashKey**) Key1;
1176         HKey2 = *(HashKey**) Key2;
1177
1178         return HKey1->Key > HKey2->Key;
1179 }
1180
1181
1182 /**
1183  * @ingroup HashListSort
1184  * @brief sort the hash alphabeticaly by their keys.
1185  * Caution: This taints the hashlist, so accessing it later 
1186  * will be significantly slower! You can un-taint it by SortByHashKeyStr
1187  * @param Hash the list to sort
1188  * @param Order 0/1 Forward/Backward
1189  */
1190 void SortByHashKey(HashList *Hash, int Order)
1191 {
1192         if (Hash->nLookupTableItems < 2)
1193                 return;
1194         qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), 
1195               (Order)?SortByKeys:SortByKeysRev);
1196         Hash->tainted = 1;
1197 }
1198
1199 /**
1200  * @ingroup HashListSort
1201  * @brief sort the hash by their keys (so it regains untainted state).
1202  * this will result in the sequence the hashing allgorithm produces it by default.
1203  * @param Hash the list to sort
1204  */
1205 void SortByHashKeyStr(HashList *Hash)
1206 {
1207         Hash->tainted = 0;
1208         if (Hash->nLookupTableItems < 2)
1209                 return;
1210         qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortByHashKeys);
1211 }
1212
1213
1214 /**
1215  * @ingroup HashListSort
1216  * @brief gives user sort routines access to the hash payload
1217  * @param HashVoid to retrieve Data to
1218  * @return Data belonging to HashVoid
1219  */
1220 const void *GetSearchPayload(const void *HashVoid)
1221 {
1222         return (*(HashKey**)HashVoid)->PL->Data;
1223 }
1224
1225 /**
1226  * @ingroup HashListSort
1227  * @brief sort the hash by your sort function. see the following sample.
1228  * this will result in the sequence the hashing allgorithm produces it by default.
1229  * @param Hash the list to sort
1230  * @param SortBy Sortfunction; see below how to implement this
1231  */
1232 void SortByPayload(HashList *Hash, CompareFunc SortBy)
1233 {
1234         if (Hash->nLookupTableItems < 2)
1235                 return;
1236         qsort(Hash->LookupTable, Hash->nLookupTableItems, sizeof(HashKey*), SortBy);
1237         Hash->tainted = 1;
1238 }
1239
1240
1241
1242
1243 /**
1244  * given you've put char * into your hash as a payload, a sort function might
1245  * look like this:
1246  * int SortByChar(const void* First, const void* Second)
1247  * {
1248  *      char *a, *b;
1249  *      a = (char*) GetSearchPayload(First);
1250  *      b = (char*) GetSearchPayload(Second);
1251  *      return strcmp (a, b);
1252  * }
1253  */
1254
1255
1256 /**
1257  * @ingroup HashListAccess
1258  * @brief Generic function to free a reference.  
1259  * since a reference actualy isn't needed to be freed, do nothing.
1260  */
1261 void reference_free_handler(void *ptr) 
1262 {
1263         return;
1264 }
1265
1266
1267 /**
1268  * @ingroup HashListAlgorithm
1269  * This exposes the hashlittle() function to consumers.
1270  */
1271 int HashLittle(const void *key, size_t length) {
1272         return (int)hashlittle(key, length, 1);
1273 }
1274
1275
1276 /**
1277  * @ingroup HashListMset
1278  * @brief parses an MSet string into a list for later use
1279  * @param MSetList List to be read from MSetStr
1280  * @param MSetStr String containing the list
1281  */
1282 int ParseMSet(MSet **MSetList, StrBuf *MSetStr)
1283 {
1284         const char *POS = NULL, *SetPOS = NULL;
1285         StrBuf *OneSet;
1286         HashList *ThisMSet;
1287         long StartSet, EndSet;
1288         long *pEndSet;
1289         
1290         *MSetList = NULL;
1291         if ((MSetStr == NULL) || (StrLength(MSetStr) == 0))
1292             return 0;
1293             
1294         OneSet = NewStrBufPlain(NULL, StrLength(MSetStr));
1295         if (OneSet == NULL)
1296                 return 0;
1297
1298         ThisMSet = NewHash(0, lFlathash);
1299         if (ThisMSet == NULL)
1300         {
1301                 FreeStrBuf(&OneSet);
1302                 return 0;
1303         }
1304
1305         *MSetList = (MSet*) ThisMSet;
1306
1307         /* an MSet is a coma separated value list. */
1308         StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1309         do {
1310                 SetPOS = NULL;
1311
1312                 /* One set may consist of two Numbers: Start + optional End */
1313                 StartSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1314                 EndSet = 0; /* no range is our default. */
1315                 /* do we have an end (aka range?) */
1316                 if ((SetPOS != NULL) && (SetPOS != StrBufNOTNULL))
1317                 {
1318                         if (*(SetPOS) == '*')
1319                                 EndSet = LONG_MAX; /* ranges with '*' go until infinity */
1320                         else 
1321                                 /* in other cases, get the EndPoint */
1322                                 EndSet = StrBufExtractNext_long(OneSet, &SetPOS, ':');
1323                 }
1324
1325                 pEndSet = (long*) malloc (sizeof(long));
1326                 if (pEndSet == NULL)
1327                 {
1328                         FreeStrBuf(&OneSet);
1329                         DeleteHash(&ThisMSet);
1330                         return 0;
1331                 }
1332                 *pEndSet = EndSet;
1333
1334                 Put(ThisMSet, LKEY(StartSet), pEndSet, NULL);
1335                 /* if we don't have another, we're done. */
1336                 if (POS == StrBufNOTNULL)
1337                         break;
1338                 StrBufExtract_NextToken(OneSet, MSetStr, &POS, ',');
1339         } while (1);
1340         FreeStrBuf(&OneSet);
1341
1342         return 1;
1343 }
1344
1345 /**
1346  * @ingroup HashListMset
1347  * @brief checks whether a message is inside a mset
1348  * @param MSetList List to search for MsgNo
1349  * @param MsgNo number to search in mset
1350  */
1351 int IsInMSetList(MSet *MSetList, long MsgNo)
1352 {
1353         /* basicaly we are a ... */
1354         long MemberPosition;
1355         HashList *Hash = (HashList*) MSetList;
1356         long HashAt;
1357         long EndAt;
1358         long StartAt;
1359
1360         if (Hash == NULL)
1361                 return 0;
1362         if (Hash->MemberSize == 0)
1363                 return 0;
1364         /** first, find out were we could fit in... */
1365         HashAt = FindInHash(Hash, MsgNo);
1366         
1367         /* we're below the first entry, so not found. */
1368         if (HashAt < 0)
1369                 return 0;
1370         /* upper edge? move to last item */
1371         if (HashAt >= Hash->nMembersUsed)
1372                 HashAt = Hash->nMembersUsed - 1;
1373         /* Match? then we got it. */
1374         else if (Hash->LookupTable[HashAt]->Key == MsgNo)
1375                 return 1;
1376         /* One above possible range start? we need to move to the lower one. */ 
1377         else if ((HashAt > 0) && 
1378                  (Hash->LookupTable[HashAt]->Key > MsgNo))
1379                 HashAt -=1;
1380
1381         /* Fetch the actual data */
1382         StartAt = Hash->LookupTable[HashAt]->Key;
1383         MemberPosition = Hash->LookupTable[HashAt]->Position;
1384         EndAt = *(long*) Hash->Members[MemberPosition]->Data;
1385         if ((MsgNo >= StartAt) && (EndAt == LONG_MAX))
1386                 return 1;
1387         /* no range? */
1388         if (EndAt == 0)
1389                 return 0;
1390         /* inside of range? */
1391         if ((StartAt <= MsgNo) && (EndAt >= MsgNo))
1392                 return 1;
1393         return 0;
1394 }
1395
1396
1397 /**
1398  * @ingroup HashListMset
1399  * @brief frees a mset [redirects to @ref DeleteHash
1400  * @param FreeMe to be free'd
1401  */
1402 void DeleteMSet(MSet **FreeMe)
1403 {
1404         DeleteHash((HashList**) FreeMe);
1405 }