server.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. struct sockaddr_storage addr;
  221. socklen_t addrlen;
  222. if (callback == nullptr) {
  223. return false;
  224. }
  225. if (parse_uri(url.c_str(), c_scheme, c_host, &port, c_path) != 0) {
  226. return false;
  227. }
  228. std::string scheme(c_scheme);
  229. std::string host(c_host);
  230. std::string path(c_path);
  231. if (scheme != "udp") {
  232. return false;
  233. }
  234. if (GetAddr(host, std::to_string(port), SOCK_DGRAM, IPPROTO_UDP, &addr, &addrlen) == false) {
  235. return false;
  236. }
  237. fd = socket(addr.ss_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
  238. if (fd < 0) {
  239. return false;
  240. }
  241. if (bind(fd, (struct sockaddr *)&addr, addrlen) != 0) {
  242. close(fd);
  243. return false;
  244. }
  245. run_ = true;
  246. thread_ = std::thread(&MockServer::Run, this);
  247. fd_ = fd;
  248. callback_ = callback;
  249. return true;
  250. }
  251. Server::Server()
  252. {
  253. mode_ = Server::CREATE_MODE_FORK;
  254. }
  255. Server::Server(enum Server::CREATE_MODE mode)
  256. {
  257. mode_ = mode;
  258. }
  259. void Server::MockPing(PING_TYPE type, const std::string &host, int ttl, float time)
  260. {
  261. struct MockPingIP ping_ip;
  262. ping_ip.type = type;
  263. ping_ip.host = host;
  264. ping_ip.ttl = ttl;
  265. ping_ip.time = time;
  266. mock_ping_ips_.push_back(ping_ip);
  267. }
  268. void Server::StartPost(void *arg)
  269. {
  270. Server *server = (Server *)arg;
  271. bool has_ipv6 = false;
  272. for (auto &it : server->mock_ping_ips_) {
  273. if (has_ipv6 == false && check_is_ipv6(it.host.c_str()) == 0) {
  274. has_ipv6 = true;
  275. }
  276. fast_ping_fake_ip_add(it.type, it.host.c_str(), it.ttl, it.time);
  277. }
  278. if (has_ipv6 == true) {
  279. fast_ping_fake_ip_add(PING_TYPE_ICMP, "2001::", 64, 10);
  280. dns_server_check_ipv6_ready();
  281. }
  282. }
  283. bool Server::Start(const std::string &conf, enum CONF_TYPE type)
  284. {
  285. pid_t pid = 0;
  286. int fds[2];
  287. std::string conf_file;
  288. fds[0] = 0;
  289. fds[1] = 0;
  290. Defer
  291. {
  292. if (fds[0] > 0) {
  293. close(fds[0]);
  294. }
  295. if (fds[0] > 0) {
  296. close(fds[1]);
  297. }
  298. };
  299. if (type == CONF_TYPE_STRING) {
  300. conf_temp_file_.SetPattern("/tmp/smartdns_conf.XXXXXX");
  301. conf_temp_file_.Write(conf);
  302. conf_file = conf_temp_file_.GetPath();
  303. } else if (type == CONF_TYPE_FILE) {
  304. conf_file = conf;
  305. } else {
  306. return false;
  307. }
  308. if (access(conf_file.c_str(), F_OK) != 0) {
  309. return false;
  310. }
  311. conf_file_ = conf_file;
  312. if (pipe2(fds, O_CLOEXEC | O_NONBLOCK) != 0) {
  313. return false;
  314. }
  315. if (mode_ == CREATE_MODE_FORK) {
  316. pid = fork();
  317. if (pid == 0) {
  318. std::vector<std::string> args = {
  319. "smartdns", "-f", "-x", "-c", conf_file, "-p", "-",
  320. };
  321. char *argv[args.size() + 1];
  322. for (size_t i = 0; i < args.size(); i++) {
  323. argv[i] = (char *)args[i].c_str();
  324. }
  325. smartdns_reg_post_func(Server::StartPost, this);
  326. smartdns_main(args.size(), argv, fds[1]);
  327. _exit(1);
  328. } else if (pid < 0) {
  329. return false;
  330. }
  331. } else if (mode_ == CREATE_MODE_THREAD) {
  332. thread_ = std::thread([&]() {
  333. std::vector<std::string> args = {
  334. "smartdns", "-f", "-x", "-c", conf_file_, "-p", "-",
  335. };
  336. char *argv[args.size() + 1];
  337. for (size_t i = 0; i < args.size(); i++) {
  338. argv[i] = (char *)args[i].c_str();
  339. }
  340. smartdns_reg_post_func(Server::StartPost, this);
  341. smartdns_main(args.size(), argv, fds[1]);
  342. smartdns_reg_post_func(nullptr, nullptr);
  343. });
  344. } else {
  345. return false;
  346. }
  347. struct pollfd pfd[1];
  348. pfd[0].fd = fds[0];
  349. pfd[0].events = POLLIN;
  350. int ret = poll(pfd, 1, 10000);
  351. if (ret == 0) {
  352. if (thread_.joinable()) {
  353. thread_.join();
  354. }
  355. if (pid > 0) {
  356. kill(pid, SIGKILL);
  357. }
  358. return false;
  359. }
  360. pid_ = pid;
  361. return pid > 0;
  362. }
  363. void Server::Stop(bool graceful)
  364. {
  365. if (thread_.joinable()) {
  366. dns_server_stop();
  367. thread_.join();
  368. }
  369. if (pid_ > 0) {
  370. if (graceful) {
  371. kill(pid_, SIGTERM);
  372. } else {
  373. kill(pid_, SIGKILL);
  374. }
  375. }
  376. waitpid(pid_, nullptr, 0);
  377. pid_ = 0;
  378. }
  379. bool Server::IsRunning()
  380. {
  381. if (pid_ <= 0) {
  382. return false;
  383. }
  384. if (waitpid(pid_, nullptr, WNOHANG) == 0) {
  385. return true;
  386. }
  387. return kill(pid_, 0) == 0;
  388. }
  389. Server::~Server()
  390. {
  391. Stop(false);
  392. }
  393. } // namespace smartdns