]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/open.c
tdb2: unify tdb1_traverse into tdb_traverse
[ccan] / ccan / tdb2 / open.c
1  /*
2    Trivial Database 2: opening and closing TDBs
3    Copyright (C) Rusty Russell 2010
4
5    This library is free software; you can redistribute it and/or
6    modify it under the terms of the GNU Lesser General Public
7    License as published by the Free Software Foundation; either
8    version 3 of the License, or (at your option) any later version.
9
10    This library is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14
15    You should have received a copy of the GNU Lesser General Public
16    License along with this library; if not, see <http://www.gnu.org/licenses/>.
17 */
18 #include "private.h"
19 #include <ccan/build_assert/build_assert.h>
20 #include <assert.h>
21
22 /* all tdbs, to detect double-opens (fcntl file don't nest!) */
23 static struct tdb_context *tdbs = NULL;
24
25 static struct tdb_file *find_file(dev_t device, ino_t ino)
26 {
27         struct tdb_context *i;
28
29         for (i = tdbs; i; i = i->next) {
30                 if (i->file->device == device && i->file->inode == ino) {
31                         i->file->refcnt++;
32                         return i->file;
33                 }
34         }
35         return NULL;
36 }
37
38 static bool read_all(int fd, void *buf, size_t len)
39 {
40         while (len) {
41                 ssize_t ret;
42                 ret = read(fd, buf, len);
43                 if (ret < 0)
44                         return false;
45                 if (ret == 0) {
46                         /* ETOOSHORT? */
47                         errno = EWOULDBLOCK;
48                         return false;
49                 }
50                 buf = (char *)buf + ret;
51                 len -= ret;
52         }
53         return true;
54 }
55
56 static uint64_t random_number(struct tdb_context *tdb)
57 {
58         int fd;
59         uint64_t ret = 0;
60         struct timeval now;
61
62         fd = open("/dev/urandom", O_RDONLY);
63         if (fd >= 0) {
64                 if (read_all(fd, &ret, sizeof(ret))) {
65                         close(fd);
66                         return ret;
67                 }
68                 close(fd);
69         }
70         /* FIXME: Untested!  Based on Wikipedia protocol description! */
71         fd = open("/dev/egd-pool", O_RDWR);
72         if (fd >= 0) {
73                 /* Command is 1, next byte is size we want to read. */
74                 char cmd[2] = { 1, sizeof(uint64_t) };
75                 if (write(fd, cmd, sizeof(cmd)) == sizeof(cmd)) {
76                         char reply[1 + sizeof(uint64_t)];
77                         int r = read(fd, reply, sizeof(reply));
78                         if (r > 1) {
79                                 /* Copy at least some bytes. */
80                                 memcpy(&ret, reply+1, r - 1);
81                                 if (reply[0] == sizeof(uint64_t)
82                                     && r == sizeof(reply)) {
83                                         close(fd);
84                                         return ret;
85                                 }
86                         }
87                 }
88                 close(fd);
89         }
90
91         /* Fallback: pid and time. */
92         gettimeofday(&now, NULL);
93         ret = getpid() * 100132289ULL + now.tv_sec * 1000000ULL + now.tv_usec;
94         tdb_logerr(tdb, TDB_SUCCESS, TDB_LOG_WARNING,
95                    "tdb_open: random from getpid and time");
96         return ret;
97 }
98
99 static void tdb2_context_init(struct tdb_context *tdb)
100 {
101         /* Initialize the TDB2 fields here */
102         tdb_io_init(tdb);
103         tdb->tdb2.direct_access = 0;
104         tdb->tdb2.transaction = NULL;
105         tdb->tdb2.access = NULL;
106 }
107
108 struct new_database {
109         struct tdb_header hdr;
110         struct tdb_freetable ftable;
111 };
112
113 /* initialise a new database */
114 static enum TDB_ERROR tdb_new_database(struct tdb_context *tdb,
115                                        struct tdb_attribute_seed *seed,
116                                        struct tdb_header *hdr)
117 {
118         /* We make it up in memory, then write it out if not internal */
119         struct new_database newdb;
120         unsigned int magic_len;
121         ssize_t rlen;
122         enum TDB_ERROR ecode;
123
124         /* Fill in the header */
125         newdb.hdr.version = TDB_VERSION;
126         if (seed)
127                 newdb.hdr.hash_seed = seed->seed;
128         else
129                 newdb.hdr.hash_seed = random_number(tdb);
130         newdb.hdr.hash_test = TDB_HASH_MAGIC;
131         newdb.hdr.hash_test = tdb->hash_fn(&newdb.hdr.hash_test,
132                                            sizeof(newdb.hdr.hash_test),
133                                            newdb.hdr.hash_seed,
134                                            tdb->hash_data);
135         newdb.hdr.recovery = 0;
136         newdb.hdr.features_used = newdb.hdr.features_offered = TDB_FEATURE_MASK;
137         newdb.hdr.seqnum = 0;
138         memset(newdb.hdr.reserved, 0, sizeof(newdb.hdr.reserved));
139         /* Initial hashes are empty. */
140         memset(newdb.hdr.hashtable, 0, sizeof(newdb.hdr.hashtable));
141
142         /* Free is empty. */
143         newdb.hdr.free_table = offsetof(struct new_database, ftable);
144         memset(&newdb.ftable, 0, sizeof(newdb.ftable));
145         ecode = set_header(NULL, &newdb.ftable.hdr, TDB_FTABLE_MAGIC, 0,
146                            sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr),
147                            sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr),
148                            0);
149         if (ecode != TDB_SUCCESS) {
150                 return ecode;
151         }
152
153         /* Magic food */
154         memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
155         strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
156
157         /* This creates an endian-converted database, as if read from disk */
158         magic_len = sizeof(newdb.hdr.magic_food);
159         tdb_convert(tdb,
160                     (char *)&newdb.hdr + magic_len, sizeof(newdb) - magic_len);
161
162         *hdr = newdb.hdr;
163
164         if (tdb->flags & TDB_INTERNAL) {
165                 tdb->file->map_size = sizeof(newdb);
166                 tdb->file->map_ptr = malloc(tdb->file->map_size);
167                 if (!tdb->file->map_ptr) {
168                         return tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
169                                           "tdb_new_database:"
170                                           " failed to allocate");
171                 }
172                 memcpy(tdb->file->map_ptr, &newdb, tdb->file->map_size);
173                 return TDB_SUCCESS;
174         }
175         if (lseek(tdb->file->fd, 0, SEEK_SET) == -1) {
176                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
177                                   "tdb_new_database:"
178                                   " failed to seek: %s", strerror(errno));
179         }
180
181         if (ftruncate(tdb->file->fd, 0) == -1) {
182                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
183                                   "tdb_new_database:"
184                                   " failed to truncate: %s", strerror(errno));
185         }
186
187         rlen = write(tdb->file->fd, &newdb, sizeof(newdb));
188         if (rlen != sizeof(newdb)) {
189                 if (rlen >= 0)
190                         errno = ENOSPC;
191                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
192                                   "tdb_new_database: %zi writing header: %s",
193                                   rlen, strerror(errno));
194         }
195         return TDB_SUCCESS;
196 }
197
198 static enum TDB_ERROR tdb_new_file(struct tdb_context *tdb)
199 {
200         tdb->file = malloc(sizeof(*tdb->file));
201         if (!tdb->file)
202                 return tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
203                                   "tdb_open: cannot alloc tdb_file structure");
204         tdb->file->num_lockrecs = 0;
205         tdb->file->lockrecs = NULL;
206         tdb->file->allrecord_lock.count = 0;
207         tdb->file->refcnt = 1;
208         tdb->file->map_ptr = NULL;
209         return TDB_SUCCESS;
210 }
211
212 enum TDB_ERROR tdb_set_attribute(struct tdb_context *tdb,
213                                  const union tdb_attribute *attr)
214 {
215         switch (attr->base.attr) {
216         case TDB_ATTRIBUTE_LOG:
217                 tdb->log_fn = attr->log.fn;
218                 tdb->log_data = attr->log.data;
219                 break;
220         case TDB_ATTRIBUTE_HASH:
221         case TDB_ATTRIBUTE_SEED:
222         case TDB_ATTRIBUTE_OPENHOOK:
223         case TDB_ATTRIBUTE_TDB1_HASHSIZE:
224                 return tdb->last_error
225                         = tdb_logerr(tdb, TDB_ERR_EINVAL,
226                                      TDB_LOG_USE_ERROR,
227                                      "tdb_set_attribute:"
228                                      " cannot set %s after opening",
229                                      attr->base.attr == TDB_ATTRIBUTE_HASH
230                                      ? "TDB_ATTRIBUTE_HASH"
231                                      : attr->base.attr == TDB_ATTRIBUTE_SEED
232                                      ? "TDB_ATTRIBUTE_SEED"
233                                      : attr->base.attr == TDB_ATTRIBUTE_OPENHOOK
234                                      ? "TDB_ATTRIBUTE_OPENHOOK"
235                                      : "TDB_ATTRIBUTE_TDB1_HASHSIZE");
236         case TDB_ATTRIBUTE_STATS:
237                 return tdb->last_error
238                         = tdb_logerr(tdb, TDB_ERR_EINVAL,
239                                      TDB_LOG_USE_ERROR,
240                                      "tdb_set_attribute:"
241                                      " cannot set TDB_ATTRIBUTE_STATS");
242         case TDB_ATTRIBUTE_FLOCK:
243                 tdb->lock_fn = attr->flock.lock;
244                 tdb->unlock_fn = attr->flock.unlock;
245                 tdb->lock_data = attr->flock.data;
246                 break;
247         default:
248                 return tdb->last_error
249                         = tdb_logerr(tdb, TDB_ERR_EINVAL,
250                                      TDB_LOG_USE_ERROR,
251                                      "tdb_set_attribute:"
252                                      " unknown attribute type %u",
253                                      attr->base.attr);
254         }
255         return TDB_SUCCESS;
256 }
257
258 enum TDB_ERROR tdb_get_attribute(struct tdb_context *tdb,
259                                  union tdb_attribute *attr)
260 {
261         switch (attr->base.attr) {
262         case TDB_ATTRIBUTE_LOG:
263                 if (!tdb->log_fn)
264                         return tdb->last_error = TDB_ERR_NOEXIST;
265                 attr->log.fn = tdb->log_fn;
266                 attr->log.data = tdb->log_data;
267                 break;
268         case TDB_ATTRIBUTE_HASH:
269                 attr->hash.fn = tdb->hash_fn;
270                 attr->hash.data = tdb->hash_data;
271                 break;
272         case TDB_ATTRIBUTE_SEED:
273                 if (tdb->flags & TDB_VERSION1)
274                         return tdb->last_error
275                                 = tdb_logerr(tdb, TDB_ERR_EINVAL,
276                                              TDB_LOG_USE_ERROR,
277                                      "tdb_get_attribute:"
278                                      " cannot get TDB_ATTRIBUTE_SEED"
279                                      " on TDB1 tdb.");
280                 attr->seed.seed = tdb->hash_seed;
281                 break;
282         case TDB_ATTRIBUTE_OPENHOOK:
283                 if (!tdb->openhook)
284                         return tdb->last_error = TDB_ERR_NOEXIST;
285                 attr->openhook.fn = tdb->openhook;
286                 attr->openhook.data = tdb->openhook_data;
287                 break;
288         case TDB_ATTRIBUTE_STATS: {
289                 size_t size = attr->stats.size;
290                 if (size > tdb->stats.size)
291                         size = tdb->stats.size;
292                 memcpy(&attr->stats, &tdb->stats, size);
293                 break;
294         }
295         case TDB_ATTRIBUTE_FLOCK:
296                 attr->flock.lock = tdb->lock_fn;
297                 attr->flock.unlock = tdb->unlock_fn;
298                 attr->flock.data = tdb->lock_data;
299                 break;
300         case TDB_ATTRIBUTE_TDB1_HASHSIZE:
301                 if (!(tdb->flags & TDB_VERSION1))
302                         return tdb->last_error
303                                 = tdb_logerr(tdb, TDB_ERR_EINVAL,
304                                              TDB_LOG_USE_ERROR,
305                                      "tdb_get_attribute:"
306                                      " cannot get TDB_ATTRIBUTE_TDB1_HASHSIZE"
307                                      " on TDB2 tdb.");
308                 attr->tdb1_hashsize.hsize = tdb->tdb1.header.hash_size;
309                 break;
310         default:
311                 return tdb->last_error
312                         = tdb_logerr(tdb, TDB_ERR_EINVAL,
313                                      TDB_LOG_USE_ERROR,
314                                      "tdb_get_attribute:"
315                                      " unknown attribute type %u",
316                                      attr->base.attr);
317         }
318         attr->base.next = NULL;
319         return TDB_SUCCESS;
320 }
321
322 void tdb_unset_attribute(struct tdb_context *tdb,
323                          enum tdb_attribute_type type)
324 {
325         switch (type) {
326         case TDB_ATTRIBUTE_LOG:
327                 tdb->log_fn = NULL;
328                 break;
329         case TDB_ATTRIBUTE_OPENHOOK:
330                 tdb->openhook = NULL;
331                 break;
332         case TDB_ATTRIBUTE_HASH:
333         case TDB_ATTRIBUTE_SEED:
334         case TDB_ATTRIBUTE_TDB1_HASHSIZE:
335                 tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
336                            "tdb_unset_attribute: cannot unset %s after opening",
337                            type == TDB_ATTRIBUTE_HASH
338                            ? "TDB_ATTRIBUTE_HASH"
339                            : type == TDB_ATTRIBUTE_SEED
340                            ? "TDB_ATTRIBUTE_SEED"
341                            : "TDB_ATTRIBUTE_TDB1_HASHSIZE");
342                 break;
343         case TDB_ATTRIBUTE_STATS:
344                 tdb_logerr(tdb, TDB_ERR_EINVAL,
345                            TDB_LOG_USE_ERROR,
346                            "tdb_unset_attribute:"
347                            "cannot unset TDB_ATTRIBUTE_STATS");
348                 break;
349         case TDB_ATTRIBUTE_FLOCK:
350                 tdb->lock_fn = tdb_fcntl_lock;
351                 tdb->unlock_fn = tdb_fcntl_unlock;
352                 break;
353         default:
354                 tdb_logerr(tdb, TDB_ERR_EINVAL,
355                            TDB_LOG_USE_ERROR,
356                            "tdb_unset_attribute: unknown attribute type %u",
357                            type);
358         }
359 }
360
361 static bool is_tdb1(struct tdb1_header *hdr, const void *buf, ssize_t rlen)
362 {
363         /* This code assumes we've tried to read entire tdb1 header. */
364         BUILD_ASSERT(sizeof(*hdr) <= sizeof(struct tdb_header));
365
366         if (rlen < (ssize_t)sizeof(*hdr)) {
367                 return false;
368         }
369
370         memcpy(hdr, buf, sizeof(*hdr));
371         if (strcmp(hdr->magic_food, TDB_MAGIC_FOOD) != 0)
372                 return false;
373
374         return hdr->version == TDB1_VERSION
375                 || hdr->version == TDB1_BYTEREV(TDB1_VERSION);
376 }
377
378 struct tdb_context *tdb_open(const char *name, int tdb_flags,
379                              int open_flags, mode_t mode,
380                              union tdb_attribute *attr)
381 {
382         struct tdb_context *tdb;
383         struct stat st;
384         int saved_errno = 0;
385         uint64_t hash_test;
386         unsigned v;
387         ssize_t rlen;
388         struct tdb_header hdr;
389         struct tdb_attribute_seed *seed = NULL;
390         struct tdb_attribute_tdb1_hashsize *hsize_attr = NULL;
391         tdb_bool_err berr;
392         enum TDB_ERROR ecode;
393         int openlock;
394
395         tdb = malloc(sizeof(*tdb) + (name ? strlen(name) + 1 : 0));
396         if (!tdb) {
397                 /* Can't log this */
398                 errno = ENOMEM;
399                 return NULL;
400         }
401         /* Set name immediately for logging functions. */
402         if (name) {
403                 tdb->name = strcpy((char *)(tdb + 1), name);
404         } else {
405                 tdb->name = NULL;
406         }
407         tdb->flags = tdb_flags;
408         tdb->log_fn = NULL;
409         tdb->open_flags = open_flags;
410         tdb->last_error = TDB_SUCCESS;
411         tdb->file = NULL;
412         tdb->openhook = NULL;
413         tdb->lock_fn = tdb_fcntl_lock;
414         tdb->unlock_fn = tdb_fcntl_unlock;
415         tdb->hash_fn = tdb_jenkins_hash;
416         memset(&tdb->stats, 0, sizeof(tdb->stats));
417         tdb->stats.base.attr = TDB_ATTRIBUTE_STATS;
418         tdb->stats.size = sizeof(tdb->stats);
419
420         while (attr) {
421                 switch (attr->base.attr) {
422                 case TDB_ATTRIBUTE_HASH:
423                         tdb->hash_fn = attr->hash.fn;
424                         tdb->hash_data = attr->hash.data;
425                         break;
426                 case TDB_ATTRIBUTE_SEED:
427                         seed = &attr->seed;
428                         break;
429                 case TDB_ATTRIBUTE_OPENHOOK:
430                         tdb->openhook = attr->openhook.fn;
431                         tdb->openhook_data = attr->openhook.data;
432                         break;
433                 case TDB_ATTRIBUTE_TDB1_HASHSIZE:
434                         hsize_attr = &attr->tdb1_hashsize;
435                         break;
436                 default:
437                         /* These are set as normal. */
438                         ecode = tdb_set_attribute(tdb, attr);
439                         if (ecode != TDB_SUCCESS)
440                                 goto fail;
441                 }
442                 attr = attr->base.next;
443         }
444
445         if (tdb_flags & ~(TDB_INTERNAL | TDB_NOLOCK | TDB_NOMMAP | TDB_CONVERT
446                           | TDB_NOSYNC | TDB_SEQNUM | TDB_ALLOW_NESTING
447                           | TDB_RDONLY | TDB_VERSION1)) {
448                 ecode = tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
449                                    "tdb_open: unknown flags %u", tdb_flags);
450                 goto fail;
451         }
452
453         if (hsize_attr) {
454                 if (!(tdb_flags & TDB_VERSION1) ||
455                     (!(tdb_flags & TDB_INTERNAL) && !(open_flags & O_CREAT))) {
456                         ecode = tdb_logerr(tdb, TDB_ERR_EINVAL,
457                                            TDB_LOG_USE_ERROR,
458                                            "tdb_open: can only use"
459                                            " TDB_ATTRIBUTE_TDB1_HASHSIZE when"
460                                            " creating a TDB_VERSION1 tdb");
461                         goto fail;
462                 }
463         }
464
465         if (seed) {
466                 if (tdb_flags & TDB_VERSION1) {
467                         ecode = tdb_logerr(tdb, TDB_ERR_EINVAL,
468                                            TDB_LOG_USE_ERROR,
469                                            "tdb_open:"
470                                            " cannot set TDB_ATTRIBUTE_SEED"
471                                            " on TDB1 tdb.");
472                         goto fail;
473                 } else if (!(tdb_flags & TDB_INTERNAL)
474                            && !(open_flags & O_CREAT)) {
475                         ecode = tdb_logerr(tdb, TDB_ERR_EINVAL,
476                                            TDB_LOG_USE_ERROR,
477                                            "tdb_open:"
478                                            " cannot set TDB_ATTRIBUTE_SEED"
479                                            " without O_CREAT.");
480                         goto fail;
481                 }
482         }
483
484         if ((open_flags & O_ACCMODE) == O_WRONLY) {
485                 ecode = tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
486                                    "tdb_open: can't open tdb %s write-only",
487                                    name);
488                 goto fail;
489         }
490
491         if ((open_flags & O_ACCMODE) == O_RDONLY) {
492                 openlock = F_RDLCK;
493                 tdb->flags |= TDB_RDONLY;
494         } else {
495                 if (tdb_flags & TDB_RDONLY) {
496                         ecode = tdb_logerr(tdb, TDB_ERR_EINVAL,
497                                            TDB_LOG_USE_ERROR,
498                                            "tdb_open: can't use TDB_RDONLY"
499                                            " without O_RDONLY");
500                         goto fail;
501                 }
502                 openlock = F_WRLCK;
503         }
504
505         /* internal databases don't need any of the rest. */
506         if (tdb->flags & TDB_INTERNAL) {
507                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
508                 ecode = tdb_new_file(tdb);
509                 if (ecode != TDB_SUCCESS) {
510                         goto fail;
511                 }
512                 tdb->file->fd = -1;
513                 if (tdb->flags & TDB_VERSION1)
514                         ecode = tdb1_new_database(tdb, hsize_attr);
515                 else {
516                         ecode = tdb_new_database(tdb, seed, &hdr);
517                         if (ecode == TDB_SUCCESS) {
518                                 tdb_convert(tdb, &hdr.hash_seed,
519                                             sizeof(hdr.hash_seed));
520                                 tdb->hash_seed = hdr.hash_seed;
521                                 tdb2_context_init(tdb);
522                                 tdb_ftable_init(tdb);
523                         }
524                 }
525                 if (ecode != TDB_SUCCESS) {
526                         goto fail;
527                 }
528                 return tdb;
529         }
530
531         if (stat(name, &st) != -1)
532                 tdb->file = find_file(st.st_dev, st.st_ino);
533
534         if (!tdb->file) {
535                 int fd;
536
537                 if ((fd = open(name, open_flags, mode)) == -1) {
538                         /* errno set by open(2) */
539                         saved_errno = errno;
540                         tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
541                                    "tdb_open: could not open file %s: %s",
542                                    name, strerror(errno));
543                         goto fail_errno;
544                 }
545
546                 /* on exec, don't inherit the fd */
547                 v = fcntl(fd, F_GETFD, 0);
548                 fcntl(fd, F_SETFD, v | FD_CLOEXEC);
549
550                 if (fstat(fd, &st) == -1) {
551                         saved_errno = errno;
552                         tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
553                                    "tdb_open: could not stat open %s: %s",
554                                    name, strerror(errno));
555                         close(fd);
556                         goto fail_errno;
557                 }
558
559                 ecode = tdb_new_file(tdb);
560                 if (ecode != TDB_SUCCESS) {
561                         close(fd);
562                         goto fail;
563                 }
564
565                 tdb->file->fd = fd;
566                 tdb->file->device = st.st_dev;
567                 tdb->file->inode = st.st_ino;
568                 tdb->file->map_ptr = NULL;
569                 tdb->file->map_size = 0;
570         }
571
572         /* ensure there is only one process initialising at once */
573         ecode = tdb_lock_open(tdb, openlock, TDB_LOCK_WAIT|TDB_LOCK_NOCHECK);
574         if (ecode != TDB_SUCCESS) {
575                 saved_errno = errno;
576                 goto fail_errno;
577         }
578
579         /* call their open hook if they gave us one. */
580         if (tdb->openhook) {
581                 ecode = tdb->openhook(tdb->file->fd, tdb->openhook_data);
582                 if (ecode != TDB_SUCCESS) {
583                         tdb_logerr(tdb, ecode, TDB_LOG_ERROR,
584                                    "tdb_open: open hook failed");
585                         goto fail;
586                 }
587                 open_flags |= O_CREAT;
588         }
589
590         /* If they used O_TRUNC, read will return 0. */
591         rlen = pread(tdb->file->fd, &hdr, sizeof(hdr), 0);
592         if (rlen == 0 && (open_flags & O_CREAT)) {
593                 if (tdb->flags & TDB_VERSION1) {
594                         ecode = tdb1_new_database(tdb, hsize_attr);
595                         if (ecode != TDB_SUCCESS)
596                                 goto fail;
597                         goto finished;
598                 }
599                 ecode = tdb_new_database(tdb, seed, &hdr);
600                 if (ecode != TDB_SUCCESS) {
601                         goto fail;
602                 }
603         } else if (rlen < 0) {
604                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
605                                    "tdb_open: error %s reading %s",
606                                    strerror(errno), name);
607                 goto fail;
608         } else if (rlen < sizeof(hdr)
609                    || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
610                 if (is_tdb1(&tdb->tdb1.header, &hdr, rlen)) {
611                         ecode = tdb1_open(tdb);
612                         if (!ecode)
613                                 goto finished;
614                         goto fail;
615                 }
616                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
617                                    "tdb_open: %s is not a tdb file", name);
618                 goto fail;
619         }
620
621         if (hdr.version != TDB_VERSION) {
622                 if (hdr.version == bswap_64(TDB_VERSION))
623                         tdb->flags |= TDB_CONVERT;
624                 else {
625                         if (is_tdb1(&tdb->tdb1.header, &hdr, rlen)) {
626                                 ecode = tdb1_open(tdb);
627                                 if (!ecode)
628                                         goto finished;
629                                 goto fail;
630                         }
631                         /* wrong version */
632                         ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
633                                            "tdb_open:"
634                                            " %s is unknown version 0x%llx",
635                                            name, (long long)hdr.version);
636                         goto fail;
637                 }
638         } else if (tdb->flags & TDB_CONVERT) {
639                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
640                                    "tdb_open:"
641                                    " %s does not need TDB_CONVERT",
642                                    name);
643                 goto fail;
644         }
645
646         if (tdb->flags & TDB_VERSION1) {
647                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
648                                    "tdb_open:"
649                                    " %s does not need TDB_VERSION1",
650                                    name);
651                 goto fail;
652         }
653
654         tdb2_context_init(tdb);
655
656         tdb_convert(tdb, &hdr, sizeof(hdr));
657         tdb->hash_seed = hdr.hash_seed;
658         hash_test = TDB_HASH_MAGIC;
659         hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
660         if (hdr.hash_test != hash_test) {
661                 /* wrong hash variant */
662                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
663                                    "tdb_open:"
664                                    " %s uses a different hash function",
665                                    name);
666                 goto fail;
667         }
668
669         /* Clear any features we don't understand. */
670         if ((open_flags & O_ACCMODE) != O_RDONLY) {
671                 hdr.features_used &= TDB_FEATURE_MASK;
672                 ecode = tdb_write_convert(tdb, offsetof(struct tdb_header,
673                                                         features_used),
674                                           &hdr.features_used,
675                                           sizeof(hdr.features_used));
676                 if (ecode != TDB_SUCCESS)
677                         goto fail;
678         }
679
680 finished:
681         if (tdb->flags & TDB_VERSION1) {
682                 /* if needed, run recovery */
683                 if (tdb1_transaction_recover(tdb) == -1) {
684                         ecode = tdb->last_error;
685                         goto fail;
686                 }
687         }
688
689         tdb_unlock_open(tdb, openlock);
690
691         /* This makes sure we have current map_size and mmap. */
692         if (tdb->flags & TDB_VERSION1) {
693                 ecode = tdb1_probe_length(tdb);
694         } else {
695                 ecode = tdb->tdb2.io->oob(tdb, tdb->file->map_size + 1, true);
696         }
697         if (unlikely(ecode != TDB_SUCCESS))
698                 goto fail;
699
700         if (!(tdb->flags & TDB_VERSION1)) {
701                 /* Now it's fully formed, recover if necessary. */
702                 berr = tdb_needs_recovery(tdb);
703                 if (unlikely(berr != false)) {
704                         if (berr < 0) {
705                                 ecode = berr;
706                                 goto fail;
707                         }
708                         ecode = tdb_lock_and_recover(tdb);
709                         if (ecode != TDB_SUCCESS) {
710                                 goto fail;
711                         }
712                 }
713
714                 ecode = tdb_ftable_init(tdb);
715                 if (ecode != TDB_SUCCESS) {
716                         goto fail;
717                 }
718         }
719
720         tdb->next = tdbs;
721         tdbs = tdb;
722         return tdb;
723
724  fail:
725         /* Map ecode to some logical errno. */
726         switch (ecode) {
727         case TDB_ERR_CORRUPT:
728         case TDB_ERR_IO:
729                 saved_errno = EIO;
730                 break;
731         case TDB_ERR_LOCK:
732                 saved_errno = EWOULDBLOCK;
733                 break;
734         case TDB_ERR_OOM:
735                 saved_errno = ENOMEM;
736                 break;
737         case TDB_ERR_EINVAL:
738                 saved_errno = EINVAL;
739                 break;
740         default:
741                 saved_errno = EINVAL;
742                 break;
743         }
744
745 fail_errno:
746 #ifdef TDB_TRACE
747         close(tdb->tracefd);
748 #endif
749         if (tdb->file) {
750                 tdb_lock_cleanup(tdb);
751                 if (--tdb->file->refcnt == 0) {
752                         assert(tdb->file->num_lockrecs == 0);
753                         if (tdb->file->map_ptr) {
754                                 if (tdb->flags & TDB_INTERNAL) {
755                                         free(tdb->file->map_ptr);
756                                 } else
757                                         tdb_munmap(tdb->file);
758                         }
759                         if (close(tdb->file->fd) != 0)
760                                 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
761                                            "tdb_open: failed to close tdb fd"
762                                            " on error: %s", strerror(errno));
763                         free(tdb->file->lockrecs);
764                         free(tdb->file);
765                 }
766         }
767
768         free(tdb);
769         errno = saved_errno;
770         return NULL;
771 }
772
773 int tdb_close(struct tdb_context *tdb)
774 {
775         int ret = 0;
776         struct tdb_context **i;
777
778         tdb_trace(tdb, "tdb_close");
779
780         if (tdb->flags & TDB_VERSION1) {
781                 if (tdb->tdb1.transaction) {
782                         tdb1_transaction_cancel(tdb);
783                 }
784         } else {
785                 if (tdb->tdb2.transaction) {
786                         tdb_transaction_cancel(tdb);
787                 }
788         }
789
790         if (tdb->file->map_ptr) {
791                 if (tdb->flags & TDB_INTERNAL)
792                         free(tdb->file->map_ptr);
793                 else
794                         tdb_munmap(tdb->file);
795         }
796         if (tdb->file) {
797                 tdb_lock_cleanup(tdb);
798                 if (--tdb->file->refcnt == 0) {
799                         ret = close(tdb->file->fd);
800                         free(tdb->file->lockrecs);
801                         free(tdb->file);
802                 }
803         }
804
805         /* Remove from tdbs list */
806         for (i = &tdbs; *i; i = &(*i)->next) {
807                 if (*i == tdb) {
808                         *i = tdb->next;
809                         break;
810                 }
811         }
812
813 #ifdef TDB_TRACE
814         close(tdb->tracefd);
815 #endif
816         free(tdb);
817
818         return ret;
819 }
820
821 void tdb_foreach_(int (*fn)(struct tdb_context *, void *), void *p)
822 {
823         struct tdb_context *i;
824
825         for (i = tdbs; i; i = i->next) {
826                 if (fn(i, p) != 0)
827                         break;
828         }
829 }