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