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