tdb2: allow multiple opens of the same file.
[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         memset(newdb.hdr.reserved, 0, sizeof(newdb.hdr.reserved));
111         /* Initial hashes are empty. */
112         memset(newdb.hdr.hashtable, 0, sizeof(newdb.hdr.hashtable));
113
114         /* Free is empty. */
115         newdb.hdr.free_table = offsetof(struct new_database, ftable);
116         memset(&newdb.ftable, 0, sizeof(newdb.ftable));
117         ecode = set_header(NULL, &newdb.ftable.hdr, TDB_FTABLE_MAGIC, 0,
118                            sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr),
119                            sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr),
120                            0);
121         if (ecode != TDB_SUCCESS) {
122                 return ecode;
123         }
124
125         /* Magic food */
126         memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
127         strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
128
129         /* This creates an endian-converted database, as if read from disk */
130         magic_len = sizeof(newdb.hdr.magic_food);
131         tdb_convert(tdb,
132                     (char *)&newdb.hdr + magic_len, sizeof(newdb) - magic_len);
133
134         *hdr = newdb.hdr;
135
136         if (tdb->flags & TDB_INTERNAL) {
137                 tdb->file->map_size = sizeof(newdb);
138                 tdb->file->map_ptr = malloc(tdb->file->map_size);
139                 if (!tdb->file->map_ptr) {
140                         return tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
141                                           "tdb_new_database:"
142                                           " failed to allocate");
143                 }
144                 memcpy(tdb->file->map_ptr, &newdb, tdb->file->map_size);
145                 return TDB_SUCCESS;
146         }
147         if (lseek(tdb->file->fd, 0, SEEK_SET) == -1) {
148                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
149                                   "tdb_new_database:"
150                                   " failed to seek: %s", strerror(errno));
151         }
152
153         if (ftruncate(tdb->file->fd, 0) == -1) {
154                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
155                                   "tdb_new_database:"
156                                   " failed to truncate: %s", strerror(errno));
157         }
158
159         rlen = write(tdb->file->fd, &newdb, sizeof(newdb));
160         if (rlen != sizeof(newdb)) {
161                 if (rlen >= 0)
162                         errno = ENOSPC;
163                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
164                                   "tdb_new_database: %zi writing header: %s",
165                                   rlen, strerror(errno));
166         }
167         return TDB_SUCCESS;
168 }
169
170 static enum TDB_ERROR tdb_new_file(struct tdb_context *tdb)
171 {
172         tdb->file = malloc(sizeof(*tdb->file));
173         if (!tdb->file)
174                 return tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
175                                   "tdb_open: could alloc tdb_file structure");
176         tdb->file->num_lockrecs = 0;
177         tdb->file->lockrecs = NULL;
178         tdb->file->allrecord_lock.count = 0;
179         tdb->file->refcnt = 1;
180         return TDB_SUCCESS;
181 }
182
183 struct tdb_context *tdb_open(const char *name, int tdb_flags,
184                              int open_flags, mode_t mode,
185                              union tdb_attribute *attr)
186 {
187         struct tdb_context *tdb;
188         struct stat st;
189         int saved_errno = 0;
190         uint64_t hash_test;
191         unsigned v;
192         ssize_t rlen;
193         struct tdb_header hdr;
194         struct tdb_attribute_seed *seed = NULL;
195         tdb_bool_err berr;
196         enum TDB_ERROR ecode;
197
198         tdb = malloc(sizeof(*tdb));
199         if (!tdb) {
200                 /* Can't log this */
201                 errno = ENOMEM;
202                 return NULL;
203         }
204         tdb->name = NULL;
205         tdb->direct_access = 0;
206         tdb->flags = tdb_flags;
207         tdb->logfn = NULL;
208         tdb->transaction = NULL;
209         tdb->stats = NULL;
210         tdb->access = NULL;
211         tdb->file = NULL;
212         tdb_hash_init(tdb);
213         tdb_io_init(tdb);
214
215         while (attr) {
216                 switch (attr->base.attr) {
217                 case TDB_ATTRIBUTE_LOG:
218                         tdb->logfn = attr->log.log_fn;
219                         tdb->log_private = attr->log.log_private;
220                         break;
221                 case TDB_ATTRIBUTE_HASH:
222                         tdb->khash = attr->hash.hash_fn;
223                         tdb->hash_priv = attr->hash.hash_private;
224                         break;
225                 case TDB_ATTRIBUTE_SEED:
226                         seed = &attr->seed;
227                         break;
228                 case TDB_ATTRIBUTE_STATS:
229                         tdb->stats = &attr->stats;
230                         /* They have stats we don't know about?  Tell them. */
231                         if (tdb->stats->size > sizeof(attr->stats))
232                                 tdb->stats->size = sizeof(attr->stats);
233                         break;
234                 default:
235                         ecode = tdb_logerr(tdb, TDB_ERR_EINVAL,
236                                            TDB_LOG_USE_ERROR,
237                                            "tdb_open:"
238                                            " unknown attribute type %u",
239                                            attr->base.attr);
240                         goto fail;
241                 }
242                 attr = attr->base.next;
243         }
244
245         if (tdb_flags & ~(TDB_INTERNAL | TDB_NOLOCK | TDB_NOMMAP | TDB_CONVERT
246                           | TDB_NOSYNC)) {
247                 ecode = tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
248                                    "tdb_open: unknown flags %u", tdb_flags);
249                 goto fail;
250         }
251
252         if ((open_flags & O_ACCMODE) == O_WRONLY) {
253                 ecode = tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
254                                    "tdb_open: can't open tdb %s write-only",
255                                    name);
256                 goto fail;
257         }
258
259         if ((open_flags & O_ACCMODE) == O_RDONLY) {
260                 tdb->read_only = true;
261                 tdb->mmap_flags = PROT_READ;
262         } else {
263                 tdb->read_only = false;
264                 tdb->mmap_flags = PROT_READ | PROT_WRITE;
265         }
266
267         /* internal databases don't need any of the rest. */
268         if (tdb->flags & TDB_INTERNAL) {
269                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
270                 ecode = tdb_new_file(tdb);
271                 if (ecode != TDB_SUCCESS) {
272                         goto fail;
273                 }
274                 tdb->file->fd = -1;
275                 ecode = tdb_new_database(tdb, seed, &hdr);
276                 if (ecode != TDB_SUCCESS) {
277                         goto fail;
278                 }
279                 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
280                 tdb->hash_seed = hdr.hash_seed;
281                 tdb_ftable_init(tdb);
282                 return tdb;
283         }
284
285         if (stat(name, &st) != -1)
286                 tdb->file = find_file(st.st_dev, st.st_ino);
287
288         if (!tdb->file) {
289                 int fd;
290
291                 if ((fd = open(name, open_flags, mode)) == -1) {
292                         /* errno set by open(2) */
293                         saved_errno = errno;
294                         tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
295                                    "tdb_open: could not open file %s: %s",
296                                    name, strerror(errno));
297                         goto fail_errno;
298                 }
299
300                 /* on exec, don't inherit the fd */
301                 v = fcntl(fd, F_GETFD, 0);
302                 fcntl(fd, F_SETFD, v | FD_CLOEXEC);
303
304                 if (fstat(fd, &st) == -1) {
305                         saved_errno = errno;
306                         tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
307                                    "tdb_open: could not stat open %s: %s",
308                                    name, strerror(errno));
309                         goto fail_errno;
310                 }
311
312                 ecode = tdb_new_file(tdb);
313                 if (ecode != TDB_SUCCESS)
314                         goto fail;
315
316                 tdb->file->next = files;
317                 tdb->file->fd = fd;
318                 tdb->file->device = st.st_dev;
319                 tdb->file->inode = st.st_ino;
320                 tdb->file->map_ptr = NULL;
321                 tdb->file->map_size = sizeof(struct tdb_header);
322         }
323
324         /* ensure there is only one process initialising at once */
325         ecode = tdb_lock_open(tdb, TDB_LOCK_WAIT|TDB_LOCK_NOCHECK);
326         if (ecode != TDB_SUCCESS) {
327                 goto fail;
328         }
329
330         /* If they used O_TRUNC, read will return 0. */
331         rlen = pread(tdb->file->fd, &hdr, sizeof(hdr), 0);
332         if (rlen == 0 && (open_flags & O_CREAT)) {
333                 ecode = tdb_new_database(tdb, seed, &hdr);
334                 if (ecode != TDB_SUCCESS) {
335                         goto fail;
336                 }
337         } else if (rlen < 0) {
338                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
339                                    "tdb_open: error %s reading %s",
340                                    strerror(errno), name);
341                 goto fail;
342         } else if (rlen < sizeof(hdr)
343                    || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
344                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
345                                    "tdb_open: %s is not a tdb file", name);
346                 goto fail;
347         }
348
349         if (hdr.version != TDB_VERSION) {
350                 if (hdr.version == bswap_64(TDB_VERSION))
351                         tdb->flags |= TDB_CONVERT;
352                 else {
353                         /* wrong version */
354                         ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
355                                            "tdb_open:"
356                                            " %s is unknown version 0x%llx",
357                                            name, (long long)hdr.version);
358                         goto fail;
359                 }
360         }
361
362         tdb_convert(tdb, &hdr, sizeof(hdr));
363         tdb->hash_seed = hdr.hash_seed;
364         hash_test = TDB_HASH_MAGIC;
365         hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
366         if (hdr.hash_test != hash_test) {
367                 /* wrong hash variant */
368                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
369                                    "tdb_open:"
370                                    " %s uses a different hash function",
371                                    name);
372                 goto fail;
373         }
374
375         tdb->name = strdup(name);
376         if (!tdb->name) {
377                 ecode = tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
378                                    "tdb_open: failed to allocate name");
379                 goto fail;
380         }
381
382         /* Clear any features we don't understand. */
383         if ((open_flags & O_ACCMODE) != O_RDONLY) {
384                 hdr.features_used &= TDB_FEATURE_MASK;
385                 if (tdb_write_convert(tdb, offsetof(struct tdb_header,
386                                                     features_used),
387                                       &hdr.features_used,
388                                       sizeof(hdr.features_used)) == -1)
389                         goto fail;
390         }
391
392         tdb_unlock_open(tdb);
393
394         /* This make sure we have current map_size and mmap. */
395         tdb->methods->oob(tdb, tdb->file->map_size + 1, true);
396
397         /* Now it's fully formed, recover if necessary. */
398         berr = tdb_needs_recovery(tdb);
399         if (unlikely(berr != false)) {
400                 if (berr < 0) {
401                         ecode = berr;
402                         goto fail;
403                 }
404                 ecode = tdb_lock_and_recover(tdb);
405                 if (ecode != TDB_SUCCESS) {
406                         goto fail;
407                 }
408         }
409
410         ecode = tdb_ftable_init(tdb);
411         if (ecode != TDB_SUCCESS) {
412                 goto fail;
413         }
414
415         /* Add to linked list if we're new. */
416         if (tdb->file->refcnt == 1)
417                 files = tdb->file;
418         return tdb;
419
420  fail:
421         /* Map ecode to some logical errno. */
422         switch (ecode) {
423         case TDB_ERR_CORRUPT:
424         case TDB_ERR_IO:
425                 saved_errno = EIO;
426                 break;
427         case TDB_ERR_LOCK:
428                 saved_errno = EWOULDBLOCK;
429                 break;
430         case TDB_ERR_OOM:
431                 saved_errno = ENOMEM;
432                 break;
433         case TDB_ERR_EINVAL:
434                 saved_errno = EINVAL;
435                 break;
436         default:
437                 saved_errno = EINVAL;
438                 break;
439         }
440
441 fail_errno:
442 #ifdef TDB_TRACE
443         close(tdb->tracefd);
444 #endif
445         free((char *)tdb->name);
446         if (tdb->file) {
447                 tdb_unlock_all(tdb);
448                 if (--tdb->file->refcnt == 0) {
449                         assert(tdb->file->num_lockrecs == 0);
450                         if (tdb->file->map_ptr) {
451                                 if (tdb->flags & TDB_INTERNAL) {
452                                         free(tdb->file->map_ptr);
453                                 } else
454                                         tdb_munmap(tdb->file);
455                         }
456                         if (close(tdb->file->fd) != 0)
457                                 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
458                                            "tdb_open: failed to close tdb fd"
459                                            " on error: %s", strerror(errno));
460                         free(tdb->file->lockrecs);
461                         free(tdb->file);
462                 }
463         }
464
465         free(tdb);
466         errno = saved_errno;
467         return NULL;
468 }
469
470 int tdb_close(struct tdb_context *tdb)
471 {
472         int ret = 0;
473
474         tdb_trace(tdb, "tdb_close");
475
476         if (tdb->transaction) {
477                 tdb_transaction_cancel(tdb);
478         }
479
480         if (tdb->file->map_ptr) {
481                 if (tdb->flags & TDB_INTERNAL)
482                         free(tdb->file->map_ptr);
483                 else
484                         tdb_munmap(tdb->file);
485         }
486         free((char *)tdb->name);
487         if (tdb->file) {
488                 struct tdb_file **i;
489
490                 tdb_unlock_all(tdb);
491                 if (--tdb->file->refcnt == 0) {
492                         ret = close(tdb->file->fd);
493
494                         /* Remove from files list */
495                         for (i = &files; *i; i = &(*i)->next) {
496                                 if (*i == tdb->file) {
497                                         *i = tdb->file->next;
498                                         break;
499                                 }
500                         }
501                         free(tdb->file->lockrecs);
502                         free(tdb->file);
503                 }
504         }
505
506 #ifdef TDB_TRACE
507         close(tdb->tracefd);
508 #endif
509         free(tdb);
510
511         return ret;
512 }