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