tdb: unify logging code in test dir.
[ccan] / ccan / tdb / test / run-bad-tdb-header.c
1 #define _XOPEN_SOURCE 500
2 #include <ccan/tdb/tdb.h>
3 #include <ccan/tdb/io.c>
4 #include <ccan/tdb/tdb.c>
5 #include <ccan/tdb/lock.c>
6 #include <ccan/tdb/freelist.c>
7 #include <ccan/tdb/traverse.c>
8 #include <ccan/tdb/transaction.c>
9 #include <ccan/tdb/error.c>
10 #include <ccan/tdb/open.c>
11 #include <ccan/tdb/check.c>
12 #include <ccan/tap/tap.h>
13 #include <stdlib.h>
14 #include <err.h>
15 #include "logging.h"
16
17 int main(int argc, char *argv[])
18 {
19         struct tdb_context *tdb;
20         struct tdb_header hdr;
21         int fd;
22
23         plan_tests(11);
24         /* Can open fine if complete crap, as long as O_CREAT. */
25         fd = open("run-bad-tdb-header.tdb", O_RDWR|O_CREAT|O_TRUNC, 0600);
26         ok1(fd >= 0);
27         ok1(write(fd, "hello world", 11) == 11);
28         close(fd);
29         tdb = tdb_open_ex("run-bad-tdb-header.tdb", 1024, 0, O_RDWR, 0,
30                           &taplogctx, NULL);
31         ok1(!tdb);
32         tdb = tdb_open_ex("run-bad-tdb-header.tdb", 1024, 0, O_CREAT|O_RDWR,
33                           0600, &taplogctx, NULL);
34         ok1(tdb);
35         tdb_close(tdb);
36
37         /* Now, with wrong version it should *not* overwrite. */
38         fd = open("run-bad-tdb-header.tdb", O_RDWR);
39         ok1(fd >= 0);
40         ok1(read(fd, &hdr, sizeof(hdr)) == sizeof(hdr));
41         ok1(hdr.version == TDB_VERSION);
42         hdr.version++;
43         lseek(fd, 0, SEEK_SET);
44         ok1(write(fd, &hdr, sizeof(hdr)) == sizeof(hdr));
45         close(fd);
46
47         tdb = tdb_open_ex("run-bad-tdb-header.tdb", 1024, 0, O_RDWR|O_CREAT,
48                           0600, &taplogctx, NULL);
49         ok1(errno == EIO);
50         ok1(!tdb);
51
52         /* With truncate, will be fine. */
53         tdb = tdb_open_ex("run-bad-tdb-header.tdb", 1024, 0,
54                           O_RDWR|O_CREAT|O_TRUNC, 0600, &taplogctx, NULL);
55         ok1(tdb);
56         tdb_close(tdb);
57
58         return exit_status();
59 }