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