r10421: following on discussions with simo, I have worked out a way of
[ira/wip.git] / source / lib / tdb / common / tdb.c
1  /* 
2    Unix SMB/CIFS implementation.
3
4    trivial database library
5
6    Copyright (C) Andrew Tridgell              1999-2005
7    Copyright (C) Paul `Rusty' Russell              2000
8    Copyright (C) Jeremy Allison                    2000-2003
9    
10      ** NOTE! The following LGPL license applies to the tdb
11      ** library. This does NOT imply that all of Samba is released
12      ** under the LGPL
13    
14    This library is free software; you can redistribute it and/or
15    modify it under the terms of the GNU Lesser General Public
16    License as published by the Free Software Foundation; either
17    version 2 of the License, or (at your option) any later version.
18
19    This library is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22    Lesser General Public License for more details.
23
24    You should have received a copy of the GNU Lesser General Public
25    License along with this library; if not, write to the Free Software
26    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27 */
28
29 #include "tdb_private.h"
30
31 TDB_DATA tdb_null;
32
33 /* Returns 0 on fail.  On success, return offset of record, and fills
34    in rec */
35 static tdb_off_t tdb_find(struct tdb_context *tdb, TDB_DATA key, u32 hash,
36                         struct list_struct *r)
37 {
38         tdb_off_t rec_ptr;
39         
40         /* read in the hash top */
41         if (tdb_ofs_read(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1)
42                 return 0;
43
44         /* keep looking until we find the right record */
45         while (rec_ptr) {
46                 if (tdb_rec_read(tdb, rec_ptr, r) == -1)
47                         return 0;
48
49                 if (!TDB_DEAD(r) && hash==r->full_hash && key.dsize==r->key_len) {
50                         unsigned char *k;
51                         /* a very likely hit - read the key */
52                         k = tdb_alloc_read(tdb, rec_ptr + sizeof(*r), 
53                                            r->key_len);
54                         if (!k)
55                                 return 0;
56
57                         if (memcmp(key.dptr, k, key.dsize) == 0) {
58                                 SAFE_FREE(k);
59                                 return rec_ptr;
60                         }
61                         SAFE_FREE(k);
62                 }
63                 rec_ptr = r->next;
64         }
65         return TDB_ERRCODE(TDB_ERR_NOEXIST, 0);
66 }
67
68 /* As tdb_find, but if you succeed, keep the lock */
69 tdb_off_t tdb_find_lock_hash(struct tdb_context *tdb, TDB_DATA key, u32 hash, int locktype,
70                            struct list_struct *rec)
71 {
72         u32 rec_ptr;
73
74         if (tdb_lock(tdb, BUCKET(hash), locktype) == -1)
75                 return 0;
76         if (!(rec_ptr = tdb_find(tdb, key, hash, rec)))
77                 tdb_unlock(tdb, BUCKET(hash), locktype);
78         return rec_ptr;
79 }
80
81
82 /* update an entry in place - this only works if the new data size
83    is <= the old data size and the key exists.
84    on failure return -1.
85 */
86 static int tdb_update_hash(struct tdb_context *tdb, TDB_DATA key, u32 hash, TDB_DATA dbuf)
87 {
88         struct list_struct rec;
89         tdb_off_t rec_ptr;
90
91         /* find entry */
92         if (!(rec_ptr = tdb_find(tdb, key, hash, &rec)))
93                 return -1;
94
95         /* must be long enough key, data and tailer */
96         if (rec.rec_len < key.dsize + dbuf.dsize + sizeof(tdb_off_t)) {
97                 tdb->ecode = TDB_SUCCESS; /* Not really an error */
98                 return -1;
99         }
100
101         if (tdb->methods->tdb_write(tdb, rec_ptr + sizeof(rec) + rec.key_len,
102                       dbuf.dptr, dbuf.dsize) == -1)
103                 return -1;
104
105         if (dbuf.dsize != rec.data_len) {
106                 /* update size */
107                 rec.data_len = dbuf.dsize;
108                 return tdb_rec_write(tdb, rec_ptr, &rec);
109         }
110  
111         return 0;
112 }
113
114 /* find an entry in the database given a key */
115 /* If an entry doesn't exist tdb_err will be set to
116  * TDB_ERR_NOEXIST. If a key has no data attached
117  * then the TDB_DATA will have zero length but
118  * a non-zero pointer
119  */
120 TDB_DATA tdb_fetch(struct tdb_context *tdb, TDB_DATA key)
121 {
122         tdb_off_t rec_ptr;
123         struct list_struct rec;
124         TDB_DATA ret;
125         u32 hash;
126
127         /* find which hash bucket it is in */
128         hash = tdb->hash_fn(&key);
129         if (!(rec_ptr = tdb_find_lock_hash(tdb,key,hash,F_RDLCK,&rec)))
130                 return tdb_null;
131
132         ret.dptr = tdb_alloc_read(tdb, rec_ptr + sizeof(rec) + rec.key_len,
133                                   rec.data_len);
134         ret.dsize = rec.data_len;
135         tdb_unlock(tdb, BUCKET(rec.full_hash), F_RDLCK);
136         return ret;
137 }
138
139 /* check if an entry in the database exists 
140
141    note that 1 is returned if the key is found and 0 is returned if not found
142    this doesn't match the conventions in the rest of this module, but is
143    compatible with gdbm
144 */
145 static int tdb_exists_hash(struct tdb_context *tdb, TDB_DATA key, u32 hash)
146 {
147         struct list_struct rec;
148         
149         if (tdb_find_lock_hash(tdb, key, hash, F_RDLCK, &rec) == 0)
150                 return 0;
151         tdb_unlock(tdb, BUCKET(rec.full_hash), F_RDLCK);
152         return 1;
153 }
154
155 int tdb_exists(struct tdb_context *tdb, TDB_DATA key)
156 {
157         u32 hash = tdb->hash_fn(&key);
158         return tdb_exists_hash(tdb, key, hash);
159 }
160
161 /* actually delete an entry in the database given the offset */
162 int tdb_do_delete(struct tdb_context *tdb, tdb_off_t rec_ptr, struct list_struct*rec)
163 {
164         tdb_off_t last_ptr, i;
165         struct list_struct lastrec;
166
167         if (tdb->read_only) return -1;
168
169         if (tdb_write_lock_record(tdb, rec_ptr) == -1) {
170                 /* Someone traversing here: mark it as dead */
171                 rec->magic = TDB_DEAD_MAGIC;
172                 return tdb_rec_write(tdb, rec_ptr, rec);
173         }
174         if (tdb_write_unlock_record(tdb, rec_ptr) != 0)
175                 return -1;
176
177         /* find previous record in hash chain */
178         if (tdb_ofs_read(tdb, TDB_HASH_TOP(rec->full_hash), &i) == -1)
179                 return -1;
180         for (last_ptr = 0; i != rec_ptr; last_ptr = i, i = lastrec.next)
181                 if (tdb_rec_read(tdb, i, &lastrec) == -1)
182                         return -1;
183
184         /* unlink it: next ptr is at start of record. */
185         if (last_ptr == 0)
186                 last_ptr = TDB_HASH_TOP(rec->full_hash);
187         if (tdb_ofs_write(tdb, last_ptr, &rec->next) == -1)
188                 return -1;
189
190         /* recover the space */
191         if (tdb_free(tdb, rec_ptr, rec) == -1)
192                 return -1;
193         return 0;
194 }
195
196 /* delete an entry in the database given a key */
197 static int tdb_delete_hash(struct tdb_context *tdb, TDB_DATA key, u32 hash)
198 {
199         tdb_off_t rec_ptr;
200         struct list_struct rec;
201         int ret;
202
203         if (!(rec_ptr = tdb_find_lock_hash(tdb, key, hash, F_WRLCK, &rec)))
204                 return -1;
205         ret = tdb_do_delete(tdb, rec_ptr, &rec);
206         if (tdb_unlock(tdb, BUCKET(rec.full_hash), F_WRLCK) != 0)
207                 TDB_LOG((tdb, 0, "tdb_delete: WARNING tdb_unlock failed!\n"));
208         return ret;
209 }
210
211 int tdb_delete(struct tdb_context *tdb, TDB_DATA key)
212 {
213         u32 hash = tdb->hash_fn(&key);
214         return tdb_delete_hash(tdb, key, hash);
215 }
216
217 /* store an element in the database, replacing any existing element
218    with the same key 
219
220    return 0 on success, -1 on failure
221 */
222 int tdb_store(struct tdb_context *tdb, TDB_DATA key, TDB_DATA dbuf, int flag)
223 {
224         struct list_struct rec;
225         u32 hash;
226         tdb_off_t rec_ptr;
227         char *p = NULL;
228         int ret = 0;
229
230         if (tdb->read_only) {
231                 tdb->ecode = TDB_ERR_RDONLY;
232                 return -1;
233         }
234
235         /* find which hash bucket it is in */
236         hash = tdb->hash_fn(&key);
237         if (tdb_lock(tdb, BUCKET(hash), F_WRLCK) == -1)
238                 return -1;
239
240         /* check for it existing, on insert. */
241         if (flag == TDB_INSERT) {
242                 if (tdb_exists_hash(tdb, key, hash)) {
243                         tdb->ecode = TDB_ERR_EXISTS;
244                         goto fail;
245                 }
246         } else {
247                 /* first try in-place update, on modify or replace. */
248                 if (tdb_update_hash(tdb, key, hash, dbuf) == 0)
249                         goto out;
250                 if (tdb->ecode == TDB_ERR_NOEXIST &&
251                     flag == TDB_MODIFY) {
252                         /* if the record doesn't exist and we are in TDB_MODIFY mode then
253                          we should fail the store */
254                         goto fail;
255                 }
256         }
257         /* reset the error code potentially set by the tdb_update() */
258         tdb->ecode = TDB_SUCCESS;
259
260         /* delete any existing record - if it doesn't exist we don't
261            care.  Doing this first reduces fragmentation, and avoids
262            coalescing with `allocated' block before it's updated. */
263         if (flag != TDB_INSERT)
264                 tdb_delete_hash(tdb, key, hash);
265
266         /* Copy key+value *before* allocating free space in case malloc
267            fails and we are left with a dead spot in the tdb. */
268
269         if (!(p = (char *)malloc(key.dsize + dbuf.dsize))) {
270                 tdb->ecode = TDB_ERR_OOM;
271                 goto fail;
272         }
273
274         memcpy(p, key.dptr, key.dsize);
275         if (dbuf.dsize)
276                 memcpy(p+key.dsize, dbuf.dptr, dbuf.dsize);
277
278         /* we have to allocate some space */
279         if (!(rec_ptr = tdb_allocate(tdb, key.dsize + dbuf.dsize, &rec)))
280                 goto fail;
281
282         /* Read hash top into next ptr */
283         if (tdb_ofs_read(tdb, TDB_HASH_TOP(hash), &rec.next) == -1)
284                 goto fail;
285
286         rec.key_len = key.dsize;
287         rec.data_len = dbuf.dsize;
288         rec.full_hash = hash;
289         rec.magic = TDB_MAGIC;
290
291         /* write out and point the top of the hash chain at it */
292         if (tdb_rec_write(tdb, rec_ptr, &rec) == -1
293             || tdb->methods->tdb_write(tdb, rec_ptr+sizeof(rec), p, key.dsize+dbuf.dsize)==-1
294             || tdb_ofs_write(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1) {
295                 /* Need to tdb_unallocate() here */
296                 goto fail;
297         }
298  out:
299         SAFE_FREE(p); 
300         tdb_unlock(tdb, BUCKET(hash), F_WRLCK);
301         return ret;
302 fail:
303         ret = -1;
304         goto out;
305 }
306
307
308 /* Append to an entry. Create if not exist. */
309 int tdb_append(struct tdb_context *tdb, TDB_DATA key, TDB_DATA new_dbuf)
310 {
311         u32 hash;
312         TDB_DATA dbuf;
313         int ret = -1;
314
315         /* find which hash bucket it is in */
316         hash = tdb->hash_fn(&key);
317         if (tdb_lock(tdb, BUCKET(hash), F_WRLCK) == -1)
318                 return -1;
319
320         dbuf = tdb_fetch(tdb, key);
321
322         if (dbuf.dptr == NULL) {
323                 dbuf.dptr = malloc(new_dbuf.dsize);
324         } else {
325                 dbuf.dptr = realloc(dbuf.dptr, dbuf.dsize + new_dbuf.dsize);
326         }
327
328         if (dbuf.dptr == NULL) {
329                 tdb->ecode = TDB_ERR_OOM;
330                 goto failed;
331         }
332
333         memcpy(dbuf.dptr + dbuf.dsize, new_dbuf.dptr, new_dbuf.dsize);
334         dbuf.dsize += new_dbuf.dsize;
335
336         ret = tdb_store(tdb, key, dbuf, 0);
337         
338 failed:
339         tdb_unlock(tdb, BUCKET(hash), F_WRLCK);
340         SAFE_FREE(dbuf.dptr);
341         return ret;
342 }
343
344
345 /*
346   return the name of the current tdb file
347   useful for external logging functions
348 */
349 const char *tdb_name(struct tdb_context *tdb)
350 {
351         return tdb->name;
352 }
353
354 /*
355   return the underlying file descriptor being used by tdb, or -1
356   useful for external routines that want to check the device/inode
357   of the fd
358 */
359 int tdb_fd(struct tdb_context *tdb)
360 {
361         return tdb->fd;
362 }
363
364 /*
365   return the current logging function
366   useful for external tdb routines that wish to log tdb errors
367 */
368 tdb_log_func tdb_log_fn(struct tdb_context *tdb)
369 {
370         return tdb->log_fn;
371 }