server.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. /*************************************************************************
  2. *
  3. * Copyright (C) 2018-2023 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 (request.response_data_len == 0) {
  141. if (callback_ret == SERVER_REQUEST_OK) {
  142. request.response_data_len =
  143. dns_encode(request.response_data, request.response_data_max_len, request.response_packet);
  144. } else if (callback_ret == SERVER_REQUEST_SOA) {
  145. struct dns_soa soa;
  146. memset(&soa, 0, sizeof(soa));
  147. strncpy(soa.mname, "ns1.example.com", sizeof(soa.mname));
  148. strncpy(soa.rname, "hostmaster.example.com", sizeof(soa.rname));
  149. soa.serial = 1;
  150. soa.refresh = 3600;
  151. soa.retry = 600;
  152. soa.expire = 86400;
  153. soa.minimum = 3600;
  154. dns_packet_init(request.response_packet, sizeof(response_packet_buff), &head);
  155. dns_add_domain(request.response_packet, request.domain.c_str(), request.qtype, request.qclass);
  156. request.response_packet->head.rcode = DNS_RC_NXDOMAIN;
  157. dns_add_SOA(request.response_packet, DNS_RRS_AN, request.domain.c_str(), 1, &soa);
  158. request.response_data_len =
  159. dns_encode(request.response_data, request.response_data_max_len, request.response_packet);
  160. }
  161. }
  162. sendto(fd_, request.response_data, request.response_data_len, MSG_NOSIGNAL, (struct sockaddr *)&from,
  163. addrlen);
  164. }
  165. }
  166. }
  167. bool MockServer::AddIP(struct ServerRequestContext *request, const std::string &domain, const std::string &ip, int ttl)
  168. {
  169. struct sockaddr_storage addr;
  170. socklen_t addrlen = sizeof(addr);
  171. memset(&addr, 0, sizeof(addr));
  172. if (GetAddr(ip, "53", SOCK_DGRAM, IPPROTO_UDP, &addr, &addrlen)) {
  173. if (addr.ss_family == AF_INET) {
  174. struct sockaddr_in *addr4 = (struct sockaddr_in *)&addr;
  175. dns_add_A(request->response_packet, DNS_RRS_AN, domain.c_str(), ttl,
  176. (unsigned char *)&addr4->sin_addr.s_addr);
  177. } else if (addr.ss_family == AF_INET6) {
  178. struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&addr;
  179. if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
  180. dns_add_A(request->response_packet, DNS_RRS_AN, domain.c_str(), ttl,
  181. (unsigned char *)&addr6->sin6_addr.s6_addr[12]);
  182. return true;
  183. }
  184. dns_add_AAAA(request->response_packet, DNS_RRS_AN, domain.c_str(), ttl,
  185. (unsigned char *)&addr6->sin6_addr.s6_addr);
  186. }
  187. return true;
  188. }
  189. return false;
  190. }
  191. bool MockServer::GetAddr(const std::string &host, const std::string port, int type, int protocol,
  192. struct sockaddr_storage *addr, socklen_t *addrlen)
  193. {
  194. struct addrinfo hints;
  195. struct addrinfo *result = nullptr;
  196. memset(&hints, 0, sizeof(hints));
  197. hints.ai_family = AF_UNSPEC;
  198. hints.ai_socktype = type;
  199. hints.ai_protocol = protocol;
  200. hints.ai_flags = AI_PASSIVE;
  201. if (getaddrinfo(host.c_str(), port.c_str(), &hints, &result) != 0) {
  202. goto errout;
  203. }
  204. memcpy(addr, result->ai_addr, result->ai_addrlen);
  205. *addrlen = result->ai_addrlen;
  206. return true;
  207. errout:
  208. if (result) {
  209. freeaddrinfo(result);
  210. }
  211. return false;
  212. }
  213. bool MockServer::Start(const std::string &url, ServerRequest callback)
  214. {
  215. char c_scheme[256];
  216. char c_host[256];
  217. int port;
  218. char c_path[256];
  219. int fd;
  220. int yes = 1;
  221. struct sockaddr_storage addr;
  222. socklen_t addrlen;
  223. if (callback == nullptr) {
  224. return false;
  225. }
  226. if (parse_uri(url.c_str(), c_scheme, c_host, &port, c_path) != 0) {
  227. return false;
  228. }
  229. std::string scheme(c_scheme);
  230. std::string host(c_host);
  231. std::string path(c_path);
  232. if (scheme != "udp") {
  233. return false;
  234. }
  235. if (GetAddr(host, std::to_string(port), SOCK_DGRAM, IPPROTO_UDP, &addr, &addrlen) == false) {
  236. return false;
  237. }
  238. fd = socket(addr.ss_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
  239. if (fd < 0) {
  240. return false;
  241. }
  242. setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  243. setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes));
  244. if (bind(fd, (struct sockaddr *)&addr, addrlen) != 0) {
  245. close(fd);
  246. return false;
  247. }
  248. run_ = true;
  249. thread_ = std::thread(&MockServer::Run, this);
  250. fd_ = fd;
  251. callback_ = callback;
  252. return true;
  253. }
  254. Server::Server()
  255. {
  256. mode_ = Server::CREATE_MODE_FORK;
  257. }
  258. Server::Server(enum Server::CREATE_MODE mode)
  259. {
  260. mode_ = mode;
  261. }
  262. void Server::MockPing(PING_TYPE type, const std::string &host, int ttl, float time)
  263. {
  264. struct MockPingIP ping_ip;
  265. ping_ip.type = type;
  266. ping_ip.host = host;
  267. ping_ip.ttl = ttl;
  268. ping_ip.time = time;
  269. mock_ping_ips_.push_back(ping_ip);
  270. }
  271. void Server::StartPost(void *arg)
  272. {
  273. Server *server = (Server *)arg;
  274. bool has_ipv6 = false;
  275. for (auto &it : server->mock_ping_ips_) {
  276. if (has_ipv6 == false && check_is_ipv6(it.host.c_str()) == 0) {
  277. has_ipv6 = true;
  278. }
  279. fast_ping_fake_ip_add(it.type, it.host.c_str(), it.ttl, it.time);
  280. }
  281. if (has_ipv6 == true) {
  282. fast_ping_fake_ip_add(PING_TYPE_ICMP, "2001::", 64, 10);
  283. dns_server_check_ipv6_ready();
  284. }
  285. }
  286. bool Server::Start(const std::string &conf, enum CONF_TYPE type)
  287. {
  288. pid_t pid = 0;
  289. int fds[2];
  290. std::string conf_file;
  291. fds[0] = 0;
  292. fds[1] = 0;
  293. Defer
  294. {
  295. if (fds[0] > 0) {
  296. close(fds[0]);
  297. }
  298. if (fds[0] > 0) {
  299. close(fds[1]);
  300. }
  301. };
  302. if (type == CONF_TYPE_STRING) {
  303. conf_temp_file_.SetPattern("/tmp/smartdns_conf.XXXXXX");
  304. conf_temp_file_.Write(conf);
  305. conf_file = conf_temp_file_.GetPath();
  306. } else if (type == CONF_TYPE_FILE) {
  307. conf_file = conf;
  308. } else {
  309. return false;
  310. }
  311. if (access(conf_file.c_str(), F_OK) != 0) {
  312. return false;
  313. }
  314. conf_file_ = conf_file;
  315. if (pipe2(fds, O_CLOEXEC | O_NONBLOCK) != 0) {
  316. return false;
  317. }
  318. if (mode_ == CREATE_MODE_FORK) {
  319. pid = fork();
  320. if (pid == 0) {
  321. std::vector<std::string> args = {
  322. "smartdns", "-f", "-x", "-c", conf_file, "-p", "-",
  323. };
  324. char *argv[args.size() + 1];
  325. for (size_t i = 0; i < args.size(); i++) {
  326. argv[i] = (char *)args[i].c_str();
  327. }
  328. smartdns_reg_post_func(Server::StartPost, this);
  329. smartdns_main(args.size(), argv, fds[1]);
  330. _exit(1);
  331. } else if (pid < 0) {
  332. return false;
  333. }
  334. } else if (mode_ == CREATE_MODE_THREAD) {
  335. thread_ = std::thread([&]() {
  336. std::vector<std::string> args = {
  337. "smartdns", "-f", "-x", "-c", conf_file_, "-p", "-",
  338. };
  339. char *argv[args.size() + 1];
  340. for (size_t i = 0; i < args.size(); i++) {
  341. argv[i] = (char *)args[i].c_str();
  342. }
  343. smartdns_reg_post_func(Server::StartPost, this);
  344. smartdns_main(args.size(), argv, fds[1]);
  345. smartdns_reg_post_func(nullptr, nullptr);
  346. });
  347. } else {
  348. return false;
  349. }
  350. struct pollfd pfd[1];
  351. pfd[0].fd = fds[0];
  352. pfd[0].events = POLLIN;
  353. int ret = poll(pfd, 1, 10000);
  354. if (ret == 0) {
  355. if (thread_.joinable()) {
  356. thread_.join();
  357. }
  358. if (pid > 0) {
  359. kill(pid, SIGKILL);
  360. }
  361. return false;
  362. }
  363. pid_ = pid;
  364. return pid > 0;
  365. }
  366. void Server::Stop(bool graceful)
  367. {
  368. if (thread_.joinable()) {
  369. dns_server_stop();
  370. thread_.join();
  371. }
  372. if (pid_ > 0) {
  373. if (graceful) {
  374. kill(pid_, SIGTERM);
  375. } else {
  376. kill(pid_, SIGKILL);
  377. }
  378. }
  379. waitpid(pid_, nullptr, 0);
  380. pid_ = 0;
  381. }
  382. bool Server::IsRunning()
  383. {
  384. if (pid_ <= 0) {
  385. return false;
  386. }
  387. if (waitpid(pid_, nullptr, WNOHANG) == 0) {
  388. return true;
  389. }
  390. return kill(pid_, 0) == 0;
  391. }
  392. Server::~Server()
  393. {
  394. Stop(false);
  395. }
  396. } // namespace smartdns