server.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. /*************************************************************************
  2. *
  3. * Copyright (C) 2018-2024 Ruilin Peng (Nick) <[email protected]>.
  4. *
  5. * smartdns is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * smartdns is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include "server.h"
  19. #include "dns_server.h"
  20. #include "fast_ping.h"
  21. #include "include/utils.h"
  22. #include "smartdns.h"
  23. #include "util.h"
  24. #include <arpa/inet.h>
  25. #include <fcntl.h>
  26. #include <fstream>
  27. #include <netinet/in.h>
  28. #include <poll.h>
  29. #include <signal.h>
  30. #include <string>
  31. #include <sys/socket.h>
  32. #include <sys/types.h>
  33. #include <sys/wait.h>
  34. #include <unistd.h>
  35. #include <vector>
  36. namespace smartdns
  37. {
  38. MockServer::MockServer() {}
  39. MockServer::~MockServer()
  40. {
  41. Stop();
  42. }
  43. bool MockServer::IsRunning()
  44. {
  45. if (fd_ > 0) {
  46. return true;
  47. }
  48. return false;
  49. }
  50. void MockServer::Stop()
  51. {
  52. if (run_ == true) {
  53. run_ = false;
  54. if (thread_.joinable()) {
  55. thread_.join();
  56. }
  57. }
  58. if (fd_ > 0) {
  59. close(fd_);
  60. fd_;
  61. }
  62. }
  63. void MockServer::Run()
  64. {
  65. while (run_ == true) {
  66. struct pollfd fds[1];
  67. fds[0].fd = fd_;
  68. fds[0].events = POLLIN;
  69. fds[0].revents = 0;
  70. int ret = poll(fds, 1, 100);
  71. if (ret == 0) {
  72. continue;
  73. } else if (ret < 0) {
  74. sleep(1);
  75. continue;
  76. }
  77. if (fds[0].revents & POLLIN) {
  78. struct sockaddr_storage from;
  79. socklen_t addrlen = sizeof(from);
  80. unsigned char in_buff[4096];
  81. int query_id = 0;
  82. int len = recvfrom(fd_, in_buff, sizeof(in_buff), 0, (struct sockaddr *)&from, &addrlen);
  83. if (len < 0) {
  84. continue;
  85. }
  86. char packet_buff[4096];
  87. unsigned char response_data_buff[4096];
  88. unsigned char response_packet_buff[4096];
  89. memset(packet_buff, 0, sizeof(packet_buff));
  90. struct dns_packet *packet = (struct dns_packet *)packet_buff;
  91. struct ServerRequestContext request;
  92. memset(&request, 0, sizeof(request));
  93. int ret = dns_decode(packet, sizeof(packet_buff), in_buff, len);
  94. if (ret == 0) {
  95. request.packet = packet;
  96. query_id = packet->head.id;
  97. if (packet->head.qr == DNS_QR_QUERY) {
  98. struct dns_rrs *rrs = nullptr;
  99. int rr_count = 0;
  100. int qtype = 0;
  101. int qclass = 0;
  102. char domain[256];
  103. rrs = dns_get_rrs_start(packet, DNS_RRS_QD, &rr_count);
  104. for (int i = 0; i < rr_count && rrs; i++, rrs = dns_get_rrs_next(packet, rrs)) {
  105. ret = dns_get_domain(rrs, domain, sizeof(domain), &qtype, &qclass);
  106. if (ret == 0) {
  107. request.domain = domain;
  108. request.qtype = (dns_type)qtype;
  109. request.qclass = qclass;
  110. break;
  111. }
  112. }
  113. }
  114. }
  115. request.from = (struct sockaddr_storage *)&from;
  116. request.fromlen = addrlen;
  117. request.request_data = in_buff;
  118. request.request_data_len = len;
  119. request.response_packet = (struct dns_packet *)response_packet_buff;
  120. request.response_data = response_data_buff;
  121. request.response_data_len = 0;
  122. request.response_data_max_len = sizeof(response_data_buff);
  123. struct dns_head head;
  124. memset(&head, 0, sizeof(head));
  125. head.id = query_id;
  126. head.qr = DNS_QR_ANSWER;
  127. head.opcode = DNS_OP_QUERY;
  128. head.aa = 0;
  129. head.rd = 0;
  130. head.ra = 1;
  131. head.rcode = DNS_RC_NOERROR;
  132. dns_packet_init(request.response_packet, sizeof(response_packet_buff), &head);
  133. auto callback_ret = callback_(&request);
  134. if (callback_ret == SERVER_REQUEST_ERROR) {
  135. dns_packet_init(request.response_packet, sizeof(response_packet_buff), &head);
  136. request.response_packet->head.rcode = DNS_RC_SERVFAIL;
  137. dns_add_domain(request.response_packet, request.domain.c_str(), request.qtype, request.qclass);
  138. request.response_data_len =
  139. dns_encode(request.response_data, request.response_data_max_len, request.response_packet);
  140. } else if (callback_ret == SERVER_REQUEST_NO_RESPONSE) {
  141. continue;
  142. } else if (request.response_data_len == 0) {
  143. if (callback_ret == SERVER_REQUEST_OK) {
  144. request.response_data_len =
  145. dns_encode(request.response_data, request.response_data_max_len, request.response_packet);
  146. } else if (callback_ret == SERVER_REQUEST_SOA) {
  147. struct dns_soa soa;
  148. memset(&soa, 0, sizeof(soa));
  149. strncpy(soa.mname, "ns1.example.com", sizeof(soa.mname));
  150. strncpy(soa.rname, "hostmaster.example.com", sizeof(soa.rname));
  151. soa.serial = 1;
  152. soa.refresh = 3600;
  153. soa.retry = 600;
  154. soa.expire = 86400;
  155. soa.minimum = 3600;
  156. dns_packet_init(request.response_packet, sizeof(response_packet_buff), &head);
  157. dns_add_domain(request.response_packet, request.domain.c_str(), request.qtype, request.qclass);
  158. request.response_packet->head.rcode = DNS_RC_NXDOMAIN;
  159. dns_add_SOA(request.response_packet, DNS_RRS_AN, request.domain.c_str(), 1, &soa);
  160. request.response_data_len =
  161. dns_encode(request.response_data, request.response_data_max_len, request.response_packet);
  162. }
  163. }
  164. sendto(fd_, request.response_data, request.response_data_len, MSG_NOSIGNAL, (struct sockaddr *)&from,
  165. addrlen);
  166. }
  167. }
  168. }
  169. bool MockServer::AddIP(struct ServerRequestContext *request, const std::string &domain, const std::string &ip, int ttl)
  170. {
  171. struct sockaddr_storage addr;
  172. socklen_t addrlen = sizeof(addr);
  173. memset(&addr, 0, sizeof(addr));
  174. if (GetAddr(ip, "53", SOCK_DGRAM, IPPROTO_UDP, &addr, &addrlen)) {
  175. if (addr.ss_family == AF_INET) {
  176. struct sockaddr_in *addr4 = (struct sockaddr_in *)&addr;
  177. dns_add_A(request->response_packet, DNS_RRS_AN, domain.c_str(), ttl,
  178. (unsigned char *)&addr4->sin_addr.s_addr);
  179. } else if (addr.ss_family == AF_INET6) {
  180. struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&addr;
  181. if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
  182. dns_add_A(request->response_packet, DNS_RRS_AN, domain.c_str(), ttl,
  183. (unsigned char *)&addr6->sin6_addr.s6_addr[12]);
  184. return true;
  185. }
  186. dns_add_AAAA(request->response_packet, DNS_RRS_AN, domain.c_str(), ttl,
  187. (unsigned char *)&addr6->sin6_addr.s6_addr);
  188. }
  189. return true;
  190. }
  191. return false;
  192. }
  193. bool MockServer::GetAddr(const std::string &host, const std::string port, int type, int protocol,
  194. struct sockaddr_storage *addr, socklen_t *addrlen)
  195. {
  196. struct addrinfo hints;
  197. struct addrinfo *result = nullptr;
  198. memset(&hints, 0, sizeof(hints));
  199. hints.ai_family = AF_UNSPEC;
  200. hints.ai_socktype = type;
  201. hints.ai_protocol = protocol;
  202. hints.ai_flags = AI_PASSIVE;
  203. if (getaddrinfo(host.c_str(), port.c_str(), &hints, &result) != 0) {
  204. goto errout;
  205. }
  206. memcpy(addr, result->ai_addr, result->ai_addrlen);
  207. *addrlen = result->ai_addrlen;
  208. return true;
  209. errout:
  210. if (result) {
  211. freeaddrinfo(result);
  212. }
  213. return false;
  214. }
  215. bool MockServer::Start(const std::string &url, ServerRequest callback)
  216. {
  217. char c_scheme[256];
  218. char c_host[256];
  219. int port;
  220. char c_path[256];
  221. int fd;
  222. int yes = 1;
  223. struct sockaddr_storage addr;
  224. socklen_t addrlen;
  225. if (callback == nullptr) {
  226. return false;
  227. }
  228. if (parse_uri(url.c_str(), c_scheme, c_host, &port, c_path) != 0) {
  229. return false;
  230. }
  231. std::string scheme(c_scheme);
  232. std::string host(c_host);
  233. std::string path(c_path);
  234. if (scheme != "udp") {
  235. return false;
  236. }
  237. if (GetAddr(host, std::to_string(port), SOCK_DGRAM, IPPROTO_UDP, &addr, &addrlen) == false) {
  238. return false;
  239. }
  240. fd = socket(addr.ss_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
  241. if (fd < 0) {
  242. return false;
  243. }
  244. setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  245. setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes));
  246. if (bind(fd, (struct sockaddr *)&addr, addrlen) != 0) {
  247. close(fd);
  248. return false;
  249. }
  250. run_ = true;
  251. thread_ = std::thread(&MockServer::Run, this);
  252. fd_ = fd;
  253. callback_ = callback;
  254. return true;
  255. }
  256. Server::Server()
  257. {
  258. mode_ = Server::CREATE_MODE_FORK;
  259. }
  260. Server::Server(enum Server::CREATE_MODE mode)
  261. {
  262. mode_ = mode;
  263. }
  264. void Server::MockPing(PING_TYPE type, const std::string &host, int ttl, float time)
  265. {
  266. struct MockPingIP ping_ip;
  267. ping_ip.type = type;
  268. ping_ip.host = host;
  269. ping_ip.ttl = ttl;
  270. ping_ip.time = time;
  271. mock_ping_ips_.push_back(ping_ip);
  272. }
  273. void Server::StartPost(void *arg)
  274. {
  275. Server *server = (Server *)arg;
  276. bool has_ipv6 = false;
  277. for (auto &it : server->mock_ping_ips_) {
  278. if (has_ipv6 == false && check_is_ipv6(it.host.c_str()) == 0) {
  279. has_ipv6 = true;
  280. }
  281. fast_ping_fake_ip_add(it.type, it.host.c_str(), it.ttl, it.time);
  282. }
  283. if (has_ipv6 == true) {
  284. fast_ping_fake_ip_add(PING_TYPE_ICMP, "2001::", 64, 10);
  285. dns_server_check_ipv6_ready();
  286. }
  287. }
  288. bool Server::Start(const std::string &conf, enum CONF_TYPE type)
  289. {
  290. pid_t pid = 0;
  291. int fds[2];
  292. std::string conf_file;
  293. fds[0] = 0;
  294. fds[1] = 0;
  295. Defer
  296. {
  297. if (fds[0] > 0) {
  298. close(fds[0]);
  299. }
  300. if (fds[0] > 0) {
  301. close(fds[1]);
  302. }
  303. };
  304. const char *default_conf = R"""(
  305. log-num 0
  306. log-console yes
  307. log-level debug
  308. cache-persist no
  309. )""";
  310. if (type == CONF_TYPE_STRING) {
  311. conf_temp_file_.SetPattern("/tmp/smartdns_conf.XXXXXX");
  312. conf_temp_file_.Write(default_conf);
  313. conf_temp_file_.Write(conf);
  314. conf_file = conf_temp_file_.GetPath();
  315. } else if (type == CONF_TYPE_FILE) {
  316. conf_file = conf;
  317. } else {
  318. return false;
  319. }
  320. if (access(conf_file.c_str(), F_OK) != 0) {
  321. return false;
  322. }
  323. conf_file_ = conf_file;
  324. if (pipe2(fds, O_CLOEXEC | O_NONBLOCK) != 0) {
  325. return false;
  326. }
  327. if (mode_ == CREATE_MODE_FORK) {
  328. pid = fork();
  329. if (pid == 0) {
  330. std::vector<std::string> args = {
  331. "smartdns", "-f", "-x", "-c", conf_file, "-p", "-",
  332. };
  333. char *argv[args.size() + 1];
  334. for (size_t i = 0; i < args.size(); i++) {
  335. argv[i] = (char *)args[i].c_str();
  336. }
  337. smartdns_reg_post_func(Server::StartPost, this);
  338. smartdns_main(args.size(), argv, fds[1], 0);
  339. _exit(1);
  340. } else if (pid < 0) {
  341. return false;
  342. }
  343. } else if (mode_ == CREATE_MODE_THREAD) {
  344. thread_ = std::thread([&]() {
  345. std::vector<std::string> args = {"smartdns", "-f", "-x", "-c", conf_file_, "-p", "-", "-S"};
  346. char *argv[args.size() + 1];
  347. for (size_t i = 0; i < args.size(); i++) {
  348. argv[i] = (char *)args[i].c_str();
  349. }
  350. smartdns_reg_post_func(Server::StartPost, this);
  351. smartdns_main(args.size(), argv, fds[1], 1);
  352. smartdns_reg_post_func(nullptr, nullptr);
  353. });
  354. } else {
  355. return false;
  356. }
  357. struct pollfd pfd[1];
  358. pfd[0].fd = fds[0];
  359. pfd[0].events = POLLIN;
  360. int ret = poll(pfd, 1, 10000);
  361. if (ret == 0) {
  362. if (thread_.joinable()) {
  363. thread_.join();
  364. }
  365. if (pid > 0) {
  366. kill(pid, SIGKILL);
  367. }
  368. return false;
  369. }
  370. pid_ = pid;
  371. return pid > 0;
  372. }
  373. void Server::Stop(bool graceful)
  374. {
  375. if (thread_.joinable()) {
  376. dns_server_stop();
  377. thread_.join();
  378. }
  379. if (pid_ > 0) {
  380. if (graceful) {
  381. kill(pid_, SIGTERM);
  382. } else {
  383. kill(pid_, SIGKILL);
  384. }
  385. }
  386. waitpid(pid_, nullptr, 0);
  387. pid_ = 0;
  388. }
  389. bool Server::IsRunning()
  390. {
  391. if (pid_ <= 0) {
  392. return false;
  393. }
  394. if (waitpid(pid_, nullptr, WNOHANG) == 0) {
  395. return true;
  396. }
  397. return kill(pid_, 0) == 0;
  398. }
  399. Server::~Server()
  400. {
  401. Stop(false);
  402. }
  403. } // namespace smartdns