]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/tdb.c
tdb2: rename ->read and ->write functions.
[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((char *)tdb->name);
401         if (tdb->fd != -1)
402                 if (close(tdb->fd) != 0)
403                         tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
404                                    "tdb_open: failed to close tdb->fd"
405                                    " on error!");
406         free(tdb);
407         errno = saved_errno;
408         return NULL;
409 }
410
411 static int update_rec_hdr(struct tdb_context *tdb,
412                           tdb_off_t off,
413                           tdb_len_t keylen,
414                           tdb_len_t datalen,
415                           struct tdb_used_record *rec,
416                           uint64_t h)
417 {
418         uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
419
420         if (set_header(tdb, rec, TDB_USED_MAGIC, keylen, datalen,
421                        keylen + dataroom, h))
422                 return -1;
423
424         return tdb_write_convert(tdb, off, rec, sizeof(*rec));
425 }
426
427 /* Returns -1 on error, 0 on OK */
428 static int replace_data(struct tdb_context *tdb,
429                         struct hash_info *h,
430                         struct tdb_data key, struct tdb_data dbuf,
431                         tdb_off_t old_off, tdb_len_t old_room,
432                         bool growing)
433 {
434         tdb_off_t new_off;
435
436         /* Allocate a new record. */
437         new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, TDB_USED_MAGIC,
438                         growing);
439         if (unlikely(new_off == TDB_OFF_ERR))
440                 return -1;
441
442         /* We didn't like the existing one: remove it. */
443         if (old_off) {
444                 add_stat(tdb, frees, 1);
445                 add_free_record(tdb, old_off,
446                                 sizeof(struct tdb_used_record)
447                                 + key.dsize + old_room);
448                 if (replace_in_hash(tdb, h, new_off) == -1)
449                         return -1;
450         } else {
451                 if (add_to_hash(tdb, h, new_off) == -1)
452                         return -1;
453         }
454
455         new_off += sizeof(struct tdb_used_record);
456         if (tdb->methods->twrite(tdb, new_off, key.dptr, key.dsize) == -1)
457                 return -1;
458
459         new_off += key.dsize;
460         if (tdb->methods->twrite(tdb, new_off, dbuf.dptr, dbuf.dsize) == -1)
461                 return -1;
462
463         /* FIXME: tdb_increment_seqnum(tdb); */
464         return 0;
465 }
466
467 int tdb_store(struct tdb_context *tdb,
468               struct tdb_data key, struct tdb_data dbuf, int flag)
469 {
470         struct hash_info h;
471         tdb_off_t off;
472         tdb_len_t old_room = 0;
473         struct tdb_used_record rec;
474         int ret;
475
476         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
477         if (unlikely(off == TDB_OFF_ERR))
478                 return -1;
479
480         /* Now we have lock on this hash bucket. */
481         if (flag == TDB_INSERT) {
482                 if (off) {
483                         tdb->ecode = TDB_ERR_EXISTS;
484                         goto fail;
485                 }
486         } else {
487                 if (off) {
488                         old_room = rec_data_length(&rec)
489                                 + rec_extra_padding(&rec);
490                         if (old_room >= dbuf.dsize) {
491                                 /* Can modify in-place.  Easy! */
492                                 if (update_rec_hdr(tdb, off,
493                                                    key.dsize, dbuf.dsize,
494                                                    &rec, h.h))
495                                         goto fail;
496                                 if (tdb->methods->twrite(tdb, off + sizeof(rec)
497                                                          + key.dsize,
498                                                          dbuf.dptr, dbuf.dsize))
499                                         goto fail;
500                                 tdb_unlock_hashes(tdb, h.hlock_start,
501                                                   h.hlock_range, F_WRLCK);
502                                 return 0;
503                         }
504                 } else {
505                         if (flag == TDB_MODIFY) {
506                                 /* if the record doesn't exist and we
507                                    are in TDB_MODIFY mode then we should fail
508                                    the store */
509                                 tdb->ecode = TDB_ERR_NOEXIST;
510                                 goto fail;
511                         }
512                 }
513         }
514
515         /* If we didn't use the old record, this implies we're growing. */
516         ret = replace_data(tdb, &h, key, dbuf, off, old_room, off != 0);
517         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
518         return ret;
519
520 fail:
521         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
522         return -1;
523 }
524
525 int tdb_append(struct tdb_context *tdb,
526                struct tdb_data key, struct tdb_data dbuf)
527 {
528         struct hash_info h;
529         tdb_off_t off;
530         struct tdb_used_record rec;
531         tdb_len_t old_room = 0, old_dlen;
532         unsigned char *newdata;
533         struct tdb_data new_dbuf;
534         int ret;
535
536         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
537         if (unlikely(off == TDB_OFF_ERR))
538                 return -1;
539
540         if (off) {
541                 old_dlen = rec_data_length(&rec);
542                 old_room = old_dlen + rec_extra_padding(&rec);
543
544                 /* Fast path: can append in place. */
545                 if (rec_extra_padding(&rec) >= dbuf.dsize) {
546                         if (update_rec_hdr(tdb, off, key.dsize,
547                                            old_dlen + dbuf.dsize, &rec, h.h))
548                                 goto fail;
549
550                         off += sizeof(rec) + key.dsize + old_dlen;
551                         if (tdb->methods->twrite(tdb, off, dbuf.dptr,
552                                                  dbuf.dsize) == -1)
553                                 goto fail;
554
555                         /* FIXME: tdb_increment_seqnum(tdb); */
556                         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range,
557                                           F_WRLCK);
558                         return 0;
559                 }
560
561                 /* Slow path. */
562                 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
563                 if (!newdata) {
564                         tdb_logerr(tdb, TDB_ERR_OOM, TDB_DEBUG_FATAL,
565                                    "tdb_append: failed to allocate %zu bytes",
566                                    (size_t)(key.dsize+old_dlen+dbuf.dsize));
567                         goto fail;
568                 }
569                 if (tdb->methods->tread(tdb, off + sizeof(rec) + key.dsize,
570                                         newdata, old_dlen) != 0) {
571                         free(newdata);
572                         goto fail;
573                 }
574                 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
575                 new_dbuf.dptr = newdata;
576                 new_dbuf.dsize = old_dlen + dbuf.dsize;
577         } else {
578                 newdata = NULL;
579                 new_dbuf = dbuf;
580         }
581
582         /* If they're using tdb_append(), it implies they're growing record. */
583         ret = replace_data(tdb, &h, key, new_dbuf, off, old_room, true);
584         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
585         free(newdata);
586
587         return ret;
588
589 fail:
590         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
591         return -1;
592 }
593
594 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
595 {
596         tdb_off_t off;
597         struct tdb_used_record rec;
598         struct hash_info h;
599         struct tdb_data ret;
600
601         off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
602         if (unlikely(off == TDB_OFF_ERR))
603                 return tdb_null;
604
605         if (!off) {
606                 tdb->ecode = TDB_ERR_NOEXIST;
607                 ret = tdb_null;
608         } else {
609                 ret.dsize = rec_data_length(&rec);
610                 ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
611                                           ret.dsize);
612         }
613
614         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
615         return ret;
616 }
617
618 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
619 {
620         tdb_off_t off;
621         struct tdb_used_record rec;
622         struct hash_info h;
623
624         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
625         if (unlikely(off == TDB_OFF_ERR))
626                 return -1;
627
628         if (!off) {
629                 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
630                 tdb->ecode = TDB_ERR_NOEXIST;
631                 return -1;
632         }
633
634         if (delete_from_hash(tdb, &h) == -1)
635                 goto unlock_err;
636
637         /* Free the deleted entry. */
638         add_stat(tdb, frees, 1);
639         if (add_free_record(tdb, off,
640                             sizeof(struct tdb_used_record)
641                             + rec_key_length(&rec)
642                             + rec_data_length(&rec)
643                             + rec_extra_padding(&rec)) != 0)
644                 goto unlock_err;
645
646         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
647         return 0;
648
649 unlock_err:
650         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
651         return -1;
652 }
653
654 int tdb_close(struct tdb_context *tdb)
655 {
656         struct tdb_context **i;
657         int ret = 0;
658
659         tdb_trace(tdb, "tdb_close");
660
661         if (tdb->transaction) {
662                 tdb_transaction_cancel(tdb);
663         }
664
665         if (tdb->map_ptr) {
666                 if (tdb->flags & TDB_INTERNAL)
667                         free(tdb->map_ptr);
668                 else
669                         tdb_munmap(tdb);
670         }
671         free((char *)tdb->name);
672         if (tdb->fd != -1) {
673                 ret = close(tdb->fd);
674                 tdb->fd = -1;
675         }
676         free(tdb->lockrecs);
677
678         /* Remove from contexts list */
679         for (i = &tdbs; *i; i = &(*i)->next) {
680                 if (*i == tdb) {
681                         *i = tdb->next;
682                         break;
683                 }
684         }
685
686 #ifdef TDB_TRACE
687         close(tdb->tracefd);
688 #endif
689         free(tdb);
690
691         return ret;
692 }
693
694 enum TDB_ERROR tdb_error(const struct tdb_context *tdb)
695 {
696         return tdb->ecode;
697 }
698
699 const char *tdb_errorstr(const struct tdb_context *tdb)
700 {
701         /* Gcc warns if you miss a case in the switch, so use that. */
702         switch (tdb->ecode) {
703         case TDB_SUCCESS: return "Success";
704         case TDB_ERR_CORRUPT: return "Corrupt database";
705         case TDB_ERR_IO: return "IO Error";
706         case TDB_ERR_LOCK: return "Locking error";
707         case TDB_ERR_OOM: return "Out of memory";
708         case TDB_ERR_EXISTS: return "Record exists";
709         case TDB_ERR_NESTING: return "Transaction already started";
710         case TDB_ERR_EINVAL: return "Invalid parameter";
711         case TDB_ERR_NOEXIST: return "Record does not exist";
712         case TDB_ERR_RDONLY: return "write not permitted";
713         }
714         return "Invalid error code";
715 }
716
717 void COLD tdb_logerr(struct tdb_context *tdb,
718                      enum TDB_ERROR ecode,
719                      enum tdb_debug_level level,
720                      const char *fmt, ...)
721 {
722         char *message;
723         va_list ap;
724         size_t len;
725         /* tdb_open paths care about errno, so save it. */
726         int saved_errno = errno;
727
728         tdb->ecode = ecode;
729
730         if (!tdb->logfn)
731                 return;
732
733         /* FIXME: Doesn't assume asprintf. */
734         va_start(ap, fmt);
735         len = vsnprintf(NULL, 0, fmt, ap);
736         va_end(ap);
737
738         message = malloc(len + 1);
739         if (!message) {
740                 tdb->logfn(tdb, level, tdb->log_private,
741                            "out of memory formatting message");
742                 return;
743         }
744         va_start(ap, fmt);
745         len = vsprintf(message, fmt, ap);
746         va_end(ap);
747         tdb->logfn(tdb, level, tdb->log_private, message);
748         free(message);
749         errno = saved_errno;
750 }