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