Explore Enterprise Education Gitee Premium Gitee AI AI teammates
Fetch the repository succeeded.
Open Source > Development Lib > Common Toolkit &&
Donate
Please sign in before you donate.
Scan WeChat QR to Pay
Cancel
Complete
Prompt
Switch to Alipay.
OK
Cancel
103 Star 575 Fork 242

cpp-master/cpp-tbox

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
Already have an account? Sign in
文件
develop
Branches (18)
Tags (32)
master
develop
opt/websocket
feat/http-client
feature/tls-crypto-https
fix/jsonrpc
feat/mqtt-reconnect
tidy/doc
wlabs-develop
fix/terminal-mem-leak
feat/use-config-enable-epoll
feature-Broker
opt-loop-wdog
feature-DBus
feature-epoll
feature-update-readme
feature-Dns
feature-TcpSSL
v1.15.5
v1.15.4
v1.14.4
v1.13.10
v1.13.2
v1.12.28
v1.12.25
v1.12.22
v1.12.20
v1.12.10
v1.12.0
v1.11.14
v1.11.12
v1.11.11
v1.11.5
v1.11.4
v1.11.2
v1.11.0
v1.10.27
v1.10.23
develop
Branches (18)
Tags (32)
master
develop
opt/websocket
feat/http-client
feature/tls-crypto-https
fix/jsonrpc
feat/mqtt-reconnect
tidy/doc
wlabs-develop
fix/terminal-mem-leak
feat/use-config-enable-epoll
feature-Broker
opt-loop-wdog
feature-DBus
feature-epoll
feature-update-readme
feature-Dns
feature-TcpSSL
v1.15.5
v1.15.4
v1.14.4
v1.13.10
v1.13.2
v1.12.28
v1.12.25
v1.12.22
v1.12.20
v1.12.10
v1.12.0
v1.11.14
v1.11.12
v1.11.11
v1.11.5
v1.11.4
v1.11.2
v1.11.0
v1.10.27
v1.10.23
Clone or Download
Clone/Download
Prompt
To download the code, please copy the following command and execute it in the terminal
To ensure that your submitted code identity is correctly recognized by Gitee, please execute the following command.
When using the SSH protocol for the first time to clone or push code, follow the prompts below to complete the SSH configuration.
1 Generate RSA keys.
2 Obtain the content of the RSA public key and configure it in SSH Public Keys
To use SVN on Gitee, please visit the usage guide
When using the HTTPS protocol, the command line will prompt for account and password verification as follows. For security reasons, Gitee recommends configure and use personal access tokens instead of login passwords for cloning, pushing, and other operations.
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # Private Token
develop
Branches (18)
Tags (32)
master
develop
opt/websocket
feat/http-client
feature/tls-crypto-https
fix/jsonrpc
feat/mqtt-reconnect
tidy/doc
wlabs-develop
fix/terminal-mem-leak
feat/use-config-enable-epoll
feature-Broker
opt-loop-wdog
feature-DBus
feature-epoll
feature-update-readme
feature-Dns
feature-TcpSSL
v1.15.5
v1.15.4
v1.14.4
v1.13.10
v1.13.2
v1.12.28
v1.12.25
v1.12.22
v1.12.20
v1.12.10
v1.12.0
v1.11.14
v1.11.12
v1.11.11
v1.11.5
v1.11.4
v1.11.2
v1.11.0
v1.10.27
v1.10.23
cpp-tbox
/
modules
/
network
/
dns_request.cpp
cpp-tbox
/
modules
/
network
/
dns_request.cpp
dns_request.cpp 8.87 KB
Copy Edit Raw Blame History
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 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
/*
* .============.
* // M A K E / \
* // C++ DEV / \
* // E A S Y / \/ \
* ++ ----------. \/\ .
* \\ \ \ /\ /
* \\ \ \ /
* \\ \ \ /
* -============'
*
* Copyright (c) 2018 Hevake and contributors, all rights reserved.
*
* This file is part of cpp-tbox (https://github.com/cpp-main/cpp-tbox)
* Use of this source code is governed by MIT license that can be found
* in the LICENSE file in the root of the source tree. All contributing
* project authors may be found in the CONTRIBUTORS.md file in the root
* of the source tree.
*/
#include "dns_request.h"
#include <unistd.h>
#include <sstream>
#include <map>
#include <memory>
#include <tbox/base/assert.h>
#include <tbox/base/wrapped_recorder.h>
#include <tbox/util/serializer.h>
#include <tbox/util/string.h>
#include <tbox/util/fs.h>
#undef MODULE_ID
#define MODULE_ID "tbox.dns"
namespace tbox {
namespace network {
namespace {
enum DNS_TYPE {
DNS_TYPE_A = 1, //!< 期望获得查询名的IP地址
DNS_TYPE_NS = 2, //!< 一个授权的域名服务器
DNS_TYPE_CNAME = 5, //!< 规范名称
DNS_TYPE_PTR = 12, //!< 指针记录
DNS_TYPE_HINFO = 13, //!< 主机信息
DNS_TYPE_MX = 15, //!< 邮件交换记录
DNS_TYPE_AXFR = 252, //!< 对区域转换的请求
DNS_TYPE_ANY = 255, //!< 对所有记录的请求
};
enum DNS_CLASS {
DNS_CLASS_IN = 1, //!< 互联网地址
};
enum DNS_RC {
DNS_RC_FORMAT_ERROR = 1, //!< 数据包格式错误
DNS_RC_SERVER_FAIL = 2, //!< 服务器的错误
DNS_RC_NAME_ERROR = 3, //!< 名称不存在
DNS_RC_NOT_IMPL = 4, //!< 服务器不支持查询
DNS_RC_REFUSED = 5, //!< 服务器拒绝
};
/// 将domain写入到缓冲
/**
* "www.baidu.com\x0" --> "\x03www0円x5baidu0円x3com0円x0"
*/
void AppendDomain(util::Serializer &dump, const std::string domain)
{
std::vector<std::string> str_vec;
util::string::Split(domain, ".", str_vec);
for (auto &seg : str_vec) {
dump << uint8_t(seg.length());
dump.append(seg.data(), seg.length());
}
dump << uint8_t(0);
}
/// 从缓冲中提取domain,与AppendDomain()相反
std::string FetchDomain(util::Deserializer &parser)
{
std::ostringstream oss;
bool first = true;
for (;;) {
uint8_t len = 0;
parser >> len;
if (len == 0)
break;
if (!first)
oss << '.';
first = false;
//! 处理压缩的字串
if ((len & 0xc0) == 0xc0) {
uint8_t offset_low = 0;
parser >> offset_low;
uint16_t offset = (len & 0x3f) << 8 | offset_low;
util::Deserializer sub_parser(parser);
sub_parser.set_pos(offset);
oss << FetchDomain(sub_parser);
break;
} else {
char str[len + 1];
parser.fetch(str, len);
str[len] = '0円';
oss << str;
}
}
return oss.str();
}
}
DnsRequest::DnsRequest(event::Loop *wp_loop) :
udp_(wp_loop),
timeout_monitor_(wp_loop)
{
init();
}
DnsRequest::DnsRequest(event::Loop *wp_loop, const IPAddressVec &dns_ip_vec) :
udp_(wp_loop),
timeout_monitor_(wp_loop),
dns_ip_vec_(dns_ip_vec)
{
init();
}
DnsRequest::~DnsRequest() {
udp_.disable();
}
void DnsRequest::init()
{
using namespace std::placeholders;
udp_.setRecvCallback(std::bind(&DnsRequest::onUdpRecv, this, _1, _2, _3));
timeout_monitor_.initialize(std::chrono::seconds(1), 5);
timeout_monitor_.setCallback(std::bind(&DnsRequest::onRequestTimeout, this, _1));
}
void DnsRequest::setDnsIPAddresses(const IPAddressVec &dns_ip_vec)
{
dns_ip_vec_ = dns_ip_vec;
}
DnsRequest::ReqId DnsRequest::request(const DomainName &domain, const Callback &cb)
{
if (dns_ip_vec_.empty()) {
LogWarn("dns srv ip not specify");
return false;
}
ReqId req_id = ++req_id_alloc_;
std::vector<uint8_t> send_buff;
util::Serializer dump(send_buff);
uint16_t flags = 0x0100; //!< QR:请求, OPCODE:标准查询, RA:期望递归
uint16_t qd_count = 1;
uint16_t an_count = 0;
uint16_t ns_count = 0;
uint16_t ar_count = 0;
dump << req_id
<< flags
<< qd_count
<< an_count
<< ns_count
<< ar_count;
AppendDomain(dump, domain.toString());
uint16_t dns_type = DNS_TYPE_A;
uint16_t dns_class = DNS_CLASS_IN;
dump << dns_type
<< dns_class;
#if 0
std::string hex_str = util::string::RawDataToHexStr(send_buff.data(), send_buff.size());
LogTrace("send data: %s", hex_str.c_str());
#endif
for (auto &ip : dns_ip_vec_) {
SockAddr dns_srv(ip, 53);
udp_.send(send_buff.data(), send_buff.size(), dns_srv);
}
addRequest(req_id, cb);
return req_id;
}
bool DnsRequest::cancel(ReqId req_id)
{
return deleteRequest(req_id);
}
bool DnsRequest::isRunning(ReqId req_id) const
{
auto iter = requests_.find(req_id);
return iter != requests_.end();
}
void DnsRequest::onUdpRecv(const void *data_ptr, size_t data_size, const SockAddr &from)
{
#if 0
std::string hex_str = util::string::RawDataToHexStr(data_ptr, data_size);
LogTrace("recv from %s : %s", from.toString().c_str(), hex_str.c_str());
#endif
if (requests_.empty())
return;
RECORD_SCOPE();
util::Deserializer parser(data_ptr, data_size);
uint16_t req_id, flags;
parser >> req_id >> flags;
Request *req = findRequest(req_id);
if (req == nullptr)
return;
if ((flags & 0x8000) == 0) //! 必须是回复包
return;
//! 检查flags
uint8_t rcode = flags & 0x000f;
Result result;
if (rcode == 0) { //! 正常
uint16_t qd_count, an_count, ns_count, ar_count;
parser >> qd_count >> an_count >> ns_count >> ar_count;
#if 0
LogTrace("id:%d, flags:%04x, qd_count:%d, an_count:%d, ns_count:%d, ar_count:%d",
id, flags, qd_count, an_count, an_count, ns_count, ar_count);
#endif
//! 解析Question字段
for (uint16_t i = 0; i < qd_count; ++i) {
FetchDomain(parser);
uint16_t dns_type, dns_class;
parser >> dns_type >> dns_class;
}
for (uint16_t i = 0; i < an_count; ++i) {
FetchDomain(parser);
uint16_t an_type, an_class, an_len;
uint32_t an_ttl;
parser >> an_type >> an_class >> an_ttl >> an_len;
#if 0
LogTrace("type:%d, class:%d, ttl:%d, len:%d", an_type, an_class, an_ttl, an_len);
#endif
if (an_type == DNS_TYPE_A) {
uint32_t ip_value;
auto old_endian = parser.setEndian(util::Endian::kLittle);
parser >> ip_value;
parser.setEndian(old_endian);
A a = { an_ttl, IPAddress(ip_value) };
result.a_vec.push_back(a);
} else if (an_type == DNS_TYPE_CNAME) {
std::string domain = FetchDomain(parser);
CNAME cname = { an_ttl, DomainName(domain) };
result.cname_vec.push_back(cname);
} else {
LogNotice("unknow type:%d", an_type);
parser.skip(an_len);
}
}
} else {
//! 出现异常
if (rcode == DNS_RC_NAME_ERROR) {
//! 如果是域名自身的问题,则直接返回失败
result.status = Result::Status::kDomainError;
} else if (rcode == DNS_RC_FORMAT_ERROR) {
LogNotice("dns packet error"); //! 不应该发生
result.status = Result::Status::kFail;
} else {
//! 如果是服务器的问题,则略过当前数据,等待其它服务器的数据
++req->response_count;
if (req->response_count < dns_ip_vec_.size())
return;
result.status = Result::Status::kAllDnsFail;
}
}
if (req->cb)
req->cb(result);
deleteRequest(req_id);
(void)from;
}
void DnsRequest::onRequestTimeout(ReqId req_id)
{
auto req = findRequest(req_id);
if (req == nullptr)
return;
Result result;
result.status = Result::Status::kTimeout;
if (req->cb)
req->cb(result);
deleteRequest(req_id);
}
void DnsRequest::addRequest(ReqId req_id, const Callback &cb)
{
if (requests_.empty())
udp_.enable();
Request req;
req.cb = cb;
requests_[req_id] = req;
timeout_monitor_.add(req_id);
}
DnsRequest::Request* DnsRequest::findRequest(ReqId req_id)
{
auto iter = requests_.find(req_id);
if (iter != requests_.end())
return &(iter->second);
return nullptr;
}
bool DnsRequest::deleteRequest(ReqId req_id)
{
auto iter = requests_.find(req_id);
if (iter != requests_.end()) {
requests_.erase(iter);
if (requests_.empty())
udp_.disable();
return true;
}
return false;
}
}
}
Loading...
Report
Report success
We will send you the feedback within 2 working days through the letter!
Please fill in the reason for the report carefully. Provide as detailed a description as possible.
Please select a report type
Cancel
Send
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

About

cpp-tbox是一个Linux C++,MIT开源许可的,基于 Reactor 模式的开发框架与组件库。它主要针对智能硬件、机器人、网络服务等开发领域。 它提供了一套易于开发、稳定可靠的框架,有:通信库(TCP/UDP/串口)、HTTP、线程池、定时器池、协程、日志、命令终端、状态机、行为树等非常实用的开发组件,以及完备实用的主框架,能为广大开发者节省大量开发与调试时间。
Cancel

Releases

No release

The Open Source Evaluation Index is derived from the OSS Compass evaluation system, which evaluates projects around the following three dimensions

1. Open source ecosystem

  • Productivity: To evaluate the ability of open-source projects to output software artifacts and open-source value.
  • Innovation: Used to evaluate the degree of diversity of open source software and its ecosystem.
  • Robustness: Used to evaluate the ability of open-source projects to resist internal and external interference and self recover in the face of changing development environments.

2. Collaboration, People, Software

  • Collaboration: represents the degree and depth of collaboration in open source development behavior.
  • Observe the influence of core personnel in open source projects, and examine the evaluations of users and developers on open source projects from a third-party perspective.
  • Software: Evaluate the value of products exported from open-source projects and their ultimate destination. It is also a concrete manifestation of "open source software", one of the oldest mainstream directions in open source evaluation.

3. Evaluation model

    Based on the dimensions of "open source ecosystem" and "collaboration, people, and software", identify quantifiable indicators directly or indirectly related to this goal, quantitatively evaluate the health and ecology of open source projects, and ultimately form an open source evaluation index.

Contributors

All

Activities

can not load any more
Edit
About
Homepage
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/cpp-master/cpp-tbox.git
git@gitee.com:cpp-master/cpp-tbox.git
cpp-master
cpp-tbox
cpp-tbox
develop
Going to Help Center

Search

Comment
Repository Report
Back to the top
Login prompt
This operation requires login to the code cloud account. Please log in before operating.
Go to login
No account. Register

AltStyle によって変換されたページ (->オリジナル) /