]>
git.ipfire.org Git - thirdparty/pdns.git/blob - modules/tinydnsbackend/cdb.cc
e6d1e7b43e21968692138a623d2c8d09873caff6
6 #include "pdns/misc.hh"
7 #include "pdns/iputils.hh"
11 CDB::CDB(const string
&cdbfile
)
13 d_fd
= open(cdbfile
.c_str(), O_RDONLY
);
16 L
<<Logger::Error
<<"Failed to open cdb database file '"<<cdbfile
<<"'. Error: "<<stringerror()<<endl
;
17 throw new PDNSException("Failed to open cdb database file '"+cdbfile
+"'. Error: " + stringerror());
20 memset(&d_cdbf
,0,sizeof(struct cdb_find
));
21 int cdbinit
= cdb_init(&d_cdb
, d_fd
);
24 L
<<Logger::Error
<<"Failed to initialize cdb structure. ErrorNr: '"<<cdbinit
<<endl
;
25 throw new PDNSException("Failed to initialize cdb structure.");
30 d_searchType
= SearchKey
;
38 int CDB::searchKey(const string
&key
) {
39 d_searchType
= SearchKey
;
41 // A 'bug' in tinycdb (the lib used for reading the CDB files) means we have to copy the key because the cdb_find struct
42 // keeps a pointer to it.
43 d_key
= strdup(key
.c_str());
44 return cdb_findinit(&d_cdbf
, &d_cdb
, d_key
, key
.size());
47 bool CDB::searchSuffix(const string
&key
) {
48 d_searchType
= SearchSuffix
;
50 //See CDB::searchKey()
51 d_key
= strdup(key
.c_str());
53 // We are ok with a search on things, but we do want to know if a record with that key exists.........
54 bool hasDomain
= (cdb_find(&d_cdb
, key
.c_str(), key
.size()) == 1);
56 cdb_seqinit(&d_seqPtr
, &d_cdb
);
62 void CDB::searchAll() {
63 d_searchType
= SearchAll
;
64 cdb_seqinit(&d_seqPtr
, &d_cdb
);
67 bool CDB::moveToNext() {
69 if (d_searchType
== SearchKey
) {
70 hasNext
= cdb_findnext(&d_cdbf
);
72 hasNext
= cdb_seqnext(&d_seqPtr
, &d_cdb
);
77 bool CDB::readNext(pair
<string
, string
> &value
) {
78 while (moveToNext()) {
82 pos
= cdb_keypos(&d_cdb
);
83 len
= cdb_keylen(&d_cdb
);
85 char *key
= (char *)malloc(len
);
86 cdb_read(&d_cdb
, key
, len
, pos
);
88 if (d_searchType
== SearchSuffix
) {
89 char *p
= strstr(key
, d_key
);
95 string
skey(key
, len
);
98 pos
= cdb_datapos(&d_cdb
);
99 len
= cdb_datalen(&d_cdb
);
100 char *val
= (char *)malloc(len
);
101 cdb_read(&d_cdb
, val
, len
, pos
);
102 string
sval(val
, len
);
105 value
= make_pair(skey
, sval
);
108 // We're done searching, so we can clean up d_key
109 if (d_searchType
!= SearchAll
) {
115 vector
<string
> CDB::findall(string
&key
)
118 struct cdb_find cdbf
;
120 cdb_findinit(&cdbf
, &d_cdb
, key
.c_str(), key
.size());
122 while(cdb_findnext(&cdbf
) > 0) {
124 unsigned int vpos
= cdb_datapos(&d_cdb
);
125 unsigned int vlen
= cdb_datalen(&d_cdb
);
126 char *val
= (char *)malloc(vlen
);
127 cdb_read(&d_cdb
, val
, vlen
, vpos
);
128 string
sval(val
, vlen
);