c0561fb9fe1f2511797aa5604d368721a3a57f61
[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         struct tdb_freelist flist;
84 };
85
86 /* initialise a new database */
87 static int 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
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         memset(newdb.hdr.reserved, 0, sizeof(newdb.hdr.reserved));
107         /* Initial hashes are empty. */
108         memset(newdb.hdr.hashtable, 0, sizeof(newdb.hdr.hashtable));
109
110         /* Free is empty. */
111         newdb.hdr.free_list = offsetof(struct new_database, flist);
112         memset(&newdb.flist, 0, sizeof(newdb.flist));
113         set_header(NULL, &newdb.flist.hdr, 0,
114                    sizeof(newdb.flist.buckets), sizeof(newdb.flist.buckets), 1);
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         tdb_io_init(tdb);
180         tdb_lock_init(tdb);
181
182         while (attr) {
183                 switch (attr->base.attr) {
184                 case TDB_ATTRIBUTE_LOG:
185                         tdb->log = attr->log.log_fn;
186                         tdb->log_priv = attr->log.log_private;
187                         break;
188                 case TDB_ATTRIBUTE_HASH:
189                         tdb->khash = attr->hash.hash_fn;
190                         tdb->hash_priv = attr->hash.hash_private;
191                         break;
192                 case TDB_ATTRIBUTE_SEED:
193                         seed = &attr->seed;
194                         break;
195                 default:
196                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
197                                  "tdb_open: unknown attribute type %u\n",
198                                  attr->base.attr);
199                         errno = EINVAL;
200                         goto fail;
201                 }
202                 attr = attr->base.next;
203         }
204
205         if ((open_flags & O_ACCMODE) == O_WRONLY) {
206                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
207                          "tdb_open: can't open tdb %s write-only\n", name);
208                 errno = EINVAL;
209                 goto fail;
210         }
211
212         if ((open_flags & O_ACCMODE) == O_RDONLY) {
213                 tdb->read_only = true;
214                 /* read only databases don't do locking */
215                 tdb->flags |= TDB_NOLOCK;
216                 tdb->mmap_flags = PROT_READ;
217         } else {
218                 tdb->read_only = false;
219                 tdb->mmap_flags = PROT_READ | PROT_WRITE;
220         }
221
222         /* internal databases don't need any of the rest. */
223         if (tdb->flags & TDB_INTERNAL) {
224                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
225                 if (tdb_new_database(tdb, seed, &hdr) != 0) {
226                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
227                                  "tdb_open: tdb_new_database failed!");
228                         goto fail;
229                 }
230                 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
231                 tdb->hash_seed = hdr.hash_seed;
232                 tdb_flist_init(tdb);
233                 return tdb;
234         }
235
236         if ((tdb->fd = open(name, open_flags, mode)) == -1) {
237                 tdb->log(tdb, TDB_DEBUG_WARNING, tdb->log_priv,
238                          "tdb_open: could not open file %s: %s\n",
239                          name, strerror(errno));
240                 goto fail;      /* errno set by open(2) */
241         }
242
243         /* on exec, don't inherit the fd */
244         v = fcntl(tdb->fd, F_GETFD, 0);
245         fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
246
247         /* ensure there is only one process initialising at once */
248         if (tdb_lock_open(tdb) == -1) {
249                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
250                          "tdb_open: failed to get open lock on %s: %s\n",
251                          name, strerror(errno));
252                 goto fail;      /* errno set by tdb_brlock */
253         }
254
255         if (!tdb_pread_all(tdb->fd, &hdr, sizeof(hdr), 0)
256             || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
257                 if (!(open_flags & O_CREAT)
258                     || tdb_new_database(tdb, seed, &hdr) == -1) {
259                         if (errno == 0) {
260                                 errno = EIO; /* ie bad format or something */
261                         }
262                         goto fail;
263                 }
264         } else if (hdr.version != TDB_VERSION) {
265                 if (hdr.version == bswap_64(TDB_VERSION))
266                         tdb->flags |= TDB_CONVERT;
267                 else {
268                         /* wrong version */
269                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
270                                  "tdb_open: %s is unknown version 0x%llx\n",
271                                  name, (long long)hdr.version);
272                         errno = EIO;
273                         goto fail;
274                 }
275         }
276
277         tdb_convert(tdb, &hdr, sizeof(hdr));
278         tdb->hash_seed = hdr.hash_seed;
279         hash_test = TDB_HASH_MAGIC;
280         hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
281         if (hdr.hash_test != hash_test) {
282                 /* wrong hash variant */
283                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
284                          "tdb_open: %s uses a different hash function\n",
285                          name);
286                 errno = EIO;
287                 goto fail;
288         }
289
290         if (fstat(tdb->fd, &st) == -1)
291                 goto fail;
292
293         /* Is it already in the open list?  If so, fail. */
294         if (tdb_already_open(st.st_dev, st.st_ino)) {
295                 /* FIXME */
296                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
297                          "tdb_open: %s (%d,%d) is already open in this process\n",
298                          name, (int)st.st_dev, (int)st.st_ino);
299                 errno = EBUSY;
300                 goto fail;
301         }
302
303         tdb->name = strdup(name);
304         if (!tdb->name) {
305                 errno = ENOMEM;
306                 goto fail;
307         }
308
309         tdb->device = st.st_dev;
310         tdb->inode = st.st_ino;
311         tdb_unlock_open(tdb);
312
313         /* This make sure we have current map_size and mmap. */
314         tdb->methods->oob(tdb, tdb->map_size + 1, true);
315
316         if (tdb_flist_init(tdb) == -1)
317                 goto fail;
318
319         tdb->next = tdbs;
320         tdbs = tdb;
321         return tdb;
322
323  fail:
324         save_errno = errno;
325
326         if (!tdb)
327                 return NULL;
328
329 #ifdef TDB_TRACE
330         close(tdb->tracefd);
331 #endif
332         if (tdb->map_ptr) {
333                 if (tdb->flags & TDB_INTERNAL) {
334                         free(tdb->map_ptr);
335                 } else
336                         tdb_munmap(tdb);
337         }
338         free((char *)tdb->name);
339         if (tdb->fd != -1)
340                 if (close(tdb->fd) != 0)
341                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
342                                  "tdb_open: failed to close tdb->fd"
343                                  " on error!\n");
344         free(tdb);
345         errno = save_errno;
346         return NULL;
347 }
348
349 /* FIXME: modify, don't rewrite! */
350 static int update_rec_hdr(struct tdb_context *tdb,
351                           tdb_off_t off,
352                           tdb_len_t keylen,
353                           tdb_len_t datalen,
354                           struct tdb_used_record *rec,
355                           uint64_t h)
356 {
357         uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
358
359         if (set_header(tdb, rec, keylen, datalen, keylen + dataroom, h))
360                 return -1;
361
362         return tdb_write_convert(tdb, off, rec, sizeof(*rec));
363 }
364
365 /* Returns -1 on error, 0 on OK */
366 static int replace_data(struct tdb_context *tdb,
367                         struct hash_info *h,
368                         struct tdb_data key, struct tdb_data dbuf,
369                         tdb_off_t old_off, tdb_len_t old_room,
370                         bool growing)
371 {
372         tdb_off_t new_off;
373
374         /* Allocate a new record. */
375         new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, growing);
376         if (unlikely(new_off == TDB_OFF_ERR))
377                 return -1;
378
379         /* We didn't like the existing one: remove it. */
380         if (old_off) {
381                 add_free_record(tdb, old_off,
382                                 sizeof(struct tdb_used_record)
383                                 + key.dsize + old_room);
384                 if (replace_in_hash(tdb, h, new_off) == -1)
385                         return -1;
386         } else {
387                 if (add_to_hash(tdb, h, new_off) == -1)
388                         return -1;
389         }
390
391         new_off += sizeof(struct tdb_used_record);
392         if (tdb->methods->write(tdb, new_off, key.dptr, key.dsize) == -1)
393                 return -1;
394
395         new_off += key.dsize;
396         if (tdb->methods->write(tdb, new_off, dbuf.dptr, dbuf.dsize) == -1)
397                 return -1;
398
399         /* FIXME: tdb_increment_seqnum(tdb); */
400         return 0;
401 }
402
403 int tdb_store(struct tdb_context *tdb,
404               struct tdb_data key, struct tdb_data dbuf, int flag)
405 {
406         struct hash_info h;
407         tdb_off_t off;
408         tdb_len_t old_room = 0;
409         struct tdb_used_record rec;
410         int ret;
411
412         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
413         if (unlikely(off == TDB_OFF_ERR))
414                 return -1;
415
416         /* Now we have lock on this hash bucket. */
417         if (flag == TDB_INSERT) {
418                 if (off) {
419                         tdb->ecode = TDB_ERR_EXISTS;
420                         goto fail;
421                 }
422         } else {
423                 if (off) {
424                         old_room = rec_data_length(&rec)
425                                 + rec_extra_padding(&rec);
426                         if (old_room >= dbuf.dsize) {
427                                 /* Can modify in-place.  Easy! */
428                                 if (update_rec_hdr(tdb, off,
429                                                    key.dsize, dbuf.dsize,
430                                                    &rec, h.h))
431                                         goto fail;
432                                 if (tdb->methods->write(tdb, off + sizeof(rec)
433                                                         + key.dsize,
434                                                         dbuf.dptr, dbuf.dsize))
435                                         goto fail;
436                                 tdb_unlock_hashes(tdb, h.hlock_start,
437                                                   h.hlock_range, F_WRLCK);
438                                 return 0;
439                         }
440                         /* FIXME: See if right record is free? */
441                 } else {
442                         if (flag == TDB_MODIFY) {
443                                 /* if the record doesn't exist and we
444                                    are in TDB_MODIFY mode then we should fail
445                                    the store */
446                                 tdb->ecode = TDB_ERR_NOEXIST;
447                                 goto fail;
448                         }
449                 }
450         }
451
452         /* If we didn't use the old record, this implies we're growing. */
453         ret = replace_data(tdb, &h, key, dbuf, off, old_room, off != 0);
454         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
455         return ret;
456
457 fail:
458         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
459         return -1;
460 }
461
462 int tdb_append(struct tdb_context *tdb,
463                struct tdb_data key, struct tdb_data dbuf)
464 {
465         struct hash_info h;
466         tdb_off_t off;
467         struct tdb_used_record rec;
468         tdb_len_t old_room = 0, old_dlen;
469         unsigned char *newdata;
470         struct tdb_data new_dbuf;
471         int ret;
472
473         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
474         if (unlikely(off == TDB_OFF_ERR))
475                 return -1;
476
477         if (off) {
478                 old_dlen = rec_data_length(&rec);
479                 old_room = old_dlen + rec_extra_padding(&rec);
480
481                 /* Fast path: can append in place. */
482                 if (rec_extra_padding(&rec) >= dbuf.dsize) {
483                         if (update_rec_hdr(tdb, off, key.dsize,
484                                            old_dlen + dbuf.dsize, &rec, h.h))
485                                 goto fail;
486
487                         off += sizeof(rec) + key.dsize + old_dlen;
488                         if (tdb->methods->write(tdb, off, dbuf.dptr,
489                                                 dbuf.dsize) == -1)
490                                 goto fail;
491
492                         /* FIXME: tdb_increment_seqnum(tdb); */
493                         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range,
494                                           F_WRLCK);
495                         return 0;
496                 }
497                 /* FIXME: Check right record free? */
498
499                 /* Slow path. */
500                 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
501                 if (!newdata) {
502                         tdb->ecode = TDB_ERR_OOM;
503                         tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
504                                  "tdb_append: cannot allocate %llu bytes!\n",
505                                  (long long)key.dsize + old_dlen + dbuf.dsize);
506                         goto fail;
507                 }
508                 if (tdb->methods->read(tdb, off + sizeof(rec) + key.dsize,
509                                        newdata, old_dlen) != 0) {
510                         free(newdata);
511                         goto fail;
512                 }
513                 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
514                 new_dbuf.dptr = newdata;
515                 new_dbuf.dsize = old_dlen + dbuf.dsize;
516         } else {
517                 newdata = NULL;
518                 new_dbuf = dbuf;
519         }
520
521         /* If they're using tdb_append(), it implies they're growing record. */
522         ret = replace_data(tdb, &h, key, new_dbuf, off, old_room, true);
523         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
524         free(newdata);
525
526         return ret;
527
528 fail:
529         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
530         return -1;
531 }
532
533 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
534 {
535         tdb_off_t off;
536         struct tdb_used_record rec;
537         struct hash_info h;
538         struct tdb_data ret;
539
540         off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
541         if (unlikely(off == TDB_OFF_ERR))
542                 return tdb_null;
543
544         if (!off) {
545                 tdb->ecode = TDB_ERR_NOEXIST;
546                 ret = tdb_null;
547         } else {
548                 ret.dsize = rec_data_length(&rec);
549                 ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
550                                           ret.dsize);
551         }
552
553         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
554         return ret;
555 }
556
557 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
558 {
559         tdb_off_t off;
560         struct tdb_used_record rec;
561         struct hash_info h;
562
563         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
564         if (unlikely(off == TDB_OFF_ERR))
565                 return -1;
566
567         if (!off) {
568                 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
569                 tdb->ecode = TDB_ERR_NOEXIST;
570                 return -1;
571         }
572
573         if (delete_from_hash(tdb, &h) == -1)
574                 goto unlock_err;
575
576         /* Free the deleted entry. */
577         if (add_free_record(tdb, off,
578                             sizeof(struct tdb_used_record)
579                             + rec_key_length(&rec)
580                             + rec_data_length(&rec)
581                             + rec_extra_padding(&rec)) != 0)
582                 goto unlock_err;
583
584         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
585         return 0;
586
587 unlock_err:
588         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
589         return -1;
590 }
591
592 int tdb_close(struct tdb_context *tdb)
593 {
594         struct tdb_context **i;
595         int ret = 0;
596
597         /* FIXME:
598         if (tdb->transaction) {
599                 tdb_transaction_cancel(tdb);
600         }
601         */
602         tdb_trace(tdb, "tdb_close");
603
604         if (tdb->map_ptr) {
605                 if (tdb->flags & TDB_INTERNAL)
606                         free(tdb->map_ptr);
607                 else
608                         tdb_munmap(tdb);
609         }
610         free((char *)tdb->name);
611         if (tdb->fd != -1) {
612                 ret = close(tdb->fd);
613                 tdb->fd = -1;
614         }
615         free(tdb->lockrecs);
616
617         /* Remove from contexts list */
618         for (i = &tdbs; *i; i = &(*i)->next) {
619                 if (*i == tdb) {
620                         *i = tdb->next;
621                         break;
622                 }
623         }
624
625 #ifdef TDB_TRACE
626         close(tdb->tracefd);
627 #endif
628         free(tdb);
629
630         return ret;
631 }
632
633 enum TDB_ERROR tdb_error(struct tdb_context *tdb)
634 {
635         return tdb->ecode;
636 }
637
638 const char *tdb_errorstr(struct tdb_context *tdb)
639 {
640         /* Gcc warns if you miss a case in the switch, so use that. */
641         switch (tdb->ecode) {
642         case TDB_SUCCESS: return "Success";
643         case TDB_ERR_CORRUPT: return "Corrupt database";
644         case TDB_ERR_IO: return "IO Error";
645         case TDB_ERR_LOCK: return "Locking error";
646         case TDB_ERR_OOM: return "Out of memory";
647         case TDB_ERR_EXISTS: return "Record exists";
648         case TDB_ERR_NESTING: return "Transaction already started";
649         case TDB_ERR_EINVAL: return "Invalid parameter";
650         case TDB_ERR_NOEXIST: return "Record does not exist";
651         case TDB_ERR_RDONLY: return "write not permitted";
652         }
653         return "Invalid error code";
654 }