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