server.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. #ifndef _SMARTDNS_SERVER_
  19. #define _SMARTDNS_SERVER_
  20. #include "dns.h"
  21. #include <functional>
  22. #include <string>
  23. #include <unistd.h>
  24. #include <sys/socket.h>
  25. #include <thread>
  26. namespace smartdns
  27. {
  28. class Server
  29. {
  30. public:
  31. enum CONF_TYPE {
  32. CONF_TYPE_STRING,
  33. CONF_TYPE_FILE,
  34. };
  35. Server();
  36. virtual ~Server();
  37. bool Start(const std::string &conf, enum CONF_TYPE type = CONF_TYPE_STRING);
  38. void Stop(bool graceful = true);
  39. bool IsRunning();
  40. private:
  41. pid_t pid_;
  42. int fd_;
  43. std::string conf_file_;
  44. bool clean_conf_file_{false};
  45. };
  46. struct ServerRequestContext {
  47. std::string domain;
  48. dns_type qtype;
  49. int qclass;
  50. struct sockaddr_storage *from;
  51. socklen_t fromlen;
  52. struct dns_packet *packet;
  53. uint8_t *request_data;
  54. int request_data_len;
  55. uint8_t *response_data;
  56. struct dns_packet *response_packet;
  57. int response_data_max_len;
  58. int response_data_len;
  59. };
  60. using ServerRequest = std::function<bool(struct ServerRequestContext *request)>;
  61. class MockServer
  62. {
  63. public:
  64. MockServer();
  65. virtual ~MockServer();
  66. bool Start(const std::string &url, ServerRequest callback);
  67. void Stop();
  68. bool IsRunning();
  69. private:
  70. void Run();
  71. bool GetAddr(const std::string &host, const std::string port, int type, int protocol, struct sockaddr_storage *addr,
  72. socklen_t *addrlen);
  73. int fd_;
  74. std::thread thread_;
  75. bool run_;
  76. ServerRequest callback_;
  77. };
  78. } // namespace smartdns
  79. #endif // _SMARTDNS_SERVER_