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