1 /* Simple program to dump out all records of TDB */
2 #include <stdint.h>
3 #include <stdlib.h>
4 #include <fcntl.h>
5 #include <stdio.h>
6 #include <stdarg.h>
7 #include <string.h>
8 #include <sys/types.h>
9 #include "xenstore_lib.h"
10 #include "tdb.h"
11 #include "talloc.h"
12 #include "utils.h"
13 
total_size(struct xs_tdb_record_hdr * hdr)14 static uint32_t total_size(struct xs_tdb_record_hdr *hdr)
15 {
16 	return sizeof(*hdr) + hdr->num_perms * sizeof(struct xs_permissions)
17 		+ hdr->datalen + hdr->childlen;
18 }
19 
perm_to_char(enum xs_perm_type perm)20 static char perm_to_char(enum xs_perm_type perm)
21 {
22 	return perm == XS_PERM_READ ? 'r' :
23 		perm == XS_PERM_WRITE ? 'w' :
24 		perm == XS_PERM_NONE ? '-' :
25 		perm == (XS_PERM_READ|XS_PERM_WRITE) ? 'b' :
26 		'?';
27 }
28 
tdb_logger(TDB_CONTEXT * tdb,int level,const char * fmt,...)29 static void tdb_logger(TDB_CONTEXT *tdb, int level, const char * fmt, ...)
30 {
31 	va_list ap;
32 
33 	va_start(ap, fmt);
34 	vfprintf(stderr, fmt, ap);
35 	va_end(ap);
36 }
37 
main(int argc,char * argv[])38 int main(int argc, char *argv[])
39 {
40 	TDB_DATA key;
41 	TDB_CONTEXT *tdb;
42 
43 	if (argc != 2)
44 		barf("Usage: xs_tdb_dump <tdbfile>");
45 
46 	tdb = tdb_open_ex(talloc_strdup(NULL, argv[1]), 0, 0, O_RDONLY, 0,
47 			  &tdb_logger, NULL);
48 	if (!tdb)
49 		barf_perror("Could not open %s", argv[1]);
50 
51 	key = tdb_firstkey(tdb);
52 	while (key.dptr) {
53 		TDB_DATA data;
54 		struct xs_tdb_record_hdr *hdr;
55 
56 		data = tdb_fetch(tdb, key);
57 		hdr = (void *)data.dptr;
58 		if (data.dsize < sizeof(*hdr))
59 			fprintf(stderr, "%.*s: BAD truncated\n",
60 				(int)key.dsize, key.dptr);
61 		else if (data.dsize != total_size(hdr))
62 			fprintf(stderr, "%.*s: BAD length %i for %i/%i/%i (%i)\n",
63 				(int)key.dsize, key.dptr, (int)data.dsize,
64 				hdr->num_perms, hdr->datalen,
65 				hdr->childlen, total_size(hdr));
66 		else {
67 			unsigned int i;
68 			char *p;
69 
70 			printf("%.*s: ", (int)key.dsize, key.dptr);
71 			for (i = 0; i < hdr->num_perms; i++)
72 				printf("%s%c%i",
73 				       i == 0 ? "" : ",",
74 				       perm_to_char(hdr->perms[i].perms),
75 				       hdr->perms[i].id);
76 			p = (void *)&hdr->perms[hdr->num_perms];
77 			printf(" %.*s\n", hdr->datalen, p);
78 			p += hdr->datalen;
79 			for (i = 0; i < hdr->childlen; i += strlen(p+i)+1)
80 				printf("\t-> %s\n", p+i);
81 		}
82 		key = tdb_nextkey(tdb, key);
83 	}
84 	return 0;
85 }
86 
87