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