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