600d6b765d7bbb7f84d9a4d6f7a374c5a2fadb9c
[ccan] / ccan / tdb2 / tdb.c
1 #include "private.h"
2 #include <ccan/tdb2/tdb2.h>
3 #include <assert.h>
4 #include <stdarg.h>
5
6 /* The null return. */
7 struct tdb_data tdb_null = { .dptr = NULL, .dsize = 0 };
8
9 /* all contexts, to ensure no double-opens (fcntl locks don't nest!) */
10 static struct tdb_context *tdbs = NULL;
11
12 static bool tdb_already_open(dev_t device, ino_t ino)
13 {
14         struct tdb_context *i;
15         
16         for (i = tdbs; i; i = i->next) {
17                 if (i->device == device && i->inode == ino) {
18                         return true;
19                 }
20         }
21
22         return false;
23 }
24
25 static bool read_all(int fd, void *buf, size_t len)
26 {
27         while (len) {
28                 ssize_t ret;
29                 ret = read(fd, buf, len);
30                 if (ret < 0)
31                         return false;
32                 if (ret == 0) {
33                         /* ETOOSHORT? */
34                         errno = EWOULDBLOCK;
35                         return false;
36                 }
37                 buf = (char *)buf + ret;
38                 len -= ret;
39         }
40         return true;
41 }
42
43 static uint64_t random_number(struct tdb_context *tdb)
44 {
45         int fd;
46         uint64_t ret = 0;
47         struct timeval now;
48
49         fd = open("/dev/urandom", O_RDONLY);
50         if (fd >= 0) {
51                 if (read_all(fd, &ret, sizeof(ret))) {
52                         close(fd);
53                         return ret;
54                 }
55                 close(fd);
56         }
57         /* FIXME: Untested!  Based on Wikipedia protocol description! */
58         fd = open("/dev/egd-pool", O_RDWR);
59         if (fd >= 0) {
60                 /* Command is 1, next byte is size we want to read. */
61                 char cmd[2] = { 1, sizeof(uint64_t) };
62                 if (write(fd, cmd, sizeof(cmd)) == sizeof(cmd)) {
63                         char reply[1 + sizeof(uint64_t)];
64                         int r = read(fd, reply, sizeof(reply));
65                         if (r > 1) {
66                                 /* Copy at least some bytes. */
67                                 memcpy(&ret, reply+1, r - 1);
68                                 if (reply[0] == sizeof(uint64_t)
69                                     && r == sizeof(reply)) {
70                                         close(fd);
71                                         return ret;
72                                 }
73                         }
74                 }
75                 close(fd);
76         }
77
78         /* Fallback: pid and time. */
79         gettimeofday(&now, NULL);
80         ret = getpid() * 100132289ULL + now.tv_sec * 1000000ULL + now.tv_usec;
81         tdb_logerr(tdb, TDB_SUCCESS, TDB_LOG_WARNING,
82                    "tdb_open: random from getpid and time");
83         return ret;
84 }
85
86 struct new_database {
87         struct tdb_header hdr;
88         struct tdb_freetable ftable;
89 };
90
91 /* initialise a new database */
92 static int tdb_new_database(struct tdb_context *tdb,
93                             struct tdb_attribute_seed *seed,
94                             struct tdb_header *hdr)
95 {
96         /* We make it up in memory, then write it out if not internal */
97         struct new_database newdb;
98         unsigned int magic_len;
99         ssize_t rlen;
100
101         /* Fill in the header */
102         newdb.hdr.version = TDB_VERSION;
103         if (seed)
104                 newdb.hdr.hash_seed = seed->seed;
105         else
106                 newdb.hdr.hash_seed = random_number(tdb);
107         newdb.hdr.hash_test = TDB_HASH_MAGIC;
108         newdb.hdr.hash_test = tdb->khash(&newdb.hdr.hash_test,
109                                          sizeof(newdb.hdr.hash_test),
110                                          newdb.hdr.hash_seed,
111                                          tdb->hash_priv);
112         newdb.hdr.recovery = 0;
113         memset(newdb.hdr.reserved, 0, sizeof(newdb.hdr.reserved));
114         /* Initial hashes are empty. */
115         memset(newdb.hdr.hashtable, 0, sizeof(newdb.hdr.hashtable));
116
117         /* Free is empty. */
118         newdb.hdr.free_table = offsetof(struct new_database, ftable);
119         memset(&newdb.ftable, 0, sizeof(newdb.ftable));
120         tdb->ecode = set_header(NULL, &newdb.ftable.hdr, TDB_FTABLE_MAGIC, 0,
121                                 sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr),
122                                 sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr),
123                                 0);
124         if (tdb->ecode != TDB_SUCCESS) {
125                 return -1;
126         }
127
128         /* Magic food */
129         memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
130         strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
131
132         /* This creates an endian-converted database, as if read from disk */
133         magic_len = sizeof(newdb.hdr.magic_food);
134         tdb_convert(tdb,
135                     (char *)&newdb.hdr + magic_len, sizeof(newdb) - magic_len);
136
137         *hdr = newdb.hdr;
138
139         if (tdb->flags & TDB_INTERNAL) {
140                 tdb->map_size = sizeof(newdb);
141                 tdb->map_ptr = malloc(tdb->map_size);
142                 if (!tdb->map_ptr) {
143                         tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
144                                    "tdb_new_database: failed to allocate");
145                         return -1;
146                 }
147                 memcpy(tdb->map_ptr, &newdb, tdb->map_size);
148                 return 0;
149         }
150         if (lseek(tdb->fd, 0, SEEK_SET) == -1)
151                 return -1;
152
153         if (ftruncate(tdb->fd, 0) == -1)
154                 return -1;
155
156         rlen = write(tdb->fd, &newdb, sizeof(newdb));
157         if (rlen != sizeof(newdb)) {
158                 if (rlen >= 0)
159                         errno = ENOSPC;
160                 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
161                            "tdb_new_database: %zi writing header: %s",
162                            rlen, strerror(errno));
163                 return -1;
164         }
165         return 0;
166 }
167
168 struct tdb_context *tdb_open(const char *name, int tdb_flags,
169                              int open_flags, mode_t mode,
170                              union tdb_attribute *attr)
171 {
172         struct tdb_context *tdb;
173         struct stat st;
174         int saved_errno = 0;
175         uint64_t hash_test;
176         unsigned v;
177         ssize_t rlen;
178         struct tdb_header hdr;
179         struct tdb_attribute_seed *seed = NULL;
180         tdb_bool_err berr;
181         enum TDB_ERROR ecode;
182
183         tdb = malloc(sizeof(*tdb));
184         if (!tdb) {
185                 /* Can't log this */
186                 errno = ENOMEM;
187                 return NULL;
188         }
189         tdb->name = NULL;
190         tdb->map_ptr = NULL;
191         tdb->direct_access = 0;
192         tdb->fd = -1;
193         tdb->map_size = sizeof(struct tdb_header);
194         tdb->ecode = TDB_SUCCESS;
195         tdb->flags = tdb_flags;
196         tdb->logfn = NULL;
197         tdb->transaction = NULL;
198         tdb->stats = NULL;
199         tdb->access = NULL;
200         tdb_hash_init(tdb);
201         tdb_io_init(tdb);
202         tdb_lock_init(tdb);
203
204         while (attr) {
205                 switch (attr->base.attr) {
206                 case TDB_ATTRIBUTE_LOG:
207                         tdb->logfn = attr->log.log_fn;
208                         tdb->log_private = attr->log.log_private;
209                         break;
210                 case TDB_ATTRIBUTE_HASH:
211                         tdb->khash = attr->hash.hash_fn;
212                         tdb->hash_priv = attr->hash.hash_private;
213                         break;
214                 case TDB_ATTRIBUTE_SEED:
215                         seed = &attr->seed;
216                         break;
217                 case TDB_ATTRIBUTE_STATS:
218                         tdb->stats = &attr->stats;
219                         /* They have stats we don't know about?  Tell them. */
220                         if (tdb->stats->size > sizeof(attr->stats))
221                                 tdb->stats->size = sizeof(attr->stats);
222                         break;
223                 default:
224                         tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
225                                    "tdb_open: unknown attribute type %u",
226                                    attr->base.attr);
227                         goto fail;
228                 }
229                 attr = attr->base.next;
230         }
231
232         if ((open_flags & O_ACCMODE) == O_WRONLY) {
233                 tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
234                            "tdb_open: can't open tdb %s write-only", name);
235                 goto fail;
236         }
237
238         if ((open_flags & O_ACCMODE) == O_RDONLY) {
239                 tdb->read_only = true;
240                 /* read only databases don't do locking */
241                 tdb->flags |= TDB_NOLOCK;
242                 tdb->mmap_flags = PROT_READ;
243         } else {
244                 tdb->read_only = false;
245                 tdb->mmap_flags = PROT_READ | PROT_WRITE;
246         }
247
248         /* internal databases don't need any of the rest. */
249         if (tdb->flags & TDB_INTERNAL) {
250                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
251                 if (tdb_new_database(tdb, seed, &hdr) != 0) {
252                         goto fail;
253                 }
254                 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
255                 tdb->hash_seed = hdr.hash_seed;
256                 tdb_ftable_init(tdb);
257                 return tdb;
258         }
259
260         if ((tdb->fd = open(name, open_flags, mode)) == -1) {
261                 /* errno set by open(2) */
262                 saved_errno = errno;
263                 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
264                            "tdb_open: could not open file %s: %s",
265                            name, strerror(errno));
266                 goto fail;
267         }
268
269         /* on exec, don't inherit the fd */
270         v = fcntl(tdb->fd, F_GETFD, 0);
271         fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
272
273         /* ensure there is only one process initialising at once */
274         tdb->ecode = tdb_lock_open(tdb, TDB_LOCK_WAIT|TDB_LOCK_NOCHECK);
275         if (tdb->ecode != TDB_SUCCESS) {
276                 goto fail;
277         }
278
279         /* If they used O_TRUNC, read will return 0. */
280         rlen = read(tdb->fd, &hdr, sizeof(hdr));
281         if (rlen == 0 && (open_flags & O_CREAT)) {
282                 if (tdb_new_database(tdb, seed, &hdr) == -1) {
283                         goto fail;
284                 }
285         } else if (rlen < 0) {
286                 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
287                            "tdb_open: error %s reading %s",
288                            strerror(errno), name);
289                 goto fail;
290         } else if (rlen < sizeof(hdr)
291                    || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
292                 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
293                            "tdb_open: %s is not a tdb file", name);
294                 goto fail;
295         }
296
297         if (hdr.version != TDB_VERSION) {
298                 if (hdr.version == bswap_64(TDB_VERSION))
299                         tdb->flags |= TDB_CONVERT;
300                 else {
301                         /* wrong version */
302                         tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
303                                    "tdb_open: %s is unknown version 0x%llx",
304                                    name, (long long)hdr.version);
305                         goto fail;
306                 }
307         }
308
309         tdb_convert(tdb, &hdr, sizeof(hdr));
310         tdb->hash_seed = hdr.hash_seed;
311         hash_test = TDB_HASH_MAGIC;
312         hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
313         if (hdr.hash_test != hash_test) {
314                 /* wrong hash variant */
315                 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
316                            "tdb_open: %s uses a different hash function",
317                            name);
318                 goto fail;
319         }
320
321         if (fstat(tdb->fd, &st) == -1) {
322                 saved_errno = errno;
323                 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
324                            "tdb_open: could not stat open %s: %s",
325                            name, strerror(errno));
326                 goto fail;
327         }
328
329         /* Is it already in the open list?  If so, fail. */
330         if (tdb_already_open(st.st_dev, st.st_ino)) {
331                 /* FIXME */
332                 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_USE_ERROR,
333                            "tdb_open: %s (%d,%d) is already open in this"
334                            " process",
335                            name, (int)st.st_dev, (int)st.st_ino);
336                 goto fail;
337         }
338
339         tdb->name = strdup(name);
340         if (!tdb->name) {
341                 tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
342                            "tdb_open: failed to allocate name");
343                 goto fail;
344         }
345
346         tdb->device = st.st_dev;
347         tdb->inode = st.st_ino;
348         tdb_unlock_open(tdb);
349
350         /* This make sure we have current map_size and mmap. */
351         tdb->methods->oob(tdb, tdb->map_size + 1, true);
352
353         /* Now it's fully formed, recover if necessary. */
354         berr = tdb_needs_recovery(tdb);
355         if (unlikely(berr != false)) {
356                 if (berr < 0) {
357                         ecode = berr;
358                         goto fail;
359                 }
360                 ecode = tdb_lock_and_recover(tdb);
361                 if (ecode != TDB_SUCCESS) {
362                         tdb->ecode = ecode;
363                         goto fail;
364                 }
365         }
366
367         tdb->ecode = tdb_ftable_init(tdb);
368         if (tdb->ecode != TDB_SUCCESS) {
369                 goto fail;
370         }
371
372         tdb->next = tdbs;
373         tdbs = tdb;
374         return tdb;
375
376  fail:
377         /* Map ecode to some logical errno. */
378         if (!saved_errno) {
379                 switch (tdb->ecode) {
380                 case TDB_ERR_CORRUPT:
381                 case TDB_ERR_IO:
382                         saved_errno = EIO;
383                         break;
384                 case TDB_ERR_LOCK:
385                         saved_errno = EWOULDBLOCK;
386                         break;
387                 case TDB_ERR_OOM:
388                         saved_errno = ENOMEM;
389                         break;
390                 case TDB_ERR_EINVAL:
391                         saved_errno = EINVAL;
392                         break;
393                 default:
394                         saved_errno = EINVAL;
395                         break;
396                 }
397         }
398
399 #ifdef TDB_TRACE
400         close(tdb->tracefd);
401 #endif
402         if (tdb->map_ptr) {
403                 if (tdb->flags & TDB_INTERNAL) {
404                         free(tdb->map_ptr);
405                 } else
406                         tdb_munmap(tdb);
407         }
408         free(tdb->lockrecs);
409         free((char *)tdb->name);
410         if (tdb->fd != -1)
411                 if (close(tdb->fd) != 0)
412                         tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
413                                    "tdb_open: failed to close tdb->fd"
414                                    " on error: %s", strerror(errno));
415         free(tdb);
416         errno = saved_errno;
417         return NULL;
418 }
419
420 static int update_rec_hdr(struct tdb_context *tdb,
421                           tdb_off_t off,
422                           tdb_len_t keylen,
423                           tdb_len_t datalen,
424                           struct tdb_used_record *rec,
425                           uint64_t h)
426 {
427         uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
428         enum TDB_ERROR ecode;
429
430         ecode = set_header(tdb, rec, TDB_USED_MAGIC, keylen, datalen,
431                            keylen + dataroom, h);
432         if (ecode != TDB_SUCCESS) {
433                 tdb->ecode = ecode;
434                 return -1;
435         }
436
437         ecode = tdb_write_convert(tdb, off, rec, sizeof(*rec));
438         if (ecode != TDB_SUCCESS) {
439                 tdb->ecode = ecode;
440                 return -1;
441         }
442         return 0;
443 }
444
445 /* Returns -1 on error, 0 on OK */
446 static int replace_data(struct tdb_context *tdb,
447                         struct hash_info *h,
448                         struct tdb_data key, struct tdb_data dbuf,
449                         tdb_off_t old_off, tdb_len_t old_room,
450                         bool growing)
451 {
452         tdb_off_t new_off;
453         enum TDB_ERROR ecode;
454
455         /* Allocate a new record. */
456         new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, TDB_USED_MAGIC,
457                         growing);
458         if (TDB_OFF_IS_ERR(new_off)) {
459                 tdb->ecode = new_off;
460                 return -1;
461         }
462
463         /* We didn't like the existing one: remove it. */
464         if (old_off) {
465                 add_stat(tdb, frees, 1);
466                 ecode = add_free_record(tdb, old_off,
467                                         sizeof(struct tdb_used_record)
468                                         + key.dsize + old_room);
469                 if (ecode == TDB_SUCCESS)
470                         ecode = replace_in_hash(tdb, h, new_off);
471         } else {
472                 ecode = add_to_hash(tdb, h, new_off);
473         }
474         if (ecode != TDB_SUCCESS) {
475                 tdb->ecode = ecode;
476                 return -1;
477         }
478
479         new_off += sizeof(struct tdb_used_record);
480         ecode = tdb->methods->twrite(tdb, new_off, key.dptr, key.dsize);
481         if (ecode != TDB_SUCCESS) {
482                 tdb->ecode = ecode;
483                 return -1;
484         }
485
486         new_off += key.dsize;
487         ecode = tdb->methods->twrite(tdb, new_off, dbuf.dptr, dbuf.dsize);
488         if (ecode != TDB_SUCCESS) {
489                 tdb->ecode = ecode;
490                 return -1;
491         }
492
493         /* FIXME: tdb_increment_seqnum(tdb); */
494         return 0;
495 }
496
497 int tdb_store(struct tdb_context *tdb,
498               struct tdb_data key, struct tdb_data dbuf, int flag)
499 {
500         struct hash_info h;
501         tdb_off_t off;
502         tdb_len_t old_room = 0;
503         struct tdb_used_record rec;
504         int ret;
505         enum TDB_ERROR ecode;
506
507         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
508         if (TDB_OFF_IS_ERR(off)) {
509                 tdb->ecode = off;
510                 return -1;
511         }
512
513         /* Now we have lock on this hash bucket. */
514         if (flag == TDB_INSERT) {
515                 if (off) {
516                         tdb->ecode = TDB_ERR_EXISTS;
517                         goto fail;
518                 }
519         } else {
520                 if (off) {
521                         old_room = rec_data_length(&rec)
522                                 + rec_extra_padding(&rec);
523                         if (old_room >= dbuf.dsize) {
524                                 /* Can modify in-place.  Easy! */
525                                 if (update_rec_hdr(tdb, off,
526                                                    key.dsize, dbuf.dsize,
527                                                    &rec, h.h))
528                                         goto fail;
529                                 ecode = tdb->methods->twrite(tdb,
530                                                              off + sizeof(rec)
531                                                              + key.dsize,
532                                                              dbuf.dptr,
533                                                              dbuf.dsize);
534                                 if (ecode != TDB_SUCCESS) {
535                                         tdb->ecode = ecode;
536                                         goto fail;
537                                 }
538                                 tdb_unlock_hashes(tdb, h.hlock_start,
539                                                   h.hlock_range, F_WRLCK);
540                                 return 0;
541                         }
542                 } else {
543                         if (flag == TDB_MODIFY) {
544                                 /* if the record doesn't exist and we
545                                    are in TDB_MODIFY mode then we should fail
546                                    the store */
547                                 tdb->ecode = TDB_ERR_NOEXIST;
548                                 goto fail;
549                         }
550                 }
551         }
552
553         /* If we didn't use the old record, this implies we're growing. */
554         ret = replace_data(tdb, &h, key, dbuf, off, old_room, off != 0);
555         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
556         return ret;
557
558 fail:
559         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
560         return -1;
561 }
562
563 int tdb_append(struct tdb_context *tdb,
564                struct tdb_data key, struct tdb_data dbuf)
565 {
566         struct hash_info h;
567         tdb_off_t off;
568         struct tdb_used_record rec;
569         tdb_len_t old_room = 0, old_dlen;
570         unsigned char *newdata;
571         struct tdb_data new_dbuf;
572         enum TDB_ERROR ecode;
573         int ret;
574
575         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
576         if (TDB_OFF_IS_ERR(off)) {
577                 tdb->ecode = off;
578                 return -1;
579         }
580
581         if (off) {
582                 old_dlen = rec_data_length(&rec);
583                 old_room = old_dlen + rec_extra_padding(&rec);
584
585                 /* Fast path: can append in place. */
586                 if (rec_extra_padding(&rec) >= dbuf.dsize) {
587                         if (update_rec_hdr(tdb, off, key.dsize,
588                                            old_dlen + dbuf.dsize, &rec, h.h))
589                                 goto fail;
590
591                         off += sizeof(rec) + key.dsize + old_dlen;
592                         ecode = tdb->methods->twrite(tdb, off, dbuf.dptr,
593                                                      dbuf.dsize);
594                         if (ecode != TDB_SUCCESS) {
595                                 tdb->ecode = ecode;
596                                 goto fail;
597                         }
598
599                         /* FIXME: tdb_increment_seqnum(tdb); */
600                         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range,
601                                           F_WRLCK);
602                         return 0;
603                 }
604
605                 /* Slow path. */
606                 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
607                 if (!newdata) {
608                         tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
609                                    "tdb_append: failed to allocate %zu bytes",
610                                    (size_t)(key.dsize+old_dlen+dbuf.dsize));
611                         goto fail;
612                 }
613                 ecode = tdb->methods->tread(tdb, off + sizeof(rec) + key.dsize,
614                                             newdata, old_dlen);
615                 if (ecode != TDB_SUCCESS) {
616                         tdb->ecode = ecode;
617                         free(newdata);
618                         goto fail;
619                 }
620                 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
621                 new_dbuf.dptr = newdata;
622                 new_dbuf.dsize = old_dlen + dbuf.dsize;
623         } else {
624                 newdata = NULL;
625                 new_dbuf = dbuf;
626         }
627
628         /* If they're using tdb_append(), it implies they're growing record. */
629         ret = replace_data(tdb, &h, key, new_dbuf, off, old_room, true);
630         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
631         free(newdata);
632
633         return ret;
634
635 fail:
636         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
637         return -1;
638 }
639
640 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
641 {
642         tdb_off_t off;
643         struct tdb_used_record rec;
644         struct hash_info h;
645         struct tdb_data ret;
646
647         off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
648         if (TDB_OFF_IS_ERR(off)) {
649                 tdb->ecode = off;
650                 return tdb_null;
651         }
652
653         if (!off) {
654                 tdb->ecode = TDB_ERR_NOEXIST;
655                 ret = tdb_null;
656         } else {
657                 ret.dsize = rec_data_length(&rec);
658                 ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
659                                           ret.dsize);
660                 if (TDB_PTR_IS_ERR(ret.dptr)) {
661                         tdb->ecode = TDB_PTR_ERR(ret.dptr);
662                         ret = tdb_null;
663                 }
664         }
665
666         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
667         return ret;
668 }
669
670 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
671 {
672         tdb_off_t off;
673         struct tdb_used_record rec;
674         struct hash_info h;
675         enum TDB_ERROR ecode;
676
677         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
678         if (TDB_OFF_IS_ERR(off)) {
679                 tdb->ecode = off;
680                 return -1;
681         }
682
683         if (!off) {
684                 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
685                 tdb->ecode = TDB_ERR_NOEXIST;
686                 return -1;
687         }
688
689         ecode = delete_from_hash(tdb, &h);
690         if (ecode != TDB_SUCCESS) {
691                 tdb->ecode = ecode;
692                 goto unlock_err;
693         }
694
695         /* Free the deleted entry. */
696         add_stat(tdb, frees, 1);
697         ecode = add_free_record(tdb, off,
698                                 sizeof(struct tdb_used_record)
699                                 + rec_key_length(&rec)
700                                 + rec_data_length(&rec)
701                                 + rec_extra_padding(&rec));
702         if (ecode != TDB_SUCCESS) {
703                 tdb->ecode = ecode;
704                 goto unlock_err;
705         }
706
707         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
708         return 0;
709
710 unlock_err:
711         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
712         return -1;
713 }
714
715 int tdb_close(struct tdb_context *tdb)
716 {
717         struct tdb_context **i;
718         int ret = 0;
719
720         tdb_trace(tdb, "tdb_close");
721
722         if (tdb->transaction) {
723                 tdb_transaction_cancel(tdb);
724         }
725
726         if (tdb->map_ptr) {
727                 if (tdb->flags & TDB_INTERNAL)
728                         free(tdb->map_ptr);
729                 else
730                         tdb_munmap(tdb);
731         }
732         free((char *)tdb->name);
733         if (tdb->fd != -1) {
734                 ret = close(tdb->fd);
735                 tdb->fd = -1;
736         }
737         free(tdb->lockrecs);
738
739         /* Remove from contexts list */
740         for (i = &tdbs; *i; i = &(*i)->next) {
741                 if (*i == tdb) {
742                         *i = tdb->next;
743                         break;
744                 }
745         }
746
747 #ifdef TDB_TRACE
748         close(tdb->tracefd);
749 #endif
750         free(tdb);
751
752         return ret;
753 }
754
755 enum TDB_ERROR tdb_error(const struct tdb_context *tdb)
756 {
757         return tdb->ecode;
758 }
759
760 const char *tdb_errorstr(const struct tdb_context *tdb)
761 {
762         /* Gcc warns if you miss a case in the switch, so use that. */
763         switch (tdb->ecode) {
764         case TDB_SUCCESS: return "Success";
765         case TDB_ERR_CORRUPT: return "Corrupt database";
766         case TDB_ERR_IO: return "IO Error";
767         case TDB_ERR_LOCK: return "Locking error";
768         case TDB_ERR_OOM: return "Out of memory";
769         case TDB_ERR_EXISTS: return "Record exists";
770         case TDB_ERR_EINVAL: return "Invalid parameter";
771         case TDB_ERR_NOEXIST: return "Record does not exist";
772         case TDB_ERR_RDONLY: return "write not permitted";
773         }
774         return "Invalid error code";
775 }
776
777 enum TDB_ERROR COLD tdb_logerr(struct tdb_context *tdb,
778                                enum TDB_ERROR ecode,
779                                enum tdb_log_level level,
780                                const char *fmt, ...)
781 {
782         char *message;
783         va_list ap;
784         size_t len;
785         /* tdb_open paths care about errno, so save it. */
786         int saved_errno = errno;
787
788         tdb->ecode = ecode;
789
790         if (!tdb->logfn)
791                 return ecode;
792
793         /* FIXME: Doesn't assume asprintf. */
794         va_start(ap, fmt);
795         len = vsnprintf(NULL, 0, fmt, ap);
796         va_end(ap);
797
798         message = malloc(len + 1);
799         if (!message) {
800                 tdb->logfn(tdb, TDB_LOG_ERROR, tdb->log_private,
801                            "out of memory formatting message:");
802                 tdb->logfn(tdb, level, tdb->log_private, fmt);
803                 return ecode;
804         }
805         va_start(ap, fmt);
806         len = vsprintf(message, fmt, ap);
807         va_end(ap);
808         tdb->logfn(tdb, level, tdb->log_private, message);
809         free(message);
810         errno = saved_errno;
811         return ecode;
812 }