adding hash type, changed tls configs to hash
[radsecproxy.git] / hash.c
1 /*
2  * Copyright (C) 2008 Stig Venaas <venaas@uninett.no>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  */
8
9 #include <stdlib.h>
10 #include <string.h>
11 #include <pthread.h>
12 #include "list.h"
13 #include "hash.h"
14
15 struct entry {
16     void *key;
17     uint32_t keylen;
18     void *data;
19 };
20         
21 /* allocates and initialises hash structure; returns NULL if malloc fails */
22 struct hash *hash_create() {
23     struct hash *h = malloc(sizeof(struct hash));
24     if (!h)
25         return NULL;
26     h->hashlist = list_create();
27     if (!h->hashlist) {
28         free(h);
29         return NULL;
30     }
31     pthread_mutex_init(&h->mutex, NULL);
32     return h;
33 }
34
35 /* frees all memory associated with the hash */
36 void hash_destroy(struct hash *h) {
37     struct list_node *ln;
38     
39     if (!h)
40         return;
41     for (ln = list_first(h->hashlist); ln; ln = list_next(ln)) {
42         free(((struct entry *)ln->data)->key);
43         free(((struct entry *)ln->data)->data);
44     }
45     list_destroy(h->hashlist);
46     pthread_mutex_destroy(&h->mutex);
47 }
48
49 /* insert entry in hash; returns 1 if ok, 0 if malloc fails */
50 int hash_insert(struct hash *h, void *key, uint32_t keylen, void *data) {
51     struct entry *e;
52
53     if (!h)
54         return 0;
55     e = malloc(sizeof(struct entry));
56     if (!e)
57         return 0;
58     e->key = malloc(keylen);
59     if (!e->key) {
60         free(e);
61         return 0;
62     }
63     memcpy(e->key, key, keylen);
64     e->keylen = keylen;
65     e->data = data;
66     pthread_mutex_lock(&h->mutex);
67     if (!list_push(h->hashlist, e)) {
68         pthread_mutex_unlock(&h->mutex);
69         free(e->key);
70         free(e);
71         return 0;
72     }
73     pthread_mutex_unlock(&h->mutex);
74     return 1;
75 }
76
77 /* reads entry from hash */
78 void *hash_read(struct hash *h, void *key, uint32_t keylen) {
79     struct list_node *ln;
80     struct entry *e;
81     
82     if (!h)
83         return 0;
84     pthread_mutex_lock(&h->mutex);
85     for (ln = list_first(h->hashlist); ln; ln = list_next(ln)) {
86         e = (struct entry *)ln->data;
87         if (e->keylen == keylen && !memcmp(e->key, key, keylen)) {
88                 pthread_mutex_unlock(&h->mutex);
89                 return e->data;
90         }
91     }
92     pthread_mutex_unlock(&h->mutex);
93     return NULL;
94 }