tdb2: TDB_SEQNUM and tdb_get_seqnum support.
[ccan] / ccan / tdb2 / open.c
1 #include "private.h"
2 #include <assert.h>
3
4 /* all lock info, to detect double-opens (fcntl file don't nest!) */
5 static struct tdb_file *files = NULL;
6
7 static struct tdb_file *find_file(dev_t device, ino_t ino)
8 {
9         struct tdb_file *i;
10
11         for (i = files; i; i = i->next) {
12                 if (i->device == device && i->inode == ino) {
13                         i->refcnt++;
14                         break;
15                 }
16         }
17         return i;
18 }
19
20 static bool read_all(int fd, void *buf, size_t len)
21 {
22         while (len) {
23                 ssize_t ret;
24                 ret = read(fd, buf, len);
25                 if (ret < 0)
26                         return false;
27                 if (ret == 0) {
28                         /* ETOOSHORT? */
29                         errno = EWOULDBLOCK;
30                         return false;
31                 }
32                 buf = (char *)buf + ret;
33                 len -= ret;
34         }
35         return true;
36 }
37
38 static uint64_t random_number(struct tdb_context *tdb)
39 {
40         int fd;
41         uint64_t ret = 0;
42         struct timeval now;
43
44         fd = open("/dev/urandom", O_RDONLY);
45         if (fd >= 0) {
46                 if (read_all(fd, &ret, sizeof(ret))) {
47                         close(fd);
48                         return ret;
49                 }
50                 close(fd);
51         }
52         /* FIXME: Untested!  Based on Wikipedia protocol description! */
53         fd = open("/dev/egd-pool", O_RDWR);
54         if (fd >= 0) {
55                 /* Command is 1, next byte is size we want to read. */
56                 char cmd[2] = { 1, sizeof(uint64_t) };
57                 if (write(fd, cmd, sizeof(cmd)) == sizeof(cmd)) {
58                         char reply[1 + sizeof(uint64_t)];
59                         int r = read(fd, reply, sizeof(reply));
60                         if (r > 1) {
61                                 /* Copy at least some bytes. */
62                                 memcpy(&ret, reply+1, r - 1);
63                                 if (reply[0] == sizeof(uint64_t)
64                                     && r == sizeof(reply)) {
65                                         close(fd);
66                                         return ret;
67                                 }
68                         }
69                 }
70                 close(fd);
71         }
72
73         /* Fallback: pid and time. */
74         gettimeofday(&now, NULL);
75         ret = getpid() * 100132289ULL + now.tv_sec * 1000000ULL + now.tv_usec;
76         tdb_logerr(tdb, TDB_SUCCESS, TDB_LOG_WARNING,
77                    "tdb_open: random from getpid and time");
78         return ret;
79 }
80
81 struct new_database {
82         struct tdb_header hdr;
83         struct tdb_freetable ftable;
84 };
85
86 /* initialise a new database */
87 static enum TDB_ERROR tdb_new_database(struct tdb_context *tdb,
88                                        struct tdb_attribute_seed *seed,
89                                        struct tdb_header *hdr)
90 {
91         /* We make it up in memory, then write it out if not internal */
92         struct new_database newdb;
93         unsigned int magic_len;
94         ssize_t rlen;
95         enum TDB_ERROR ecode;
96
97         /* Fill in the header */
98         newdb.hdr.version = TDB_VERSION;
99         if (seed)
100                 newdb.hdr.hash_seed = seed->seed;
101         else
102                 newdb.hdr.hash_seed = random_number(tdb);
103         newdb.hdr.hash_test = TDB_HASH_MAGIC;
104         newdb.hdr.hash_test = tdb->khash(&newdb.hdr.hash_test,
105                                          sizeof(newdb.hdr.hash_test),
106                                          newdb.hdr.hash_seed,
107                                          tdb->hash_priv);
108         newdb.hdr.recovery = 0;
109         newdb.hdr.features_used = newdb.hdr.features_offered = TDB_FEATURE_MASK;
110         newdb.hdr.seqnum = 0;
111         memset(newdb.hdr.reserved, 0, sizeof(newdb.hdr.reserved));
112         /* Initial hashes are empty. */
113         memset(newdb.hdr.hashtable, 0, sizeof(newdb.hdr.hashtable));
114
115         /* Free is empty. */
116         newdb.hdr.free_table = offsetof(struct new_database, ftable);
117         memset(&newdb.ftable, 0, sizeof(newdb.ftable));
118         ecode = set_header(NULL, &newdb.ftable.hdr, TDB_FTABLE_MAGIC, 0,
119                            sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr),
120                            sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr),
121                            0);
122         if (ecode != TDB_SUCCESS) {
123                 return ecode;
124         }
125
126         /* Magic food */
127         memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
128         strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
129
130         /* This creates an endian-converted database, as if read from disk */
131         magic_len = sizeof(newdb.hdr.magic_food);
132         tdb_convert(tdb,
133                     (char *)&newdb.hdr + magic_len, sizeof(newdb) - magic_len);
134
135         *hdr = newdb.hdr;
136
137         if (tdb->flags & TDB_INTERNAL) {
138                 tdb->file->map_size = sizeof(newdb);
139                 tdb->file->map_ptr = malloc(tdb->file->map_size);
140                 if (!tdb->file->map_ptr) {
141                         return tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
142                                           "tdb_new_database:"
143                                           " failed to allocate");
144                 }
145                 memcpy(tdb->file->map_ptr, &newdb, tdb->file->map_size);
146                 return TDB_SUCCESS;
147         }
148         if (lseek(tdb->file->fd, 0, SEEK_SET) == -1) {
149                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
150                                   "tdb_new_database:"
151                                   " failed to seek: %s", strerror(errno));
152         }
153
154         if (ftruncate(tdb->file->fd, 0) == -1) {
155                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
156                                   "tdb_new_database:"
157                                   " failed to truncate: %s", strerror(errno));
158         }
159
160         rlen = write(tdb->file->fd, &newdb, sizeof(newdb));
161         if (rlen != sizeof(newdb)) {
162                 if (rlen >= 0)
163                         errno = ENOSPC;
164                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
165                                   "tdb_new_database: %zi writing header: %s",
166                                   rlen, strerror(errno));
167         }
168         return TDB_SUCCESS;
169 }
170
171 static enum TDB_ERROR tdb_new_file(struct tdb_context *tdb)
172 {
173         tdb->file = malloc(sizeof(*tdb->file));
174         if (!tdb->file)
175                 return tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
176                                   "tdb_open: could alloc tdb_file structure");
177         tdb->file->num_lockrecs = 0;
178         tdb->file->lockrecs = NULL;
179         tdb->file->allrecord_lock.count = 0;
180         tdb->file->refcnt = 1;
181         return TDB_SUCCESS;
182 }
183
184 struct tdb_context *tdb_open(const char *name, int tdb_flags,
185                              int open_flags, mode_t mode,
186                              union tdb_attribute *attr)
187 {
188         struct tdb_context *tdb;
189         struct stat st;
190         int saved_errno = 0;
191         uint64_t hash_test;
192         unsigned v;
193         ssize_t rlen;
194         struct tdb_header hdr;
195         struct tdb_attribute_seed *seed = NULL;
196         tdb_bool_err berr;
197         enum TDB_ERROR ecode;
198
199         tdb = malloc(sizeof(*tdb));
200         if (!tdb) {
201                 /* Can't log this */
202                 errno = ENOMEM;
203                 return NULL;
204         }
205         tdb->name = NULL;
206         tdb->direct_access = 0;
207         tdb->flags = tdb_flags;
208         tdb->logfn = NULL;
209         tdb->transaction = NULL;
210         tdb->stats = NULL;
211         tdb->access = NULL;
212         tdb->file = NULL;
213         tdb_hash_init(tdb);
214         tdb_io_init(tdb);
215
216         while (attr) {
217                 switch (attr->base.attr) {
218                 case TDB_ATTRIBUTE_LOG:
219                         tdb->logfn = attr->log.log_fn;
220                         tdb->log_private = attr->log.log_private;
221                         break;
222                 case TDB_ATTRIBUTE_HASH:
223                         tdb->khash = attr->hash.hash_fn;
224                         tdb->hash_priv = attr->hash.hash_private;
225                         break;
226                 case TDB_ATTRIBUTE_SEED:
227                         seed = &attr->seed;
228                         break;
229                 case TDB_ATTRIBUTE_STATS:
230                         tdb->stats = &attr->stats;
231                         /* They have stats we don't know about?  Tell them. */
232                         if (tdb->stats->size > sizeof(attr->stats))
233                                 tdb->stats->size = sizeof(attr->stats);
234                         break;
235                 default:
236                         ecode = tdb_logerr(tdb, TDB_ERR_EINVAL,
237                                            TDB_LOG_USE_ERROR,
238                                            "tdb_open:"
239                                            " unknown attribute type %u",
240                                            attr->base.attr);
241                         goto fail;
242                 }
243                 attr = attr->base.next;
244         }
245
246         if (tdb_flags & ~(TDB_INTERNAL | TDB_NOLOCK | TDB_NOMMAP | TDB_CONVERT
247                           | TDB_NOSYNC | TDB_SEQNUM)) {
248                 ecode = tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
249                                    "tdb_open: unknown flags %u", tdb_flags);
250                 goto fail;
251         }
252
253         if ((open_flags & O_ACCMODE) == O_WRONLY) {
254                 ecode = tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
255                                    "tdb_open: can't open tdb %s write-only",
256                                    name);
257                 goto fail;
258         }
259
260         if ((open_flags & O_ACCMODE) == O_RDONLY) {
261                 tdb->read_only = true;
262                 tdb->mmap_flags = PROT_READ;
263         } else {
264                 tdb->read_only = false;
265                 tdb->mmap_flags = PROT_READ | PROT_WRITE;
266         }
267
268         /* internal databases don't need any of the rest. */
269         if (tdb->flags & TDB_INTERNAL) {
270                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
271                 ecode = tdb_new_file(tdb);
272                 if (ecode != TDB_SUCCESS) {
273                         goto fail;
274                 }
275                 tdb->file->fd = -1;
276                 ecode = tdb_new_database(tdb, seed, &hdr);
277                 if (ecode != TDB_SUCCESS) {
278                         goto fail;
279                 }
280                 if (name) {
281                         tdb->name = strdup(name);
282                         if (!tdb->name) {
283                                 ecode = tdb_logerr(tdb, TDB_ERR_OOM,
284                                                    TDB_LOG_ERROR,
285                                                    "tdb_open: failed to"
286                                                    " allocate name");
287                                 goto fail;
288                         }
289                 }
290                 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
291                 tdb->hash_seed = hdr.hash_seed;
292                 tdb_ftable_init(tdb);
293                 return tdb;
294         }
295
296         if (stat(name, &st) != -1)
297                 tdb->file = find_file(st.st_dev, st.st_ino);
298
299         if (!tdb->file) {
300                 int fd;
301
302                 if ((fd = open(name, open_flags, mode)) == -1) {
303                         /* errno set by open(2) */
304                         saved_errno = errno;
305                         tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
306                                    "tdb_open: could not open file %s: %s",
307                                    name, strerror(errno));
308                         goto fail_errno;
309                 }
310
311                 /* on exec, don't inherit the fd */
312                 v = fcntl(fd, F_GETFD, 0);
313                 fcntl(fd, F_SETFD, v | FD_CLOEXEC);
314
315                 if (fstat(fd, &st) == -1) {
316                         saved_errno = errno;
317                         tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
318                                    "tdb_open: could not stat open %s: %s",
319                                    name, strerror(errno));
320                         goto fail_errno;
321                 }
322
323                 ecode = tdb_new_file(tdb);
324                 if (ecode != TDB_SUCCESS)
325                         goto fail;
326
327                 tdb->file->next = files;
328                 tdb->file->fd = fd;
329                 tdb->file->device = st.st_dev;
330                 tdb->file->inode = st.st_ino;
331                 tdb->file->map_ptr = NULL;
332                 tdb->file->map_size = sizeof(struct tdb_header);
333         }
334
335         /* ensure there is only one process initialising at once */
336         ecode = tdb_lock_open(tdb, TDB_LOCK_WAIT|TDB_LOCK_NOCHECK);
337         if (ecode != TDB_SUCCESS) {
338                 goto fail;
339         }
340
341         /* If they used O_TRUNC, read will return 0. */
342         rlen = pread(tdb->file->fd, &hdr, sizeof(hdr), 0);
343         if (rlen == 0 && (open_flags & O_CREAT)) {
344                 ecode = tdb_new_database(tdb, seed, &hdr);
345                 if (ecode != TDB_SUCCESS) {
346                         goto fail;
347                 }
348         } else if (rlen < 0) {
349                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
350                                    "tdb_open: error %s reading %s",
351                                    strerror(errno), name);
352                 goto fail;
353         } else if (rlen < sizeof(hdr)
354                    || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
355                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
356                                    "tdb_open: %s is not a tdb file", name);
357                 goto fail;
358         }
359
360         if (hdr.version != TDB_VERSION) {
361                 if (hdr.version == bswap_64(TDB_VERSION))
362                         tdb->flags |= TDB_CONVERT;
363                 else {
364                         /* wrong version */
365                         ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
366                                            "tdb_open:"
367                                            " %s is unknown version 0x%llx",
368                                            name, (long long)hdr.version);
369                         goto fail;
370                 }
371         }
372
373         tdb_convert(tdb, &hdr, sizeof(hdr));
374         tdb->hash_seed = hdr.hash_seed;
375         hash_test = TDB_HASH_MAGIC;
376         hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
377         if (hdr.hash_test != hash_test) {
378                 /* wrong hash variant */
379                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
380                                    "tdb_open:"
381                                    " %s uses a different hash function",
382                                    name);
383                 goto fail;
384         }
385
386         tdb->name = strdup(name);
387         if (!tdb->name) {
388                 ecode = tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
389                                    "tdb_open: failed to allocate name");
390                 goto fail;
391         }
392
393         /* Clear any features we don't understand. */
394         if ((open_flags & O_ACCMODE) != O_RDONLY) {
395                 hdr.features_used &= TDB_FEATURE_MASK;
396                 if (tdb_write_convert(tdb, offsetof(struct tdb_header,
397                                                     features_used),
398                                       &hdr.features_used,
399                                       sizeof(hdr.features_used)) == -1)
400                         goto fail;
401         }
402
403         tdb_unlock_open(tdb);
404
405         /* This make sure we have current map_size and mmap. */
406         tdb->methods->oob(tdb, tdb->file->map_size + 1, true);
407
408         /* Now it's fully formed, recover if necessary. */
409         berr = tdb_needs_recovery(tdb);
410         if (unlikely(berr != false)) {
411                 if (berr < 0) {
412                         ecode = berr;
413                         goto fail;
414                 }
415                 ecode = tdb_lock_and_recover(tdb);
416                 if (ecode != TDB_SUCCESS) {
417                         goto fail;
418                 }
419         }
420
421         ecode = tdb_ftable_init(tdb);
422         if (ecode != TDB_SUCCESS) {
423                 goto fail;
424         }
425
426         /* Add to linked list if we're new. */
427         if (tdb->file->refcnt == 1)
428                 files = tdb->file;
429         return tdb;
430
431  fail:
432         /* Map ecode to some logical errno. */
433         switch (ecode) {
434         case TDB_ERR_CORRUPT:
435         case TDB_ERR_IO:
436                 saved_errno = EIO;
437                 break;
438         case TDB_ERR_LOCK:
439                 saved_errno = EWOULDBLOCK;
440                 break;
441         case TDB_ERR_OOM:
442                 saved_errno = ENOMEM;
443                 break;
444         case TDB_ERR_EINVAL:
445                 saved_errno = EINVAL;
446                 break;
447         default:
448                 saved_errno = EINVAL;
449                 break;
450         }
451
452 fail_errno:
453 #ifdef TDB_TRACE
454         close(tdb->tracefd);
455 #endif
456         free((char *)tdb->name);
457         if (tdb->file) {
458                 tdb_unlock_all(tdb);
459                 if (--tdb->file->refcnt == 0) {
460                         assert(tdb->file->num_lockrecs == 0);
461                         if (tdb->file->map_ptr) {
462                                 if (tdb->flags & TDB_INTERNAL) {
463                                         free(tdb->file->map_ptr);
464                                 } else
465                                         tdb_munmap(tdb->file);
466                         }
467                         if (close(tdb->file->fd) != 0)
468                                 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
469                                            "tdb_open: failed to close tdb fd"
470                                            " on error: %s", strerror(errno));
471                         free(tdb->file->lockrecs);
472                         free(tdb->file);
473                 }
474         }
475
476         free(tdb);
477         errno = saved_errno;
478         return NULL;
479 }
480
481 int tdb_close(struct tdb_context *tdb)
482 {
483         int ret = 0;
484
485         tdb_trace(tdb, "tdb_close");
486
487         if (tdb->transaction) {
488                 tdb_transaction_cancel(tdb);
489         }
490
491         if (tdb->file->map_ptr) {
492                 if (tdb->flags & TDB_INTERNAL)
493                         free(tdb->file->map_ptr);
494                 else
495                         tdb_munmap(tdb->file);
496         }
497         free((char *)tdb->name);
498         if (tdb->file) {
499                 struct tdb_file **i;
500
501                 tdb_unlock_all(tdb);
502                 if (--tdb->file->refcnt == 0) {
503                         ret = close(tdb->file->fd);
504
505                         /* Remove from files list */
506                         for (i = &files; *i; i = &(*i)->next) {
507                                 if (*i == tdb->file) {
508                                         *i = tdb->file->next;
509                                         break;
510                                 }
511                         }
512                         free(tdb->file->lockrecs);
513                         free(tdb->file);
514                 }
515         }
516
517 #ifdef TDB_TRACE
518         close(tdb->tracefd);
519 #endif
520         free(tdb);
521
522         return ret;
523 }