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