From: Fred Morcos Date: Tue, 26 Sep 2023 12:40:37 +0000 (+0200) Subject: Cleanup remote backend X-Git-Tag: rec-5.0.0-alpha2~30^2 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=refs%2Fpull%2F13320%2Fhead;p=thirdparty%2Fpdns.git Cleanup remote backend --- diff --git a/modules/remotebackend/httpconnector.cc b/modules/remotebackend/httpconnector.cc index 2c21d85c09..015f3008aa 100644 --- a/modules/remotebackend/httpconnector.cc +++ b/modules/remotebackend/httpconnector.cc @@ -80,16 +80,17 @@ HTTPConnector::HTTPConnector(std::map options) : } } -HTTPConnector::~HTTPConnector() {} +HTTPConnector::~HTTPConnector() = default; void HTTPConnector::addUrlComponent(const Json& parameters, const string& element, std::stringstream& ss) { std::string sparam; - if (parameters[element] != Json()) + if (parameters[element] != Json()) { ss << "/" << YaHTTP::Utility::encodeURL(asString(parameters[element]), false); + } } -std::string HTTPConnector::buildMemberListArgs(std::string prefix, const Json& args) +std::string HTTPConnector::buildMemberListArgs(const std::string& prefix, const Json& args) { std::stringstream stream; @@ -101,7 +102,7 @@ std::string HTTPConnector::buildMemberListArgs(std::string prefix, const Json& a stream << prefix << "[" << YaHTTP::Utility::encodeURL(pair.first, false) << "]="; } else { - stream << prefix << "[" << YaHTTP::Utility::encodeURL(pair.first, false) << "]=" << YaHTTP::Utility::encodeURL(this->asString(pair.second), false); + stream << prefix << "[" << YaHTTP::Utility::encodeURL(pair.first, false) << "]=" << YaHTTP::Utility::encodeURL(HTTPConnector::asString(pair.second), false); } stream << "&"; } @@ -173,7 +174,7 @@ void HTTPConnector::restful_requestbuilder(const std::string& method, const Json else if (method == "createSlaveDomain") { addUrlComponent(parameters, "ip", ss); addUrlComponent(parameters, "domain", ss); - if (parameters["account"].is_null() == false && parameters["account"].is_string()) { + if (!parameters["account"].is_null() && parameters["account"].is_string()) { req.POST()["account"] = parameters["account"].string_value(); } req.preparePost(); @@ -316,7 +317,8 @@ void HTTPConnector::post_requestbuilder(const Json& input, YaHTTP::Request& req) req.body = out; } else { - std::stringstream url, content; + std::stringstream url; + std::stringstream content; // call url/method.suffix url << d_url << "/" << input["method"].string_value() << d_url_suffix; req.setup("POST", url.str()); @@ -329,7 +331,9 @@ void HTTPConnector::post_requestbuilder(const Json& input, YaHTTP::Request& req) int HTTPConnector::send_message(const Json& input) { - int rv, ec, fd; + int rv = 0; + int ec = 0; + int fd = 0; std::vector members; std::string method; @@ -338,10 +342,12 @@ int HTTPConnector::send_message(const Json& input) // perform request YaHTTP::Request req; - if (d_post) + if (d_post) { post_requestbuilder(input, req); - else + } + else { restful_requestbuilder(input["method"].string_value(), input["parameters"], req); + } rv = -1; req.headers["connection"] = "Keep-Alive"; // see if we can streamline requests (not needed, strictly speaking) @@ -366,13 +372,18 @@ int HTTPConnector::send_message(const Json& input) } } - if (rv == 1) + if (rv == 1) { return rv; + } this->d_socket.reset(); // connect using tcp - struct addrinfo *gAddr, *gAddrPtr, hints; + struct addrinfo* gAddr = nullptr; + struct addrinfo* gAddrPtr = nullptr; + struct addrinfo hints + { + }; std::string sPort = std::to_string(d_port); memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; @@ -383,7 +394,7 @@ int HTTPConnector::send_message(const Json& input) // try to connect to each address. gAddrPtr = gAddr; - while (gAddrPtr) { + while (gAddrPtr != nullptr) { try { d_socket = std::make_unique(gAddrPtr->ai_family, gAddrPtr->ai_socktype, gAddrPtr->ai_protocol); d_addr.setSockaddr(gAddrPtr->ai_addr, gAddrPtr->ai_addrlen); @@ -399,8 +410,9 @@ int HTTPConnector::send_message(const Json& input) g_log << Logger::Error << "While writing to HTTP endpoint " << d_addr.toStringWithPort() << ": exception caught" << std::endl; } - if (rv > -1) + if (rv > -1) { break; + } d_socket.reset(); gAddrPtr = gAddrPtr->ai_next; } @@ -418,27 +430,31 @@ int HTTPConnector::recv_message(Json& output) YaHTTP::AsyncResponseLoader arl; YaHTTP::Response resp; - if (d_socket == nullptr) + if (d_socket == nullptr) { return -1; // cannot receive :( + } char buffer[4096]; int rd = -1; - time_t t0; + time_t t0 = 0; arl.initialize(&resp); try { - t0 = time((time_t*)NULL); - while (arl.ready() == false && (labs(time((time_t*)NULL) - t0) <= timeout)) { + t0 = time((time_t*)nullptr); + while (!arl.ready() && (labs(time((time_t*)nullptr) - t0) <= timeout)) { rd = d_socket->readWithTimeout(buffer, sizeof(buffer), timeout); - if (rd == 0) + if (rd == 0) { throw NetworkError("EOF while reading"); - if (rd < 0) + } + if (rd < 0) { throw NetworkError(std::string(strerror(rd))); + } arl.feed(std::string(buffer, rd)); } // timeout occurred. - if (arl.ready() == false) + if (!arl.ready()) { throw NetworkError("timeout"); + } } catch (NetworkError& ne) { d_socket.reset(); @@ -459,8 +475,9 @@ int HTTPConnector::recv_message(Json& output) int rv = -1; std::string err; output = Json::parse(resp.body, err); - if (output != nullptr) + if (output != nullptr) { return resp.body.size(); + } g_log << Logger::Error << "Cannot parse JSON reply: " << err << endl; return rv; diff --git a/modules/remotebackend/pipeconnector.cc b/modules/remotebackend/pipeconnector.cc index e6f3a5da8e..cc90a44197 100644 --- a/modules/remotebackend/pipeconnector.cc +++ b/modules/remotebackend/pipeconnector.cc @@ -45,17 +45,18 @@ PipeConnector::PipeConnector(std::map optionsMap) : PipeConnector::~PipeConnector() { - int status; + int status = 0; // just in case... - if (d_pid == -1) + if (d_pid == -1) { return; + } - if (!waitpid(d_pid, &status, WNOHANG)) { + if (waitpid(d_pid, &status, WNOHANG) == 0) { kill(d_pid, 9); waitpid(d_pid, &status, 0); } - if (d_fd1[1]) { + if (d_fd1[1] != 0) { close(d_fd1[1]); } } @@ -63,39 +64,46 @@ PipeConnector::~PipeConnector() void PipeConnector::launch() { // no relaunch - if (d_pid > 0 && checkStatus()) + if (d_pid > 0 && checkStatus()) { return; + } std::vector v; split(v, command, boost::is_any_of(" ")); std::vector argv(v.size() + 1); - argv[v.size()] = 0; + argv[v.size()] = nullptr; - for (size_t n = 0; n < v.size(); n++) + for (size_t n = 0; n < v.size(); n++) { argv[n] = v[n].c_str(); + } signal(SIGPIPE, SIG_IGN); - if (access(argv[0], X_OK)) // check before fork so we can throw + if (access(argv[0], X_OK) != 0) { // check before fork so we can throw throw PDNSException("Command '" + string(argv[0]) + "' cannot be executed: " + stringerror()); + } - if (pipe(d_fd1) < 0 || pipe(d_fd2) < 0) + if (pipe(d_fd1) < 0 || pipe(d_fd2) < 0) { throw PDNSException("Unable to open pipe for coprocess: " + string(strerror(errno))); + } - if ((d_pid = fork()) < 0) + if ((d_pid = fork()) < 0) { throw PDNSException("Unable to fork for coprocess: " + stringerror()); - else if (d_pid > 0) { // parent speaking + } + if (d_pid > 0) { // parent speaking close(d_fd1[0]); setCloseOnExec(d_fd1[1]); close(d_fd2[1]); setCloseOnExec(d_fd2[0]); - if (!(d_fp = std::unique_ptr(fdopen(d_fd2[0], "r"), fclose))) + if (!(d_fp = std::unique_ptr(fdopen(d_fd2[0], "r"), fclose))) { throw PDNSException("Unable to associate a file pointer with pipe: " + stringerror()); - if (d_timeout) - setbuf(d_fp.get(), 0); // no buffering please, confuses poll + } + if (d_timeout != 0) { + setbuf(d_fp.get(), nullptr); // no buffering please, confuses poll + } } - else if (!d_pid) { // child + else if (d_pid == 0) { // child signal(SIGCHLD, SIG_DFL); // silence a warning from perl close(d_fd1[1]); close(d_fd2[0]); @@ -112,8 +120,9 @@ void PipeConnector::launch() // stdin & stdout are now connected, fire up our coprocess! - if (execv(argv[0], const_cast(argv.data())) < 0) // now what + if (execv(argv[0], const_cast(argv.data())) < 0) { // now what exit(123); + } /* not a lot we can do here. We shouldn't return because that will leave a forked process around. no way to log this either - only thing we can do is make sure that our parent catches this soonest! */ @@ -127,7 +136,7 @@ void PipeConnector::launch() this->send(msg); msg = nullptr; - if (this->recv(msg) == false) { + if (!this->recv(msg)) { g_log << Logger::Error << "Failed to initialize coprocess" << std::endl; } } @@ -140,13 +149,14 @@ int PipeConnector::send_message(const Json& input) line.append(1, '\n'); unsigned int sent = 0; - int bytes; + int bytes = 0; // writen routine - socket may not accept al data in one go while (sent < line.size()) { bytes = write(d_fd1[1], line.c_str() + sent, line.length() - sent); - if (bytes < 0) + if (bytes < 0) { throw PDNSException("Writing to coprocess failed: " + std::string(strerror(errno))); + } sent += bytes; } @@ -162,33 +172,38 @@ int PipeConnector::recv_message(Json& output) while (1) { receive.clear(); - if (d_timeout) { + if (d_timeout != 0) { int ret = waitForData(fileno(d_fp.get()), 0, d_timeout * 1000); - if (ret < 0) + if (ret < 0) { throw PDNSException("Error waiting on data from coprocess: " + stringerror()); - if (!ret) + } + if (ret == 0) { throw PDNSException("Timeout waiting for data from coprocess"); + } } - if (!stringfgets(d_fp.get(), receive)) + if (!stringfgets(d_fp.get(), receive)) { throw PDNSException("Child closed pipe"); + } s_output.append(receive); // see if it can be parsed output = Json::parse(s_output, err); - if (output != nullptr) + if (output != nullptr) { return s_output.size(); + } } return 0; } -bool PipeConnector::checkStatus() +bool PipeConnector::checkStatus() const { - int status; + int status = 0; int ret = waitpid(d_pid, &status, WNOHANG); - if (ret < 0) + if (ret < 0) { throw PDNSException("Unable to ascertain status of coprocess " + std::to_string(d_pid) + " from " + std::to_string(getpid()) + ": " + string(strerror(errno))); - else if (ret) { + } + if (ret != 0) { if (WIFEXITED(status)) { int exitStatus = WEXITSTATUS(status); throw PDNSException("Coprocess exited with code " + std::to_string(exitStatus)); @@ -197,8 +212,9 @@ bool PipeConnector::checkStatus() int sig = WTERMSIG(status); string reason = "CoProcess died on receiving signal " + std::to_string(sig); #ifdef WCOREDUMP - if (WCOREDUMP(status)) + if (WCOREDUMP(status)) { reason += ". Dumped core"; + } #endif throw PDNSException(reason); diff --git a/modules/remotebackend/remotebackend.cc b/modules/remotebackend/remotebackend.cc index 19e1ec99a6..8fa086ab6b 100644 --- a/modules/remotebackend/remotebackend.cc +++ b/modules/remotebackend/remotebackend.cc @@ -49,7 +49,7 @@ bool Connector::recv(Json& value) if (value["result"] == Json()) { throw PDNSException("No 'result' field in response from remote process"); } - else if (value["result"].is_bool() && boolFromJson(value, "result", false) == false) { + if (value["result"].is_bool() && !boolFromJson(value, "result", false)) { retval = false; } for (const auto& message : value["log"].array_items()) { @@ -78,13 +78,11 @@ RemoteBackend::RemoteBackend(const std::string& suffix) this->d_connstr = getArg("connection-string"); this->d_dnssec = mustDo("dnssec"); - this->d_index = -1; - this->d_trxid = 0; build(); } -RemoteBackend::~RemoteBackend() {} +RemoteBackend::~RemoteBackend() = default; bool RemoteBackend::send(Json& value) { @@ -131,10 +129,11 @@ int RemoteBackend::build() std::map options; // connstr is of format "type:options" - size_t pos; - pos = d_connstr.find_first_of(":"); - if (pos == std::string::npos) + size_t pos = 0; + pos = d_connstr.find_first_of(':'); + if (pos == std::string::npos) { throw PDNSException("Invalid connection string: malformed"); + } type = d_connstr.substr(0, pos); opts = d_connstr.substr(pos + 1); @@ -144,10 +143,12 @@ int RemoteBackend::build() // find out some options and parse them while we're at it for (const auto& opt : parts) { - std::string key, val; + std::string key; + std::string val; // make sure there is something else than air in the option... - if (opt.find_first_not_of(" ") == std::string::npos) + if (opt.find_first_not_of(" ") == std::string::npos) { continue; + } // split it on '='. if not found, we treat it as "yes" pos = opt.find_first_of("="); @@ -193,14 +194,15 @@ int RemoteBackend::build() */ void RemoteBackend::lookup(const QType& qtype, const DNSName& qdomain, int zoneId, DNSPacket* pkt_p) { - if (d_index != -1) + if (d_index != -1) { throw PDNSException("Attempt to lookup while one running"); + } string localIP = "0.0.0.0"; string remoteIP = "0.0.0.0"; string realRemote = "0.0.0.0/0"; - if (pkt_p) { + if (pkt_p != nullptr) { localIP = pkt_p->getLocal().toString(); realRemote = pkt_p->getRealRemote().toString(); remoteIP = pkt_p->getInnerRemote().toString(); @@ -210,30 +212,34 @@ void RemoteBackend::lookup(const QType& qtype, const DNSName& qdomain, int zoneI {"method", "lookup"}, {"parameters", Json::object{{"qtype", qtype.toString()}, {"qname", qdomain.toString()}, {"remote", remoteIP}, {"local", localIP}, {"real-remote", realRemote}, {"zone-id", zoneId}}}}; - if (this->send(query) == false || this->recv(d_result) == false) { + if (!this->send(query) || !this->recv(d_result)) { return; } // OK. we have result parameters in result. do not process empty result. - if (d_result["result"].is_array() == false || d_result["result"].array_items().size() < 1) + if (!d_result["result"].is_array() || d_result["result"].array_items().empty()) { return; + } d_index = 0; } bool RemoteBackend::list(const DNSName& target, int domain_id, bool include_disabled) { - if (d_index != -1) + if (d_index != -1) { throw PDNSException("Attempt to lookup while one running"); + } Json query = Json::object{ {"method", "list"}, {"parameters", Json::object{{"zonename", target.toString()}, {"domain_id", domain_id}, {"include_disabled", include_disabled}}}}; - if (this->send(query) == false || this->recv(d_result) == false) + if (!this->send(query) || !this->recv(d_result)) { return false; - if (d_result["result"].is_array() == false || d_result["result"].array_items().size() < 1) + } + if (!d_result["result"].is_array() || d_result["result"].array_items().empty()) { return false; + } d_index = 0; return true; @@ -241,8 +247,9 @@ bool RemoteBackend::list(const DNSName& target, int domain_id, bool include_disa bool RemoteBackend::get(DNSResourceRecord& rr) { - if (d_index == -1) + if (d_index == -1) { return false; + } rr.qtype = stringFromJson(d_result["result"][d_index], "qtype"); rr.qname = DNSName(stringFromJson(d_result["result"][d_index], "qname")); @@ -250,10 +257,12 @@ bool RemoteBackend::get(DNSResourceRecord& rr) rr.content = stringFromJson(d_result["result"][d_index], "content"); rr.ttl = d_result["result"][d_index]["ttl"].int_value(); rr.domain_id = intFromJson(d_result["result"][d_index], "domain_id", -1); - if (d_dnssec) - rr.auth = intFromJson(d_result["result"][d_index], "auth", 1); - else - rr.auth = 1; + if (d_dnssec) { + rr.auth = (intFromJson(d_result["result"][d_index], "auth", 1) != 0); + } + else { + rr.auth = true; + } rr.scopeMask = d_result["result"][d_index]["scopeMask"].int_value(); d_index++; @@ -268,24 +277,28 @@ bool RemoteBackend::get(DNSResourceRecord& rr) bool RemoteBackend::getBeforeAndAfterNamesAbsolute(uint32_t id, const DNSName& qname, DNSName& unhashed, DNSName& before, DNSName& after) { // no point doing dnssec if it's not supported - if (d_dnssec == false) + if (!d_dnssec) { return false; + } Json query = Json::object{ {"method", "getBeforeAndAfterNamesAbsolute"}, {"parameters", Json::object{{"id", Json(static_cast(id))}, {"qname", qname.toString()}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) + if (!this->send(query) || !this->recv(answer)) { return false; + } unhashed = DNSName(stringFromJson(answer["result"], "unhashed")); before.clear(); after.clear(); - if (answer["result"]["before"] != Json()) + if (answer["result"]["before"] != Json()) { before = DNSName(stringFromJson(answer["result"], "before")); - if (answer["result"]["after"] != Json()) + } + if (answer["result"]["after"] != Json()) { after = DNSName(stringFromJson(answer["result"], "after")); + } return true; } @@ -296,20 +309,23 @@ bool RemoteBackend::getAllDomainMetadata(const DNSName& name, std::mapsend(query) == false) + if (!this->send(query)) { return false; + } meta.clear(); Json answer; // not mandatory to implement - if (this->recv(answer) == false) + if (!this->recv(answer)) { return true; + } for (const auto& pair : answer["result"].object_items()) { if (pair.second.is_array()) { - for (const auto& val : pair.second.array_items()) + for (const auto& val : pair.second.array_items()) { meta[pair.first].push_back(asString(val)); + } } else { meta[pair.first].push_back(asString(pair.second)); @@ -325,19 +341,22 @@ bool RemoteBackend::getDomainMetadata(const DNSName& name, const std::string& ki {"method", "getDomainMetadata"}, {"parameters", Json::object{{"name", name.toString()}, {"kind", kind}}}}; - if (this->send(query) == false) + if (!this->send(query)) { return false; + } meta.clear(); Json answer; // not mandatory to implement - if (this->recv(answer) == false) + if (!this->recv(answer)) { return true; + } if (answer["result"].is_array()) { - for (const auto& row : answer["result"].array_items()) + for (const auto& row : answer["result"].array_items()) { meta.push_back(row.string_value()); + } } else if (answer["result"].is_string()) { meta.push_back(answer["result"].string_value()); @@ -353,8 +372,9 @@ bool RemoteBackend::setDomainMetadata(const DNSName& name, const std::string& ki {"parameters", Json::object{{"name", name.toString()}, {"kind", kind}, {"value", meta}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) + if (!this->send(query) || !this->recv(answer)) { return false; + } return boolFromJson(answer, "result", false); } @@ -362,16 +382,18 @@ bool RemoteBackend::setDomainMetadata(const DNSName& name, const std::string& ki bool RemoteBackend::getDomainKeys(const DNSName& name, std::vector& keys) { // no point doing dnssec if it's not supported - if (d_dnssec == false) + if (!d_dnssec) { return false; + } Json query = Json::object{ {"method", "getDomainKeys"}, {"parameters", Json::object{{"name", name.toString()}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) + if (!this->send(query) || !this->recv(answer)) { return false; + } keys.clear(); @@ -391,33 +413,33 @@ bool RemoteBackend::getDomainKeys(const DNSName& name, std::vector(id)}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) - return false; - - return true; + return this->send(query) && this->recv(answer); } bool RemoteBackend::addDomainKey(const DNSName& name, const KeyData& key, int64_t& id) { // no point doing dnssec if it's not supported - if (d_dnssec == false) + if (!d_dnssec) { return false; + } Json query = Json::object{ {"method", "addDomainKey"}, {"parameters", Json::object{{"name", name.toString()}, {"key", Json::object{{"flags", static_cast(key.flags)}, {"active", key.active}, {"published", key.published}, {"content", key.content}}}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) + if (!this->send(query) || !this->recv(answer)) { return false; + } id = answer["result"].int_value(); return id >= 0; @@ -426,69 +448,61 @@ bool RemoteBackend::addDomainKey(const DNSName& name, const KeyData& key, int64_ bool RemoteBackend::activateDomainKey(const DNSName& name, unsigned int id) { // no point doing dnssec if it's not supported - if (d_dnssec == false) + if (!d_dnssec) { return false; + } Json query = Json::object{ {"method", "activateDomainKey"}, {"parameters", Json::object{{"name", name.toString()}, {"id", static_cast(id)}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) - return false; - - return true; + return this->send(query) && this->recv(answer); } bool RemoteBackend::deactivateDomainKey(const DNSName& name, unsigned int id) { // no point doing dnssec if it's not supported - if (d_dnssec == false) + if (!d_dnssec) { return false; + } Json query = Json::object{ {"method", "deactivateDomainKey"}, {"parameters", Json::object{{"name", name.toString()}, {"id", static_cast(id)}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) - return false; - - return true; + return this->send(query) && this->recv(answer); } bool RemoteBackend::publishDomainKey(const DNSName& name, unsigned int id) { // no point doing dnssec if it's not supported - if (d_dnssec == false) + if (!d_dnssec) { return false; + } Json query = Json::object{ {"method", "publishDomainKey"}, {"parameters", Json::object{{"name", name.toString()}, {"id", static_cast(id)}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) - return false; - - return true; + return this->send(query) && this->recv(answer); } bool RemoteBackend::unpublishDomainKey(const DNSName& name, unsigned int id) { // no point doing dnssec if it's not supported - if (d_dnssec == false) + if (!d_dnssec) { return false; + } Json query = Json::object{ {"method", "unpublishDomainKey"}, {"parameters", Json::object{{"name", name.toString()}, {"id", static_cast(id)}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) - return false; - - return true; + return this->send(query) && this->recv(answer); } bool RemoteBackend::doesDNSSEC() @@ -499,16 +513,18 @@ bool RemoteBackend::doesDNSSEC() bool RemoteBackend::getTSIGKey(const DNSName& name, DNSName& algorithm, std::string& content) { // no point doing dnssec if it's not supported - if (d_dnssec == false) + if (!d_dnssec) { return false; + } Json query = Json::object{ {"method", "getTSIGKey"}, {"parameters", Json::object{{"name", name.toString()}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) + if (!this->send(query) || !this->recv(answer)) { return false; + } algorithm = DNSName(stringFromJson(answer["result"], "algorithm")); content = stringFromJson(answer["result"], "content"); @@ -519,48 +535,46 @@ bool RemoteBackend::getTSIGKey(const DNSName& name, DNSName& algorithm, std::str bool RemoteBackend::setTSIGKey(const DNSName& name, const DNSName& algorithm, const std::string& content) { // no point doing dnssec if it's not supported - if (d_dnssec == false) + if (!d_dnssec) { return false; + } Json query = Json::object{ {"method", "setTSIGKey"}, {"parameters", Json::object{{"name", name.toString()}, {"algorithm", algorithm.toString()}, {"content", content}}}}; Json answer; - if (connector->send(query) == false || connector->recv(answer) == false) - return false; - - return true; + return connector->send(query) && connector->recv(answer); } bool RemoteBackend::deleteTSIGKey(const DNSName& name) { // no point doing dnssec if it's not supported - if (d_dnssec == false) + if (!d_dnssec) { return false; + } Json query = Json::object{ {"method", "deleteTSIGKey"}, {"parameters", Json::object{{"name", name.toString()}}}}; Json answer; - if (connector->send(query) == false || connector->recv(answer) == false) - return false; - - return true; + return connector->send(query) && connector->recv(answer); } bool RemoteBackend::getTSIGKeys(std::vector& keys) { // no point doing dnssec if it's not supported - if (d_dnssec == false) + if (!d_dnssec) { return false; + } Json query = Json::object{ {"method", "getTSIGKeys"}, {"parameters", Json::object{}}}; Json answer; - if (connector->send(query) == false || connector->recv(answer) == false) + if (!connector->send(query) || !connector->recv(answer)) { return false; + } for (const auto& jsonKey : answer["result"].array_items()) { struct TSIGKey key; @@ -577,14 +591,15 @@ void RemoteBackend::parseDomainInfo(const Json& obj, DomainInfo& di) { di.id = intFromJson(obj, "id", -1); di.zone = DNSName(stringFromJson(obj, "zone")); - for (const auto& master : obj["masters"].array_items()) - di.masters.push_back(ComboAddress(master.string_value(), 53)); + for (const auto& master : obj["masters"].array_items()) { + di.masters.emplace_back(master.string_value(), 53); + } di.notified_serial = static_cast(doubleFromJson(obj, "notified_serial", 0)); di.serial = static_cast(obj["serial"].number_value()); di.last_check = static_cast(obj["last_check"].number_value()); - string kind = ""; + string kind; if (obj["kind"].is_string()) { kind = stringFromJson(obj, "kind"); } @@ -602,15 +617,18 @@ void RemoteBackend::parseDomainInfo(const Json& obj, DomainInfo& di) bool RemoteBackend::getDomainInfo(const DNSName& domain, DomainInfo& di, bool /* getSerial */) { - if (domain.empty()) + if (domain.empty()) { return false; + } + Json query = Json::object{ {"method", "getDomainInfo"}, {"parameters", Json::object{{"name", domain.toString()}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) + if (!this->send(query) || !this->recv(answer)) { return false; + } this->parseDomainInfo(answer["result"], di); return true; @@ -623,7 +641,7 @@ void RemoteBackend::setNotified(uint32_t id, uint32_t serial) {"parameters", Json::object{{"id", static_cast(id)}, {"serial", static_cast(serial)}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) { + if (!this->send(query) || !this->recv(answer)) { g_log << Logger::Error << kBackendId << " Failed to execute RPC for RemoteBackend::setNotified(" << id << "," << serial << ")" << endl; } } @@ -646,11 +664,12 @@ bool RemoteBackend::superMasterBackend(const string& ip, const DNSName& domain, {"method", "superMasterBackend"}, {"parameters", Json::object{{"ip", ip}, {"domain", domain.toString()}, {"nsset", rrset}}}}; - *ddb = 0; + *ddb = nullptr; Json answer; - if (this->send(query) == false || this->recv(answer) == false) + if (!this->send(query) || !this->recv(answer)) { return false; + } // we are the backend *ddb = this; @@ -676,9 +695,7 @@ bool RemoteBackend::createSlaveDomain(const string& ip, const DNSName& domain, c }}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) - return false; - return true; + return this->send(query) && this->recv(answer); } bool RemoteBackend::replaceRRSet(uint32_t domain_id, const DNSName& qname, const QType& qtype, const vector& rrset) @@ -699,10 +716,7 @@ bool RemoteBackend::replaceRRSet(uint32_t domain_id, const DNSName& qname, const {"parameters", Json::object{{"domain_id", static_cast(domain_id)}, {"qname", qname.toString()}, {"qtype", qtype.toString()}, {"trxid", static_cast(d_trxid)}, {"rrset", json_rrset}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) - return false; - - return true; + return this->send(query) && this->recv(answer); } bool RemoteBackend::feedRecord(const DNSResourceRecord& rr, const DNSName& ordername, bool /* ordernameIsNSEC3 */) @@ -715,19 +729,18 @@ bool RemoteBackend::feedRecord(const DNSResourceRecord& rr, const DNSName& order }}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) - return false; - return true; // XXX FIXME this API should not return 'true' I think -ahu + return this->send(query) && this->recv(answer); // XXX FIXME this API should not return 'true' I think -ahu } bool RemoteBackend::feedEnts(int domain_id, map& nonterm) { Json::array nts; - for (const auto& t : nonterm) + for (const auto& t : nonterm) { nts.push_back(Json::object{ {"nonterm", t.first.toString()}, {"auth", t.second}}); + } Json query = Json::object{ {"method", "feedEnts"}, @@ -735,19 +748,18 @@ bool RemoteBackend::feedEnts(int domain_id, map& nonterm) }; Json answer; - if (this->send(query) == false || this->recv(answer) == false) - return false; - return true; + return this->send(query) && this->recv(answer); } bool RemoteBackend::feedEnts3(int domain_id, const DNSName& domain, map& nonterm, const NSEC3PARAMRecordContent& ns3prc, bool narrow) { Json::array nts; - for (const auto& t : nonterm) + for (const auto& t : nonterm) { nts.push_back(Json::object{ {"nonterm", t.first.toString()}, {"auth", t.second}}); + } Json query = Json::object{ {"method", "feedEnts3"}, @@ -755,30 +767,30 @@ bool RemoteBackend::feedEnts3(int domain_id, const DNSName& domain, mapsend(query) == false || this->recv(answer) == false) - return false; - return true; + return this->send(query) && this->recv(answer); } bool RemoteBackend::startTransaction(const DNSName& domain, int domain_id) { - this->d_trxid = time((time_t*)NULL); + this->d_trxid = time((time_t*)nullptr); Json query = Json::object{ {"method", "startTransaction"}, {"parameters", Json::object{{"domain", domain.toString()}, {"domain_id", domain_id}, {"trxid", static_cast(d_trxid)}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) { + if (!this->send(query) || !this->recv(answer)) { d_trxid = -1; return false; } return true; } + bool RemoteBackend::commitTransaction() { - if (d_trxid == -1) + if (d_trxid == -1) { return false; + } Json query = Json::object{ {"method", "commitTransaction"}, @@ -786,15 +798,14 @@ bool RemoteBackend::commitTransaction() d_trxid = -1; Json answer; - if (this->send(query) == false || this->recv(answer) == false) - return false; - return true; + return this->send(query) && this->recv(answer); } bool RemoteBackend::abortTransaction() { - if (d_trxid == -1) + if (d_trxid == -1) { return false; + } Json query = Json::object{ {"method", "abortTransaction"}, @@ -802,9 +813,7 @@ bool RemoteBackend::abortTransaction() d_trxid = -1; Json answer; - if (this->send(query) == false || this->recv(answer) == false) - return false; - return true; + return this->send(query) && this->recv(answer); } string RemoteBackend::directBackendCmd(const string& querystr) @@ -814,8 +823,9 @@ string RemoteBackend::directBackendCmd(const string& querystr) {"parameters", Json::object{{"query", querystr}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) + if (!this->send(query) || !this->recv(answer)) { return "backend command failed"; + } return asString(answer["result"]); } @@ -827,11 +837,13 @@ bool RemoteBackend::searchRecords(const string& pattern, int maxResults, vector< {"parameters", Json::object{{"pattern", pattern}, {"maxResults", maxResults}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) + if (!this->send(query) || !this->recv(answer)) { return false; + } - if (answer["result"].is_array() == false) + if (!answer["result"].is_array()) { return false; + } for (const auto& row : answer["result"].array_items()) { DNSResourceRecord rr; @@ -841,10 +853,12 @@ bool RemoteBackend::searchRecords(const string& pattern, int maxResults, vector< rr.content = stringFromJson(row, "content"); rr.ttl = row["ttl"].int_value(); rr.domain_id = intFromJson(row, "domain_id", -1); - if (d_dnssec) - rr.auth = intFromJson(row, "auth", 1); - else + if (d_dnssec) { + rr.auth = (intFromJson(row, "auth", 1) != 0); + } + else { rr.auth = 1; + } rr.scopeMask = row["scopeMask"].int_value(); result.push_back(rr); } @@ -865,11 +879,13 @@ void RemoteBackend::getAllDomains(vector* domains, bool /* getSerial {"parameters", Json::object{{"include_disabled", include_disabled}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) + if (!this->send(query) || !this->recv(answer)) { return; + } - if (answer["result"].is_array() == false) + if (!answer["result"].is_array()) { return; + } for (const auto& row : answer["result"].array_items()) { DomainInfo di; @@ -886,11 +902,13 @@ void RemoteBackend::getUpdatedMasters(vector& domains, std::unordere }; Json answer; - if (this->send(query) == false || this->recv(answer) == false) + if (!this->send(query) || !this->recv(answer)) { return; + } - if (answer["result"].is_array() == false) + if (!answer["result"].is_array()) { return; + } for (const auto& row : answer["result"].array_items()) { DomainInfo di; @@ -907,11 +925,13 @@ void RemoteBackend::getUnfreshSlaveInfos(vector* domains) }; Json answer; - if (this->send(query) == false || this->recv(answer) == false) + if (!this->send(query) || !this->recv(answer)) { return; + } - if (answer["result"].is_array() == false) + if (!answer["result"].is_array()) { return; + } for (const auto& row : answer["result"].array_items()) { DomainInfo di; @@ -927,7 +947,7 @@ void RemoteBackend::setStale(uint32_t domain_id) {"parameters", Json::object{{"id", static_cast(domain_id)}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) { + if (!this->send(query) || !this->recv(answer)) { g_log << Logger::Error << kBackendId << " Failed to execute RPC for RemoteBackend::setStale(" << domain_id << ")" << endl; } } @@ -939,7 +959,7 @@ void RemoteBackend::setFresh(uint32_t domain_id) {"parameters", Json::object{{"id", static_cast(domain_id)}}}}; Json answer; - if (this->send(query) == false || this->recv(answer) == false) { + if (!this->send(query) || !this->recv(answer)) { g_log << Logger::Error << kBackendId << " Failed to execute RPC for RemoteBackend::setFresh(" << domain_id << ")" << endl; } } @@ -951,7 +971,7 @@ DNSBackend* RemoteBackend::maker() } catch (...) { g_log << Logger::Error << kBackendId << " Unable to instantiate a remotebackend!" << endl; - return 0; + return nullptr; }; } diff --git a/modules/remotebackend/remotebackend.hh b/modules/remotebackend/remotebackend.hh index 078594e7f3..23c7be638a 100644 --- a/modules/remotebackend/remotebackend.hh +++ b/modules/remotebackend/remotebackend.hh @@ -51,21 +51,24 @@ using json11::Json; class Connector { public: - virtual ~Connector(){}; + virtual ~Connector() = default; bool send(Json& value); bool recv(Json& value); virtual int send_message(const Json& input) = 0; virtual int recv_message(Json& output) = 0; protected: - string asString(const Json& value) + static string asString(const Json& value) { - if (value.is_number()) + if (value.is_number()) { return std::to_string(value.int_value()); - if (value.is_bool()) + } + if (value.is_bool()) { return (value.bool_value() ? "1" : "0"); - if (value.is_string()) + } + if (value.is_string()) { return value.string_value(); + } throw JsonException("Json value not convertible to String"); }; }; @@ -75,9 +78,9 @@ class UnixsocketConnector : public Connector { public: UnixsocketConnector(std::map options); - virtual ~UnixsocketConnector(); - virtual int send_message(const Json& input); - virtual int recv_message(Json& output); + ~UnixsocketConnector() override; + int send_message(const Json& input) override; + int recv_message(Json& output) override; private: ssize_t read(std::string& data); @@ -94,10 +97,10 @@ class HTTPConnector : public Connector { public: HTTPConnector(std::map options); - ~HTTPConnector(); + ~HTTPConnector() override; - virtual int send_message(const Json& input); - virtual int recv_message(Json& output); + int send_message(const Json& input) override; + int recv_message(Json& output) override; private: std::string d_url; @@ -108,8 +111,8 @@ private: bool d_post_json; void restful_requestbuilder(const std::string& method, const Json& parameters, YaHTTP::Request& req); void post_requestbuilder(const Json& input, YaHTTP::Request& req); - void addUrlComponent(const Json& parameters, const string& element, std::stringstream& ss); - std::string buildMemberListArgs(std::string prefix, const Json& args); + static void addUrlComponent(const Json& parameters, const string& element, std::stringstream& ss); + static std::string buildMemberListArgs(const std::string& prefix, const Json& args); std::unique_ptr d_socket; ComboAddress d_addr; std::string d_host; @@ -121,9 +124,9 @@ class ZeroMQConnector : public Connector { public: ZeroMQConnector(std::map options); - virtual ~ZeroMQConnector(); - virtual int send_message(const Json& input); - virtual int recv_message(Json& output); + ~ZeroMQConnector() override; + int send_message(const Json& input) override; + int recv_message(Json& output) override; private: void connect(); @@ -140,19 +143,19 @@ class PipeConnector : public Connector { public: PipeConnector(std::map options); - ~PipeConnector(); + ~PipeConnector() override; - virtual int send_message(const Json& input); - virtual int recv_message(Json& output); + int send_message(const Json& input) override; + int recv_message(Json& output) override; private: void launch(); - bool checkStatus(); + [[nodiscard]] bool checkStatus() const; std::string command; std::map options; - int d_fd1[2], d_fd2[2]; + int d_fd1[2]{}, d_fd2[2]{}; int d_pid; int d_timeout; std::unique_ptr d_fp{nullptr, fclose}; @@ -162,7 +165,7 @@ class RemoteBackend : public DNSBackend { public: RemoteBackend(const std::string& suffix = ""); - ~RemoteBackend(); + ~RemoteBackend() override; void lookup(const QType& qtype, const DNSName& qdomain, int zoneId = -1, DNSPacket* pkt_p = nullptr) override; bool get(DNSResourceRecord& rr) override; @@ -211,35 +214,41 @@ private: std::unique_ptr connector; bool d_dnssec; Json d_result; - int d_index; - int64_t d_trxid; + int d_index{-1}; + int64_t d_trxid{0}; std::string d_connstr; bool send(Json& value); bool recv(Json& value); - void makeErrorAndThrow(Json& value); + static void makeErrorAndThrow(Json& value); - string asString(const Json& value) + static string asString(const Json& value) { - if (value.is_number()) + if (value.is_number()) { return std::to_string(value.int_value()); - if (value.is_bool()) + } + if (value.is_bool()) { return (value.bool_value() ? "1" : "0"); - if (value.is_string()) + } + if (value.is_string()) { return value.string_value(); + } throw JsonException("Json value not convertible to String"); }; - bool asBool(const Json& value) + static bool asBool(const Json& value) { - if (value.is_bool()) + if (value.is_bool()) { return value.bool_value(); + } try { string val = asString(value); - if (val == "0") + if (val == "0") { return false; - if (val == "1") + } + if (val == "1") { return true; + } } catch (const JsonException&) { }; diff --git a/modules/remotebackend/test-remotebackend-http.cc b/modules/remotebackend/test-remotebackend-http.cc index bcfb51e7c5..824db56203 100644 --- a/modules/remotebackend/test-remotebackend-http.cc +++ b/modules/remotebackend/test-remotebackend-http.cc @@ -67,7 +67,7 @@ struct RemotebackendSetup { RemotebackendSetup() { - be = 0; + be = nullptr; try { // setup minimum arguments ::arg().set("module-dir") = "./.libs"; @@ -82,7 +82,7 @@ struct RemotebackendSetup BOOST_TEST_MESSAGE("Cannot start remotebackend: " << ex.reason); }; } - ~RemotebackendSetup() {} + ~RemotebackendSetup() = default; }; BOOST_GLOBAL_FIXTURE(RemotebackendSetup); diff --git a/modules/remotebackend/test-remotebackend-json.cc b/modules/remotebackend/test-remotebackend-json.cc index 266b73aca6..48d023ed82 100644 --- a/modules/remotebackend/test-remotebackend-json.cc +++ b/modules/remotebackend/test-remotebackend-json.cc @@ -66,7 +66,7 @@ struct RemotebackendSetup { RemotebackendSetup() { - be = 0; + be = nullptr; try { // setup minimum arguments ::arg().set("module-dir") = "./.libs"; @@ -81,7 +81,7 @@ struct RemotebackendSetup BOOST_TEST_MESSAGE("Cannot start remotebackend: " << ex.reason); }; } - ~RemotebackendSetup() {} + ~RemotebackendSetup() = default; }; BOOST_GLOBAL_FIXTURE(RemotebackendSetup); diff --git a/modules/remotebackend/test-remotebackend-keys.hh b/modules/remotebackend/test-remotebackend-keys.hh index 807bdd8609..ac501b5708 100644 --- a/modules/remotebackend/test-remotebackend-keys.hh +++ b/modules/remotebackend/test-remotebackend-keys.hh @@ -19,6 +19,9 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ +#include +#include + DNSBackend::KeyData k1 = {std::string("Private-key-format: v1.2\nAlgorithm: 5 (RSASHA1)\nModulus: qpe9fxlN4dBT38cLPWtqljZhcJjbqRprj9XsYmf2/uFu4kA5sHYrlQY7H9lpzGJPRfOAfxShBpKs1AVaVInfJQ==\nPublicExponent: AQAB\nPrivateExponent: Ad3YogzXvVDLsWuAfioY571QlolbdTbzVlhLEMLD6dSRx+xcZgw6c27ak2HAH00iSKTvqK3AyeaK8Eqy/oJ5QQ==\nPrime1: wo8LZrdU2y0xLGCeLhwziQDDtTMi18NEIwlx8tUPnhs=\nPrime2: 4HcuFqgo7NOiXFvN+V2PT+QaIt2+oi6D2m8/qtTDS78=\nExponent1: GUdCoPbi9JM7l1t6Ud1iKMPLqchaF5SMTs0UXAuous8=\nExponent2: nzgKqimX9f1corTAEw0pddrwKyEtcu8ZuhzFhZCsAxM=\nCoefficient: YGNxbulf5GTNiIu0oNKmAF0khNtx9layjOPEI0R4/RY="), 1, 257, true, true}; DNSBackend::KeyData k2 = {std::string("Private-key-format: v1.2\nAlgorithm: 5 (RSASHA1)\nModulus: tY2TAMgL/whZdSbn2aci4wcMqohO24KQAaq5RlTRwQ33M8FYdW5fZ3DMdMsSLQUkjGnKJPKEdN3Qd4Z5b18f+w==\nPublicExponent: AQAB\nPrivateExponent: BB6xibPNPrBV0PUp3CQq0OdFpk9v9EZ2NiBFrA7osG5mGIZICqgOx/zlHiHKmX4OLmL28oU7jPKgogeuONXJQQ==\nPrime1: yjxe/iHQ4IBWpvCmuGqhxApWF+DY9LADIP7bM3Ejf3M=\nPrime2: 5dGWTyYEQRBVK74q1a64iXgaNuYm1pbClvvZ6ccCq1k=\nExponent1: TwM5RebmWeAqerzJFoIqw5IaQugJO8hM4KZR9A4/BTs=\nExponent2: bpV2HSmu3Fvuj7jWxbFoDIXlH0uJnrI2eg4/4hSnvSk=\nCoefficient: e2uDDWN2zXwYa2P6VQBWQ4mR1ZZjFEtO/+YqOJZun1Y="), 2, 256, true, true}; diff --git a/modules/remotebackend/test-remotebackend-pipe.cc b/modules/remotebackend/test-remotebackend-pipe.cc index e293a48ad8..6ad872c281 100644 --- a/modules/remotebackend/test-remotebackend-pipe.cc +++ b/modules/remotebackend/test-remotebackend-pipe.cc @@ -66,7 +66,7 @@ struct RemotebackendSetup { RemotebackendSetup() { - be = 0; + be = nullptr; try { // setup minimum arguments ::arg().set("module-dir") = "./.libs"; @@ -85,7 +85,7 @@ struct RemotebackendSetup BOOST_TEST_MESSAGE("Cannot start remotebackend: " << ex.reason); }; } - ~RemotebackendSetup() {} + ~RemotebackendSetup() = default; }; BOOST_GLOBAL_FIXTURE(RemotebackendSetup); diff --git a/modules/remotebackend/test-remotebackend-post.cc b/modules/remotebackend/test-remotebackend-post.cc index 10e5e09932..fe129623f1 100644 --- a/modules/remotebackend/test-remotebackend-post.cc +++ b/modules/remotebackend/test-remotebackend-post.cc @@ -66,7 +66,7 @@ struct RemotebackendSetup { RemotebackendSetup() { - be = 0; + be = nullptr; try { // setup minimum arguments ::arg().set("module-dir") = "./.libs"; @@ -81,7 +81,7 @@ struct RemotebackendSetup BOOST_TEST_MESSAGE("Cannot start remotebackend: " << ex.reason); }; } - ~RemotebackendSetup() {} + ~RemotebackendSetup() = default; }; BOOST_GLOBAL_FIXTURE(RemotebackendSetup); diff --git a/modules/remotebackend/test-remotebackend-unix.cc b/modules/remotebackend/test-remotebackend-unix.cc index 5ccdf1aef6..fd2c1b15a6 100644 --- a/modules/remotebackend/test-remotebackend-unix.cc +++ b/modules/remotebackend/test-remotebackend-unix.cc @@ -66,7 +66,7 @@ struct RemotebackendSetup { RemotebackendSetup() { - be = 0; + be = nullptr; try { // setup minimum arguments ::arg().set("module-dir") = "./.libs"; @@ -85,7 +85,7 @@ struct RemotebackendSetup BOOST_TEST_MESSAGE("Cannot start remotebackend: " << ex.reason); }; } - ~RemotebackendSetup() {} + ~RemotebackendSetup() = default; }; BOOST_GLOBAL_FIXTURE(RemotebackendSetup); diff --git a/modules/remotebackend/test-remotebackend-zeromq.cc b/modules/remotebackend/test-remotebackend-zeromq.cc index dc346b7035..bccf076837 100644 --- a/modules/remotebackend/test-remotebackend-zeromq.cc +++ b/modules/remotebackend/test-remotebackend-zeromq.cc @@ -68,7 +68,7 @@ struct RemotebackendSetup { RemotebackendSetup() { - be = 0; + be = nullptr; try { // setup minimum arguments ::arg().set("module-dir") = "./.libs"; @@ -87,7 +87,7 @@ struct RemotebackendSetup BOOST_TEST_MESSAGE("Cannot start remotebackend: " << ex.reason); }; } - ~RemotebackendSetup() {} + ~RemotebackendSetup() = default; }; BOOST_GLOBAL_FIXTURE(RemotebackendSetup); diff --git a/modules/remotebackend/test-remotebackend.cc b/modules/remotebackend/test-remotebackend.cc index 443713cc8d..e4a43208bf 100644 --- a/modules/remotebackend/test-remotebackend.cc +++ b/modules/remotebackend/test-remotebackend.cc @@ -75,8 +75,9 @@ BOOST_AUTO_TEST_CASE(test_method_list) BOOST_TEST_MESSAGE("Testing list method"); be->list(DNSName("unit.test."), -1); - while (be->get(rr)) + while (be->get(rr)) { record_count++; + } BOOST_CHECK_EQUAL(record_count, 5); // number of records our test domain has } @@ -90,7 +91,7 @@ BOOST_AUTO_TEST_CASE(test_method_doesDNSSEC) BOOST_AUTO_TEST_CASE(test_method_setDomainMetadata) { std::vector meta; - meta.push_back("VALUE"); + meta.emplace_back("VALUE"); BOOST_TEST_MESSAGE("Testing setDomainMetadata method"); BOOST_CHECK(be->setDomainMetadata(DNSName("unit.test."), "TEST", meta)); } @@ -102,8 +103,9 @@ BOOST_AUTO_TEST_CASE(test_method_alsoNotifies) BOOST_TEST_MESSAGE("Testing alsoNotifies method"); be->alsoNotifies(DNSName("unit.test."), &alsoNotifies); BOOST_CHECK_EQUAL(alsoNotifies.size(), 1); - if (alsoNotifies.size() > 0) + if (!alsoNotifies.empty()) { BOOST_CHECK_EQUAL(alsoNotifies.count("192.0.2.1"), 1); + } BOOST_CHECK(be->setDomainMetadata(DNSName("unit.test."), "ALSO-NOTIFY", std::vector())); } @@ -115,8 +117,9 @@ BOOST_AUTO_TEST_CASE(test_method_getDomainMetadata) BOOST_CHECK_EQUAL(meta.size(), 1); // in case we got more than one value, which would be unexpected // but not fatal - if (meta.size() > 0) + if (!meta.empty()) { BOOST_CHECK_EQUAL(meta[0], "VALUE"); + } } BOOST_AUTO_TEST_CASE(test_method_getAllDomainMetadata) @@ -127,14 +130,15 @@ BOOST_AUTO_TEST_CASE(test_method_getAllDomainMetadata) BOOST_CHECK_EQUAL(meta.size(), 1); // in case we got more than one value, which would be unexpected // but not fatal - if (meta.size() > 0) + if (!meta.empty()) { BOOST_CHECK_EQUAL(meta["TEST"][0], "VALUE"); + } } BOOST_AUTO_TEST_CASE(test_method_addDomainKey) { BOOST_TEST_MESSAGE("Testing addDomainKey method"); - int64_t id; + int64_t id = 0; be->addDomainKey(DNSName("unit.test."), k1, id); BOOST_CHECK_EQUAL(id, 1); be->addDomainKey(DNSName("unit.test."), k2, id); @@ -182,7 +186,9 @@ BOOST_AUTO_TEST_CASE(test_method_removeDomainKey) BOOST_AUTO_TEST_CASE(test_method_getBeforeAndAfterNamesAbsolute) { - DNSName unhashed, before, after; + DNSName unhashed; + DNSName before; + DNSName after; BOOST_TEST_MESSAGE("Testing getBeforeAndAfterNamesAbsolute method"); be->getBeforeAndAfterNamesAbsolute(-1, DNSName("middle.unit.test."), unhashed, before, after); @@ -193,7 +199,8 @@ BOOST_AUTO_TEST_CASE(test_method_getBeforeAndAfterNamesAbsolute) BOOST_AUTO_TEST_CASE(test_method_setTSIGKey) { - std::string algorithm, content; + std::string algorithm; + std::string content; BOOST_TEST_MESSAGE("Testing setTSIGKey method"); BOOST_CHECK_MESSAGE(be->setTSIGKey(DNSName("unit.test."), DNSName("hmac-md5."), "kp4/24gyYsEzbuTVJRUMoqGFmN3LYgVDzJ/3oRSP7ys="), "did not return true"); } @@ -210,7 +217,8 @@ BOOST_AUTO_TEST_CASE(test_method_getTSIGKey) BOOST_AUTO_TEST_CASE(test_method_deleteTSIGKey) { - std::string algorithm, content; + std::string algorithm; + std::string content; BOOST_TEST_MESSAGE("Testing deleteTSIGKey method"); BOOST_CHECK_MESSAGE(be->deleteTSIGKey(DNSName("unit.test.")), "did not return true"); } @@ -220,8 +228,8 @@ BOOST_AUTO_TEST_CASE(test_method_getTSIGKeys) std::vector keys; BOOST_TEST_MESSAGE("Testing getTSIGKeys method"); be->getTSIGKeys(keys); - BOOST_CHECK(keys.size() > 0); - if (keys.size() > 0) { + BOOST_CHECK(!keys.empty()); + if (!keys.empty()) { BOOST_CHECK_EQUAL(keys[0].name.toString(), "test."); BOOST_CHECK_EQUAL(keys[0].algorithm.toString(), "NULL."); BOOST_CHECK_EQUAL(keys[0].key, "NULL"); @@ -268,7 +276,7 @@ BOOST_AUTO_TEST_CASE(test_method_superMasterBackend) { DNSResourceRecord rr; std::vector nsset; - DNSBackend* dbd; + DNSBackend* dbd = nullptr; BOOST_TEST_MESSAGE("Testing superMasterBackend method"); rr.qname = DNSName("example.com."); @@ -284,7 +292,7 @@ BOOST_AUTO_TEST_CASE(test_method_superMasterBackend) rr.content = "ns2.example.com."; nsset.push_back(rr); - BOOST_CHECK(be->superMasterBackend("10.0.0.1", DNSName("example.com."), nsset, NULL, NULL, &dbd)); + BOOST_CHECK(be->superMasterBackend("10.0.0.1", DNSName("example.com."), nsset, nullptr, nullptr, &dbd)); // let's see what we got BOOST_CHECK_EQUAL(dbd, be); @@ -376,7 +384,7 @@ BOOST_AUTO_TEST_CASE(test_method_getUpdatedMasters) be->getUpdatedMasters(result, catalogs, hashes); - BOOST_REQUIRE(result.size() > 0); + BOOST_REQUIRE(!result.empty()); di = result.at(0); BOOST_CHECK_EQUAL(di.zone.toString(), "master.test."); diff --git a/modules/remotebackend/unixconnector.cc b/modules/remotebackend/unixconnector.cc index 9fd071528b..82447c6172 100644 --- a/modules/remotebackend/unixconnector.cc +++ b/modules/remotebackend/unixconnector.cc @@ -62,42 +62,52 @@ int UnixsocketConnector::send_message(const Json& input) { auto data = input.dump() + "\n"; int rv = this->write(data); - if (rv == -1) + if (rv == -1) { return -1; + } return rv; } int UnixsocketConnector::recv_message(Json& output) { - int rv; - std::string s_output, err; - - struct timeval t0, t; - - gettimeofday(&t0, NULL); + int rv = 0; + std::string s_output; + std::string err; + + struct timeval t0 + { + }; + struct timeval t + { + }; + + gettimeofday(&t0, nullptr); memcpy(&t, &t0, sizeof(t0)); s_output = ""; while ((t.tv_sec - t0.tv_sec) * 1000 + (t.tv_usec - t0.tv_usec) / 1000 < this->timeout) { int avail = waitForData(this->fd, 0, this->timeout * 500); // use half the timeout as poll timeout - if (avail < 0) // poll error + if (avail < 0) { // poll error return -1; + } if (avail == 0) { // timeout - gettimeofday(&t, NULL); + gettimeofday(&t, nullptr); continue; } rv = this->read(s_output); - if (rv == -1) + if (rv == -1) { return -1; + } if (rv > 0) { // see if it can be parsed output = Json::parse(s_output, err); - if (output != nullptr) + if (output != nullptr) { return s_output.size(); + } } - gettimeofday(&t, NULL); + gettimeofday(&t, nullptr); } close(fd); @@ -107,17 +117,19 @@ int UnixsocketConnector::recv_message(Json& output) ssize_t UnixsocketConnector::read(std::string& data) { - ssize_t nread; + ssize_t nread = 0; char buf[1500] = {0}; reconnect(); - if (!connected) + if (!connected) { return -1; + } nread = ::read(this->fd, buf, sizeof buf); // just try again later... - if (nread == -1 && errno == EAGAIN) + if (nread == -1 && errno == EAGAIN) { return 0; + } if (nread == -1 || nread == 0) { connected = false; @@ -134,8 +146,9 @@ ssize_t UnixsocketConnector::write(const std::string& data) size_t pos = 0; reconnect(); - if (!connected) + if (!connected) { return -1; + } while (pos < data.size()) { ssize_t written = ::write(fd, &data.at(pos), data.size() - pos); @@ -144,20 +157,21 @@ ssize_t UnixsocketConnector::write(const std::string& data) close(fd); return -1; } - else { - pos = pos + static_cast(written); - } + pos = pos + static_cast(written); } return pos; } void UnixsocketConnector::reconnect() { - struct sockaddr_un sock; - int rv; + struct sockaddr_un sock + { + }; + int rv = 0; - if (connected) + if (connected) { return; // no point reconnecting if connected... + } connected = true; g_log << Logger::Info << "Reconnecting to backend" << std::endl; @@ -169,7 +183,7 @@ void UnixsocketConnector::reconnect() return; } - if (makeUNsockaddr(path, &sock)) { + if (makeUNsockaddr(path, &sock) != 0) { g_log << Logger::Error << "Unable to create UNIX domain socket: Path '" << path << "' is not a valid UNIX socket path." << std::endl; return; } @@ -192,7 +206,7 @@ void UnixsocketConnector::reconnect() this->send(msg); msg = nullptr; - if (this->recv(msg) == false) { + if (!this->recv(msg)) { g_log << Logger::Warning << "Failed to initialize backend" << std::endl; close(fd); this->connected = false; diff --git a/modules/remotebackend/zmqconnector.cc b/modules/remotebackend/zmqconnector.cc index 86544eda20..cce0f3a5ea 100644 --- a/modules/remotebackend/zmqconnector.cc +++ b/modules/remotebackend/zmqconnector.cc @@ -59,13 +59,13 @@ ZeroMQConnector::ZeroMQConnector(std::map options) : this->send(msg); msg = nullptr; - if (this->recv(msg) == false) { + if (!this->recv(msg)) { g_log << Logger::Error << "Failed to initialize zeromq" << std::endl; throw PDNSException("Failed to initialize zeromq"); } }; -ZeroMQConnector::~ZeroMQConnector() {} +ZeroMQConnector::~ZeroMQConnector() = default; int ZeroMQConnector::send_message(const Json& input) { @@ -88,8 +88,9 @@ int ZeroMQConnector::send_message(const Json& input) // message was not sent g_log << Logger::Error << "Cannot send to " << this->d_endpoint << ": " << zmq_strerror(errno) << std::endl; } - else + else { return line.size(); + } } } } @@ -120,7 +121,7 @@ int ZeroMQConnector::recv_message(Json& output) // we have an event if ((item.revents & ZMQ_POLLIN) == ZMQ_POLLIN) { string data; - size_t msg_size; + size_t msg_size = 0; zmq_msg_init(&message); // read something if (zmq_msg_recv(&message, this->d_sock.get(), ZMQ_NOBLOCK) > 0) { @@ -129,18 +130,18 @@ int ZeroMQConnector::recv_message(Json& output) data.assign(reinterpret_cast(zmq_msg_data(&message)), msg_size); zmq_msg_close(&message); output = Json::parse(data, err); - if (output != nullptr) + if (output != nullptr) { rv = msg_size; - else + } + else { g_log << Logger::Error << "Cannot parse JSON reply from " << this->d_endpoint << ": " << err << endl; + } break; } - else if (errno == EAGAIN) { + if (errno == EAGAIN) { continue; // try again } } - else { - break; - } + break; } } }