summaryrefslogtreecommitdiffstats
path: root/dnsdist-kvs.cc
blob: d20aa1e980ea35ea3cb8ff365a5aea147dd45a6f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/*
 * This file is part of PowerDNS or dnsdist.
 * Copyright -- PowerDNS.COM B.V. and its contributors
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * In addition, for the avoidance of any doubt, permission is granted to
 * link this program with OpenSSL and to (re)distribute the binaries
 * produced as the result of such linking.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "dnsdist-kvs.hh"
#include "dolog.hh"

#include <sys/stat.h>

std::vector<std::string> KeyValueLookupKeySourceIP::getKeys(const ComboAddress& addr)
{
  std::vector<std::string> result;
  ComboAddress truncated(addr);

  std::string key;
  if (truncated.isIPv4()) {
    truncated.truncate(d_v4Mask);
    key.reserve(sizeof(truncated.sin4.sin_addr.s_addr) + (d_includePort ? sizeof(truncated.sin4.sin_port) : 0));
    key.append(reinterpret_cast<const char*>(&truncated.sin4.sin_addr.s_addr), sizeof(truncated.sin4.sin_addr.s_addr));
  }
  else if (truncated.isIPv6()) {
    truncated.truncate(d_v6Mask);
    key.reserve(sizeof(truncated.sin6.sin6_addr.s6_addr) + (d_includePort ? sizeof(truncated.sin4.sin_port) : 0));
    key.append(reinterpret_cast<const char*>(&truncated.sin6.sin6_addr.s6_addr), sizeof(truncated.sin6.sin6_addr.s6_addr));
  }

  if (d_includePort) {
    key.append(reinterpret_cast<const char*>(&truncated.sin4.sin_port), sizeof(truncated.sin4.sin_port));
  }

  result.push_back(std::move(key));

  return result;
}

std::vector<std::string> KeyValueLookupKeySuffix::getKeys(const DNSName& qname)
{
  if (qname.empty() || qname.isRoot()) {
    return {};
  }

  auto lowerQName = qname.makeLowerCase();
  size_t labelsCount = lowerQName.countLabels();
  if (d_minLabels != 0) {
    if (labelsCount < d_minLabels) {
      return {};
    }
    labelsCount -= (d_minLabels - 1);
  }

  std::vector<std::string> result;
  result.reserve(labelsCount);

  while(!lowerQName.isRoot()) {
    result.emplace_back(d_wireFormat ? lowerQName.toDNSString() : lowerQName.toStringRootDot());
    labelsCount--;
    if (!lowerQName.chopOff() || labelsCount == 0) {
      break;
    }
  }

  return result;
}

#ifdef HAVE_LMDB

bool LMDBKVStore::getValue(const std::string& key, std::string& value)
{
  try {
    auto transaction = d_env.getROTransaction();
    MDBOutVal result;
    int rc = transaction->get(d_dbi, MDBInVal(key), result);
    if (rc == 0) {
      value = result.get<std::string>();
      return true;
    }
    else if (rc == MDB_NOTFOUND) {
      return false;
    }
  }
  catch (const std::exception& e) {
    vinfolog("Error while looking up key '%s' from LMDB file '%s', database '%s': %s", key, d_fname, d_dbName, e.what());
  }
  return false;
}

bool LMDBKVStore::keyExists(const std::string& key)
{
  try {
    auto transaction = d_env.getROTransaction();
    MDBOutVal result;
    int rc = transaction->get(d_dbi, MDBInVal(key), result);
    if (rc == 0) {
      return true;
    }
    else if (rc == MDB_NOTFOUND) {
      return false;
    }
  }
  catch (const std::exception& e) {
    vinfolog("Error while looking up key '%s' from LMDB file '%s', database '%s': %s", key, d_fname, d_dbName, e.what());
  }
  return false;
}

bool LMDBKVStore::getRangeValue(const std::string& key, std::string& value)
{
  try {
    auto transaction = d_env.getROTransaction();
    auto cursor = transaction->getROCursor(d_dbi);
    MDBOutVal actualKey;
    MDBOutVal result;
    // for range-based lookups, we expect the data in LMDB
    // to be stored with the last value of the range as key
    // and the first value of the range as data, sometimes
    // followed by any other content we don't care about
    // range-based lookups are mostly useful for network ranges,
    // for which we expect addresses to be stored in network byte
    // order

    // retrieve the first key greater or equal to our key
    int rc = cursor.lower_bound(MDBInVal(key), actualKey, result);

    if (rc == 0) {
      auto last = actualKey.get<std::string>();
      if (last.size() != key.size() || key > last) {
        return false;
      }

      value = result.get<std::string>();
      if (value.size() < key.size()) {
        return false;
      }

      // take the first part of the data, which should be
      // the first address of the range
      auto first = value.substr(0, key.size());
      if (first.size() != key.size() || key < first) {
        return false;
      }

      return true;
    }
    else if (rc == MDB_NOTFOUND) {
      return false;
    }
  }
  catch (const std::exception& e) {
    vinfolog("Error while looking up a range from LMDB file '%s', database '%s': %s", d_fname, d_dbName, e.what());
  }
  return false;
}

#endif /* HAVE_LMDB */

#ifdef HAVE_CDB

CDBKVStore::CDBKVStore(const std::string& fname, time_t refreshDelay): d_fname(fname), d_refreshDelay(refreshDelay)
{
  d_refreshing.clear();

  time_t now = time(nullptr);
  if (d_refreshDelay > 0) {
    d_nextCheck = now + d_refreshDelay;
  }

  refreshDBIfNeeded(now);
}

CDBKVStore::~CDBKVStore() {
}

bool CDBKVStore::reload(const struct stat& st)
{
  auto newCDB = std::make_unique<CDB>(d_fname);
  {
    *(d_cdb.write_lock()) = std::move(newCDB);
  }
  d_mtime = st.st_mtime;
  return true;
}

bool CDBKVStore::reload()
{
  struct stat st;
  if (stat(d_fname.c_str(), &st) == 0) {
    return reload(st);
  }
  else {
    warnlog("Error while retrieving the last modification time of CDB database '%s': %s", d_fname, stringerror());
    return false;
  }
}

void CDBKVStore::refreshDBIfNeeded(time_t now)
{
  if (d_refreshing.test_and_set()) {
    /* someone else is already refreshing */
    return;
  }

  try {
    struct stat st;
    if (stat(d_fname.c_str(), &st) == 0) {
      if (st.st_mtime > d_mtime) {
        reload(st);
      }
    }
    else {
      warnlog("Error while retrieving the last modification time of CDB database '%s': %s", d_fname, stringerror());
    }
    d_nextCheck = now + d_refreshDelay;
    d_refreshing.clear();
  }
  catch (...) {
    d_refreshing.clear();
    throw;
  }
}

bool CDBKVStore::getValue(const std::string& key, std::string& value)
{
  time_t now = time(nullptr);

  try {
    if (d_nextCheck != 0 && now >= d_nextCheck) {
      refreshDBIfNeeded(now);
    }

    {
      auto cdb = d_cdb.read_lock();
      if (*cdb && (*cdb)->findOne(key, value)) {
        return true;
      }
    }
  }
  catch (const std::exception& e) {
    vinfolog("Error while looking up key '%s' from CDB file '%s': %s", key, d_fname, e.what());
  }
  return false;
}

bool CDBKVStore::keyExists(const std::string& key)
{
  time_t now = time(nullptr);

  try {
    if (d_nextCheck != 0 && now >= d_nextCheck) {
      refreshDBIfNeeded(now);
    }

    {
      auto cdb = d_cdb.read_lock();
      if (!*cdb) {
        return false;
      }

      return (*cdb)->keyExists(key);
    }
  }
  catch (const std::exception& e) {
    vinfolog("Error while looking up key '%s' from CDB file '%s': %s", key, d_fname, e.what());
  }
  return false;
}

#endif /* HAVE_CDB */