tdb2: open hook for implementing TDB_CLEAR_IF_FIRST
[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->hash_fn(&newdb.hdr.hash_test,
105                                            sizeof(newdb.hdr.hash_test),
106                                            newdb.hdr.hash_seed,
107                                            tdb->hash_data);
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         struct tdb_attribute_openhook *openhook = NULL;
197         tdb_bool_err berr;
198         enum TDB_ERROR ecode;
199
200         tdb = malloc(sizeof(*tdb));
201         if (!tdb) {
202                 /* Can't log this */
203                 errno = ENOMEM;
204                 return NULL;
205         }
206         tdb->name = NULL;
207         tdb->direct_access = 0;
208         tdb->flags = tdb_flags;
209         tdb->log_fn = NULL;
210         tdb->transaction = NULL;
211         tdb->stats = NULL;
212         tdb->access = NULL;
213         tdb->last_error = TDB_SUCCESS;
214         tdb->file = NULL;
215         tdb_hash_init(tdb);
216         tdb_io_init(tdb);
217
218         while (attr) {
219                 switch (attr->base.attr) {
220                 case TDB_ATTRIBUTE_LOG:
221                         tdb->log_fn = attr->log.fn;
222                         tdb->log_data = attr->log.data;
223                         break;
224                 case TDB_ATTRIBUTE_HASH:
225                         tdb->hash_fn = attr->hash.fn;
226                         tdb->hash_data = attr->hash.data;
227                         break;
228                 case TDB_ATTRIBUTE_SEED:
229                         seed = &attr->seed;
230                         break;
231                 case TDB_ATTRIBUTE_STATS:
232                         tdb->stats = &attr->stats;
233                         /* They have stats we don't know about?  Tell them. */
234                         if (tdb->stats->size > sizeof(attr->stats))
235                                 tdb->stats->size = sizeof(attr->stats);
236                         break;
237                 case TDB_ATTRIBUTE_OPENHOOK:
238                         openhook = &attr->openhook;
239                         break;
240                 default:
241                         ecode = tdb_logerr(tdb, TDB_ERR_EINVAL,
242                                            TDB_LOG_USE_ERROR,
243                                            "tdb_open:"
244                                            " unknown attribute type %u",
245                                            attr->base.attr);
246                         goto fail;
247                 }
248                 attr = attr->base.next;
249         }
250
251         if (tdb_flags & ~(TDB_INTERNAL | TDB_NOLOCK | TDB_NOMMAP | TDB_CONVERT
252                           | TDB_NOSYNC | TDB_SEQNUM)) {
253                 ecode = tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
254                                    "tdb_open: unknown flags %u", tdb_flags);
255                 goto fail;
256         }
257
258         if ((open_flags & O_ACCMODE) == O_WRONLY) {
259                 ecode = tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
260                                    "tdb_open: can't open tdb %s write-only",
261                                    name);
262                 goto fail;
263         }
264
265         if ((open_flags & O_ACCMODE) == O_RDONLY) {
266                 tdb->read_only = true;
267                 tdb->mmap_flags = PROT_READ;
268         } else {
269                 tdb->read_only = false;
270                 tdb->mmap_flags = PROT_READ | PROT_WRITE;
271         }
272
273         /* internal databases don't need any of the rest. */
274         if (tdb->flags & TDB_INTERNAL) {
275                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
276                 ecode = tdb_new_file(tdb);
277                 if (ecode != TDB_SUCCESS) {
278                         goto fail;
279                 }
280                 tdb->file->fd = -1;
281                 ecode = tdb_new_database(tdb, seed, &hdr);
282                 if (ecode != TDB_SUCCESS) {
283                         goto fail;
284                 }
285                 if (name) {
286                         tdb->name = strdup(name);
287                         if (!tdb->name) {
288                                 ecode = tdb_logerr(tdb, TDB_ERR_OOM,
289                                                    TDB_LOG_ERROR,
290                                                    "tdb_open: failed to"
291                                                    " allocate name");
292                                 goto fail;
293                         }
294                 }
295                 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
296                 tdb->hash_seed = hdr.hash_seed;
297                 tdb_ftable_init(tdb);
298                 return tdb;
299         }
300
301         if (stat(name, &st) != -1)
302                 tdb->file = find_file(st.st_dev, st.st_ino);
303
304         if (!tdb->file) {
305                 int fd;
306
307                 if ((fd = open(name, open_flags, mode)) == -1) {
308                         /* errno set by open(2) */
309                         saved_errno = errno;
310                         tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
311                                    "tdb_open: could not open file %s: %s",
312                                    name, strerror(errno));
313                         goto fail_errno;
314                 }
315
316                 /* on exec, don't inherit the fd */
317                 v = fcntl(fd, F_GETFD, 0);
318                 fcntl(fd, F_SETFD, v | FD_CLOEXEC);
319
320                 if (fstat(fd, &st) == -1) {
321                         saved_errno = errno;
322                         tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
323                                    "tdb_open: could not stat open %s: %s",
324                                    name, strerror(errno));
325                         goto fail_errno;
326                 }
327
328                 ecode = tdb_new_file(tdb);
329                 if (ecode != TDB_SUCCESS)
330                         goto fail;
331
332                 tdb->file->next = files;
333                 tdb->file->fd = fd;
334                 tdb->file->device = st.st_dev;
335                 tdb->file->inode = st.st_ino;
336                 tdb->file->map_ptr = NULL;
337                 tdb->file->map_size = sizeof(struct tdb_header);
338         }
339
340         /* ensure there is only one process initialising at once */
341         ecode = tdb_lock_open(tdb, TDB_LOCK_WAIT|TDB_LOCK_NOCHECK);
342         if (ecode != TDB_SUCCESS) {
343                 goto fail;
344         }
345
346         /* call their open hook if they gave us one. */
347         if (openhook) {
348                 ecode = openhook->fn(tdb->file->fd, openhook->data);
349                 if (ecode != TDB_SUCCESS) {
350                         tdb_logerr(tdb, ecode, TDB_LOG_ERROR,
351                                    "tdb_open: open hook failed");
352                         goto fail;
353                 }
354                 open_flags |= O_CREAT;
355         }
356
357         /* If they used O_TRUNC, read will return 0. */
358         rlen = pread(tdb->file->fd, &hdr, sizeof(hdr), 0);
359         if (rlen == 0 && (open_flags & O_CREAT)) {
360                 ecode = tdb_new_database(tdb, seed, &hdr);
361                 if (ecode != TDB_SUCCESS) {
362                         goto fail;
363                 }
364         } else if (rlen < 0) {
365                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
366                                    "tdb_open: error %s reading %s",
367                                    strerror(errno), name);
368                 goto fail;
369         } else if (rlen < sizeof(hdr)
370                    || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
371                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
372                                    "tdb_open: %s is not a tdb file", name);
373                 goto fail;
374         }
375
376         if (hdr.version != TDB_VERSION) {
377                 if (hdr.version == bswap_64(TDB_VERSION))
378                         tdb->flags |= TDB_CONVERT;
379                 else {
380                         /* wrong version */
381                         ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
382                                            "tdb_open:"
383                                            " %s is unknown version 0x%llx",
384                                            name, (long long)hdr.version);
385                         goto fail;
386                 }
387         }
388
389         tdb_convert(tdb, &hdr, sizeof(hdr));
390         tdb->hash_seed = hdr.hash_seed;
391         hash_test = TDB_HASH_MAGIC;
392         hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
393         if (hdr.hash_test != hash_test) {
394                 /* wrong hash variant */
395                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
396                                    "tdb_open:"
397                                    " %s uses a different hash function",
398                                    name);
399                 goto fail;
400         }
401
402         tdb->name = strdup(name);
403         if (!tdb->name) {
404                 ecode = tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
405                                    "tdb_open: failed to allocate name");
406                 goto fail;
407         }
408
409         /* Clear any features we don't understand. */
410         if ((open_flags & O_ACCMODE) != O_RDONLY) {
411                 hdr.features_used &= TDB_FEATURE_MASK;
412                 if (tdb_write_convert(tdb, offsetof(struct tdb_header,
413                                                     features_used),
414                                       &hdr.features_used,
415                                       sizeof(hdr.features_used)) == -1)
416                         goto fail;
417         }
418
419         tdb_unlock_open(tdb);
420
421         /* This make sure we have current map_size and mmap. */
422         tdb->methods->oob(tdb, tdb->file->map_size + 1, true);
423
424         /* Now it's fully formed, recover if necessary. */
425         berr = tdb_needs_recovery(tdb);
426         if (unlikely(berr != false)) {
427                 if (berr < 0) {
428                         ecode = berr;
429                         goto fail;
430                 }
431                 ecode = tdb_lock_and_recover(tdb);
432                 if (ecode != TDB_SUCCESS) {
433                         goto fail;
434                 }
435         }
436
437         ecode = tdb_ftable_init(tdb);
438         if (ecode != TDB_SUCCESS) {
439                 goto fail;
440         }
441
442         /* Add to linked list if we're new. */
443         if (tdb->file->refcnt == 1)
444                 files = tdb->file;
445         return tdb;
446
447  fail:
448         /* Map ecode to some logical errno. */
449         switch (ecode) {
450         case TDB_ERR_CORRUPT:
451         case TDB_ERR_IO:
452                 saved_errno = EIO;
453                 break;
454         case TDB_ERR_LOCK:
455                 saved_errno = EWOULDBLOCK;
456                 break;
457         case TDB_ERR_OOM:
458                 saved_errno = ENOMEM;
459                 break;
460         case TDB_ERR_EINVAL:
461                 saved_errno = EINVAL;
462                 break;
463         default:
464                 saved_errno = EINVAL;
465                 break;
466         }
467
468 fail_errno:
469 #ifdef TDB_TRACE
470         close(tdb->tracefd);
471 #endif
472         free(cast_const(char *, tdb->name));
473         if (tdb->file) {
474                 tdb_lock_cleanup(tdb);
475                 if (--tdb->file->refcnt == 0) {
476                         assert(tdb->file->num_lockrecs == 0);
477                         if (tdb->file->map_ptr) {
478                                 if (tdb->flags & TDB_INTERNAL) {
479                                         free(tdb->file->map_ptr);
480                                 } else
481                                         tdb_munmap(tdb->file);
482                         }
483                         if (close(tdb->file->fd) != 0)
484                                 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
485                                            "tdb_open: failed to close tdb fd"
486                                            " on error: %s", strerror(errno));
487                         free(tdb->file->lockrecs);
488                         free(tdb->file);
489                 }
490         }
491
492         free(tdb);
493         errno = saved_errno;
494         return NULL;
495 }
496
497 int tdb_close(struct tdb_context *tdb)
498 {
499         int ret = 0;
500
501         tdb_trace(tdb, "tdb_close");
502
503         if (tdb->transaction) {
504                 tdb_transaction_cancel(tdb);
505         }
506
507         if (tdb->file->map_ptr) {
508                 if (tdb->flags & TDB_INTERNAL)
509                         free(tdb->file->map_ptr);
510                 else
511                         tdb_munmap(tdb->file);
512         }
513         free(cast_const(char *, tdb->name));
514         if (tdb->file) {
515                 struct tdb_file **i;
516
517                 tdb_lock_cleanup(tdb);
518                 if (--tdb->file->refcnt == 0) {
519                         ret = close(tdb->file->fd);
520
521                         /* Remove from files list */
522                         for (i = &files; *i; i = &(*i)->next) {
523                                 if (*i == tdb->file) {
524                                         *i = tdb->file->next;
525                                         break;
526                                 }
527                         }
528                         free(tdb->file->lockrecs);
529                         free(tdb->file);
530                 }
531         }
532
533 #ifdef TDB_TRACE
534         close(tdb->tracefd);
535 #endif
536         free(tdb);
537
538         return ret;
539 }