• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PowerDNS / pdns / 17089486438

20 Aug 2025 05:31AM UTC coverage: 64.683% (-1.2%) from 65.866%
17089486438

push

github

web-flow
Merge pull request #15991 from omoerbeek/boost-fix-system-lib-dep

Fix Boost system lib req: it is no longer a lib for boost >= 1.89

40936 of 91910 branches covered (44.54%)

Branch coverage included in aggregate %.

124729 of 164210 relevant lines covered (75.96%)

4764249.21 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/modules/remotebackend/httpconnector.cc
1
/*
2
 * This file is part of PowerDNS or dnsdist.
3
 * Copyright -- PowerDNS.COM B.V. and its contributors
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of version 2 of the GNU General Public License as
7
 * published by the Free Software Foundation.
8
 *
9
 * In addition, for the avoidance of any doubt, permission is granted to
10
 * link this program with OpenSSL and to (re)distribute the binaries
11
 * produced as the result of such linking.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
 */
22
#ifdef HAVE_CONFIG_H
23
#include "config.h"
24
#endif
25
#include "remotebackend.hh"
26
#include <sys/socket.h>
27
#include <unistd.h>
28
#include <fcntl.h>
29

30
#include <sstream>
31
#include "pdns/lock.hh"
32

33
#ifndef UNIX_PATH_MAX
34
#define UNIX_PATH_MAX 108
35
#endif
36

37
HTTPConnector::HTTPConnector(std::map<std::string, std::string> options) :
38
  d_socket(nullptr)
39
{
×
40

41
  if (options.find("url") == options.end()) {
×
42
    throw PDNSException("Cannot find 'url' option in the remote backend HTTP connector's parameters");
×
43
  }
×
44

45
  this->d_url = options.find("url")->second;
×
46

47
  try {
×
48
    YaHTTP::URL url(d_url);
×
49
    d_host = url.host;
×
50
    d_port = url.port;
×
51
  }
×
52
  catch (const std::exception& e) {
×
53
    throw PDNSException("Error parsing the 'url' option provided to the remote backend HTTP connector: " + std::string(e.what()));
×
54
  }
×
55

56
  if (options.find("url-suffix") != options.end()) {
×
57
    this->d_url_suffix = options.find("url-suffix")->second;
×
58
  }
×
59
  else {
×
60
    this->d_url_suffix = "";
×
61
  }
×
62
  this->timeout = 2;
×
63
  this->d_post = false;
×
64
  this->d_post_json = false;
×
65

66
  if (options.find("timeout") != options.end()) {
×
67
    this->timeout = std::stoi(options.find("timeout")->second) / 1000;
×
68
  }
×
69
  if (options.find("post") != options.end()) {
×
70
    std::string val = options.find("post")->second;
×
71
    if (val == "yes" || val == "true" || val == "on" || val == "1") {
×
72
      this->d_post = true;
×
73
    }
×
74
  }
×
75
  if (options.find("post_json") != options.end()) {
×
76
    std::string val = options.find("post_json")->second;
×
77
    if (val == "yes" || val == "true" || val == "on" || val == "1") {
×
78
      this->d_post_json = true;
×
79
    }
×
80
  }
×
81
}
×
82

83
HTTPConnector::~HTTPConnector() = default;
×
84

85
void HTTPConnector::addUrlComponent(const Json& parameters, const string& element, std::stringstream& ss)
86
{
×
87
  std::string sparam;
×
88
  if (parameters[element] != Json()) {
×
89
    ss << "/" << YaHTTP::Utility::encodeURL(asString(parameters[element]), false);
×
90
  }
×
91
}
×
92

93
std::string HTTPConnector::buildMemberListArgs(const std::string& prefix, const Json& args)
94
{
×
95
  std::stringstream stream;
×
96

97
  for (const auto& pair : args.object_items()) {
×
98
    stream << prefix << "[" << YaHTTP::Utility::encodeURL(pair.first, false) << "]=";
×
99
    if (pair.second.is_bool()) {
×
100
      stream << (pair.second.bool_value() ? "1" : "0");
×
101
    }
×
102
    else if (!pair.second.is_null()) {
×
103
      stream << YaHTTP::Utility::encodeURL(HTTPConnector::asString(pair.second), false);
×
104
    }
×
105
    stream << "&";
×
106
  }
×
107

108
  return stream.str().substr(0, stream.str().size() - 1); // snip the trailing &
×
109
}
×
110

111
// builds our request (near-restful)
112
void HTTPConnector::restful_requestbuilder(const std::string& method, const Json& parameters, YaHTTP::Request& req)
113
{
×
114
  std::stringstream ss;
×
115
  std::string sparam;
×
116
  std::string verb;
×
117

118
  // special names are qname, name, zonename, kind, others go to headers
119

120
  ss << d_url;
×
121

122
  ss << "/" << method;
×
123

124
  // add the url components, if found, in following order.
125
  // id must be first due to the fact that the qname/name can be empty
126

127
  addUrlComponent(parameters, "id", ss);
×
128
  addUrlComponent(parameters, "domain_id", ss);
×
129
  addUrlComponent(parameters, "zonename", ss);
×
130
  addUrlComponent(parameters, "qname", ss);
×
131
  addUrlComponent(parameters, "name", ss);
×
132
  addUrlComponent(parameters, "kind", ss);
×
133
  addUrlComponent(parameters, "qtype", ss);
×
134

135
  // set the correct type of request based on method
136
  if (method == "activateDomainKey" || method == "deactivateDomainKey" || method == "publishDomainKey" || method == "unpublishDomainKey") {
×
137
    // create an empty post
138
    req.preparePost();
×
139
    verb = "POST";
×
140
  }
×
141
  else if (method == "setTSIGKey") {
×
142
    req.POST()["algorithm"] = parameters["algorithm"].string_value();
×
143
    req.POST()["content"] = parameters["content"].string_value();
×
144
    req.preparePost();
×
145
    verb = "PATCH";
×
146
  }
×
147
  else if (method == "deleteTSIGKey") {
×
148
    verb = "DELETE";
×
149
  }
×
150
  else if (method == "addDomainKey") {
×
151
    const Json& param = parameters["key"];
×
152
    req.POST()["flags"] = asString(param["flags"]);
×
153
    req.POST()["active"] = (param["active"].bool_value() ? "1" : "0");
×
154
    req.POST()["published"] = (param["published"].bool_value() ? "1" : "0");
×
155
    req.POST()["content"] = param["content"].string_value();
×
156
    req.preparePost();
×
157
    verb = "PUT";
×
158
  }
×
159
  else if (method == "superMasterBackend") {
×
160
    std::stringstream ss2;
×
161
    addUrlComponent(parameters, "ip", ss);
×
162
    addUrlComponent(parameters, "domain", ss);
×
163
    // then we need to serialize rrset payload into POST
164
    for (size_t index = 0; index < parameters["nsset"].array_items().size(); index++) {
×
165
      ss2 << buildMemberListArgs("nsset[" + std::to_string(index) + "]", parameters["nsset"][index]) << "&";
×
166
    }
×
167
    req.body = ss2.str().substr(0, ss2.str().size() - 1);
×
168
    req.headers["content-type"] = "application/x-www-form-urlencoded; charset=utf-8";
×
169
    req.headers["content-length"] = std::to_string(req.body.size());
×
170
    verb = "POST";
×
171
  }
×
172
  else if (method == "createSlaveDomain") {
×
173
    addUrlComponent(parameters, "ip", ss);
×
174
    addUrlComponent(parameters, "domain", ss);
×
175
    if (!parameters["account"].is_null() && parameters["account"].is_string()) {
×
176
      req.POST()["account"] = parameters["account"].string_value();
×
177
    }
×
178
    req.preparePost();
×
179
    verb = "PUT";
×
180
  }
×
181
  else if (method == "replaceRRSet") {
×
182
    std::stringstream ss2;
×
183
    for (size_t index = 0; index < parameters["rrset"].array_items().size(); index++) {
×
184
      ss2 << buildMemberListArgs("rrset[" + std::to_string(index) + "]", parameters["rrset"][index]) << "&";
×
185
    }
×
186
    req.body = ss2.str().substr(0, ss2.str().size() - 1); // remove trailing &
×
187
    req.headers["content-type"] = "application/x-www-form-urlencoded; charset=utf-8";
×
188
    req.headers["content-length"] = std::to_string(req.body.size());
×
189
    verb = "PATCH";
×
190
  }
×
191
  else if (method == "feedRecord") {
×
192
    addUrlComponent(parameters, "trxid", ss);
×
193
    req.body = buildMemberListArgs("rr", parameters["rr"]);
×
194
    req.headers["content-type"] = "application/x-www-form-urlencoded; charset=utf-8";
×
195
    req.headers["content-length"] = std::to_string(req.body.size());
×
196
    verb = "PATCH";
×
197
  }
×
198
  else if (method == "feedEnts") {
×
199
    std::stringstream ss2;
×
200
    addUrlComponent(parameters, "trxid", ss);
×
201
    for (const auto& param : parameters["nonterm"].array_items()) {
×
202
      ss2 << "nonterm[]=" << YaHTTP::Utility::encodeURL(param.string_value(), false) << "&";
×
203
    }
×
204
    for (const auto& param : parameters["auth"].array_items()) {
×
205
      ss2 << "auth[]=" << (param["auth"].bool_value() ? "1" : "0") << "&";
×
206
    }
×
207
    req.body = ss2.str().substr(0, ss2.str().size() - 1);
×
208
    req.headers["content-type"] = "application/x-www-form-urlencoded; charset=utf-8";
×
209
    req.headers["content-length"] = std::to_string(req.body.size());
×
210
    verb = "PATCH";
×
211
  }
×
212
  else if (method == "feedEnts3") {
×
213
    std::stringstream ss2;
×
214
    addUrlComponent(parameters, "domain", ss);
×
215
    addUrlComponent(parameters, "trxid", ss);
×
216
    ss2 << "times=" << parameters["times"].int_value() << "&salt=" << YaHTTP::Utility::encodeURL(parameters["salt"].string_value(), false) << "&narrow=" << (parameters["narrow"].bool_value() ? 1 : 0) << "&";
×
217
    for (const auto& param : parameters["nonterm"].array_items()) {
×
218
      ss2 << "nonterm[]=" << YaHTTP::Utility::encodeURL(param.string_value(), false) << "&";
×
219
    }
×
220
    for (const auto& param : parameters["auth"].array_items()) {
×
221
      ss2 << "auth[]=" << (param["auth"].bool_value() ? "1" : "0") << "&";
×
222
    }
×
223
    req.body = ss2.str().substr(0, ss2.str().size() - 1);
×
224
    req.headers["content-type"] = "application/x-www-form-urlencoded; charset=utf-8";
×
225
    req.headers["content-length"] = std::to_string(req.body.size());
×
226
    verb = "PATCH";
×
227
  }
×
228
  else if (method == "startTransaction") {
×
229
    addUrlComponent(parameters, "domain", ss);
×
230
    addUrlComponent(parameters, "trxid", ss);
×
231
    req.preparePost();
×
232
    verb = "POST";
×
233
  }
×
234
  else if (method == "commitTransaction" || method == "abortTransaction") {
×
235
    addUrlComponent(parameters, "trxid", ss);
×
236
    req.preparePost();
×
237
    verb = "POST";
×
238
  }
×
239
  else if (method == "setDomainMetadata") {
×
240
    // copy all metadata values into post
241
    std::stringstream ss2;
×
242
    // this one has values too
243
    if (parameters["value"].is_array()) {
×
244
      for (const auto& val : parameters["value"].array_items()) {
×
245
        ss2 << "value[]=" << YaHTTP::Utility::encodeURL(val.string_value(), false) << "&";
×
246
      }
×
247
    }
×
248
    req.body = ss2.str().substr(0, ss2.str().size() - 1);
×
249
    req.headers["content-type"] = "application/x-www-form-urlencoded; charset=utf-8";
×
250
    req.headers["content-length"] = std::to_string(req.body.size());
×
251
    verb = "PATCH";
×
252
  }
×
253
  else if (method == "removeDomainKey") {
×
254
    // this one is delete
255
    verb = "DELETE";
×
256
  }
×
257
  else if (method == "setNotified") {
×
258
    req.POST()["serial"] = asString(parameters["serial"]);
×
259
    req.preparePost();
×
260
    verb = "PATCH";
×
261
  }
×
262
  else if (method == "setStale") {
×
263
    req.preparePost();
×
264
    verb = "PATCH";
×
265
  }
×
266
  else if (method == "setFresh") {
×
267
    req.preparePost();
×
268
    verb = "PATCH";
×
269
  }
×
270
  else if (method == "directBackendCmd") {
×
271
    req.POST()["query"] = parameters["query"].string_value();
×
272
    req.preparePost();
×
273
    verb = "POST";
×
274
  }
×
275
  else if (method == "searchRecords" || method == "searchComments") {
×
276
    req.GET()["pattern"] = parameters["pattern"].string_value();
×
277
    req.GET()["maxResults"] = std::to_string(parameters["maxResults"].int_value());
×
278
    verb = "GET";
×
279
  }
×
280
  else if (method == "getAllDomains") {
×
281
    req.GET()["includeDisabled"] = (parameters["include_disabled"].bool_value() ? "true" : "false");
×
282
    verb = "GET";
×
283
  }
×
284
  else {
×
285
    // perform normal get
286
    verb = "GET";
×
287
  }
×
288

289
  // put everything else into headers
290
  for (const auto& pair : parameters.object_items()) {
×
291
    std::string member = pair.first;
×
292
    // whitelist header parameters
293
    if ((member == "trxid" || member == "local" || member == "remote" || member == "real-remote" || member == "zone-id")) {
×
294
      std::string hdr = "x-remotebackend-" + member;
×
295
      req.headers[hdr] = asString(pair.second);
×
296
    }
×
297
  };
×
298

299
  // finally add suffix and store url
300
  ss << d_url_suffix;
×
301

302
  req.setup(verb, ss.str());
×
303
  req.headers["accept"] = "application/json";
×
304
}
×
305

306
void HTTPConnector::post_requestbuilder(const Json& input, YaHTTP::Request& req)
307
{
×
308
  if (this->d_post_json) {
×
309
    std::string out = input.dump();
×
310
    req.setup("POST", d_url);
×
311
    // simple case, POST JSON into url. nothing fancy.
312
    req.headers["Content-Type"] = "text/javascript; charset=utf-8";
×
313
    req.headers["Content-Length"] = std::to_string(out.size());
×
314
    req.headers["accept"] = "application/json";
×
315
    req.body = out;
×
316
  }
×
317
  else {
×
318
    std::stringstream url;
×
319
    std::stringstream content;
×
320
    // call url/method.suffix
321
    url << d_url << "/" << input["method"].string_value() << d_url_suffix;
×
322
    req.setup("POST", url.str());
×
323
    // then build content
324
    req.POST()["parameters"] = input["parameters"].dump();
×
325
    req.preparePost();
×
326
    req.headers["accept"] = "application/json";
×
327
  }
×
328
}
×
329

330
int HTTPConnector::send_message(const Json& input)
331
{
×
332
  int rv = 0;
×
333
  int ec = 0;
×
334
  int fd = 0;
×
335

336
  std::vector<std::string> members;
×
337
  std::string method;
×
338
  std::ostringstream out;
×
339

340
  // perform request
341
  YaHTTP::Request req;
×
342

343
  if (d_post) {
×
344
    post_requestbuilder(input, req);
×
345
  }
×
346
  else {
×
347
    restful_requestbuilder(input["method"].string_value(), input["parameters"], req);
×
348
  }
×
349

350
  rv = -1;
×
351
  req.headers["connection"] = "Keep-Alive"; // see if we can streamline requests (not needed, strictly speaking)
×
352

353
  out << req;
×
354

355
  // try sending with current socket, if it fails retry with new socket
356
  if (this->d_socket != nullptr) {
×
357
    fd = this->d_socket->getHandle();
×
358
    // there should be no data waiting
359
    if (waitForRWData(fd, true, 0, 1) < 1) {
×
360
      try {
×
361
        d_socket->writenWithTimeout(out.str().c_str(), out.str().size(), timeout);
×
362
        rv = 1;
×
363
      }
×
364
      catch (NetworkError& ne) {
×
365
        g_log << Logger::Error << "While writing to HTTP endpoint " << d_addr.toStringWithPort() << ": " << ne.what() << std::endl;
×
366
      }
×
367
      catch (...) {
×
368
        g_log << Logger::Error << "While writing to HTTP endpoint " << d_addr.toStringWithPort() << ": exception caught" << std::endl;
×
369
      }
×
370
    }
×
371
  }
×
372

373
  if (rv == 1) {
×
374
    return rv;
×
375
  }
×
376

377
  this->d_socket.reset();
×
378

379
  // connect using tcp
380
  struct addrinfo* gAddr = nullptr;
×
381
  struct addrinfo* gAddrPtr = nullptr;
×
382
  struct addrinfo hints{};
×
383
  std::string sPort = std::to_string(d_port);
×
384
  memset(&hints, 0, sizeof hints);
×
385
  hints.ai_family = AF_UNSPEC;
×
386
  hints.ai_flags = AI_ADDRCONFIG;
×
387
  hints.ai_socktype = SOCK_STREAM;
×
388
  hints.ai_protocol = IPPROTO_TCP;
×
389
  if ((ec = getaddrinfo(d_host.c_str(), sPort.c_str(), &hints, &gAddr)) == 0) {
×
390
    // try to connect to each address.
391
    gAddrPtr = gAddr;
×
392

393
    while (gAddrPtr != nullptr) {
×
394
      try {
×
395
        d_socket = std::make_unique<Socket>(gAddrPtr->ai_family, gAddrPtr->ai_socktype, gAddrPtr->ai_protocol);
×
396
        d_addr.setSockaddr(gAddrPtr->ai_addr, gAddrPtr->ai_addrlen);
×
397
        d_socket->connect(d_addr);
×
398
        d_socket->setNonBlocking();
×
399
        d_socket->writenWithTimeout(out.str().c_str(), out.str().size(), timeout);
×
400
        rv = 1;
×
401
      }
×
402
      catch (NetworkError& ne) {
×
403
        g_log << Logger::Error << "While writing to HTTP endpoint " << d_addr.toStringWithPort() << ": " << ne.what() << std::endl;
×
404
      }
×
405
      catch (...) {
×
406
        g_log << Logger::Error << "While writing to HTTP endpoint " << d_addr.toStringWithPort() << ": exception caught" << std::endl;
×
407
      }
×
408

409
      if (rv > -1) {
×
410
        break;
×
411
      }
×
412
      d_socket.reset();
×
413
      gAddrPtr = gAddrPtr->ai_next;
×
414
    }
×
415
    freeaddrinfo(gAddr);
×
416
  }
×
417
  else {
×
418
    g_log << Logger::Error << "Unable to resolve " << d_host << ": " << gai_strerror(ec) << std::endl;
×
419
  }
×
420

421
  return rv;
×
422
}
×
423

424
int HTTPConnector::recv_message(Json& output)
425
{
×
426
  YaHTTP::AsyncResponseLoader arl;
×
427
  YaHTTP::Response resp;
×
428

429
  if (d_socket == nullptr) {
×
430
    return -1; // cannot receive :(
×
431
  }
×
432
  std::array<char, 4096> buffer{};
×
433
  time_t time0 = 0;
×
434

435
  arl.initialize(&resp);
×
436

437
  try {
×
438
    time0 = time(nullptr);
×
439
    while (!arl.ready() && (labs(time(nullptr) - time0) <= timeout)) {
×
440
      auto readBytes = d_socket->readWithTimeout(buffer.data(), buffer.size(), timeout);
×
441
      if (readBytes == 0) {
×
442
        throw NetworkError("EOF while reading");
×
443
      }
×
444
      arl.feed(std::string(buffer.data(), readBytes));
×
445
    }
×
446
    // timeout occurred.
447
    if (!arl.ready()) {
×
448
      throw NetworkError("timeout");
×
449
    }
×
450
  }
×
451
  catch (NetworkError& ne) {
×
452
    d_socket.reset();
×
453
    throw PDNSException("While reading from HTTP endpoint " + d_addr.toStringWithPort() + ": " + ne.what());
×
454
  }
×
455
  catch (...) {
×
456
    d_socket.reset();
×
457
    throw PDNSException("While reading from HTTP endpoint " + d_addr.toStringWithPort() + ": unknown error");
×
458
  }
×
459

460
  arl.finalize();
×
461

462
  if ((resp.status < 200 || resp.status >= 400) && resp.status != 404) {
×
463
    // bad.
464
    throw PDNSException("Received unacceptable HTTP status code " + std::to_string(resp.status) + " from HTTP endpoint " + d_addr.toStringWithPort());
×
465
  }
×
466

467
  std::string err;
×
468
  output = Json::parse(resp.body, err);
×
469
  if (output != nullptr) {
×
470
    return static_cast<int>(resp.body.size());
×
471
  }
×
472
  g_log << Logger::Error << "Cannot parse JSON reply: " << err << endl;
×
473

474
  return -1;
×
475
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc