79c76b1991fe5eca77edfdad99ab8d07e3a79d15
[ccan] / ccan / tdb2 / tdb.c
1 #include "private.h"
2 #include <ccan/tdb2/tdb2.h>
3 #include <ccan/build_assert/build_assert.h>
4 #include <ccan/likely/likely.h>
5 #include <assert.h>
6
7 /* The null return. */
8 struct tdb_data tdb_null = { .dptr = NULL, .dsize = 0 };
9
10 /* all contexts, to ensure no double-opens (fcntl locks don't nest!) */
11 static struct tdb_context *tdbs = NULL;
12
13 PRINTF_FMT(4, 5) static void
14 null_log_fn(struct tdb_context *tdb,
15             enum tdb_debug_level level, void *priv,
16             const char *fmt, ...)
17 {
18 }
19
20 static bool tdb_already_open(dev_t device, ino_t ino)
21 {
22         struct tdb_context *i;
23         
24         for (i = tdbs; i; i = i->next) {
25                 if (i->device == device && i->inode == ino) {
26                         return true;
27                 }
28         }
29
30         return false;
31 }
32
33 static uint64_t random_number(struct tdb_context *tdb)
34 {
35         int fd;
36         uint64_t ret = 0;
37         struct timeval now;
38
39         fd = open("/dev/urandom", O_RDONLY);
40         if (fd >= 0) {
41                 if (tdb_read_all(fd, &ret, sizeof(ret))) {
42                         tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
43                                  "tdb_open: random from /dev/urandom\n");
44                         close(fd);
45                         return ret;
46                 }
47                 close(fd);
48         }
49         /* FIXME: Untested!  Based on Wikipedia protocol description! */
50         fd = open("/dev/egd-pool", O_RDWR);
51         if (fd >= 0) {
52                 /* Command is 1, next byte is size we want to read. */
53                 char cmd[2] = { 1, sizeof(uint64_t) };
54                 if (write(fd, cmd, sizeof(cmd)) == sizeof(cmd)) {
55                         char reply[1 + sizeof(uint64_t)];
56                         int r = read(fd, reply, sizeof(reply));
57                         if (r > 1) {
58                                 tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
59                                          "tdb_open: %u random bytes from"
60                                          " /dev/egd-pool\n", 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->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
77                  "tdb_open: random from getpid and time\n");
78         return ret;
79 }
80
81 struct new_database {
82         struct tdb_header hdr;
83         /* Initial free zone. */
84         struct free_zone_header zhdr;
85         tdb_off_t free[BUCKETS_FOR_ZONE(INITIAL_ZONE_BITS) + 1];
86 };
87
88 /* initialise a new database */
89 static int tdb_new_database(struct tdb_context *tdb,
90                             struct tdb_attribute_seed *seed,
91                             struct tdb_header *hdr)
92 {
93         /* We make it up in memory, then write it out if not internal */
94         struct new_database newdb;
95         unsigned int magic_len;
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         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.zhdr.zone_bits = INITIAL_ZONE_BITS;
114         memset(newdb.free, 0, sizeof(newdb.free));
115
116         /* Magic food */
117         memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
118         strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
119
120         /* This creates an endian-converted database, as if read from disk */
121         magic_len = sizeof(newdb.hdr.magic_food);
122         tdb_convert(tdb,
123                     (char *)&newdb.hdr + magic_len, sizeof(newdb) - magic_len);
124
125         *hdr = newdb.hdr;
126
127         if (tdb->flags & TDB_INTERNAL) {
128                 tdb->map_size = sizeof(newdb);
129                 tdb->map_ptr = malloc(tdb->map_size);
130                 if (!tdb->map_ptr) {
131                         tdb->ecode = TDB_ERR_OOM;
132                         return -1;
133                 }
134                 memcpy(tdb->map_ptr, &newdb, tdb->map_size);
135                 return 0;
136         }
137         if (lseek(tdb->fd, 0, SEEK_SET) == -1)
138                 return -1;
139
140         if (ftruncate(tdb->fd, 0) == -1)
141                 return -1;
142
143         if (!tdb_pwrite_all(tdb->fd, &newdb, sizeof(newdb), 0)) {
144                 tdb->ecode = TDB_ERR_IO;
145                 return -1;
146         }
147         return 0;
148 }
149
150 struct tdb_context *tdb_open(const char *name, int tdb_flags,
151                              int open_flags, mode_t mode,
152                              union tdb_attribute *attr)
153 {
154         struct tdb_context *tdb;
155         struct stat st;
156         int save_errno;
157         uint64_t hash_test;
158         unsigned v;
159         struct tdb_header hdr;
160         struct tdb_attribute_seed *seed = NULL;
161
162         tdb = malloc(sizeof(*tdb));
163         if (!tdb) {
164                 /* Can't log this */
165                 errno = ENOMEM;
166                 goto fail;
167         }
168         tdb->name = NULL;
169         tdb->map_ptr = NULL;
170         tdb->direct_access = 0;
171         tdb->fd = -1;
172         tdb->map_size = sizeof(struct tdb_header);
173         tdb->ecode = TDB_SUCCESS;
174         tdb->flags = tdb_flags;
175         tdb->log = null_log_fn;
176         tdb->log_priv = NULL;
177         tdb->transaction = NULL;
178         tdb_hash_init(tdb);
179         /* last_zone will be set below. */
180         tdb_io_init(tdb);
181         tdb_lock_init(tdb);
182
183         while (attr) {
184                 switch (attr->base.attr) {
185                 case TDB_ATTRIBUTE_LOG:
186                         tdb->log = attr->log.log_fn;
187                         tdb->log_priv = attr->log.log_private;
188                         break;
189                 case TDB_ATTRIBUTE_HASH:
190                         tdb->khash = attr->hash.hash_fn;
191                         tdb->hash_priv = attr->hash.hash_private;
192                         break;
193                 case TDB_ATTRIBUTE_SEED:
194                         seed = &attr->seed;
195                         break;
196                 default:
197                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
198                                  "tdb_open: unknown attribute type %u\n",
199                                  attr->base.attr);
200                         errno = EINVAL;
201                         goto fail;
202                 }
203                 attr = attr->base.next;
204         }
205
206         if ((open_flags & O_ACCMODE) == O_WRONLY) {
207                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
208                          "tdb_open: can't open tdb %s write-only\n", name);
209                 errno = EINVAL;
210                 goto fail;
211         }
212
213         if ((open_flags & O_ACCMODE) == O_RDONLY) {
214                 tdb->read_only = true;
215                 /* read only databases don't do locking */
216                 tdb->flags |= TDB_NOLOCK;
217                 tdb->mmap_flags = PROT_READ;
218         } else {
219                 tdb->read_only = false;
220                 tdb->mmap_flags = PROT_READ | PROT_WRITE;
221         }
222
223         /* internal databases don't need any of the rest. */
224         if (tdb->flags & TDB_INTERNAL) {
225                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
226                 if (tdb_new_database(tdb, seed, &hdr) != 0) {
227                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
228                                  "tdb_open: tdb_new_database failed!");
229                         goto fail;
230                 }
231                 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
232                 tdb->hash_seed = hdr.hash_seed;
233                 tdb_zone_init(tdb);
234                 return tdb;
235         }
236
237         if ((tdb->fd = open(name, open_flags, mode)) == -1) {
238                 tdb->log(tdb, TDB_DEBUG_WARNING, tdb->log_priv,
239                          "tdb_open: could not open file %s: %s\n",
240                          name, strerror(errno));
241                 goto fail;      /* errno set by open(2) */
242         }
243
244         /* on exec, don't inherit the fd */
245         v = fcntl(tdb->fd, F_GETFD, 0);
246         fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
247
248         /* ensure there is only one process initialising at once */
249         if (tdb_lock_open(tdb) == -1) {
250                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
251                          "tdb_open: failed to get open lock on %s: %s\n",
252                          name, strerror(errno));
253                 goto fail;      /* errno set by tdb_brlock */
254         }
255
256         if (!tdb_pread_all(tdb->fd, &hdr, sizeof(hdr), 0)
257             || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
258                 if (!(open_flags & O_CREAT)
259                     || tdb_new_database(tdb, seed, &hdr) == -1) {
260                         if (errno == 0) {
261                                 errno = EIO; /* ie bad format or something */
262                         }
263                         goto fail;
264                 }
265         } else if (hdr.version != TDB_VERSION) {
266                 if (hdr.version == bswap_64(TDB_VERSION))
267                         tdb->flags |= TDB_CONVERT;
268                 else {
269                         /* wrong version */
270                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
271                                  "tdb_open: %s is unknown version 0x%llx\n",
272                                  name, (long long)hdr.version);
273                         errno = EIO;
274                         goto fail;
275                 }
276         }
277
278         tdb_convert(tdb, &hdr, sizeof(hdr));
279         tdb->hash_seed = hdr.hash_seed;
280         hash_test = TDB_HASH_MAGIC;
281         hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
282         if (hdr.hash_test != hash_test) {
283                 /* wrong hash variant */
284                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
285                          "tdb_open: %s uses a different hash function\n",
286                          name);
287                 errno = EIO;
288                 goto fail;
289         }
290
291         if (fstat(tdb->fd, &st) == -1)
292                 goto fail;
293
294         /* Is it already in the open list?  If so, fail. */
295         if (tdb_already_open(st.st_dev, st.st_ino)) {
296                 /* FIXME */
297                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
298                          "tdb_open: %s (%d,%d) is already open in this process\n",
299                          name, (int)st.st_dev, (int)st.st_ino);
300                 errno = EBUSY;
301                 goto fail;
302         }
303
304         tdb->name = strdup(name);
305         if (!tdb->name) {
306                 errno = ENOMEM;
307                 goto fail;
308         }
309
310         tdb->device = st.st_dev;
311         tdb->inode = st.st_ino;
312         tdb_unlock_open(tdb);
313
314         /* This make sure we have current map_size and mmap. */
315         tdb->methods->oob(tdb, tdb->map_size + 1, true);
316
317         /* Now we can pick a random free zone to start from. */
318         if (tdb_zone_init(tdb) == -1)
319                 goto fail;
320
321         tdb->next = tdbs;
322         tdbs = tdb;
323         return tdb;
324
325  fail:
326         save_errno = errno;
327
328         if (!tdb)
329                 return NULL;
330
331 #ifdef TDB_TRACE
332         close(tdb->tracefd);
333 #endif
334         if (tdb->map_ptr) {
335                 if (tdb->flags & TDB_INTERNAL) {
336                         free(tdb->map_ptr);
337                 } else
338                         tdb_munmap(tdb);
339         }
340         free((char *)tdb->name);
341         if (tdb->fd != -1)
342                 if (close(tdb->fd) != 0)
343                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
344                                  "tdb_open: failed to close tdb->fd"
345                                  " on error!\n");
346         free(tdb);
347         errno = save_errno;
348         return NULL;
349 }
350
351 /* FIXME: modify, don't rewrite! */
352 static int update_rec_hdr(struct tdb_context *tdb,
353                           tdb_off_t off,
354                           tdb_len_t keylen,
355                           tdb_len_t datalen,
356                           struct tdb_used_record *rec,
357                           uint64_t h)
358 {
359         uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
360
361         if (set_header(tdb, rec, keylen, datalen, keylen + dataroom, h,
362                        rec_zone_bits(rec)))
363                 return -1;
364
365         return tdb_write_convert(tdb, off, rec, sizeof(*rec));
366 }
367
368 /* Returns -1 on error, 0 on OK */
369 static int replace_data(struct tdb_context *tdb,
370                         struct hash_info *h,
371                         struct tdb_data key, struct tdb_data dbuf,
372                         tdb_off_t old_off, tdb_len_t old_room,
373                         unsigned old_zone,
374                         bool growing)
375 {
376         tdb_off_t new_off;
377
378         /* Allocate a new record. */
379         new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, growing);
380         if (unlikely(new_off == TDB_OFF_ERR))
381                 return -1;
382
383         /* We didn't like the existing one: remove it. */
384         if (old_off) {
385                 add_free_record(tdb, old_zone, old_off,
386                                 sizeof(struct tdb_used_record)
387                                 + key.dsize + old_room);
388                 if (replace_in_hash(tdb, h, new_off) == -1)
389                         return -1;
390         } else {
391                 if (add_to_hash(tdb, h, new_off) == -1)
392                         return -1;
393         }
394
395         new_off += sizeof(struct tdb_used_record);
396         if (tdb->methods->write(tdb, new_off, key.dptr, key.dsize) == -1)
397                 return -1;
398
399         new_off += key.dsize;
400         if (tdb->methods->write(tdb, new_off, dbuf.dptr, dbuf.dsize) == -1)
401                 return -1;
402
403         /* FIXME: tdb_increment_seqnum(tdb); */
404         return 0;
405 }
406
407 int tdb_store(struct tdb_context *tdb,
408               struct tdb_data key, struct tdb_data dbuf, int flag)
409 {
410         struct hash_info h;
411         tdb_off_t off;
412         tdb_len_t old_room = 0;
413         struct tdb_used_record rec;
414         int ret;
415
416         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
417         if (unlikely(off == TDB_OFF_ERR))
418                 return -1;
419
420         /* Now we have lock on this hash bucket. */
421         if (flag == TDB_INSERT) {
422                 if (off) {
423                         tdb->ecode = TDB_ERR_EXISTS;
424                         goto fail;
425                 }
426         } else {
427                 if (off) {
428                         old_room = rec_data_length(&rec)
429                                 + rec_extra_padding(&rec);
430                         if (old_room >= dbuf.dsize) {
431                                 /* Can modify in-place.  Easy! */
432                                 if (update_rec_hdr(tdb, off,
433                                                    key.dsize, dbuf.dsize,
434                                                    &rec, h.h))
435                                         goto fail;
436                                 if (tdb->methods->write(tdb, off + sizeof(rec)
437                                                         + key.dsize,
438                                                         dbuf.dptr, dbuf.dsize))
439                                         goto fail;
440                                 tdb_unlock_hashes(tdb, h.hlock_start,
441                                                   h.hlock_range, F_WRLCK);
442                                 return 0;
443                         }
444                         /* FIXME: See if right record is free? */
445                 } else {
446                         if (flag == TDB_MODIFY) {
447                                 /* if the record doesn't exist and we
448                                    are in TDB_MODIFY mode then we should fail
449                                    the store */
450                                 tdb->ecode = TDB_ERR_NOEXIST;
451                                 goto fail;
452                         }
453                 }
454         }
455
456         /* If we didn't use the old record, this implies we're growing. */
457         ret = replace_data(tdb, &h, key, dbuf, off, old_room,
458                            rec_zone_bits(&rec), off != 0);
459         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
460         return ret;
461
462 fail:
463         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
464         return -1;
465 }
466
467 int tdb_append(struct tdb_context *tdb,
468                struct tdb_data key, struct tdb_data dbuf)
469 {
470         struct hash_info h;
471         tdb_off_t off;
472         struct tdb_used_record rec;
473         tdb_len_t old_room = 0, old_dlen;
474         unsigned char *newdata;
475         struct tdb_data new_dbuf;
476         int ret;
477
478         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
479         if (unlikely(off == TDB_OFF_ERR))
480                 return -1;
481
482         if (off) {
483                 old_dlen = rec_data_length(&rec);
484                 old_room = old_dlen + rec_extra_padding(&rec);
485
486                 /* Fast path: can append in place. */
487                 if (rec_extra_padding(&rec) >= dbuf.dsize) {
488                         if (update_rec_hdr(tdb, off, key.dsize,
489                                            old_dlen + dbuf.dsize, &rec, h.h))
490                                 goto fail;
491
492                         off += sizeof(rec) + key.dsize + old_dlen;
493                         if (tdb->methods->write(tdb, off, dbuf.dptr,
494                                                 dbuf.dsize) == -1)
495                                 goto fail;
496
497                         /* FIXME: tdb_increment_seqnum(tdb); */
498                         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range,
499                                           F_WRLCK);
500                         return 0;
501                 }
502                 /* FIXME: Check right record free? */
503
504                 /* Slow path. */
505                 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
506                 if (!newdata) {
507                         tdb->ecode = TDB_ERR_OOM;
508                         tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
509                                  "tdb_append: cannot allocate %llu bytes!\n",
510                                  (long long)key.dsize + old_dlen + dbuf.dsize);
511                         goto fail;
512                 }
513                 if (tdb->methods->read(tdb, off + sizeof(rec) + key.dsize,
514                                        newdata, old_dlen) != 0) {
515                         free(newdata);
516                         goto fail;
517                 }
518                 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
519                 new_dbuf.dptr = newdata;
520                 new_dbuf.dsize = old_dlen + dbuf.dsize;
521         } else {
522                 newdata = NULL;
523                 new_dbuf = dbuf;
524         }
525
526         /* If they're using tdb_append(), it implies they're growing record. */
527         ret = replace_data(tdb, &h, key, new_dbuf, off,
528                            old_room, rec_zone_bits(&rec), true);
529         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
530         free(newdata);
531
532         return ret;
533
534 fail:
535         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
536         return -1;
537 }
538
539 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
540 {
541         tdb_off_t off;
542         struct tdb_used_record rec;
543         struct hash_info h;
544         struct tdb_data ret;
545
546         off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
547         if (unlikely(off == TDB_OFF_ERR))
548                 return tdb_null;
549
550         if (!off) {
551                 tdb->ecode = TDB_ERR_NOEXIST;
552                 ret = tdb_null;
553         } else {
554                 ret.dsize = rec_data_length(&rec);
555                 ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
556                                           ret.dsize);
557         }
558
559         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
560         return ret;
561 }
562
563 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
564 {
565         tdb_off_t off;
566         struct tdb_used_record rec;
567         struct hash_info h;
568
569         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
570         if (unlikely(off == TDB_OFF_ERR))
571                 return -1;
572
573         if (!off) {
574                 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
575                 tdb->ecode = TDB_ERR_NOEXIST;
576                 return -1;
577         }
578
579         if (delete_from_hash(tdb, &h) == -1)
580                 goto unlock_err;
581
582         /* Free the deleted entry. */
583         if (add_free_record(tdb, rec_zone_bits(&rec), off,
584                             sizeof(struct tdb_used_record)
585                             + rec_key_length(&rec)
586                             + rec_data_length(&rec)
587                             + rec_extra_padding(&rec)) != 0)
588                 goto unlock_err;
589
590         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
591         return 0;
592
593 unlock_err:
594         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
595         return -1;
596 }
597
598 int tdb_close(struct tdb_context *tdb)
599 {
600         struct tdb_context **i;
601         int ret = 0;
602
603         /* FIXME:
604         if (tdb->transaction) {
605                 tdb_transaction_cancel(tdb);
606         }
607         */
608         tdb_trace(tdb, "tdb_close");
609
610         if (tdb->map_ptr) {
611                 if (tdb->flags & TDB_INTERNAL)
612                         free(tdb->map_ptr);
613                 else
614                         tdb_munmap(tdb);
615         }
616         free((char *)tdb->name);
617         if (tdb->fd != -1) {
618                 ret = close(tdb->fd);
619                 tdb->fd = -1;
620         }
621         free(tdb->lockrecs);
622
623         /* Remove from contexts list */
624         for (i = &tdbs; *i; i = &(*i)->next) {
625                 if (*i == tdb) {
626                         *i = tdb->next;
627                         break;
628                 }
629         }
630
631 #ifdef TDB_TRACE
632         close(tdb->tracefd);
633 #endif
634         free(tdb);
635
636         return ret;
637 }
638
639 enum TDB_ERROR tdb_error(struct tdb_context *tdb)
640 {
641         return tdb->ecode;
642 }
643
644 const char *tdb_errorstr(struct tdb_context *tdb)
645 {
646         /* Gcc warns if you miss a case in the switch, so use that. */
647         switch (tdb->ecode) {
648         case TDB_SUCCESS: return "Success";
649         case TDB_ERR_CORRUPT: return "Corrupt database";
650         case TDB_ERR_IO: return "IO Error";
651         case TDB_ERR_LOCK: return "Locking error";
652         case TDB_ERR_OOM: return "Out of memory";
653         case TDB_ERR_EXISTS: return "Record exists";
654         case TDB_ERR_NESTING: return "Transaction already started";
655         case TDB_ERR_EINVAL: return "Invalid parameter";
656         case TDB_ERR_NOEXIST: return "Record does not exist";
657         case TDB_ERR_RDONLY: return "write not permitted";
658         }
659         return "Invalid error code";
660 }