server.cc 11 KB

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