DNSClient.hpp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. /*
  2. Copyright (c) 2009-2010 Christopher A. Taylor. All rights reserved.
  3. Redistribution and use in source and binary forms, with or without
  4. modification, are permitted provided that the following conditions are met:
  5. * Redistributions of source code must retain the above copyright notice,
  6. this list of conditions and the following disclaimer.
  7. * Redistributions in binary form must reproduce the above copyright notice,
  8. this list of conditions and the following disclaimer in the documentation
  9. and/or other materials provided with the distribution.
  10. * Neither the name of LibCat nor the names of its contributors may be used
  11. to endorse or promote products derived from this software without
  12. specific prior written permission.
  13. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  14. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  16. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  17. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  18. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  19. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  20. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  21. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  22. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  23. POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. // TODO: React to timeouts from DNS server by switching to a backup
  26. // TODO: Use TTL from DNS record instead of fixed constant
  27. // TODO: If the DNS resolution load is high, it would make sense to put
  28. // multiple requests in the same DNS packet
  29. // TODO: Retransmissions could also be grouped into the same DNS packets
  30. // TODO: The locks held in DNSClient are fairly coarse and could be broken up
  31. #ifndef CAT_DNS_CLIENT_HPP
  32. #define CAT_DNS_CLIENT_HPP
  33. #include <cat/net/ThreadPoolSockets.hpp>
  34. #include <cat/threads/Thread.hpp>
  35. #include <cat/threads/WaitableFlag.hpp>
  36. #include <cat/crypt/rand/Fortuna.hpp>
  37. #include <cat/port/FastDelegate.h>
  38. namespace cat {
  39. static const int HOSTNAME_MAXLEN = 63; // Max characters in a hostname request
  40. static const int DNSREQ_TIMEOUT = 3000; // DNS request timeout interval
  41. static const int DNSREQ_REPOST_TIME = 300; // Number of milliseconds between retries
  42. static const int DNSREQ_MAX_SIMUL = 2048; // Maximum number of simultaneous DNS requests
  43. static const int DNSCACHE_MAX_REQS = 8; // Maximum number of requests to cache
  44. static const int DNSCACHE_MAX_RESP = 8; // Maximum number of responses to cache
  45. static const int DNSCACHE_TIMEOUT = 60000; // Time until a cached response is dropped
  46. // Prototype: bool MyResultCallback(const char *, const NetAddr*, int);
  47. typedef fastdelegate::FastDelegate3<const char *, const NetAddr*, int, bool> DNSResultCallback;
  48. //// DNSRequest
  49. struct DNSCallback
  50. {
  51. DNSCallback *next;
  52. DNSResultCallback cb;
  53. ThreadRefObject *ref;
  54. };
  55. struct DNSRequest
  56. {
  57. DNSRequest *last, *next;
  58. u32 first_post_time; // Timestamp for first post, for timeout
  59. u32 last_post_time; // Timestamp for last post, for retries and cache
  60. // Our copy of the hostname string
  61. char hostname[HOSTNAME_MAXLEN+1];
  62. u16 id; // Random request ID
  63. DNSCallback callback_head;
  64. // For caching purposes
  65. NetAddr responses[DNSCACHE_MAX_RESP];
  66. int num_responses;
  67. };
  68. //// DNSClient
  69. class DNSClient : Thread, public UDPEndpoint, public Singleton<DNSClient>
  70. {
  71. static const int TICK_RATE = 200; // milliseconds
  72. static const int DNS_THREAD_KILL_TIMEOUT = 10000; // 10 seconds
  73. CAT_SINGLETON(DNSClient)
  74. : UDPEndpoint(REFOBJ_PRIO_0+5)
  75. {
  76. _server_addr.Invalidate();
  77. _dns_unavailable = true;
  78. _cache_head = _cache_tail = 0;
  79. _cache_size = 0;
  80. _request_head = _request_tail = 0;
  81. _request_queue_size = 0;
  82. }
  83. public:
  84. virtual ~DNSClient();
  85. /*
  86. In your startup code, call Initialize() and check the return value.
  87. In your shutdown code, call Shutdown(). This will delete the DNSClient object.
  88. */
  89. bool Initialize();
  90. void Shutdown();
  91. /*
  92. If hostname is numeric or in the cache, the callback function will be invoked
  93. immediately from the requesting thread, rather than from another thread.
  94. First attempts numerical resolve of hostname, then queries the DNS server.
  95. Hostname string length limited to HOSTNAME_MAXLEN characters.
  96. Caches the most recent DNSCACHE_MAX_REQS requests.
  97. Returns up to DNSCACHE_MAX_RESP addresses per resolve request.
  98. Performs DNS lookup on a cached request after DNSCACHE_TIMEOUT.
  99. Gives up on DNS lookup after DNSREQ_TIMEOUT.
  100. If holdRef is valid, the reference will be held until the callback completes.
  101. If no results were found, array_length == 0.
  102. If the callback returns false, the result will not be entered into the cache.
  103. The resolved addresses may need to be promoted to IPv6.
  104. If Resolve() returns false, no callback will be generated.
  105. */
  106. bool Resolve(const char *hostname, DNSResultCallback, ThreadRefObject *holdRef = 0);
  107. private:
  108. NetAddr _server_addr;
  109. volatile bool _dns_unavailable;
  110. FortunaOutput *_csprng;
  111. private:
  112. Mutex _request_lock;
  113. DNSRequest *_request_head;
  114. DNSRequest *_request_tail;
  115. int _request_queue_size;
  116. bool GetUnusedID(u16 &id); // not thread-safe, caller must lock
  117. bool IsValidHostname(const char *hostname);
  118. DNSRequest *PullRequest(u16 id); // not thread-safe, caller must lock
  119. private:
  120. Mutex _cache_lock;
  121. DNSRequest *_cache_head;
  122. DNSRequest *_cache_tail;
  123. int _cache_size;
  124. // These functions do not lock, caller must lock:
  125. void CacheAdd(DNSRequest *req); // Assumes not already in cache
  126. DNSRequest *CacheGet(const char *hostname); // Case-insensitive
  127. void CacheKill(DNSRequest *req); // Assumes already in cache
  128. private:
  129. bool GetServerAddr();
  130. bool BindToRandomPort(bool ignoreUnreachable);
  131. bool PostDNSPacket(DNSRequest *req, u32 now);
  132. bool PerformLookup(DNSRequest *req); // not thread-safe, caller must lock
  133. protected:
  134. virtual void OnRead(ThreadPoolLocalStorage *tls, const NetAddr &src, u8 *data, u32 bytes);
  135. virtual void OnClose();
  136. virtual void OnUnreachable(const NetAddr &src);
  137. protected:
  138. void ProcessDNSResponse(DNSRequest *req, int qdcount, int ancount, u8 *data, u32 bytes);
  139. void NotifyRequesters(DNSRequest *req);
  140. private:
  141. WaitableFlag _kill_flag;
  142. bool ThreadFunction(void *param);
  143. };
  144. } // namespace cat
  145. #endif // CAT_DNS_CLIENT_HPP
粤ICP备19079148号