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