tdb2: tdb_name and tdb_fd functions.
[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->khash(&newdb.hdr.hash_test,
105                                          sizeof(newdb.hdr.hash_test),
106                                          newdb.hdr.hash_seed,
107                                          tdb->hash_priv);
108         newdb.hdr.recovery = 0;
109         newdb.hdr.features_used = newdb.hdr.features_offered = TDB_FEATURE_MASK;
110         memset(newdb.hdr.reserved, 0, sizeof(newdb.hdr.reserved));
111         /* Initial hashes are empty. */
112         memset(newdb.hdr.hashtable, 0, sizeof(newdb.hdr.hashtable));
113
114         /* Free is empty. */
115         newdb.hdr.free_table = offsetof(struct new_database, ftable);
116         memset(&newdb.ftable, 0, sizeof(newdb.ftable));
117         ecode = set_header(NULL, &newdb.ftable.hdr, TDB_FTABLE_MAGIC, 0,
118                            sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr),
119                            sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr),
120                            0);
121         if (ecode != TDB_SUCCESS) {
122                 return ecode;
123         }
124
125         /* Magic food */
126         memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
127         strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
128
129         /* This creates an endian-converted database, as if read from disk */
130         magic_len = sizeof(newdb.hdr.magic_food);
131         tdb_convert(tdb,
132                     (char *)&newdb.hdr + magic_len, sizeof(newdb) - magic_len);
133
134         *hdr = newdb.hdr;
135
136         if (tdb->flags & TDB_INTERNAL) {
137                 tdb->file->map_size = sizeof(newdb);
138                 tdb->file->map_ptr = malloc(tdb->file->map_size);
139                 if (!tdb->file->map_ptr) {
140                         return tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
141                                           "tdb_new_database:"
142                                           " failed to allocate");
143                 }
144                 memcpy(tdb->file->map_ptr, &newdb, tdb->file->map_size);
145                 return TDB_SUCCESS;
146         }
147         if (lseek(tdb->file->fd, 0, SEEK_SET) == -1) {
148                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
149                                   "tdb_new_database:"
150                                   " failed to seek: %s", strerror(errno));
151         }
152
153         if (ftruncate(tdb->file->fd, 0) == -1) {
154                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
155                                   "tdb_new_database:"
156                                   " failed to truncate: %s", strerror(errno));
157         }
158
159         rlen = write(tdb->file->fd, &newdb, sizeof(newdb));
160         if (rlen != sizeof(newdb)) {
161                 if (rlen >= 0)
162                         errno = ENOSPC;
163                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
164                                   "tdb_new_database: %zi writing header: %s",
165                                   rlen, strerror(errno));
166         }
167         return TDB_SUCCESS;
168 }
169
170 static enum TDB_ERROR tdb_new_file(struct tdb_context *tdb)
171 {
172         tdb->file = malloc(sizeof(*tdb->file));
173         if (!tdb->file)
174                 return tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
175                                   "tdb_open: could alloc tdb_file structure");
176         tdb->file->num_lockrecs = 0;
177         tdb->file->lockrecs = NULL;
178         tdb->file->allrecord_lock.count = 0;
179         tdb->file->refcnt = 1;
180         return TDB_SUCCESS;
181 }
182
183 struct tdb_context *tdb_open(const char *name, int tdb_flags,
184                              int open_flags, mode_t mode,
185                              union tdb_attribute *attr)
186 {
187         struct tdb_context *tdb;
188         struct stat st;
189         int saved_errno = 0;
190         uint64_t hash_test;
191         unsigned v;
192         ssize_t rlen;
193         struct tdb_header hdr;
194         struct tdb_attribute_seed *seed = NULL;
195         tdb_bool_err berr;
196         enum TDB_ERROR ecode;
197
198         tdb = malloc(sizeof(*tdb));
199         if (!tdb) {
200                 /* Can't log this */
201                 errno = ENOMEM;
202                 return NULL;
203         }
204         tdb->name = NULL;
205         tdb->direct_access = 0;
206         tdb->flags = tdb_flags;
207         tdb->logfn = NULL;
208         tdb->transaction = NULL;
209         tdb->stats = NULL;
210         tdb->access = NULL;
211         tdb->file = NULL;
212         tdb_hash_init(tdb);
213         tdb_io_init(tdb);
214
215         while (attr) {
216                 switch (attr->base.attr) {
217                 case TDB_ATTRIBUTE_LOG:
218                         tdb->logfn = attr->log.log_fn;
219                         tdb->log_private = attr->log.log_private;
220                         break;
221                 case TDB_ATTRIBUTE_HASH:
222                         tdb->khash = attr->hash.hash_fn;
223                         tdb->hash_priv = attr->hash.hash_private;
224                         break;
225                 case TDB_ATTRIBUTE_SEED:
226                         seed = &attr->seed;
227                         break;
228                 case TDB_ATTRIBUTE_STATS:
229                         tdb->stats = &attr->stats;
230                         /* They have stats we don't know about?  Tell them. */
231                         if (tdb->stats->size > sizeof(attr->stats))
232                                 tdb->stats->size = sizeof(attr->stats);
233                         break;
234                 default:
235                         ecode = tdb_logerr(tdb, TDB_ERR_EINVAL,
236                                            TDB_LOG_USE_ERROR,
237                                            "tdb_open:"
238                                            " unknown attribute type %u",
239                                            attr->base.attr);
240                         goto fail;
241                 }
242                 attr = attr->base.next;
243         }
244
245         if (tdb_flags & ~(TDB_INTERNAL | TDB_NOLOCK | TDB_NOMMAP | TDB_CONVERT
246                           | TDB_NOSYNC)) {
247                 ecode = tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
248                                    "tdb_open: unknown flags %u", tdb_flags);
249                 goto fail;
250         }
251
252         if ((open_flags & O_ACCMODE) == O_WRONLY) {
253                 ecode = tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
254                                    "tdb_open: can't open tdb %s write-only",
255                                    name);
256                 goto fail;
257         }
258
259         if ((open_flags & O_ACCMODE) == O_RDONLY) {
260                 tdb->read_only = true;
261                 tdb->mmap_flags = PROT_READ;
262         } else {
263                 tdb->read_only = false;
264                 tdb->mmap_flags = PROT_READ | PROT_WRITE;
265         }
266
267         /* internal databases don't need any of the rest. */
268         if (tdb->flags & TDB_INTERNAL) {
269                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
270                 ecode = tdb_new_file(tdb);
271                 if (ecode != TDB_SUCCESS) {
272                         goto fail;
273                 }
274                 tdb->file->fd = -1;
275                 ecode = tdb_new_database(tdb, seed, &hdr);
276                 if (ecode != TDB_SUCCESS) {
277                         goto fail;
278                 }
279                 if (name) {
280                         tdb->name = strdup(name);
281                         if (!tdb->name) {
282                                 ecode = tdb_logerr(tdb, TDB_ERR_OOM,
283                                                    TDB_LOG_ERROR,
284                                                    "tdb_open: failed to"
285                                                    " allocate name");
286                                 goto fail;
287                         }
288                 }
289                 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
290                 tdb->hash_seed = hdr.hash_seed;
291                 tdb_ftable_init(tdb);
292                 return tdb;
293         }
294
295         if (stat(name, &st) != -1)
296                 tdb->file = find_file(st.st_dev, st.st_ino);
297
298         if (!tdb->file) {
299                 int fd;
300
301                 if ((fd = open(name, open_flags, mode)) == -1) {
302                         /* errno set by open(2) */
303                         saved_errno = errno;
304                         tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
305                                    "tdb_open: could not open file %s: %s",
306                                    name, strerror(errno));
307                         goto fail_errno;
308                 }
309
310                 /* on exec, don't inherit the fd */
311                 v = fcntl(fd, F_GETFD, 0);
312                 fcntl(fd, F_SETFD, v | FD_CLOEXEC);
313
314                 if (fstat(fd, &st) == -1) {
315                         saved_errno = errno;
316                         tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
317                                    "tdb_open: could not stat open %s: %s",
318                                    name, strerror(errno));
319                         goto fail_errno;
320                 }
321
322                 ecode = tdb_new_file(tdb);
323                 if (ecode != TDB_SUCCESS)
324                         goto fail;
325
326                 tdb->file->next = files;
327                 tdb->file->fd = fd;
328                 tdb->file->device = st.st_dev;
329                 tdb->file->inode = st.st_ino;
330                 tdb->file->map_ptr = NULL;
331                 tdb->file->map_size = sizeof(struct tdb_header);
332         }
333
334         /* ensure there is only one process initialising at once */
335         ecode = tdb_lock_open(tdb, TDB_LOCK_WAIT|TDB_LOCK_NOCHECK);
336         if (ecode != TDB_SUCCESS) {
337                 goto fail;
338         }
339
340         /* If they used O_TRUNC, read will return 0. */
341         rlen = pread(tdb->file->fd, &hdr, sizeof(hdr), 0);
342         if (rlen == 0 && (open_flags & O_CREAT)) {
343                 ecode = tdb_new_database(tdb, seed, &hdr);
344                 if (ecode != TDB_SUCCESS) {
345                         goto fail;
346                 }
347         } else if (rlen < 0) {
348                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
349                                    "tdb_open: error %s reading %s",
350                                    strerror(errno), name);
351                 goto fail;
352         } else if (rlen < sizeof(hdr)
353                    || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
354                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
355                                    "tdb_open: %s is not a tdb file", name);
356                 goto fail;
357         }
358
359         if (hdr.version != TDB_VERSION) {
360                 if (hdr.version == bswap_64(TDB_VERSION))
361                         tdb->flags |= TDB_CONVERT;
362                 else {
363                         /* wrong version */
364                         ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
365                                            "tdb_open:"
366                                            " %s is unknown version 0x%llx",
367                                            name, (long long)hdr.version);
368                         goto fail;
369                 }
370         }
371
372         tdb_convert(tdb, &hdr, sizeof(hdr));
373         tdb->hash_seed = hdr.hash_seed;
374         hash_test = TDB_HASH_MAGIC;
375         hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
376         if (hdr.hash_test != hash_test) {
377                 /* wrong hash variant */
378                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
379                                    "tdb_open:"
380                                    " %s uses a different hash function",
381                                    name);
382                 goto fail;
383         }
384
385         tdb->name = strdup(name);
386         if (!tdb->name) {
387                 ecode = tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
388                                    "tdb_open: failed to allocate name");
389                 goto fail;
390         }
391
392         /* Clear any features we don't understand. */
393         if ((open_flags & O_ACCMODE) != O_RDONLY) {
394                 hdr.features_used &= TDB_FEATURE_MASK;
395                 if (tdb_write_convert(tdb, offsetof(struct tdb_header,
396                                                     features_used),
397                                       &hdr.features_used,
398                                       sizeof(hdr.features_used)) == -1)
399                         goto fail;
400         }
401
402         tdb_unlock_open(tdb);
403
404         /* This make sure we have current map_size and mmap. */
405         tdb->methods->oob(tdb, tdb->file->map_size + 1, true);
406
407         /* Now it's fully formed, recover if necessary. */
408         berr = tdb_needs_recovery(tdb);
409         if (unlikely(berr != false)) {
410                 if (berr < 0) {
411                         ecode = berr;
412                         goto fail;
413                 }
414                 ecode = tdb_lock_and_recover(tdb);
415                 if (ecode != TDB_SUCCESS) {
416                         goto fail;
417                 }
418         }
419
420         ecode = tdb_ftable_init(tdb);
421         if (ecode != TDB_SUCCESS) {
422                 goto fail;
423         }
424
425         /* Add to linked list if we're new. */
426         if (tdb->file->refcnt == 1)
427                 files = tdb->file;
428         return tdb;
429
430  fail:
431         /* Map ecode to some logical errno. */
432         switch (ecode) {
433         case TDB_ERR_CORRUPT:
434         case TDB_ERR_IO:
435                 saved_errno = EIO;
436                 break;
437         case TDB_ERR_LOCK:
438                 saved_errno = EWOULDBLOCK;
439                 break;
440         case TDB_ERR_OOM:
441                 saved_errno = ENOMEM;
442                 break;
443         case TDB_ERR_EINVAL:
444                 saved_errno = EINVAL;
445                 break;
446         default:
447                 saved_errno = EINVAL;
448                 break;
449         }
450
451 fail_errno:
452 #ifdef TDB_TRACE
453         close(tdb->tracefd);
454 #endif
455         free((char *)tdb->name);
456         if (tdb->file) {
457                 tdb_unlock_all(tdb);
458                 if (--tdb->file->refcnt == 0) {
459                         assert(tdb->file->num_lockrecs == 0);
460                         if (tdb->file->map_ptr) {
461                                 if (tdb->flags & TDB_INTERNAL) {
462                                         free(tdb->file->map_ptr);
463                                 } else
464                                         tdb_munmap(tdb->file);
465                         }
466                         if (close(tdb->file->fd) != 0)
467                                 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
468                                            "tdb_open: failed to close tdb fd"
469                                            " on error: %s", strerror(errno));
470                         free(tdb->file->lockrecs);
471                         free(tdb->file);
472                 }
473         }
474
475         free(tdb);
476         errno = saved_errno;
477         return NULL;
478 }
479
480 int tdb_close(struct tdb_context *tdb)
481 {
482         int ret = 0;
483
484         tdb_trace(tdb, "tdb_close");
485
486         if (tdb->transaction) {
487                 tdb_transaction_cancel(tdb);
488         }
489
490         if (tdb->file->map_ptr) {
491                 if (tdb->flags & TDB_INTERNAL)
492                         free(tdb->file->map_ptr);
493                 else
494                         tdb_munmap(tdb->file);
495         }
496         free((char *)tdb->name);
497         if (tdb->file) {
498                 struct tdb_file **i;
499
500                 tdb_unlock_all(tdb);
501                 if (--tdb->file->refcnt == 0) {
502                         ret = close(tdb->file->fd);
503
504                         /* Remove from files list */
505                         for (i = &files; *i; i = &(*i)->next) {
506                                 if (*i == tdb->file) {
507                                         *i = tdb->file->next;
508                                         break;
509                                 }
510                         }
511                         free(tdb->file->lockrecs);
512                         free(tdb->file);
513                 }
514         }
515
516 #ifdef TDB_TRACE
517         close(tdb->tracefd);
518 #endif
519         free(tdb);
520
521         return ret;
522 }