mdns_client_impl.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. // Copyright 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef NET_DNS_MDNS_CLIENT_IMPL_H_
  5. #define NET_DNS_MDNS_CLIENT_IMPL_H_
  6. #include <stdint.h>
  7. #include <map>
  8. #include <memory>
  9. #include <string>
  10. #include <utility>
  11. #include <vector>
  12. #include "base/cancelable_callback.h"
  13. #include "base/containers/queue.h"
  14. #include "base/gtest_prod_util.h"
  15. #include "base/memory/raw_ptr.h"
  16. #include "base/observer_list.h"
  17. #include "base/time/time.h"
  18. #include "net/base/io_buffer.h"
  19. #include "net/base/ip_endpoint.h"
  20. #include "net/base/net_export.h"
  21. #include "net/dns/mdns_cache.h"
  22. #include "net/dns/mdns_client.h"
  23. #include "net/socket/datagram_server_socket.h"
  24. #include "net/socket/udp_server_socket.h"
  25. #include "net/socket/udp_socket.h"
  26. namespace base {
  27. class Clock;
  28. class OneShotTimer;
  29. } // namespace base
  30. namespace net {
  31. class NetLog;
  32. class MDnsSocketFactoryImpl : public MDnsSocketFactory {
  33. public:
  34. MDnsSocketFactoryImpl() : net_log_(nullptr) {}
  35. explicit MDnsSocketFactoryImpl(NetLog* net_log) : net_log_(net_log) {}
  36. MDnsSocketFactoryImpl(const MDnsSocketFactoryImpl&) = delete;
  37. MDnsSocketFactoryImpl& operator=(const MDnsSocketFactoryImpl&) = delete;
  38. ~MDnsSocketFactoryImpl() override = default;
  39. void CreateSockets(
  40. std::vector<std::unique_ptr<DatagramServerSocket>>* sockets) override;
  41. private:
  42. const raw_ptr<NetLog> net_log_;
  43. };
  44. // A connection to the network for multicast DNS clients. It reads data into
  45. // DnsResponse objects and alerts the delegate that a packet has been received.
  46. class NET_EXPORT_PRIVATE MDnsConnection {
  47. public:
  48. class Delegate {
  49. public:
  50. // Handle an mDNS packet buffered in |response| with a size of |bytes_read|.
  51. virtual void HandlePacket(DnsResponse* response, int bytes_read) = 0;
  52. virtual void OnConnectionError(int error) = 0;
  53. virtual ~Delegate() = default;
  54. };
  55. explicit MDnsConnection(MDnsConnection::Delegate* delegate);
  56. MDnsConnection(const MDnsConnection&) = delete;
  57. MDnsConnection& operator=(const MDnsConnection&) = delete;
  58. virtual ~MDnsConnection();
  59. // Succeeds if at least one of the socket handlers succeeded.
  60. int Init(MDnsSocketFactory* socket_factory);
  61. void Send(const scoped_refptr<IOBuffer>& buffer, unsigned size);
  62. private:
  63. class SocketHandler {
  64. public:
  65. SocketHandler(std::unique_ptr<DatagramServerSocket> socket,
  66. MDnsConnection* connection);
  67. SocketHandler(const SocketHandler&) = delete;
  68. SocketHandler& operator=(const SocketHandler&) = delete;
  69. ~SocketHandler();
  70. int Start();
  71. void Send(const scoped_refptr<IOBuffer>& buffer, unsigned size);
  72. private:
  73. int DoLoop(int rv);
  74. void OnDatagramReceived(int rv);
  75. // Callback for when sending a query has finished.
  76. void SendDone(int rv);
  77. std::unique_ptr<DatagramServerSocket> socket_;
  78. raw_ptr<MDnsConnection> connection_;
  79. IPEndPoint recv_addr_;
  80. DnsResponse response_;
  81. IPEndPoint multicast_addr_;
  82. bool send_in_progress_ = false;
  83. base::queue<std::pair<scoped_refptr<IOBuffer>, unsigned>> send_queue_;
  84. };
  85. // Callback for handling a datagram being received on either ipv4 or ipv6.
  86. void OnDatagramReceived(DnsResponse* response,
  87. const IPEndPoint& recv_addr,
  88. int bytes_read);
  89. void PostOnError(SocketHandler* loop, int rv);
  90. void OnError(int rv);
  91. // Only socket handlers which successfully bound and started are kept.
  92. std::vector<std::unique_ptr<SocketHandler>> socket_handlers_;
  93. raw_ptr<Delegate> delegate_;
  94. base::WeakPtrFactory<MDnsConnection> weak_ptr_factory_{this};
  95. };
  96. class MDnsListenerImpl;
  97. class NET_EXPORT_PRIVATE MDnsClientImpl : public MDnsClient {
  98. public:
  99. // The core object exists while the MDnsClient is listening, and is deleted
  100. // whenever the number of listeners reaches zero. The deletion happens
  101. // asychronously, so destroying the last listener does not immediately
  102. // invalidate the core.
  103. class Core : public base::SupportsWeakPtr<Core>, MDnsConnection::Delegate {
  104. public:
  105. Core(base::Clock* clock, base::OneShotTimer* timer);
  106. Core(const Core&) = delete;
  107. Core& operator=(const Core&) = delete;
  108. ~Core() override;
  109. // Initialize the core.
  110. int Init(MDnsSocketFactory* socket_factory);
  111. // Send a query with a specific rrtype and name. Returns true on success.
  112. bool SendQuery(uint16_t rrtype, const std::string& name);
  113. // Add/remove a listener to the list of listeners.
  114. void AddListener(MDnsListenerImpl* listener);
  115. void RemoveListener(MDnsListenerImpl* listener);
  116. // Query the cache for records of a specific type and name.
  117. void QueryCache(uint16_t rrtype,
  118. const std::string& name,
  119. std::vector<const RecordParsed*>* records) const;
  120. // Parse the response and alert relevant listeners.
  121. void HandlePacket(DnsResponse* response, int bytes_read) override;
  122. void OnConnectionError(int error) override;
  123. MDnsCache* cache_for_testing() { return &cache_; }
  124. private:
  125. FRIEND_TEST_ALL_PREFIXES(MDnsTest, CacheCleanupWithShortTTL);
  126. class ListenerKey {
  127. public:
  128. ListenerKey(const std::string& name, uint16_t type);
  129. ListenerKey(const ListenerKey&) = default;
  130. ListenerKey(ListenerKey&&) = default;
  131. bool operator<(const ListenerKey& key) const;
  132. const std::string& name_lowercase() const { return name_lowercase_; }
  133. uint16_t type() const { return type_; }
  134. private:
  135. std::string name_lowercase_;
  136. uint16_t type_;
  137. };
  138. typedef base::ObserverList<MDnsListenerImpl>::Unchecked ObserverListType;
  139. typedef std::map<ListenerKey, std::unique_ptr<ObserverListType>>
  140. ListenerMap;
  141. // Alert listeners of an update to the cache.
  142. void AlertListeners(MDnsCache::UpdateType update_type,
  143. const ListenerKey& key, const RecordParsed* record);
  144. // Schedule a cache cleanup to a specific time, cancelling other cleanups.
  145. void ScheduleCleanup(base::Time cleanup);
  146. // Clean up the cache and schedule a new cleanup.
  147. void DoCleanup();
  148. // Callback for when a record is removed from the cache.
  149. void OnRecordRemoved(const RecordParsed* record);
  150. void NotifyNsecRecord(const RecordParsed* record);
  151. // Delete and erase the observer list for |key|. Only deletes the observer
  152. // list if is empty.
  153. void CleanupObserverList(const ListenerKey& key);
  154. ListenerMap listeners_;
  155. MDnsCache cache_;
  156. raw_ptr<base::Clock> clock_;
  157. raw_ptr<base::OneShotTimer> cleanup_timer_;
  158. base::Time scheduled_cleanup_;
  159. std::unique_ptr<MDnsConnection> connection_;
  160. };
  161. MDnsClientImpl();
  162. // Test constructor, takes a mock clock and mock timer.
  163. MDnsClientImpl(base::Clock* clock,
  164. std::unique_ptr<base::OneShotTimer> cleanup_timer);
  165. MDnsClientImpl(const MDnsClientImpl&) = delete;
  166. MDnsClientImpl& operator=(const MDnsClientImpl&) = delete;
  167. ~MDnsClientImpl() override;
  168. // MDnsClient implementation:
  169. std::unique_ptr<MDnsListener> CreateListener(
  170. uint16_t rrtype,
  171. const std::string& name,
  172. MDnsListener::Delegate* delegate) override;
  173. std::unique_ptr<MDnsTransaction> CreateTransaction(
  174. uint16_t rrtype,
  175. const std::string& name,
  176. int flags,
  177. const MDnsTransaction::ResultCallback& callback) override;
  178. int StartListening(MDnsSocketFactory* socket_factory) override;
  179. void StopListening() override;
  180. bool IsListening() const override;
  181. Core* core() { return core_.get(); }
  182. private:
  183. raw_ptr<base::Clock> clock_;
  184. std::unique_ptr<base::OneShotTimer> cleanup_timer_;
  185. std::unique_ptr<Core> core_;
  186. };
  187. class MDnsListenerImpl : public MDnsListener,
  188. public base::SupportsWeakPtr<MDnsListenerImpl> {
  189. public:
  190. MDnsListenerImpl(uint16_t rrtype,
  191. const std::string& name,
  192. base::Clock* clock,
  193. MDnsListener::Delegate* delegate,
  194. MDnsClientImpl* client);
  195. MDnsListenerImpl(const MDnsListenerImpl&) = delete;
  196. MDnsListenerImpl& operator=(const MDnsListenerImpl&) = delete;
  197. ~MDnsListenerImpl() override;
  198. // MDnsListener implementation:
  199. bool Start() override;
  200. // Actively refresh any received records.
  201. void SetActiveRefresh(bool active_refresh) override;
  202. const std::string& GetName() const override;
  203. uint16_t GetType() const override;
  204. MDnsListener::Delegate* delegate() { return delegate_; }
  205. // Alert the delegate of a record update.
  206. void HandleRecordUpdate(MDnsCache::UpdateType update_type,
  207. const RecordParsed* record_parsed);
  208. // Alert the delegate of the existence of an Nsec record.
  209. void AlertNsecRecord();
  210. private:
  211. void ScheduleNextRefresh();
  212. void DoRefresh();
  213. uint16_t rrtype_;
  214. std::string name_;
  215. raw_ptr<base::Clock> clock_;
  216. raw_ptr<MDnsClientImpl> client_;
  217. raw_ptr<MDnsListener::Delegate> delegate_;
  218. base::Time last_update_;
  219. uint32_t ttl_;
  220. bool started_ = false;
  221. bool active_refresh_ = false;
  222. base::CancelableRepeatingClosure next_refresh_;
  223. };
  224. class MDnsTransactionImpl : public base::SupportsWeakPtr<MDnsTransactionImpl>,
  225. public MDnsTransaction,
  226. public MDnsListener::Delegate {
  227. public:
  228. MDnsTransactionImpl(uint16_t rrtype,
  229. const std::string& name,
  230. int flags,
  231. const MDnsTransaction::ResultCallback& callback,
  232. MDnsClientImpl* client);
  233. MDnsTransactionImpl(const MDnsTransactionImpl&) = delete;
  234. MDnsTransactionImpl& operator=(const MDnsTransactionImpl&) = delete;
  235. ~MDnsTransactionImpl() override;
  236. // MDnsTransaction implementation:
  237. bool Start() override;
  238. const std::string& GetName() const override;
  239. uint16_t GetType() const override;
  240. // MDnsListener::Delegate implementation:
  241. void OnRecordUpdate(MDnsListener::UpdateType update,
  242. const RecordParsed* record) override;
  243. void OnNsecRecord(const std::string& name, unsigned type) override;
  244. void OnCachePurged() override;
  245. private:
  246. bool is_active() { return !callback_.is_null(); }
  247. void Reset();
  248. // Trigger the callback and reset all related variables.
  249. void TriggerCallback(MDnsTransaction::Result result,
  250. const RecordParsed* record);
  251. // Internal callback for when a cache record is found.
  252. void CacheRecordFound(const RecordParsed* record);
  253. // Signal the transactionis over and release all related resources.
  254. void SignalTransactionOver();
  255. // Reads records from the cache and calls the callback for every
  256. // record read.
  257. void ServeRecordsFromCache();
  258. // Send a query to the network and set up a timeout to time out the
  259. // transaction. Returns false if it fails to start listening on the network
  260. // or if it fails to send a query.
  261. bool QueryAndListen();
  262. uint16_t rrtype_;
  263. std::string name_;
  264. MDnsTransaction::ResultCallback callback_;
  265. std::unique_ptr<MDnsListener> listener_;
  266. base::CancelableOnceCallback<void()> timeout_;
  267. raw_ptr<MDnsClientImpl> client_;
  268. bool started_ = false;
  269. int flags_;
  270. };
  271. } // namespace net
  272. #endif // NET_DNS_MDNS_CLIENT_IMPL_H_